From d37639ef711e8d1cad1e6fc1a84f8aa7f7275e6b Mon Sep 17 00:00:00 2001 From: baKon Date: Sun, 18 Oct 2026 22:53:56 -0500 Subject: [PATCH 001/152] prefix cache: a reserved snapshot is a save target until its commit (#129) A checkpoint reservation (Scheduler::reserve_ckpt, at planning) is written only after the step (Engine::checkpoint_save), and nothing between the two checked that the slot was still the reservation's. A later reservation in the same step that found the store full ran retention over every session, and the policy, placing its ladder from each session's tip, could release the very slot just handed out: a second request's reservation lands on a snapshot a first session already holds (the same prefix, so the same key) below that session's tip, or a lookup's take_over indexes a fresh reservation under a session whose ladder does not keep it. The save then faulted in checkpoint_copy ("the store does not hold that slot ... given back after its id was handed out"), the step loop read the negative as a device fault, and the engine exited with every in-flight request (#129: every 25-50 min under multi-session agentic load, the store not full at the fault, 12-15 of 16 in use -- the eviction itself had freed the rest). A reservation now keeps its slot the way a handed-out snapshot does: retention, the LRU eviction and expiry skip it from reserve_checkpoint until commit_checkpoint, or until the next step begins when the save was skipped (its request gone), so a skipped save cannot hold a slot for good. The engine issues every save before it plans the next step, so the window covers the copy. A reservation that finds every slot handed out or awaiting a save is refused as before (ckpt_refused) and the chunk goes without a snapshot. mem_test: the two cases, the shared-prefix one at the position geometric backoff releases, and a step boundary (begin_step) in the three cases that reserve several snapshots in a row without committing, as the engine does one per step. --- core/mem/prefix.cpp | 31 ++++++++++----- core/mem/prefix.h | 21 +++++++--- tests/mem_test.cpp | 95 +++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 129 insertions(+), 18 deletions(-) diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index 574889e4..179e9e86 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -711,9 +711,9 @@ int64_t PrefixCache::retain(uint64_t session) { int64_t freed = 0; for (const auto& a : all) { if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; } - /* Keep one handed out this step regardless of policy: its admission restores from the - * slot ahead of the step. */ - if (handed(a.second)) { kept.push_back(a.second); continue; } + /* Keep one handed out this step or reserved and not yet committed regardless of policy: + * its admission restores from the slot ahead of the step, or the step's save lands in it. */ + if (handed(a.second) || reserved(a.second)) { kept.push_back(a.second); continue; } auto e = ck_by_prefix_.find(a.second); if (e == ck_by_prefix_.end()) continue; /* And one a lookup resumed from since the session's tip was written. The policy places @@ -754,6 +754,10 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa if (existing != ck_by_prefix_.end()) { existing->second.used = ++clock_; existing->second.used_ns = rad_mono_ns(); + /* Another session's snapshot, this step's save target: retention run by a later + * reservation in this step places its ladder from THAT session's tip and may not keep + * this position. Held until the save is committed. */ + if (!reserved(prefix)) reserved_.push_back(prefix); *slot_out = existing->second.slot; return RAD_OK; } @@ -768,20 +772,21 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa for (uint64_t s : sessions) retain(s); if (kv_->alloc_checkpoint(&slot) < 0) { /* Evict the least recently used snapshot, where a use is its reservation or a lookup - * resuming from it, and never one handed out this step (its admission restores from - * the slot ahead of the step). A tip gets no protection beyond its recency: sessions + * resuming from it, and never one handed out or reserved this step (its admission + * restores from the slot ahead of the step; the save lands in it after). A tip gets + * no protection beyond its recency: sessions * are request ids, and a client that rewrites its last message leaves one tip per * turn that no later turn reaches, while the anchor every turn resumes from is used * each turn. */ const Ckpt* victim = nullptr; for (const auto& kvp : ck_by_prefix_) { - if (handed(kvp.first)) continue; + if (handed(kvp.first) || reserved(kvp.first)) continue; if (!victim || kvp.second.used < victim->used) victim = &kvp.second; } if (!victim) { ++stats_.ckpt_refused; RAD_DEBUG("prefix cache: no snapshot at %lld for session %llu: every one of the " - "%lld slots was handed out this step", (long long)pos, + "%lld slots was handed out this step or awaits its save", (long long)pos, (unsigned long long)session, (long long)ck_by_prefix_.size()); return RAD_E_FULL; } @@ -805,11 +810,17 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa c.used_ns = rad_mono_ns(); ck_by_prefix_.emplace(prefix, c); ck_by_session_[session].push_back(prefix); + /* A save target until committed: a lookup's take_over may index it under another session + * before the save, where retention run by a later reservation in this step would weigh it by + * that session's ladder. */ + reserved_.push_back(prefix); *slot_out = slot; return RAD_OK; } void PrefixCache::commit_checkpoint(const BlockHash& prefix) { + /* The save has landed: the slot is a snapshot like any other from here. */ + reserved_.erase(std::remove(reserved_.begin(), reserved_.end(), prefix), reserved_.end()); auto it = ck_by_prefix_.find(prefix); if (it == ck_by_prefix_.end()) return; /* One that lost its slot since the reservation holds nothing to serve. */ @@ -915,12 +926,12 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) { } } - /* ---- snapshots: skip uncommitted reservations and ones handed out this step. At most - * --checkpoint-slots of them, so walk the whole index. */ + /* ---- snapshots: skip uncommitted reservations, ones handed out this step and ones a save + * is pending on. At most --checkpoint-slots of them, so walk the whole index. */ std::vector gone; for (const auto& kvp : ck_by_prefix_) { const Ckpt& c = kvp.second; - if (!c.valid || handed(kvp.first)) continue; + if (!c.valid || handed(kvp.first) || reserved(kvp.first)) continue; auto e = map_.find(kvp.first); const uint64_t used = std::max(c.used_ns, e == map_.end() ? 0 : e->second.used_ns); if (used < cutoff) gone.push_back(kvp.first); diff --git a/core/mem/prefix.h b/core/mem/prefix.h index 934d8350..2f171fb1 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -284,9 +284,10 @@ public: void hold(uint64_t req, const std::vector& tokens, const std::vector& mm); void release(uint64_t req); /* Start of a step's admissions. Snapshots the previous step's lookups handed out have been - * read by its forward by now; until this call they keep their slots against retention, - * reserve_checkpoint's eviction and expiry. */ - void begin_step() { handed_.clear(); } + * read by its forward by now, and the ones it reserved have been saved into (the engine + * issues the save before the next step is planned); until this call they keep their slots + * against retention, reserve_checkpoint's eviction and expiry. */ + void begin_step() { handed_.clear(); reserved_.clear(); } /* ---------------- expiry ---------------- * @@ -307,8 +308,11 @@ public: /* Reserve a snapshot slot for `session` at `pos`. When the store is full, applies the * retention policy, then evicts the least recently used snapshot (a use is its reservation or * a lookup resuming from it), a tip like any other. A snapshot handed out this step is never - * evicted: its admission restores from the slot ahead of the step. RAD_E_FULL when nothing - * can be given up. */ + * released, by retention or eviction: its admission restores from the slot ahead of the step. + * Nor is one this call reserved and commit_checkpoint has not yet committed: the engine saves + * into the slot after the step, and a later reservation in the same step must not run + * retention over a save target (a second request reserving a snapshot a first session holds + * below its tip). RAD_E_FULL when nothing can be given up. */ int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix, int32_t* slot_out); /* The state for `prefix` is now in its slot; lookup() offers it only after this (Ckpt::valid). */ @@ -421,6 +425,13 @@ private: bool handed(const BlockHash& h) const { return std::find(handed_.begin(), handed_.end(), h) != handed_.end(); } + /* Snapshots reserve_checkpoint reserved and commit_checkpoint has not committed: the step's + * save targets, kept in their slots until the commit, or until the next step begins when the + * save was skipped (its request gone). */ + mutable std::vector reserved_; + bool reserved(const BlockHash& h) const { + return std::find(reserved_.begin(), reserved_.end(), h) != reserved_.end(); + } mutable uint64_t clock_ = 0; std::unique_ptr policy_; mutable Stats stats_; diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 8b46aa55..e2eeb1bf 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -1611,8 +1611,9 @@ TEST(checkpoint_retention_is_budgeted_and_keeps_the_tip) { auto prompt = tok_run(4242, 16 * 64); const std::vector hs = chain_of(prompt); - /* Eight checkpoints at 64, 128, ... 512 fill the pool exactly. */ + /* Eight checkpoints at 64, 128, ... 512 fill the pool exactly, one step each. */ for (int i = 1; i <= 8; ++i) { + f.pc.begin_step(); int32_t s = -1; CHECK_OK(f.pc.reserve_checkpoint(1, i * 64, hs[i * 4 - 1], &s)); } @@ -1621,6 +1622,7 @@ TEST(checkpoint_retention_is_budgeted_and_keeps_the_tip) { /* The ninth forces retention. Geometric backoff over {64..512} keeps 512, 448, 384, 256 and * 64 and releases the rest; the tip survives, as an appending agent transcript needs. */ + f.pc.begin_step(); int32_t s9 = -1; CHECK_OK(f.pc.reserve_checkpoint(1, 9 * 64, hs[9 * 4 - 1], &s9)); auto held = f.pc.checkpoints(1); @@ -1768,6 +1770,89 @@ TEST(a_snapshot_handed_out_this_step_is_not_evicted) { CHECK_OK(f.pc.reserve_checkpoint(1, 128, hs[7], &s2)); } +/* A reservation made this step is a save target: the engine copies the state into its slot + * after the step, and nothing checks the slot again before that copy. A later reservation in the + * same step that finds the store full runs retention over every session, and the policy, placing + * its ladder from each session's tip, may release the very slot just handed out -- a second + * request's reservation lands on a snapshot a first session already holds (the same prefix, so + * the same key), and that snapshot is below the first session's tip. Geometric backoff over + * {64..512} releases 192, so the shared reservation is made to land there. The save then faults + * ("the store does not hold that slot") and the step loop stops the engine. A reservation keeps + * its slot until its commit, or until the next step begins, as a handed-out snapshot does. */ +TEST(a_reservation_this_step_survives_retention) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/8)); + + const auto a = tok_run(4242, 16 * 33); + publish(f, 1, a, 16 * 32); + const std::vector hs = chain_of(a); + std::vector slot_at(9, -1); + for (int i = 1; i <= 8; ++i) slot_at[(size_t)i] = ckpt_at(f, 1, hs, i * 64); + CHECK_EQ(f.kv.free_checkpoint_slots(), 0ll); + + /* Session 2 prefilling the same prompt reserves at 192: the same key, so session 1's slot. */ + f.pc.begin_step(); + int32_t s2 = -1; + CHECK_OK(f.pc.reserve_checkpoint(2, 192, hs[11], &s2)); + CHECK_EQ(s2, slot_at[3]); + + /* The same step's next reservation finds the store full: retention runs over session 1, + * whose ladder does not keep 192. */ + BlockHash other = hs[3]; + other.lo ^= 0x5eedull; + int32_t s3 = -1; + CHECK_OK(f.pc.reserve_checkpoint(3, 64, other, &s3)); + CHECK(s3 >= 0); + CHECK(s3 != s2); + CHECK(f.kv.checkpoint_held(s2)); + bool kept_192 = false; + for (int64_t p : f.pc.checkpoints(1)) if (p == 192) kept_192 = true; + CHECK(kept_192); + CHECK(f.pc.stats().ckpt_retired >= 1ll); + + /* The next step may release it again: an uncommitted reservation whose save was skipped (its + * request gone) must not hold a slot for good. (A committed one is a snapshot like any other + * from the commit on, tested below.) */ + f.pc.begin_step(); + for (int i = 0; i < 3; ++i) { + BlockHash fresh = hs[3]; + fresh.lo ^= 0x1000ull + (uint64_t)i; + int32_t s = -1; + CHECK_OK(f.pc.reserve_checkpoint(10 + (uint64_t)i, 64, fresh, &s)); + } + bool still_192 = false; + for (int64_t p : f.pc.checkpoints(1)) if (p == 192) still_192 = true; + CHECK(!still_192); +} + +/* Eviction after retention skips it too. With one slot, the reservation is the only candidate, + * so a second reservation in the same step is refused instead of taking it; once committed, it + * is a snapshot like any other and the next step's reservation may take the slot. */ +TEST(a_reservation_this_step_is_not_evicted) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/1)); + const auto a = tok_run(5151, 16 * 9); + const std::vector hs = chain_of(a); + + f.pc.begin_step(); + int32_t s1 = -1; + CHECK_OK(f.pc.reserve_checkpoint(1, 64, hs[3], &s1)); + CHECK(s1 >= 0); + + BlockHash other = hs[3]; + other.lo ^= 0x5eedull; + int32_t s2 = -1; + CHECK_EQ(f.pc.reserve_checkpoint(2, 64, other, &s2), RAD_E_FULL); + CHECK(f.kv.checkpoint_held(s1)); + CHECK_EQ(f.pc.stats().ckpt_evictions, 0ll); + CHECK_EQ(f.pc.stats().ckpt_refused, 1ll); + + f.pc.commit_checkpoint(hs[3]); + f.pc.begin_step(); + CHECK_OK(f.pc.reserve_checkpoint(2, 64, other, &s2)); + CHECK_EQ(s2, s1); +} + TEST(a_dead_sessions_tip_is_evictable_so_the_slot_pool_cannot_wedge) { /* One checkpoint each from more distinct sessions than slots, each its session's tip. If tips * were unevictable the pool would wedge and every later request get RAD_E_FULL. A session is a @@ -1790,7 +1875,8 @@ TEST(a_dead_sessions_tip_is_evictable_so_the_slot_pool_cannot_wedge) { } CHECK_EQ(f.kv.free_checkpoint_slots(), 0ll); - /* The ninth session is served by retiring the least recently used tip. */ + /* The ninth session, a step later, is served by retiring the least recently used tip. */ + f.pc.begin_step(); BlockHash fresh = hs[3]; fresh.lo ^= 0x5eedull; int32_t s9 = -1; @@ -1813,6 +1899,7 @@ TEST(a_sessions_index_entry_does_not_outlive_its_last_snapshot) { auto prompt = tok_run(313, 16 * 32); const std::vector hs = chain_of(prompt); for (int i = 1; i <= 5; ++i) { + f.pc.begin_step(); int32_t s = -1; CHECK_OK(f.pc.reserve_checkpoint(7, i * 64, hs[i * 4 - 1], &s)); } @@ -1821,8 +1908,10 @@ TEST(a_sessions_index_entry_does_not_outlive_its_last_snapshot) { CHECK_EQ((long long)f.pc.checkpoints(7).size(), 2ll); CHECK_EQ(f.pc.sessions_tracked(), 1ll); - /* Four more sessions, one snapshot each: session 7's tip is the LRU and is evicted. */ + /* Four more sessions, one snapshot each, a step apart: session 7's tip is the LRU and is + * evicted. */ for (uint64_t sess = 20; sess < 24; ++sess) { + f.pc.begin_step(); BlockHash h = hs[9]; h.lo ^= sess; int32_t s = -1; From f10c8521cd69fe21f77ea614848718cb5f87e15d Mon Sep 17 00:00:00 2001 From: sfjes Date: Sun, 18 Oct 2026 16:38:37 -0700 Subject: [PATCH 002/152] --host-headroom-mib N: the RAM radiance leaves free for the system at startup becomes a flag -- kLockMargin's fixed 4 GiB suited a busy server, and a 30 GiB host paid it in dead RAM to no purpose: startup refuses a host pin unless available memory covers it with that much still free, and --checkpoint-slots auto's bound is priced with it; so when 1.7.0 began counting the checkpoint store against this check, configs that 1.6.0 ran refused to start and the fix cost a quarter of the prefix cache. --- core/config.cpp | 4 +++ core/engine.h | 4 +++ core/engine_bringup.cpp | 65 +++++++++++++++++++++++------------------ core/rad_core.h | 1 + docs/GUIDE.md | 15 ++++++---- spec.md | 1 + tests/config_test.cpp | 3 +- 7 files changed, 57 insertions(+), 36 deletions(-) diff --git a/core/config.cpp b/core/config.cpp index f9fd92cf..871f9820 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -73,6 +73,8 @@ static const Flag g_flags[] = { { "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" }, { "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" }, { "--host-pool-mib", "N", "pinned host tier" }, + { "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n" + " pins its host memory at startup (default 4096)" }, { "--embedding-placement", "WHERE", "ram (default) | vram: where the token embedding lives. ram\n" " pins it in host memory beside --host-pool-mib, read over the\n" " link in place; by default a model whose output head reads the\n" @@ -461,6 +463,7 @@ int config_parse(int argc, char** argv, Config* c) { /* --gpu-headroom is accepted as an alias of --gpu-headroom-mib. */ else if (S("--gpu-headroom-mib") || S("--gpu-headroom")) { if (!num(0, INT64_MAX, &c->gpu_headroom_mib)) return RAD_E_INVAL; } + else if (S("--host-headroom-mib")) { if (!num(0, INT64_MAX, &c->host_headroom_mib)) return RAD_E_INVAL; } else if (S("--kv-cache-dtype")) { if (!(v = need(i))) return RAD_E_INVAL; if (std::strcmp(v, "bf16") && std::strcmp(v, "fp8")) { @@ -1000,6 +1003,7 @@ const ShowRow kShow[] = { { "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } }, { "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } }, { "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } }, + { "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } }, { "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } }, { "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } }, { "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } }, diff --git a/core/engine.h b/core/engine.h index 19c468a5..47de51c3 100644 --- a/core/engine.h +++ b/core/engine.h @@ -159,6 +159,10 @@ private: * time. Requests and unloads go to the table alone and never wait for a load's copy. */ std::mutex lora_mu_; std::set lora_targets_; + /* --host-headroom-mib in bytes: the host RAM startup leaves free for the system when it + * pins host memory (engine_bringup.cpp). 4 GiB suits a busy server; a small host wants to + * leave less to make room for its tiers, which is why it is a flag and not a constant. */ + int64_t host_headroom_bytes() const { return cfg_.host_headroom_mib * ((int64_t)1 << 20); } /* Resolves --embedding-placement, --vision-tower-placement and --ngram-placement into Config * before the card is split (engine_bringup.cpp describes how auto chooses). `wfs` is every * rank's footprint, read for its towers. `host_late` is the pinned host memory startup diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 705ffaf3..934dca63 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -275,10 +275,11 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const } /* ------------------------------------------------------------------ locked host memory */ -/* Host memory left free beside a table locked whole: the process's unpooled allocations, the - * load's staging windows, and the page cache holding the container's hot pages. Without it the - * kernel reclaims the files the engine reads, then the OOM killer runs. */ -static const int64_t kLockMargin = (int64_t)4 << 30; +/* The margin (--host-headroom-mib, Engine::host_headroom_bytes): host memory left free beside a + * table locked whole -- the process's unpooled allocations, the load's staging windows, and the + * page cache holding the container's hot pages. Without it the kernel reclaims the files the + * engine reads, then the OOM killer runs. It is dead RAM by design; a host that can reclaim + * cheaply trades it for pool, cache or slots. */ /* Every level of every memory cgroup the process is in, leaf first: `visit(dir, room)` until it * returns false (cgroup_levels). /proc/self/cgroup reads "0::/path" on v2 and "N:memory:/path" @@ -309,12 +310,13 @@ static void memory_cgroups(const std::function= 0 && avail - still - kLockMargin < need) { + avail >= 0 && avail - still - margin < need) { *why = fmt("%s of memory is available, %s more is still to be allocated (the pinned host " "pools, the prefix cache's host tier, the checkpoint slots and the host " - "activation arenas), and this wants %s with %s to spare", + "activation arenas), and this wants %s with %s to spare " + "(--host-headroom-mib)", humanb(avail).c_str(), humanb(still).c_str(), humanb(need).c_str(), - humanb(kLockMargin).c_str()); + humanb(margin).c_str()); return false; } bool fits = true; memory_cgroups([&](const std::string& dir, int64_t room) { - if (room - still - kLockMargin >= need) return true; + if (room - still - margin >= need) return true; *why = fmt("the memory cgroup at %s leaves %s, %s more is still to be allocated, " - "and this wants %s with %s to spare", dir.c_str(), + "and this wants %s with %s to spare (--host-headroom-mib)", dir.c_str(), humanb(room).c_str(), humanb(still).c_str(), humanb(need).c_str(), - humanb(kLockMargin).c_str()); + humanb(margin).c_str()); fits = false; return false; }); return fits; } -/* The most lockable_room(need, still, false) admits, and in `limit` the bound that decides it. - * INT64_MAX when no limit can be read. */ -static int64_t lockable_bytes(int64_t still, std::string* limit) { +/* The most lockable_room(need, still, margin, false) admits, and in `limit` the bound that + * decides it. INT64_MAX when no limit can be read. */ +static int64_t lockable_bytes(int64_t still, int64_t margin, std::string* limit) { int64_t most = INT64_MAX; *limit = "no readable memory limit"; if (const int64_t avail = meminfo_bytes("MemAvailable"); avail >= 0) { - most = avail - still - kLockMargin; + most = avail - still - margin; *limit = fmt("%s of memory available, less %s still to be allocated and %s to spare", - humanb(avail).c_str(), humanb(still).c_str(), humanb(kLockMargin).c_str()); + humanb(avail).c_str(), humanb(still).c_str(), humanb(margin).c_str()); } memory_cgroups([&](const std::string& dir, int64_t room) { - if (room - still - kLockMargin < most) { - most = room - still - kLockMargin; + if (room - still - margin < most) { + most = room - still - margin; *limit = fmt("the memory cgroup at %s, which leaves %s, less %s still to be allocated " "and %s to spare", dir.c_str(), humanb(room).c_str(), - humanb(still).c_str(), humanb(kLockMargin).c_str()); + humanb(still).c_str(), humanb(margin).c_str()); } return true; }); @@ -470,7 +473,9 @@ int Engine::resolve_table_placement(const std::vector& facts, const int64_t pools_still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB + cfg_.prefix_cache_mib * MiB + host_late; std::string emb_room_why; - auto emb_room = [&]() { return lockable_room(emb_pin, pools_still, false, &emb_room_why); }; + auto emb_room = [&]() { + return lockable_room(emb_pin, pools_still, host_headroom_bytes(), false, &emb_room_why); + }; if (emb_max == 0) { if (emb == TablePlacement::Ram && emb_asked) { RAD_ERR("--embedding-placement ram: this model has no token embedding table that only " @@ -525,7 +530,7 @@ int Engine::resolve_table_placement(const std::vector& facts, std::string why; const int64_t pin = (int64_t)cfg_.tp * align_up(tower_max, (int64_t)MiB); if (!lockable_room(pin, pools_still + (int64_t)cfg_.tp * cfg_.embedding_host_mib * MiB, - false, &why)) { + host_headroom_bytes(), false, &why)) { RAD_ERR("--vision-tower-placement ram: the encoder towers (%s a rank, pinned on every " "rank) cannot be held in host memory: %s. Use vram.", humanb(tower_max).c_str(), why.c_str()); @@ -609,7 +614,8 @@ int Engine::resolve_table_placement(const std::vector& facts, } else { std::string card_why, ram_why; const bool card = ng == TablePlacement::Auto && ngram_device && card_holds(&card_why); - const bool room = !card && lockable_room(need, still, !ngram_device, &ram_why); + const bool room = + !card && lockable_room(need, still, host_headroom_bytes(), !ngram_device, &ram_why); if (ng == TablePlacement::Ram) { if (!room) { RAD_ERR("--ngram-placement ram: the n-gram table (%s) cannot be held in memory as " @@ -2763,7 +2769,7 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) { int64_t still = cfg_.prefix_cache_mib * ((int64_t)1 << 20); for (const auto& r : ranks_) still += arena_host_bytes(r->program); std::string limit; - int64_t room = lockable_bytes(still, &limit); + int64_t room = lockable_bytes(still, host_headroom_bytes(), &limit); if (!device_is_host()) { bool lifted = false; if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) { @@ -2906,7 +2912,8 @@ int Engine::configure_kv() { }; if (!sized) return refuse("no host has"); std::string why; - if (!lockable_room(slot * n, 0, false, &why)) return refuse("does not fit: " + why); + if (!lockable_room(slot * n, 0, host_headroom_bytes(), false, &why)) + return refuse("does not fit: " + why); if (ck_store_.open(slot, slot * n) != RAD_OK) return refuse(std::string("the host did not pin: ") + rad_dev_last_error()); if (!sized_auto) diff --git a/core/rad_core.h b/core/rad_core.h index 845b3537..3e625702 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -743,6 +743,7 @@ struct Config { * always resolve to bf16 and only add a third name. */ std::string kv_cache_dtype = "bf16"; int64_t host_pool_mib = 0; + int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */ /* File tier for weights: what fits in neither the VRAM slab nor the pinned host pool is read * from the container with O_DIRECT ahead of the ops that read it (a scheduled unit by the * exact prefetch, a routed expert a routed layer at a time). Off by default because disk diff --git a/docs/GUIDE.md b/docs/GUIDE.md index c6fffd4a..451ef4a9 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -685,7 +685,8 @@ GiB a card at `--tp 2`. Under `ram` each rank pins its own shard in host memory `--host-pool-mib`, and the lookup reads a step's rows over the link, so the table costs no VRAM. The table is the model-level weight only `embed_lookup` reads. A model whose head is tied to it keeps it on the card (the head's GEMM would stream it whole every step), and so does a host that cannot pin -it (available memory and memory cgroups, after the pools, with 4 GiB to spare); startup says which. +it (available memory and memory cgroups, after the pools, with `--host-headroom-mib` to spare, +default 4 GiB); startup says which. An explicit `ram` turns either case into a refusal. `disk` is refused: the lookup writes activations the card reads, which a host kernel reading the container cannot do. @@ -711,9 +712,9 @@ from the container through a row cache with direct reads on the host; about half are first-seen, so steps wait on the drive. `ram` copies the table into host memory at load (12 to 40 s more startup, depending on the page cache) and the card's gather kernel reads the pinned copy, so a step has no host work. `vram` puts all of it on every card. `ram` needs the table's size free -after the pinned host pools and the prefix cache's host tier, with 4 GiB to spare, under every -memory cgroup the process sits in, and refuses the start otherwise. `auto` takes the first of `vram`, -`ram` and `disk` that holds the table. Without a device kernel for the gather (no libr4d) the table is +after the pinned host pools and the prefix cache's host tier, with `--host-headroom-mib` to spare +(default 4 GiB), under every memory cgroup the process sits in, and refuses the start otherwise. +`auto` takes the first of `vram`, `ram` and `disk` that holds the table. Without a device kernel for the gather (no libr4d) the table is read on the host: `vram` is refused, and `ram` is a copy in locked huge pages, which also needs a memlock limit that large (`--ulimit memlock=-1` in Docker, `LimitMEMLOCK=infinity` under systemd). @@ -1072,8 +1073,9 @@ running or not, and a conversation without a snapshot under its next prompt reus backoff keeps 9 for a 200K-token conversation at the default 2048-token interval, so 10 a sequence, 80 at `--max-num-seqs 8`. The store is pinned for the life of the server, so `auto` takes at most an eighth of host memory (and never less than 8 slots where the host can pin them), and never more than -the host can pin after the host pools, the host tier and the activation arenas. The startup log says -what it chose; Flash-Next at `--tp 2 --max-num-seqs 8` on a host with 128 GB of RAM: +the host can pin after the host pools, the host tier, the activation arenas and +`--host-headroom-mib`. The startup log says what it chose; Flash-Next at `--tp 2 +--max-num-seqs 8` on a host with 128 GB of RAM: ``` checkpoint slots: auto: 80 linear-state snapshot(s) of 113.50 MiB in pinned host memory (8.87 GiB), @@ -1267,6 +1269,7 @@ still verified by the adapter, so output is exact and only the acceptance rate c | `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card | | `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` | | `--host-pool-mib N` | 0 | pinned host tier (weights) | +| `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3) | | `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card (§4.3) | | `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container (§4.3) | | `--vision-tower-placement WHERE` | vram | `vram` or `ram`: the encoder towers (vision, and audio where a model has one) on the card, or pinned in host memory beside `--host-pool-mib` and read in place once an image (§4.3) | diff --git a/spec.md b/spec.md index 1157a62b..1ace7bff 100644 --- a/spec.md +++ b/spec.md @@ -894,6 +894,7 @@ utilisation fraction: |---|---| | `--gpu-headroom-mib` | VRAM left unclaimed on every card (default 96) | | `--host-pool-mib` | the pinned host tier | +| `--host-headroom-mib` | host RAM left free for the system at startup (default 4096) | | `--weights-disk-tier` | the file tier for weights, read from the container; needs `O_DIRECT` | | `--max-model-len`, `--max-num-seqs` | the KV cache's bound | diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 6e856f0d..3f43b87d 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -417,7 +417,8 @@ const std::map>& legal_values() { { "--max-num-seqs", { "4" } }, { "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } }, { "--gpu-headroom-mib", { "128" } }, { "--kv-cache-dtype", { "fp8" } }, - { "--host-pool-mib", { "1024" } }, { "--embedding-placement", { "vram" } }, + { "--host-pool-mib", { "1024" } }, { "--host-headroom-mib", { "2048" } }, + { "--embedding-placement", { "vram" } }, { "--vision-tower-placement", { "ram" } }, { "--ngram-placement", { "disk" } }, { "--prefix-cache-mib", { "256" } }, { "--prefix-cache-ttl", { "60" } }, { "--placement", { "all_vram" } }, { "--checkpoint-interval", { "256" } }, From df030c7483db284412140bf4886594ce4b50bb36 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 18:42:12 +0000 Subject: [PATCH 003/152] core/text: added (non-special) tokens go through the decoder chain, as in HuggingFace Gemma's tokenizer.json spells runs of 2-31 spaces as added, non-special tokens in U+2581 (ids 138-167). piece_at returned every user-defined token literally, so indentation and double spaces in a Gemma reply came out as U+2581. HuggingFace runs every token it keeps through the decoder; now a user-defined token does too, and only control and unknown tokens stay literal. decode, the Detokenizer and TokenView change together. tokenizer_test covers it with a Gemma-shaped tokenizer.json. Co-Authored-By: Claude Opus 5.5 --- core/text/tokenizer.cpp | 7 ++++--- tests/tokenizer_test.cpp | 31 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index 7cfeee0e..3be3237b 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -1470,9 +1470,10 @@ std::string Tokenizer::piece_at(int32_t id, bool render_special, At at) const { if (b >= 0) return std::string(1, (char)b); std::string s = v_->text(id); - /* User-defined and control tokens are stored as literal text; only normal tokens are in the - * vocab's own encoding and need the decoder chain. */ - if (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN || t == RAD_TT_USER_DEFINED) return s; + /* Control tokens are stored as literal text. A user-defined (added, non-special) token goes + * through the decoder chain like a normal one, as HuggingFace decodes every token it keeps: + * Gemma's whitespace runs are added tokens spelled in U+2581 ("\u2581\u2581" is two spaces). */ + if (t == RAD_TT_CONTROL || t == RAD_TT_UNKNOWN) return s; /* No declared decoder means the tokens are already text (true for unigram and wordpiece, not * byte-level BPE). rad-convert emits the chain it read, so the absence is declared. */ diff --git a/tests/tokenizer_test.cpp b/tests/tokenizer_test.cpp index 358be069..c20f303a 100644 --- a/tests/tokenizer_test.cpp +++ b/tests/tokenizer_test.cpp @@ -1020,4 +1020,35 @@ TEST(the_token_view_gives_grammars_the_decoded_bytes) { CHECK_EQ(tv.token_piece(world[0])[0], ' '); } +/* Gemma's tokenizer.json: whitespace runs are added tokens, not special, spelled in U+2581, and + * the decoder replaces U+2581 with a space. HuggingFace decodes them to spaces; returned literally, + * an indented line came out as "▁▁- web-a" (TranslateGemma, 18. 10. 2026). */ +TEST(an_added_whitespace_run_decodes_to_spaces_as_huggingface_does) { + auto v = from_json(R"JSON({ + "normalizer": { "type": "Replace", "pattern": { "String": " " }, "content": "▁" }, + "decoder": { "type": "Sequence", "decoders": [ + { "type": "Replace", "pattern": { "String": "▁" }, "content": " " }, + { "type": "ByteFallback" }, { "type": "Fuse" } ] }, + "model": { "type": "BPE", "byte_fallback": true, + "vocab": {"": 0, "▁": 1, "-": 2, "▁▁": 3, "": 4, "▁▁▁▁": 5}, + "merges": ["▁ ▁", "▁▁ ▁▁"] }, + "added_tokens": [ + {"id": 3, "content": "▁▁", "special": false, "normalized": false}, + {"id": 5, "content": "▁▁▁▁", "special": false, "normalized": false}, + {"id": 4, "content": "", "special": true} ] + })JSON"); + REQUIRE(v != nullptr); + Tokenizer t; + CHECK_OK(t.init(v)); + CHECK_EQ(t.piece(3, false), std::string(" ")); + CHECK_EQ(t.piece(5, false), std::string(" ")); + CHECK_EQ(t.decode({ 3, 2, 5, 2 }, false), std::string(" - -")); + /* A control token still renders as written. */ + CHECK_EQ(t.piece(4, true), std::string("")); + + TokenView tv; + CHECK_OK(tv.init(v)); + CHECK_EQ(tv.token_piece(3), std::string(" ")); +} + RAD_TEST_MAIN() From 35b357825ea01efc792646607752ded6608bd5e1 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 18:54:49 +0800 Subject: [PATCH 004/152] tests: the oot test builds libr4d at the tree's RAD_HIP_VOPD_REPEATABLE oot_plugins.sh gave libr4d's out-of-tree configure the tree's HIP compiler and targets but not RAD_HIP_VOPD_REPEATABLE. In a tree configured as the build image configures it (ON, for the patched LLVM 24), the out-of-tree libr4d was compiled with VOPD pairing off and step 5 found different device code. The option is now the script's sixth argument (default OFF), forwarded to the device libraries' configure. In radiance-build, ctest -L oot failed at step 5 and now passes. Co-Authored-By: Claude Opus 5.5 --- tests/CMakeLists.txt | 6 +++--- tests/oot_plugins.sh | 16 +++++++++------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9db4e779..82e007d7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -506,13 +506,13 @@ endif() # Installs the build into a prefix, then configures, builds and installs every plugin directory # standalone against it with find_package(radiance). The result must match the tree's plugins, # vocabulary and registration, and serve rad-kbench's fixture through the installed tools -# (tests/oot_plugins.sh). libr4d is included when the tree built it, with the same HIP compiler and -# targets. Labelled `oot`: it rebuilds every plugin and takes minutes. +# (tests/oot_plugins.sh). libr4d is included when the tree built it, with the same HIP compiler, +# targets and RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and takes minutes. set(RAD_OOT_HIP "") if(RAD_HIP_FOUND AND TARGET libr4d) get_target_property(RAD_OOT_R4D_ARCH libr4d HIP_ARCHITECTURES) string(REPLACE ";" "\\;" RAD_OOT_R4D_ARCH "${RAD_OOT_R4D_ARCH}") - set(RAD_OOT_HIP ${CMAKE_HIP_COMPILER} "${RAD_OOT_R4D_ARCH}") + set(RAD_OOT_HIP ${CMAKE_HIP_COMPILER} "${RAD_OOT_R4D_ARCH}" ${RAD_HIP_VOPD_REPEATABLE}) endif() add_test(NAME oot_plugins COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh diff --git a/tests/oot_plugins.sh b/tests/oot_plugins.sh index 4d323229..3d4de138 100644 --- a/tests/oot_plugins.sh +++ b/tests/oot_plugins.sh @@ -1,5 +1,5 @@ #!/bin/sh -# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS] +# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE]] # # THE PLUGINS RADIANCE SHIPS, BUILT THE WAY A THIRD PARTY BUILDS THEIRS. The tree's build is # installed into a prefix; then every plugin directory -- the kernel libraries, the quantisers, @@ -19,13 +19,14 @@ # every host library implements (a norm, the fp8 activation quantiser, a gated activation) # are enough; # 5. with HIP_COMPILER given, the device library the tree built (libr4d) is built out of tree -# too, for HIP_TARGETS, and compiles to the tree's device code. A replay of a device library -# needs a card, and this test must not touch one a server is using; the same instructions mean -# the tree's own GPU suite (ctest -L gpu) has already checked what the out-of-tree build -# produced. +# too, for HIP_TARGETS and at the tree's RAD_HIP_VOPD_REPEATABLE (VOPD_REPEATABLE, default +# OFF; on LLVM 24 it decides whether VOPD pairs, so it changes the code), and compiles to the +# tree's device code. A replay of a device library needs a card, and this test must not touch +# one a server is using; the same instructions mean the tree's own GPU suite (ctest -L gpu) +# has already checked what the out-of-tree build produced. set -eu B=$1; S=$2; W=$3 -HIPC=${4:-}; HIPT=${5:-} +HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF} GEN=${CMAKE_GENERATOR:-Ninja} J=${CMAKE_BUILD_PARALLEL_LEVEL:-$(nproc 2>/dev/null || echo 4)} @@ -62,7 +63,8 @@ for d in $dirs; do n=$(basename "$d") say "building $d against the installed package" extra="" - is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT" + is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT + -DRAD_HIP_VOPD_REPEATABLE=$VOPD" # shellcheck disable=SC2086 run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \ -DCMAKE_PREFIX_PATH="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra From 52f47505c2aa29256ddef1f6f63c9d4904352a13 Mon Sep 17 00:00:00 2001 From: davetha Date: Sun, 18 Oct 2026 22:05:43 +0000 Subject: [PATCH 005/152] json-schema: a pattern without ^ or $ searches, as JSON Schema reads it _visit_pattern() read only ^...$ and refused every other `pattern` with "Pattern must start with '^' and end with '$'". JSON Schema patterns are unanchored (ECMA-262 search, validation 6.3.3). Since 1.8 constrains tool-call arguments with a grammar, a bare pattern on array items failed the whole request: an opencode agent's tool list did, on every request. A missing anchor is now written out as any string text on that side, (?:[^"\\]|\\.)*, not ".*" ('.' matches '"' here, so on array items ["1","x"] read as one string holding a digit). A one-sided anchor beside a top-level '|' is still refused. vendor/patches/0017, vendor/UPSTREAM; tests in gbnf_test (json_schema_grammars_admit_exactly_their_instances) and sample_test (an empty pattern now matches every string). --- tests/gbnf_test.cpp | 16 +++++ tests/sample_test.cpp | 7 ++- vendor/UPSTREAM | 19 ++++++ .../llama/common/json-schema-to-grammar.cpp | 42 ++++++++++++- ...a-a-pattern-without-anchors-searches.patch | 60 +++++++++++++++++++ 5 files changed, 140 insertions(+), 4 deletions(-) create mode 100644 vendor/patches/0017-json-schema-a-pattern-without-anchors-searches.patch diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index 7bce8d68..c120b1d2 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -1694,6 +1694,17 @@ TEST(json_schema_grammars_admit_exactly_their_instances) { { R"({"type":"string","pattern":"^[a-z]{2,5}-[0-9]+$"})", { R"("ab-1")", R"("abcde-123")" }, { R"("a-1")", R"("ab-")", R"("abcdef-1")", R"("AB-1")", R"("ab1")" } }, + /* A pattern without ^ or $ searches, as JSON Schema says: the missing side is any text. + * Tool schemas send them bare; on array items a tool call's JSON arguments reach this + * converter, so one bare pattern there failed the whole request. */ + { R"({"type":"string","pattern":"[0-9]+"})", + { R"("7")", R"("ab12c")" }, { R"("abc")", R"("")" } }, + { R"({"type":"string","pattern":"^ab"})", { R"("ab")", R"("abz")" }, { R"("zab")" } }, + { R"({"type":"string","pattern":"ab$"})", { R"("ab")", R"("zab")" }, { R"("abz")" } }, + { R"({"type":"string","pattern":"a\\$"})", { R"("a$")", R"("za$z")" }, { R"("a")" } }, + { R"({"type":"string","pattern":"x|yz"})", { R"("x")", R"("ayzb")" }, { R"("y")" } }, + { R"({"type":"array","items":{"type":"string","pattern":"[0-9]+"}})", + { R"(["1","x2"])", R"(["x\"1"])", "[]" }, { R"(["x"])", R"(["1","x"])" } }, { R"({"type":"array","items":{"type":"integer"},"minItems":1,"maxItems":3})", { "[1]", "[1,2,3]", "[-4,0]" }, { "[]", "[1,2,3,4]", R"(["a"])" } }, { R"({"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"string"}},)" @@ -1713,6 +1724,11 @@ TEST(json_schema_grammars_admit_exactly_their_instances) { if (schema_admits(bv->v, R"({"type":"number","minimum":0.5})", "-1")) fprintf(stderr, " SKIP number bounds: the converter does not enforce minimum/maximum " "on \"number\"\n"); + for (const char* schema : { R"({"type":"string","pattern":"^a|b"})", + R"({"type":"string","pattern":"a|b$"})" }) { + std::string gbnf, err; + CHECK(grammar_from_json_schema(schema, "root", &gbnf, &err) < 0); + } for (const Case& c : cases) { for (const char* y : c.yes) { const bool ok = schema_admits(bv->v, c.schema, y); diff --git a/tests/sample_test.cpp b/tests/sample_test.cpp index 90f3e9a8..baef11f2 100644 --- a/tests/sample_test.cpp +++ b/tests/sample_test.cpp @@ -1123,10 +1123,11 @@ TEST(json_schema_refuses_what_it_cannot_actually_enforce) { "{\"type\":\"string\",\"pattern\":\"^a]$\"}", "root", &gbnf, &err) < 0); CHECK(!err.empty()); - /* An empty pattern would run front()/back() on an empty string. */ + /* An empty pattern would run front()/back() on an empty string. Unanchored, as JSON Schema + * reads it, it now matches every string and never reaches them (vendor patch 0017). */ err.clear(); - CHECK(grammar_from_json_schema( - "{\"type\":\"string\",\"pattern\":\"\"}", "root", &gbnf, &err) < 0); + CHECK_OK(grammar_from_json_schema( + "{\"type\":\"string\",\"pattern\":\"\"}", "root", &gbnf, &err)); /* A leading quantifier would run back() on an empty vector. */ err.clear(); diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index 1093c4d8..356bc758 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -101,6 +101,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/* patches/0013-json-schema-a-count-past-int-is-no-bound.patch patches/0014-json-schema-a-not-of-every-type-is-never.patch patches/0016-chat-analyse-a-template-once.patch + patches/0017-json-schema-a-pattern-without-anchors-searches.patch On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs @@ -487,3 +488,21 @@ PATCH SERIES from it per request is unchanged: the prompt, grammar, triggers, preserved tokens, stops and PEG parser of 32 requests through each shipped template hash the same with and without the cache, and a render took 1.4-1.6 ms with it against 10-13 ms without (one loaded machine). + + patches/0017-json-schema-a-pattern-without-anchors-searches.patch + + _visit_pattern() read only ^...$ and refused every other `pattern` with "Pattern must + start with '^' and end with '$'". JSON Schema patterns are unanchored (ECMA-262 search, + validation 6.3.3), and tool schemas send them bare: an opencode agent's tool list drew + twelve of these refusals, so every request it made failed. A bare pattern on array items + is refused, since a tool call's JSON arguments reach this converter. (A top-level string + argument is written raw under the XML call formats and never reaches it, which is why a + bare pattern there passed.) A missing anchor is now written out as any string text on that + side, (?:[^"\\]|\\.)*, before the old check, which then refuses only what that cannot + spell: a one-sided anchor beside a top-level '|', where the anchor binds to one branch. The + filler is not ".*": '.' matches '"' here, and on array items ["1","x"] then read as one + string "1\",\"x" holding a digit. An empty pattern now matches every string rather than + being refused (tests/sample_test.cpp updated). A final '$' after an odd run of + backslashes is a literal and does not count as an anchor. tests/gbnf_test.cpp + (json_schema_grammars_admit_exactly_their_instances) holds the converter to the search + reading, on plain strings and on array items, and pins the refusal. diff --git a/vendor/llama/common/json-schema-to-grammar.cpp b/vendor/llama/common/json-schema-to-grammar.cpp index 12e2756e..df4846dc 100644 --- a/vendor/llama/common/json-schema-to-grammar.cpp +++ b/vendor/llama/common/json-schema-to-grammar.cpp @@ -291,6 +291,45 @@ static inline bool is_gbnf_escape(char c) { return false; } } + +// RADIANCE: a JSON Schema `pattern` is unanchored (ECMA-262 search semantics, JSON Schema +// validation 6.3.3): "[0-9]+" admits any string holding a digit. _visit_pattern() reads only +// ^...$, so a missing anchor is written out as "any string text" on that side. That filler is +// not ".*": '.' here matches '"', and the string would run on past its closing quote. A +// one-sided anchor beside a top-level '|' binds to one branch only, so that pattern is +// returned as it came and refused. +static std::string anchor_pattern(const std::string & p) { + static const std::string any = "(?:[^\"\\\\]|\\\\.)*"; + const bool starts = !p.empty() && p.front() == '^'; + size_t slashes = 0; // backslashes before a final '$': an odd count makes it a literal + if (!p.empty() && p.back() == '$') { + for (size_t k = p.size() - 1; k > 0 && p[k - 1] == '\\'; --k) slashes++; + } + const bool ends = p.size() > (starts ? 1u : 0u) && p.back() == '$' && slashes % 2 == 0; + if (starts && ends) { + return p; + } + const size_t from = starts ? 1 : 0; + const std::string core = p.substr(from, p.size() - from - (ends ? 1 : 0)); + if (core.empty()) { + return "^" + any + "$"; + } + if (starts != ends) { + int depth = 0; + bool in_class = false; + for (size_t k = 0; k < core.size(); ++k) { + const char c = core[k]; + if (c == '\\') { ++k; continue; } + if (in_class) { if (c == ']') in_class = false; continue; } + if (c == '[') in_class = true; + else if (c == '(') depth++; + else if (c == ')') depth--; + else if (c == '|' && depth == 0) return p; + } + } + return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$"; +} + static std::unordered_set ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'}; static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function & replacement) { @@ -357,7 +396,8 @@ private: return string_join(rules, " | "); } - std::string _visit_pattern(const std::string & pattern, const std::string & name) { + std::string _visit_pattern(const std::string & client_pattern, const std::string & name) { + const std::string pattern = anchor_pattern(client_pattern); // RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight // off the wire. The size test has to come first. if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) { diff --git a/vendor/patches/0017-json-schema-a-pattern-without-anchors-searches.patch b/vendor/patches/0017-json-schema-a-pattern-without-anchors-searches.patch new file mode 100644 index 00000000..b38c7466 --- /dev/null +++ b/vendor/patches/0017-json-schema-a-pattern-without-anchors-searches.patch @@ -0,0 +1,60 @@ +diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp +index 12e2756..df4846d 100644 +--- a/common/json-schema-to-grammar.cpp ++++ b/common/json-schema-to-grammar.cpp +@@ -291,6 +291,45 @@ static inline bool is_gbnf_escape(char c) { + return false; + } + } ++ ++// RADIANCE: a JSON Schema `pattern` is unanchored (ECMA-262 search semantics, JSON Schema ++// validation 6.3.3): "[0-9]+" admits any string holding a digit. _visit_pattern() reads only ++// ^...$, so a missing anchor is written out as "any string text" on that side. That filler is ++// not ".*": '.' here matches '"', and the string would run on past its closing quote. A ++// one-sided anchor beside a top-level '|' binds to one branch only, so that pattern is ++// returned as it came and refused. ++static std::string anchor_pattern(const std::string & p) { ++ static const std::string any = "(?:[^\"\\\\]|\\\\.)*"; ++ const bool starts = !p.empty() && p.front() == '^'; ++ size_t slashes = 0; // backslashes before a final '$': an odd count makes it a literal ++ if (!p.empty() && p.back() == '$') { ++ for (size_t k = p.size() - 1; k > 0 && p[k - 1] == '\\'; --k) slashes++; ++ } ++ const bool ends = p.size() > (starts ? 1u : 0u) && p.back() == '$' && slashes % 2 == 0; ++ if (starts && ends) { ++ return p; ++ } ++ const size_t from = starts ? 1 : 0; ++ const std::string core = p.substr(from, p.size() - from - (ends ? 1 : 0)); ++ if (core.empty()) { ++ return "^" + any + "$"; ++ } ++ if (starts != ends) { ++ int depth = 0; ++ bool in_class = false; ++ for (size_t k = 0; k < core.size(); ++k) { ++ const char c = core[k]; ++ if (c == '\\') { ++k; continue; } ++ if (in_class) { if (c == ']') in_class = false; continue; } ++ if (c == '[') in_class = true; ++ else if (c == '(') depth++; ++ else if (c == ')') depth--; ++ else if (c == '|' && depth == 0) return p; ++ } ++ } ++ return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$"; ++} ++ + static std::unordered_set ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'}; + + static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function & replacement) { +@@ -357,7 +396,8 @@ private: + return string_join(rules, " | "); + } + +- std::string _visit_pattern(const std::string & pattern, const std::string & name) { ++ std::string _visit_pattern(const std::string & client_pattern, const std::string & name) { ++ const std::string pattern = anchor_pattern(client_pattern); + // RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight + // off the wire. The size test has to come first. + if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) { From dd56e1158dad8ad2d6211df571c38e8e8e47b0c5 Mon Sep 17 00:00:00 2001 From: davetha Date: Mon, 19 Oct 2026 03:07:26 +0000 Subject: [PATCH 006/152] json-schema: \d \w \s and their negations are written out as classes \d \w \s \D \W \S were refused in a literal ("Unsupported regex escape") and copied raw into a class, where GBNF cannot load them. Tool schemas use them freely: oh-my-pi's workpool tool sends "\S" thirteen times, so with 0017 its requests got past the anchors and were refused here. Each shorthand is written out as its ECMA-262 class before the scanner reads the pattern. The negated forms leave out '"', '\' and the control characters and admit any JSON escape instead, so a match cannot run past the closing quote; \s also admits \t \n \f \r. In a class a positive shorthand becomes its ranges and [\s\S] and its kin become any text; a negated shorthand mixed into a class is refused. vendor/patches/0018, vendor/UPSTREAM; gbnf_test cases, and sample_test's "cannot spell" case moves from \d to \b. --- tests/gbnf_test.cpp | 16 ++- tests/sample_test.cpp | 7 +- vendor/UPSTREAM | 18 ++++ .../llama/common/json-schema-to-grammar.cpp | 79 ++++++++++++++- ...ma-shorthand-classes-are-written-out.patch | 97 +++++++++++++++++++ 5 files changed, 212 insertions(+), 5 deletions(-) create mode 100644 vendor/patches/0018-json-schema-shorthand-classes-are-written-out.patch diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index c120b1d2..60aa78d1 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -1705,6 +1705,19 @@ TEST(json_schema_grammars_admit_exactly_their_instances) { { R"({"type":"string","pattern":"x|yz"})", { R"("x")", R"("ayzb")" }, { R"("y")" } }, { R"({"type":"array","items":{"type":"string","pattern":"[0-9]+"}})", { R"(["1","x2"])", R"(["x\"1"])", "[]" }, { R"(["x"])", R"(["1","x"])" } }, + /* \d \w \s and their negations (0018), as tool schemas send them: oh-my-pi's workpool tool + * carries "\S" thirteen times. A negated class must not cross the closing quote. */ + { R"({"type":"string","pattern":"\\S"})", { R"("a")", R"(" a ")" }, { R"("")", R"(" ")" } }, + { R"({"type":"array","items":{"type":"string","pattern":"\\S"}})", + { R"(["a"," b"])" }, { R"([" "])", R"(["a"," "])" } }, + { R"({"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"})", + { R"("2026-10-19")" }, { R"("2026-1-19")", R"("20x6-10-19")" } }, + { R"({"type":"string","pattern":"^[\\w-]+$"})", { R"("a_b-1")" }, { R"("a b")", R"("")" } }, + { R"({"type":"string","pattern":"^-?\\d+(?:\\.\\d+)?$"})", + { R"("3")", R"("-3.14")" }, { R"("3.")", R"("x")" } }, + { R"({"type":"string","pattern":"^a\\sb$"})", { R"("a b")", R"("a\tb")" }, { R"("ab")" } }, + { R"({"type":"string","pattern":"^[\\s\\S]{2}$"})", { R"("ab")", R"("a ")" }, { R"("a")" } }, + { R"({"type":"string","pattern":"^\\D$"})", { R"("x")" }, { R"("7")" } }, { R"({"type":"array","items":{"type":"integer"},"minItems":1,"maxItems":3})", { "[1]", "[1,2,3]", "[-4,0]" }, { "[]", "[1,2,3,4]", R"(["a"])" } }, { R"({"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"string"}},)" @@ -1725,7 +1738,8 @@ TEST(json_schema_grammars_admit_exactly_their_instances) { fprintf(stderr, " SKIP number bounds: the converter does not enforce minimum/maximum " "on \"number\"\n"); for (const char* schema : { R"({"type":"string","pattern":"^a|b"})", - R"({"type":"string","pattern":"a|b$"})" }) { + R"({"type":"string","pattern":"a|b$"})", + R"({"type":"string","pattern":"^[a\\S]$"})" }) { std::string gbnf, err; CHECK(grammar_from_json_schema(schema, "root", &gbnf, &err) < 0); } diff --git a/tests/sample_test.cpp b/tests/sample_test.cpp index baef11f2..3043f33d 100644 --- a/tests/sample_test.cpp +++ b/tests/sample_test.cpp @@ -1108,11 +1108,12 @@ TEST(json_schema_refuses_what_it_cannot_actually_enforce) { "{\"$ref\":\"https://example.com/s.json#/x\"}", "root", &gbnf, &err) < 0); CHECK(!err.empty()); - /* GBNF cannot spell \d. Copying it through would succeed here and produce a grammar that - * fails to load, an internal error on a schema we accepted. */ + /* GBNF cannot spell \b. Copying it through would succeed here and produce a grammar that + * fails to load, an internal error on a schema we accepted. (\d and its kin are written out + * as classes since vendor patch 0018.) */ err.clear(); CHECK(grammar_from_json_schema( - "{\"type\":\"string\",\"pattern\":\"^\\\\d+$\"}", "root", &gbnf, &err) < 0); + "{\"type\":\"string\",\"pattern\":\"^a\\\\bb$\"}", "root", &gbnf, &err) < 0); CHECK(!err.empty()); /* A stray ']' is in NON_LITERAL_SET but claimed by no arm of the pattern scanner, so the diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index 356bc758..0e21d000 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -102,6 +102,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/* patches/0014-json-schema-a-not-of-every-type-is-never.patch patches/0016-chat-analyse-a-template-once.patch patches/0017-json-schema-a-pattern-without-anchors-searches.patch + patches/0018-json-schema-shorthand-classes-are-written-out.patch On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs @@ -506,3 +507,20 @@ PATCH SERIES backslashes is a literal and does not count as an anchor. tests/gbnf_test.cpp (json_schema_grammars_admit_exactly_their_instances) holds the converter to the search reading, on plain strings and on array items, and pins the refusal. + + patches/0018-json-schema-shorthand-classes-are-written-out.patch + + \d \w \s and their negations were refused in a literal ("Unsupported regex escape") and + copied raw inside a class, where GBNF cannot load them. Tool schemas use them freely: + oh-my-pi's workpool tool carries "\S" thirteen times, so with 0017 the request got past + the anchors and was refused here instead. Each shorthand is now written out before the + scanner reads the pattern, as the class ECMA-262 gives it: \d [0-9], \w [A-Za-z0-9_], \s the + ECMA-262 space characters. A JSON string holds text, so the negated forms leave out '"', + '\' and the control characters and admit any JSON escape instead -- a match cannot run past + the closing quote -- and \s also admits the escapes \t \n \f \r. In a class a positive + shorthand becomes its ranges ([\w-], [\da-f]) and [\s\S] and its kin become any text; a + negated shorthand mixed into a class has no GBNF spelling and is refused with a message + that says so. The escapes are judged on the encoded text, so \D admits an escape such as + \u0031 that decodes to a digit. sample_test's "cannot spell" case moves from \d to \b, + which is still refused; gbnf_test covers \S on strings and array items, \d dates and + decimals, [\w-], \s with an escaped tab, [\s\S] and \D, and the refused [a\S]. diff --git a/vendor/llama/common/json-schema-to-grammar.cpp b/vendor/llama/common/json-schema-to-grammar.cpp index df4846dc..46648333 100644 --- a/vendor/llama/common/json-schema-to-grammar.cpp +++ b/vendor/llama/common/json-schema-to-grammar.cpp @@ -330,6 +330,77 @@ static std::string anchor_pattern(const std::string & p) { return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$"; } +// RADIANCE: \d \w \s and their negations, which GBNF cannot spell, written out as the classes +// ECMA-262 gives them, before the scanner reads the pattern. A JSON string holds text, not raw +// bytes: the negated forms leave out '"', '\' and the control characters, which a string can only +// carry escaped, and admit any JSON escape instead, so a match never runs past the closing quote; +// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its +// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling, +// so false is returned and the pattern refused. +static bool expand_shorthands(const std::string & p, std::string & out) { + static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF"; + static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})"; + static const std::string raw = "\"\\\\\\x00-\\x1F"; + auto negated = [&](const std::string & cls) { return "(?:[^" + cls + raw + "]|" + esc + ")"; }; + out.clear(); + for (size_t i = 0; i < p.size(); ++i) { + const char c = p[i]; + if (c == '\\' && i + 1 < p.size()) { + const char n = p[++i]; + switch (n) { + case 'd': out += "[0-9]"; break; + case 'w': out += "[A-Za-z0-9_]"; break; + case 's': out += "(?:[" + sp + "]|\\\\[tnfr])"; break; + case 'D': out += negated("0-9"); break; + case 'W': out += negated("A-Za-z0-9_"); break; + case 'S': out += negated(sp); break; + default: out += c; out += n; break; + } + continue; + } + if (c != '[') { + out += c; + continue; + } + // The class runs to the first unescaped ']', as the scanner reads it. + size_t j = i + 1; + std::string body; + while (j < p.size() && p[j] != ']') { + if (p[j] == '\\' && j + 1 < p.size()) { + body += p.substr(j, 2); + j += 2; + } else { + body += p[j++]; + } + } + if (body == "\\s\\S" || body == "\\S\\s" || body == "\\d\\D" || body == "\\D\\d" || + body == "\\w\\W" || body == "\\W\\w") { + out += "(?:[^" + raw + "]|" + esc + ")"; + i = j; + continue; + } + std::string cls = "["; + for (size_t k = 0; k < body.size(); ++k) { + if (body[k] == '\\' && k + 1 < body.size()) { + const char n = body[++k]; + if (n == 'd') cls += "0-9"; + else if (n == 'w') cls += "A-Za-z0-9_"; + else if (n == 's') cls += sp; + else if (n == 'D' || n == 'W' || n == 'S') return false; + else { cls += '\\'; cls += n; } + } else { + cls += body[k]; + } + } + out += cls; + if (j < p.size()) { + out += ']'; + } + i = j; + } + return true; +} + static std::unordered_set ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'}; static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function & replacement) { @@ -397,7 +468,13 @@ private: } std::string _visit_pattern(const std::string & client_pattern, const std::string & name) { - const std::string pattern = anchor_pattern(client_pattern); + std::string expanded; + if (!expand_shorthands(client_pattern, expanded)) { + _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class " + "cannot be spelled in GBNF"); + return ""; + } + const std::string pattern = anchor_pattern(expanded); // RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight // off the wire. The size test has to come first. if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) { diff --git a/vendor/patches/0018-json-schema-shorthand-classes-are-written-out.patch b/vendor/patches/0018-json-schema-shorthand-classes-are-written-out.patch new file mode 100644 index 00000000..f3f6b75f --- /dev/null +++ b/vendor/patches/0018-json-schema-shorthand-classes-are-written-out.patch @@ -0,0 +1,97 @@ +diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp +index df4846d..4664833 100644 +--- a/common/json-schema-to-grammar.cpp ++++ b/common/json-schema-to-grammar.cpp +@@ -330,6 +330,77 @@ static std::string anchor_pattern(const std::string & p) { + return "^" + (starts ? "" : any) + "(?:" + core + ")" + (ends ? "" : any) + "$"; + } + ++// RADIANCE: \d \w \s and their negations, which GBNF cannot spell, written out as the classes ++// ECMA-262 gives them, before the scanner reads the pattern. A JSON string holds text, not raw ++// bytes: the negated forms leave out '"', '\' and the control characters, which a string can only ++// carry escaped, and admit any JSON escape instead, so a match never runs past the closing quote; ++// \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its ++// ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling, ++// so false is returned and the pattern refused. ++static bool expand_shorthands(const std::string & p, std::string & out) { ++ static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF"; ++ static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})"; ++ static const std::string raw = "\"\\\\\\x00-\\x1F"; ++ auto negated = [&](const std::string & cls) { return "(?:[^" + cls + raw + "]|" + esc + ")"; }; ++ out.clear(); ++ for (size_t i = 0; i < p.size(); ++i) { ++ const char c = p[i]; ++ if (c == '\\' && i + 1 < p.size()) { ++ const char n = p[++i]; ++ switch (n) { ++ case 'd': out += "[0-9]"; break; ++ case 'w': out += "[A-Za-z0-9_]"; break; ++ case 's': out += "(?:[" + sp + "]|\\\\[tnfr])"; break; ++ case 'D': out += negated("0-9"); break; ++ case 'W': out += negated("A-Za-z0-9_"); break; ++ case 'S': out += negated(sp); break; ++ default: out += c; out += n; break; ++ } ++ continue; ++ } ++ if (c != '[') { ++ out += c; ++ continue; ++ } ++ // The class runs to the first unescaped ']', as the scanner reads it. ++ size_t j = i + 1; ++ std::string body; ++ while (j < p.size() && p[j] != ']') { ++ if (p[j] == '\\' && j + 1 < p.size()) { ++ body += p.substr(j, 2); ++ j += 2; ++ } else { ++ body += p[j++]; ++ } ++ } ++ if (body == "\\s\\S" || body == "\\S\\s" || body == "\\d\\D" || body == "\\D\\d" || ++ body == "\\w\\W" || body == "\\W\\w") { ++ out += "(?:[^" + raw + "]|" + esc + ")"; ++ i = j; ++ continue; ++ } ++ std::string cls = "["; ++ for (size_t k = 0; k < body.size(); ++k) { ++ if (body[k] == '\\' && k + 1 < body.size()) { ++ const char n = body[++k]; ++ if (n == 'd') cls += "0-9"; ++ else if (n == 'w') cls += "A-Za-z0-9_"; ++ else if (n == 's') cls += sp; ++ else if (n == 'D' || n == 'W' || n == 'S') return false; ++ else { cls += '\\'; cls += n; } ++ } else { ++ cls += body[k]; ++ } ++ } ++ out += cls; ++ if (j < p.size()) { ++ out += ']'; ++ } ++ i = j; ++ } ++ return true; ++} ++ + static std::unordered_set ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'}; + + static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function & replacement) { +@@ -397,7 +468,13 @@ private: + } + + std::string _visit_pattern(const std::string & client_pattern, const std::string & name) { +- const std::string pattern = anchor_pattern(client_pattern); ++ std::string expanded; ++ if (!expand_shorthands(client_pattern, expanded)) { ++ _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class " ++ "cannot be spelled in GBNF"); ++ return ""; ++ } ++ const std::string pattern = anchor_pattern(expanded); + // RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight + // off the wire. The size test has to come first. + if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) { From 12735a62dcd61571571de30c71f299dac4694af2 Mon Sep 17 00:00:00 2001 From: davetha Date: Mon, 19 Oct 2026 04:08:28 +0000 Subject: [PATCH 007/152] json-schema: identity escapes of punctuation are read as the character Patterns written in JavaScript escape punctuation that needs no escape: "\/" in a path, "\-" in a class. zod's email pattern carries "[A-Za-z0-9_'+\-]", so any tool validating an email with zod sent a schema that was refused outside a class ("Unsupported regex escape") or, inside one, produced a grammar that failed to load. Outside a class such an escape is now the bare character; regex syntax characters and '"' keep their backslash. Inside a class it is written \xHH, so an escaped '-' or '^' cannot read as a range or a negation. Found by running 203 patterns harvested from installed agent packages through rad-gbnf-check. vendor/patches/0019, vendor/UPSTREAM; gbnf_test cases. --- tests/gbnf_test.cpp | 12 ++++ vendor/UPSTREAM | 12 ++++ .../llama/common/json-schema-to-grammar.cpp | 26 ++++++++- ...hema-identity-escapes-of-punctuation.patch | 58 +++++++++++++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) create mode 100644 vendor/patches/0019-json-schema-identity-escapes-of-punctuation.patch diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index 60aa78d1..9cc84c52 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -1718,6 +1718,18 @@ TEST(json_schema_grammars_admit_exactly_their_instances) { { R"({"type":"string","pattern":"^a\\sb$"})", { R"("a b")", R"("a\tb")" }, { R"("ab")" } }, { R"({"type":"string","pattern":"^[\\s\\S]{2}$"})", { R"("ab")", R"("a ")" }, { R"("a")" } }, { R"({"type":"string","pattern":"^\\D$"})", { R"("x")" }, { R"("7")" } }, + /* identity escapes of punctuation (0019): zod's email pattern sends "\-" inside a class, and + * JavaScript-written patterns escape "/". An escaped '-' in a class is not a range. */ + { R"({"type":"string","pattern":"^a\\/b$"})", { R"("a/b")" }, { R"("ab")" } }, + { R"({"type":"string","pattern":"^a\\-b$"})", { R"("a-b")" }, { R"("ab")" } }, + { R"({"type":"string","pattern":"^[a\\-z]$"})", { R"("a")", R"("-")", R"("z")" }, { R"("b")" } }, + { R"({"type":"string","pattern":"^[a\\^]$"})", { R"("^")", R"("a")" }, { R"("b")" } }, + { R"({"type":"string","pattern":"^[\\^a]$"})", { R"("^")", R"("a")" }, { R"("b")" } }, + { R"({"type":"string","pattern":"^[\\--z]$"})", { R"("-")", R"("a")" }, { R"("+")" } }, + { R"({"type":"string","pattern":"^[\\.]$"})", { R"(".")" }, { R"("a")" } }, + { R"({"type":"string","pattern":"a\\-b"})", { R"("xa-by")" }, { R"("ab")" } }, + { R"({"type":"string","pattern":"^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"})", + { R"("a.b@c.io")", R"("x-y@d-e.org")" }, { R"("a@b")", R"("a b@c.io")" } }, { R"({"type":"array","items":{"type":"integer"},"minItems":1,"maxItems":3})", { "[1]", "[1,2,3]", "[-4,0]" }, { "[]", "[1,2,3,4]", R"(["a"])" } }, { R"({"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"string"}},)" diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index 0e21d000..20076c4c 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -103,6 +103,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/* patches/0016-chat-analyse-a-template-once.patch patches/0017-json-schema-a-pattern-without-anchors-searches.patch patches/0018-json-schema-shorthand-classes-are-written-out.patch + patches/0019-json-schema-identity-escapes-of-punctuation.patch On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs @@ -524,3 +525,14 @@ PATCH SERIES \u0031 that decodes to a digit. sample_test's "cannot spell" case moves from \d to \b, which is still refused; gbnf_test covers \S on strings and array items, \d dates and decimals, [\w-], \s with an escaped tab, [\s\S] and \D, and the refused [a\S]. + + patches/0019-json-schema-identity-escapes-of-punctuation.patch + + Patterns written in JavaScript escape punctuation that needs no escape: "\/" in a path, + "\-" in a class (zod's email pattern carries both "[A-Za-z0-9_'+\-]" and "[A-Za-z0-9\-]"). + Outside a class these were refused ("Unsupported regex escape"); inside one they were copied + raw and the grammar failed to load. Outside a class such an escape is now the bare + character -- regex syntax characters and '"' keep their backslash and go the old way -- + and inside a class it is written \xHH, so an escaped '-' or '^' cannot read as a range or + a negation. gbnf_test covers "\/" and "\-" in literals, "\-" "\^" "\." in classes and as + a range endpoint, an unanchored "a\-b", and zod's email pattern. diff --git a/vendor/llama/common/json-schema-to-grammar.cpp b/vendor/llama/common/json-schema-to-grammar.cpp index 46648333..92561c49 100644 --- a/vendor/llama/common/json-schema-to-grammar.cpp +++ b/vendor/llama/common/json-schema-to-grammar.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -336,7 +337,12 @@ static std::string anchor_pattern(const std::string & p) { // carry escaped, and admit any JSON escape instead, so a match never runs past the closing quote; // \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its // ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling, -// so false is returned and the pattern refused. +// so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript +// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. +static bool is_identity_punct(char c) { + return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast(c)); +} + static bool expand_shorthands(const std::string & p, std::string & out) { static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF"; static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})"; @@ -354,7 +360,16 @@ static bool expand_shorthands(const std::string & p, std::string & out) { case 'D': out += negated("0-9"); break; case 'W': out += negated("A-Za-z0-9_"); break; case 'S': out += negated(sp); break; - default: out += c; out += n; break; + default: + // An identity escape of punctuation GBNF has no escape for ("\/", "\-") is the + // bare character; regex syntax characters and '"' keep their backslash. + if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) { + out += n; + } else { + out += c; + out += n; + } + break; } continue; } @@ -387,6 +402,13 @@ static bool expand_shorthands(const std::string & p, std::string & out) { else if (n == 'w') cls += "A-Za-z0-9_"; else if (n == 's') cls += sp; else if (n == 'D' || n == 'W' || n == 'S') return false; + else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') { + // "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could + // read as a range or a negation, so they are written as \xHH. + cls += "\\x"; + cls += "0123456789ABCDEF"[(n >> 4) & 0xF]; + cls += "0123456789ABCDEF"[n & 0xF]; + } else { cls += '\\'; cls += n; } } else { cls += body[k]; diff --git a/vendor/patches/0019-json-schema-identity-escapes-of-punctuation.patch b/vendor/patches/0019-json-schema-identity-escapes-of-punctuation.patch new file mode 100644 index 00000000..24a75154 --- /dev/null +++ b/vendor/patches/0019-json-schema-identity-escapes-of-punctuation.patch @@ -0,0 +1,58 @@ +diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp +index 4664833..92561c4 100644 +--- a/common/json-schema-to-grammar.cpp ++++ b/common/json-schema-to-grammar.cpp +@@ -4,6 +4,7 @@ + #include + + #include ++#include + #include + #include + #include +@@ -336,7 +337,12 @@ static std::string anchor_pattern(const std::string & p) { + // carry escaped, and admit any JSON escape instead, so a match never runs past the closing quote; + // \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its + // ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling, +-// so false is returned and the pattern refused. ++// so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript ++// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. ++static bool is_identity_punct(char c) { ++ return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast(c)); ++} ++ + static bool expand_shorthands(const std::string & p, std::string & out) { + static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF"; + static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})"; +@@ -354,7 +360,16 @@ static bool expand_shorthands(const std::string & p, std::string & out) { + case 'D': out += negated("0-9"); break; + case 'W': out += negated("A-Za-z0-9_"); break; + case 'S': out += negated(sp); break; +- default: out += c; out += n; break; ++ default: ++ // An identity escape of punctuation GBNF has no escape for ("\/", "\-") is the ++ // bare character; regex syntax characters and '"' keep their backslash. ++ if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) { ++ out += n; ++ } else { ++ out += c; ++ out += n; ++ } ++ break; + } + continue; + } +@@ -387,6 +402,13 @@ static bool expand_shorthands(const std::string & p, std::string & out) { + else if (n == 'w') cls += "A-Za-z0-9_"; + else if (n == 's') cls += sp; + else if (n == 'D' || n == 'W' || n == 'S') return false; ++ else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') { ++ // "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could ++ // read as a range or a negation, so they are written as \xHH. ++ cls += "\\x"; ++ cls += "0123456789ABCDEF"[(n >> 4) & 0xF]; ++ cls += "0123456789ABCDEF"[n & 0xF]; ++ } + else { cls += '\\'; cls += n; } + } else { + cls += body[k]; From 8015d9a639d7da365cf364117c33101d6d3d546e Mon Sep 17 00:00:00 2001 From: davetha Date: Mon, 19 Oct 2026 04:44:13 +0000 Subject: [PATCH 008/152] json-schema: control-character escapes match their JSON escape; other class escapes are refused Inside a class, escapes GBNF does not know ([\b], [\f], [\v], [\0], an escaped space, \p{..}, \c, a backreference) were copied raw and the grammar then failed to load, an internal error on a schema the converter had accepted. A JSON string holds a control character only as an escape, so \t \n \r \f \v \0 (and \b in a class) now match that escape, in a positive class as alternatives beside it and in a negated class by leaving the escape out. Outside a class the escape is a group, so a quantifier takes all of it. An escaped space or non-ASCII character is itself; \x and \u in a class need their hex digits. Any other class escape is refused at conversion with a message naming it. vendor/patches/0020, vendor/UPSTREAM; gbnf_test cases. --- tests/gbnf_test.cpp | 25 ++- vendor/UPSTREAM | 18 +++ .../llama/common/json-schema-to-grammar.cpp | 100 ++++++++++-- ...escapes-and-unloadable-class-escapes.patch | 150 ++++++++++++++++++ 4 files changed, 279 insertions(+), 14 deletions(-) create mode 100644 vendor/patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index 9cc84c52..ac57da48 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -1728,6 +1728,23 @@ TEST(json_schema_grammars_admit_exactly_their_instances) { { R"({"type":"string","pattern":"^[\\--z]$"})", { R"("-")", R"("a")" }, { R"("+")" } }, { R"({"type":"string","pattern":"^[\\.]$"})", { R"(".")" }, { R"("a")" } }, { R"({"type":"string","pattern":"a\\-b"})", { R"("xa-by")" }, { R"("ab")" } }, + /* control-character escapes (0020): a JSON string holds a tab or a backspace only as an + * escape, so [\t] [\b] [\f] [\v] [\0] and \t outside a class match the escape, and an + * escaped space or non-ASCII character is itself. */ + { R"({"type":"string","pattern":"^[\\b]$"})", { R"("\b")" }, { R"("b")", R"("\\")" } }, + { R"({"type":"string","pattern":"^[a\\t]+$"})", { R"("a\ta")", R"("a")" }, { R"("t")", R"("a b")" } }, + { R"({"type":"string","pattern":"^[\\f\\v]$"})", { R"("\f")", R"("\u000b")", R"("\u000B")" }, { R"("f")", R"("v")" } }, + { R"({"type":"string","pattern":"^[\\0]$"})", { R"("\u0000")" }, { R"("0")" } }, + { R"({"type":"string","pattern":"^a\\tb$"})", { R"("a\tb")" }, { R"("atb")" } }, + { R"({"type":"string","pattern":"^[a\\ ]+$"})", { R"("a a")" }, { R"("ab")" } }, + { R"({"type":"string","pattern":"^a\\ b$"})", { R"("a b")" }, { R"("ab")" } }, + { R"({"type":"string","pattern":"^[\\s]$"})", { R"(" ")", R"("\n")" }, { R"("n")" } }, + { R"({"type":"string","pattern":"^[^\\t]$"})", { R"("a")" }, { R"("")" } }, + { R"({"type":"string","pattern":"^a\\t+b$"})", { R"("a\t\tb")" }, { R"("a\tttb")", R"("ab")" } }, + { R"({"type":"string","pattern":"^x\\v{2}$"})", { R"("x\u000b\u000B")" }, { R"("x\u000b")" } }, + { R"({"type":"string","pattern":"^[\\t]{2}$"})", { R"("\t\t")" }, { R"("\t")" } }, + { R"({"type":"string","pattern":"^[^\\n]+$"})", { R"("ab")", R"("a\tb")" }, { R"("a\nb")" } }, + { R"({"type":"string","pattern":"^[^\\s]+$"})", { R"("ab")" }, { R"("\t")", R"("a b")" } }, { R"({"type":"string","pattern":"^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"})", { R"("a.b@c.io")", R"("x-y@d-e.org")" }, { R"("a@b")", R"("a b@c.io")" } }, { R"({"type":"array","items":{"type":"integer"},"minItems":1,"maxItems":3})", @@ -1751,7 +1768,13 @@ TEST(json_schema_grammars_admit_exactly_their_instances) { "on \"number\"\n"); for (const char* schema : { R"({"type":"string","pattern":"^a|b"})", R"({"type":"string","pattern":"a|b$"})", - R"({"type":"string","pattern":"^[a\\S]$"})" }) { + R"({"type":"string","pattern":"^[a\\S]$"})", + R"({"type":"string","pattern":"^[\\p{L}]$"})", + R"({"type":"string","pattern":"^[\\cA]$"})", + R"({"type":"string","pattern":"^[a\\1]$"})", + R"({"type":"string","pattern":"^[\\01]$"})", + R"({"type":"string","pattern":"^[\\xZ]$"})", + R"({"type":"string","pattern":"^[\\u{41}]$"})" }) { std::string gbnf, err; CHECK(grammar_from_json_schema(schema, "root", &gbnf, &err) < 0); } diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index 20076c4c..a2fcf8ef 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -104,6 +104,7 @@ vendor/llama/common/regex-partial.{h,cpp} <- llama.cpp common/* patches/0017-json-schema-a-pattern-without-anchors-searches.patch patches/0018-json-schema-shorthand-classes-are-written-out.patch patches/0019-json-schema-identity-escapes-of-punctuation.patch + patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch On 0003: a `pattern` in a `response_format` reaches _visit_pattern() as client data, and three of its paths do not survive that. `front()`/`back()` run on an empty string; `seq.back()` runs @@ -536,3 +537,20 @@ PATCH SERIES and inside a class it is written \xHH, so an escaped '-' or '^' cannot read as a range or a negation. gbnf_test covers "\/" and "\-" in literals, "\-" "\^" "\." in classes and as a range endpoint, an unanchored "a\-b", and zod's email pattern. + + patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch + + Inside a class, escapes GBNF does not know (\b \f \v \0, an escaped space, \p{..}, \c, a + backreference) were copied raw and the grammar failed to load -- an internal error on a + schema the converter had accepted. A JSON string holds a control character only as an + escape, so \t \n \r \f \b \v \0 in a class, and \t \n \r \f \v \0 outside one, now + match that escape: a positive class gains them as alternatives ("[a\t]" reads + "(?:[a]|\\t)", and "[\s]" gains "\\[tnfr]" as 0018 gave the bare \s), and a negated class is + spelled as text that is neither a listed character nor one of those escapes ("[^\n]+" no + longer admits the escape \n). An outside escape is a group, so a quantifier takes all of it. + An escaped space or non-ASCII character is itself. \x and \u in a class need their hex + digits; "\0" before a digit (a legacy octal) is refused. Every other class escape is now + refused at conversion with a message naming it. Limits: a negated class still admits the + \u form of a character it leaves out (\u0009 for \t), and a positive class admits \t \n + \r \f \b only in their short form. gbnf_test covers each escape in and out of a class, quantified, and negated, and the + refusals. diff --git a/vendor/llama/common/json-schema-to-grammar.cpp b/vendor/llama/common/json-schema-to-grammar.cpp index 92561c49..53f067c3 100644 --- a/vendor/llama/common/json-schema-to-grammar.cpp +++ b/vendor/llama/common/json-schema-to-grammar.cpp @@ -338,12 +338,33 @@ static std::string anchor_pattern(const std::string & p) { // \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its // ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling, // so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript -// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. +// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. \t \n \r \f +// \b (in a class) \v \0 are control characters, which a JSON string carries only as escapes, so +// they match the escape. Any other escape in a class (\p{..}, \c, a backreference) has no GBNF +// spelling: `bad` names it and false is returned, rather than copying it into a grammar that +// would then fail to load. static bool is_identity_punct(char c) { return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast(c)); } -static bool expand_shorthands(const std::string & p, std::string & out) { +// The JSON escape for the control character a regex escape names, or "" if it names none. +static std::string json_control_escape(char n) { + switch (n) { + case 't': case 'n': case 'r': case 'f': case 'b': return std::string("\\\\") + n; + case 'v': return "\\\\u000[bB]"; + case '0': return "\\\\u0000"; + default: return ""; + } +} + +static std::string hex_escape(char n) { + std::string s = "\\x"; + s += "0123456789ABCDEF"[(n >> 4) & 0xF]; + s += "0123456789ABCDEF"[n & 0xF]; + return s; +} + +static bool expand_shorthands(const std::string & p, std::string & out, char & bad) { static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF"; static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})"; static const std::string raw = "\"\\\\\\x00-\\x1F"; @@ -365,6 +386,12 @@ static bool expand_shorthands(const std::string & p, std::string & out) { // bare character; regex syntax characters and '"' keep their backslash. if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) { out += n; + } else if (n != 'b' && !json_control_escape(n).empty()) { + // A group, so a following quantifier takes the whole escape. Outside a class + // \b is a word boundary, which the scanner refuses. + out += "(?:" + json_control_escape(n) + ")"; + } else if (n == ' ' || static_cast(n) >= 0x80) { + out += n; } else { out += c; out += n; @@ -395,28 +422,74 @@ static bool expand_shorthands(const std::string & p, std::string & out) { continue; } std::string cls = "["; + // A positive class's control characters can only appear as JSON escapes, which are two + // or six characters long, so they become alternatives beside the class. + std::vector escapes; + const bool negated_cls = !body.empty() && body[0] == '^'; + std::string excluded; // the control characters a negated class leaves out, by escape letter for (size_t k = 0; k < body.size(); ++k) { if (body[k] == '\\' && k + 1 < body.size()) { const char n = body[++k]; if (n == 'd') cls += "0-9"; else if (n == 'w') cls += "A-Za-z0-9_"; - else if (n == 's') cls += sp; - else if (n == 'D' || n == 'W' || n == 'S') return false; + else if (n == 's') { + cls += sp; + if (!negated_cls) escapes.push_back("\\\\[tnfr]"); + else excluded += "tnfr"; + } + else if (n == 'D' || n == 'W' || n == 'S') { bad = n; return false; } + else if (!json_control_escape(n).empty()) { + if (n == '0' && k + 1 < body.size() && std::isdigit(static_cast(body[k + 1]))) { + bad = n; // "\01" is a legacy octal escape + return false; + } + if (negated_cls) excluded += n; + else escapes.push_back(json_control_escape(n)); + } else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') { // "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could // read as a range or a negation, so they are written as \xHH. - cls += "\\x"; - cls += "0123456789ABCDEF"[(n >> 4) & 0xF]; - cls += "0123456789ABCDEF"[n & 0xF]; + cls += hex_escape(n); } - else { cls += '\\'; cls += n; } + else if (n == 'x' || n == 'u') { + // Copied for GBNF to read, so the hex digits must be there. + const size_t len = n == 'x' ? 2 : 4; + for (size_t h = 1; h <= len; ++h) { + if (k + h >= body.size() || !std::isxdigit(static_cast(body[k + h]))) { + bad = n; + return false; + } + } + cls += '\\'; + cls += n; + } + else if (std::string("\"[]\\").find(n) != std::string::npos) { cls += '\\'; cls += n; } + else if (n == ' ' || static_cast(n) >= 0x80) cls += n; + else { bad = n; return false; } } else { cls += body[k]; } } - out += cls; if (j < p.size()) { - out += ']'; + cls += ']'; + } + if (negated_cls && !excluded.empty() && j < p.size()) { + // A string holds those characters only as escapes, so the class becomes text that is + // neither a listed character nor one of those escapes. Their \u forms (\u0009 for \t) + // are still admitted. + std::string letters; + for (char e : std::string("bfnrt")) { + if (excluded.find(e) == std::string::npos) letters += e; + } + out += "(?:[^" + cls.substr(2, cls.size() - 3) + raw + "]|\\\\(?:[\"\\\\/" + letters + + "]|u[0-9A-Fa-f]{4}))"; + } else if (!escapes.empty() && j < p.size()) { + out += "(?:"; + if (cls != "[]") out += cls + "|"; + for (size_t e = 0; e < escapes.size(); ++e) out += (e ? "|" : "") + escapes[e]; + out += ")"; + } else { + out += cls; } i = j; } @@ -491,9 +564,10 @@ private: std::string _visit_pattern(const std::string & client_pattern, const std::string & name) { std::string expanded; - if (!expand_shorthands(client_pattern, expanded)) { - _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class " - "cannot be spelled in GBNF"); + char bad = 0; + if (!expand_shorthands(client_pattern, expanded, bad)) { + _errors.push_back(std::string("Unsupported regex escape '\\") + bad + + "' inside a character class: GBNF cannot spell it"); return ""; } const std::string pattern = anchor_pattern(expanded); diff --git a/vendor/patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch b/vendor/patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch new file mode 100644 index 00000000..75f3b0de --- /dev/null +++ b/vendor/patches/0020-json-schema-control-escapes-and-unloadable-class-escapes.patch @@ -0,0 +1,150 @@ +diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp +index 92561c4..53f067c 100644 +--- a/common/json-schema-to-grammar.cpp ++++ b/common/json-schema-to-grammar.cpp +@@ -338,12 +338,33 @@ static std::string anchor_pattern(const std::string & p) { + // \s adds the escapes \t \n \f \r for the same reason. In a class a positive shorthand becomes its + // ranges and [\s\S] and its kin become any text; a negated one mixed into a class has no spelling, + // so false is returned and the pattern refused. Identity escapes of punctuation, which JavaScript +-// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. ++// writes freely ("\/" in a path, "\-" in a class), become characters GBNF can read. \t \n \r \f ++// \b (in a class) \v \0 are control characters, which a JSON string carries only as escapes, so ++// they match the escape. Any other escape in a class (\p{..}, \c, a backreference) has no GBNF ++// spelling: `bad` names it and false is returned, rather than copying it into a grammar that ++// would then fail to load. + static bool is_identity_punct(char c) { + return c > ' ' && c < 0x7F && c != '\\' && !std::isalnum(static_cast(c)); + } + +-static bool expand_shorthands(const std::string & p, std::string & out) { ++// The JSON escape for the control character a regex escape names, or "" if it names none. ++static std::string json_control_escape(char n) { ++ switch (n) { ++ case 't': case 'n': case 'r': case 'f': case 'b': return std::string("\\\\") + n; ++ case 'v': return "\\\\u000[bB]"; ++ case '0': return "\\\\u0000"; ++ default: return ""; ++ } ++} ++ ++static std::string hex_escape(char n) { ++ std::string s = "\\x"; ++ s += "0123456789ABCDEF"[(n >> 4) & 0xF]; ++ s += "0123456789ABCDEF"[n & 0xF]; ++ return s; ++} ++ ++static bool expand_shorthands(const std::string & p, std::string & out, char & bad) { + static const std::string sp = " \\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000\\uFEFF"; + static const std::string esc = "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})"; + static const std::string raw = "\"\\\\\\x00-\\x1F"; +@@ -365,6 +386,12 @@ static bool expand_shorthands(const std::string & p, std::string & out) { + // bare character; regex syntax characters and '"' keep their backslash. + if (is_identity_punct(n) && std::string("^$.[](){}|*+?\"").find(n) == std::string::npos) { + out += n; ++ } else if (n != 'b' && !json_control_escape(n).empty()) { ++ // A group, so a following quantifier takes the whole escape. Outside a class ++ // \b is a word boundary, which the scanner refuses. ++ out += "(?:" + json_control_escape(n) + ")"; ++ } else if (n == ' ' || static_cast(n) >= 0x80) { ++ out += n; + } else { + out += c; + out += n; +@@ -395,28 +422,74 @@ static bool expand_shorthands(const std::string & p, std::string & out) { + continue; + } + std::string cls = "["; ++ // A positive class's control characters can only appear as JSON escapes, which are two ++ // or six characters long, so they become alternatives beside the class. ++ std::vector escapes; ++ const bool negated_cls = !body.empty() && body[0] == '^'; ++ std::string excluded; // the control characters a negated class leaves out, by escape letter + for (size_t k = 0; k < body.size(); ++k) { + if (body[k] == '\\' && k + 1 < body.size()) { + const char n = body[++k]; + if (n == 'd') cls += "0-9"; + else if (n == 'w') cls += "A-Za-z0-9_"; +- else if (n == 's') cls += sp; +- else if (n == 'D' || n == 'W' || n == 'S') return false; ++ else if (n == 's') { ++ cls += sp; ++ if (!negated_cls) escapes.push_back("\\\\[tnfr]"); ++ else excluded += "tnfr"; ++ } ++ else if (n == 'D' || n == 'W' || n == 'S') { bad = n; return false; } ++ else if (!json_control_escape(n).empty()) { ++ if (n == '0' && k + 1 < body.size() && std::isdigit(static_cast(body[k + 1]))) { ++ bad = n; // "\01" is a legacy octal escape ++ return false; ++ } ++ if (negated_cls) excluded += n; ++ else escapes.push_back(json_control_escape(n)); ++ } + else if (is_identity_punct(n) && n != '"' && n != '[' && n != ']') { + // "\-" "\." "\^" and the like: GBNF has no such escape, and bare they could + // read as a range or a negation, so they are written as \xHH. +- cls += "\\x"; +- cls += "0123456789ABCDEF"[(n >> 4) & 0xF]; +- cls += "0123456789ABCDEF"[n & 0xF]; ++ cls += hex_escape(n); + } +- else { cls += '\\'; cls += n; } ++ else if (n == 'x' || n == 'u') { ++ // Copied for GBNF to read, so the hex digits must be there. ++ const size_t len = n == 'x' ? 2 : 4; ++ for (size_t h = 1; h <= len; ++h) { ++ if (k + h >= body.size() || !std::isxdigit(static_cast(body[k + h]))) { ++ bad = n; ++ return false; ++ } ++ } ++ cls += '\\'; ++ cls += n; ++ } ++ else if (std::string("\"[]\\").find(n) != std::string::npos) { cls += '\\'; cls += n; } ++ else if (n == ' ' || static_cast(n) >= 0x80) cls += n; ++ else { bad = n; return false; } + } else { + cls += body[k]; + } + } +- out += cls; + if (j < p.size()) { +- out += ']'; ++ cls += ']'; ++ } ++ if (negated_cls && !excluded.empty() && j < p.size()) { ++ // A string holds those characters only as escapes, so the class becomes text that is ++ // neither a listed character nor one of those escapes. Their \u forms (\u0009 for \t) ++ // are still admitted. ++ std::string letters; ++ for (char e : std::string("bfnrt")) { ++ if (excluded.find(e) == std::string::npos) letters += e; ++ } ++ out += "(?:[^" + cls.substr(2, cls.size() - 3) + raw + "]|\\\\(?:[\"\\\\/" + letters + ++ "]|u[0-9A-Fa-f]{4}))"; ++ } else if (!escapes.empty() && j < p.size()) { ++ out += "(?:"; ++ if (cls != "[]") out += cls + "|"; ++ for (size_t e = 0; e < escapes.size(); ++e) out += (e ? "|" : "") + escapes[e]; ++ out += ")"; ++ } else { ++ out += cls; + } + i = j; + } +@@ -491,9 +564,10 @@ private: + + std::string _visit_pattern(const std::string & client_pattern, const std::string & name) { + std::string expanded; +- if (!expand_shorthands(client_pattern, expanded)) { +- _errors.push_back("Unsupported pattern: \\D, \\W or \\S inside a character class " +- "cannot be spelled in GBNF"); ++ char bad = 0; ++ if (!expand_shorthands(client_pattern, expanded, bad)) { ++ _errors.push_back(std::string("Unsupported regex escape '\\") + bad + ++ "' inside a character class: GBNF cannot spell it"); + return ""; + } + const std::string pattern = anchor_pattern(expanded); From 0eb3d96ce18ce08d903852d5a9269ccdbe3900a0 Mon Sep 17 00:00:00 2001 From: Nunze Date: Sun, 18 Oct 2026 18:55:35 +0200 Subject: [PATCH 009/152] libr4d: at eight ranks the exact one-shot ends at 8192 elements, the two-shot at 8 blocks The exact all-reduce at eight ranks shared the three- and four-rank band: one-shot up to 524288 elements. The one-shot sends (ws-1)*N bytes a rank, seven times the message at eight ranks, where the two-shot sends 2*(ws-1)/ws*N, and on eight R9700 (PCIe P2P, bf16, warm) the two-shot is the faster from 16384 elements on. A decode step of eight streams with a draft window of six on GLM-5.3-Flash (4096 wide, an out-of-tree plugin) reduces 48 x 4096 = 196608 elements: 232 us one-shot, 68 us two-shot, where all_reduce was 20.7% of the step's device time. R4D_AR_8RANK_ONESHOT_MAX_ELEMS is 8192, a multiple of 64, the eight-rank two-shot's DIV; cArTsExact8 starts one element above it. The two-shot's block rule stops at 8 blocks at eight ranks: every block handshakes with seven peers, and past eight blocks the extra flag rounds cost more than the reduce bandwidth they add (4 blocks up to 393216 elements, 5 at 524288, 8 instead of 16 from 2097152). Both rows fold in fp32 in ascending rank order, so neither change moves a bit. numel before after 4096 one-shot 22.5 us one-shot nb 4 12.8 us 16384 one-shot 39.7 two-shot nb 4 21.5 131072 one-shot 176.3 two-shot nb 4 52.3 196608 one-shot nb 16 233.2 two-shot nb 4 68.7 524288 one-shot 573.7 two-shot nb 5 177.4 2097152 two-shot nb 16 615.8 two-shot nb 8 610.5 8388608 two-shot nb 16 2460 two-shot nb 8 2489 16777216 two-shot nb 16 4999 two-shot nb 8 4824 At 4096 the rule already chose 4 blocks; the 22.5 us was the microbenchmark's, ten launches after the host-side check, which now warms up with as many launches as it times. Band edges are the union over every candidate row (core/plugin/bands.cpp), so the edge at 8192 splits the two-, three- and four-rank bands too. Both halves resolve the same row, kernel and bits, at the cost of one more instance per (width, dtype) whose slot holds 8192 elements. Keeping the edge to eight ranks would need the band builder to skip rows whose fixed constraints the geometry rules out (world_size 8 here), a change to every op's bands for one row; plugin_test states the new edges instead. r4d_selftest runs the eight-rank rows (ar_oneshot_8rank_exact, ar_twoshot_8rank_exact, ar_gather_8rank) through the width-parametrised cases of the three- and four-rank ones instead of skipping them: the pattern's band edge is at 8192 and 8256 there, and a 9-word message must be refused. --perfar8 numel [iters] [dtype] times both rows, one thread a card, at the block rule and at 4 to 64 blocks, each checked bit for bit against the fold on every rank. On the cards: ar_oneshot_8rank_exact 20 ok, ar_twoshot_8rank_exact 16 ok, ar_gather_8rank 5 ok. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- docs/GUIDE.md | 7 +- docs/OPS.md | 10 +- libr4d/r4d_ar_entry.hip | 4 + libr4d/r4d_rows.cpp | 15 +- libr4d/r4d_selftest.cpp | 376 ++++++++++++++++++++++++++++++++++++---- tests/plugin_test.cpp | 53 +++--- 6 files changed, 400 insertions(+), 65 deletions(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 451ef4a9..bf961929 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1000,9 +1000,10 @@ prefill. At three and four ranks `wht6` selects tiered int8 over a two-shot all-reduce, both hops quantised (at three ranks the shards are whole 32-element groups, one uneven where the message does not divide), with the same floor. Eight ranks have no lossy wire; `--tp 8 --tp-wire wht6` stops at -startup naming the all-reduce it found no kernel for, and `--tp-wire exact`. The exact wire at three, -four and eight ranks is one-shot up to 1 MiB a message and two-shot above it, which sends -2·(ranks−1)/ranks of the message per rank instead of (ranks−1) times it, with the same bits. +startup naming the all-reduce it found no kernel for, and `--tp-wire exact`. The exact wire at three +and four ranks is one-shot up to 1 MiB a message and two-shot above it, which sends +2·(ranks−1)/ranks of the message per rank instead of (ranks−1) times it, with the same bits. At +eight ranks the one-shot's seven copies lose early, and it ends at 8192 elements (16 KiB of bf16). On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce runs inside the residual's write, with the MoE gather in front of it. At two ranks the rotated forms of `ar_hc_write` and diff --git a/docs/OPS.md b/docs/OPS.md index 74571720..71719d4a 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -1601,11 +1601,11 @@ not accept a lossy wire gets no kernel rather than the quantised one. `hops` (1 or 2) is a caller's request for one-shot or two-shot; libref accepts and ignores it, and no libr4d row reads it. libr4d chooses by message size where a width has both: its two-shot rows -start above 524288 elements, a band edge of the ranged `numel`. Every all-reduce kernel serves `y` -absent, in place. `overlap` 1 says the caller issues the collective on its second lane, beside -compute; libr4d then picks rows with a narrow launch (8 blocks of 256 threads at two ranks, 4 of -1024 for the four-rank two-shots, exact and tiered-int8) that compute the same bits and leave the -CUs to the kernels running beside them. libref ignores it. +start above 524288 elements (8192 at eight ranks), a band edge of the ranged `numel`. Every +all-reduce kernel serves `y` absent, in place. `overlap` 1 says the caller issues the collective on +its second lane, beside compute; libr4d then picks rows with a narrow launch (8 blocks of 256 +threads at two ranks, 4 of 1024 for the four-rank two-shots, exact and tiered-int8) that compute the +same bits and leave the CUs to the kernels running beside them. libref ignores it. libr4d serves these at 2, 3, 4 and 8 ranks: diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 1283c5f1..c6ce62ad 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -499,6 +499,10 @@ static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) { * full-message rule over-launches across the mid band. */ int cap = in->nb_cap; if (shard_nb && cap > 24) cap = 24; + /* Every block handshakes with all seven peers at eight ranks; past eight blocks the extra + * flag rounds cost more than the added reduce bandwidth (8 against 16 blocks measured up to 3 % + * faster from 2097152 elements on). */ + if (shard_nb && in->world == 8 && cap > 8) cap = 8; c->nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(basis, cap); if (c->nblocks > in->max_blocks) c->nblocks = in->max_blocks; return RAD_OK; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 43345363..a244d920 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -70,6 +70,11 @@ * (32 sequences verifying four tokens) and a 2048-token prefill chunk is 10 MiB. A multiple of 128 * (see pAllReduce's `numel`). */ #define R4D_AR_WIDE_ONESHOT_MAX_ELEMS 524288 +/* The same bound at eight ranks, where the one-shot's (ws-1)*N is seven times the message and + * loses early: on eight R9700 the two-shot is faster from 16384 elements on (21.6 against 26.3 + * us), at a 48-row decode message of 4096 wide 3.4 times. A multiple of 64, the 8-rank + * two-shot's DIV. */ +#define R4D_AR_8RANK_ONESHOT_MAX_ELEMS 8192 #define R4D_XSTR(v) R4D_STR(v) #define R4D_STR(v) #v @@ -2675,9 +2680,9 @@ static const RadOpSchema kSchemas[] = { SCHEMA("all_reduce", pAllReduce, oAllReduce, "sum over the tensor-parallel group. `exact` separates the exact sum from the " "quantised wire and a caller that does not declare it gets no kernel. At 4 and 8 ranks " - "the exact sum is one-shot up to " R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements and " - "two-shot above, chosen by the " - "message's band; `hops` is accepted and no row of this plugin reads it."), + "the exact sum is one-shot up to " R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements " + "(at 8 ranks " R4D_XSTR(R4D_AR_8RANK_ONESHOT_MAX_ELEMS) ") and two-shot above, chosen " + "by the message's band; `hops` is accepted and no row of this plugin reads it."), SCHEMA("all_gather", pAllGather, oAllGather, "y is [world_size * numel] with rank r's contribution at offset r * numel. The bytes are " "moved and never summed: the vocab-parallel sampler's payload is (u32 token id, f32 " @@ -3483,7 +3488,7 @@ static const RadConstraint cArTsExact4Lane[] = { }; static const RadConstraint cArTsExact8[] = { C_EQ("world_size", 8), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), - C_DIV("numel", 64), C_GE("numel", R4D_AR_WIDE_ONESHOT_MAX_ELEMS + 1), + C_DIV("numel", 64), C_GE("numel", R4D_AR_8RANK_ONESHOT_MAX_ELEMS + 1), C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS), C_P2P, }; @@ -5603,7 +5608,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch, per-block pipelined " "handshake", "exactly 8 ranks, all peer-accessible; messages above " - R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements, two hops; shares the wide family's " + R4D_XSTR(R4D_AR_8RANK_ONESHOT_MAX_ELEMS) " elements, two hops; shares the wide family's " "flag/seq/scratch set; message must shard evenly over the ranks; in place; cudagraph-safe", "bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks", RAD_DOMAIN_DEVICE, R4D_PRIO_AR_TWOSHOT, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 34bf4e0c..bce16403 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -58,6 +58,8 @@ #include #include #include +#include +#include #include #include @@ -16099,10 +16101,11 @@ static void gather_two_rank(const Plugin& pl, const std::vector& devs, cons } /* ------------------------------------------------------------------ the wide (3/4/8-rank) family */ -/* The wide kernels are templated on the world size; these cases run them at 3 and 4 ranks (4 is - * the TP4 width). Checked: a rendezvous of `world`, a sum of 1 + 2 + .. + world on every rank bit - * for bit, slot parity surviving a block-count sweep, and the gather placing every slice in both - * layouts. Skipped on fewer cards than the width, with the width named in the skip. */ +/* The wide kernels are templated on the world size; these cases run them at 3, 4 and 8 ranks (4 + * is the TP4 width, 8 the TP8 one). Checked: a rendezvous of `world`, a sum of 1 + 2 + .. + world + * on every rank bit for bit, slot parity surviving a block-count sweep, and the gather placing + * every slice in both layouts. Skipped on fewer cards than the width, with the width named in the + * skip. */ static void ar_wide_rank(const Plugin& pl, const std::vector& devs, const char* name, int world) { const RadKernelInfo* row = find(pl, name); @@ -16245,10 +16248,11 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons return; } struct Run { const char* dtype; std::vector sizes; int oop; }; - /* The three-rank list walks the UNEVEN split (words % 3 of 0, 1 and 2); the four-rank rows - * cannot be given one -- cArTsExact4/cArTi8Ts4 constrain numel so the words divide evenly - * (r4d_rows.cpp), and the two-shot's own entry refuses any other message -- so its list keeps - * the whole-word sizes and the band edges instead. */ + /* The three-rank list walks the UNEVEN split (words % 3 of 0, 1 and 2); the four- and + * eight-rank rows cannot be given one -- cArTsExact4/cArTsExact8/cArTi8Ts4 constrain numel so + * the words divide evenly (r4d_rows.cpp; every size below is a multiple of 64 elements, so + * the words divide by eight too), and the two-shot's own entry refuses any other message -- + * so their list keeps the whole-word sizes and the band edges instead. */ std::vector runs; if (world == 3) { runs = { @@ -16268,6 +16272,12 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons /* fp32: words = numel / 4, whole groups of four either side of the same edge. */ { "fp32", { 1048580 - 4, 524352 }, 0 }, }; + /* Eight ranks end the one-shot band at 8192 (R4D_AR_8RANK_ONESHOT_MAX_ELEMS): the edge + * there instead, words divisible by eight on both sides. */ + if (world == 8) runs = { + { "bf16", { 4194304, 128, 8192, 8256, 4196352, 20971520, 46137344, 4194304 }, 2 }, + { "fp32", { 8192, 8256, 1048576 }, 0 }, + }; } for (const Run& run : runs) { std::vector t((size_t)world); @@ -16321,28 +16331,309 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons } if (row->fini) for (ArPattern& a : t) if (a.inst) row->fini(a.inst); } - /* The four-rank rows' even-shard rule, checked from the one place that can: a message whose - * 16-byte words do not divide by four must be REFUSED (r4d_ar_twoshot_Nrank_exact.hip shards - * it evenly and the entry throws on any residual), not launched with a truncated tail. The - * three-rank row has no such rule -- it splits unevenly by design. */ - if (world == 4 && std::strstr(name, "twoshot")) { - ArPattern t[4]; - for (int r = 0; r < 4; ++r) { - t[r].row = row; t[r].rank = r; t[r].dev = devs[(size_t)r]; t[r].world = 4; - t[r].dtype = "bf16"; t[r].sizes = { 524288, 40 }; /* 40 elems = 5 words: 5 % 4 != 0 */ - t[r].out_of_place = 1; + /* The four- and eight-rank rows' even-shard rule, checked from the one place that can: a + * message whose 16-byte words do not divide by the world must be REFUSED + * (r4d_ar_twoshot_Nrank_exact.hip shards it evenly and the entry throws on any residual), not + * launched with a truncated tail. The three-rank row has no such rule -- it splits unevenly + * by design. 40 bf16 elements are 5 words (5 % 4 != 0), 72 are 9 (9 % 8 != 0). */ + if (world >= 4 && std::strstr(name, "twoshot")) { + const int64_t odd = world == 4 ? 40 : 72; + const std::string w = std::to_string(world); + std::vector t((size_t)world); + std::vector th; + for (int r = 0; r < world; ++r) { + t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; + t[(size_t)r].world = world; + t[(size_t)r].dtype = "bf16"; t[(size_t)r].sizes = { 524288, odd }; + t[(size_t)r].out_of_place = 1; + th.emplace_back(ar_pattern_worker, &t[(size_t)r]); } - std::thread a(ar_pattern_worker, &t[0]), b(ar_pattern_worker, &t[1]), - c(ar_pattern_worker, &t[2]), d(ar_pattern_worker, &t[3]); - a.join(); b.join(); c.join(); d.join(); + for (std::thread& x : th) x.join(); int refused = 0; for (const ArPattern& x : t) { if (x.rc_init == RAD_OK && x.rc_launch == RAD_E_SHAPE) ++refused; if (x.inst) row->fini(x.inst); } - ok((std::string(name) + " refuses a 5-word message at 4 ranks (RAD_E_SHAPE, not a launch)").c_str(), - refused == 4, - std::to_string(refused) + " of 4 ranks refused, rc " + std::to_string(t[0].rc_launch)); + ok((std::string(name) + " refuses a " + std::to_string(odd * 2 / 16) + "-word message at " + + w + " ranks (RAD_E_SHAPE, not a launch)").c_str(), + refused == world, + std::to_string(refused) + " of " + w + " ranks refused, rc " + + std::to_string(t[0].rc_launch)); + } +} + +/* The eight-rank exact all-reduce timed, one thread per card as the engine runs it: both rows + * (one-shot, two-shot) at every message size given, each at the block rule and at fixed block + * counts, out of place on the per-element pattern and checked bit for bit against the fp32 + * ascending-rank fold on every rank. + * + * Warm, every rank launches `iters` times back to back after as many warm-up launches, and the + * period is the span over iters (the handshake keeps ranks in lockstep after the first). Cold + * (--cold MIB), each launch follows a read of MIB through its card's caches and is timed alone; + * flushes end at different times on different cards, so a launch's time on a rank includes + * waiting for the last to arrive. The last arriver's time (the minimum over ranks) is the + * collective's own, the maximum adds the skew; both are reported as medians over the launches. + * The one-shot sends (W-1)*N bytes a rank, the two-shot 2*(W-1)/W*N; GB/s is given on the payload + * and on those sent bytes. */ +class StBarrier { +public: + explicit StBarrier(int n) : n_(n) {} + void wait() { + std::unique_lock lk(m_); + const int g = gen_; + if (++in_ == n_) { in_ = 0; ++gen_; cv_.notify_all(); return; } + cv_.wait(lk, [&] { return gen_ != g; }); + } +private: + std::mutex m_; + std::condition_variable cv_; + int n_, in_ = 0, gen_ = 0; +}; + +struct Ar8Perf { + int rank = 0, dev = 0, world = 8, iters = 0; + const char* dtype = "bf16"; + std::vector sizes; + std::vector rows; + std::vector nbs; + StBarrier* bar = nullptr; + int rc_init = RAD_OK; + /* Per config (size, row, block count): launch rc, wrong elements, the warm period in ms and + * the cold per-launch times in ms. */ + std::vector rc; + std::vector bad; + std::vector period; + std::vector> cold; +}; + +static void ar8_perf_worker(Ar8Perf* t) { + const size_t ncfg = t->sizes.size() * t->rows.size() * t->nbs.size(); + t->rc.assign(ncfg, RAD_E_STATE); t->bad.assign(ncfg, 0); t->period.assign(ncfg, 0.0f); + t->cold.assign(ncfg, {}); + if (st_set_device(t->dev) != hipSuccess) t->rc_init = RAD_E_DEVICE; + const bool bf = !std::strcmp(t->dtype, "bf16"); + const int esz = bf ? 2 : 4; + int64_t most = 0; + for (int64_t n : t->sizes) most = std::max(most, n); + std::vector inst(t->rows.size(), nullptr); + std::vector ip = { + PI("world_size", t->world), PI("numel", most), PS("dtype", t->dtype), PI("exact", 1), + }; + for (size_t j = 0; j < t->rows.size() && t->rc_init == RAD_OK; ++j) + t->rc_init = t->rows[j]->init(ip.data(), (int)ip.size(), t->rank, t->world, &inst[j]); + void *in = nullptr, *out = nullptr, *csrc = nullptr, *cdst = nullptr; + if (t->rc_init == RAD_OK && + (hipMalloc(&in, (size_t)most * esz) != hipSuccess || + hipMalloc(&out, (size_t)most * esz) != hipSuccess || + (g_cold > 0 && (hipMalloc(&csrc, (size_t)g_cold) != hipSuccess || + hipMalloc(&cdst, (size_t)std::min(g_cold, kColdChunk)) != hipSuccess)))) + t->rc_init = RAD_E_NOMEM; + /* Every rank takes part in every barrier whatever its own state, so one failing rank ends + * the run instead of hanging the others. */ + t->bar->wait(); + std::vector h((size_t)most * esz), want((size_t)most * esz), got((size_t)most * esz); + std::vector ev(2 * (size_t)std::max(t->iters, 1)); + for (hipEvent_t& e : ev) st_ev_create(&e); + size_t cfg = 0; + for (int64_t n : t->sizes) { + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int r = 0; r < t->world; ++r) { + const float v = ar_pattern_value(r, i); + acc += bf ? h_bf16(h_to_bf16(v)) : v; + } + const float v = ar_pattern_value(t->rank, i); + if (bf) { + const uint16_t b = h_to_bf16(v), w = h_to_bf16(acc); + std::memcpy(&h[(size_t)i * 2], &b, 2); std::memcpy(&want[(size_t)i * 2], &w, 2); + } else { + std::memcpy(&h[(size_t)i * 4], &v, 4); std::memcpy(&want[(size_t)i * 4], &acc, 4); + } + } + if (t->rc_init == RAD_OK) st_memcpy(in, h.data(), (size_t)n * esz, hipMemcpyHostToDevice); + const uint32_t dt = bf ? RAD_BF16 : RAD_F32; + for (size_t j = 0; j < t->rows.size(); ++j) { + for (int nb : t->nbs) { + std::vector ps = ip; + if (nb > 0) ps.push_back(PI("nblocks", nb)); + RadTensor ts[2] = { T(in, dt, { n }), T(out, dt, { n }) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts; a.n_t = 2; + a.p = ps.data(); a.n_p = (int)ps.size(); + a.instance = inst[j]; + a.rank = t->rank; + a.world_size = t->world; + t->bar->wait(); + int rc = t->rc_init; + if (rc == RAD_OK) { + st_memset(out, 0, (size_t)n * esz); + rc = t->rows[j]->launch(&a, nullptr); + if (st_stream_sync(nullptr) != hipSuccess && rc == RAD_OK) rc = RAD_E_DEVICE; + } + t->rc[cfg] = rc; + t->bar->wait(); + if (rc == RAD_OK) { + st_memcpy(got.data(), out, (size_t)n * esz, hipMemcpyDeviceToHost); + for (int64_t i = 0; i < n; ++i) + t->bad[cfg] += std::memcmp(&got[(size_t)i * esz], &want[(size_t)i * esz], + (size_t)esz) != 0; + } + /* The entry's checks depend only on the arguments, so every rank skips or times + * the same configs; the barriers run unconditionally all the same. */ + const bool timed = rc == RAD_OK && t->iters > 0; + /* As many warm-up launches as timed ones: after the host-side check the cards sit + * idle, and ten launches did not bring the first configuration of a size back to + * clock (the block rule read slower than the same count pinned). */ + if (timed) { + for (int i = 0; i < std::max(t->iters, 50); ++i) + t->rows[j]->launch(&a, nullptr); + st_stream_sync(nullptr); + } + t->bar->wait(); + if (timed) { + if (g_cold <= 0) { + st_ev_record(ev[0], nullptr); + for (int i = 0; i < t->iters; ++i) t->rows[j]->launch(&a, nullptr); + st_ev_record(ev[1], nullptr); + st_ev_sync(ev[1]); + float ms = 0.0f; + st_ev_elapsed(&ms, ev[0], ev[1]); + t->period[cfg] = ms / (float)t->iters; + } else { + for (int i = 0; i < t->iters; ++i) { + for (int64_t off = 0; off < g_cold; off += kColdChunk) + hip_ck(hipMemcpyAsync(cdst, (const char*)csrc + off, + (size_t)std::min(kColdChunk, g_cold - off), + hipMemcpyDeviceToDevice, nullptr), + "hipMemcpyAsync", __LINE__); + st_ev_record(ev[2 * (size_t)i], nullptr); + t->rows[j]->launch(&a, nullptr); + st_ev_record(ev[2 * (size_t)i + 1], nullptr); + } + st_ev_sync(ev[2 * (size_t)t->iters - 1]); + t->cold[cfg].resize((size_t)t->iters); + for (int i = 0; i < t->iters; ++i) + st_ev_elapsed(&t->cold[cfg][(size_t)i], ev[2 * (size_t)i], + ev[2 * (size_t)i + 1]); + } + } + t->bar->wait(); + ++cfg; + } + } + } + for (hipEvent_t e : ev) st_ev_destroy(e); + for (size_t j = 0; j < t->rows.size(); ++j) + if (inst[j] && t->rows[j]->fini) t->rows[j]->fini(inst[j]); + for (void* p : { in, out, csrc, cdst }) if (p) st_free(p); +} + +static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dtype) { + constexpr int W = 8; + if (iters <= 0) iters = 200; + const bool bf = !std::strcmp(dtype, "bf16"); + if (!bf && std::strcmp(dtype, "fp32")) { + std::printf("--perfar8: dtype bf16 or fp32\n"); + return; + } + const int esz = bf ? 2 : 4; + /* Messages at 4096 wide: 1, 4, 32 and 48 rows (the last eight streams with a draft window + * of six), 128 rows (the three- and four-rank one-shot band's top), 512, a 2048-row prefill + * chunk and 4096. */ + std::vector sizes = numel > 0 ? std::vector{ numel } + : std::vector{ 4096, 16384, 131072, 196608, 524288, 2097152, 8388608, 16777216 }; + for (int64_t n : sizes) + if (n <= 0 || n * esz % 16) { std::printf("--perfar8: numel %lld not whole 16-byte words\n", + (long long)n); return; } + int nd = 0; + if (hipGetDeviceCount(&nd) != hipSuccess) nd = 0; + std::vector devs; + for (int d = 0; d < nd; ++d) { + hipDeviceProp_t p; + if (hipGetDeviceProperties(&p, d) == hipSuccess && + !std::strncmp(p.gcnArchName, "gfx1201", 7)) + devs.push_back(d); + } + if ((int)devs.size() < W) { std::printf("--perfar8: needs 8 gfx1201 cards, found %zu\n", + devs.size()); return; } + std::vector rows; + for (const char* name : { "ar_oneshot_8rank_exact", "ar_twoshot_8rank_exact" }) { + const RadKernelInfo* r = find(pl, name); + if (!r) { std::printf("--perfar8: row %s absent\n", name); return; } + rows.push_back(r); + } + const std::vector nbs = { 0, 4, 8, 16, 32, 64 }; + std::printf("eight-rank exact all-reduce, %s, %d launches a point, %s\n", dtype, iters, + g_cold > 0 ? fmt("cold (%lld MiB read before each; last arriver / with skew, " + "medians)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, period over the span, slowest rank)"); + StBarrier bar(W); + std::vector t((size_t)W); + std::vector th; + for (int r = 0; r < W; ++r) { + Ar8Perf& x = t[(size_t)r]; + x.rank = r; x.dev = devs[(size_t)r]; x.iters = iters; x.dtype = dtype; + x.sizes = sizes; x.rows = rows; x.nbs = nbs; x.bar = &bar; + th.emplace_back(ar8_perf_worker, &x); + } + for (std::thread& x : th) x.join(); + for (const Ar8Perf& x : t) + if (x.rc_init != RAD_OK) { + std::printf(" rank %d: init rc=%d\n", x.rank, x.rc_init); + return; + } + auto median = [](std::vector v) { + if (v.empty()) return 0.0f; + std::sort(v.begin(), v.end()); + return v[v.size() / 2]; + }; + size_t cfg = 0; + for (int64_t n : sizes) { + const double bytes = (double)n * esz; + std::printf(" numel %lld (%.0f KiB, %lld 16-byte words)\n", (long long)n, bytes / 1024.0, + (long long)(n * esz / 16)); + for (size_t j = 0; j < rows.size(); ++j) { + const bool two = j == 1; + const double sent = two ? 2.0 * (W - 1) / W * bytes : (double)(W - 1) * bytes; + for (int nb : nbs) { + const Ar8Perf& r0 = t[0]; + /* The entry's nb_for, to name the rule's count: 1400 words a block, floor 4, + * ceiling 16, the two-shot over its shard with ceiling 8 at eight ranks. */ + const int64_t basis = n * esz / 16 / (two ? W : 1); + const int64_t rule = + std::min(std::max(basis / 1400, 4), two ? 8 : 16); + const std::string nbs_ = + nb ? std::to_string(nb) : fmt("rule %lld", (long long)rule); + if (r0.rc[cfg] != RAD_OK) { + std::printf(" %-9s nb %-7s rc=%d (not served)\n", + two ? "two-shot" : "one-shot", nbs_.c_str(), r0.rc[cfg]); + ++cfg; + continue; + } + int64_t bad = 0; + for (const Ar8Perf& x : t) bad += x.bad[cfg]; + double us = 0.0, us_hi = 0.0; + if (g_cold <= 0) { + for (const Ar8Perf& x : t) us = std::max(us, (double)x.period[cfg] * 1000.0); + } else { + std::vector lo((size_t)iters, 1e30f), hi((size_t)iters, 0.0f); + for (const Ar8Perf& x : t) + for (int i = 0; i < iters && i < (int)x.cold[cfg].size(); ++i) { + lo[(size_t)i] = std::min(lo[(size_t)i], x.cold[cfg][(size_t)i]); + hi[(size_t)i] = std::max(hi[(size_t)i], x.cold[cfg][(size_t)i]); + } + us = median(lo) * 1000.0; us_hi = median(hi) * 1000.0; + } + std::printf(" %-9s nb %-7s %8.1f us%s %6.2f GB/s payload %6.2f GB/s sent a " + "rank %s\n", two ? "two-shot" : "one-shot", nbs_.c_str(), us, + g_cold > 0 ? fmt(" (skew %.1f)", us_hi).c_str() : "", + us > 0 ? bytes / (us * 1e3) : 0.0, us > 0 ? sent / (us * 1e3) : 0.0, + bad ? fmt("%lld elements differ from the fold", (long long)bad).c_str() + : "= fold on every rank"); + ++cfg; + } + } } } @@ -19638,10 +19929,12 @@ static void device_phase(const Plugin& pl) { for (const char* base : { "ar_oneshot_2rank_exact", "ar_gather_2rank", "ar_oneshot_3rank_exact", "ar_twoshot_3rank_exact", "ar_twoshot_3rank_ti8", "ar_gather_3rank", "ar_oneshot_4rank_exact", "ar_twoshot_4rank_exact", - "ar_twoshot_4rank_ti8", "ar_gather_4rank" }) { + "ar_twoshot_4rank_ti8", "ar_gather_4rank", "ar_oneshot_8rank_exact", + "ar_twoshot_8rank_exact", "ar_gather_8rank" }) { for (const std::string& n : { std::string(base), std::string(base) + "_host" }) { if (!sel(n.c_str())) continue; - const int world = std::strstr(base, "4rank") ? 4 + const int world = std::strstr(base, "8rank") ? 8 + : std::strstr(base, "4rank") ? 4 : std::strstr(base, "3rank") ? 3 : 2; if (!g_case) { if (world == 2) std::printf("\ncross-rank\n"); @@ -19683,16 +19976,12 @@ static void device_phase(const Plugin& pl) { std::strstr(base, "gather") != nullptr); } } - /* The 8-rank rows cannot be exercised on a four-card box. Reported as skipped rather - * than quietly passing: a row that has never been launched is not a row that works. */ + /* The wide rows at every width are dispatched above and skip themselves, naming the width + * they need, on a box with fewer cards. */ auto skip_pair = [](const char* base, const char* why) { for (const std::string& n : { std::string(base), std::string(base) + "_host" }) if (sel(n.c_str())) skip(n.c_str(), why); }; - /* Only the 8-rank rows now: the four-rank ones are dispatched above and skip themselves with - * the width they need. */ - for (const char* n : { "ar_oneshot_8rank_exact", "ar_twoshot_8rank_exact", "ar_gather_8rank" }) - skip_pair(n, "needs 8 cards"); skip_pair("ar_oneshot_2rank_wht6", "lossy wire: needs a tolerance harness, not a smoke test"); skip_pair("ar_ln_had_quant_i8", "two-rank fusion: needs the same harness as the wht6 wire"); /* Also skipped: the norm half is rmsnorm_quant_fp8's device function, checked there, and the @@ -19836,6 +20125,10 @@ static void usage(void) { " or runs (S contiguous runs). a=bf16 (default) or a=fp8_e4m3 (scale\n" " every 128); y=bf16 (default), y=f16 or y=f32. Each row's t and y are\n" " compared with the first row's; --cold applies.\n" + " --perfar8 numel [iters] [dtype]: the eight-rank exact all-reduce, one thread\n" + " a card: one-shot and two-shot at the block rule and at 4..64 blocks,\n" + " each checked against the rank-order fold; numel 0 runs the decode\n" + " and prefill messages at 4096 wide. dtype bf16 (default) or fp32.\n" " --perfqsa CTX [M] [iters]: the QSA indexer at a real context length. It is\n" " the only decode op that grows with context, and at 200K it is\n" " about a third of the step. M is 1 + n_spec.\n" @@ -19872,6 +20165,9 @@ int main(int argc, char** argv) { int lo_it = 200; bool lo_fp8 = false; uint32_t lo_ydt = RAD_BF16; + long long ar8_n = -1; + int ar8_it = 200; + const char* ar8_dt = "bf16"; for (int i = 1; i < argc; ++i) { if (!std::strcmp(argv[i], "--real")) { if (i + 5 >= argc) { usage(); return 2; } @@ -19959,6 +20255,12 @@ int main(int argc, char** argv) { return 2; } } + } else if (!std::strcmp(argv[i], "--perfar8")) { + /* The eight-rank exact all-reduce rows timed; numel 0 runs the default sizes. */ + if (i + 1 >= argc) { usage(); return 2; } + ar8_n = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_it = (int)std::strtol(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_dt = argv[++i]; } else if (!std::strcmp(argv[i], "--perfhc")) { /* The gated residual's read at M rows. */ if (i + 1 >= argc) { usage(); return 2; } @@ -20068,6 +20370,16 @@ int main(int argc, char** argv) { dfree_all(); #else skip("bf16 expert GEMM timing", "built without HIP"); +#endif + return 0; + } + if (ar8_n >= 0) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + ar8_perf(pl, ar8_n, ar8_it, ar8_dt); + dfree_all(); +#else + skip("eight-rank all-reduce timing", "built without HIP"); #endif return 0; } diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 96562ea4..3349b8a5 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -843,11 +843,14 @@ TEST(an_engine_with_no_card_leaves_a_gpu_librarys_device_rows_out) { for (const KernelRow& row : r.rows()) CHECK(row.info->domain != RAD_DOMAIN_DEVICE); } -/* The shipped libr4d picks the all-reduce by message size. At 3, 4 and 8 ranks the exact sum is a - * one-shot for decode-sized messages and a two-shot for prefill chunks; the two-shot rows start one - * element above the one-shot bound, which is a band edge of the ranged `numel`. The band under it - * must stay resolvable for every row with a DIV on `numel` (two-rank wht6 (64), three- and - * four-rank ti8 (32, 128)), or a lossy serve loses its decode band. Only the real plugin can show +/* The shipped libr4d picks the all-reduce by message size. At 3 and 4 ranks the exact sum is a + * one-shot for decode-sized messages and a two-shot for prefill chunks, at 8 ranks a one-shot only + * up to 8192 elements (its seven-fold send loses early); the two-shot rows start one element above + * the one-shot bound, which is a band edge of the ranged `numel`. Edges are the union over every + * candidate row, so the eight-rank edge at 8192 also splits the other widths' bands, each half + * resolving the same row. The band under the one-shot bound must stay resolvable for every row + * with a DIV on `numel` (two-rank wht6 (64), three- and four-rank ti8 (32, 128)), or a lossy + * serve loses its decode band. Only the real plugin can show * resolution above two ranks on a two-card machine. Geometry: Qwen3.8-Flash-Next, 2560 wide, * 2048-token chunk. */ TEST(libr4d_resolves_the_all_reduce_by_message_size) { @@ -868,35 +871,44 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) { }; CHECK_EQ(band_names(bands(3, 1, chunk)), - "524288:ar_oneshot_3rank_exact 5242880:ar_twoshot_3rank_exact "); + "8192:ar_oneshot_3rank_exact 524288:ar_oneshot_3rank_exact " + "5242880:ar_twoshot_3rank_exact "); CHECK_EQ(band_names(bands(4, 1, chunk)), - "524288:ar_oneshot_4rank_exact 5242880:ar_twoshot_4rank_exact "); + "8192:ar_oneshot_4rank_exact 524288:ar_oneshot_4rank_exact " + "5242880:ar_twoshot_4rank_exact "); CHECK_EQ(band_names(bands(8, 1, chunk)), - "524288:ar_oneshot_8rank_exact 5242880:ar_twoshot_8rank_exact "); + "8192:ar_oneshot_8rank_exact 524288:ar_twoshot_8rank_exact " + "5242880:ar_twoshot_8rank_exact "); CHECK_EQ(band_names(bands(3, 0, chunk)), - "524288:ar_twoshot_3rank_ti8 5242880:ar_twoshot_3rank_ti8 "); + "8192:ar_twoshot_3rank_ti8 524288:ar_twoshot_3rank_ti8 5242880:ar_twoshot_3rank_ti8 "); CHECK_EQ(band_names(bands(4, 0, chunk)), - "524288:ar_twoshot_4rank_ti8 5242880:ar_twoshot_4rank_ti8 "); + "8192:ar_twoshot_4rank_ti8 524288:ar_twoshot_4rank_ti8 5242880:ar_twoshot_4rank_ti8 "); CHECK_EQ(band_names(bands(2, 0, chunk)), - "524288:ar_oneshot_2rank_wht6 5242880:ar_oneshot_2rank_wht6 "); + "8192:ar_oneshot_2rank_wht6 524288:ar_oneshot_2rank_wht6 " + "5242880:ar_oneshot_2rank_wht6 "); CHECK_EQ(band_names(bands(2, 1, chunk)), - "524288:ar_oneshot_2rank_exact 5242880:ar_oneshot_2rank_exact "); + "8192:ar_oneshot_2rank_exact 524288:ar_oneshot_2rank_exact " + "5242880:ar_oneshot_2rank_exact "); /* A 16384-token chunk is two-shot to its end: the two-shot's bound guards its word offsets, * it is not a prefill size, and a chunk past 20971520 elements would otherwise fall back to * the one-shot's twice-as-heavy send. */ CHECK_EQ(band_names(bands(4, 1, 16384)), - "524288:ar_oneshot_4rank_exact 41943040:ar_twoshot_4rank_exact "); + "8192:ar_oneshot_4rank_exact 524288:ar_oneshot_4rank_exact " + "41943040:ar_twoshot_4rank_exact "); CHECK_EQ(band_names(bands(3, 1, 16384)), - "524288:ar_oneshot_3rank_exact 41943040:ar_twoshot_3rank_exact "); + "8192:ar_oneshot_3rank_exact 524288:ar_oneshot_3rank_exact " + "41943040:ar_twoshot_3rank_exact "); /* Above the two-shot's bound the one-shot takes the message back. */ CHECK_EQ(band_names(bands(4, 1, 131072)), - "524288:ar_oneshot_4rank_exact 268435456:ar_twoshot_4rank_exact " - "335544320:ar_oneshot_4rank_exact "); + "8192:ar_oneshot_4rank_exact 524288:ar_oneshot_4rank_exact " + "268435456:ar_twoshot_4rank_exact 335544320:ar_oneshot_4rank_exact "); - /* A step that never exceeds the bound has one band, and it is the one-shot's. */ - CHECK_EQ(band_names(bands(4, 1, 128)), "327680:ar_oneshot_4rank_exact "); + /* A step that never exceeds the bound stays on the one-shot, split only at the eight-rank + * edge. */ + CHECK_EQ(band_names(bands(4, 1, 128)), + "8192:ar_oneshot_4rank_exact 327680:ar_oneshot_4rank_exact "); /* Eight ranks have no lossy wire: every band is a miss that names the request. */ const std::vector none = bands(8, 0, chunk); @@ -912,9 +924,10 @@ TEST(libr4d_resolves_the_all_reduce_by_message_size) { for (const Band& b : bands(3, 0, chunk)) CHECK_EQ(b.dom[RAD_DOMAIN_DEVICE].ranged_div, 32ll); for (const Band& b : bands(4, 0, chunk)) CHECK_EQ(b.dom[RAD_DOMAIN_DEVICE].ranged_div, 128ll); const std::vector exact4 = bands(4, 1, chunk); - REQUIRE_EQ(exact4.size(), 2u); + REQUIRE_EQ(exact4.size(), 3u); CHECK_EQ(exact4[0].dom[RAD_DOMAIN_DEVICE].ranged_div, 0ll); - CHECK_EQ(exact4[1].dom[RAD_DOMAIN_DEVICE].ranged_div, 64ll); + CHECK_EQ(exact4[1].dom[RAD_DOMAIN_DEVICE].ranged_div, 0ll); + CHECK_EQ(exact4[2].dom[RAD_DOMAIN_DEVICE].ranged_div, 64ll); for (const Band& b : bands(3, 1, chunk)) CHECK_EQ(b.dom[RAD_DOMAIN_DEVICE].ranged_div, 0ll); } From 4777be865475d096052e4b7a2330fe5573fd5c9a Mon Sep 17 00:00:00 2001 From: Nunze Date: Sun, 18 Oct 2026 18:55:36 +0200 Subject: [PATCH 010/152] libr4d: the eight-rank two-shot's shards weighted per rank (RADIANCE_AR8_SHARD_WEIGHTS) In the two-shot rank r reduces shard r: in the first hop it sends N - len_r and receives (ws-1)*len_r, in the second the reverse. With even shards every rank moves 1.75 N each way at eight ranks, so on a board whose links differ the slowest link sets the time. On eight R9700 (four links at Gen5 x16, two at Gen5 x8 and two that trained at Gen4 x8, 14.3 GB/s one way by TransferBench) the 16 MiB two-shot, a 2048-token chunk at 4096 wide, takes 2.45 to 3.05 ms over a day, where the Gen4 links alone need 2.05 ms for their 28 MiB. RADIANCE_AR8_SHARD_WEIGHTS=w0,...,w7 sizes rank r's shard in proportion to w_r (the floor, then the few remaining words one each to the weighted ranks in ascending order); a rank of weight 0 owns no shard and only pushes, gathers and handshakes. The shard bounds become a table the kernel takes by value (r4d_ar_shards.h, host-only, shared by the launcher, the shim and the selftest), so a recorded launch keeps its table. Equal weights give the even split word for word, and unset the split is the even one as before; three and four ranks stay unweighted. Which rank reduces a word changes the link it crosses, not its fold, so every table gives the same bits. Every rank must cut the message at the same words: init reads the variable on each rank and fails on all of them if the ranks disagree. A weight over half the sum makes the longest shard's two regions outgrow a message, and only then does init grow the slot. Weighted shards need not divide the words evenly, so the even rule (words % 8, else RAD_E_SHAPE) applies without weights only. Measured with --perfar8 (16 MiB, bf16, warm): even 2.78 to 3.05 ms that day, 4,1,0,4,0,1,4,4 (no shard on the Gen4 ranks) 2.71, 4,2,1,4,1,2,4,4 2.50, 2,1,1,2,1,1,2,2 2.58. Only 10 to 17%: with the hops separated by a handshake a rank sends in one and receives in the other, and the larger of N - len and 7 len a hop is least at len = N/8. The weights pay once the hops overlap. r4d_selftest: ar_wide_weighted runs 0,3,1,0,5,1,2,4, 1,0,0,0,0,0,0,0 and 4,1,0,4,0,1,4,4 over uneven and empty shards, a single owner (the slot grows) and messages of 1 and 9 words, which the even split refuses; the refusal check runs without weights whatever the environment. 55 of 55 on the cards, every one bit for bit with the fold. --perfar8 prints the weights, every size's shard lengths and each rank's time. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d.h | 13 +- libr4d/r4d_ar_entry.hip | 71 ++++++++- libr4d/r4d_ar_shards.h | 76 ++++++++++ libr4d/r4d_ar_twoshot_Nrank_exact.hip | 64 ++++++--- libr4d/r4d_selftest.cpp | 200 ++++++++++++++++++-------- 5 files changed, 332 insertions(+), 92 deletions(-) create mode 100644 libr4d/r4d_ar_shards.h diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 62d488ed..81a08e1f 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -380,10 +380,12 @@ void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers); // rank s (fp32, ascending rank order), then gathered. Sends 2*(ws-1)/ws*N bytes per rank in two // hops, for sizes where the one-shot's (ws-1)*N send is too heavy. Shards are as even as the word // count allows (the first n16 % ws take one more word), so the message need not divide by the -// rank count. Regions A and B sit at 0 and the longest shard, so the slot stride must hold twice -// that. Above the bound below the caller falls back to the one-shot; it only guards the kernel's -// int word offsets (2^28 elements is 2^26 words at fp32). A lower bound would send large prefill -// chunks (e.g. 8192 tokens at Gemma 4's 2816 width, 23M-46M elements) to the one-shot. +// rank count. At 8 ranks `shard_weights` (8 ints, or null for the even split) sizes the shards per +// rank instead (r4d_ar_shards.h); every rank must pass the same weights. Regions A and B sit at 0 +// and the longest shard, so the slot stride must hold twice that. Above the bound below the +// caller falls back to the one-shot; it only guards the kernel's int word offsets (2^28 elements +// is 2^26 words at fp32). A lower bound would send large prefill chunks (e.g. 8192 tokens at +// Gemma 4's 2816 width, 23M-46M elements) to the one-shot. enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456 }; void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, @@ -403,7 +405,8 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long peer_flags5, long peer_flags6, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, - long nblocks, long nthreads, long drain, long acq, long pub); + long nblocks, long nthreads, long drain, long acq, long pub, + const int* shard_weights); // The tiered int8 wire on both two-shot hops (r4d_ar_twoshot_Nrank_ti8.hip; codec in // r4d_ar_ti8.h), 3 or 4 ranks. Int8 groups of 32 with an fp16 scale and a per-group record // (T1 plain, T2 top-1-exact, T3 wht32), 38 bytes/group; tiering is deterministic and diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index c6ce62ad..36760cf2 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -20,6 +20,7 @@ #include "r4d_args.h" #include "r4d.h" +#include "r4d_ar_shards.h" #include #include @@ -68,6 +69,7 @@ struct Rendezvous { long flags [R4D_MAX_RANKS] = { 0 }; long seq [R4D_MAX_RANKS] = { 0 }; int dev [R4D_MAX_RANKS] = { 0 }; + int shard_w[R4D_MAX_RANKS][R4D_MAX_RANKS] = { { 0 } }; int failed = 0; }; @@ -111,6 +113,10 @@ struct ArInst { * each card reaches over its own link (see build). */ int host = 0; long gate_ctr = 0; /* the blocks that have seen their peer's bytes land (r4d_ar_seq.h) */ + /* The eight-rank two-shot's per-rank shard weights (r4d_ar_shards.h), fixed at build so the + * scratch was sized for them and a recorded launch keeps its table. */ + int shard_weighted = 0; + int shard_w[R4D_MAX_RANKS] = { 0 }; }; /* A parameter that may be declared as a range: init gets one band's frozen geometry, and buffers @@ -127,6 +133,29 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) { long align16(long v) { return (v + 15) & ~15L; } +/* RADIANCE_AR8_SHARD_WEIGHTS, read at every eight-rank build so a process can change it between + * instances; each rank reads it and build() checks that they agree. */ +bool ar8_shard_weights(int* w) { + const char* e = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); + if (!e || !*e) return false; + static std::once_flag said_bad, said_on; + int got[8]; + if (!r4d_ar_shard_weights_parse(e, 8, got)) { + std::call_once(said_bad, [e] { + std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs eight non-negative integers, " + "comma-separated, sum > 0); eight-rank two-shot shards stay even\n", + R4D_AR8_SHARD_WEIGHTS_ENV, e); + }); + return false; + } + std::memcpy(w, got, sizeof(got)); + std::call_once(said_on, [w] { + std::fprintf(stderr, "[r4d] eight-rank two-shot shards weighted %d,%d,%d,%d,%d,%d,%d,%d\n", + w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + }); + return true; +} + /* Sequence counter allocation in words: 2 * nbw (r4d_ar_seq.h), then r4d_ar_link_landed's block * counter, padded to a cache line. */ long kSeqWords(long nbw) { return 2L * nbw + 32; } @@ -136,7 +165,9 @@ long kSeqWords(long nbw) { return 2L * nbw + 32; } * One sizing rule for the whole family: a slot holds a full message. The one-shots need exactly * that; the two-shot's two regions (2 * message / world_size) and the tiered-int8 wire's two * images (2 * ceil(shard/32) * 38 bytes) are smaller. RadInitFn is not told which row resolved, - * so sizing for the maximum avoids reconstructing which kernel this instance serves. + * so sizing for the maximum avoids reconstructing which kernel this instance serves. The one + * exception is a weighted eight-rank two-shot whose largest weight is over half the sum: its two + * regions of the longest shard outgrow a message, and the slot grows to hold them. * * Cost: at a 4096-token chunk on a 5120-wide residual, 40 MiB a slot and 80 MiB for the pair. One * set serves every op with the same (rank, world, dtype, bound); see the cache below. */ @@ -153,6 +184,15 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, in->max_numel = (long)max_numel; in->slot_bytes = align16((long)max_numel * in->esize); in->slot16 = in->slot_bytes / 16; + if (world == 8 && ar8_shard_weights(in->shard_w)) { + in->shard_weighted = 1; + const long need16 = + 2 * r4d_ar_shard_max_bound((long)max_numel * in->esize / 16, 8, in->shard_w); + if (need16 > in->slot16) { + in->slot16 = need16; + in->slot_bytes = need16 * 16; + } + } int maxb = 0, nb_design = 0, max_peers = 0; if (world == 2) { @@ -223,10 +263,21 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, g_rv.flags[rank] = fl; g_rv.seq[rank] = sq; g_rv.dev[rank] = dev; + for (int i = 0; i < R4D_MAX_RANKS; ++i) + g_rv.shard_w[rank][i] = in->shard_weighted ? in->shard_w[i] : -1; } int rc = rv_barrier(world); if (rc != RAD_OK) return rc; + /* Every rank must cut the message at the same words, or an owner reduces words its peers + * pushed elsewhere. All ranks compare the same table, so all refuse together. */ + for (int r = 0; r < world; ++r) + if (std::memcmp(g_rv.shard_w[r], g_rv.shard_w[rank], sizeof(g_rv.shard_w[rank]))) { + std::fprintf(stderr, "[r4d] ranks %d and %d read different %s\n", rank, r, + R4D_AR8_SHARD_WEIGHTS_ENV); + return RAD_E_STATE; + } + /* Peer access is per context, so each rank enables its own, after the publish barrier where * peer device ordinals are known. A host can expose more HIP devices than ranks (e.g. an * integrated GPU), so the ordinal comes from the peer rather than the rank. */ @@ -494,7 +545,11 @@ static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) { c->pub = cfgv.pub; const long words16 = (long)n * in->esize / 16; - const long basis = shard_nb ? words16 / in->world : words16; + long basis = shard_nb ? words16 / in->world : words16; + if (shard_nb && in->shard_weighted) { + long off[R4D_MAX_RANKS + 1]; + basis = r4d_ar_shard_table(words16, in->world, in->shard_w, off); + } /* The two-shots move shards, so they use the smaller basis and a tighter ceiling; the * full-message rule over-launches across the mid band. */ int cap = in->nb_cap; @@ -842,10 +897,14 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; if (c.in->world != 8) return RAD_E_SHAPE; if (c.numel > R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) return RAD_E_SHAPE; - const long words16 = c.numel * c.in->esize / 16; - if (words16 % c.in->world) return RAD_E_SHAPE; - if (2 * (c.numel * c.in->esize) / c.in->world > c.in->slot_bytes) return RAD_E_SCRATCH; const ArInst* in = c.in; + const int* weights = in->shard_weighted ? in->shard_w : nullptr; + /* Even shards keep the four-rank rule (whole words a rank); weighted ones are uneven anyway. */ + const long words16 = c.numel * in->esize / 16; + if (!weights && words16 % in->world) return RAD_E_SHAPE; + long off[R4D_MAX_RANKS + 1]; + const long sh_max = r4d_ar_shard_table(words16, in->world, weights, off); + if (2 * sh_max * 16 > in->slot_bytes) return RAD_E_SCRATCH; R4D_TRY("ar_twoshot_8rank_exact", r4d_ar_twoshot_8rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_scratch[3], in->peer_scratch[4], in->peer_scratch[5], @@ -856,7 +915,7 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub)); + c.pub, weights)); return RAD_OK; } diff --git a/libr4d/r4d_ar_shards.h b/libr4d/r4d_ar_shards.h new file mode 100644 index 00000000..2cc2ec6d --- /dev/null +++ b/libr4d/r4d_ar_shards.h @@ -0,0 +1,76 @@ +#pragma once +// r4d_ar_shards.h: the exact two-shot's shard table. Shard s is the 16-byte words +// [off[s], off[s+1]) and is reduced by rank s. Host only and HIP-free: the launcher, the plugin +// shim (which sizes scratch and picks the block count from it) and the selftest (which prints it) +// must derive the same table from the same inputs. +// +// The even split is n16 / ws words a shard with the first n16 % ws shards one word longer. Weights +// split proportionally (floor(n16 * w_s / sum)) and hand the few remaining words, one each, to the +// weighted ranks in ascending order; equal weights therefore reproduce the even split exactly, and +// a zero weight always means an empty shard. Which rank owns a word changes only the link it +// crosses, not its fold (fp32, ascending rank), so every table gives the same bits. +#include + +#define R4D_AR8_SHARD_WEIGHTS_ENV "RADIANCE_AR8_SHARD_WEIGHTS" +enum { R4D_AR_SHARD_WEIGHT_MAX = 65535 }; + +// `ws` non-negative integers separated by commas, each at most R4D_AR_SHARD_WEIGHT_MAX, summing +// to more than zero; nothing else (no blanks, signs or trailing text). +inline bool r4d_ar_shard_weights_parse(const char* s, int ws, int* w) { + if (!s) return false; + long sum = 0; + for (int i = 0; i < ws; ++i) { + if (*s < '0' || *s > '9') return false; + long v = 0; + while (*s >= '0' && *s <= '9') { + v = v * 10 + (*s++ - '0'); + if (v > R4D_AR_SHARD_WEIGHT_MAX) return false; + } + w[i] = (int)v; + sum += v; + if (i + 1 < ws) { + if (*s != ',') return false; + ++s; + } + } + return *s == '\0' && sum > 0; +} + +// Fills off[0..ws] and returns the longest shard. `w` null: the even split. +inline long r4d_ar_shard_table(long n16, int ws, const int* w, long* off) { + long len[16]; + if (!w) { + const long base = n16 / ws, rem = n16 % ws; + for (int s = 0; s < ws; ++s) len[s] = base + (s < rem ? 1 : 0); + } else { + long sum = 0; + for (int s = 0; s < ws; ++s) sum += w[s]; + long left = n16; + for (int s = 0; s < ws; ++s) { + len[s] = n16 * w[s] / sum; + left -= len[s]; + } + for (int s = 0; s < ws && left > 0; ++s) + if (w[s] > 0) { ++len[s]; --left; } + } + long sh_max = 0; + off[0] = 0; + for (int s = 0; s < ws; ++s) { + off[s + 1] = off[s] + len[s]; + if (len[s] > sh_max) sh_max = len[s]; + } + return sh_max; +} + +// The longest shard any message of at most n16 words can get under `w` (null: even): what the +// scratch slot must hold twice. +inline long r4d_ar_shard_max_bound(long n16, int ws, const int* w) { + if (!w) return (n16 + ws - 1) / ws; + long sum = 0, wmax = 0; + for (int s = 0; s < ws; ++s) { + sum += w[s]; + if (w[s] > wmax) wmax = w[s]; + } + const long b = n16 * wmax / sum + 1; + return b < n16 ? b : n16; +} diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index a1f021cf..eedcd541 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -9,10 +9,14 @@ // to my out and every peer's slot[me] region B, flag 2s; assemble out from region B. Region A at // 0, B at sh_max; the slot stride must hold 2*sh_max. // -// Uneven shards: n16 words split into base = n16/ws words per shard, and the first n16 % ws shards -// take one more, so shard s starts at s*base + min(s, rem). At 4 and 8 ranks engine residuals -// divide evenly; at 3 they rarely do (a 2048-wide bf16 row is 256 words). Each word is the same -// fp32 fold in ascending rank order whoever owns it, so the bits match the one-shot's. +// The shard table (r4d_ar_shards.h) comes in as a kernel argument. By default it is the even +// split (the first n16 % ws shards one word longer); at 3 ranks engine residuals rarely divide (a +// 2048-wide bf16 row is 256 words). At 8 ranks it may be weighted per link +// (RADIANCE_AR8_SHARD_WEIGHTS); a rank with weight 0 owns nothing and only pushes, gathers and +// handshakes. Over both phases a rank moves N + (ws-2)*len_r each way, but phase 1 only sends +// N - len_r (receiving (ws-1)*len_r) and phase 2 the reverse, so a short shard on a slow link pays +// only as far as the phases overlap on that link (docs/GUIDE.md, 4.7). Each word is the same fp32 +// fold in ascending rank order whoever owns it, so the bits match the one-shot's. // // Shares the wide family's flag/seq/scratch set (r4d_ar_wide.h): it publishes in the 2*seq flag // space plus the 2s-1 half-step and advances the per-block counter once per AR, so one buffer set @@ -20,14 +24,21 @@ // requirement in the mix. #include "r4d.h" #include "r4d_ar_wide.h" +#include "r4d_ar_shards.h" #include #include +template +struct R4DArShardOff { + int off[WS + 1]; + int sh_max; +}; + template __global__ void r4d_ar_twoshot_wide_exact_kernel( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, - int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16, + int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff sh, int slot_stride16, int rank, int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; @@ -38,11 +49,9 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel( const unsigned int s = s_seq; const int parity = (int)s_slot; - // shard s = words [s*base + min(s, rem), +base + (s < rem)); sh_max is the longest one - const int base = n16 / WS, rem = n16 % WS; - const int sh_max = base + (rem ? 1 : 0); -#define R4D_TS_OFF(s) ((s) * base + ((s) < rem ? (s) : rem)) -#define R4D_TS_LEN(s) (base + ((s) < rem ? 1 : 0)) + const int sh_max = sh.sh_max; +#define R4D_TS_OFF(s) (sh.off[s]) +#define R4D_TS_LEN(s) (sh.off[(s) + 1] - sh.off[s]) const int w = (sh_max + nb - 1) / nb; // block b owns words [w0,w1) of the SHARD space const int w0 = b * w; @@ -118,7 +127,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream_i, long nblocks, long nthreads, long drain, long acq, long pub, - long gate, long gate_ctr) { + long gate, long gate_ctr, const int* shard_weights) { constexpr int NPEERS = WS - 1; if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce: rank " + std::to_string(rank) + @@ -133,11 +142,25 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, std::to_string(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) + " elems); use the fallback path"); const long n16 = nbytes / 16; - if (n16 < WS) + if (!shard_weights && n16 < WS) throw std::runtime_error("all_reduce: message (" + std::to_string(n16) + " 16B words) is shorter than one word a rank"); - // the longest shard (the kernel's uneven split); regions A and B each hold one - const long sh_max = (n16 + WS - 1) / WS; + if (n16 < 1) throw std::runtime_error("all_reduce: empty message"); + if (shard_weights) { + long wsum = 0; + for (int s = 0; s < WS; ++s) { + if (shard_weights[s] < 0 || shard_weights[s] > R4D_AR_SHARD_WEIGHT_MAX) + throw std::runtime_error("all_reduce: shard weight out of range"); + wsum += shard_weights[s]; + } + if (wsum <= 0) throw std::runtime_error("all_reduce: shard weights sum to zero"); + } + long off[WS + 1]; + const long sh_max = r4d_ar_shard_table(n16, WS, shard_weights, off); + R4DArShardOff sh{}; + for (int s = 0; s <= WS; ++s) sh.off[s] = (int)off[s]; + sh.sh_max = (int)sh_max; + // regions A and B each hold the longest shard if (2 * sh_max > (long)slot_stride16) throw std::runtime_error("all_reduce: shard (" + std::to_string(sh_max) + " 16B words) needs 2x inside the per-source slot stride (" + @@ -178,7 +201,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, #define R4D_AR_TS_LAUNCH(T, LN) \ r4d_ar_twoshot_wide_exact_kernel<<>>( \ (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ - (int4*)out, (unsigned int*)seq_ctrs, (int)n16, (int)slot_stride16, \ + (int4*)out, (unsigned int*)seq_ctrs, sh, (int)slot_stride16, \ (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \ (unsigned int*)gate_ctr) if (dtype == 0) R4D_AR_TS_LAUNCH(__hip_bfloat16, 8); @@ -197,7 +220,7 @@ void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pee const long pf[2] = {peer_flags0, peer_flags1}; /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, nullptr); } void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -209,7 +232,8 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr, + nullptr); } void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -219,12 +243,14 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long peer_flags5, long peer_flags6, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, - long nblocks, long nthreads, long drain, long acq, long pub) { + long nblocks, long nthreads, long drain, long acq, long pub, + const int* shard_weights) { const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3, peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, peer_flags4, peer_flags5, peer_flags6}; /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, + shard_weights); } diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index bce16403..0e9e2407 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -35,6 +35,7 @@ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_args.h" +#include "r4d_ar_shards.h" #include "r4d_hc_fp8.h" #include "r4d_fp8_frag.h" #include "r4d_fp8_lm.h" @@ -16239,6 +16240,82 @@ static void ar_pattern_worker(ArPattern* t) { st_free(out); } +/* An environment variable set (or, with a null value, cleared) for one scope and restored after + * it: the eight-rank two-shot reads its settings at every init. */ +struct ScopedEnv { + const char* name; + bool had; + std::string kept; + ScopedEnv(const char* n, const char* v) : name(n) { + const char* was = std::getenv(n); + had = was != nullptr; + if (was) kept = was; + if (v) setenv(n, v, 1); else unsetenv(n); + } + ~ScopedEnv() { if (had) setenv(name, kept.c_str(), 1); else unsetenv(name); } + ScopedEnv(const ScopedEnv&) = delete; + ScopedEnv& operator=(const ScopedEnv&) = delete; +}; + +struct ArPatternRun { const char* dtype; std::vector sizes; int oop; }; + +/* One run on a fresh instance per rank, every size checked against the fold. False when init + * failed, so the caller stops instead of reporting every later run as failed too. */ +static bool ar_pattern_check(const RadKernelInfo* row, const std::vector& devs, + const std::string& name, int world, const ArPatternRun& run) { + std::vector t((size_t)world); + std::vector th; + for (int r = 0; r < world; ++r) { + t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; + t[(size_t)r].world = world; + t[(size_t)r].dtype = run.dtype; t[(size_t)r].sizes = run.sizes; + t[(size_t)r].out_of_place = run.oop; + th.emplace_back(ar_pattern_worker, &t[(size_t)r]); + } + for (std::thread& x : th) x.join(); + const std::string what = name + " " + run.dtype; + bool up = true, ran = true; + std::string rcs; + for (const ArPattern& a : t) { + up = up && a.rc_init == RAD_OK; ran = ran && a.rc_launch == RAD_OK; + rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; + } + ok((what + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); + if (!up) return false; + ok((what + " launches").c_str(), ran, "init/launch rc " + rcs); + if (ran) { + const bool bf = !std::strcmp(run.dtype, "bf16"); + for (size_t k = 0; k < run.sizes.size(); ++k) { + const int64_t n = run.sizes[k]; + int64_t bad = 0, first = -1; + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int r = 0; r < world; ++r) { + const float v = ar_pattern_value(r, i); + acc += bf ? h_bf16(h_to_bf16(v)) : v; + } + const float want = bf ? h_bf16(h_to_bf16(acc)) : acc; + for (int r = 0; r < world; ++r) + if (t[(size_t)r].out.size() <= k || t[(size_t)r].out[k][(size_t)i] != want) { + if (first < 0) first = i; + ++bad; + } + } + const int64_t words = n * (bf ? 2 : 4) / 16; + const std::string label = + what + " numel " + std::to_string(n) + " (" + std::to_string(words) + + " words, % " + std::to_string(world) + " = " + + std::to_string(words % world) + + ((int)k == run.oop ? ", out of place" : ", in place") + + ") == fp32 ascending-rank fold on every rank, bit for bit"; + ok(label.c_str(), bad == 0, + std::to_string(bad) + " elements wrong, first at " + std::to_string(first)); + } + } + if (row->fini) for (ArPattern& a : t) if (a.inst) row->fini(a.inst); + return true; +} + static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, const char* name, int world) { const RadKernelInfo* row = find(pl, name); @@ -16247,12 +16324,13 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str()); return; } - struct Run { const char* dtype; std::vector sizes; int oop; }; + using Run = ArPatternRun; /* The three-rank list walks the UNEVEN split (words % 3 of 0, 1 and 2); the four- and * eight-rank rows cannot be given one -- cArTsExact4/cArTsExact8/cArTi8Ts4 constrain numel so * the words divide evenly (r4d_rows.cpp; every size below is a multiple of 64 elements, so - * the words divide by eight too), and the two-shot's own entry refuses any other message -- - * so their list keeps the whole-word sizes and the band edges instead. */ + * the words divide by eight too), and without shard weights the two-shot's own entry refuses + * any other message -- so their list keeps the whole-word sizes and the band edges instead + * (uneven eight-rank shards: ar_wide_weighted). */ std::vector runs; if (world == 3) { runs = { @@ -16279,64 +16357,16 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons { "fp32", { 8192, 8256, 1048576 }, 0 }, }; } - for (const Run& run : runs) { - std::vector t((size_t)world); - std::vector th; - for (int r = 0; r < world; ++r) { - t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; - t[(size_t)r].world = world; - t[(size_t)r].dtype = run.dtype; t[(size_t)r].sizes = run.sizes; - t[(size_t)r].out_of_place = run.oop; - th.emplace_back(ar_pattern_worker, &t[(size_t)r]); - } - for (std::thread& x : th) x.join(); - const std::string what = std::string(name) + " " + run.dtype; - bool up = true, ran = true; - std::string rcs; - for (const ArPattern& a : t) { - up = up && a.rc_init == RAD_OK; ran = ran && a.rc_launch == RAD_OK; - rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; - } - ok((what + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); - if (!up) return; - ok((what + " launches").c_str(), ran, "init/launch rc " + rcs); - if (ran) { - const bool bf = !std::strcmp(run.dtype, "bf16"); - for (size_t k = 0; k < run.sizes.size(); ++k) { - const int64_t n = run.sizes[k]; - int64_t bad = 0, first = -1; - for (int64_t i = 0; i < n; ++i) { - float acc = 0.0f; - for (int r = 0; r < world; ++r) { - const float v = ar_pattern_value(r, i); - acc += bf ? h_bf16(h_to_bf16(v)) : v; - } - const float want = bf ? h_bf16(h_to_bf16(acc)) : acc; - for (int r = 0; r < world; ++r) - if (t[(size_t)r].out.size() <= k || t[(size_t)r].out[k][(size_t)i] != want) { - if (first < 0) first = i; - ++bad; - } - } - const int64_t words = n * (bf ? 2 : 4) / 16; - const std::string label = - what + " numel " + std::to_string(n) + " (" + std::to_string(words) + - " words, % " + std::to_string(world) + " = " + - std::to_string(words % world) + - ((int)k == run.oop ? ", out of place" : ", in place") + - ") == fp32 ascending-rank fold on every rank, bit for bit"; - ok(label.c_str(), bad == 0, - std::to_string(bad) + " elements wrong, first at " + std::to_string(first)); - } - } - if (row->fini) for (ArPattern& a : t) if (a.inst) row->fini(a.inst); - } + for (const Run& run : runs) + if (!ar_pattern_check(row, devs, name, world, run)) return; /* The four- and eight-rank rows' even-shard rule, checked from the one place that can: a - * message whose 16-byte words do not divide by the world must be REFUSED - * (r4d_ar_twoshot_Nrank_exact.hip shards it evenly and the entry throws on any residual), not - * launched with a truncated tail. The three-rank row has no such rule -- it splits unevenly - * by design. 40 bf16 elements are 5 words (5 % 4 != 0), 72 are 9 (9 % 8 != 0). */ + * message whose 16-byte words do not divide by the world must be REFUSED, not launched with a + * truncated tail. The three-rank row has no such rule -- it splits unevenly by design -- and + * neither has a weighted eight-rank one (ar_wide_weighted), so the rule is checked without + * weights whatever the environment. 40 bf16 elements are 5 words (5 % 4 != 0), 72 are 9 + * (9 % 8 != 0). */ if (world >= 4 && std::strstr(name, "twoshot")) { + ScopedEnv even(R4D_AR8_SHARD_WEIGHTS_ENV, nullptr); const int64_t odd = world == 4 ? 40 : 72; const std::string w = std::to_string(world); std::vector t((size_t)world); @@ -16362,6 +16392,28 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons } } +/* The eight-rank two-shot with per-rank shard weights (RADIANCE_AR8_SHARD_WEIGHTS): shards of + * unequal length, empty ones (weight 0: the rank only pushes, gathers and handshakes), a single + * owner (its two regions outgrow a message, so init must grow the slot), and messages shorter than + * one word a rank, which the even split refuses. The fold is the same whoever owns a word, so the + * oracle is unchanged. */ +static void ar_wide_weighted(const Plugin& pl, const std::vector& devs, const char* name) { + constexpr int W = 8; + const RadKernelInfo* row = find(pl, name); + if (!row) { ok(name, false, "row absent"); return; } + if ((int)devs.size() < W) { skip(name, "needs 8 gfx1201 cards"); return; } + /* bf16: 72 elements are 9 words, 8 are one; 8256 is 1032 words, 4196352 is 524544. */ + const std::vector runs = { + { "bf16", { 4194304, 72, 8, 128, 8256, 4196352, 4194304 }, 1 }, + { "fp32", { 36, 1048580 }, 0 }, + }; + for (const char* w : { "0,3,1,0,5,1,2,4", "1,0,0,0,0,0,0,0", "4,1,0,4,0,1,4,4" }) { + ScopedEnv env(R4D_AR8_SHARD_WEIGHTS_ENV, w); + for (const ArPatternRun& run : runs) + if (!ar_pattern_check(row, devs, std::string(name) + " weights " + w, W, run)) return; + } +} + /* The eight-rank exact all-reduce timed, one thread per card as the engine runs it: both rows * (one-shot, two-shot) at every message size given, each at the block rule and at fixed block * counts, out of place on the per-element pattern and checked bit for bit against the fp32 @@ -16568,6 +16620,17 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty g_cold > 0 ? fmt("cold (%lld MiB read before each; last arriver / with skew, " "medians)", (long long)(g_cold >> 20)).c_str() : "warm (back to back, period over the span, slowest rank)"); + /* The plugin reads the same variable through the same parser at init, so this is the table + * the two-shot runs. */ + int wts[W]; + const char* wenv = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); + const bool weighted = wenv && *wenv && r4d_ar_shard_weights_parse(wenv, W, wts); + std::printf("two-shot shard weights: %s\n", + weighted ? fmt("%d,%d,%d,%d,%d,%d,%d,%d", wts[0], wts[1], wts[2], wts[3], wts[4], + wts[5], wts[6], wts[7]).c_str() + : wenv && *wenv ? fmt("even (%s=\"%s\" is invalid)", R4D_AR8_SHARD_WEIGHTS_ENV, + wenv).c_str() + : "even"); StBarrier bar(W); std::vector t((size_t)W); std::vector th; @@ -16591,16 +16654,22 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty size_t cfg = 0; for (int64_t n : sizes) { const double bytes = (double)n * esz; + const int64_t n16 = n * esz / 16; std::printf(" numel %lld (%.0f KiB, %lld 16-byte words)\n", (long long)n, bytes / 1024.0, - (long long)(n * esz / 16)); + (long long)n16); + long off[W + 1]; + const int64_t sh_max = r4d_ar_shard_table((long)n16, W, weighted ? wts : nullptr, off); + std::string shards; + for (int r = 0; r < W; ++r) shards += fmt(" %ld", off[r + 1] - off[r]); + std::printf(" two-shot shard words by rank:%s\n", shards.c_str()); for (size_t j = 0; j < rows.size(); ++j) { const bool two = j == 1; const double sent = two ? 2.0 * (W - 1) / W * bytes : (double)(W - 1) * bytes; for (int nb : nbs) { const Ar8Perf& r0 = t[0]; /* The entry's nb_for, to name the rule's count: 1400 words a block, floor 4, - * ceiling 16, the two-shot over its shard with ceiling 8 at eight ranks. */ - const int64_t basis = n * esz / 16 / (two ? W : 1); + * ceiling 16, the two-shot over its longest shard with ceiling 8 at eight ranks. */ + const int64_t basis = two ? (weighted ? sh_max : n16 / W) : n16; const int64_t rule = std::min(std::max(basis / 1400, 4), two ? 8 : 16); const std::string nbs_ = @@ -16614,6 +16683,11 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty int64_t bad = 0; for (const Ar8Perf& x : t) bad += x.bad[cfg]; double us = 0.0, us_hi = 0.0; + /* Warm: each rank's period; cold: each rank's median launch. */ + std::string per_rank; + for (const Ar8Perf& x : t) + per_rank += fmt(" %.1f", g_cold <= 0 ? (double)x.period[cfg] * 1000.0 + : (double)median(x.cold[cfg]) * 1000.0); if (g_cold <= 0) { for (const Ar8Perf& x : t) us = std::max(us, (double)x.period[cfg] * 1000.0); } else { @@ -16631,6 +16705,7 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty us > 0 ? bytes / (us * 1e3) : 0.0, us > 0 ? sent / (us * 1e3) : 0.0, bad ? fmt("%lld elements differ from the fold", (long long)bad).c_str() : "= fold on every rank"); + std::printf(" us by rank:%s\n", per_rank.c_str()); ++cfg; } } @@ -19956,6 +20031,7 @@ static void device_phase(const Plugin& pl) { ar_wide_ti8(pl, devs, n.c_str(), world); } else if (std::strstr(base, "twoshot")) { ar_wide_pattern(pl, devs, n.c_str(), world); + if (world == 8) ar_wide_weighted(pl, devs, n.c_str()); } else { ar_wide_rank(pl, devs, n.c_str(), world); /* The one-shot through the same per-element oracle: both rows of the op agree From adc7f37a7088365e5295743afa3007d10f658efc Mon Sep 17 00:00:00 2001 From: Nunze Date: Sun, 18 Oct 2026 18:55:36 +0200 Subject: [PATCH 011/152] libr4d: the eight-rank two-shot in pieces, both hops on the link at once, by message size Each block splits its words (in shard space) into K runs. Step j pushes run j+1's first hop and reduces and pushes run j's second, then handshakes, so a rank with a short shard sends and receives at once instead of one direction a hop. A launch takes K+1 handshakes instead of two. The flag a (block, source) publishes is a monotone counter, so one handshake vouches for every earlier one, and r4d_ar_seq_take reserves the K steps at once (`steps`, 1 for every other kernel): one-shots and gathers on the same instance stay in the family's flag space. The regions stay at 0 and the longest shard, so the scratch is as before; every word is touched by the same thread in the same three steps, so the fold, the bits and the in-place form are unchanged. The launcher clamps K to the words a block holds, and K 1 is its own instantiation without the loop. 16 MiB, bf16, warm K 1 K 2 K 4 K 8 even 2841 us 2806 2667 2470 4,1,0,4,0,1,4,4 2730 2126 1798 1636 4,2,1,4,1,2,4,4 2495 2121 1940 1922 4,1,0,4,0,1,4,4 in 8 pieces is 42% under the even split. Fitting measured = f x computed + h x (K+1) at K 4 and 8 gives f = 1.21 and h about 5 us a handshake: what separates 1636 us from the 1.17 ms the Gen4 links need is their efficiency, not the handshakes. A decode-sized message loses with either: numel even K 1 4,1,0,4,0,1,4,4: K 1 / K 2 / K 4 / K 8 196608 73 us 85 / 76 / 81 / 113 524288 214 207 / 166 / 169 / 198 2097152 699 711 / 581 / 531 / 527 8388608 2841 2730 / 2126 / 1798 / 1636 so below RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS and RADIANCE_AR8_PIECES_MIN_ELEMS (262144 elements each) the message runs even and in one piece, on the kernel as it was. Above them, without RADIANCE_AR8_PIECES, K follows the size (r4d_ar8_auto_pieces): 2 under 1048576 elements, 4 under 4194304, 8 above, where the crossings above lie. RADIANCE_AR8_PIECES (1 to 16) fixes K over the floor, and a launch's `pieces` parameter (the selftest's) overrides that. Weights and K are a function of the message size and the instance (ar8_weights_for, ar8_pieces_for), so a replay of the same size decides the same; the slot is sized for weights only when the largest message is over the weight floor. Every rank compares both variables and both floors at init. r4d_selftest, with both floors at 0: the weighted and even sets at K 1, 2 and 4 (1- and 9-word messages cross the launcher's clamp), and one instance whose K changes from launch to launch (1, 4, 2, 8, 16, 3, 1), which a wrong flag reservation hangs or races. At the default floors: the size rule over 131072 to 4194304 elements, K 4 on both sides of the piece floor, a 131073-word message over the weight floor (served only weighted) and a 9-word one under it (refused, and served at a floor of 64). 192 of 192 on the cards. --perfar8 names the floors and times the two-shot as the server runs it and at K 1, 2, 4 and 8. GLM-5.3-Flash at TP8 (an out-of-tree plugin) on these eight cards with 4,1,0,4,0,1,4,4, against the same build without in the same hour: a 20K-token prefill 3450 tok/s against 2945, 8K 3372 against 2920; eight agent streams 457 tok/s against 458, one 141 against 139. K 8 at every size instead gave the same prefill (3461) and 436 at eight streams, 113 at one. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d.h | 14 ++- libr4d/r4d_ar_entry.hip | 89 +++++++++++-- libr4d/r4d_ar_seq.h | 10 +- libr4d/r4d_ar_shards.h | 37 +++++- libr4d/r4d_ar_twoshot_Nrank_exact.hip | 168 ++++++++++++++++--------- libr4d/r4d_ar_wide.h | 3 +- libr4d/r4d_selftest.cpp | 175 ++++++++++++++++++++++---- 7 files changed, 391 insertions(+), 105 deletions(-) diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 81a08e1f..8745d5db 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -382,11 +382,13 @@ void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers); // count allows (the first n16 % ws take one more word), so the message need not divide by the // rank count. At 8 ranks `shard_weights` (8 ints, or null for the even split) sizes the shards per // rank instead (r4d_ar_shards.h); every rank must pass the same weights. Regions A and B sit at 0 -// and the longest shard, so the slot stride must hold twice that. Above the bound below the -// caller falls back to the one-shot; it only guards the kernel's int word offsets (2^28 elements -// is 2^26 words at fp32). A lower bound would send large prefill chunks (e.g. 8192 tokens at -// Gemma 4's 2816 width, 23M-46M elements) to the one-shot. -enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456 }; +// and the longest shard, so the slot stride must hold twice that. `pieces` (8 ranks, 1 to +// R4D_AR_TS_MAX_PIECES, the same on every rank) pipelines each block's words in that many runs so +// phase 1 of one run and phase 2 of the previous share the link; 1 is the unpipelined kernel. +// Above the bound below the caller falls back to the one-shot; it only guards the kernel's int +// word offsets (2^28 elements is 2^26 words at fp32). A lower bound would send large prefill +// chunks (e.g. 8192 tokens at Gemma 4's 2816 width, 23M-46M elements) to the one-shot. +enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456, R4D_AR_TS_MAX_PIECES = 16 }; void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, @@ -406,7 +408,7 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - const int* shard_weights); + const int* shard_weights, long pieces); // The tiered int8 wire on both two-shot hops (r4d_ar_twoshot_Nrank_ti8.hip; codec in // r4d_ar_ti8.h), 3 or 4 ranks. Int8 groups of 32 with an fp16 scale and a per-group record // (T1 plain, T2 top-1-exact, T3 wht32), 38 bytes/group; tiering is deterministic and diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 36760cf2..b0e2c9a9 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -34,6 +34,8 @@ static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 268435456, "r4d_rows.cpp restates this bound; libr4d changed it"); static_assert(R4D_MAX_RANKS == 8, "the 8-rank entry point names exactly seven peers"); +static_assert((long long)R4D_AR8_MIN_ELEMS_MAX == (long long)R4D_AR_TWOSHOT_WIDE_MAX_ELEMS, + "r4d_ar_shards.h restates the two-shot band's top"); /* ------------------------------------------------------------------ throw conversion * @@ -70,6 +72,9 @@ struct Rendezvous { long seq [R4D_MAX_RANKS] = { 0 }; int dev [R4D_MAX_RANKS] = { 0 }; int shard_w[R4D_MAX_RANKS][R4D_MAX_RANKS] = { { 0 } }; + int pieces [R4D_MAX_RANKS] = { 0 }; + long long weights_min[R4D_MAX_RANKS] = { 0 }; + long long pieces_min [R4D_MAX_RANKS] = { 0 }; int failed = 0; }; @@ -117,6 +122,12 @@ struct ArInst { * scratch was sized for them and a recorded launch keeps its table. */ int shard_weighted = 0; int shard_w[R4D_MAX_RANKS] = { 0 }; + /* Its piece count (RADIANCE_AR8_PIECES), 0 for the size rule (r4d_ar8_auto_pieces); a launch's + * `pieces` parameter overrides it. */ + int pieces = 0; + /* Messages under these sizes (elements) run even and in one piece, whatever is configured. */ + long long weights_min = R4D_AR8_MIN_ELEMS_DEFAULT; + long long pieces_min = R4D_AR8_MIN_ELEMS_DEFAULT; }; /* A parameter that may be declared as a range: init gets one band's frozen geometry, and buffers @@ -156,6 +167,49 @@ bool ar8_shard_weights(int* w) { return true; } +/* RADIANCE_AR8_PIECES and the two size floors, read like the weights. */ +int ar8_pieces() { + const char* e = std::getenv(R4D_AR8_PIECES_ENV); + if (!e || !*e) return 0; + long long v = 0; + if (!r4d_ar_parse_count(e, R4D_AR_TS_MAX_PIECES, &v) || v < 1) { + static std::once_flag said; + std::call_once(said, [e] { + std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs 1..%d); the eight-rank " + "two-shot takes its piece count from the message size\n", + R4D_AR8_PIECES_ENV, e, (int)R4D_AR_TS_MAX_PIECES); + }); + return 0; + } + return (int)v; +} + +long long ar8_min_elems(const char* name, std::once_flag* said) { + const char* e = std::getenv(name); + if (!e || !*e) return R4D_AR8_MIN_ELEMS_DEFAULT; + long long v = 0; + if (!r4d_ar_parse_count(e, R4D_AR8_MIN_ELEMS_MAX, &v)) { + std::call_once(*said, [name, e] { + std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs 0..%d elements); using %d\n", + name, e, (int)R4D_AR8_MIN_ELEMS_MAX, + (int)R4D_AR8_MIN_ELEMS_DEFAULT); + }); + return R4D_AR8_MIN_ELEMS_DEFAULT; + } + return v; +} + +/* The eight-rank two-shot's choice for one message, a function of its size and the instance + * alone: a recorded launch keeps the table and piece count it was recorded with, and replays of + * the same size agree with it. */ +const int* ar8_weights_for(const ArInst* in, long numel) { + return in->shard_weighted && numel >= in->weights_min ? in->shard_w : nullptr; +} +long long ar8_pieces_for(const ArInst* in, long numel, long long asked) { + if (numel < in->pieces_min) return 1; + return asked > 0 ? asked : r4d_ar8_auto_pieces(numel); +} + /* Sequence counter allocation in words: 2 * nbw (r4d_ar_seq.h), then r4d_ar_link_landed's block * counter, padded to a cache line. */ long kSeqWords(long nbw) { return 2L * nbw + 32; } @@ -184,11 +238,18 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, in->max_numel = (long)max_numel; in->slot_bytes = align16((long)max_numel * in->esize); in->slot16 = in->slot_bytes / 16; + if (world == 8) { + static std::once_flag said_w, said_p; + in->pieces = ar8_pieces(); + in->weights_min = ar8_min_elems(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, &said_w); + in->pieces_min = ar8_min_elems(R4D_AR8_PIECES_MIN_ENV, &said_p); + } if (world == 8 && ar8_shard_weights(in->shard_w)) { in->shard_weighted = 1; const long need16 = 2 * r4d_ar_shard_max_bound((long)max_numel * in->esize / 16, 8, in->shard_w); - if (need16 > in->slot16) { + /* Sized only if some message this instance carries is weighted. */ + if (max_numel >= in->weights_min && need16 > in->slot16) { in->slot16 = need16; in->slot_bytes = need16 * 16; } @@ -265,16 +326,24 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, g_rv.dev[rank] = dev; for (int i = 0; i < R4D_MAX_RANKS; ++i) g_rv.shard_w[rank][i] = in->shard_weighted ? in->shard_w[i] : -1; + g_rv.pieces[rank] = in->pieces; + g_rv.weights_min[rank] = in->weights_min; + g_rv.pieces_min[rank] = in->pieces_min; } int rc = rv_barrier(world); if (rc != RAD_OK) return rc; /* Every rank must cut the message at the same words, or an owner reduces words its peers - * pushed elsewhere. All ranks compare the same table, so all refuse together. */ + * pushed elsewhere, and take the same handshake steps, or the flags drift apart. All ranks + * compare the same values, so all refuse together. */ for (int r = 0; r < world; ++r) - if (std::memcmp(g_rv.shard_w[r], g_rv.shard_w[rank], sizeof(g_rv.shard_w[rank]))) { - std::fprintf(stderr, "[r4d] ranks %d and %d read different %s\n", rank, r, - R4D_AR8_SHARD_WEIGHTS_ENV); + if (std::memcmp(g_rv.shard_w[r], g_rv.shard_w[rank], sizeof(g_rv.shard_w[rank])) || + g_rv.pieces[r] != g_rv.pieces[rank] || + g_rv.weights_min[r] != g_rv.weights_min[rank] || + g_rv.pieces_min[r] != g_rv.pieces_min[rank]) { + std::fprintf(stderr, "[r4d] ranks %d and %d read different eight-rank two-shot " + "settings (%s, %s and their _MIN_ELEMS)\n", rank, r, + R4D_AR8_SHARD_WEIGHTS_ENV, R4D_AR8_PIECES_ENV); return RAD_E_STATE; } @@ -546,7 +615,7 @@ static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) { const long words16 = (long)n * in->esize / 16; long basis = shard_nb ? words16 / in->world : words16; - if (shard_nb && in->shard_weighted) { + if (shard_nb && ar8_weights_for(in, n)) { long off[R4D_MAX_RANKS + 1]; basis = r4d_ar_shard_table(words16, in->world, in->shard_w, off); } @@ -898,13 +967,17 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { if (c.in->world != 8) return RAD_E_SHAPE; if (c.numel > R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) return RAD_E_SHAPE; const ArInst* in = c.in; - const int* weights = in->shard_weighted ? in->shard_w : nullptr; + const int* weights = ar8_weights_for(in, c.numel); /* Even shards keep the four-rank rule (whole words a rank); weighted ones are uneven anyway. */ const long words16 = c.numel * in->esize / 16; if (!weights && words16 % in->world) return RAD_E_SHAPE; long off[R4D_MAX_RANKS + 1]; const long sh_max = r4d_ar_shard_table(words16, in->world, weights, off); if (2 * sh_max * 16 > in->slot_bytes) return RAD_E_SCRATCH; + /* Pieces only move the handshakes; the regions stay at 0 and sh_max, so scratch is as above. */ + const long long asked = r4d_pgeti_or(a->p, a->n_p, "pieces", in->pieces); + if (asked < 0 || asked > R4D_AR_TS_MAX_PIECES) return RAD_E_INVAL; + const long long pieces = ar8_pieces_for(in, c.numel, asked); R4D_TRY("ar_twoshot_8rank_exact", r4d_ar_twoshot_8rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_scratch[3], in->peer_scratch[4], in->peer_scratch[5], @@ -915,7 +988,7 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub, weights)); + c.pub, weights, (long)pieces)); return RAD_OK; } diff --git a/libr4d/r4d_ar_seq.h b/libr4d/r4d_ar_seq.h index 9613548c..e9ae425c 100644 --- a/libr4d/r4d_ar_seq.h +++ b/libr4d/r4d_ar_seq.h @@ -33,17 +33,21 @@ // Sets `s_seq` to this block's handshake value and `s_slot` to the launch's scratch slot (0 or 1), // then barriers so every thread can read both. `nbw` is the capacity the counters were allocated -// for, and gridDim.x must not exceed it. +// for, and gridDim.x must not exceed it. `steps` handshake values are taken at once (s_seq is the +// first): a kernel that handshakes more than twice per launch reserves the flag values it +// publishes, so every kernel on the instance stays in the same monotone flag space. All ranks must +// take the same number for the same block. // // The barrier fences LDS only, since it publishes just the two LDS words. A full __syncthreads // would wait for the outstanding parity atomics and invalidate the vector caches, putting that // traffic on the path to the first push. __device__ __forceinline__ void r4d_ar_seq_take(unsigned int* __restrict__ ctrs, unsigned int nbw, - unsigned int& s_seq, unsigned int& s_slot) { + unsigned int& s_seq, unsigned int& s_slot, + unsigned int steps = 1u) { const unsigned int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; unsigned int* const par = ctrs + nbw; const unsigned int pt = nt > 32u ? 32u : 0u; // first lane of the second wave, if there is one - if (tid == 0) s_seq = atomicAdd(&ctrs[b], 1u) + 1u; + if (tid == 0) s_seq = atomicAdd(&ctrs[b], steps) + 1u; if (tid == pt) s_slot = (atomicAdd(&par[b], 1u) + 1u) & 1u; for (unsigned int j = b + (tid + 1u) * nb; j < nbw; j += nt * nb) atomicAdd(&par[j], 1u); __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); diff --git a/libr4d/r4d_ar_shards.h b/libr4d/r4d_ar_shards.h index 2cc2ec6d..6d3de9ab 100644 --- a/libr4d/r4d_ar_shards.h +++ b/libr4d/r4d_ar_shards.h @@ -12,7 +12,42 @@ #include #define R4D_AR8_SHARD_WEIGHTS_ENV "RADIANCE_AR8_SHARD_WEIGHTS" -enum { R4D_AR_SHARD_WEIGHT_MAX = 65535 }; +#define R4D_AR8_PIECES_ENV "RADIANCE_AR8_PIECES" +// Below these message sizes (elements) the weights and the pieces do not apply: a decode-sized +// message pays more for the extra handshakes and the uneven split than its link time saves +// (measured on the eight R9700: 196608 elements run fastest even and in one piece, 524288 already +// gain from weights and two pieces). +#define R4D_AR8_SHARD_WEIGHTS_MIN_ENV "RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS" +#define R4D_AR8_PIECES_MIN_ENV "RADIANCE_AR8_PIECES_MIN_ELEMS" +enum { + R4D_AR_SHARD_WEIGHT_MAX = 65535, + R4D_AR8_MIN_ELEMS_DEFAULT = 262144, + R4D_AR8_MIN_ELEMS_MAX = 268435456, // the two-shot band's top (r4d.h) +}; + +// The piece count when RADIANCE_AR8_PIECES is unset, by message size in elements: more pieces +// shorten the one-way first and last steps ((K+1)/K of the link time) but add a handshake each, +// which only a large message amortises (measured at 4,1,0,4,0,1,4,4: K2 best at 524288, K4 at +// 2097152, K8 at 8388608). +inline int r4d_ar8_auto_pieces(long long numel) { + if (numel < 262144) return 1; + if (numel < 1048576) return 2; + if (numel < 4194304) return 4; + return 8; +} + +// A non-negative decimal integer of at most `max`, nothing else. +inline bool r4d_ar_parse_count(const char* s, long long max, long long* out) { + if (!s || *s < '0' || *s > '9') return false; + long long v = 0; + while (*s >= '0' && *s <= '9') { + v = v * 10 + (*s++ - '0'); + if (v > max) return false; + } + if (*s) return false; + *out = v; + return true; +} // `ws` non-negative integers separated by commas, each at most R4D_AR_SHARD_WEIGHT_MAX, summing // to more than zero; nothing else (no blanks, signs or trailing text). diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index eedcd541..98b0e6f2 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -18,10 +18,15 @@ // only as far as the phases overlap on that link (docs/GUIDE.md, 4.7). Each word is the same fp32 // fold in ascending rank order whoever owns it, so the bits match the one-shot's. // +// At 8 ranks the message may also run in pieces (RADIANCE_AR8_PIECES, by default a count from +// the message size, r4d_ar_shards.h): each block's words split into `pieces` runs pipelined so +// piece j+1's phase 1 shares the link with piece j's phase 2. A rank with a short shard then +// sends and receives at once instead of one direction per phase. +// // Shares the wide family's flag/seq/scratch set (r4d_ar_wide.h): it publishes in the 2*seq flag -// space plus the 2s-1 half-step and advances the per-block counter once per AR, so one buffer set -// can carry any mix of one-shot and two-shot launches. The slot stride must hold the largest -// requirement in the mix. +// space plus the 2s-1 half-step (with pieces: pieces+1 values from 2s-1 on, after reserving one +// step a piece), so one buffer set can carry any mix of one-shot and two-shot launches. The slot +// stride must hold the largest requirement in the mix. #include "r4d.h" #include "r4d_ar_wide.h" #include "r4d_ar_shards.h" @@ -34,19 +39,22 @@ struct R4DArShardOff { int sh_max; }; -template +// PIECED false fixes pieces at 1, so the unpipelined launch keeps the straight-line kernel. +template __global__ void r4d_ar_twoshot_wide_exact_kernel( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff sh, int slot_stride16, int rank, int drain, int acq, int pub, - long long* gate, unsigned int* gate_ctr) { + long long* gate, unsigned int* gate_ctr, int pieces_arg) { constexpr int NPEERS = WS - 1; + const int pieces = PIECED ? pieces_arg : 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); - r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); // device-resident, replay-safe - const unsigned int s = s_seq; + // device-resident, replay-safe; `pieces` steps reserve the 2*pieces flag values this launch uses + r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot, (unsigned int)pieces); + const unsigned int v0 = 2u * s_seq - 1u; const int parity = (int)s_slot; const int sh_max = sh.sh_max; @@ -56,6 +64,7 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel( const int w = (sh_max + nb - 1) / nb; // block b owns words [w0,w1) of the SHARD space const int w0 = b * w; int w1 = w0 + w; if (w1 > sh_max) w1 = sh_max; + const int pw = (w + pieces - 1) / pieces; // piece j of the block: [w0 + j*pw, +pw) within w1 // region A of my slot in every peer's scratch (B sits at +sh_max) int4* pa[NPEERS]; @@ -63,60 +72,83 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel( for (int p = 0; p < NPEERS; ++p) pa[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16; - // ---- phase 1 push: my contribution to each peer-owned shard -> owner's region A - for (int p = 0; p < NPEERS; ++p) { - const int owner = peers.rank[p]; - const int4* src = in4 + (size_t)R4D_TS_OFF(owner); - int4* dst = pa[p]; - const int lim = w1 < R4D_TS_LEN(owner) ? w1 : R4D_TS_LEN(owner); - for (int k = w0 + tid; k < lim; k += nt) dst[k] = src[k]; - } - r4d_ar_handshake(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub); - - // ---- reduce my shard (fp32, ascending rank, own contribution from the input), and phase 2 - // push: the reduced word goes to my out and every peer's region B in the same pass const int4* src[WS]; #pragma unroll for (int r = 0; r < WS; ++r) src[r] = (r == rank) ? (in4 + (size_t)R4D_TS_OFF(rank)) : (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16); int4* my_out = out4 + (size_t)R4D_TS_OFF(rank); - const int my_lim = w1 < R4D_TS_LEN(rank) ? w1 : R4D_TS_LEN(rank); - for (int k = w0 + tid; k < my_lim; k += nt) { - float acc[LANES]; -#pragma unroll - for (int j = 0; j < LANES; ++j) acc[j] = 0.0f; -#pragma unroll - for (int r = 0; r < WS; ++r) { - const int4 v = src[r][k]; - const T* pv = reinterpret_cast(&v); -#pragma unroll - for (int j = 0; j < LANES; ++j) acc[j] += r4d_ar_to_f(pv[j]); - } - int4 o; - T* po = reinterpret_cast(&o); -#pragma unroll - for (int j = 0; j < LANES; ++j) r4d_ar_from_f(acc[j], po[j]); - my_out[k] = o; -#pragma unroll - for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o; // region B - } - r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); - /* The hold ends after the second handshake, not the first: the reduce above is fused with the - * phase-2 push (every reduced word goes to each peer's region B), so at the first handshake the - * link still carries this launch's phase-2 bytes. Here every phase-1 and phase-2 remote store - * has retired behind its flag store and every peer's pushes to this rank have been waited on; - * only the local assemble is left (r4d_ar_seq.h). */ - r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); - // ---- assemble: every peer-owned shard from my region B copies - for (int p = 0; p < NPEERS; ++p) { - const int owner = peers.rank[p]; - const int4* srcB = my_base + ((size_t)parity * WS + owner) * (size_t)slot_stride16 + sh_max; - int4* dst = out4 + (size_t)R4D_TS_OFF(owner); - const int lim = w1 < R4D_TS_LEN(owner) ? w1 : R4D_TS_LEN(owner); - for (int k = w0 + tid; k < lim; k += nt) dst[k] = srcB[k]; + // phase 1: my contribution to each peer-owned shard -> owner's region A + auto push1 = [&](int j) { + const int p0 = w0 + j * pw, p1 = p0 + pw < w1 ? p0 + pw : w1; + for (int p = 0; p < NPEERS; ++p) { + const int owner = peers.rank[p]; + const int4* s1 = in4 + (size_t)R4D_TS_OFF(owner); + int4* dst = pa[p]; + const int lim = p1 < R4D_TS_LEN(owner) ? p1 : R4D_TS_LEN(owner); + for (int k = p0 + tid; k < lim; k += nt) dst[k] = s1[k]; + } + }; + // reduce my shard (fp32, ascending rank, own contribution from the input) fused with the phase-2 + // push: the reduced word goes to my out and every peer's region B in the same pass + auto reduce2 = [&](int j) { + const int p0 = w0 + j * pw, p1 = p0 + pw < w1 ? p0 + pw : w1; + const int my_lim = p1 < R4D_TS_LEN(rank) ? p1 : R4D_TS_LEN(rank); + for (int k = p0 + tid; k < my_lim; k += nt) { + float acc[LANES]; +#pragma unroll + for (int l = 0; l < LANES; ++l) acc[l] = 0.0f; +#pragma unroll + for (int r = 0; r < WS; ++r) { + const int4 v = src[r][k]; + const T* pv = reinterpret_cast(&v); +#pragma unroll + for (int l = 0; l < LANES; ++l) acc[l] += r4d_ar_to_f(pv[l]); + } + int4 o; + T* po = reinterpret_cast(&o); +#pragma unroll + for (int l = 0; l < LANES; ++l) r4d_ar_from_f(acc[l], po[l]); + my_out[k] = o; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o; // region B + } + }; + // every peer-owned shard from my region B copies + auto assemble = [&](int j) { + const int p0 = w0 + j * pw, p1 = p0 + pw < w1 ? p0 + pw : w1; + for (int p = 0; p < NPEERS; ++p) { + const int owner = peers.rank[p]; + const int4* srcB = my_base + ((size_t)parity * WS + owner) * (size_t)slot_stride16 + sh_max; + int4* dst = out4 + (size_t)R4D_TS_OFF(owner); + const int lim = p1 < R4D_TS_LEN(owner) ? p1 : R4D_TS_LEN(owner); + for (int k = p0 + tid; k < lim; k += nt) dst[k] = srcB[k]; + } + }; + + /* Pieces run as a pipeline so both directions of a link carry bytes at once: step j pushes + * piece j+1's phase 1 and piece j's phase 2. One flag word per (block, source) is a monotone + * counter, so a step's single handshake (v0 + 1 + j) also vouches for every earlier one. A rank + * owning little sends nearly all its bytes in phase 1 and receives them in phase 2; without the + * overlap one direction idles in each phase. With one piece the sequence is push, flag 2s-1, + * reduce, flag 2s, assemble. A word is touched by the same thread in all three steps, which keeps + * the in-place form safe. */ + push1(0); + r4d_ar_handshake(peers, my_flags, b, rank, v0, drain, acq, pub); + for (int j = 0; j < pieces; ++j) { + if (j + 1 < pieces) push1(j + 1); + reduce2(j); + if (j > 0) assemble(j - 1); + r4d_ar_handshake(peers, my_flags, b, rank, v0 + 1u + (unsigned int)j, drain, acq, pub); } + /* The hold ends after the last handshake, not the first: the reduce is fused with the phase-2 + * push (every reduced word goes to each peer's region B), so until then the link still carries + * this launch's phase-2 bytes. Here every phase-1 and phase-2 remote store has retired behind + * its flag store and every peer's pushes to this rank have been waited on; only the local + * assemble of the last piece is left (r4d_ar_seq.h). */ + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); + assemble(pieces - 1); #undef R4D_TS_OFF #undef R4D_TS_LEN } @@ -127,7 +159,8 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream_i, long nblocks, long nthreads, long drain, long acq, long pub, - long gate, long gate_ctr, const int* shard_weights) { + long gate, long gate_ctr, const int* shard_weights, + long pieces) { constexpr int NPEERS = WS - 1; if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce: rank " + std::to_string(rank) + @@ -173,6 +206,12 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, int nt = (int)nthreads; if (nt < 64) nt = 64; if (nt > 1024) nt = 1024; + if (pieces < 1 || pieces > R4D_AR_TS_MAX_PIECES) + throw std::runtime_error("all_reduce: pieces " + std::to_string(pieces) + " outside 1.." + + std::to_string((int)R4D_AR_TS_MAX_PIECES)); + // a block's share of the longest shard bounds the pieces worth a handshake each + const long words_a_block = (sh_max + nb - 1) / nb; + const int np = (int)(pieces < words_a_block ? pieces : words_a_block); R4DArWidePeers peers{}; for (int i = 0; i < NPEERS; ++i) { @@ -198,17 +237,23 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, } hipStream_t st = (hipStream_t)stream_i; -#define R4D_AR_TS_LAUNCH(T, LN) \ - r4d_ar_twoshot_wide_exact_kernel<<>>( \ +#define R4D_AR_TS_LAUNCH_P(T, LN, P) \ + r4d_ar_twoshot_wide_exact_kernel<<>>( \ (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ (int4*)out, (unsigned int*)seq_ctrs, sh, (int)slot_stride16, \ (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \ - (unsigned int*)gate_ctr) + (unsigned int*)gate_ctr, np) +#define R4D_AR_TS_LAUNCH(T, LN) \ + do { \ + if (np > 1) R4D_AR_TS_LAUNCH_P(T, LN, true); \ + else R4D_AR_TS_LAUNCH_P(T, LN, false); \ + } while (0) if (dtype == 0) R4D_AR_TS_LAUNCH(__hip_bfloat16, 8); else if (dtype == 1) R4D_AR_TS_LAUNCH(__half, 8); else if (dtype == 2) R4D_AR_TS_LAUNCH(float, 4); else throw std::runtime_error("all_reduce: bad dtype"); #undef R4D_AR_TS_LAUNCH +#undef R4D_AR_TS_LAUNCH_P } void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, @@ -220,7 +265,8 @@ void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pee const long pf[2] = {peer_flags0, peer_flags1}; /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, nullptr); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, nullptr, + 1L); } void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -233,7 +279,7 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr, - nullptr); + nullptr, 1L); } void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -244,7 +290,7 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - const int* shard_weights) { + const int* shard_weights, long pieces) { const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3, peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, @@ -252,5 +298,5 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, - shard_weights); + shard_weights, pieces); } diff --git a/libr4d/r4d_ar_wide.h b/libr4d/r4d_ar_wide.h index 353b5d13..ab0d8e93 100644 --- a/libr4d/r4d_ar_wide.h +++ b/libr4d/r4d_ar_wide.h @@ -1,7 +1,8 @@ #pragma once // r4d_ar_wide.h: shared transport of the wide (ws>2) all-reduce family. Every wide kernel // (one-shot exact, two-shot exact, two-shot ti8) publishes in the 2*seq flag space (the two-shots -// add the 2s-1 half-step), advances seq_ctrs[b] once per AR, and lays scratch out as 2*ws slots of +// add the 2s-1 half-step), advances seq_ctrs[b] once per AR (a two-shot in pieces by its piece +// count, reserving the extra flag values it publishes), and lays scratch out as 2*ws slots of // one stride (parity x source rank). The parity is the launch's, from the parity counters in // r4d_ar_seq.h, so seq_ctrs is 2 * R4D_AR_WIDE_MAX_BLOCKS words. The constants sizing the shared // flag/seq/scratch set are defined only here so they cannot drift apart. diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 0e9e2407..5562421d 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -16179,6 +16179,7 @@ struct ArPattern { const char* dtype = nullptr; /* "bf16" or "fp32" */ std::vector sizes; int out_of_place = -1; /* index into sizes, or -1 */ + std::vector pieces; /* per size: a launch `pieces` parameter, 0 or absent none */ void* inst = nullptr; int rc_init = RAD_E_STATE, rc_launch = RAD_OK; std::vector> out; @@ -16221,7 +16222,9 @@ static void ar_pattern_worker(ArPattern* t) { RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts; a.n_t = oop ? 2 : 1; - a.p = ps.data(); a.n_p = (int)ps.size(); + std::vector lp = ps; + if (k < t->pieces.size() && t->pieces[k] > 0) lp.push_back(PI("pieces", t->pieces[k])); + a.p = lp.data(); a.n_p = (int)lp.size(); a.instance = t->inst; a.rank = t->rank; a.world_size = t->world; @@ -16257,7 +16260,10 @@ struct ScopedEnv { ScopedEnv& operator=(const ScopedEnv&) = delete; }; -struct ArPatternRun { const char* dtype; std::vector sizes; int oop; }; +struct ArPatternRun { + const char* dtype; std::vector sizes; int oop; + std::vector pieces = {}; /* per size, as ArPattern::pieces */ +}; /* One run on a fresh instance per rank, every size checked against the fold. False when init * failed, so the caller stops instead of reporting every later run as failed too. */ @@ -16270,6 +16276,7 @@ static bool ar_pattern_check(const RadKernelInfo* row, const std::vector& d t[(size_t)r].world = world; t[(size_t)r].dtype = run.dtype; t[(size_t)r].sizes = run.sizes; t[(size_t)r].out_of_place = run.oop; + t[(size_t)r].pieces = run.pieces; th.emplace_back(ar_pattern_worker, &t[(size_t)r]); } for (std::thread& x : th) x.join(); @@ -16307,6 +16314,8 @@ static bool ar_pattern_check(const RadKernelInfo* row, const std::vector& d " words, % " + std::to_string(world) + " = " + std::to_string(words % world) + ((int)k == run.oop ? ", out of place" : ", in place") + + (k < run.pieces.size() && run.pieces[k] > 0 + ? ", pieces " + std::to_string(run.pieces[k]) : std::string()) + ") == fp32 ascending-rank fold on every rank, bit for bit"; ok(label.c_str(), bad == 0, std::to_string(bad) + " elements wrong, first at " + std::to_string(first)); @@ -16392,32 +16401,112 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons } } -/* The eight-rank two-shot with per-rank shard weights (RADIANCE_AR8_SHARD_WEIGHTS): shards of - * unequal length, empty ones (weight 0: the rank only pushes, gathers and handshakes), a single - * owner (its two regions outgrow a message, so init must grow the slot), and messages shorter than - * one word a rank, which the even split refuses. The fold is the same whoever owns a word, so the - * oracle is unchanged. */ +/* The eight-rank two-shot with per-rank shard weights (RADIANCE_AR8_SHARD_WEIGHTS) and in + * pieces (RADIANCE_AR8_PIECES): shards of unequal length, empty ones (weight 0: the rank only + * pushes, gathers and handshakes), a single owner (its two regions outgrow a message, so init + * must grow the slot), and messages shorter than one word a rank, which the even split refuses -- + * each at one, two and four pieces. Messages of a few words have fewer words a block than pieces, + * so the launcher's clamp is crossed too. A last run changes the piece count from launch to + * launch on one instance: a launch reserves one handshake step a piece, so a wrong reservation + * leaves a peer waiting on a flag value it already passed or running ahead into a slot still + * being read. These runs drop both size floors to 0 so small messages are weighted and pieced + * too; the last runs check the floors themselves. The fold is the same whoever owns a word, so + * the oracle is unchanged. */ static void ar_wide_weighted(const Plugin& pl, const std::vector& devs, const char* name) { constexpr int W = 8; const RadKernelInfo* row = find(pl, name); if (!row) { ok(name, false, "row absent"); return; } if ((int)devs.size() < W) { skip(name, "needs 8 gfx1201 cards"); return; } - /* bf16: 72 elements are 9 words, 8 are one; 8256 is 1032 words, 4196352 is 524544. */ - const std::vector runs = { + /* bf16: 72 elements are 9 words, 8 are one; 8256 is 1032 words, 4196352 is 524544. Without + * weights the words must divide by eight. */ + const std::vector uneven = { { "bf16", { 4194304, 72, 8, 128, 8256, 4196352, 4194304 }, 1 }, { "fp32", { 36, 1048580 }, 0 }, }; - for (const char* w : { "0,3,1,0,5,1,2,4", "1,0,0,0,0,0,0,0", "4,1,0,4,0,1,4,4" }) { - ScopedEnv env(R4D_AR8_SHARD_WEIGHTS_ENV, w); - for (const ArPatternRun& run : runs) - if (!ar_pattern_check(row, devs, std::string(name) + " weights " + w, W, run)) return; + const std::vector even = { + { "bf16", { 4194304, 128, 8256, 4196352, 4194304 }, 1 }, + { "fp32", { 8256, 1048576 }, 0 }, + }; + { + ScopedEnv floor_w(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, "0"), floor_k(R4D_AR8_PIECES_MIN_ENV, "0"); + for (const char* k : { "1", "2", "4" }) { + ScopedEnv env_k(R4D_AR8_PIECES_ENV, k); + for (const char* w : { "", "0,3,1,0,5,1,2,4", "1,0,0,0,0,0,0,0", "4,1,0,4,0,1,4,4" }) { + ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, *w ? w : nullptr); + const std::string label = + std::string(name) + " pieces " + k + + (*w ? std::string(" weights ") + w : std::string(" even")); + for (const ArPatternRun& run : *w ? uneven : even) + if (!ar_pattern_check(row, devs, label, W, run)) return; + } + } + { + ScopedEnv env_k(R4D_AR8_PIECES_ENV, nullptr); + ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, "4,1,0,4,0,1,4,4"); + const ArPatternRun mixed = { + "bf16", { 4194304, 4194304, 8256, 4196352, 72, 4194304, 4194304 }, 3, + { 1, 4, 2, 8, 16, 3, 1 } }; + ar_pattern_check(row, devs, + std::string(name) + " weights 4,1,0,4,0,1,4,4, pieces per launch", W, + mixed); + } + } + /* The floors at their defaults (R4D_AR8_MIN_ELEMS_DEFAULT elements) with weights, first at the + * size rule's piece counts (131072 runs one piece, 262144 two, 1048576 four, 4194304 eight), + * then at four pieces set. Which side of the weight floor a message fell on shows in what the + * entry accepts: 1048584 elements are 131073 words, over the floor and not divisible by eight, + * so only a weighted split serves it; 72 (9 words) is under it, so the even rule refuses it, + * unless the floor is lowered under it. The piece floor and rule change no bits and no rc; + * the sizes on both sides are checked for bits. */ + ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, "4,1,0,4,0,1,4,4"); + ScopedEnv floor_k(R4D_AR8_PIECES_MIN_ENV, nullptr); + { + ScopedEnv env_k(R4D_AR8_PIECES_ENV, nullptr); + ScopedEnv floor_w(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, nullptr); + const ArPatternRun rule = { + "bf16", { 131072, 262144, 1048576, 4194304, 8256, 4196352 }, 1 }; + if (!ar_pattern_check(row, devs, std::string(name) + " weights 4,1,0,4,0,1,4,4, size rule", + W, rule)) + return; + } + ScopedEnv env_k(R4D_AR8_PIECES_ENV, "4"); + for (const char* fw : { (const char*)nullptr, "64" }) { + ScopedEnv floor_w(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, fw); + const std::string at = std::string(name) + " weights 4,1,0,4,0,1,4,4, pieces 4, floor " + + (fw ? fw : "default"); + if (!fw) { + const ArPatternRun sides = { "bf16", { 1048584, 131072, 524288, 4194304, 8256 }, 0 }; + if (!ar_pattern_check(row, devs, at, W, sides)) return; + } + std::vector t((size_t)W); + std::vector th; + for (int r = 0; r < W; ++r) { + t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; + t[(size_t)r].world = W; t[(size_t)r].dtype = "bf16"; + t[(size_t)r].sizes = { 524288, 72 }; t[(size_t)r].out_of_place = 1; + th.emplace_back(ar_pattern_worker, &t[(size_t)r]); + } + for (std::thread& x : th) x.join(); + const int want = fw ? RAD_OK : RAD_E_SHAPE; + int as_wanted = 0; + for (const ArPattern& x : t) { + if (x.rc_init == RAD_OK && x.rc_launch == want) ++as_wanted; + if (x.inst) row->fini(x.inst); + } + ok((at + (fw ? ": a 9-word message (over the floor) is served" + : ": a 9-word message (under the floor) is refused, RAD_E_SHAPE")).c_str(), + as_wanted == W, + std::to_string(as_wanted) + " of 8 ranks as expected, rc " + + std::to_string(t[0].rc_launch)); } } /* The eight-rank exact all-reduce timed, one thread per card as the engine runs it: both rows - * (one-shot, two-shot) at every message size given, each at the block rule and at fixed block - * counts, out of place on the per-element pattern and checked bit for bit against the fp32 - * ascending-rank fold on every rank. + * (one-shot; two-shot without a `pieces` parameter -- RADIANCE_AR8_PIECES or the size rule -- + * and at 1, 2, 4 and 8 pieces, K1 the unpipelined kernel; under the piece floor every row runs + * K1, and the launcher clamps K to the words a block holds) at every message size given, each at + * the block rule and at fixed block counts, out of place on the per-element pattern and checked + * bit for bit against the fp32 ascending-rank fold on every rank. * * Warm, every rank launches `iters` times back to back after as many warm-up launches, and the * period is the span over iters (the handshake keeps ranks in lockstep after the first). Cold @@ -16447,6 +16536,7 @@ struct Ar8Perf { const char* dtype = "bf16"; std::vector sizes; std::vector rows; + std::vector ks; /* per row: the `pieces` parameter, 0 or -1 none */ std::vector nbs; StBarrier* bar = nullptr; int rc_init = RAD_OK; @@ -16508,6 +16598,7 @@ static void ar8_perf_worker(Ar8Perf* t) { for (int nb : t->nbs) { std::vector ps = ip; if (nb > 0) ps.push_back(PI("nblocks", nb)); + if (t->ks[j] > 0) ps.push_back(PI("pieces", t->ks[j])); RadTensor ts[2] = { T(in, dt, { n }), T(out, dt, { n }) }; RadArgs a; std::memset(&a, 0, sizeof(a)); @@ -16610,10 +16701,16 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty if ((int)devs.size() < W) { std::printf("--perfar8: needs 8 gfx1201 cards, found %zu\n", devs.size()); return; } std::vector rows; + std::vector ks; + /* The two-shot once a piece count; its instances share one key, so they are one buffer set. */ for (const char* name : { "ar_oneshot_8rank_exact", "ar_twoshot_8rank_exact" }) { const RadKernelInfo* r = find(pl, name); if (!r) { std::printf("--perfar8: row %s absent\n", name); return; } - rows.push_back(r); + const bool two = !std::strcmp(name, "ar_twoshot_8rank_exact"); + for (int k : two ? std::vector{ -1, 1, 2, 4, 8 } : std::vector{ 0 }) { + rows.push_back(r); + ks.push_back(k); + } } const std::vector nbs = { 0, 4, 8, 16, 32, 64 }; std::printf("eight-rank exact all-reduce, %s, %d launches a point, %s\n", dtype, iters, @@ -16631,13 +16728,33 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty : wenv && *wenv ? fmt("even (%s=\"%s\" is invalid)", R4D_AR8_SHARD_WEIGHTS_ENV, wenv).c_str() : "even"); + /* The floors as the plugin reads them; under them a message runs even and in one piece, the + * `pieces` parameter included. */ + auto floor_of = [](const char* name) { + long long v = R4D_AR8_MIN_ELEMS_DEFAULT; + const char* e = std::getenv(name); + if (e && *e && !r4d_ar_parse_count(e, R4D_AR8_MIN_ELEMS_MAX, &v)) + v = R4D_AR8_MIN_ELEMS_DEFAULT; + return (int64_t)v; + }; + const int64_t wmin = floor_of(R4D_AR8_SHARD_WEIGHTS_MIN_ENV); + const int64_t kmin = floor_of(R4D_AR8_PIECES_MIN_ENV); + std::printf("two-shot floors: weights from %lld elements (%s), pieces from %lld (%s)\n", + (long long)wmin, R4D_AR8_SHARD_WEIGHTS_MIN_ENV, (long long)kmin, + R4D_AR8_PIECES_MIN_ENV); + long long kenv = 0; + const char* kenv_s = std::getenv(R4D_AR8_PIECES_ENV); + if (!kenv_s || !*kenv_s || !r4d_ar_parse_count(kenv_s, 16, &kenv) || kenv < 1) kenv = 0; + std::printf("two-shot pieces without a parameter (row \"two-shot set\"): %s\n", + kenv ? fmt("%lld (%s)", kenv, R4D_AR8_PIECES_ENV).c_str() + : "from the message size (1 / 2 / 4 / 8 from 0 / 262144 / 1048576 / 4194304)"); StBarrier bar(W); std::vector t((size_t)W); std::vector th; for (int r = 0; r < W; ++r) { Ar8Perf& x = t[(size_t)r]; x.rank = r; x.dev = devs[(size_t)r]; x.iters = iters; x.dtype = dtype; - x.sizes = sizes; x.rows = rows; x.nbs = nbs; x.bar = &bar; + x.sizes = sizes; x.rows = rows; x.ks = ks; x.nbs = nbs; x.bar = &bar; th.emplace_back(ar8_perf_worker, &x); } for (std::thread& x : th) x.join(); @@ -16658,25 +16775,33 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty std::printf(" numel %lld (%.0f KiB, %lld 16-byte words)\n", (long long)n, bytes / 1024.0, (long long)n16); long off[W + 1]; - const int64_t sh_max = r4d_ar_shard_table((long)n16, W, weighted ? wts : nullptr, off); + const bool wtd = weighted && n >= wmin; + const int64_t sh_max = r4d_ar_shard_table((long)n16, W, wtd ? wts : nullptr, off); std::string shards; for (int r = 0; r < W; ++r) shards += fmt(" %ld", off[r + 1] - off[r]); std::printf(" two-shot shard words by rank:%s\n", shards.c_str()); for (size_t j = 0; j < rows.size(); ++j) { - const bool two = j == 1; + const bool two = ks[j] != 0; + /* The piece count the shim runs (before the launcher's words-a-block clamp). */ + const int keff = n < kmin ? 1 : ks[j] > 0 ? ks[j] + : kenv ? (int)kenv : r4d_ar8_auto_pieces(n); + const std::string rname = !two ? std::string("one-shot") + : ks[j] < 0 ? fmt("two-shot set K%d", keff) + : keff != ks[j] ? fmt("two-shot K%d>%d", ks[j], keff) + : fmt("two-shot K%d", ks[j]); const double sent = two ? 2.0 * (W - 1) / W * bytes : (double)(W - 1) * bytes; for (int nb : nbs) { const Ar8Perf& r0 = t[0]; /* The entry's nb_for, to name the rule's count: 1400 words a block, floor 4, * ceiling 16, the two-shot over its longest shard with ceiling 8 at eight ranks. */ - const int64_t basis = two ? (weighted ? sh_max : n16 / W) : n16; + const int64_t basis = two ? (wtd ? sh_max : n16 / W) : n16; const int64_t rule = std::min(std::max(basis / 1400, 4), two ? 8 : 16); const std::string nbs_ = nb ? std::to_string(nb) : fmt("rule %lld", (long long)rule); if (r0.rc[cfg] != RAD_OK) { - std::printf(" %-9s nb %-7s rc=%d (not served)\n", - two ? "two-shot" : "one-shot", nbs_.c_str(), r0.rc[cfg]); + std::printf(" %-16s nb %-7s rc=%d (not served)\n", rname.c_str(), + nbs_.c_str(), r0.rc[cfg]); ++cfg; continue; } @@ -16699,8 +16824,8 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty } us = median(lo) * 1000.0; us_hi = median(hi) * 1000.0; } - std::printf(" %-9s nb %-7s %8.1f us%s %6.2f GB/s payload %6.2f GB/s sent a " - "rank %s\n", two ? "two-shot" : "one-shot", nbs_.c_str(), us, + std::printf(" %-16s nb %-7s %8.1f us%s %6.2f GB/s payload %6.2f GB/s sent a " + "rank %s\n", rname.c_str(), nbs_.c_str(), us, g_cold > 0 ? fmt(" (skew %.1f)", us_hi).c_str() : "", us > 0 ? bytes / (us * 1e3) : 0.0, us > 0 ? sent / (us * 1e3) : 0.0, bad ? fmt("%lld elements differ from the fold", (long long)bad).c_str() From 279214f520329835598a88be0bd9e394b7448fd2 Mon Sep 17 00:00:00 2001 From: Nunze Date: Sun, 18 Oct 2026 18:55:36 +0200 Subject: [PATCH 012/152] libr4d: the eight-rank two-shot's shard weights from the PCIe links by default Weights from a variable describe one board on one day. Unset or "auto", RADIANCE_AR8_SHARD_WEIGHTS now reads them from the links: each rank takes its card's bus id from the runtime (hipDeviceGetPCIBusId), walks /sys/bus/pci/devices from the root port down to the card as core/diag/sysinfo.cpp's read_card does, and keeps the slowest hop's current speed x width x line code (8b/10b under 8 GT/s, 128b/130b from there) / 8. The R9700 sits behind an on-card switch whose endpoint reports Gen5 x16 in any slot, so a degraded slot shows only at the root port. The weight is round(4 x (rate / fastest)^2): x16 4, half the rate 1, a quarter 0. On the board of the previous commits that is the measured best, 4,1,0,4,0,1,4,4, and after both Gen4 links retrained at Gen5 x8 it is 4,1,1,4,1,1,4,4, where the 16 MiB two-shot takes 1360 us. "off" keeps the shards even and eight integers set them, as before. The ranks publish their links in the rendezvous (ar8_settle) and, after one barrier, derive the same table from the same eight entries before anything is sized; settings that differ between ranks fail init on every rank. Equal weights run the unweighted kernel, and a rank whose path says nothing (no /sys/bus/pci in a container) leaves the shards even, with a warning naming it. Startup logs one line, "[r4d] eight-rank two-shot shard weights from the slowest PCIe hop of each card: r0 32.0 GT/s x16 63.0 GB/s w4, r1 32.0 GT/s x8 31.5 GB/s w1, ...". The links are read once, at init: a link that falls back while the server runs changes the weights at the next start. r4d_ar_links_test builds that board's sysfs under a temporary root (root port, on-card switch, endpoint) and checks the bottleneck hop, the weights before and after the repair, equal links, the line code and a path that says nothing; it needs only libr4d's include path. r4d_selftest runs auto and off at the default floors, for bits only since what auto derives depends on the box, and --perfar8 derives the weights the same way and names each rank's link. 206 of 206 on the cards. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_ar_entry.hip | 165 ++++++++++++++++++++++++++---------- libr4d/r4d_ar_links.h | 85 +++++++++++++++++++ libr4d/r4d_selftest.cpp | 64 +++++++++++--- tests/CMakeLists.txt | 3 +- tests/r4d_ar_links_test.cpp | 165 ++++++++++++++++++++++++++++++++++++ 5 files changed, 424 insertions(+), 58 deletions(-) create mode 100644 libr4d/r4d_ar_links.h create mode 100644 tests/r4d_ar_links_test.cpp diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index b0e2c9a9..999ae62b 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -21,6 +21,7 @@ #include "r4d_args.h" #include "r4d.h" #include "r4d_ar_shards.h" +#include "r4d_ar_links.h" #include #include @@ -71,10 +72,15 @@ struct Rendezvous { long flags [R4D_MAX_RANKS] = { 0 }; long seq [R4D_MAX_RANKS] = { 0 }; int dev [R4D_MAX_RANKS] = { 0 }; - int shard_w[R4D_MAX_RANKS][R4D_MAX_RANKS] = { { 0 } }; - int pieces [R4D_MAX_RANKS] = { 0 }; - long long weights_min[R4D_MAX_RANKS] = { 0 }; - long long pieces_min [R4D_MAX_RANKS] = { 0 }; + /* What each rank read for the eight-rank two-shot: settings that must agree, and its own + * card's link, which the weights are derived from. */ + struct Ar8Seen { + int mode = 0; + int w[R4D_MAX_RANKS] = { 0 }; + int pieces = 0; + long long weights_min = 0, pieces_min = 0; + R4DArLink link; + } ar8[R4D_MAX_RANKS]; int failed = 0; }; @@ -145,26 +151,35 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) { long align16(long v) { return (v + 15) & ~15L; } /* RADIANCE_AR8_SHARD_WEIGHTS, read at every eight-rank build so a process can change it between - * instances; each rank reads it and build() checks that they agree. */ -bool ar8_shard_weights(int* w) { + * instances: unset or "auto" derives the weights from the links, "off" keeps the shards even, + * eight integers set them. Anything else is "off", with one warning. */ +enum { AR8_EVEN = 0, AR8_SET = 1, AR8_AUTO = 2 }; +int ar8_weights_mode(int* w) { const char* e = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); - if (!e || !*e) return false; - static std::once_flag said_bad, said_on; - int got[8]; - if (!r4d_ar_shard_weights_parse(e, 8, got)) { - std::call_once(said_bad, [e] { - std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs eight non-negative integers, " - "comma-separated, sum > 0); eight-rank two-shot shards stay even\n", - R4D_AR8_SHARD_WEIGHTS_ENV, e); - }); - return false; - } - std::memcpy(w, got, sizeof(got)); - std::call_once(said_on, [w] { - std::fprintf(stderr, "[r4d] eight-rank two-shot shards weighted %d,%d,%d,%d,%d,%d,%d,%d\n", - w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + if (!e || !*e || !std::strcmp(e, "auto")) return AR8_AUTO; + if (!std::strcmp(e, "off")) return AR8_EVEN; + if (r4d_ar_shard_weights_parse(e, 8, w)) return AR8_SET; + static std::once_flag said; + std::call_once(said, [e] { + std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs auto, off or eight non-negative " + "integers, comma-separated, sum > 0); eight-rank two-shot shards stay even\n", + R4D_AR8_SHARD_WEIGHTS_ENV, e); }); - return true; + return AR8_EVEN; +} + +/* This rank's card's slowest PCIe hop, from sysfs by the runtime's bus id. */ +bool ar8_own_link(R4DArLink* l) { + int dev = 0; + char bus[64] = { 0 }; + if (hipGetDevice(&dev) != hipSuccess || + hipDeviceGetPCIBusId(bus, (int)sizeof bus, dev) != hipSuccess) + return false; + unsigned dom = 0, b = 0, d = 0, f = 0; + if (std::sscanf(bus, "%x:%x:%x.%x", &dom, &b, &d, &f) != 4) return false; + char bdf[32]; + std::snprintf(bdf, sizeof bdf, "%04x:%02x:%02x.%x", dom, b, d, f); + return r4d_ar_link_bottleneck("", bdf, l); } /* RADIANCE_AR8_PIECES and the two size floors, read like the weights. */ @@ -210,6 +225,84 @@ long long ar8_pieces_for(const ArInst* in, long numel, long long asked) { return asked > 0 ? asked : r4d_ar8_auto_pieces(numel); } +/* The eight-rank two-shot's settings, agreed before anything is sized: each rank publishes what + * it read and its own card's link, and after one barrier every rank derives the same weights from + * the same eight entries. Settings that differ between ranks would cut the message at different + * words or take different handshake steps; all ranks compare the same entries, so all refuse + * together. */ +int ar8_settle(ArInst* in, int rank, int world) { + static std::once_flag said_w, said_p, said_links, said_unknown, said_set; + Rendezvous::Ar8Seen me; + me.mode = ar8_weights_mode(me.w); + me.pieces = ar8_pieces(); + me.weights_min = ar8_min_elems(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, &said_w); + me.pieces_min = ar8_min_elems(R4D_AR8_PIECES_MIN_ENV, &said_p); + if (me.mode == AR8_AUTO && !ar8_own_link(&me.link)) me.link = R4DArLink(); + { + std::lock_guard lk(g_rv.m); + g_rv.ar8[rank] = me; + } + const int rc = rv_barrier(world); + if (rc != RAD_OK) return rc; + + const Rendezvous::Ar8Seen* all = g_rv.ar8; + for (int r = 0; r < world; ++r) + if (all[r].mode != me.mode || std::memcmp(all[r].w, me.w, sizeof(me.w)) || + all[r].pieces != me.pieces || all[r].weights_min != me.weights_min || + all[r].pieces_min != me.pieces_min) { + std::fprintf(stderr, "[r4d] ranks %d and %d read different eight-rank two-shot " + "settings (%s, %s and their _MIN_ELEMS)\n", rank, r, + R4D_AR8_SHARD_WEIGHTS_ENV, R4D_AR8_PIECES_ENV); + return RAD_E_STATE; + } + in->pieces = me.pieces; + in->weights_min = me.weights_min; + in->pieces_min = me.pieces_min; + + int w[R4D_MAX_RANKS] = { 0 }; + if (me.mode == AR8_SET) { + std::memcpy(w, me.w, sizeof(w)); + std::call_once(said_set, [&w] { + std::fprintf(stderr, "[r4d] eight-rank two-shot shards weighted " + "%d,%d,%d,%d,%d,%d,%d,%d (%s)\n", w[0], w[1], w[2], w[3], w[4], w[5], + w[6], w[7], R4D_AR8_SHARD_WEIGHTS_ENV); + }); + } else if (me.mode == AR8_AUTO) { + double gbs[R4D_MAX_RANKS] = { 0 }; + for (int r = 0; r < world; ++r) gbs[r] = r4d_ar_link_gbs(all[r].link); + if (!r4d_ar_weights_from_rates(gbs, world, w)) { + std::call_once(said_unknown, [all, world] { + std::string who; + for (int r = 0; r < world; ++r) + if (r4d_ar_link_gbs(all[r].link) <= 0.0) who += " " + std::to_string(r); + std::fprintf(stderr, "[r4d] eight-rank two-shot: no PCIe link speed in sysfs for " + "rank%s; shards stay even\n", who.c_str()); + }); + return RAD_OK; + } + std::call_once(said_links, [all, world, &w] { + std::string l; + for (int r = 0; r < world; ++r) { + char one[96]; + std::snprintf(one, sizeof one, "%s r%d %.1f GT/s x%d %.1f GB/s w%d", + r ? "," : "", r, all[r].link.gts, all[r].link.width, + r4d_ar_link_gbs(all[r].link), w[r]); + l += one; + } + std::fprintf(stderr, "[r4d] eight-rank two-shot shard weights from the slowest PCIe " + "hop of each card:%s\n", l.c_str()); + }); + bool same = true; + for (int r = 1; r < world; ++r) same = same && w[r] == w[0]; + if (same) return RAD_OK; /* equal links: the even split, on the unweighted path */ + } else { + return RAD_OK; + } + in->shard_weighted = 1; + std::memcpy(in->shard_w, w, sizeof(in->shard_w)); + return RAD_OK; +} + /* Sequence counter allocation in words: 2 * nbw (r4d_ar_seq.h), then r4d_ar_link_landed's block * counter, padded to a cache line. */ long kSeqWords(long nbw) { return 2L * nbw + 32; } @@ -239,13 +332,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, in->slot_bytes = align16((long)max_numel * in->esize); in->slot16 = in->slot_bytes / 16; if (world == 8) { - static std::once_flag said_w, said_p; - in->pieces = ar8_pieces(); - in->weights_min = ar8_min_elems(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, &said_w); - in->pieces_min = ar8_min_elems(R4D_AR8_PIECES_MIN_ENV, &said_p); + const int rc8 = ar8_settle(in, rank, world); + if (rc8 != RAD_OK) return rc8; } - if (world == 8 && ar8_shard_weights(in->shard_w)) { - in->shard_weighted = 1; + if (in->shard_weighted) { const long need16 = 2 * r4d_ar_shard_max_bound((long)max_numel * in->esize / 16, 8, in->shard_w); /* Sized only if some message this instance carries is weighted. */ @@ -324,29 +414,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, g_rv.flags[rank] = fl; g_rv.seq[rank] = sq; g_rv.dev[rank] = dev; - for (int i = 0; i < R4D_MAX_RANKS; ++i) - g_rv.shard_w[rank][i] = in->shard_weighted ? in->shard_w[i] : -1; - g_rv.pieces[rank] = in->pieces; - g_rv.weights_min[rank] = in->weights_min; - g_rv.pieces_min[rank] = in->pieces_min; } int rc = rv_barrier(world); if (rc != RAD_OK) return rc; - /* Every rank must cut the message at the same words, or an owner reduces words its peers - * pushed elsewhere, and take the same handshake steps, or the flags drift apart. All ranks - * compare the same values, so all refuse together. */ - for (int r = 0; r < world; ++r) - if (std::memcmp(g_rv.shard_w[r], g_rv.shard_w[rank], sizeof(g_rv.shard_w[rank])) || - g_rv.pieces[r] != g_rv.pieces[rank] || - g_rv.weights_min[r] != g_rv.weights_min[rank] || - g_rv.pieces_min[r] != g_rv.pieces_min[rank]) { - std::fprintf(stderr, "[r4d] ranks %d and %d read different eight-rank two-shot " - "settings (%s, %s and their _MIN_ELEMS)\n", rank, r, - R4D_AR8_SHARD_WEIGHTS_ENV, R4D_AR8_PIECES_ENV); - return RAD_E_STATE; - } - /* Peer access is per context, so each rank enables its own, after the publish barrier where * peer device ordinals are known. A host can expose more HIP devices than ranks (e.g. an * integrated GPU), so the ordinal comes from the peer rather than the rank. */ diff --git a/libr4d/r4d_ar_links.h b/libr4d/r4d_ar_links.h new file mode 100644 index 00000000..32ccfe35 --- /dev/null +++ b/libr4d/r4d_ar_links.h @@ -0,0 +1,85 @@ +#pragma once +// r4d_ar_links.h: the eight-rank two-shot's shard weights from the PCIe links (host only). +// +// A card's link to the CPU is as fast as its slowest hop. The R9700 sits behind an on-card switch +// whose endpoint reports full speed in any slot, so a degraded slot shows only at the root port: +// every hop from the root port down is read, as core/diag/sysinfo.cpp (read_card) reads it, from +// the kernel's sysfs under `root` ("" on a real machine, a directory tree in tests). Nothing that +// a file does not say is guessed; a card with no readable hop has no rate. +// +// Weight from the rate relative to the fastest card: w = round(4 * (rate / max)^2), so x16 4, +// half the rate 1, a quarter 0. A rank's bytes per direction grow with its shard, so the weights +// fall faster than the rate; the measured best on four Gen5 x16, two Gen5 x8 and two Gen4 x8 was +// 4,1,0,4,0,1,4,4 (docs/GUIDE.md, 4.7). +#include +#include +#include +#include +#include +#include + +struct R4DArLink { + std::string bdf; // the slowest hop, "" when none was readable + double gts = 0.0; // its current speed in GT/s + int width = 0; // its current width in lanes +}; + +// Payload GB/s of one direction: 8b/10b below 8 GT/s, 128b/130b from Gen3 on. +inline double r4d_ar_link_gbs(const R4DArLink& l) { + if (l.gts <= 0.0 || l.width <= 0) return 0.0; + const double enc = l.gts < 8.0 ? 8.0 / 10.0 : 128.0 / 130.0; + return l.gts * l.width * enc / 8.0; +} + +inline std::string r4d_ar_sysfs_line(const std::string& path) { + std::ifstream f(path); + std::string s; + if (!f || !std::getline(f, s)) return std::string(); + return s; +} + +inline bool r4d_ar_is_bdf(const std::string& s) { + unsigned d, b, dv, f; + char tail; + return s.size() == 12 && std::sscanf(s.c_str(), "%4x:%2x:%2x.%1x%c", &d, &b, &dv, &f, &tail) == 4; +} + +// The slowest hop between the root port and the card `bdf` ("0000:03:00.0", lower case). False +// when no hop on the path says its current speed and width. +inline bool r4d_ar_link_bottleneck(const std::string& root, const std::string& bdf, + R4DArLink* out) { + namespace fs = std::filesystem; + const std::string devs = root + "/sys/bus/pci/devices/"; + std::error_code ec; + const fs::path real = fs::canonical(devs + bdf, ec); + if (ec) return false; + R4DArLink best; + for (const fs::path& part : real) { + const std::string p = part.string(); + if (!r4d_ar_is_bdf(p)) continue; + R4DArLink h; + h.bdf = p; + h.gts = std::strtod(r4d_ar_sysfs_line(devs + p + "/current_link_speed").c_str(), nullptr); + h.width = std::atoi(r4d_ar_sysfs_line(devs + p + "/current_link_width").c_str()); + const double r = r4d_ar_link_gbs(h); + if (r <= 0.0) continue; + if (best.bdf.empty() || r < r4d_ar_link_gbs(best)) best = h; + } + if (best.bdf.empty()) return false; + *out = best; + return true; +} + +// Weights from every rank's rate (GB/s). False when a rank's rate is unknown. +inline bool r4d_ar_weights_from_rates(const double* gbs, int ws, int* w) { + double top = 0.0; + for (int r = 0; r < ws; ++r) { + if (!(gbs[r] > 0.0)) return false; + if (gbs[r] > top) top = gbs[r]; + } + for (int r = 0; r < ws; ++r) { + const double q = gbs[r] / top; + w[r] = (int)std::lround(4.0 * q * q); + } + return true; +} diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 5562421d..36c7e482 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -36,6 +36,7 @@ #include "rad_plugin.h" #include "r4d_args.h" #include "r4d_ar_shards.h" +#include "r4d_ar_links.h" #include "r4d_hc_fp8.h" #include "r4d_fp8_frag.h" #include "r4d_fp8_lm.h" @@ -16375,7 +16376,7 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons * weights whatever the environment. 40 bf16 elements are 5 words (5 % 4 != 0), 72 are 9 * (9 % 8 != 0). */ if (world >= 4 && std::strstr(name, "twoshot")) { - ScopedEnv even(R4D_AR8_SHARD_WEIGHTS_ENV, nullptr); + ScopedEnv even(R4D_AR8_SHARD_WEIGHTS_ENV, "off"); const int64_t odd = world == 4 ? 40 : 72; const std::string w = std::to_string(world); std::vector t((size_t)world); @@ -16432,7 +16433,7 @@ static void ar_wide_weighted(const Plugin& pl, const std::vector& devs, con for (const char* k : { "1", "2", "4" }) { ScopedEnv env_k(R4D_AR8_PIECES_ENV, k); for (const char* w : { "", "0,3,1,0,5,1,2,4", "1,0,0,0,0,0,0,0", "4,1,0,4,0,1,4,4" }) { - ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, *w ? w : nullptr); + ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, *w ? w : "off"); const std::string label = std::string(name) + " pieces " + k + (*w ? std::string(" weights ") + w : std::string(" even")); @@ -16451,6 +16452,17 @@ static void ar_wide_weighted(const Plugin& pl, const std::vector& devs, con mixed); } } + /* The weights from this box's links ("auto", the default) and switched off, at the default + * floors and piece rule: what the engine runs without settings. Bits only, since what auto + * derives depends on the box (the startup line names it). */ + for (const char* mode : { "auto", "off" }) { + ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, mode); + ScopedEnv env_k(R4D_AR8_PIECES_ENV, nullptr); + ScopedEnv floor_w(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, nullptr); + ScopedEnv floor_k(R4D_AR8_PIECES_MIN_ENV, nullptr); + const ArPatternRun run = { "bf16", { 4194304, 524288, 8256, 8388608, 196608 }, 1 }; + if (!ar_pattern_check(row, devs, std::string(name) + " weights " + mode, W, run)) return; + } /* The floors at their defaults (R4D_AR8_MIN_ELEMS_DEFAULT elements) with weights, first at the * size rule's piece counts (131072 runs one piece, 262144 two, 1048576 four, 4194304 eight), * then at four pieces set. Which side of the weight floor a message fell on shows in what the @@ -16672,6 +16684,39 @@ static void ar8_perf_worker(Ar8Perf* t) { for (void* p : { in, out, csrc, cdst }) if (p) st_free(p); } +/* The eight-rank two-shot's weights as the plugin derives them at init (r4d_ar_entry.hip, + * ar8_settle): RADIANCE_AR8_SHARD_WEIGHTS unset or "auto" from each rank's slowest PCIe hop, "off" + * or anything invalid even, eight integers as given; equal derived weights are the even split. + * `how` names the source and, for "auto", every rank's link. */ +static bool ar8_weights_as_plugin(const std::vector& devs, int* w, std::string* how) { + const char* e = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); + if (e && *e && std::strcmp(e, "auto")) { + if (!std::strcmp(e, "off")) { *how = " (off)"; return false; } + if (r4d_ar_shard_weights_parse(e, 8, w)) { *how = " (set)"; return true; } + *how = fmt(" (%s=\"%s\" is invalid)", R4D_AR8_SHARD_WEIGHTS_ENV, e); + return false; + } + double gbs[8] = { 0 }; + std::string links; + for (int r = 0; r < 8 && r < (int)devs.size(); ++r) { + char bus[64] = { 0 }; + unsigned dom = 0, b = 0, d = 0, f = 0; + R4DArLink l; + if (hipDeviceGetPCIBusId(bus, (int)sizeof bus, devs[(size_t)r]) == hipSuccess && + std::sscanf(bus, "%x:%x:%x.%x", &dom, &b, &d, &f) == 4) + r4d_ar_link_bottleneck("", fmt("%04x:%02x:%02x.%x", dom, b, d, f), &l); + gbs[r] = r4d_ar_link_gbs(l); + links += fmt("%s r%d %.1f GT/s x%d", r ? "," : "", r, l.gts, l.width); + } + if (!r4d_ar_weights_from_rates(gbs, 8, w)) { + *how = " (auto: a link is unreadable;" + links + ")"; + return false; + } + *how = " (auto:" + links + ")"; + for (int r = 1; r < 8; ++r) if (w[r] != w[0]) return true; + return false; +} + static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dtype) { constexpr int W = 8; if (iters <= 0) iters = 200; @@ -16717,17 +16762,16 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty g_cold > 0 ? fmt("cold (%lld MiB read before each; last arriver / with skew, " "medians)", (long long)(g_cold >> 20)).c_str() : "warm (back to back, period over the span, slowest rank)"); - /* The plugin reads the same variable through the same parser at init, so this is the table - * the two-shot runs. */ + /* The plugin reads the same variable and the same sysfs files through the same functions at + * init, so this is the table the two-shot runs. */ int wts[W]; - const char* wenv = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); - const bool weighted = wenv && *wenv && r4d_ar_shard_weights_parse(wenv, W, wts); - std::printf("two-shot shard weights: %s\n", + std::string how; + const bool weighted = ar8_weights_as_plugin(devs, wts, &how); + std::printf("two-shot shard weights: %s%s\n", weighted ? fmt("%d,%d,%d,%d,%d,%d,%d,%d", wts[0], wts[1], wts[2], wts[3], wts[4], wts[5], wts[6], wts[7]).c_str() - : wenv && *wenv ? fmt("even (%s=\"%s\" is invalid)", R4D_AR8_SHARD_WEIGHTS_ENV, - wenv).c_str() - : "even"); + : "even", + how.c_str()); /* The floors as the plugin reads them; under them a message runs even and in one piece, the * `pieces` parameter included. */ auto floor_of = [](const char* name) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 82e007d7..51e97566 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -45,7 +45,8 @@ set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test) # relayout_parity_test checks each kernel library's relayout of libquant's planes against a # recorded hash of the stored bytes. libr4d's layout sources are host-only, so they are compiled in, # with -ffp-contract=off as libr4d uses, so scale conversions round identically. -set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test) +# r4d_ar_links_test checks libr4d's header-only link reader, so it needs only the include path. +set(RAD_TESTS_WITH_R4D_HOST relayout_parity_test r4d_ar_links_test) # Chat templates (copied from the model repositories) and media samples, passed by absolute path so # test binaries can run from anywhere. diff --git a/tests/r4d_ar_links_test.cpp b/tests/r4d_ar_links_test.cpp new file mode 100644 index 00000000..a91e84f6 --- /dev/null +++ b/tests/r4d_ar_links_test.cpp @@ -0,0 +1,165 @@ +/* r4d_ar_links_test.cpp -- the eight-rank two-shot's shard weights from the PCIe links + * (libr4d/r4d_ar_links.h). + * + * Each case builds sysfs under a root directory, laid out like the eight-R9700 box the weights + * were measured on: each card behind its on-card switch (upstream and downstream port at Gen5 + * x16, endpoint at Gen5 x16) under a root port whose link is the real slot. The slot shows only + * at the root port, so a reader that stops at the card's own link sees eight equal cards. + * + * Bottleneck the slowest hop of a card's path, root port included + * Weights round(4 * (rate / max)^2): two Gen4 x8 links give 4,1,0,4,0,1,4,4, the + * repaired ones 4 and 1; a card whose path says nothing leaves the weights unknown + */ +#include "rad_test.h" + +#include "r4d_ar_links.h" + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +struct Root { + std::string dir; + Root() { + std::string tmpl = radtest::tmp_path("root.XXXXXX"); + dir = mkdtemp(tmpl.data()) ? tmpl : ""; + } + void put(const std::string& rel, const std::string& text) const { + const fs::path p = fs::path(dir) / rel.substr(1); + fs::create_directories(p.parent_path()); + std::ofstream(p) << text; + } + void link(const std::string& rel, const std::string& target) const { + const fs::path p = fs::path(dir) / rel.substr(1); + fs::create_directories(p.parent_path()); + fs::create_symlink(target, p); + } +}; + +/* A device under /sys/devices at `path` with its /sys/bus/pci/devices link; `speed` "" writes no + * link files, as some bridges inside a switch do. */ +void pci(const Root& r, const std::string& path, const std::string& speed, int width) { + const std::string bdf = path.substr(path.rfind('/') + 1); + const std::string d = "/sys/devices/" + path; + r.put(d + "/class", "0x060400\n"); + if (!speed.empty()) { + r.put(d + "/current_link_speed", speed + "\n"); + r.put(d + "/current_link_width", std::to_string(width) + "\n"); + } + r.link("/sys/bus/pci/devices/" + bdf, "../../../devices/" + path); +} + +std::string bdf_on(int bus) { + char b[16]; + std::snprintf(b, sizeof b, "0000:%02x:00.0", bus); + return b; +} + +/* Card `i` behind root port 0000:00:0i.1 running `speed` x`width`; returns the card's BDF. */ +std::string card(const Root& r, int i, const std::string& speed, int width) { + const std::string rp = "pci0000:00/0000:00:0" + std::to_string(i) + ".1"; + const std::string up = rp + "/" + bdf_on(0x10 + 3 * i); + const std::string down = up + "/" + bdf_on(0x11 + 3 * i); + const std::string ep = down + "/" + bdf_on(0x12 + 3 * i); + pci(r, rp, speed, width); + pci(r, up, "32.0 GT/s PCIe", 16); + pci(r, down, "32.0 GT/s PCIe", 16); + pci(r, ep, "32.0 GT/s PCIe", 16); + return bdf_on(0x12 + 3 * i); +} + +struct Slot { const char* speed; int width; }; + +/* The weights the eight cards give, or "unknown". */ +std::string weights(const Root& r, const Slot* slots) { + std::string bdf[8]; + for (int i = 0; i < 8; ++i) bdf[i] = card(r, i, slots[i].speed, slots[i].width); + double gbs[8] = { 0 }; + for (int i = 0; i < 8; ++i) { + R4DArLink l; + if (r4d_ar_link_bottleneck(r.dir, bdf[i], &l)) gbs[i] = r4d_ar_link_gbs(l); + } + int w[8]; + if (!r4d_ar_weights_from_rates(gbs, 8, w)) return "unknown"; + std::string s; + for (int i = 0; i < 8; ++i) s += (i ? "," : "") + std::to_string(w[i]); + return s; +} + +const char* G5 = "32.0 GT/s PCIe"; +const char* G4 = "16.0 GT/s PCIe"; + +} // namespace + +TEST(the_slowest_hop_is_the_root_port_behind_an_on_card_switch) { + Root r; + const std::string bdf = card(r, 2, G4, 8); + R4DArLink l; + REQUIRE(r4d_ar_link_bottleneck(r.dir, bdf, &l)); + CHECK_EQ(l.bdf, std::string("0000:00:02.1")); + CHECK(l.gts == 16.0); + CHECK_EQ(l.width, 8); + CHECK(std::fabs(r4d_ar_link_gbs(l) - 16.0 * 8 * 128.0 / 130.0 / 8.0) < 1e-9); +} + +TEST(two_degraded_links_give_the_measured_weights) { + Root r; + const Slot s[8] = { { G5, 16 }, { G5, 8 }, { G4, 8 }, { G5, 16 }, + { G4, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } }; + CHECK_EQ(weights(r, s), std::string("4,1,0,4,0,1,4,4")); +} + +TEST(repaired_links_give_four_and_one) { + Root r; + const Slot s[8] = { { G5, 16 }, { G5, 8 }, { G5, 16 }, { G5, 16 }, + { G5, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } }; + CHECK_EQ(weights(r, s), std::string("4,1,4,4,1,1,4,4")); +} + +TEST(equal_links_give_equal_weights) { + Root r; + Slot s[8]; + for (Slot& x : s) x = { G5, 16 }; + CHECK_EQ(weights(r, s), std::string("4,4,4,4,4,4,4,4")); +} + +/* A Gen2 link moves 8 of every 10 bits, Gen3 on 128 of 130: 5.0 GT/s x16 is 8.0 GB/s, an eighth + * of Gen5 x16 at 63.0, so its weight rounds to 0. */ +TEST(the_line_code_is_counted) { + R4DArLink l; + l.gts = 5.0; l.width = 16; + CHECK(std::fabs(r4d_ar_link_gbs(l) - 8.0) < 1e-9); + l.gts = 8.0; l.width = 16; + CHECK(std::fabs(r4d_ar_link_gbs(l) - 8.0 * 16 * 128.0 / 130.0 / 8.0) < 1e-9); +} + +/* A hop without link files (a bridge inside a switch) is skipped; a path where no hop says + * anything has no rate, and one such card leaves all weights unknown, not guessed. */ +TEST(a_silent_path_has_no_rate_and_no_weights) { + Root r; + const Slot s[8] = { { G5, 16 }, { G5, 8 }, { G4, 8 }, { G5, 16 }, + { G4, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } }; + std::string bdf[8]; + for (int i = 0; i < 8; ++i) bdf[i] = card(r, i, s[i].speed, s[i].width); + pci(r, "pci0000:00/0000:00:09.1", "", 0); + pci(r, "pci0000:00/0000:00:09.1/0000:40:00.0", "", 0); + R4DArLink l; + CHECK(!r4d_ar_link_bottleneck(r.dir, "0000:40:00.0", &l)); + CHECK(!r4d_ar_link_bottleneck(r.dir, "0000:41:00.0", &l)); + double gbs[8] = { 0 }; + for (int i = 0; i < 7; ++i) { + R4DArLink x; + if (r4d_ar_link_bottleneck(r.dir, bdf[i], &x)) gbs[i] = r4d_ar_link_gbs(x); + } + int w[8]; + CHECK(!r4d_ar_weights_from_rates(gbs, 8, w)); +} + +RAD_TEST_MAIN() From 2c0dd8535e4e1252dc183c7d54d340d2080eb72b Mon Sep 17 00:00:00 2001 From: Nunze Date: Sun, 18 Oct 2026 18:55:37 +0200 Subject: [PATCH 013/152] sample: at eight ranks a rank keeps the candidates the merge can hold Over a split vocabulary every rank's candidates are gathered and merged in one workgroup (sample_merge_topk), and libr4d's row holds world_size * n_cand <= 4096 pairs in LDS. The engine declared the default 1024 a rank, 8192 pairs at eight ranks, and the first step stopped on a shape the merge does not serve. Declare now narrows the width to 4096 / world_size, 512 at eight ranks, and says so in one line; a request whose top_k is wider is refused at admission, as a top_k over the width already was. Two and four ranks keep 1024. sample_test: at two, four and eight ranks declare succeeds, top_k at the width is admitted and one more is refused, naming the width. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- core/sample/host_ref.h | 4 ++++ core/sample/sampler.cpp | 8 ++++++++ tests/sample_test.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/core/sample/host_ref.h b/core/sample/host_ref.h index c7155d16..787309a5 100644 --- a/core/sample/host_ref.h +++ b/core/sample/host_ref.h @@ -197,6 +197,10 @@ int32_t host_argmax(const float* logits, int64_t n_vocab); /* The candidate width every stage after top-k works in, SamplerConfig::max_candidates' default. */ constexpr int64_t kSampleCandidates = 1024; +/* Under a split vocabulary the merge (sample_merge_topk) holds world_size * n_cand gathered pairs + * in one workgroup's LDS; libr4d's row serves 4096 at most, so the per-rank width shrinks with + * the world (512 at eight ranks). */ +constexpr int64_t kSampleMergeCandidates = 4096; enum class ChainOrder { Radiance = 0, /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */ diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index 68b58a2e..7a16de8b 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -145,6 +145,14 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { const int64_t rows = rows_for(cfg_); const int64_t nv = cfg_.n_vocab_local; + if (vocab_parallel() && cfg_.max_candidates * cfg_.world_size > kSampleMergeCandidates) { + const int64_t cap = kSampleMergeCandidates / cfg_.world_size; + RAD_INFO("sampler: candidate width %lld a rank -> %lld: the merge of %d ranks' candidate " + "sets holds %lld pairs at most (top_k above %lld is refused per request)", + (long long)cfg_.max_candidates, (long long)cap, cfg_.world_size, + (long long)kSampleMergeCandidates, (long long)cap); + cfg_.max_candidates = cap; + } const int64_t ncand = cfg_.max_candidates; /* ---------------------------------------------------------- buffers */ diff --git a/tests/sample_test.cpp b/tests/sample_test.cpp index 3043f33d..cc62d6dd 100644 --- a/tests/sample_test.cpp +++ b/tests/sample_test.cpp @@ -2100,6 +2100,46 @@ TEST(a_greedy_row_over_a_split_vocabulary_is_staged_as_a_chain_row) { CHECK_EQ(p[1].top_k, 1); } +/* Over a split vocabulary the merge holds every rank's candidates in one workgroup, 4096 pairs at + * most (kSampleMergeCandidates, libr4d's sample_merge_topk). At two and four ranks the default + * width of 1024 a rank fits; at eight it would ask 8192 and the step's merge would find no kernel, + * so declare narrows it to 512 and admission refuses a wider top_k instead. */ +TEST(the_candidate_width_over_a_split_vocabulary_is_what_the_merge_holds) { + Registry reg; + (void)reg.load_plugin(home() + "/kernels/libref.so", 0); + for (int world : { 2, 4, 8 }) { + RadModelMeta meta{}; + meta.arch_id = "sampler_split"; + meta.name = "sampler_split"; + RadBuildCtx bc{}; + bc.world_size = world; + bc.max_seqs = 2; + bc.max_tok = 2; + bc.max_ctx = 64; + bc.scope = ""; + Builder b(reg, meta, bc); + Sampler s; + SamplerConfig cfg; + cfg.n_vocab = 2048 * (int64_t)world; + cfg.n_vocab_local = 2048; + cfg.max_seqs = 2; + cfg.world_size = world; + cfg.rank = world - 1; + cfg.vocab_off = 2048 * (int64_t)(world - 1); + cfg.max_hist = 16; + CHECK_OK(s.declare(&b, cfg)); + + const int64_t width = world == 8 ? 512 : kSampleCandidates; + SamplingParams sp = greedy_params(); + std::string why; + sp.top_k = (int)width; + CHECK_OK(s.check_request(sp, &why)); + sp.top_k = (int)width + 1; + CHECK_EQ(s.check_request(sp, &why), RAD_E_INVAL); + CHECK(why.find("candidate width of " + std::to_string(width)) != std::string::npos); + } +} + /* Triggers are resolved at admission, with special tokens recognised: a one-token word becomes an * id, a longer word is scanned for as bytes, a token trigger that is not one token is a bad * request, and a regular expression is refused by name (it would be matched over the reply once From 6fb31c057778c3444287f8bc20d5c28116b1f294 Mon Sep 17 00:00:00 2001 From: Nunze Date: Sun, 18 Oct 2026 18:55:37 +0200 Subject: [PATCH 014/152] docs/GUIDE: eight cards on unequal links -- weighted shards, pieces and their environment Co-Authored-By: Claude Opus 5.5 --- docs/GUIDE.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index bf961929..d71a57e9 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1029,6 +1029,51 @@ link pay more. access, for a board where peer traffic is broken or slow. `on` requires peer access and stops at startup, naming the pairs, if the driver refuses any. `auto`, the default, trusts the driver. +**Eight cards on unequal links.** In the two-shot rank r reduces shard r of the message, and every +rank's link carries at least the whole message each way whatever its shard, so the slowest link +sets the time of every prefill all-reduce. On a board whose slots differ (here eight R9700s: four +at Gen5 x16, two at Gen5 x8, two links that trained at Gen4 x8) the eight-rank two-shot does two +things from 262144 elements (512 KiB of bf16) up: + +- it weights the shards by link: a rank on a slow link reduces a short shard, or none; +- it runs the message in pieces, so one piece's second hop shares the link with the next piece's + first, both directions at once: 2 pieces under 1048576 elements, 4 under 4194304, 8 above. + +Every word is still folded in fp32 in ascending rank order whoever reduces it, so the bits are +those of the even split. Below that size a decode step's message runs even and in one piece: there +the extra handshakes cost more than the link time they save. + +The weights come from the links. At startup each rank reads its card's PCIe path in sysfs from the +root port down and takes the slowest hop (the R9700's on-card switch reports full speed in any +slot, so a degraded slot shows only at the root port); its weight is round(4·(rate/fastest)²), so +x16 is 4, half the rate 1 and a quarter 0. Equal links give equal weights and the unweighted +kernel. One line names what was read: + +``` +[r4d] eight-rank two-shot shard weights from the slowest PCIe hop of each card: r0 32.0 GT/s x16 +63.0 GB/s w4, r1 32.0 GT/s x8 31.5 GB/s w1, r2 16.0 GT/s x8 15.8 GB/s w0, ... +``` + +`r4d_selftest --perfar8 0` prints the same weights and times both rows at every piece count, each +checked against the fold (warm, the slowest rank): + +| message (bf16) | even, one piece | weights 4,1,0,4,0,1,4,4 | +|---|---|---| +| 196608 elements (384 KiB) | 73 µs | below 262144: even, one piece | +| 524288 (1 MiB) | 214 µs | 166 µs in 2 pieces | +| 2097152 (4 MiB) | 699 µs | 531 µs in 4 pieces | +| 8388608 (16 MiB, a 2048-token chunk at 4096 wide) | 2841 µs | 1636 µs in 8 pieces | + +With the two Gen4 links retrained to Gen5 x8 the weights read 4,1,1,4,1,1,4,4 and the 16 MiB +message takes 1360 µs. + +The links are read once, at startup: a link that drops to a lower speed while the server runs +keeps its weight until the next start. `RADIANCE_AR8_SHARD_WEIGHTS` overrides them: `off` keeps +the shards even, eight comma-separated integers set them, unset or `auto` reads the links. +`RADIANCE_AR8_PIECES` (1 to 16) fixes the piece count, and `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` +and `RADIANCE_AR8_PIECES_MIN_ELEMS` move the two sizes they start at. Every rank must read the +same values; where they differ, every rank stops at startup. + ### 4.8 Host tier for finished conversations By default a finished conversation's KV blocks stay in VRAM, held by the prefix cache, until evicted @@ -2616,6 +2661,7 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct? | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | +| `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) | Engine development has its own instruments: `RADIANCE_DEBUG_*` (residual probes, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on the operands the model issued; From fb7a30cd848188a387a8cbf6220c06f4ab34aadf Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 015/152] libr4d: a refused IPC export is not fatal r4d_ar_ipc_alloc exports every collective buffer with hipIpcGetMemHandle. Beside another process holding the same cards it answers invalid argument while the allocation is fine, and HIPOK stopped the engine. libr4d's ranks are threads of one process and share the pointer itself, so the handle is never read: a refused export leaves it empty. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_ar_oneshot_2rank_exact.hip | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/libr4d/r4d_ar_oneshot_2rank_exact.hip b/libr4d/r4d_ar_oneshot_2rank_exact.hip index 9d6a5137..37bbd373 100644 --- a/libr4d/r4d_ar_oneshot_2rank_exact.hip +++ b/libr4d/r4d_ar_oneshot_2rank_exact.hip @@ -300,10 +300,18 @@ long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len // The zeroes must land before the pointer reaches a peer, or its first push or flag store could // race the queued memset. HIPOK(hipStreamSynchronize(nullptr)); + // The handle is for an out-of-process peer. libr4d's ranks are threads of one process and share + // the pointer itself (r4d_ar_entry.hip), so a refused export is not fatal: beside another engine + // on the same cards hipIpcGetMemHandle answers invalid argument while the allocation is fine. hipIpcMemHandle_t h; - HIPOK(hipIpcGetMemHandle(&h, p)); - std::memcpy(out_handle, &h, sizeof(h)); - *out_len = (int)sizeof(h); + if (hipIpcGetMemHandle(&h, p) == hipSuccess) { + std::memcpy(out_handle, &h, sizeof(h)); + *out_len = (int)sizeof(h); + } else { + (void)hipGetLastError(); + std::memset(out_handle, 0, R4D_AR_HANDLE_BYTES); + *out_len = 0; + } return (long)p; } // r4d_p2p_copy2d as a kernel with a bounded workgroup count. From 1d1cb21e02bb782f497260daf3b27868b0be582e Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 016/152] libr4d: R4D_AR_MAX_BLOCKS, a ceiling on collective blocks for two engines on one set of cards Every block of a collective spins until its twin on the peer card has pushed. One engine is safe (both cards dispatch its blocks in the same order); two tensor-parallel engines on the same cards can deadlock, one engine's spinners filling a card while their twins wait behind the other engine's kernel. Two TP2 engines on two R9700s hung within a minute of concurrent prefill and the failed queue eviction froze the host. Capped in both engines so their spinners together leave part of a card free, the cycle cannot close: 15 minutes of concurrent load clean at 64 / 16. Only launch counts shrink; each element's sum is the same. Unset, nothing changes. GUIDE section 8 documents it. Co-Authored-By: Claude Opus 5.5 --- docs/GUIDE.md | 14 ++++++++++++++ libr4d/r4d_ar_entry.hip | 17 ++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index d71a57e9..4b1bdea0 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2651,6 +2651,20 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct? | `ROCM_PATH` | where ROCm lives, if not `/opt/rocm` (build time) | | `HF_TOKEN` | for `scripts/hfget.sh` and `--model ` on a gated or private repo | | `XDG_CACHE_HOME` | where `--model ` fetches to without `--download-dir` (`$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf`) | +| `R4D_AR_MAX_BLOCKS` | a ceiling on libr4d's collective block counts, for two tensor-parallel engines on one set of cards; set it in both (below). Unset, nothing changes | + +**Two engines on one set of cards.** Every block of a libr4d collective spins until its twin on the +peer card has pushed, and a prefill-sized fused all-reduce launches more blocks than a card holds at +once. One engine is safe: both cards dispatch its blocks in the same order. Two tensor-parallel +engines on the same cards can deadlock: one engine's spinners fill a card while their twins wait +behind the other engine's kernel on the peer, which waits for a slot on the full card. On two R9700s +(Qwen3.8-27B and a Gemma 3 27B, both `--tp 2`) that hung within a minute of concurrent prefill, and +the driver's attempt to evict the queues froze the host. With `R4D_AR_MAX_BLOCKS` in both engines +low enough that their spinners together leave part of a card free, the cycle cannot close: 64 for +Qwen3.8-27B (its decode at 16 sequences x 4 rows stays uncapped) and 16 for the Gemma ran 15 +minutes of concurrent long prompts on both without a stall. The ceiling costs prefill time, the +reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapped, 9.8 s at 64, +10.3 s at 32. Give the engine started first its `--gpu-headroom-mib` for the second. **Tooling** diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 999ae62b..e7d80cdb 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -354,11 +354,26 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, } if (maxb <= 0) return RAD_E_DEVICE; in->max_blocks = maxb; + /* R4D_AR_MAX_BLOCKS: a ceiling on every collective's block count, for two engines sharing one + * set of cards. Each block of a collective spins until its twin on the peer card has pushed, and + * a prefill-sized ar_rmsnorm_quant_fp8 launches up to 256 blocks of 16 waves, twice what an + * R9700 holds. One engine survives that (both cards dispatch blocks in the same order, so the + * lowest unfinished block is resident on both); two engines do not: one engine's spinning blocks + * fill a card while their twins wait behind the other engine's kernel on the peer card, which + * waits for a slot on the full card. Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B) + * hung within a minute of concurrent prefill; MES then failed to evict the queues and the + * failed reset froze the host. Capped in both engines so that their spinners together cannot + * fill a card, the cycle cannot close. The flag and counter arrays keep their full size (maxb); + * only the launch counts shrink, and each element's sum is the same. Unset, nothing changes. */ + if (const char* e = std::getenv("R4D_AR_MAX_BLOCKS")) { + const int cap = std::atoi(e); + if (cap > 0 && cap < in->max_blocks) in->max_blocks = cap; + } /* Launch ceilings: 24 at two ranks, the library's design count at width. The compressed * 2-rank wire uses up to 48, set at its own call site: it moves three eighths of the bytes, so * it needs more blocks to saturate the link. */ in->nb_cap = (world == 2) ? 24 : (nb_design > 0 ? nb_design : maxb); - if (in->nb_cap > maxb) in->nb_cap = maxb; + if (in->nb_cap > in->max_blocks) in->nb_cap = in->max_blocks; /* Slots: one per (parity, source rank) at width; two at world 2, where there is one remote * writer. Flags: one word per (block, source rank) at width, one per block at world 2. From d82c11644e67a706f8798ee02a28a2beefc973a8 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 17:40:39 +0000 Subject: [PATCH 017/152] libr4d: review fixes -- a tuned ar_ln_had_quant_i8 count under the ceiling; say which gathers it cannot cap ar_ln_had_quant_i8 clamped a tuned block count to M only; it stays under R4D_AR_MAX_BLOCKS now, as every other entry's. The MoE hyper-connection gathers keep the minimum their LDS table needs, which may exceed the ceiling: the comment and GUIDE say so instead of "every collective". r4d.h states that a refused IPC export leaves the handle zeroed, out_len 0. Co-Authored-By: Claude Opus 5.5 --- docs/GUIDE.md | 2 +- libr4d/r4d.h | 3 ++- libr4d/r4d_ar_entry.hip | 5 ++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 4b1bdea0..5d1a6bf6 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2651,7 +2651,7 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct? | `ROCM_PATH` | where ROCm lives, if not `/opt/rocm` (build time) | | `HF_TOKEN` | for `scripts/hfget.sh` and `--model ` on a gated or private repo | | `XDG_CACHE_HOME` | where `--model ` fetches to without `--download-dir` (`$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf`) | -| `R4D_AR_MAX_BLOCKS` | a ceiling on libr4d's collective block counts, for two tensor-parallel engines on one set of cards; set it in both (below). Unset, nothing changes | +| `R4D_AR_MAX_BLOCKS` | a ceiling on libr4d's collective block counts, for two tensor-parallel engines on one set of cards; set it in both (below). The MoE models' hyper-connection gathers keep the minimum their LDS table needs. Unset, nothing changes | **Two engines on one set of cards.** Every block of a libr4d collective spins until its twin on the peer card has pushed, and a prefill-sized fused all-reduce launches more blocks than a card holds at diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 8745d5db..869c12c9 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -230,7 +230,8 @@ int r4d_gdn_recurrent_update_k128_v128_bf16_fp32state( // zeroed words, a handshake and a slot-parity counter per block of capacity (r4d_ar_seq.h). enum { R4D_AR_HANDLE_BYTES = 64 }; // IPC scratch helpers, startup-only: alloc returns the device pointer and writes the IPC handle -// (up to HANDLE_BYTES) into out_handle. +// (up to HANDLE_BYTES) into out_handle. A refused export (beside another engine on the same cards) +// leaves it zeroed with *out_len 0: libr4d's ranks are threads of one process and share the pointer. long r4d_ar_ipc_alloc(long size, int finegrained, char* out_handle, int* out_len); // Strided peer (or local) device-to-device copy through the copy engines; pitches and width in // bytes, height in rows. Returns 0 or -100 - hipError_t. diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index e7d80cdb..80cf89fd 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -360,7 +360,9 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, * R9700 holds. One engine survives that (both cards dispatch blocks in the same order, so the * lowest unfinished block is resident on both); two engines do not: one engine's spinning blocks * fill a card while their twins wait behind the other engine's kernel on the peer card, which - * waits for a slot on the full card. Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B) + * waits for a slot on the full card. Not capped: the hyper-connection gathers of the MoE paths + * (r4d_ar_gather_hc_write without its inverse scratch, r4d_ar_hc_write_wht6), whose LDS table + * needs a minimum block count, which may exceed the ceiling (dense models do not use them). Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B) * hung within a minute of concurrent prefill; MES then failed to evict the queues and the * failed reset froze the host. Capped in both engines so that their spinners together cannot * fill a card, the cycle cannot close. The flag and counter arrays keep their full size (maxb); @@ -1207,6 +1209,7 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { * shim's count equal to the kernel's. */ int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(M * K * 2 / 16, in->max_blocks); if (nblocks > (int)M) nblocks = (int)M; + if (nblocks > in->max_blocks) nblocks = in->max_blocks; // a tuned count under R4D_AR_MAX_BLOCKS too /* LDS floor on the block count. The compressed wire stages every row a block owns, so a count * chosen for the push alone can exceed LDS (at K = 5120, more than two rows per block). Raise * the count to the kernel's floor; refuse shapes no count within the flag capacity serves. From c94a0e6cc28ffaa645c2ae6e571f31364f444111 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 018/152] libquant: GPTQ's factorisations through LAPACK where OpenBLAS is found; one layer's factor at a time At K = 21504 (a dense 27B's down projection) the single-threaded Cholesky and inverse took hours a layer; dpotrf / dpotri take 13.5 s for all three on 24 cores, identical to 1e-14. Without OpenBLAS nothing changes. The factor cache kept every layer's factor, 3.7 GB each at that width, which OOM-killed a 62-layer conversion at layer 25; it now keeps one at a time (a layer's experts arrive together and still share it). RAD_LQ_FACTOR_CACHE_ALL keeps the old behaviour. Co-Authored-By: Claude Opus 5.5 --- libquant/CMakeLists.txt | 8 ++++++ libquant/lq_gptq.cpp | 54 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/libquant/CMakeLists.txt b/libquant/CMakeLists.txt index 3d7b1fc7..f40da2be 100644 --- a/libquant/CMakeLists.txt +++ b/libquant/CMakeLists.txt @@ -27,3 +27,11 @@ if(OpenMP_CXX_FOUND) else() message(STATUS "libquant: no OpenMP -- quantisers will run single-threaded") endif() + +# GPTQ's Hessian factorisations through LAPACK where OpenBLAS is installed (lq_gptq.cpp): the +# built-in loops are single-threaded and take hours on a 21504-wide down projection. +find_library(LQ_OPENBLAS openblas) +if(LQ_OPENBLAS) + target_compile_definitions(libquant PRIVATE RAD_LQ_LAPACK=1) + target_link_libraries(libquant PRIVATE ${LQ_OPENBLAS}) +endif() diff --git a/libquant/lq_gptq.cpp b/libquant/lq_gptq.cpp index e8195373..bea87891 100644 --- a/libquant/lq_gptq.cpp +++ b/libquant/lq_gptq.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -21,6 +22,48 @@ namespace { * U[i][j] (Frantar et al.'s formulation). Double throughout: a Cholesky is K^3/6 accumulations * deep, and f32 loses real conditioning on a matrix near-singular in the directions a rotation * flattened. */ +#ifdef RAD_LQ_LAPACK +/* LAPACK, column-major, Fortran calling convention (OpenBLAS). See the three functions below. */ +extern "C" void dpotrf_(const char* uplo, const int* n, double* a, const int* lda, int* info); +extern "C" void dpotri_(const char* uplo, const int* n, double* a, const int* lda, int* info); + +/* Zero the row-major strict upper (upper = true) or strict lower triangle. */ +static void zero_triangle(std::vector& a, int64_t k, bool upper) { +#pragma omp parallel for schedule(static) + for (int64_t i = 0; i < k; ++i) { + if (upper) for (int64_t j = i + 1; j < k; ++j) a[(size_t)(i * k + j)] = 0.0; + else for (int64_t j = 0; j < i; ++j) a[(size_t)(i * k + j)] = 0.0; + } +} + +bool chol_lower(std::vector& a, int64_t k) { + const int n = (int)k; + int info = 0; + dpotrf_("U", &n, a.data(), &n, &info); + if (info != 0) return false; + zero_triangle(a, k, true); + return true; +} + +void inv_from_chol(std::vector& l, int64_t k) { + const int n = (int)k; + int info = 0; + dpotri_("U", &n, l.data(), &n, &info); + /* Column-major upper is row-major lower: mirror it into the row-major upper half. */ +#pragma omp parallel for schedule(static) + for (int64_t i = 0; i < k; ++i) + for (int64_t j = i + 1; j < k; ++j) l[(size_t)(i * k + j)] = l[(size_t)(j * k + i)]; +} + +bool chol_upper(std::vector& a, int64_t k) { + const int n = (int)k; + int info = 0; + dpotrf_("L", &n, a.data(), &n, &info); + if (info != 0) return false; + zero_triangle(a, k, false); + return true; +} +#else bool chol_lower(std::vector& a, int64_t k) { for (int64_t i = 0; i < k; ++i) { for (int64_t j = 0; j <= i; ++j) { @@ -79,6 +122,7 @@ bool chol_upper(std::vector& a, int64_t k) { } return true; } +#endif /* RAD_LQ_LAPACK */ struct Cache { std::mutex mu; @@ -126,7 +170,15 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d if (it != c.f.end()) return it->second; } auto keep = [&](Gram u) { - if (layer) c.f.emplace(key, u); + /* One factor at a time: a dense model reads each layer's once, and a 21504-wide factor + * is 3.7 GB (every one kept OOM-killed TranslateGemma 27B's conversion at layer 25). + * Experts of one layer arrive together, so they still share it. + * RAD_LQ_FACTOR_CACHE_ALL keeps the old behaviour. */ + static const bool all = std::getenv("RAD_LQ_FACTOR_CACHE_ALL") != nullptr; + if (layer) { + if (!all) c.f.clear(); + c.f.emplace(key, u); + } return u; }; From 400bbefa13d8b73b5849d418ea562931443b89d0 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 019/152] libquant: a column-split linear's Hessian from per-rank parts Under tensor parallelism an attention output or down projection sees only its rank's K / world columns, so no rank can write the K x K Gram. A tap may write each rank's block as .part; with no whole file calib_sum places the parts on the diagonal in rank order (the cross-rank products, never formed, zero) and converts the result like a whole file. Parts that do not cover K, or not in domain 0, are reported and the weight rounds to nearest. Tested byte for byte against the whole block-diagonal file. Co-Authored-By: Claude Opus 5.5 --- docs/TOOLS.md | 6 ++++- libquant/lq_hess.cpp | 55 +++++++++++++++++++++++++++++++++++++++ libquant/lq_hess.h | 9 ++++++- tests/quant_algo_test.cpp | 38 +++++++++++++++++++++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 15a10d6f..bba746bf 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -278,7 +278,11 @@ rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad it in. A container that stores a weight rotated records the rotated input, and a recipe that rotates the same weight reads it as it is. A weight with no file there is quantised uncalibrated, and the converter says so; `awq`, `autoround` and `paroquant` use the imatrix's diagonal instead - when `--imatrix` gives one. The three-step calibrated conversion is in [MOE-W4.md](MOE-W4.md). + when `--imatrix` gives one. Under tensor parallelism a column-split linear (an attention output or + down projection) sees only its rank's columns, so a tap may write each rank's Gram as + `gram.r..part.bin`: with no whole file, libquant places the parts on the diagonal in + rank order (the cross-rank products, never formed, left zero). They must cover K and be in the + model's own domain. The three-step calibrated conversion is in [MOE-W4.md](MOE-W4.md). - `autoround` and `paroquant` are slow. AutoRound's 200 default steps each cost N·K² multiply-adds; on a 16-core Zen 5 at about 2.5 TFLOP/s that is minutes for a 17408-wide down projection and most of a working day for a 27B dense model. `iters=50` takes a quarter of the time. diff --git a/libquant/lq_hess.cpp b/libquant/lq_hess.cpp index 794e2231..f0f0735b 100644 --- a/libquant/lq_hess.cpp +++ b/libquant/lq_hess.cpp @@ -3,6 +3,7 @@ #include "lq_common.h" #include +#include #include #include #include @@ -233,6 +234,58 @@ std::string calib_stem(const char* name) { return s; } +/* The rank parts of `stem` (see calib_sum), block diagonal into `acc`; the number read. */ +int calib_sum_parts(const char* dir, const std::string& stem, int64_t K, int64_t domain, + std::vector* acc) { + std::vector> parts; + int64_t total = 0; + for (int r = 0; r < kMaxRanks; ++r) { + const std::string path = gram_path(dir, r, stem + ".part"); + FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) break; + char hdr[kHdr]; + uint32_t kk = 0, dom = 0; + bool ok = std::fread(hdr, 1, kHdr, f) == (size_t)kHdr && std::memcmp(hdr, "RADGRAM2", 8) == 0; + if (ok) { std::memcpy(&kk, hdr + 8, 4); std::memcpy(&dom, hdr + 24, 4); } + ok = ok && dom == 0 && kk > 0 && total + kk <= K; + std::vector h; + if (ok) { + h.resize((size_t)kk * kk); + ok = std::fread(h.data(), 4, h.size(), f) == h.size(); + } + std::fclose(f); + if (!ok) { + std::fprintf(stderr, "libquant: %s is not a usable part of the %lld-wide '%s' (a domain-0 " + "RADGRAM2 within K)\n", path.c_str(), (long long)K, stem.c_str()); + return 0; + } + total += kk; + parts.push_back(std::move(h)); + } + if (parts.empty()) return 0; + if (total != K) { + std::fprintf(stderr, "libquant: the %zu part(s) of '%s' cover %lld of K=%lld columns\n", + parts.size(), stem.c_str(), (long long)total, (long long)K); + return 0; + } + std::vector h((size_t)(K * K), 0.0); + int64_t off = 0; + for (const auto& p : parts) { + const int64_t k = (int64_t)std::llround(std::sqrt((double)p.size())); + for (int64_t i = 0; i < k; ++i) + for (int64_t j = 0; j < k; ++j) + h[(size_t)((off + i) * K + off + j)] = p[(size_t)(i * k + j)]; + off += k; + } + if (domain != 0) { + rotate_gram(h, K, domain); + for (double& x : h) x = (double)(float)x; + } + if (acc->empty()) acc->assign(h.size(), 0.0); + for (size_t i = 0; i < h.size(); ++i) (*acc)[i] += h[i]; + return (int)parts.size(); +} + int calib_sum(const char* dir, const std::string& stem, int64_t K, int64_t domain, std::vector* acc) { /* Sum every rank's file. Under expert parallelism a rank's `down` Hessian covers only tokens @@ -242,6 +295,8 @@ int calib_sum(const char* dir, const std::string& stem, int64_t K, int64_t domai int found = 0; for (int r = 0; r < kMaxRanks; ++r) if (read_gram(gram_path(dir, r, stem), K, domain, acc)) ++found; + if (!found && (domain == 0 || (domain >= 2 && (domain & (domain - 1)) == 0 && K % domain == 0))) + found = calib_sum_parts(dir, stem, K, domain, acc); return found; } diff --git a/libquant/lq_hess.h b/libquant/lq_hess.h index 387fbadd..48fcc963 100644 --- a/libquant/lq_hess.h +++ b/libquant/lq_hess.h @@ -51,7 +51,14 @@ std::string calib_resolve(const char* dir, const char* name, int64_t K); /* Every rank's file for `stem` in `dir`, each converted into `domain` (0, or the Hadamard width a * rotated grid quantises in), summed into `acc` (K x K, double, row-major). Returns the number of * files read, 0 when there are none. A file that exists but is unusable (wrong magic, wrong K, - * short, or a domain that cannot be converted) is reported on stderr and skipped. */ + * short, or a domain that cannot be converted) is reported on stderr and skipped. + * + * With no whole file, the parts: under tensor parallelism a column-split linear (an attention + * output or down projection) sees only its rank's K / world input columns, so each rank's tap + * writes the Gram of those as `.part` (gram.r..part.bin). They are placed on + * the diagonal in rank order, the cross-rank products, never formed on one card, left zero. The + * parts must cover K exactly and be in domain 0 (a rotation of K does not keep the blocks); the + * result is then converted into `domain` like a whole file. */ int calib_sum(const char* dir, const std::string& stem, int64_t K, int64_t domain, std::vector* acc); diff --git a/tests/quant_algo_test.cpp b/tests/quant_algo_test.cpp index 76758d82..2a779af3 100644 --- a/tests/quant_algo_test.cpp +++ b/tests/quant_algo_test.cpp @@ -272,6 +272,44 @@ TEST(an_expert_reads_its_own_hessian_before_its_layers) { CHECK(same_planes(run(both, e11), run(only_pool, e11))); } +TEST(a_column_split_hessian_is_assembled_from_its_rank_parts) { + /* Under tensor parallelism a down projection's tap sees one rank's K / 2 input columns, and each + * rank writes the Gram of its own as `.part`. GPTQ against the two parts must quantise + * exactly as against one whole file holding them block diagonally (the cross-rank products + * zero, never formed). Parts that do not cover K are reported and the weight is rounded to + * nearest, as with no calibration at all. */ + NEED_LIBQUANT(); + const std::vector& h = H(); + const int64_t k2 = kC / 2; + std::vector p0((size_t)(k2 * k2)), p1((size_t)(k2 * k2)), whole((size_t)(kC * kC), 0.0f); + for (int64_t i = 0; i < k2; ++i) + for (int64_t j = 0; j < k2; ++j) { + p0[(size_t)(i * k2 + j)] = h[(size_t)(i * kC + j)]; + p1[(size_t)(i * k2 + j)] = h[(size_t)((k2 + i) * kC + k2 + j)]; + whole[(size_t)(i * kC + j)] = p0[(size_t)(i * k2 + j)]; + whole[(size_t)((k2 + i) * kC + k2 + j)] = p1[(size_t)(i * k2 + j)]; + } + const TempDir tp("rad_quant_parts"), tw("rad_quant_whole"), ts("rad_quant_short"), + tn("rad_quant_none"); + REQUIRE(!tp.path.empty() && !tw.path.empty() && !ts.path.empty() && !tn.path.empty()); + REQUIRE(write_gram(tp.path + "/gram.r0.blk.2.ffn_down.part.bin", k2, kT, p0)); + REQUIRE(write_gram(tp.path + "/gram.r1.blk.2.ffn_down.part.bin", k2, kT, p1)); + REQUIRE(write_gram(tw.path + "/gram.r0.blk.2.ffn_down.bin", kC, kT, whole)); + REQUIRE(write_gram(ts.path + "/gram.r0.blk.2.ffn_down.part.bin", k2, kT, p0)); + + auto run = [&](const std::string& dir) -> Quantised { + Opts o; + o.s("codes", "i4").i("group", 32).s("scale", "f16").s("calib", dir.c_str()); + Quantised q = quantise(quantizer("gptq"), o, "blk.2.ffn_down.weight", kR, kC, weight()); + CHECK_EQ(q.status, RAD_OK); + return q; + }; + const Quantised parts = run(tp.path), one = run(tw.path), short_ = run(ts.path), none = run(tn.path); + CHECK(same_planes(parts, one)); + CHECK(!same_planes(parts, none)); + CHECK(same_planes(short_, none)); +} + TEST(awq_scales_the_columns_the_input_says_matter) { NEED_LIBQUANT(); Opts g, x; From cec70ad1c7ba86781ac4eddb59acc7f65ab0b632 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 17:40:57 +0000 Subject: [PATCH 020/152] libquant: review fixes -- loops kept as the LAPACK reference (RAD_LQ_LAPACK=0) and tested against it, NaN pivots refused, 4 layer factors kept The single-threaded loops stay beside LAPACK; RAD_LQ_LAPACK=0 takes them and gptq_through_lapack_matches_the_loops compares the two (output error equal to rounding). A factor whose diagonal is not finite and positive is refused, as the loops refused a NaN pivot that dpotrf lets through. The cache keeps the 4 most recent layer factors: a MoE layer's experts alternate between two stems. The size in the comment is the f32 factor's, 1.85 GB. Co-Authored-By: Claude Opus 5.5 --- libquant/lq_gptq.cpp | 85 +++++++++++++++++++++++++++++++-------- tests/quant_algo_test.cpp | 28 +++++++++++++ 2 files changed, 97 insertions(+), 16 deletions(-) diff --git a/libquant/lq_gptq.cpp b/libquant/lq_gptq.cpp index bea87891..af4ce4bf 100644 --- a/libquant/lq_gptq.cpp +++ b/libquant/lq_gptq.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -27,6 +28,16 @@ namespace { extern "C" void dpotrf_(const char* uplo, const int* n, double* a, const int* lda, int* info); extern "C" void dpotri_(const char* uplo, const int* n, double* a, const int* lda, int* info); +/* dpotrf rejects a non-positive pivot but lets a NaN through, where the loops' !(s > 0) refuses + * it: a factor whose diagonal is not finite and positive is refused here as there. */ +static bool diag_ok(const std::vector& a, int64_t k) { + for (int64_t i = 0; i < k; ++i) { + const double d = a[(size_t)(i * k + i)]; + if (!(d > 0.0) || !std::isfinite(d)) return false; + } + return true; +} + /* Zero the row-major strict upper (upper = true) or strict lower triangle. */ static void zero_triangle(std::vector& a, int64_t k, bool upper) { #pragma omp parallel for schedule(static) @@ -36,16 +47,16 @@ static void zero_triangle(std::vector& a, int64_t k, bool upper) { } } -bool chol_lower(std::vector& a, int64_t k) { +bool chol_lower_lapack(std::vector& a, int64_t k) { const int n = (int)k; int info = 0; dpotrf_("U", &n, a.data(), &n, &info); if (info != 0) return false; zero_triangle(a, k, true); - return true; + return diag_ok(a, k); } -void inv_from_chol(std::vector& l, int64_t k) { +void inv_from_chol_lapack(std::vector& l, int64_t k) { const int n = (int)k; int info = 0; dpotri_("U", &n, l.data(), &n, &info); @@ -55,16 +66,18 @@ void inv_from_chol(std::vector& l, int64_t k) { for (int64_t j = i + 1; j < k; ++j) l[(size_t)(i * k + j)] = l[(size_t)(j * k + i)]; } -bool chol_upper(std::vector& a, int64_t k) { +bool chol_upper_lapack(std::vector& a, int64_t k) { const int n = (int)k; int info = 0; dpotrf_("L", &n, a.data(), &n, &info); if (info != 0) return false; zero_triangle(a, k, false); - return true; + return diag_ok(a, k); } -#else -bool chol_lower(std::vector& a, int64_t k) { +#endif /* RAD_LQ_LAPACK */ + +/* The single-threaded loops: the reference, and the only path without OpenBLAS. */ +bool chol_lower_loop(std::vector& a, int64_t k) { for (int64_t i = 0; i < k; ++i) { for (int64_t j = 0; j <= i; ++j) { double s = a[(size_t)(i * k + j)]; @@ -82,7 +95,7 @@ bool chol_lower(std::vector& a, int64_t k) { } /* A = L L^T, factored in place -> A^-1, full and symmetric: L^-1 first, then L^-T L^-1. */ -void inv_from_chol(std::vector& l, int64_t k) { +void inv_from_chol_loop(std::vector& l, int64_t k) { for (int64_t j = 0; j < k; ++j) { l[(size_t)(j * k + j)] = 1.0 / l[(size_t)(j * k + j)]; for (int64_t i = j + 1; i < k; ++i) { @@ -103,7 +116,7 @@ void inv_from_chol(std::vector& l, int64_t k) { } /* A -> U upper with A = U^T U. */ -bool chol_upper(std::vector& a, int64_t k) { +bool chol_upper_loop(std::vector& a, int64_t k) { for (int64_t i = 0; i < k; ++i) { double d = a[(size_t)(i * k + i)]; for (int64_t t = 0; t < i; ++t) { @@ -122,11 +135,46 @@ bool chol_upper(std::vector& a, int64_t k) { } return true; } -#endif /* RAD_LQ_LAPACK */ + +/* LAPACK where OpenBLAS was found; RAD_LQ_LAPACK=0 takes the loops instead, the reference the + * LAPACK path is checked against (quant_algo_test). */ +bool use_lapack() { +#ifdef RAD_LQ_LAPACK + const char* e = std::getenv("RAD_LQ_LAPACK"); + return !(e && e[0] == '0'); +#else + return false; +#endif +} + +bool chol_lower(std::vector& a, int64_t k) { +#ifdef RAD_LQ_LAPACK + if (use_lapack()) return chol_lower_lapack(a, k); +#endif + return chol_lower_loop(a, k); +} + +void inv_from_chol(std::vector& l, int64_t k) { +#ifdef RAD_LQ_LAPACK + if (use_lapack()) return inv_from_chol_lapack(l, k); +#endif + inv_from_chol_loop(l, k); +} + +bool chol_upper(std::vector& a, int64_t k) { +#ifdef RAD_LQ_LAPACK + if (use_lapack()) return chol_upper_lapack(a, k); +#endif + return chol_upper_loop(a, k); +} + +/* Layer factors kept at once (RAD_LQ_FACTOR_CACHE_ALL: every one). */ +constexpr size_t kFactors = 4; struct Cache { std::mutex mu; std::map f; /* null = looked and found nothing */ + std::deque order; /* f's keys, oldest first */ }; Cache& cache() { @@ -170,14 +218,19 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d if (it != c.f.end()) return it->second; } auto keep = [&](Gram u) { - /* One factor at a time: a dense model reads each layer's once, and a 21504-wide factor - * is 3.7 GB (every one kept OOM-killed TranslateGemma 27B's conversion at layer 25). - * Experts of one layer arrive together, so they still share it. - * RAD_LQ_FACTOR_CACHE_ALL keeps the old behaviour. */ + /* A few layer factors, the oldest dropped first: a dense model reads each layer's + * once, and a 21504-wide factor is 1.85 GB in f32 (every one kept OOM-killed + * TranslateGemma 27B's conversion at layer 25). A MoE layer's experts run in parallel + * and alternate between its gate_up and down stems, so one kept factor would be + * recomputed over and over. RAD_LQ_FACTOR_CACHE_ALL keeps every one. */ static const bool all = std::getenv("RAD_LQ_FACTOR_CACHE_ALL") != nullptr; - if (layer) { - if (!all) c.f.clear(); + if (layer && !c.f.count(key)) { + while (!all && c.order.size() >= kFactors) { + c.f.erase(c.order.front()); + c.order.pop_front(); + } c.f.emplace(key, u); + c.order.push_back(key); } return u; }; diff --git a/tests/quant_algo_test.cpp b/tests/quant_algo_test.cpp index 2a779af3..d4a1b345 100644 --- a/tests/quant_algo_test.cpp +++ b/tests/quant_algo_test.cpp @@ -272,6 +272,34 @@ TEST(an_expert_reads_its_own_hessian_before_its_layers) { CHECK(same_planes(run(both, e11), run(only_pool, e11))); } +TEST(gptq_through_lapack_matches_the_loops) { + /* Where OpenBLAS was found the factorisations go through LAPACK; RAD_LQ_LAPACK=0 takes the + * single-threaded loops, the reference. The same Gram in two directories (the factor cache is + * keyed by directory), one run each way: the output error agrees to rounding. Codes may + * differ where error feedback lands on a rounding boundary. Without OpenBLAS both runs take + * the loops and agree trivially. */ + NEED_LIBQUANT(); + const TempDir fast_dir("rad_quant_lapack"), loop_dir("rad_quant_loops"); + REQUIRE(!fast_dir.path.empty() && !loop_dir.path.empty()); + REQUIRE(write_gram(fast_dir.path + "/gram.r0.blk.2.attn_q.bin", kC, kT, H())); + REQUIRE(write_gram(loop_dir.path + "/gram.r0.blk.2.attn_q.bin", kC, kT, H())); + auto run = [&](const std::string& dir) { + Opts o; + o.s("codes", "i4").i("group", 32).s("scale", "f16").s("calib", dir.c_str()); + return quantise(quantizer("gptq"), o, kName, kR, kC, weight()); + }; + const Quantised fast = run(fast_dir.path); + setenv("RAD_LQ_LAPACK", "0", 1); + const Quantised loops = run(loop_dir.path); + unsetenv("RAD_LQ_LAPACK"); + REQUIRE_EQ(fast.status, RAD_OK); + REQUIRE_EQ(loops.status, RAD_OK); + const double ef = out_err(weight(), decode(fast, kR, kC)); + const double el = out_err(weight(), decode(loops, kR, kC)); + std::fprintf(stderr, " LAPACK %.9g, loops %.9g\n", ef, el); + CHECK(std::fabs(ef - el) <= 1e-6 * el); +} + TEST(a_column_split_hessian_is_assembled_from_its_rank_parts) { /* Under tensor parallelism a down projection's tap sees one rank's K / 2 input columns, and each * rank writes the Gram of its own as `.part`. GPTQ against the two parts must quantise From 83856506e114060fb3a37e861a37fb0494e4f320 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 15:42:07 +0800 Subject: [PATCH 021/152] libr4d: i8a8h -- the int8 trunk GEMMs read a weight rotated by fwht128, against had_quant_act_i8g gemm_i8a8_nt_m16 and gemm_i8a8_tiled take dtype i8a8h: the same launch over i8 codes rotated by the unnormalised 128-wide Hadamard along K, the 1/128 in the bf16 scale (libquant's transform=fwht128). The layout hook accepts only the transform its dtype names and tags the rotated codes r4d.i8h.w.frag64, since the bytes cannot tell the two forms apart. r4d_selftest's i8a8h_rot measures the pair against the exact f32 product: rel_l2 0.009-0.012 rotated, 0.012-0.014 plain, ~1.0 for the rotated weight against the plain quantiser. The had_quant_act_i8g row now says the factor of 128 is the weight's, not sqrt(128). Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_fp8_layout.cpp | 20 ++++- libr4d/r4d_rows.cpp | 18 ++-- libr4d/r4d_selftest.cpp | 170 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 199 insertions(+), 9 deletions(-) diff --git a/libr4d/r4d_fp8_layout.cpp b/libr4d/r4d_fp8_layout.cpp index b74b6efa..f102ae17 100644 --- a/libr4d/r4d_fp8_layout.cpp +++ b/libr4d/r4d_fp8_layout.cpp @@ -228,8 +228,18 @@ extern "C" int r4d_rad_unrelayout_fp8_block(const RadParam* p, int n_p, int oper * side for one 128-K block. On the narrow path a lane's eight accumulator rows are eight * consecutive rows of one tile, so their scales are one 16-byte load. A row-major plane needs * eight scattered loads, which if-converted into every k step cost the decode kernel 70% at - * M = 4. The prefill tile reads one row's scale per lane and works with either form. */ + * M = 4. The prefill tile reads one row's scale per lane and works with either form. + * + * `i8a8h` is the same planes holding a weight rotated by the unnormalised 128-wide Hadamard along + * K, the 1/128 in its scale (libquant's `transform=fwht128`), to be met by had_quant_act_i8g's + * activation. The bytes cannot tell the two apart, so each dtype accepts only its own transform + * and the rotated codes carry a tag of their own. */ namespace { +bool i8_rotated(const RadParam* p, int n_p) { + const char* d = r4d_pgets(p, n_p, "dtype"); + return d && std::strcmp(d, "i8a8h") == 0; +} + int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out) { if (!out || !pl) return RAD_E_INVAL; @@ -237,7 +247,10 @@ int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en const int rc = fgeom(p, n_p, &g); if (rc != RAD_OK) return rc; if (operand != FL_B && operand != FL_BSCALE) return RAD_E_UNSUPPORTED; - if (!r4d_enc::affine(enc, RAD_I8, RAD_BF16, 1, R4D_FP8_BLOCK)) return RAD_E_DTYPE; + const bool rot = i8_rotated(p, n_p); + if (!r4d_enc::affine(enc, RAD_I8, RAD_BF16, 1, R4D_FP8_BLOCK, RAD_DT_INVALID, + rot ? "fwht128" : "")) + return RAD_E_DTYPE; if (operand == FL_BSCALE) { if (!r4d_enc::selects(enc, sel, n, "scale") || !r4d_enc::dims(pl[0], g.N, g.sk)) return RAD_E_SHAPE; @@ -248,7 +261,8 @@ int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en if (!r4d_enc::selects(enc, sel, n, "codes") || !r4d_enc::dims(pl[0], g.N, g.K)) return RAD_E_SHAPE; if (g.K % R4D_FP8_SUPER_K || g.N % r4d_fp8::kFragRows) return RAD_E_SHAPE; - ffill(out, "r4d.i8.w.frag64", RAD_I8, g.N, g.K, r4d_fp8::frag_bytes(g.N, g.K)); + ffill(out, rot ? "r4d.i8h.w.frag64" : "r4d.i8.w.frag64", RAD_I8, g.N, g.K, + r4d_fp8::frag_bytes(g.N, g.K)); return RAD_OK; } } /* namespace */ diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index a244d920..ef5fd83b 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -3746,14 +3746,16 @@ static const RadConstraint cGemmNtQBiasFp8A8M16[] = { C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), }; -/* The int8 twins: the same bands at dtype i8a8. */ +/* The int8 twins: the same bands at dtype i8a8. `i8a8h` is the same launch over a weight rotated + * by a 128-wide Hadamard, the 1/128 in its scale, as `w4a8h` is beside `w4a8`; only its layout + * tag and its activation (had_quant_act_i8g) differ. */ static const RadConstraint cGemmNtI8A8M16[] = { C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_EQ("group", R4D_FP8_BLOCK), - C_IN("dtype", "i8a8"), + C_IN("dtype", "i8a8 i8a8h"), }; static const RadConstraint cGemmNtI8A8Tiled[] = { C_DIV("K", R4D_FP8_BLOCK), C_DIV("N", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), - C_IN("dtype", "i8a8"), + C_IN("dtype", "i8a8 i8a8h"), }; /* libr4d's `K DIV 4`, renamed to docs/OPS.md's `n` as in every quantiser row here. */ static const RadConstraint cQuantActFp8[] = { @@ -5967,7 +5969,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "for the fp8 one and the weight's scale per row", "the fp8 row's: M <= 64; K a multiple of 128; N a multiple of 16", "i8 A with an f32 scale per (row, 128 K), i8 W with a bf16 scale per ROW per 128 K, bf16 C; " - "int32 accumulation within a 128-K block, folded to f32 at its end", + "int32 accumulation within a 128-K block, folded to f32 at its end. dtype i8a8h: the weight " + "rotated by a 128-wide Hadamard, the 1/128 in its scale, against had_quant_act_i8g's activation", RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_M16, ROW(cGemmNtI8A8M16), NOTUNE, nullptr, nullptr, r4d_rad_gemm_i8a8_m16, r4d_rad_gemm_i8a8_m16_scratch, @@ -5978,7 +5981,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "gemm_fp8a8_tiled at INT8 codes: the same 128x128 prefill tile, the iu8 WMMA for the fp8 one and " "the weight's scale per row, eight a lane a tile in the fold", "the fp8 row's: any M; K and N multiples of 128", - "i8 A with an f32 scale per (row, 128 K), i8 W with a bf16 scale per ROW per 128 K, bf16 C", + "i8 A with an f32 scale per (row, 128 K), i8 W with a bf16 scale per ROW per 128 K, bf16 C. " + "dtype i8a8h: the weight rotated by a 128-wide Hadamard, the 1/128 in its scale, against " + "had_quant_act_i8g's activation", RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_TILED, ROW(cGemmNtI8A8Tiled), NOTUNE, nullptr, nullptr, r4d_rad_gemm_i8a8_tiled, nullptr, @@ -6337,7 +6342,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "a 128-wide Hadamard along K, then per-(row, 128-column) symmetric int8 quantisation", "had_quant_act_fp8's: n a multiple of 128 and group 128", "bf16 in, int8 out in PLAIN ROW-MAJOR order with an f32 scale of amax/127 per (row, 128 " - "columns); the sqrt(128) of the unnormalised transform is left to the weight's stored scale", + "columns); the factor of 128 of the unnormalised transform is left to the weight's stored " + "scale (dtype i8a8h)", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cHadQuantActFp8), NOTUNE, nullptr, nullptr, r4d_rad_had_quant_act_i8g }, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 36c7e482..9a49f50f 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -4650,6 +4650,173 @@ static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N ok(nm, rel < 5e-3, d); } +/* The rotated int8 trunk against the f32 product it approximates. i8a8_numeric's reference uses + * the quantiser's own codes, so it would pass with the weight and activation rotated by different + * transforms; this one measures meaning. The weight is quantised on the host as libquant writes + * `codes=i8 group=128 scale=bf16 transform=fwht128` (each 128 of K rotated by h_fwht, the 1/128 in + * the stored scale) and the activation by had_quant_act_i8g on the device, so the pair holds only + * if h_fwht and r4d_fwht_wave are one transform and the 1/128 is divided out exactly once. + * + * Three pairings against the exact product of the sources: plain weight with quant_act_i8g + * (i8a8), rotated weight with had_quant_act_i8g (i8a8h), and the rotated weight with the plain + * quantiser, the mismatch a container served under the wrong dtype would produce, which must + * measure far off. Outlier columns make the rotated grid the better one. */ +static void i8a8h_rot(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K) { + if (!sel(row) && !sel("had_quant_act_i8g")) return; + char nm[160]; + std::snprintf(nm, sizeof nm, "%s i8a8h + had_quant_act_i8g vs the f32 it approximates, " + "M=%lld N=%lld K=%lld", row, (long long)M, (long long)N, (long long)K); + const RadKernelInfo* r = find(pl, row); + const RadKernelInfo* qp = find(pl, "quant_act_i8g"); + const RadKernelInfo* qh = find(pl, "had_quant_act_i8g"); + if (!r || !qp || !qh || !r->layout || !r->relayout) { ok(nm, false, "rows or hooks absent"); return; } + const int64_t nkb = K / 128; + + /* Outliers every 37th weight column and 23rd activation column, six times the body. */ + std::vector wsrc((size_t)(N * K)), xsrc((size_t)(M * K)); + std::vector xbf((size_t)(M * K)); + for (int64_t n = 0; n < N; ++n) + for (int64_t k = 0; k < K; ++k) { + float v = (float)(((n * 31 + k * 17) % 61) - 30) / 37.0f * 0.02f; + if (k % 37 == 0) v *= 6.0f; + wsrc[(size_t)(n * K + k)] = v; + } + for (int64_t m = 0; m < M; ++m) + for (int64_t k = 0; k < K; ++k) { + float v = (float)(((m * 29 + k * 11) % 53) - 26) / 41.0f; + if (k % 23 == 0) v *= 6.0f; + /* Rounded through bf16 here, so the reference reads the number the device does. */ + const uint16_t h = h_to_bf16(v); + xbf [(size_t)(m * K + k)] = h; + xsrc[(size_t)(m * K + k)] = h_bf16(h); + } + std::vector want((size_t)(M * N), 0.0); + for (int64_t m = 0; m < M; ++m) + for (int64_t n = 0; n < N; ++n) { + double acc = 0.0; + for (int64_t k = 0; k < K; ++k) + acc += (double)wsrc[(size_t)(n * K + k)] * (double)xsrc[(size_t)(m * K + k)]; + want[(size_t)(m * N + n)] = acc; + } + + /* The weight as libquant's rtn writes it: codes against the rounded scale, and the rotated + * form then stores that scale over 128, exact in bf16. */ + auto planes = [&](bool rot) { + Planes p; + p.enc = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128); + if (rot) rad_enc_copy_str(p.enc.transform, "fwht128"); + p.size(N, K); + std::vector v(128); + for (int64_t n = 0; n < N; ++n) + for (int64_t g = 0; g < nkb; ++g) { + for (int64_t j = 0; j < 128; ++j) v[(size_t)j] = wsrc[(size_t)(n * K + g * 128 + j)]; + if (rot) h_fwht(v.data(), 128); + float amax = 0.0f; + for (float x : v) amax = std::max(amax, std::fabs(x)); + rad_store_f32(p.data[1].data(), RAD_BF16, n * nkb + g, amax > 0 ? amax / 127.0f : 1.0f); + const float s = rad_load_f32(p.data[1].data(), RAD_BF16, n * nkb + g); + for (int64_t j = 0; j < 128; ++j) + p.data[0][(size_t)(n * K + g * 128 + j)] = + (uint8_t)(int8_t)std::max(-127.0f, std::min(127.0f, std::nearbyint(v[(size_t)j] / s))); + if (rot) rad_store_f32(p.data[1].data(), RAD_BF16, n * nkb + g, s / 128.0f); + } + return p; + }; + const Planes plain = planes(false), rotated = planes(true); + + /* The bytes, extents and arrangement of the two forms are identical, so the encoding is the + * only guard: each dtype takes its own and refuses the other, under tags of their own. */ + { + const std::vector lp8 = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8") }; + const std::vector lp8h = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8h") }; + std::vector scratch; + RadLayout lplain{}, lrot{}; + const int own_plain = stored(r, lp8, 2, plain, { "codes" }, &scratch, &lplain); + const int own_rot = stored(r, lp8h, 2, rotated, { "codes" }, &scratch, &lrot); + const int cross_a = stored(r, lp8, 2, rotated, { "codes" }, &scratch); + const int cross_b = stored(r, lp8h, 2, plain, { "codes" }, &scratch); + const bool tags = lplain.tag && lrot.tag && std::strcmp(lplain.tag, lrot.tag) != 0; + const std::string what = std::string(row) + ": i8a8 and i8a8h each take only their own encoding"; + ok(what.c_str(), own_plain == RAD_OK && own_rot == RAD_OK && cross_a == RAD_E_DTYPE && + cross_b == RAD_E_DTYPE && tags, + "own " + std::to_string(own_plain) + "/" + std::to_string(own_rot) + ", crossed " + + std::to_string(cross_a) + "/" + std::to_string(cross_b) + ", tags " + + (lplain.tag ? lplain.tag : "(none)") + " / " + (lrot.tag ? lrot.tag : "(none)")); + } + + auto launch = [&](const RadKernelInfo* k, std::vector ts, std::vector ps) { + 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; + if (k->scratch) { + const int64_t need = k->scratch(&a); + if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; } + } + const int rc = k->launch(&a, (RadStream) nullptr); + return rc == RAD_OK && st_stream_sync(nullptr) == hipSuccess ? RAD_OK : (rc ? rc : -1); + }; + + void* d_x = dalloc(xbf.size() * 2); + void* d_q = dalloc((size_t)(M * K)); + void* d_qs = dalloc((size_t)(M * nkb) * 4); + void* d_y = dalloc((size_t)(M * N) * 2); + if (!d_x || !d_q || !d_qs || !d_y) { ok(nm, false, "hipMalloc failed"); return; } + st_memcpy(d_x, xbf.data(), xbf.size() * 2, hipMemcpyHostToDevice); + + /* rel_l2 of one pairing against the reference, or -1 when something refused to run. */ + auto measure = [&](const Planes& p, const char* dt, const RadKernelInfo* quant) -> double { + const std::vector lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", dt) }; + std::vector wq, wsc; + if (stored(r, lp, 2, p, { "codes" }, &wq) != RAD_OK || + stored(r, lp, 3, p, { "scale" }, &wsc) != RAD_OK) + return -1.0; + void* d_w = dalloc(wq.size()); + void* d_s = dalloc(wsc.size()); + if (!d_w || !d_s) return -1.0; + st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice); + st_memcpy(d_s, wsc.data(), wsc.size(), hipMemcpyHostToDevice); + if (launch(quant, { T(d_x, RAD_BF16, { M, K }), T(d_q, RAD_I8, { M, K }), + T(d_qs, RAD_F32, { M, nkb }) }, + { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16") }) != RAD_OK) + return -1.0; + std::vector ts = { + T(d_q, RAD_I8, { M, K }), T(d_qs, RAD_F32, { M, nkb }), T(d_w, RAD_I8, { N, K }), + T(d_s, RAD_BF16, { N, nkb }), T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), + T(nullptr, RAD_U8, { 1 }), + }; + absent(ts[5]); absent(ts[6]); + if (launch(r, ts, { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", dt) }) + != RAD_OK) + return -1.0; + std::vector got((size_t)(M * N)); + st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost); + double num = 0.0, den = 0.0; + for (int64_t i = 0; i < M * N; ++i) { + const double d = (double)h_bf16(got[(size_t)i]) - want[(size_t)i]; + num += d * d; + den += want[(size_t)i] * want[(size_t)i]; + } + return den > 0.0 ? std::sqrt(num / den) : -1.0; + }; + const double e_plain = measure(plain, "i8a8", qp); + const double e_rot = measure(rotated, "i8a8h", qh); + const double e_cross = measure(rotated, "i8a8h", qp); + + /* Printed either way: the pass is about the plumbing, the numbers about the format. An int8 + * pair lands at a few parts in a thousand; the failures the bounds catch are far off. An + * output off by a constant c measures |1 - c|, so a 1/128 never divided out measures ~127, + * and a 1/sqrt(128) folded on the activation side too (the per-row had_*_i8 convention) + * ~0.91. */ + std::printf(" rel_l2 vs f32: i8a8 %.4f, i8a8h %.4f, rotated weight with the plain " + "quantiser %.4f\n", e_plain, e_rot, e_cross); + ok(nm, e_plain >= 0.0 && e_rot >= 0.0 && e_cross >= 0.0 && e_plain < 0.05 && e_rot < 0.05 && + e_rot < e_plain && e_cross > 0.5, + "rel_l2 i8a8 " + std::to_string(e_plain) + ", i8a8h " + std::to_string(e_rot) + + ", crossed " + std::to_string(e_cross)); +} + /* The tiled bf16 GEMM against the skinny one, byte for byte, at every tile variant. An op over * M 1..max_tok is served by the skinny row at M <= 64 and the tiled one above, so they must agree @@ -19406,6 +19573,9 @@ static void device_phase(const Plugin& pl) { bias_gemm_numeric(pl, 520, 1040, 1104, 0, true, true); bias_gemm_numeric(pl, 2050, 600, 40, 2, false, true); bias_gemm_numeric(pl, 200, 300, 136, 2, true, false); + i8a8h_rot(pl, "gemm_i8a8_nt_m16", 1, 256, 1024); + i8a8h_rot(pl, "gemm_i8a8_nt_m16", 16, 256, 1024); + i8a8h_rot(pl, "gemm_i8a8_tiled", 200, 256, 1024); w8a16_numeric(pl, "gemm_w8a16_nt_m64", 5, 272, 384, RAD_F16); w8a16_numeric(pl, "gemm_w8a16_nt_m64", 64, 2560, 6144, RAD_F16); gemm_case(pl, "gemm_w4a8_nt_m64", "w4a8", M, N, K, RAD_I8, 1, 0, 0, N*K/2, N*(K/128)*4); From 037427e67e63cd1dcf93da71001c4671378366d7 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 15:42:07 +0800 Subject: [PATCH 022/152] tests: a rotated int8 group decodes back through the Hadamard libquant's rtn at codes=i8 group=128 scale=bf16 transform=fwht128, decoded through the core: the weight gemm_nt_q reads at i8a8h comes back as its source, with less error than the plain grid on a source with outliers. Co-Authored-By: Claude Opus 5.5 --- tests/quant_test.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/quant_test.cpp b/tests/quant_test.cpp index 6f24d9b5..d318459b 100644 --- a/tests/quant_test.cpp +++ b/tests/quant_test.cpp @@ -81,6 +81,30 @@ TEST(a_rotated_int4_group_decodes_back_through_the_hadamard) { CHECK(eb < ea); } +TEST(a_rotated_int8_group_decodes_back_through_the_hadamard) { + NEED_LIBQUANT(); + /* What gemm_nt_q reads at dtype i8a8h: i8 codes with a bf16 scale a (row, 128), each group + * rotated by the unnormalised Hadamard and the 1/128 in the stored scale. A scale that kept + * the factor, or lost it twice, decodes 128 times off, and a skipped rotation to noise. */ + const int64_t R = 32, C = 512; + const std::vector w = draw(R * C, 2, 30.0f); + Opts plain, rot; + plain.s("codes", "i8").i("group", 128).s("scale", "bf16"); + rot.s("codes", "i8").i("group", 128).s("scale", "bf16").s("transform", "fwht128"); + Quantised a = quantise(quantizer("rtn"), plain, "x", R, C, w); + Quantised b = quantise(quantizer("rtn"), rot, "x", R, C, w); + REQUIRE_EQ(a.status, RAD_OK); + REQUIRE_EQ(b.status, RAD_OK); + CHECK_EQ(enc_name(b.enc), std::string("i8*bf16[1x128]/fwht128")); + const double ea = rel_err(w, decode(a, R, C)), eb = rel_err(w, decode(b, R, C)); + std::fprintf(stderr, " int8 g128: plain %.5f, rotated %.5f\n", ea, eb); + /* An int8 grid's error is a few parts in a thousand; with outliers the rotation is again the + * better grid. */ + CHECK(ea < 0.03); + CHECK(eb < 0.01); + CHECK(eb < ea); +} + TEST(the_w4nl_table_is_exact_in_e4m3_and_beats_minus_8_to_7_after_the_rotation) { NEED_LIBQUANT(); /* The sixteen levels libr4d's w4nla8h kernel decodes, in its code order, as a container From 61afe50b9665df84a717009e57bfce9b239119f5 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 15:42:07 +0800 Subject: [PATCH 023/152] libref, libavx: had_quant_act_i8g, the activation of the i8a8h GEMMs had_quant_act_fp8 at int8 codes (top 127), one body shared by both in each library, so a rotated int8 trunk runs on the host kernels too. gemm_nt_q needs no change: both libraries pick the int8 product from the operands' dtypes, and i8a8h's rotation is in the values. libref's operand description takes i8a8h, and rad-avx-check gains cases for the op and the dtype. Co-Authored-By: Claude Opus 5.5 --- libavx/README.md | 2 +- libavx/avx_cases.cpp | 11 +++++++++-- libavx/avx_isa.h | 2 +- libavx/avx_quant.cpp | 16 +++++++++++++--- libavx/avx_registry.cpp | 7 +++++++ libref/ref_ops.h | 2 ++ libref/ref_quant.cpp | 17 ++++++++++++++--- libref/ref_registry.cpp | 10 ++++++++++ libref/ref_shapes.cpp | 15 ++++++++++++++- tests/ref_test.cpp | 13 +++++++++++++ 10 files changed, 84 insertions(+), 11 deletions(-) diff --git a/libavx/README.md b/libavx/README.md index 5c54742e..1b713975 100644 --- a/libavx/README.md +++ b/libavx/README.md @@ -78,7 +78,7 @@ Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the | `rope` | YaRN with `axial` or a position scale | the same | | `rope` | Llama 3 scaling beside YaRN, with `axial`, or over multi-component positions | the same | | `rope` | a rotary half-width over 1024 | the same | -| `had_quant_act_i8`, `had_quant_act_fp8`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) | +| `had_quant_act_i8`, `had_quant_act_fp8`, `had_quant_act_i8g`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) | | `gdn_conv_prep`, `gdn_conv_update` | a convolution history over 16 | the same | | `gdn_recurrent_update` | a `state_form` other than `per_candidate` or `anchor` | the same | | `ple_conv`, `causal_conv1d` | a history over 64 | the same | diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index b9f8d505..3e77b68e 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -153,6 +153,8 @@ std::vector build_cases() { HS("dtype", "bf16") }, EB(5, 256, 2, 1.5)); add("had_quant_act_fp8", { HI("M", 5), HI("n", 256), HI("group", group), HS("dtype", "bf16") }); + add("had_quant_act_i8g", { HI("M", 5), HI("n", 256), HI("group", group), + HS("dtype", "bf16") }); add("had_quant_act_i8", { HI("M", 5), HI("n", 256), HI("group", group), HS("dtype", "bf16") }); add("dequant", { HI("M", 5), HI("n", 256), HI("group", group), @@ -221,11 +223,14 @@ std::vector build_cases() { add("gemm_nt_q_bias", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128), HS("dtype", dt) }, 0, fl); } - /* The int8 trunk (row-major codes, a scale per row per 128 of K on both sides) and OCP-MXFP4 - * (e2m1 codes with an E8M0 exponent per 32 of K against the E4M3 activation). */ + /* The int8 trunk (row-major codes, a scale per row per 128 of K on both sides; i8a8h is the + * same operands over a rotated weight) and OCP-MXFP4 (e2m1 codes with an E8M0 exponent per 32 + * of K against the E4M3 activation). */ for (int M : { 1, 65 }) { add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128), HS("dtype", "i8a8") }, 0, 2.0 * M * 96 * 256); + add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128), + HS("dtype", "i8a8h") }, 0, 2.0 * M * 96 * 256); add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 32), HS("dtype", "mxfp4a8") }, 0, 2.0 * M * 96 * 256); } @@ -961,6 +966,8 @@ std::vector build_cases() { HS("dtype", "bf16") }, (double)M * 2048 * 3, 0); speed("quant_act_i8g", { HI("M", M), HI("n", 2048), HI("group", 128), HS("dtype", "bf16") }, (double)M * 2048 * 3, 0); + speed("had_quant_act_i8g", { HI("M", M), HI("n", 2048), HI("group", 128), + HS("dtype", "bf16") }, (double)M * 2048 * 3, 0); speed("had_quant_act_i8", { HI("M", M), HI("n", 2048), HI("group", 128), HS("dtype", "bf16") }, (double)M * 2048 * 3, 0); } diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 25a08142..ac0f9ed9 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -83,7 +83,7 @@ int avx_par_force(int threads); /* ---- quantisation and rotation */ \ X(quant_act_i8) X(quant_act_i8g) X(had_quant_act_i8) X(quant_act_fp8) \ X(had_quant_act_fp8) X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) \ - X(dequant) X(quant_cols_fp8) \ + X(dequant) X(quant_cols_fp8) X(had_quant_act_i8g) \ X(rmsnorm_quant_fp8) X(gated_quant_fp8) X(givens_rotate) X(givens_dense_quant) \ /* ---- gemm and the vocabulary edges */ \ X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \ diff --git a/libavx/avx_quant.cpp b/libavx/avx_quant.cpp index ed409cc8..3b01e96b 100644 --- a/libavx/avx_quant.cpp +++ b/libavx/avx_quant.cpp @@ -537,8 +537,10 @@ AVX_KERNEL(gated_quant_fp8) { * is scaled by. * * Unlike had_quant_act_i8, 1/sqrt(g) is not applied here. = g , and the whole g is - * divided out of the weight scale instead, where dividing a bf16 by a power of two is exact. */ -AVX_KERNEL(had_quant_act_fp8) { + * divided out of the weight scale instead, where dividing a bf16 by a power of two is exact. + * + * had_quant_act_i8g is the same at int8 codes (`top` 127), for the i8a8h weight. */ +static int had_quant_q8(const RadArgs* a, float top) { if (!rad_args_have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; const int64_t n = p_int(a, "n", 0); @@ -561,7 +563,7 @@ AVX_KERNEL(had_quant_act_fp8) { fwht_row(buf, n, g); for (int64_t gi = 0; gi < ngrp; ++gi) { float sc; - fp8_group(buf, out, gi * g, gi * g + g, &sc); + fp8_group(buf, out, gi * g, gi * g + g, &sc, top); stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } out_row(q, rowoff(q, r, n), n, out); @@ -569,6 +571,14 @@ AVX_KERNEL(had_quant_act_fp8) { return RAD_OK; } +AVX_KERNEL(had_quant_act_fp8) { + return had_quant_q8(a, 448.0f); +} + +AVX_KERNEL(had_quant_act_i8g) { + return had_quant_q8(a, 127.0f); +} + /* ------------------------------------------------------------- givens_rotate */ /* ParoQuant's activation side for a 16-bit GEMM: each row is divided by its channel scales and * rotated by `stages` rounds of disjoint Givens pairs, once per part, parts side by side in y. diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index d984c394..edb6ea5a 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -772,6 +772,9 @@ static const RadOpSchema kSchemas[] = { { "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8), "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser. No normalisation: " "the 1/group is folded into the stored weight scale at convert (docs/OPS.md)." }, +{ "had_quant_act_i8g", ARR(pQuant), ARR(oQuantFp8), + "width-`group` Hadamard, then quant_act_i8g's symmetric int8 per group. No normalisation: the " + "1/group is the i8a8h weight's stored scale (docs/OPS.md)." }, { "gram_accum", ARR(pQuant), ARR(oGram), "h += x^T x over a dequantised E4M3 activation. `h` is [n, n] and INOUT." }, { "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense), @@ -1244,6 +1247,10 @@ SIMPLE("avx_had_quant_act_fp8", "had_quant_act_fp8", "quant", "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; n a multiple of group", L(had_quant_act_fp8)), +SIMPLE("avx_had_quant_act_i8g", "had_quant_act_i8g", "quant", + "width-`group` Hadamard, then the symmetric int8 quantiser, one scale per group", + "float in, i8 out, f32 scale per group; n a multiple of group", + L(had_quant_act_i8g)), SIMPLE("avx_givens_rotate", "givens_rotate", "quant", "channel scale and Givens rotations per part, in the output's dtype", "float in, float out; int32 pairs, f32 angles and channel scales", L(givens_rotate)), diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 572eb574..2d9b6a86 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -103,6 +103,7 @@ int ref_had_quant_act_i8 (const RadArgs*, RadStream); int ref_quant_act_fp8 (const RadArgs*, RadStream); int ref_quant_cols_fp8 (const RadArgs*, RadStream); int ref_had_quant_act_fp8 (const RadArgs*, RadStream); +int ref_had_quant_act_i8g (const RadArgs*, RadStream); int ref_givens_dense_quant(const RadArgs*, RadStream); int ref_givens_rotate(const RadArgs*, RadStream); int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); @@ -309,6 +310,7 @@ REF_SHAPE_FN(ref_had_quant_act_i8); REF_SHAPE_FN(ref_quant_act_fp8); REF_SHAPE_FN(ref_quant_cols_fp8); REF_SHAPE_FN(ref_had_quant_act_fp8); +REF_SHAPE_FN(ref_had_quant_act_i8g); REF_SHAPE_FN(ref_givens_dense_quant); REF_SHAPE_FN(ref_givens_rotate); REF_SHAPE_FN(ref_rmsnorm_quant_fp8); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index f1fc7db8..85160e77 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -360,8 +360,11 @@ int ref_quant_cols_fp8(const RadArgs* a, RadStream) { * ~0.2% error per group (a fifth of the int4 grid's own error). * * The output is not interchangeable with quant_act_fp8's: only a weight plane stored as w4a8h - * carries the matching rotation and /g. */ -int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { + * carries the matching rotation and /g. + * + * had_quant_act_i8g is the same at int8 codes (`top` 127), for the i8a8h weight, whose scale + * carries the /g the same way. */ +static int had_quant_act_q8(const RadArgs* a, float top) { if (!have(a, 3)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2]; const int64_t n = p_int(a, "n", 0); @@ -383,7 +386,7 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { const int64_t k0 = gi * g; for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs); fwht(buf, g); - const float sc = q8_group([&](int64_t i) { return buf[i]; }, g, 448.0f, q, + const float sc = q8_group([&](int64_t i) { return buf[i]; }, g, top, q, qb + k0 * qs, qs); stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc); } @@ -391,6 +394,14 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { return RAD_OK; } +int ref_had_quant_act_fp8(const RadArgs* a, RadStream) { + return had_quant_act_q8(a, 448.0f); +} + +int ref_had_quant_act_i8g(const RadArgs* a, RadStream) { + return had_quant_act_q8(a, 127.0f); +} + /* ------------------------------------------------------------- givens_rotate */ /* ParoQuant's activation side: each row divided by its channel factors and rotated by `stages` * rounds of disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 6b6a55d9..fc91dc28 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -1062,6 +1062,12 @@ static const RadOpSchema kSchemas[] = { "amax(rotated) / 448, shaped [M, n/group] in f32. n must be a multiple of `group` -- a rotation " "block cannot straddle the end of a row. NOT interchangeable with quant_act_fp8 in either " "direction: the consumer must be a weight that was rotated the same way." }, +/* Its int8 twin, the activation of the i8a8h GEMMs; the factor of `group` is the weight's here + * too. */ +{ "had_quant_act_i8g", ARR(pQuant), ARR(oQuantFp8), + "quant_act_i8g with a Walsh-Hadamard rotation of width `group` along n first: scale = " + "amax(rotated) / 127 per group, [M, n/group] in f32, n a multiple of `group`. Pairs with an i8 " + "weight rotated the same way, its scale carrying the factor of `group` (dtype i8a8h)." }, /* The calibration op, the only one no forward pass issues: it runs under a calibration flag and * its output is read at convert time, in another process, through a file. `dtype` is the input's: * fp8a8 where the tap is a quantiser's output, bf16 without `a_scale` for a plain activation. */ @@ -1788,6 +1794,10 @@ SIMPLE("ref_had_quant_act_fp8", "had_quant_act_fp8", "quant", "width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser", "float in, fp8_e4m3 out, f32 scale per group; n a multiple of group", ref_had_quant_act_fp8), +SIMPLE("ref_had_quant_act_i8g", "had_quant_act_i8g", "quant", + "width-`group` Hadamard, then the symmetric int8 quantiser, one scale per group", + "float in, i8 out, f32 scale per group; n a multiple of group", + ref_had_quant_act_i8g), SIMPLE("ref_gram_accum", "gram_accum", "quant", "h += x^T x over a dequantised E4M3 activation, or a plain bf16 one -- the Gram matrix " "GPTQ calibrates on", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 4ba50cac..b3dc8a6e 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -863,6 +863,18 @@ int ref_had_quant_act_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdD return o.finish("had_quant_act_fp8", operand, out); } +/* quant_act_i8g's extents: the rotation changes the values, not the shapes. */ +int ref_had_quant_act_i8g_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + Opd o; + o.t(D, { M, n }); /* x */ + o.t((uint32_t)RAD_I8, { M, n }); /* q */ + o.t((uint32_t)RAD_F32, { M, ng }); /* scale (amax / 127) */ + return o.finish("had_quant_act_i8g", operand, out); +} + /* The int8 rotated forms: `group` is the Walsh-Hadamard rotation width (libr4d's `had`) and the * scale is one per row, carrying the 1/sqrt(group) normalisation (ref_quant.cpp). Describing it as * [M, n/group] would leave the tail of every scale buffer unwritten by both sides, comparing two @@ -960,7 +972,8 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO const char* q = gs(p, n_p, "dtype"); auto is = [&](const char* s) { return q && std::strcmp(q, s) == 0; }; const bool a8 = is("fp8a8"), a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8"); - const bool i8 = is("i8a8"), mx = is("mxfp4a8"); + /* i8a8h is i8a8's operands; its rotation is in the values. */ + const bool i8 = is("i8a8") || is("i8a8h"), mx = is("mxfp4a8"); if ((!a8 && !a16 && !w4 && !w8 && !i8 && !mx) || N <= 0 || K <= 0 || group <= 0) return RAD_E_UNSUPPORTED; /* Neither has a bias form in any architecture. */ diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 6c654797..e81fafd7 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -264,6 +264,7 @@ TEST(op_vocabulary) { "scale_rows", "softmax", "quant_act_i8", "quant_act_i8g", "quant_act_fp8", "quant_cols_fp8", "had_quant_act_fp8", "givens_dense_quant", "givens_rotate", "had_quant_act_i8", + "had_quant_act_i8g", "gram_accum", /* The fused fp8 forms. A host run needs every op covered, so these keep a host-backend run * from failing with "site 'host' is unavailable for this band". */ @@ -6435,6 +6436,17 @@ TEST(had_quant_act_fp8_rotates_before_the_absmax) { CHECK_EQ(q.at(2), 0.0f); CHECK_EQ(q.at(3), 448.0f); } +/* had_quant_act_i8g is the same at int8 codes: amax / 127, nothing folded either. */ +TEST(had_quant_act_i8g_rotates_before_the_absmax) { + T x(RAD_F32, {1, 4}); x.f({1, 1, 1, -1}); + T q(RAD_I8, {1, 4}), s(RAD_F32, {1, 2}); + A a; a.t(x).t(q).t(s).i("M", 1).i("n", 4).i("group", 2).s("dtype", "f32"); + CHECK_OK(run("had_quant_act_i8g", a)); + CHECK_EQ(s.at(0), 2.0f / 127.0f); CHECK_EQ(s.at(1), 2.0f / 127.0f); + CHECK_EQ(q.at(0), 127.0f); CHECK_EQ(q.at(1), 0.0f); + CHECK_EQ(q.at(2), 0.0f); CHECK_EQ(q.at(3), 127.0f); +} + namespace { void put_pair(T& t, int64_t i, int32_t id, float v) { std::memcpy((float*)t.t.data + 2 * i, &id, 4); @@ -6898,6 +6910,7 @@ std::vector geometries() { G("quant_act_fp8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")), G("quant_cols_fp8", "M", 3, a.i("M", R).i("n", 32).s("dtype", "f32")), G("had_quant_act_fp8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")), + G("had_quant_act_i8g", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")), G("had_quant_act_i8", "M", 3, a.i("M", R).i("n", 32).i("group", 16).s("dtype", "f32")), G("rmsnorm_had_quant_i8", "M", 3, a.i("M", R).i("n", 32).d("eps", 1e-6).i("group", 16) .s("dtype", "f32")), From f706caececa16ba4efc7f979eb0fc91628812a9c Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 15:42:07 +0800 Subject: [PATCH 024/152] docs: i8a8h in OPS.md's dtype list; had_quant_act_i8g folds nothing Its consumer's scale carries the whole 1/group, as had_quant_act_fp8's does; the per-row had_* int8 forms fold 1/sqrt(group) and are not interchangeable with it. TOOLS.md: libr4d reads the int8 block rows rotated too. Co-Authored-By: Claude Opus 5.5 --- docs/OPS.md | 16 +++++++++++----- docs/TOOLS.md | 10 +++++----- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index 71719d4a..81c231ab 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -40,11 +40,14 @@ here is such a choice. otherwise; strides are the kernel's business, not the schema's. - Where an op takes `dtype`, it is a string naming the operand combination, so a weight format and an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`, `u8`, `fp8_e4m3`, - `fp8a8`, `fp8a16`, `i8a8`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`, `w8a16`, `w2a8`, - `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`, and the codebook expert forms - `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` (`docs/MOE-W4.md`). + `fp8a8`, `fp8a16`, `i8a8`, `i8a8h`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`, + `w8a16`, `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`, and the codebook + expert forms `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` (`docs/MOE-W4.md`). - `w4a8h` is `w4a8` with a `group`-wide Walsh–Hadamard along K baked into the stored weight (`docs/MOE-W4.md`). + - `i8a8` is an i8 weight with a bf16 scale per (row, 128 of K) against an int8 activation on + the same grid; `i8a8h` is that weight rotated by a 128-wide Walsh–Hadamard along K, its scale + carrying the 1/128 (libquant's `transform=fwht128`), met by `had_quant_act_i8g`. - `w4a8_asym` is the unsigned-nibble-minus-zero-point grid instead of the symmetric one. - `fp8a8` and `fp8a16` say whether a block-scaled E4M3 weight meets an fp8 or a bf16 activation. - `w5a16` and `w4a16_asym` are ParoQuant's int5 and z-lab's int4 (u5 / u4 codes, an f16 scale and @@ -470,8 +473,11 @@ not slow. `libref/ref_quant.cpp` is the definition. (`group <= 0` or `group >= n` is one per row). The scale is `amax / 127` (1 for a zero group) and each code the value over it rounded to nearest even and clamped to ±127, row-major. They feed the int8 trunk GEMM (`gemm_nt_q` at `dtype=i8a8`), which folds a scale per K block. The `had_` form - rotates first. `dequant` inverts `quant_act_i8g`: the scale stream's extent gives the group count - and `group` each group's width. + rotates first and, like `had_quant_act_fp8`, folds nothing: its consumer is a weight at + `dtype=i8a8h`, whose scale carries the whole 1/`group`. It is not interchangeable with the + per-row `had_*` int8 forms, which fold 1/sqrt(`group`) into the activation's scale. `dequant` + inverts `quant_act_i8g`: the scale stream's extent gives the group count and `group` each group's + width. The rotation is unnormalised butterflies at ascending strides `1, 2, 4, ... group/2`, pairing `i` with `i + h` where `(i & h) == 0`. The `1/sqrt(group)` is folded into the scale rather than applied diff --git a/docs/TOOLS.md b/docs/TOOLS.md index bba746bf..40bd4843 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -204,11 +204,11 @@ group=32 scale=u6 scale2=f16 group2=256`; a ternary BitNet weight is `table=tern A container can hold only what some kernel reads. The converter checks every planned encoding against the layout hooks of the kernels declare resolved and refuses one that no kernel accepts, so a grid libquant can write is usable only once a kernel library takes it. libr4d reads the plain -floats; block-scaled fp8 and fp8 rows; int8 block rows (the W8A8 trunk and lm_head); the routed -experts as fp8, int4 (`i4*bf16[1x128]/fwht128`) or the `w4nl`/`w5nl` codebooks under E4M3 scales -([MOE-W4.md](MOE-W4.md)); the dense w4, w8 and mxfp4 GEMM rows; and the 2-bit draft head. Every -encoding also decodes through the core, which the converter's error report, the oracle and the -quantisers' tests use. +floats; block-scaled fp8 and fp8 rows; int8 block rows (the W8A8 trunk and lm_head), plain or +rotated (`i8*bf16[1x128]/fwht128`); the routed experts as fp8, int4 (`i4*bf16[1x128]/fwht128`) or +the `w4nl`/`w5nl` codebooks under E4M3 scales ([MOE-W4.md](MOE-W4.md)); the dense w4, w8 and mxfp4 +GEMM rows; and the 2-bit draft head. Every encoding also decodes through the core, which the +converter's error report, the oracle and the quantisers' tests use. The recipes for the containers this tree serves are in `data/recipes/`. `scripts/convfn.sh` and `scripts/convdspark.sh` are the reference conversions. From 0b0403603badfc7f77e37a6c7a1f840b2e15704b Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 18:30:50 +0800 Subject: [PATCH 025/152] core: an architecture plugin can decline imported checkpoints An imported quantisation names its tool, which no plugin claims, so the family's one quantised plugin serves it and two are refused. rad_arch_serves_imports(), optional and absent = yes, lets a second quantised plugin that reads only its own containers return 0: the import pick then leaves it out of the family, neither counted nor picked as the only plugin. Its own descriptor still selects it. Additive export; RAD_ABI_VERSION does not move. Co-Authored-By: Claude Opus 5.5 --- abi/rad_builder.h | 8 ++++++++ arch/common/rad_arch.h | 5 +++++ core/build/startup.cpp | 6 ++++-- core/build/startup.h | 3 ++- core/plugin/loader.cpp | 3 +++ core/plugin/registry.h | 3 +++ core/plugin/testplugin/CMakeLists.txt | 5 +++++ core/plugin/testplugin/testplugin.cc | 4 ++++ docs/PLUGIN.md | 6 ++++++ tests/build_test.cpp | 17 +++++++++++++++-- 10 files changed, 55 insertions(+), 5 deletions(-) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index e91eb808..d9b667af 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -926,6 +926,14 @@ const char* rad_arch_id(void); * served at: (unquantised)". */ const char* rad_arch_quant(void); +/* Whether this plugin may serve a checkpoint whose quantisation was imported weight by weight + * (Quark, ParoQuant, GPTQ, NVFP4, ...). Such a descriptor names the producing tool, which no plugin + * claims, so the family's one quantised plugin serves it, and two are refused (startup.h). A + * family's second quantised plugin that reads only its own containers returns 0 and leaves imports + * to the first. Optional: absent or non-zero is yes. Additive export; RAD_ABI_VERSION does not + * move. */ +int rad_arch_serves_imports(void); + /* What the plugin can say before it declares anything. Optional: a plugin that does not export * it answers zero to everything, each field's default. * diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index a160909e..d593f816 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -1331,6 +1331,11 @@ inline int drafter_kv_group(RadBuilder* b, Names& nm, const RadBuildCtx* ctx, Ge return NS::audio_format(m); \ } +/* Optional: RAD_ARCH_SERVES_IMPORTS(0) keeps a family's second quantised plugin out of the pick for + * an imported checkpoint (rad_builder.h, rad_arch_serves_imports). */ +#define RAD_ARCH_SERVES_IMPORTS(V) \ + extern "C" int rad_arch_serves_imports(void) { return V; } + } /* namespace arch */ } /* namespace rad */ diff --git a/core/build/startup.cpp b/core/build/startup.cpp index a901400d..fe5178ad 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -173,11 +173,13 @@ int rad_tools_load_plugins(const std::string& home, const std::vectorarch_plugin.empty()) { std::vector fam, quantised; for (const Plugin& p : r.plugins()) - if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id) { + if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id && p.arch_serves_imports) { fam.push_back(&p); if (!p.arch_quant.empty()) quantised.push_back(&p); } diff --git a/core/build/startup.h b/core/build/startup.h index 46eee91c..d84b7ab7 100644 --- a/core/build/startup.h +++ b/core/build/startup.h @@ -67,7 +67,8 @@ std::string rad_home_file(const std::string& home, const std::string& rel); * `imported`: the checkpoint's quantisation is imported weight by weight (Checkpoint::imports), so * its descriptor names the producing tool and no plugin claims it. The family's quantised plugin * serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised - * plugins are refused by name. `out->arch_quant` is the chosen descriptor, which a container + * plugins are refused by name. A plugin whose rad_arch_serves_imports returns 0 is left out of + * both counts. `out->arch_quant` is the chosen descriptor, which a container * converted from it records. */ int rad_tools_load_plugins(const std::string& radiance_home, const std::vector& hierarchy, diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 8a496f6d..8af65715 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -208,6 +208,9 @@ int Registry::commit_(Staged& s, int order) { * container, which "" means. */ if (auto q_fn = dl_fn(s.handle, "rad_arch_quant")) p.arch_quant = or_empty(q_fn()); + /* Optional: absent means the plugin may serve an imported quantisation (startup.h). */ + if (auto i_fn = dl_fn(s.handle, "rad_arch_serves_imports")) + p.arch_serves_imports = i_fn() != 0; /* Optional: answers what the core needs before it builds the RadBuildCtx for declare. * Absent means every answer is zero (rad_builder.h). */ diff --git a/core/plugin/registry.h b/core/plugin/registry.h index 3f773fd2..65fea419 100644 --- a/core/plugin/registry.h +++ b/core/plugin/registry.h @@ -94,6 +94,9 @@ struct Plugin { int64_t (*arch_text_prepare)(int, const char*, char*, int64_t) = nullptr; /* Required of a video generator (rad_builder.h); null for every other plugin. */ int64_t (*arch_video_positions)(int, const RadVideoGeom*, float*, int64_t) = nullptr; + /* Optional (rad_builder.h, rad_arch_serves_imports); absent is true. False keeps the plugin + * out of the pick for an imported checkpoint (startup.h). */ + bool arch_serves_imports = true; RadPluginCloseFn close = nullptr; }; diff --git a/core/plugin/testplugin/CMakeLists.txt b/core/plugin/testplugin/CMakeLists.txt index 1681e0e4..39912275 100644 --- a/core/plugin/testplugin/CMakeLists.txt +++ b/core/plugin/testplugin/CMakeLists.txt @@ -60,6 +60,11 @@ foreach(q plain fp8 w4) RADTEST_ARCHQ_NAME="radtest_archq_${q}" RADTEST_ARCHQ_QUANT="${_rad_q}") endforeach() +# A fourth member, quantised but declining imported checkpoints (rad_arch_serves_imports). +rad_add_plugin(radtest_archq_w8 testarchq SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/testplugin.cc) +target_compile_definitions(radtest_archq_w8 PRIVATE RADTEST_ARCHQ=1 + RADTEST_ARCHQ_NAME="radtest_archq_w8" RADTEST_ARCHQ_QUANT="w8" + RADTEST_ARCHQ_NO_IMPORTS=1) # KV tier transfer test plugin. Unlike the others it computes (byte-row gather and scatter in the # device domain, on host backend memory), so only tests/mem_test.cpp loads it, by path. It calls diff --git a/core/plugin/testplugin/testplugin.cc b/core/plugin/testplugin/testplugin.cc index 08bb9ea8..7c28d052 100644 --- a/core/plugin/testplugin/testplugin.cc +++ b/core/plugin/testplugin/testplugin.cc @@ -623,6 +623,10 @@ const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } const char* rad_arch_id(void) { return RADTEST_ARCH_ID; } /* The other half of the selection key (spec §2.4); "" is an unquantised container. */ const char* rad_arch_quant(void) { return RADTEST_ARCH_QUANT; } +#if defined(RADTEST_ARCHQ_NO_IMPORTS) +/* Quantised, but never the plugin an imported checkpoint is handed to. */ +int rad_arch_serves_imports(void) { return 0; } +#endif /* The core loads and identifies architecture plugins; the build component drives them. Neither * hook is called by anything this test exercises, and declare refuses rather than pretending. */ int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md index 2c11410e..87970c5e 100644 --- a/docs/PLUGIN.md +++ b/docs/PLUGIN.md @@ -333,6 +333,7 @@ them by that spelling. ```c const char* rad_arch_id(void); /* "llama" -- what a container's header names */ const char* rad_arch_quant(void); /* optional: "" unquantised, or the descriptor served */ +int rad_arch_serves_imports(void); /* optional: 0 declines an imported quantisation */ int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx); void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch); int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); /* optional */ @@ -346,6 +347,11 @@ underscores; `rad-convert --arch ID` overrides it. Every configuration key reach `RadModelMeta`, and the plugin's name map says which checkpoint tensor each declared weight comes from, so `rad-convert` needs no knowledge of the model. +A checkpoint whose quantisation was imported weight by weight (GUIDE §3.2: Quark, ParoQuant, GPTQ, +NVFP4) names its producing tool, which no plugin claims; it goes to the family's one quantised +plugin, and two are refused by name. A second quantised plugin that reads only its own containers +says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep their plugin. + - **Ops from `docs/OPS.md` run on any library.** An op libref implements has a host fallback, an oracle and a specification to check kernel libraries against. An op you invent runs only on a library that implements it. diff --git a/tests/build_test.cpp b/tests/build_test.cpp index 73bb6f94..39a12e3f 100644 --- a/tests/build_test.cpp +++ b/tests/build_test.cpp @@ -1944,7 +1944,8 @@ TEST(the_home_search_path_splits_on_colons_and_the_first_home_with_a_file_wins) * selected by the (id, quantisation) pair, exactly. A checkpoint whose quantisation was imported * weight by weight names its producing tool, which no plugin claims: the family's one quantised * plugin serves it (or its only plugin), and two quantised plugins are refused by name rather than - * chosen between. */ + * chosen between. A plugin that declines imports (rad_arch_serves_imports, radtest_archq_w8) is + * still selected by its own descriptor, but is neither counted nor picked for an import. */ TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) { const std::string archq = home() + "/testarchq"; NEED_ARTIFACT(archq + "/radtest_archq_fp8.so"); @@ -1978,7 +1979,9 @@ TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) { const std::string all = make_home({ "plain", "fp8", "w4" }); const std::string one = make_home({ "plain", "fp8" }); const std::string bare = make_home({ "plain" }); - REQUIRE(!all.empty() && !one.empty() && !bare.empty()); + const std::string w8 = make_home({ "plain", "fp8", "w8" }); + const std::string plain_w8 = make_home({ "plain", "w8" }); + REQUIRE(!all.empty() && !one.empty() && !bare.empty() && !w8.empty() && !plain_w8.empty()); LoadedPlugins lp; std::string log; @@ -2000,6 +2003,16 @@ TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) { CHECK_OK(pick(bare, "quark-mxfp4", true, &lp, &log)); CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_plain")); CHECK_EQ(pick(all, "fp8", false, &lp, &log), RAD_OK); + + /* A second quantised plugin that declines imports leaves them to the first. */ + CHECK_OK(pick(w8, "quark-mxfp4", true, &lp, &log)); + CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_fp8")); + CHECK(!has(log, "more than one quantised plugin")); + CHECK_OK(pick(w8, "w8", false, &lp, &log)); + CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_w8")); + CHECK_EQ(lp.arch_quant, std::string("w8")); + CHECK_OK(pick(plain_w8, "quark-mxfp4", true, &lp, &log)); + CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_plain")); rad_tools_registry().close(); } From 3c01aacef2feb9d5eb1a88f0c4a753fac4cbf180 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 15:42:07 +0800 Subject: [PATCH 026/152] arch/common: LinearFP8 serves a rotated int8 weight at i8a8h behind had_quant_act_i8g linear_is_w8h recognises i8*bf16[1x128]/fwht128; probe() reports it as int8 so the producer writes the bf16 plane, and declare() quantises it with had_quant_act_i8g. A rotated weight fed codes its producer wrote (ActFP8::q8_fed) is refused: those codes are unrotated. Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_fp8.h | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index fe5058a2..e1f57cc5 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -762,6 +762,17 @@ inline bool linear_is_w8(const RadEncoding& e) { sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK; } +/* The same planes rotated by the unnormalised 128-wide Hadamard along K, the 1/128 in the scale + * (libquant's `transform=fwht128`), served at i8a8h behind had_quant_act_i8g. */ +inline bool linear_is_w8h(const RadEncoding& e) { + if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || + std::strncmp(e.transform, "fwht128", RAD_ENC_STR) != 0) + return false; + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_BF16 && + sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK; +} + /* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes and an E8M0 exponent per [1 x 32], * no transform (libr4d's MXFP4 layout hook). */ enum { RAD_MX_GROUP = 32 }; @@ -823,7 +834,7 @@ inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* const bool known = weight_enc(b, wn, &enc); const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16; - probed_i8 = known && linear_is_w8(enc); + probed_i8 = known && (linear_is_w8(enc) || linear_is_w8h(enc)); /* A rotated weight rotates and quantises the bf16 plane itself; a 4-bit one casts or * quantises it. */ const bool rotated = known && (linear_is_paro_mxfp4(enc) || linear_is_paro_w5(enc)); @@ -981,9 +992,18 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha /* ---- int8 weight, `gemm_nt_q` at i8a8 over the input's `a.q8` / `a.s8`. The scale plane is * one bf16 per row per 128 of K: row parts and row slices apply as is, column slices in groups * of 128. The codes come from the producer (ActFP8::q8_fed) or from op_q over `a.x` (probe() - * set reads_x). The model must have declared the pair (ActFP8::declare_qs's `i8`). */ - i8 = known && linear_is_w8(enc); + * set reads_x). The model must have declared the pair (ActFP8::declare_qs's `i8`). + * + * A rotated weight (i8a8h) takes had_quant_act_i8g instead, so it always quantises its own + * input: a producer's codes are unrotated. */ + const bool rot8 = known && linear_is_w8h(enc); + i8 = known && (linear_is_w8(enc) || rot8); if (i8) { + if (rot8 && a.q8_fed) { + fprintf(stderr, "radiance: '%s' is a rotated int8 weight and its input is fed codes " + "its producer wrote unrotated\n", wn); + return RAD_E_DTYPE; + } if (!a.x || !a.q8 || !a.s8) { fprintf(stderr, "radiance: '%s' is an int8 weight and its input lacks the bf16 plane " "or the int8 code pair (the model declared its input before learning " @@ -1018,14 +1038,15 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha } const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; if (!a.q8_fed) - op_q = rw(b, RAD_OP(b, "quant_act_i8g", + op_q = rw(b, RAD_OP(b, rot8 ? "had_quant_act_i8g" : "quant_act_i8g", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("n", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), { a.x }, { a.q8, a.s8 }); op = rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8")), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", rot8 ? "i8a8h" : "i8a8")), RAD_WEIGHTS(w, ws)), { a.q8, a.s8 }, { y }); return (op_q || a.q8_fed) && op ? RAD_OK : RAD_E_INVAL; From 2ac0d966b3f6115c18ffa73d8f02f022f17a5bcd Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 15:42:07 +0800 Subject: [PATCH 027/152] arch/common: the MLP's gated fold is an fp8a8 tile; an int8 gate_up takes the pair decl_gated_fold was declared for any gate_up that was not bf16, MXFP4 or rotated 5-bit, so an int8 one got an fp8a8 fold over int8 codes. Only a host kernel took the op, and placement then pinned every layer group's weights to the host. Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_block_mlp_fp8.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index 18485a41..ddb5dfd9 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -98,9 +98,10 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down })); RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x)); - /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4, rotated 5-bit and 4-bit gate_up - * weights take the pair. */ - if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4) + /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4, rotated 5-bit, 4-bit and int8 + * gate_up weights take the pair. Declared over int8 codes, only a host kernel would take it, + * and that would pin the layer's weights to the host. */ + if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, { w.h.q, w.h.s }, gq_ffn.want_x From 5d11c7c20039aaaacd41c1621379ea05bb1c8239 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 15:42:07 +0800 Subject: [PATCH 028/152] qwen35_w8a8: qwen35_fp8.cpp built for a rotated int8 trunk A third build of the qwen35 source, as qwen35moe_fp8 is, claiming (qwen35, w8a8_fwht128). Behind QWEN35_W8A8: check_format's method and fmt, a probe of the first delta-net input projection that learns the trunk is rotated int8 before the activations are declared (and refuses one that is not, plain int8 included: the descriptor names the rotation), and the plugin identity; the four trunk activations then carry int8 code pairs. It declines imported checkpoints (RAD_ARCH_SERVES_IMPORTS(0)): as the family's second quantised plugin it would make every imported Qwen3.8 release (Quark, ParoQuant, GPTQ, NVFP4) refuse, so those stay with qwen35_fp8. arch_test: every trunk linear an i8a8h GEMM behind its own quantiser at one and two ranks, the refusals (no int8 trunk, a plain one, another format, no fmt), lint clean with the MTP head and with DFlash2, and two ArchCases (pinned graphs; libref's vocabulary serves it at one rank). shipped_plugins_test lists the new key and holds each shipped family to at most one plugin that takes imports. ARCHITECTURES.md and GUIDE.md list the plugin. Co-Authored-By: Claude Opus 5.5 --- arch/qwen35_fp8/qwen35_fp8.cpp | 86 ++++++++++++++++++-- arch/qwen35_w8a8/CMakeLists.txt | 10 +++ arch/qwen35_w8a8/qwen35_w8a8.cpp | 19 +++++ docs/ARCHITECTURES.md | 24 ++++++ docs/GUIDE.md | 1 + tests/arch_test.cpp | 133 +++++++++++++++++++++++++++++++ tests/shipped_plugins_test.cpp | 32 +++++++- 7 files changed, 298 insertions(+), 7 deletions(-) create mode 100644 arch/qwen35_w8a8/CMakeLists.txt create mode 100644 arch/qwen35_w8a8/qwen35_w8a8.cpp diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index ce4e6659..c1b80735 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -45,9 +45,30 @@ * and includes this file. Every difference is behind `#if QWEN35_MOE`: the expert-count check, the * routing geometry read from metadata, the block's buffers, the per-layer source names, the MTP * head's feed-forward, and the plugin identity. */ +/* ============================== AND A THIRD: qwen35_w8a8 ============================== + * + * `qwen35_w8a8` is the dense build with an int8 trunk: every large linear `i8*bf16[1x128]/fwht128`, + * rotated by a 128-wide Hadamard and served at i8a8h, each quantising its own input from the bf16 + * plane (LinearFP8's int8 branch). The producers already write that plane, as they do for a rotated + * MXFP4 linear, so the graph is this one. It is a plugin of its own because the quantisation + * descriptor is half of the selection key: `w8a8_fwht128`, which names the rotation, so a plain + * int8 trunk is refused. + * + * Its differences are behind `#if QWEN35_W8A8`: check_format's method, the probe that learns the + * trunk is int8 before the activations are declared (and refuses one that is not), and the plugin + * identity. The int8 activation pairs follow from the probe. */ #ifndef QWEN35_MOE #define QWEN35_MOE 0 #endif +#ifndef QWEN35_W8A8 +#define QWEN35_W8A8 0 +#endif +#if QWEN35_MOE && QWEN35_W8A8 +#error "qwen35_w8a8 is the dense build; a routed int8 trunk is not a format this file serves" +#endif +/* The plugin's name for a message, expanded once more so it is QWEN35_NS's value. */ +#define QWEN35_STR_X(x) #x +#define QWEN35_STR(x) QWEN35_STR_X(x) #ifndef QWEN35_NS #define QWEN35_NS qwen35_fp8 #endif @@ -101,6 +122,10 @@ struct Model { rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0; + /* The trunk's linears are int8 (LinearFP8::i8), learned before the activations are declared + * because it decides whether they carry an int8 code pair. Only qwen35_w8a8 sets it. */ + bool trunk_i8 = false; + /* the residual stream and the two vocabulary edges */ rad_buf b_x = 0, b_hout = 0, b_logits = 0; ActFP8 a_h{}; @@ -178,6 +203,18 @@ static Model g_model[MAX_RANKS]; static int check_format(const RadModelMeta* meta) { const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr); const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr); +#if QWEN35_W8A8 + /* The format the convert stated (the recipe's --set keys); the trunk probe in declare() holds + * the weights to it. */ + if (!method || std::strcmp(method, "w8a8") != 0 || !fmt || std::strcmp(fmt, "fwht128") != 0) { + fprintf(stderr, "radiance: qwen35_w8a8 serves a container converted for an int8 trunk " + "(quant_method 'w8a8', fmt 'fwht128': data/recipes/" + "q38-27b-w8a8-df2.recipe's --set keys); this one says '%s' / '%s'.\n", + method ? method : "(none)", fmt ? fmt : "(none)"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +#else const char* block = rad_meta_gets(meta, "quantization_config.weight_block_size", nullptr); if (method && std::strcmp(method, "fp8") != 0) { @@ -204,6 +241,7 @@ static int check_format(const RadModelMeta* meta) { } } return RAD_OK; +#endif } /* The DFlash2 drafter: its geometry, KV group, buffers and block. @@ -406,8 +444,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } #else if (meta->n_expert > 0) { - fprintf(stderr, "radiance: qwen35_fp8 refuses a checkpoint with %lld experts; that is " - "qwen35moe\n", (long long)meta->n_expert); + fprintf(stderr, "radiance: " QWEN35_STR(QWEN35_NS) " refuses a checkpoint with %lld " + "experts; that is qwen35moe\n", (long long)meta->n_expert); return RAD_E_UNSUPPORTED; } #endif @@ -544,13 +582,41 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c cd.conv_width = gc.conv_width; m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd); +#if QWEN35_W8A8 + /* ---- the trunk's stored format, read from the first delta-net layer's input projection as + * qwen4exp_fp8 reads its own: the activations below carry an int8 code pair only for an int8 + * trunk, and this build serves only the rotated one its descriptor names. The probe maps the + * weight through the layer's own LinearFP8, which then does not map it again; the resize + * before the layer loop keeps the layers sized here. */ + m.layers.resize((size_t)m.n_main); + for (int64_t l = 0; l < m.n_main; ++l) { + if (is_full_attention(l, interval)) continue; + const char* pre = "model.language_model.layers"; + RAD_ARCH_TRY(m.layers[(size_t)l].gdn.in.probe( + b, nm, g, nm.f("blk.%lld.ssm_inz", (long long)l), + { nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre, (long long)l), + nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre, (long long)l) })); + RadEncoding enc{}; + m.trunk_i8 = weight_enc(b, nm.f("blk.%lld.ssm_inz.weight", (long long)l), &enc) && + linear_is_w8h(enc); + break; + } + if (!m.trunk_i8) { + fprintf(stderr, "radiance: qwen35_w8a8 serves a rotated int8 trunk (i8 codes with a bf16 " + "scale a [1 x 128], /fwht128), and this container's first delta-net input " + "projection is not one; convert with " + "data/recipes/q38-27b-w8a8-df2.recipe\n"); + return RAD_E_DTYPE; + } +#endif + /* ---- activation buffers. Every activation that feeds a GEMM has an fp8 copy: an E4M3 plane * of the same shape and an f32 scale plane with one column per 128. They are transients that * liveness analysis can share, but not free: the largest, `ffn`'s, is 8192 x 17408 bytes * (143 MiB) beside its 285 MiB bf16 buffer. */ m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd}); m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd}); - RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd)); + RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.trunk_i8)); m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_dim}); m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim}); @@ -566,7 +632,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * it must not share storage with transients. */ m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot}, RAD_BUF_PERSIST); - RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim)); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, m.trunk_i8)); /* `gdn_in` is conv_dim + v_dim, not in_dim: a and b have their own buffer because the * checkpoint keeps them bf16, while the fp8 output gate is the tail of this one @@ -586,7 +652,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* Rank 3, as libr4d's scan and recurrent kernels require; the quantiser reads dim 0 as the * row. */ m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v}); - RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim)); + RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim, 0, m.trunk_i8)); #if QWEN35_MOE /* ---- the routing geometry, read here so a refusal names the container's key. `n_ff` is @@ -658,7 +724,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c #else m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff}); m.a_ffn.x = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff}); - RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff)); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8)); #endif m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd}); @@ -1137,6 +1203,14 @@ QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0", "dense graph with a routed feed-forward (256 experts, 8 a token, and a shared " "expert), gated attention over paged KV every fourth layer and gated delta net " "between") +#elif QWEN35_W8A8 +QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "w8a8_fwht128", "0.1.0", + "Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), an int8 trunk: i8 weights with a bf16 " + "scale a 128 of K, rotated by a 128-wide Hadamard, against int8 activations the " + "same rotation quantises; gated attention over paged KV every fourth layer and " + "gated delta net between") +/* An imported checkpoint is never a rotated int8 trunk: qwen35_fp8 serves those. */ +RAD_ARCH_SERVES_IMPORTS(0) #else QWEN35_PLUGIN_X(QWEN35_NS, QWEN35_ARCH_ID, "fp8_e4m3", "0.1.0", "Qwen3.5 / 3.6 / 3.8 dense (0.8B..27B), block-scaled fp8 weights and fp8 " diff --git a/arch/qwen35_w8a8/CMakeLists.txt b/arch/qwen35_w8a8/CMakeLists.txt new file mode 100644 index 00000000..5a9963b8 --- /dev/null +++ b/arch/qwen35_w8a8/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/qwen35_w8a8 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(qwen35_w8a8 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(qwen35_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/qwen35_w8a8.cpp) diff --git a/arch/qwen35_w8a8/qwen35_w8a8.cpp b/arch/qwen35_w8a8/qwen35_w8a8.cpp new file mode 100644 index 00000000..028b14d0 --- /dev/null +++ b/arch/qwen35_w8a8/qwen35_w8a8.cpp @@ -0,0 +1,19 @@ +/* qwen35_w8a8 -- Qwen3.5 / 3.6 / 3.8 dense with an int8 trunk: i8 weights with a bf16 scale a 128 + * of K, rotated by a 128-wide Hadamard, against int8 activations quantised under the same rotation. + * + * This is arch/qwen35_fp8/qwen35_fp8.cpp built again, as qwen35moe_fp8 is: the same gated + * attention, gated delta net, MLP, layer schedule, rope, vocabulary edges, drafters and vision + * tower. A linear's weight encoding makes it int8 (arch/common/rad_fp8.h: LinearFP8): + * `i8*bf16[1x128]/fwht128` is gemm_nt_q at i8a8h behind had_quant_act_i8g, each linear quantising + * its own input from the bf16 plane its producer already writes. The places this build differs are + * behind `#if QWEN35_W8A8` in that file. + * + * A plugin of its own rather than qwen35_fp8 serving any encoding it is handed, because the + * quantisation descriptor is half of the selection key (spec §2.4): a container converted with + * data/recipes/q38-27b-w8a8-df2.recipe says `w8a8_fwht128`. + */ +#define QWEN35_W8A8 1 +#define QWEN35_NS qwen35_w8a8 +#define QWEN35_ARCH_ID "qwen35" + +#include "../qwen35_fp8/qwen35_fp8.cpp" diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 04a4b4ad..cec30f76 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -11,6 +11,7 @@ plugin claims. | `arch/llama_dense_fp8` | `llama` | *(empty)* | the same graph from a bf16 checkpoint, linears made block fp8 by a recipe or kept bf16. MiniCPM5-2B | | `arch/qwen35_bf16` | `qwen35` | *(empty)* | the Qwen3.5/3.6/3.8 dense hybrid, served bf16 | | `arch/qwen35_fp8` | `qwen35` | `fp8_e4m3` | the same, block-scaled FP8 weights and activations | +| `arch/qwen35_w8a8` | `qwen35` | `w8a8_fwht128` | `qwen35_fp8` with an int8 trunk: i8 weights with a bf16 scale per 128 of K, rotated by a 128-wide Hadamard, against int8 activations under the same rotation (`data/recipes/q38-27b-w8a8-df2.recipe`) | | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert | | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | @@ -235,6 +236,29 @@ and every difference is behind `#if QWEN35_MOE` in the shared source. It is a se unit rather than a branch on `n_expert` because the id is half the selection key, and one `.so` cannot claim both ids. +## `qwen35_w8a8` + +The dense build again, behind `#if QWEN35_W8A8`, for a container `data/recipes/q38-27b-w8a8-df2.recipe` +converts from the bf16 checkpoint: the trunk's linears (the set Qwen's FP8 release quantises) as +`i8*bf16[1x128]/fwht128`, each 128 of K rotated by the unnormalised Hadamard before rounding, served +by `gemm_nt_q` at `i8a8h`. The descriptor `w8a8_fwht128` is what the convert's `--set` keys state; +a probe of the first delta-net input projection holds the weights to it before the activations are +declared, since only an int8 trunk gives them an int8 code pair. The descriptor names the rotation, so +a plain int8 trunk is refused. + +- **The 1/128 is the weight's.** `had_quant_act_i8g` rotates the activation and folds nothing, as + `had_quant_act_fp8` does; the per-row `had_*_i8` forms fold 1/sqrt(128) into the activation's + scale and against this weight give an output sqrt(128) too small. +- **The encoding is the only guard.** Rotated and plain int8 have the same bytes and extents, and + the rotated weight against the plain quantiser measures rel_l2 ~1.0 (r4d_selftest, `i8a8h_rot`), + so each dtype's layout hook takes only its own transform. +- **Each rotated linear quantises its own input** from the bf16 plane its producer writes: q, k and + v quantise one input three times, and no producer writes rotated codes yet. The MLP's gated fold + is an fp8a8 tile over E4M3 codes, so an int8 gate_up runs the pair. +- **It declines imported checkpoints** (`RAD_ARCH_SERVES_IMPORTS(0)`). An imported quantisation + goes to the family's one quantised plugin, and a second one would refuse every Quark, ParoQuant, + GPTQ or NVFP4 Qwen3.8 release; they stay with `qwen35_fp8`. + --- # `qwen4exp`: Qwen4-Exp / Qwen3.8-Flash-Next diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 5d1a6bf6..c7d00abf 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -268,6 +268,7 @@ and runs. | `llama_fp8`, `llama_dense_fp8` | LLaMA-shaped decoders: MiniCPM5, Llama 3, anything reporting `model_type: llama` | | `qwen35_bf16` | Qwen3.5 / 3.6 / 3.8 dense (0.8B–27B), bf16 | | `qwen35_fp8` | the same, block-scaled fp8 | +| `qwen35_w8a8` | the same, an int8 trunk rotated by a 128-wide Hadamard | | `qwen35moe_fp8` | Qwen3.5 / 3.6 MoE (35B-A3B), 256 experts, 8 a token | | `qwen4exp_fp8` | Qwen4-Exp / Qwen3.8-Flash-Next: hybrid Gated DeltaNet + gated attention, 512 experts | | `gemma4` | Gemma 4 text decoders (26B-A4B MoE and the dense members): bf16 trunk, routed experts bf16 or block fp8, and the DFlash drafter | diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 55a96735..29aa356e 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -464,6 +464,12 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s #undef QWEN35_NS #undef QWEN35_ARCH_ID #include "../arch/qwen35moe_fp8/qwen35moe_fp8.cpp" +/* The same source a third time, as qwen35_w8a8: the int8 trunk. */ +#undef QWEN35_MOE +#undef QWEN35_W8A8 +#undef QWEN35_NS +#undef QWEN35_ARCH_ID +#include "../arch/qwen35_w8a8/qwen35_w8a8.cpp" /* The LLaMA family from a dense checkpoint: llama_fp8 under its other descriptor. */ #undef LLAMA_DENSE_SRC #undef LLAMA_NS @@ -5939,6 +5945,126 @@ TEST(the_qwen35_family_refuses_a_layer_schedule_that_contradicts_its_interval) { RAD_E_UNSUPPORTED); } +/* ==================================================================== qwen35_w8a8 */ + +namespace { + +/* The dense fixture as data/recipes/q38-27b-w8a8-df2.recipe states it: w8a8 / fwht128. */ +MetaKV q35w8a8_meta() { + MetaKV k = q35fp8_meta(); + k.m.quant = "w8a8_fwht128"; + k.m.name = "test-qwen35-27b-w8a8"; + k.set("quantization_config.quant_method", "w8a8").set("quantization_config.fmt", "fwht128"); + return k; +} + +/* The recipe's encodings by declared name: the eight trunk linears int8 (`/fwht128` unless + * `rotated` is false, which the plugin refuses), an int8 lm_head, and the DFlash2 drafter's MXFP4 + * linears with its 2-bit head. The drafter's keys come first because its names contain the + * trunk's (dflash.blk.0.attn_k.weight), and the head's last because `output.weight` is in + * `attn_output.weight`. */ +void w8a8_encs(RadBuilder* b, bool rotated = true) { + RadEncoding i8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128); + if (rotated) rad_enc_copy_str(i8.transform, "fwht128"); + RadEncoding u2 = rad_enc_affine(RAD_U2, RAD_F16, 1, 128); + rad_enc_add_plane(&u2, "zero", RAD_U8, 1, 128); + b->encs = { { "dflash.draft_head", u2 }, + { "dflash.", rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32) } }; + for (const char* t : { "attn_qg.weight", "attn_k.weight", "attn_v.weight", + "attn_output.weight", "ssm_inz.weight", "ssm_out.weight", + "ffn_gate_up.weight", "ffn_down.weight" }) + b->encs.push_back({ t, i8 }); + b->encs.push_back({ "output.weight", rad_enc_affine(RAD_I8, RAD_BF16, 1, 128) }); +} + +/* qwen35_w8a8::declare with the recipe's encodings, in lint_qwen35_fp8_family's shape. */ +int w8a8_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + w8a8_encs(b); + return qwen35_w8a8::declare(b, meta, ctx); +} + +} /* namespace */ + +/* Every trunk linear of a rotated int8 container is an i8a8h GEMM right behind its own + * had_quant_act_i8g, at one rank and two: 2 attention layers of four linears, 6 delta-net layers + * of two and 8 feed-forwards of two. None is left at fp8, which is what a linear that missed the + * encoding falls back to, and the MLP declares no gated fold (an fp8a8 tile over E4M3 codes). The + * four trunk activations carry an int8 pair; the delta net's `gdn_in` feeds no int8 linear. */ +TEST(qwen35_w8a8_serves_every_trunk_linear_rotated_int8) { + MetaKV mk = q35w8a8_meta(); + for (int world : { 1, 2 }) { + RadBuilder b; + w8a8_encs(&b); + RadBuildCtx ctx = build_ctx(0, world); + REQUIRE_EQ(qwen35_w8a8::declare(&b, mk.meta(), &ctx), RAD_OK); + int rot = 0, paired = 0; + for (size_t i = 0; i < b.ops.size(); ++i) { + const RecOp& o = b.ops[i]; + if (o.op != "gemm_nt_q") continue; + CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h")); + if (pstr(&o, "dtype") != "i8a8h") continue; + ++rot; + paired += i > 0 && b.ops[i - 1].op == "had_quant_act_i8g"; + } + CHECK_EQ(rot, 2 * 4 + 6 * 2 + 8 * 2); + CHECK_EQ(paired, rot); + CHECK_EQ(count_op(b, "quant_act_i8g"), 0); + CHECK_EQ(count_op(b, "gemm_nt_q_gated"), 0); + for (const char* a : { "h.q8", "attn_out.q8", "gdn_o.q8", "ffn.q8" }) + CHECK(find_b(b, a) != nullptr); + CHECK(find_b(b, "gdn_in.q8") == nullptr); + } +} + +/* What the int8 build refuses: a trunk that is not int8 (no stated encoding, which a block-fp8 + * plugin reads as fp8), a plain int8 trunk (the descriptor names the rotation, and a plain weight + * served behind the rotated quantiser would be wrong), and a container stated for another format + * or without the rotation's `fmt`. */ +TEST(qwen35_w8a8_refuses_what_is_not_a_rotated_int8_trunk) { + RadBuildCtx ctx = build_ctx(); + { + MetaKV mk = q35w8a8_meta(); + RadBuilder b; + CHECK_EQ(stderr_of_rc([&] { return qwen35_w8a8::declare(&b, mk.meta(), &ctx); }), + RAD_E_DTYPE); + } + { + MetaKV mk = q35w8a8_meta(); + RadBuilder b; + w8a8_encs(&b, false); + CHECK_EQ(stderr_of_rc([&] { return qwen35_w8a8::declare(&b, mk.meta(), &ctx); }), + RAD_E_DTYPE); + } + { + MetaKV mk = q35w8a8_meta(); + mk.set("quantization_config.quant_method", "fp8").set("quantization_config.fmt", "e4m3"); + RadBuilder b; + w8a8_encs(&b); + CHECK_EQ(stderr_of_rc([&] { return qwen35_w8a8::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } + { + MetaKV mk = q35w8a8_meta(); + mk.drop("quantization_config.fmt"); + RadBuilder b; + w8a8_encs(&b); + CHECK_EQ(stderr_of_rc([&] { return qwen35_w8a8::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } +} + +/* Every engine step lints clean at one and two ranks, with the MTP head's passes and with the + * DFlash2 drafter's, whose depth the probe fixes at its trained block as qwen35_fp8's does. */ +TEST(qwen35_w8a8_steps_lint_clean_with_its_mtp_head_and_a_dflash2_drafter) { + MetaKV mtp = q35w8a8_meta(); + lint_qwen35_fp8_family(w8a8_declare, qwen35_w8a8::step, mtp.meta(), 3, false, 0); + MetaKV df = with_dflash2(q35w8a8_meta()); + lint_qwen35_fp8_family(w8a8_declare, qwen35_w8a8::step, df.meta(), 7, true, 8); + RadArchProbe p{}; + CHECK_OK(qwen35_w8a8::probe(df.meta(), &p)); + CHECK_EQ(p.draft_depth, 7); +} + /* ==================================================================== llama_fp8 and DSpark */ namespace { @@ -6805,6 +6931,7 @@ struct ArchCase { /* Every architecture in the tree, at the fixtures above. */ struct ArchCases { MetaKV q35 = q35fp8_meta(), q35df = with_dflash2(q35fp8_meta()), q35moe = q35moe_meta(); + MetaKV q35w8df = with_dflash2(q35w8a8_meta()); MetaKV lla = with_dspark(llama_meta()), eg2 = eg2_meta(), qimg = qimg_meta(); MetaKV q4s = q4_small(); RadModelMeta q35b = qwen35_meta(), q4 = *q4s.meta(), lfm = lfm2_meta(); @@ -6843,6 +6970,12 @@ struct ArchCases { add("qwen35_fp8 + DFlash2", [this, sc](RadBuilder* b) { auto c = sc(1, 7); return qwen35_fp8::declare(b, q35df.meta(), &c); }, qwen35_fp8::step, 7, {}, 0xb5691456a0ce7e9dull); + add("qwen35_w8a8 + DFlash2", [this, sc](RadBuilder* b) { + auto c = sc(1, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, + qwen35_w8a8::step, 7, {}, 0x88e964c824896422ull); + add("qwen35_w8a8 + DFlash2, two ranks", [this, sc](RadBuilder* b) { + auto c = sc(2, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, + nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x7c73e987c475e40dull); add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) { auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); }, qwen35moe_fp8::step, 3, {}, 0x3157a986f13a9a72ull); diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index a503ccd1..638c8118 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -12,6 +12,7 @@ #include #include #include +#include using namespace rad; @@ -90,7 +91,8 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { { "breeze", "" }, { "embeddinggemma2", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, { "qwen35", "" }, - { "qwen35", "fp8_e4m3" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" }, + { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, + { "qwen3asr", "" }, { "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; std::set> got; for (const auto& [k, name] : keys) got.insert(k); @@ -101,4 +103,32 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { CHECK(got == want); } +/* A checkpoint whose quantisation was imported weight by weight (Quark, ParoQuant, GPTQ, NVFP4) + * names a tool no plugin claims, so the family's one quantised plugin serves it, and two are + * refused (startup.h). So each family has at most one quantised plugin that takes imports: + * qwen35_w8a8 declines them (rad_arch_serves_imports), leaving Qwen3.8 imports to qwen35_fp8. */ +TEST(every_shipped_family_has_at_most_one_plugin_for_an_imported_checkpoint) { + Registry r; + const int st = r.load_dir(dir_of("architectures"), {}); + if (st == RAD_E_IO && r.plugins().empty()) + ARTIFACT_MISSING("the architecture plugins under " + dir_of("architectures")); + CHECK_OK(st); + std::map> takers; + for (const Plugin& p : r.plugins()) + if (p.kind == RAD_PLUGIN_ARCH && !p.arch_quant.empty() && p.arch_serves_imports) + takers[p.arch_id].push_back(p.name); + for (const auto& [id, names] : takers) { + if (names.size() > 1) + for (const auto& n : names) + fprintf(stderr, " '%s' would take an imported %s checkpoint\n", n.c_str(), + id.c_str()); + CHECK_EQ(names.size(), 1u); + } + REQUIRE(takers.count("qwen35")); + CHECK_EQ(takers["qwen35"][0], std::string("qwen35_fp8")); + const Plugin* w8 = r.plugin("qwen35_w8a8"); + REQUIRE(w8 != nullptr); + CHECK(!w8->arch_serves_imports); +} + RAD_TEST_MAIN() From 37deff85cad1073b50fa969655cc6a73ce57e6f2 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Sat, 17 Oct 2026 15:42:07 +0800 Subject: [PATCH 029/152] data/recipes: q38-27b-w8a8-df2, Qwen3.8-27B with an int8 trunk, an int8 head and the DFlash2 drafter From the bf16 release: the trunk's linears RTN int8 under fwht128 (weight error 6.3e-3), the lm_head int8 (6.8e-3), the drafter as q38-27b-fp8-df2.recipe makes it; 29.0 GiB. Against the bf16 model over 45K mostly-Go positions: mean KL 0.00051 and 99.25% top-1, against 0.00404 and 97.75% for Qwen's FP8 release. Co-Authored-By: Claude Opus 5.5 --- data/recipes/q38-27b-w8a8-df2.recipe | 48 ++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 data/recipes/q38-27b-w8a8-df2.recipe diff --git a/data/recipes/q38-27b-w8a8-df2.recipe b/data/recipes/q38-27b-w8a8-df2.recipe new file mode 100644 index 00000000..22344f17 --- /dev/null +++ b/data/recipes/q38-27b-w8a8-df2.recipe @@ -0,0 +1,48 @@ +# q38-27b-w8a8-df2.recipe -- Qwen3.8-27B from its bf16 release with an int8 trunk rotated by a +# 128-wide Hadamard, and the DFlash2 drafter, served by qwen35_w8a8. +# +# rad-convert --draft-model \ +# --recipe data/recipes/q38-27b-w8a8-df2.recipe \ +# --set quantization_config.quant_method=w8a8 --set quantization_config.fmt=fwht128 \ +# -o q38-27b-w8a8-df2.rad +# +# The --set keys make the container's descriptor `w8a8_fwht128`, which selects qwen35_w8a8 (a bf16 +# checkpoint alone selects qwen35_bf16). +# +# - The trunk's linears (attention q/gate, k, v and output, the delta net's qkv/z and output, the +# MLP's gate/up and down: the set Qwen's FP8 release quantises) as int8 with a bf16 scale per +# (row, 128 of K), each 128 of K rotated by the unnormalised Hadamard before rounding and the +# 1/128 kept in the scale (`transform=fwht128`). gemm_nt_q reads them at i8a8h, each linear +# quantising its own input under the same rotation (had_quant_act_i8g). `clamp=sym` keeps the +# codes in -127..127, the range the int8 kernels are written for. Weight error 6.3e-3 relative. +# - The delta net's a/b projections, the norms, the embedding and the vision tower stay bf16, as +# in Qwen's FP8 release. +# - The lm_head int8 too, unrotated (logits_gemm_i8): weight error 6.8e-3 against block fp8's +# 2.6e-2. Against the bf16 model over 45K mostly-Go positions it halves the container's mean KL +# (0.00051 against 0.00090 with a block-fp8 head; Qwen's FP8 release 0.00404) and takes top-1 +# agreement from 98.83% to 99.25%. A block-fp8 head is one override away: +# --quant 'output.weight=rtn:codes=fp8_e4m3,block=128x128,scale=bf16' +# +# The drafter as q38-27b-fp8-df2.recipe makes it: its linears at MXFP4, and a 2-bit copy of the +# target's head (u2 with a u8 zero, least-squares clip search) whose top 32 the engine rescores +# against the target's head. + +blk.*.attn_qg.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ssm_inz.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ssm_out.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ffn_down.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search +dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search + +dflash.fc.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 From f92cce07f12691788bd2b5a4fec6aee3b62468c7 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 030/152] libr4d: Gemma 3's rows -- windowed h128/gqa2 attention, qkv_norm_rope at h128 without a value norm, ar_rmsnorm_post_quant_fp8 - r4d_attn_paged_h128_gqa2w.hip: decode and query-tiled prefill at head_dim 128, gqa 2, window >= 1, instantiations of the h256/gqa6 templates with WIN = 1 (as h256_gqa2 for Gemma 4); the h128/gqa2 rows keep window 0. - qkv_norm_rope: head_dim 128, and an optional v_norm (0 leaves v alone). - ar_rmsnorm_post_quant_fp8: ar_rmsnorm_quant_fp8 with a post-norm of the reduced sum against w_post before the residual add (the sandwich junction), exact wire only. Its own op: an optional seventh operand on ar_rmsnorm_quant_fp8 broke every plugin issuing its six. r4d_selftest: the windowed rows against the inline oracle over a history past the window, and qkv_norm_rope at h128 / v_norm 0 byte-identical to its chain. Co-Authored-By: Claude Opus 5.5 --- docs/OPS.md | 3 +- libr4d/CMakeLists.txt | 2 + libr4d/r4d.h | 8 ++- libr4d/r4d_ar_entry.hip | 10 ++- libr4d/r4d_attn_paged_h128_gqa2w.hip | 82 +++++++++++++++++++++ libr4d/r4d_attn_paged_h256_gqa6.hip | 21 ++++++ libr4d/r4d_fused_quant_fp8.hip | 41 +++++++++-- libr4d/r4d_plugin.h | 7 ++ libr4d/r4d_qkv_norm_rope.hip | 12 ++-- libr4d/r4d_rows.cpp | 103 +++++++++++++++++++++++++++ libr4d/r4d_selftest.cpp | 21 ++++-- 11 files changed, 291 insertions(+), 19 deletions(-) create mode 100644 libr4d/r4d_attn_paged_h128_gqa2w.hip diff --git a/docs/OPS.md b/docs/OPS.md index 81c231ab..3592b153 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -687,7 +687,7 @@ bytes). | `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` | | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | | `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? | -| `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | +| `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | **`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each band. @@ -1644,6 +1644,7 @@ device code. | op | params | operands | |---|---|---| | `ar_rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | +| `ar_rmsnorm_post_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w | | `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? | | `ar_hc_write` | `M`(range) `n` `hc` `world_size` `dtype` `wire`/opt | `y`:inout, `inj`, `h`:inout | | `ar_gather_hc_write` | `M`(range) `n` `hc` `top_k` `world_size` `dtype` `act`/opt `wire`/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`?, `y`:inout, `inj`, `h`:inout | diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 05afe635..a8944e37 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -44,6 +44,8 @@ set(R4D_UNITS # Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode and # prefill. "r4d_attn_paged_h256_gqa2|" + # Gemma 3 sliding window: head_dim 128, 2 queries per KV head, windowed decode and prefill. + "r4d_attn_paged_h128_gqa2w|" # Eight queries per KV head, one body instantiated at head_dim 256 (the routed 35B-A3B) and 128 # (MiniCPM5-2B). "r4d_attn_paged_gqa8|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 869c12c9..9308639e 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -100,6 +100,12 @@ int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa2_bf16kv (const R4DArgs* a, hipStream_t stream); long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a); +/* Gemma 3 sliding window (r4d_attn_paged_h128_gqa2w.hip): head_dim 128, gqa 2, window >= 1. */ +int r4d_attn_prefill_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h128_gqa2w_bf16kv (const R4DArgs* a, hipStream_t stream); +long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a); // The geometry the attention kernels above are compiled for, so a caller can check a model // before the first launch. void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows); @@ -726,7 +732,7 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off); + long loc_pack, long loc_scale_off, long wp = 0); int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void); // The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 80cf89fd..1f348c96 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -1156,7 +1156,7 @@ extern "C" int r4d_rad_ar_twoshot_4rank_ti8(const RadArgs* a, RadStream s) { /* ------------------------------------------------------------------ the fused all-reduce + norm */ -enum { AL_X = 0, AL_RESID, AL_W, AL_Q, AL_SCALE, AL_OUTBF16 }; +enum { AL_X = 0, AL_RESID, AL_W, AL_Q, AL_SCALE, AL_OUTBF16, AL_WPOST }; extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); @@ -1250,8 +1250,13 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const RadTensor* q = r4d_opt(a, AL_Q); const RadTensor* sc = r4d_opt(a, AL_SCALE); const RadTensor* ob = r4d_opt(a, AL_OUTBF16); + /* ar_rmsnorm_quant_fp8's optional post-norm (Gemma 3's sandwich); ar_ln_had_quant_i8 has no + * seventh operand, and this function serves only the fp8 op. */ + const RadTensor* wpo = r4d_opt(a, AL_WPOST); if (!x || !w || !q || !sc) return RAD_E_INVAL; if (!r4d_contig(w)) return RAD_E_STRIDE; + if (wpo && (!rs || !r4d_contig(wpo) || r4d_numel(wpo) != r4d_numel(w) || wpo->dtype != w->dtype)) + return RAD_E_SHAPE; /* Rank 2 everywhere, as in rmsnorm_quant_fp8: a norm has a gain per channel, so flattening * everything after dim 0 into the row would put one gain across several heads. */ @@ -1291,6 +1296,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { /* This rank's packed-half side buffer exists for every bf16 instance; missing means a * broken init. */ if (!in->locpack) return RAD_E_STATE; + if (wpo) return RAD_E_UNSUPPORTED; // the post-norm is the exact wire's only } R4dArCfg cfgv; @@ -1327,7 +1333,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32, (int)rp, (int)yp, (int)qp, (int)sp, (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire, - in->locpack, in->slot_bytes / 2); + in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0); return e == 0 ? RAD_OK : RAD_E_SHAPE; } diff --git a/libr4d/r4d_attn_paged_h128_gqa2w.hip b/libr4d/r4d_attn_paged_h128_gqa2w.hip new file mode 100644 index 00000000..8024553e --- /dev/null +++ b/libr4d/r4d_attn_paged_h128_gqa2w.hip @@ -0,0 +1,82 @@ +// R4D attention dispatch for Gemma 3's sliding-window layers (arch/gemma3, TranslateGemma 27B): +// head_dim 128, 2 queries per KV head (32 over 16, 16 over 8 at TP2), paged block 16, window 1024 +// (52 of 62 layers). Instantiations of the h256/gqa6 kernel templates with WIN = 1, as +// r4d_attn_paged_h256_gqa2.hip does at head_dim 256 for Gemma 4. +// +// Both bands: decode (q_len * gqa <= 64, so q_len <= 32) and the query-tiled prefill kernel. The +// windowless h128/gqa2 rows (r4d_attn_paged_h128_gqa2.hip) keep window == 0; these rows take +// window >= 1 only, so the global layers stay on the tuned full-attention legs. +#include "r4d.h" +#include "r4d_attn_args.h" +#include "r4d_common.h" +#include +#include +using std::max; +// The decode kernel uses helpers from the prefill unit, so prefill is included first. Both kernels +// are instantiated here with WIN = 1. +#include "r4d_attn_prefill_h256_gqa6.hip" +#include "r4d_attn_decode_h256_gqa6.hip" + +#define CHK4() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0) + +#define B_HEAD_DIM 128 +#define B_GQA 2 +#define B_BLOCK_SIZE 16 +#define B_TILE 16 // decode: r4d_decode_launch_win (r4d_attn_decode_h256_gqa6.hip) +// The DFlash2 drafter's head_dim 128 windowed decode set (r4d_attn_paged_h128_gqa4.hip): K +// prefetch 2 and O_KRAW. Not separately tuned for gqa 2. +#define B_OPT 20207163 + +extern "C" long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a) { + return r4d_decode_scratch(a, r4d_decode_splits_win(a, B_TILE), B_OPT); +} + +extern "C" int r4d_attn_decode_h128_gqa2w_fp8kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} +extern "C" int r4d_attn_decode_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} + +// ---- prefill --------------------------------------------------------------------------------- +// The windowless h128 prefill option set (r4d_attn_paged_gqa8.hip, G8_P_OPT_128: no O_KWIDE, which +// is a head_dim 256 fetch, K prefetch 4) with WIN on. At gqa 2 a block covers NWARPS * 16 / 2 = 192 +// query positions. window <= 0 would give full attention, but the rows never send one here. +#define P_NWARPS 24 +#define P_TILE 48 +#define P_OPT 3430923 + +template +static int prefill_launch_h128_gqa2w(const R4DArgs* a, hipStream_t s) { + if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1; + if (a->q_heads / a->kv_heads != B_GQA) return -2; + constexpr int BQ = (P_NWARPS * 16) / B_GQA; + dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs); + hipLaunchKernelGGL((r4d_attn_prefill_kernel), + grid, dim3(P_NWARPS * 32), 0, s, *a); + CHK4(); + return 0; +} + +extern "C" int r4d_attn_prefill_h128_gqa2w_fp8kv(const R4DArgs* a, hipStream_t s) { + return prefill_launch_h128_gqa2w<0>(a, s); +} +extern "C" int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t s) { + return prefill_launch_h128_gqa2w<1>(a, s); +} + +/* Prefill RadArgs wrappers. Absent descales mean 1.0 (fill_paged leaves them null). The decode + * wrappers are in r4d_attn_paged_h256_gqa6.hip beside decode_common. */ +extern "C" int r4d_rad_attn_prefill_h128_gqa2w_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = fill_paged(a, &r, B_HEAD_DIM); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h128_gqa2w_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_prefill_h128_gqa2w_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = fill_paged(a, &r, B_HEAD_DIM); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h128_gqa2w_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 947612a1..6a94e226 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -186,6 +186,7 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) { static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) { if (which == 1) return (int64_t)r4d_attn_decode_h128_gqa4_scratch_bytes(r); if (which == 2) return (int64_t)r4d_attn_decode_h256_gqa2_scratch_bytes(r); + if (which == 3) return (int64_t)r4d_attn_decode_h128_gqa2w_scratch_bytes(r); return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r); } @@ -297,3 +298,23 @@ extern "C" int r4d_rad_attn_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) if (rc != RAD_OK) return rc; return r4d_attn_decode_h256_gqa2_bf16kv(&r, (hipStream_t)s); } + +/* Gemma 3 sliding window (head_dim 128, gqa 2, window 1024) decode; its prefill entry points + * are in r4d_attn_paged_h128_gqa2w.hip. */ +extern "C" int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs* a) { + return decode_scratch(a, 128, 3); +} + +extern "C" int r4d_rad_attn_decode_h128_gqa2w_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 128, 3); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h128_gqa2w_fp8kv(&r, (hipStream_t)s); +} + +extern "C" int r4d_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 128, 3); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h128_gqa2w_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index 7fb8b679..ea31d0dd 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -363,9 +363,13 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) { return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM); } -template +// POST: a sandwich-norm junction (Gemma 3): the reduced sum is post-normed against `wp` before the +// residual add, `v = bf16(sum * s1 * (wp + wadd))` with s1 the sum's own rms, as rmsnorm_quant_i8's +// POST computes it. `x` still receives the reduced sum. Exact wire and a residual only. +template __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s, int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, char* loc_pack, long loc_scale_off, int M, uint32_t n, uint32_t nkb, @@ -546,6 +550,27 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( (void)pr; float ss = 0.0f; + if constexpr (POST && WIRE == 0 && RES) { + /* Pass one reduces and takes the sum's sum of squares; pass two post-norms it, adds it + * into the stream and takes the stream's. Each thread reads back only its own columns. */ + float s1s = 0.0f; + for (uint32_t i = tid; i < n; i += THR) { + const uint16_t a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); + xr[i] = a; + const float av = bf2f(a); + s1s += av * av; + } + const float s1 = rsqrtf(block_sum(s1s, lds) / (float)n + eps); + __syncthreads(); // lds is reused by the second sum + for (uint32_t i = tid; i < n; i += THR) { + const float g = WF32 ? ((const float*)wp)[i] : bf2f(((const uint16_t*)wp)[i]); + const uint16_t pv = f2bf(bf2f(xr[i]) * s1 * (g + wadd)); + const uint16_t h = f2bf(bf2f(rr[i]) + bf2f(pv)); + rr[i] = h; + const float v = bf2f(h); + ss += v * v; + } + } else for (uint32_t i = tid; i < n; i += THR) { /* The exact wire reduces here, in the norm's first pass; the compressed one already * reduced into `x`. */ @@ -741,8 +766,9 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off) { + long loc_pack, long loc_scale_off, long wp) { if (!x || !w || !q || !s) return -1; + if (wp && (!res || wire != 0)) return -10; // a post-norm needs the stream and the exact wire if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1; if (M <= 0 || n <= 0) return -2; // n % 8: n bf16 is a whole number of 16B words (see the push), which also gives every lane its @@ -765,18 +791,22 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long // The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order). const int thr = nthreads ? nthreads : r4d_act_threads(M, n); if (thr != 256 && thr != 512 && thr != 1024) return -6; -#define R4D_ARQ_T(wf, rs, T, W) \ - hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel), dim3((uint32_t)nb), dim3(T), \ +#define R4D_ARQ_P(wf, rs, T, W, PO) \ + hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel), dim3((uint32_t)nb), dim3(T), \ 0, \ (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, (const void*)w, \ + (const void*)wp, \ (uint16_t*)y, (uint8_t*)q, (float*)s, (int4*)peer_scratch, \ (const int4*)my_scratch, (unsigned int*)peer_flags, \ (unsigned int*)my_flags, (unsigned int*)seq_ctrs, (char*)loc_pack, \ (long)loc_scale_off, M, (uint32_t)n, \ (uint32_t)nkb, eps, wadd, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \ (uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw) +#define R4D_ARQ_T(wf, rs, T, W) R4D_ARQ_P(wf, rs, T, W, false) #define R4D_ARQ_W(wf, rs, T) \ - do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); else R4D_ARQ_T(wf, rs, T, 0); } while (0) + do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \ + else if (rs && wp) R4D_ARQ_P(wf, rs, T, 0, true); \ + else R4D_ARQ_T(wf, rs, T, 0); } while (0) #define R4D_ARQ(wf, rs) \ do { if (thr == 1024) R4D_ARQ_W(wf, rs, 1024); \ else if (thr == 512) R4D_ARQ_W(wf, rs, 512); \ @@ -786,6 +816,7 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long #undef R4D_ARQ #undef R4D_ARQ_W #undef R4D_ARQ_T +#undef R4D_ARQ_P return hipGetLastError() == hipSuccess ? 0 : -4; } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index b6a81f1c..41253c21 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -104,6 +104,13 @@ int r4d_rad_attn_prefill_h256_gqa2_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*); +/* Gemma 3 sliding window (r4d_attn_paged_h128_gqa2w.hip): head_dim 128, 2 queries per KV head, + * window >= 1. Decode (q_len*gqa <= 64) and windowed prefill, as the h256/gqa2 pair above. */ +int r4d_rad_attn_prefill_h128_gqa2w_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h128_gqa2w_bf16 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h128_gqa2w_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h128_gqa2w_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs*); /* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not * (r4d_attn_paged_window.hip): one entry point per geometry and cache dtype, every q_len and any q * row pitch, so they serve both attn_paged and attn_paged_qrow. */ diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip index 8947fbdb..0ebf24d9 100644 --- a/libr4d/r4d_qkv_norm_rope.hip +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -136,7 +136,10 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { const long long nkv = r4d_geti_or(a, "n_head_kv", 0); const long long rot = r4d_geti_or(a, "rotary_dim", hd); const long long vk = r4d_geti_or(a, "v_from_k", 0); - if (hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE); + // v_norm 0: no value norm at all (Gemma 3); the v heads are left out of the grid. + const long long vn = r4d_geti_or(a, "v_norm", 1); + if (hd != 128 && hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE); + if (vk && !vn) return R4D_NO(RAD_E_INVAL); if (nq <= 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(qw) != hd || r4d_numel(kw) != hd) return R4D_NO(RAD_E_SHAPE); const char* mode = r4d_gets(a, "mode"); @@ -169,7 +172,7 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { const float wadd = (float)r4d_getf(a, "wadd", 0.0); const float theta = (float)r4d_getf(a, "theta", 10000.0); const float rsc = (float)r4d_getf(a, "scale", 1.0); - const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + (vk ? 0 : nkv))); + const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + ((vk || !vn) ? 0 : nkv))); #define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ (uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \ @@ -178,8 +181,9 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { #define R4D_QNR(HD) \ do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \ else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0) - if (hd == 256) R4D_QNR(256); - else R4D_QNR(512); + if (hd == 128) R4D_QNR(128); + else if (hd == 256) R4D_QNR(256); + else R4D_QNR(512); #undef R4D_QNR #undef R4D_QNR_T return emit_rc; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index ef5fd83b..77bc9c73 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1252,6 +1252,19 @@ static const RadOperandSpec oArRmsNormQuantFp8[] = { { "out_bf16", RAD_OPD_OUT, 1 }, }; +/* ar_rmsnorm_post_quant_fp8: the same with a sandwich post-norm of the reduced sum before the add + * (Gemma 3's junction, arch/gemma3), exact wire only. Its own op: an optional seventh operand on + * ar_rmsnorm_quant_fp8 would break every plugin that issues that op's six. */ +static const RadOperandSpec oArRmsNormPostQuantFp8[] = { + { "x", RAD_OPD_INOUT, 0 }, + { "residual", RAD_OPD_INOUT, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, + { "w_post", RAD_OPD_WEIGHT, 0 }, +}; + /* `rmsnorm_quant_i8` is the norm with r4d_gemm_w4a8_nt_m64's activation producer on its pass: * int8 codes in the GEMM's fragment order and one f32 scale per row (quant_act_i8's grid, not * quant_act_i8g's per-group one nor the rotated rmsnorm_had_quant_i8's). Its first six operands are @@ -1295,6 +1308,7 @@ static const RadParamSpec pQkvNormRope[] = { { "ladder", RAD_P_STR, RAD_OPTIONAL }, P_F64O("wadd"), { "v_from_k", RAD_P_INT, RAD_OPTIONAL }, + { "v_norm", RAD_P_INT, RAD_OPTIONAL }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; static const RadOperandSpec oQkvNormRope[] = { @@ -2908,6 +2922,10 @@ static const RadOpSchema kSchemas[] = { "the two-rank all-reduce and the residual add, RMS norm, rotation and quantisation " "that always follow it, in one kernel."), + SCHEMA("ar_rmsnorm_post_quant_fp8", pArRmsNormQuantFp8, oArRmsNormPostQuantFp8, + "ar_rmsnorm_quant_fp8 with a post-norm of the reduced sum against w_post before the " + "residual add (a sandwich-norm junction), exact wire only, byte-identical to all_reduce, " + "rmsnorm, rmsnorm_quant_fp8."), SCHEMA("ar_rmsnorm_quant_fp8", pArRmsNormQuantFp8, oArRmsNormQuantFp8, "the two-rank all-reduce and the residual add, RMS norm and block-scaled fp8 " "quantisation that always follow it, in one kernel. Both wires."), @@ -3149,6 +3167,25 @@ static const RadConstraint cAttnPrefillH256Gqa2Bf16[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; +/* Gemma 3 sliding window: head_dim 128, 2 queries per kv head (r4d_attn_paged_h128_gqa2w.hip). + * window >= 1 only: window 0 at this geometry is the tuned full-attention pair above. Decode is + * q_len <= 32 (q_len*gqa <= 64), prefill takes the rest. */ +static const RadConstraint cAttnDecodeH128Gqa2wFp8[] = { + C_GE("window", 1), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnDecodeH128Gqa2wBf16[] = { + C_GE("window", 1), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; +static const RadConstraint cAttnPrefillH128Gqa2wFp8[] = { + C_GE("window", 1), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnPrefillH128Gqa2wBf16[] = { + C_GE("window", 1), C_EQ("head_dim", 128), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; /* Eight queries per KV head, at both head widths (r4d_attn_paged_gqa8.hip). q_len <= 8 is * `q_len * gqa <= 64` at gqa 8: a decode workgroup holds 64 rows, each query position claims gqa * of them. As on the gqa6 leg, it is also the decode/prefill bucket boundary (spec §2.2). */ @@ -3894,6 +3931,10 @@ static const RadConstraint cRmsNormQuantI8[] = { static const RadConstraint cQkvNormRope[] = { C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), }; +/* Gemma 3's prologue (arch/gemma3): head_dim 128, usually with v_norm 0. */ +static const RadConstraint cQkvNormRopeH128[] = { + C_EQ("head_dim", 128), C_IN("dtype", "bf16"), +}; static const RadConstraint cGeluMulQuantI8[] = { C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), }; @@ -5057,6 +5098,46 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_prefill_h128_gqa2w_fp8kv", "attn_paged", "attn", + "paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)", + "head_dim 128, 2 queries per kv head, paged block 16, varlen, window >= 1 from the launch argument", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH128Gqa2wFp8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa2w_fp8, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_prefill_h128_gqa2w_bf16kv", "attn_paged", "attn", + "paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)", + "head_dim 128, 2 queries per kv head, paged block 16, varlen, window >= 1 from the launch argument", + "bf16 query, bf16 kv cache, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH128Gqa2wBf16), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa2w_bf16, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h128_gqa2w_fp8kv", "attn_paged", "attn", + "paged causal attention with a sliding window, split-KV (decode / verify)", + "head_dim 128, 2 queries per kv head, paged block 16, q_len*gqa <= 64, window >= 1 from the " + "launch argument", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH128Gqa2wFp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2w_fp8, r4d_rad_attn_decode_h128_gqa2w_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h128_gqa2w_bf16kv", "attn_paged", "attn", + "paged causal attention with a sliding window, split-KV (decode / verify)", + "head_dim 128, 2 queries per kv head, paged block 16, q_len*gqa <= 64, window >= 1 from the " + "launch argument", + "bf16 query, bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH128Gqa2wBf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2w_bf16, r4d_rad_attn_decode_h128_gqa2w_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + { "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 8 queries per kv head, paged block 16, varlen", @@ -6550,6 +6631,17 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cQkvNormRope), NOTUNE, nullptr, nullptr, r4d_rad_qkv_norm_rope }, +{ "qkv_norm_rope_h128_bf16", "qkv_norm_rope", "attn", + "per-head RMS norms of separate q and k projections, the weightless norm of v unless v_norm is 0, " + "and the rotary of q and k, in place, in one dispatch", + "head_dim 128; neox, `rotary` or `head` ladder, one position component, no YaRN; one workgroup a " + "(token, head), a thread a channel", + "bf16 q/k/v and gains (or f32 gains), i32 positions; byte-identical to [rmsnorm_p +] rmsnorm x2 + " + "rope x2, each norm taken by its standalone kernel's partition", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkvNormRopeH128), NOTUNE, + nullptr, nullptr, r4d_rad_qkv_norm_rope }, + { "gelu_mul_quant_i8", "gelu_mul_quant_i8", "quant", "gelu(gate) * up, the tanh form, and quant_act_i8's quantiser in one pass over the row", "n a multiple of 16 and n*2 bytes within LDS; one workgroup per row", @@ -6625,6 +6717,17 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, /* `all_reduce` + `rmsnorm_quant_fp8`, both wires (r4d_fuse.cpp). */ r4d_fuse_ar_rmsnorm_quant_fp8 }, +{ "ar_rmsnorm_post_quant_fp8", "ar_rmsnorm_post_quant_fp8", "quant", + "the two-rank all-reduce, a post-norm of the reduced sum, the residual add, RMS norm and " + "block-scaled fp8 quantisation in one kernel: a sandwich-norm junction (Gemma 3)", + "exactly 2 ranks, the exact wire; n a multiple of 8 and x unpitched; group 128; a block owns whole " + "rows; the residual is required", + "bf16 in, E4M3 out with an f32 scale per (row, 128 columns); x receives the reduced sum", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cArRmsNormQuantFp8), ROW(tAr), nullptr, + r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_fp8, nullptr, nullptr, nullptr, + nullptr }, + { "ar_hc_write", "ar_hc_write", "norm", "the two-rank all-reduce and the gated residual's write that always follows it, in one kernel: " "h[s] += inj[s] * y over the reduced y", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 9a49f50f..bf57bd61 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -9208,16 +9208,19 @@ static void gelu_mul_quant_i8_numeric(const Plugin& pl) { * over q and k, kernel by kernel, against the one dispatch. Both of Gemma 4 31B's classes at one * rank of two: sliding (head_dim 256, 16 q over 8 kv heads, full rotary, separate v) and global * (512, 16 over 2, the proportional `head` ladder over 128, k == v), at batch heights reaching - * every width r4d_act_threads answers, including 256 at head_dim 512 (two channels per thread). */ + * every width r4d_act_threads answers, including 256 at head_dim 512 (two channels per thread). + * Gemma 3's class (head_dim 128, 16 q over 8 kv heads at one rank of two) has no value norm + * (v_norm 0), so its chain is four ops and v must come back untouched. */ static void qkv_norm_rope_numeric(const Plugin& pl) { const RadKernelInfo* np = find(pl, "rmsnorm_p_bf16"); const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); const RadKernelInfo* rp = find(pl, "rope_bf16"); const RadKernelInfo* fz = find(pl, "qkv_norm_rope_bf16"); if (!np || !nrm || !rp || !fz) { ok("qkv_norm_rope vs its five", false, "rows absent"); return; } - struct Cls { int64_t hd, nq, nkv, rot; const char* ladder; double theta; bool vk; }; - for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false }, - Cls{ 512, 16, 2, 128, "head", 1000000.0, true } }) { + struct Cls { int64_t hd, nq, nkv, rot; const char* ladder; double theta; bool vk, vn; }; + for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false, true }, + Cls{ 512, 16, 2, 128, "head", 1000000.0, true, true }, + Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false } }) { for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40 }) { const int64_t QD = cl.nq * cl.hd, KD = cl.nkv * cl.hd; std::vector hq((size_t)M * QD), hk((size_t)M * KD), hv((size_t)M * KD); @@ -9248,7 +9251,8 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { st_memcpy(dp, hp.data(), hp.size() * 4, hipMemcpyHostToDevice); const double eps = 1e-6, wadd = 0.0; /* --- the five, in the order the unfused block issues them --- */ - int rc = launch_row(np, { T(cl.vk ? dk[0] : dv[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dv[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, + int rc = !cl.vn ? RAD_OK + : launch_row(np, { T(cl.vk ? dk[0] : dv[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dv[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16") }); if (rc == RAD_OK) rc = launch_row(nrm, { T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }), T(dqw, RAD_BF16, { cl.hd }), T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }) }, @@ -9268,7 +9272,7 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { { PI("M", M), PI("head_dim", cl.hd), PI("n_head", cl.nq), PI("n_head_kv", cl.nkv), PF("theta", cl.theta), PF("eps", eps), PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), PS("ladder", cl.ladder), PF("wadd", wadd), - PI("v_from_k", cl.vk ? 1 : 0), PS("dtype", "bf16") }); + PI("v_from_k", cl.vk ? 1 : 0), PI("v_norm", cl.vn ? 1 : 0), PS("dtype", "bf16") }); const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + " M=" + std::to_string(M); if (rc != RAD_OK) { ok((what + " vs its five").c_str(), false, "rc=" + std::to_string(rc)); continue; } int nd = 0, moved = 0; @@ -18393,6 +18397,11 @@ static void device_phase(const Plugin& pl) { attn_case(pl, "attn_decode_h128_gqa2_fp8kv", 128, 2, 1, "fp8_e4m3", 0); attn_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 1, "bf16", 0); attn_numeric_case(pl, "attn_prefill_h128_gqa2_fp8kv", 128, 2, 64, "fp8_e4m3", 0, 256); + /* Gemma 3's sliding layers: head_dim 128, gqa 2, window 1024, over a history past it. */ + attn_numeric_case(pl, "attn_prefill_h128_gqa2w_fp8kv", 128, 2, 64, "fp8_e4m3", 1024, 2048); + attn_numeric_case(pl, "attn_prefill_h128_gqa2w_bf16kv", 128, 2, 64, "bf16", 1024, 2048); + attn_numeric_case(pl, "attn_decode_h128_gqa2w_fp8kv", 128, 2, 1, "fp8_e4m3", 1024, 2048); + attn_numeric_case(pl, "attn_decode_h128_gqa2w_bf16kv", 128, 2, 8, "bf16", 1024, 2048); attn_numeric_case(pl, "attn_prefill_h128_gqa2_bf16kv", 128, 2, 64, "bf16", 0, 256); attn_numeric_case(pl, "attn_decode_h128_gqa2_fp8kv", 128, 2, 1, "fp8_e4m3", 0, 256); attn_numeric_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 1, "bf16", 0, 256); From a91a2837ffa618facb6c22c87316c3cad523483a Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 031/152] arch/gemma3: Gemma 3 dense text (TranslateGemma 27B), per-(row, 128) activation linears, DFlash2 gemma4_bf16's block structure with Gemma 3's differences (modeling_gemma3, transformers 4.57): GemmaRMSNorm everywhere, one head geometry, scores at query_pre_attn_scalar^-0.5, linear rotary scaling on the global layers only, the bf16-held embedding scale, no value norm, soft-capping and YaRN refused. Linears i8a8, mxfp4a8 and w4a8i8_asym over an activation scaled per (row, 128), beside bf16 and w4a8 / w8a8: one int8 scale a row costs KL 0.097 at w8a8 on Gemma 3's outlier channels. Fused junctions on a quantised trunk. A calibration tap (RADIANCE_CALIB_DIR, RADIANCE_G3_CALIB_LAYERS), the column-split linears as rank parts. A DFlash2 drafter as qwen35_fp8 declares one; rad_block_dflash2.h applies the drafter's input_embedding_scale through embed_lookup's mult when it is not 1, so other drafters' graphs are unchanged. Against transformers' float32 forward on a tiny Gemma 3: KL 0.00016 on the host backend and the cards. arch_test: 7 cases. Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_block_dflash2.h | 25 +- arch/gemma3/CMakeLists.txt | 10 + arch/gemma3/gemma3.cpp | 1313 +++++++++++++++++++++++++++++++ tests/arch_test.cpp | 215 +++++ tests/shipped_plugins_test.cpp | 2 +- 5 files changed, 1558 insertions(+), 7 deletions(-) create mode 100644 arch/gemma3/CMakeLists.txt create mode 100644 arch/gemma3/gemma3.cpp diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h index 6dd450d7..e41ca366 100644 --- a/arch/common/rad_block_dflash2.h +++ b/arch/common/rad_block_dflash2.h @@ -113,6 +113,9 @@ struct Dflash2 { int64_t sel_topk = 16; /* candidates kept per position */ int64_t window = 0; /* sliding attention width, 0 for none */ int causal = 0; + /* The target's embedding scale, applied to the query block as the drafter was trained + * (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */ + double escale = 1.0; int64_t steps() const { return block - 1; } int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; } /* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's); @@ -468,12 +471,22 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co {w.ck, w.cv}, {}); /* ---------------------------------------------------------------- the query pass */ - op_embed = rw(b, RAD_OP(b, "embed_lookup", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), - RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), - RAD_INT("vocab_offset", g.vocab_off)), - RAD_WEIGHTS(w_tok)), - {}, {w.x}); + /* An unscaled lookup is declared exactly as before the scale existed, so a Qwen container + * resolves the same op. */ + if (cfg.escale != 1.0) + op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)), + RAD_WEIGHTS(w_tok)), + {}, {w.x}); + else + op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(w_tok)), + {}, {w.x}); /* The trunk's embedding is vocab-sharded, so the lookup is partial and needs an exact * all-reduce. */ if (g.world > 1) diff --git a/arch/gemma3/CMakeLists.txt b/arch/gemma3/CMakeLists.txt new file mode 100644 index 00000000..cd8ace6e --- /dev/null +++ b/arch/gemma3/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/gemma3 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(gemma3 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(gemma3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma3.cpp) diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp new file mode 100644 index 00000000..245ee4a8 --- /dev/null +++ b/arch/gemma3/gemma3.cpp @@ -0,0 +1,1313 @@ +/* gemma3.cpp -- Gemma 3 dense text trunk (TranslateGemma 27B), bf16 or w4a8. + * + * Built from gemma4_bf16.cpp: the same sandwich-normed blocks over one residual stream, the same + * GELU feed-forward, the same w4a8 linears and fused residual junctions. What differs, from HF's + * modeling_gemma3.py (transformers 4.57): + * + * - every norm is GemmaRMSNorm, x_hat * (1 + w), the per-head q/k norms and the final norm too; + * - one head geometry for both attention classes (head_dim 128), each with its own v projection + * and no value norm; + * - attention scores are scaled by query_pre_attn_scalar^-0.5 (1/sqrt(168) on the 27B), not by + * 1/sqrt(head_dim); + * - sliding layers rotate at rope_local_base_freq (10k) unscaled; global layers at rope_theta + * (1M) with the config's rotary scaling (linear, factor 8), which HF applies to them only; + * - the embedding is scaled by sqrt(hidden) held in the weight dtype (HF's embed_scale buffer + * cast to bf16: 73.5, not 73.32, on the 27B); + * - no layer scalar, no logit soft-capping (both softcaps are null in the 27B's config), no KV + * sharing, no partial rotary. + * + * Text only: a checkpoint's vision tower and projector are not mapped and so never converted. + */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace gemma3 { + +using namespace rad::arch; + +/* Where the language model's tensors are in a Gemma3ForConditionalGeneration checkpoint as + * transformers 4.57 saves it (TranslateGemma). */ +static const char* const kPre = "language_model.model."; +static const char* const kLayers = "language_model.model.layers"; + +/* layer_types names every layer "full_attention" or "sliding_attention"; without it, every + * `_sliding_window_pattern`-th layer is global (HF's legacy rule: (l + 1) % pattern == 0). */ +static int g3_schedule(const RadModelMeta* m, int64_t n, std::vector& is_global) { + const char* lt = meta_text_gets(m, "layer_types", nullptr); + if (lt && *lt) { + RAD_ARCH_TRY(parse_layer_kinds("gemma3", lt, {"full_attention"}, "sliding_attention", + &is_global)); + if ((int64_t)is_global.size() != n) { + fprintf(stderr, "radiance: gemma3: layer_types names %zu layers and the model has %lld\n", + is_global.size(), (long long)n); + return RAD_E_INVAL; + } + return RAD_OK; + } + const int64_t pattern = meta_text_geti(m, "_sliding_window_pattern", + meta_text_geti(m, "sliding_window_pattern", 0)); + if (pattern <= 0) { + fprintf(stderr, "radiance: gemma3: no layer_types and no sliding_window_pattern\n"); + return RAD_E_INVAL; + } + is_global.resize((size_t)n); + for (int64_t l = 0; l < n; ++l) is_global[(size_t)l] = is_full_attention(l, pattern); + return RAD_OK; +} + +struct ClassGeom { + int64_t n_head = 0, n_head_kv = 0, head_dim = 0; + int64_t window = 0; + double theta = 1.0; + float scale = 1.0f; /* rotary position divisor (linear scaling) */ + int64_t q_dim() const { return n_head * head_dim; } + int64_t kv_dim() const { return n_head_kv * head_dim; } + int64_t gqa() const { return n_head / n_head_kv; } +}; + +/* ---- one linear: gemma4_bf16's G4Linear (plain bf16, or w4a8/w8a8 over a per-row int8 + * activation), plus two formats whose activation scale is per 128 columns, not per row. + * + * Gemma 3's activations carry a few channels hundreds of times the rest, and one int8 scale a row + * spends its codes on them: on TranslateGemma 27B w8a8 alone measured KL 0.097 against bf16 + * where int8 weights alone cost 0.003. So: + * - `i8g`: int8 codes with a bf16 scale per [1 x 128] (libquant `codes=i8 group=128 + * scale=bf16`), gemm_nt_q at i8a8 over quant_act_i8g's codes, an f32 scale per (row, 128); + * - `mx`: OCP-MXFP4 (e2m1 codes, an E8M0 exponent per [1 x 32]), gemm_nt_q at mxfp4a8 over + * quant_act_fp8's E4M3 codes, an f32 scale per (row, 128); the exponent plane is passed twice, + * as b_scale and as b_ref (arch/common/rad_fp8.h LinearFP8 says why). + * Neither has a fused norm/quantiser here, so the junctions stay off for them. */ +struct G3Linear { + rad_weight w = 0, ws = 0, wref = 0; + rad_op op = 0, op_q = 0; + rad_buf q8 = 0, s8 = 0; /* the activation's code and scale planes, whatever the format */ + int64_t N = 0, K = 0; + bool quant = false; /* w4a8 / w8a8 over a per-row int8 activation */ + bool i8g = false; + bool mx = false; + bool a4 = false; /* asymmetric int4 over the per-(row, 128) int8 activation */ + bool shared_in = false; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, + std::initializer_list src, + int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, + rad_buf a, rad_buf y, + std::initializer_list row_parts = {}, + const G3Linear* in_from = nullptr); + void step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const; + void gemm(RadCtx* c, rad_buf y, int64_t T) const; +}; + +inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, + std::initializer_list src, + int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, + rad_buf a, rad_buf y, + std::initializer_list row_parts, + const G3Linear* in_from) { + N = n_out; K = n_in; + if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; + const char* wn = nm.f("%s.weight", base); + if (src.size() == 1) RAD_ARCH_TRY(map_copy(b, wn, *src.begin())); + else RAD_ARCH_TRY(map_concat(b, wn, src, 0)); + RadEncoding enc{}; + const bool known = weight_enc(b, wn, &enc); + const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 && + enc.plane[0].dtype == RAD_BF16); + int64_t parts[RAD_MAX_ROW_PARTS] = {0}; + int np = 0; + for (int64_t p : row_parts) if (np < RAD_MAX_ROW_PARTS) parts[np++] = p; + + if (plain) { + w = decl_w(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, 0, row_parts); + if (!w) return RAD_E_INVAL; + op = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w)), + { a }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } + + const RadEncPlane* sc = rad_enc_plane(&enc, "scale"); + const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0; + const bool w4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] && + (cdt == RAD_I4 || cdt == RAD_I8) && enc.plane[0].block[1] == 1 && + sc && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == 128; + if (w4) { + if (N % 16 || K % 128) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a w4 weight takes rows in " + "16s and K in whole 128-column scale groups.\n", base, + (long long)N, (long long)K); + return RAD_E_INVAL; + } + const char* sn = nm.f("%s.scale", base); + w = decl_view(b, wn, nullptr, "codes", cdt, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + ws = decl_view(b, sn, wn, "scale", RAD_F16, { N, K / 128 }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + if (!w || !ws) return RAD_E_INVAL; + if (in_from && in_from->quant && in_from->q8 && in_from->K == K) { + q8 = in_from->q8; + s8 = in_from->s8; + shared_in = true; + } else { + q8 = decl_b(b, nm.f("%s.q8", base), RAD_I8, { g.max_tok, K }); + s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, 1 }); + } + if (!q8 || !s8) return RAD_E_INVAL; + if (!shared_in) + op_q = rw(b, RAD_OP(b, "quant_act_i8", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K), + RAD_INT("group", 128), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a }, { q8, s8 }); + op = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", 128), RAD_STR("dtype", cdt == RAD_I8 ? "w8a8" : "w4a8")), + RAD_WEIGHTS(w, ws)), + { q8, s8 }, { y }); + quant = true; + return ((op_q || shared_in) && op) ? RAD_OK : RAD_E_INVAL; + } + + i8g = known && linear_is_w8(enc); + mx = known && linear_is_mxfp4(enc); + /* Asymmetric int4 (libquant `codes=u4 zero=u8 group=128 scale=f16`), unrotated: gemm_nt_q at + * w4a8i8_asym over the same per-(row, 128) int8 activation as i8g. LinearFP8 serves this grid + * only under ParoQuant's rotation, which a tensor-parallel shard cannot cut; unrotated it shards + * like any row- or column-split weight. */ + { + const RadEncPlane* zp = rad_enc_plane(&enc, "zero"); + a4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 3 && !enc.transform[0] && + enc.plane[0].dtype == RAD_U4 && enc.plane[0].block[1] == 1 && sc && + sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK && zp && + zp->dtype == RAD_U8 && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK; + } + if (a4) { + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an asymmetric int4 weight takes " + "rows in 16s and K in whole 128s\n", base, (long long)N, (long long)K); + return RAD_E_INVAL; + } + w = decl_view(b, wn, nullptr, "codes", RAD_U4, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + if (!w || !ws) return RAD_E_INVAL; + if (in_from && (in_from->i8g || in_from->a4) && in_from->q8 && in_from->K == K) { + q8 = in_from->q8; + s8 = in_from->s8; + shared_in = true; + } else { + q8 = decl_b(b, nm.f("%s.q8", base), RAD_I8, { g.max_tok, K }); + s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK }); + if (!q8 || !s8) return RAD_E_INVAL; + op_q = rw(b, RAD_OP(b, "quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a }, { q8, s8 }); + if (!op_q) return RAD_E_INVAL; + } + op = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a8i8_asym")), + RAD_WEIGHTS(w, ws)), + { q8, s8 }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } + if (i8g || mx) { + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; it takes rows in 16s and K in " + "whole %d-column activation scale groups\n", base, (long long)N, + (long long)K, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + const char* sn = nm.f("%s.scale", base); + if (mx) { + w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + wref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + if (!w || !ws || !wref) return RAD_E_INVAL; + } else { + w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + if (!w || !ws) return RAD_E_INVAL; + } + if (in_from && in_from->mx == mx && (in_from->i8g || in_from->a4) == i8g && in_from->q8 && in_from->K == K) { + q8 = in_from->q8; + s8 = in_from->s8; + shared_in = true; + } else { + q8 = decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K }); + s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK }); + if (!q8 || !s8) return RAD_E_INVAL; + op_q = rw(b, RAD_OP(b, mx ? "quant_act_fp8" : "quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a }, { q8, s8 }); + if (!op_q) return RAD_E_INVAL; + } + if (mx) + op = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")), + RAD_WEIGHTS(w, ws, wref)), + { q8, s8 }, { y }); + else + op = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "i8a8")), + RAD_WEIGHTS(w, ws)), + { q8, s8 }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } + + char en[256]; + rad_enc_format(&enc, en, sizeof en); + fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, w4a8, w8a8, " + "int8 a 128 (i8a8) or MXFP4 -- none matches\n", wn, en); + return RAD_E_DTYPE; +} + +inline void G3Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const { + if (quant) { + if (!shared_in) + RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE); + gemm(c, y, T); + } else if (i8g || mx || a4) { + /* quant_act_i8g / quant_act_fp8 take x, q, scale: no optional `asum`. */ + if (!shared_in) + RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T)); + gemm(c, y, T); + } else + RAD_ISSUE(c, op, brows(a, T), RAD_W(w), brows(y, T)); +} + +inline void G3Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const { + RAD_ISSUE_N(c, op, T, brows(q8, T), brows(s8, T), RAD_W(w), RAD_W(ws), + brows(y, T), RAD_NONE, mx ? RAD_W(wref) : RAD_NONE); +} + +/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one linear's bf16 input, + * summed over the corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set, + * for the layers RADIANCE_G3_CALIB_LAYERS names ("lo:hi", default every layer): a down projection's + * Gram is 10752^2 f32 a rank at TP2, so 62 layers of four taps do not fit beside the weights and a + * calibration runs in slices of layers, the corpus pushed through once per slice. */ +struct G3Tap { + rad_buf h = 0; + rad_op op = 0; + int64_t K = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, rad_buf a, int64_t k) { + K = k; + h = decl_b(b, nm.f("%s.gram", name), RAD_F32, { k, k }, RAD_BUF_PERSIST); + if (!h) return RAD_E_INVAL; + op = rw(b, RAD_OP(b, "gram_accum", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", k), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, h }, { h }); + return op ? RAD_OK : RAD_E_INVAL; + } + /* gram_accum takes a, a_scale?, h: no scale for a bf16 input. */ + void step(RadCtx* c, rad_buf a, int64_t T, const bool* live) const { + if (op && live && *live) RAD_ISSUE_N(c, op, T, brows(a, T), RAD_NONE, brows(h, K)); + } +}; + +/* ---- one attention block, parameterised by class. */ +struct Gemma3Attn { + struct Wire { rad_buf x = 0, h = 0, q = 0, k = 0, v = 0, attn = 0; }; + + Wire w{}; + Geom g{}; + ClassGeom cls{}; + int layer = 0; + rad_kvgroup kv = 0; + double attn_scale = 1.0; + + rad_weight w_norm = 0, w_qn = 0, w_kn = 0, w_post = 0; + G3Linear ln_q{}, ln_k{}, ln_v{}, ln_o{}; + rad_op op_norm = 0, op_qn = 0, op_kn = 0, + op_rq = 0, op_rk = 0, op_attn = 0, op_kv = 0, op_post = 0, op_ar = 0, op_add = 0; + /* the q/k norms and both rotaries as one op (libr4d `qkv_norm_rope` at v_norm 0), where it + * resolves; byte-identical to the four */ + rad_op op_qnr = 0; + /* Calibration: q|k|v's shared input and o_proj's (this rank's columns). */ + G3Tap tap_in{}, tap_o{}; + const bool* tap_live = nullptr; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, + rad_kvgroup group, const Wire& wire, double scale); + void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, + bool ar_fused = false) const; + /* The branch's post-norm alone, for a caller fusing the add and the next norm after it. */ + void post(RadCtx* c, int64_t T) const { + RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); + } +}; + +int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, + rad_kvgroup group, const Wire& wire, double scale) { + g = geom; cls = cgeo; layer = l; kv = group; w = wire; attn_scale = scale; + const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); + const char* pre = kLayers; + + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), nm.ckpt("%s.%lld.self_attn.k_norm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_post_norm.weight", l), nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l))); + w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_qn = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_BF16, {cls.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_kn = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_BF16, {cls.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_post = decl_w(b, nm.f("blk.%d.attn_post_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + + RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), + { nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l) }, + qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q)); + const G3Linear* qin = &ln_q; /* k and v read q's int8 pair */ + RAD_ARCH_TRY(ln_k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), + { nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l) }, + kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.k, {}, qin)); + RAD_ARCH_TRY(ln_v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), + { nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l) }, + kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.v, {}, qin)); + RAD_ARCH_TRY(ln_o.declare(b, nm, g, nm.f("blk.%d.attn_o", l), + { nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l) }, + g.n_embd, qd, RAD_SHARD_COL, grp_layer(l), w.attn, w.h)); + + op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + + /* Per-head q and k norms, one row per head. Gemma 3 has no value norm. */ + op_qn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head), RAD_INT("n", cls.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn)), + {w.q}, {w.q}); + op_kn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head_kv), RAD_INT("n", cls.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn)), + {w.k}, {w.k}); + + /* NeoX rotary over the full head. K is rotated as a Q-only form over its own heads (see + * gemma4_bf16: the rope kernel requires n_head > 0). `scale` divides the position: HF's + * linear scaling divides inv_freq by the factor, which is the same angle. */ + op_rq = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", 0), + RAD_F64("theta", cls.theta), RAD_F64("scale", cls.scale), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", cls.head_dim)), + RAD_NOWEIGHTS), + {w.q}, {w.q}); + op_rk = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", cls.theta), RAD_F64("scale", cls.scale), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", cls.head_dim)), + RAD_NOWEIGHTS), + {w.k}, {w.k}); + + if (rad_op_declared(b, "qkv_norm_rope")) { + op_qnr = RAD_OP(b, "qkv_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", cls.n_head_kv), + RAD_F64("theta", cls.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", cls.scale), RAD_STR("mode", "neox"), + RAD_INT("rotary_dim", cls.head_dim), RAD_F64("wadd", g.wadd_qk), + RAD_INT("v_norm", 0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn, w_kn)); + if (op_qnr) op_qnr = rw(b, op_qnr, {w.q, w.k}, {w.q, w.k}); + } + + op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), RAD_INT("window", cls.window), + RAD_INT("n_head", cls.n_head), RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_F64("scale", attn_scale), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn}); + + op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head_kv", cls.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.k, w.v}, {}); + + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + + op_post = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_post)), + {w.h}, {w.h}); + + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + return RAD_OK; +} + +void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, + bool ar_fused) const { + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + const int64_t T = batch->n_tok; + + if (entry_done) { + ln_q.gemm(c, w.q, T); + ln_k.gemm(c, w.k, T); + ln_v.gemm(c, w.v, T); + } else { + RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + ln_q.step(c, w.h, w.q, T); + ln_k.step(c, w.h, w.k, T); + ln_v.step(c, w.h, w.v, T); + tap_in.step(c, w.h, T, tap_live); + } + + if (op_qnr) { + /* v is an operand the op leaves alone at v_norm 0. */ + RAD_ISSUE(c, op_qnr, brows(w.q, T), brows(w.k, T), brows(w.v, T), rope_posmc(g, batch, T), + RAD_W(w_qn), RAD_W(w_kn)); + } else { + RAD_ISSUE_N(c, op_qn, T * cls.n_head, brows(w.q, T), RAD_W(w_qn), brows(w.q, T)); + RAD_ISSUE_N(c, op_kn, T * cls.n_head_kv, brows(w.k, T), RAD_W(w_kn), brows(w.k, T)); + RAD_ISSUE(c, op_rq, brows(w.q, T), rope_posmc(g, batch, T)); + RAD_ISSUE(c, op_rk, brows(w.k, T), rope_posmc(g, batch, T)); + } + + RAD_ISSUE(c, op_kv, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer)); + + 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, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), + brows(w.attn, T)); + + tap_o.step(c, w.attn, T, tap_live); + ln_o.step(c, w.attn, w.h, T); + /* All-reduce before the post-norm: o_proj is column-sharded, and the norm is of the sum. */ + if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + if (tail_fused) return; + RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); + RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T)); +} + +/* ---- the feed-forward: GeGLU (gelu_pytorch_tanh), second norm on the down output. */ +struct Gemma3Mlp { + struct Wire { rad_buf x = 0, h = 0, gu = 0, ffn = 0; }; + + Wire w{}; + Geom g{}; + int layer = 0; + rad_weight w_norm = 0, w_post = 0; + G3Linear ln_gu{}, ln_down{}; + rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0; + rad_op op_gq = 0; + /* Calibration: gate|up's input and down's (this rank's columns). */ + G3Tap tap_gu{}, tap_dn{}; + const bool* tap_live = nullptr; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire); + void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, + bool ar_fused = false) const; + void post(RadCtx* c, int64_t T) const { + RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); + } +}; + +int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire) { + g = geom; layer = l; w = wire; + const char* pre = kLayers; + + RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_post_norm.weight", l), nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l))); + w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_post = decl_w(b, nm.f("blk.%d.ffn_post_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + + RAD_ARCH_TRY(ln_gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), + { nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l), + nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l) }, + 2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.gu, + { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(ln_down.declare(b, nm, g, nm.f("blk.%d.ffn_down", l), + { nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l) }, + g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l), w.ffn, w.h)); + + op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + op_act = rw(b, RAD_OP(b, "gelu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.gu}, {w.ffn}); + if (ln_down.quant && !ln_down.shared_in && rad_op_declared(b, "gelu_mul_quant_i8")) + op_gq = rw(b, RAD_OP(b, "gelu_mul_quant_i8", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.gu}, {ln_down.q8, ln_down.s8}); + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_post = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_post)), + {w.h}, {w.h}); + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + return RAD_OK; +} + +void Gemma3Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, + bool ar_fused) const { + const int64_t T = batch->n_tok; + if (entry_done) { + ln_gu.gemm(c, w.gu, T); + } else { + RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + ln_gu.step(c, w.h, w.gu, T); + tap_gu.step(c, w.h, T, tap_live); + } + if (op_gq) { + RAD_ISSUE_N(c, op_gq, T, brows(w.gu, T), brows(ln_down.q8, T), brows(ln_down.s8, T), RAD_NONE); + ln_down.gemm(c, w.h, T); + } else { + RAD_ISSUE(c, op_act, brows(w.gu, T), brows(w.ffn, T)); + tap_dn.step(c, w.ffn, T, tap_live); + ln_down.step(c, w.ffn, w.h, T); + } + if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + if (tail_fused) return; + RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); + RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T)); +} + +/* ---- one residual junction as one op (libr4d `rmsnorm_quant_i8`): [post-norm of the branch, + * the add into the stream,] the next block's norm and its int8 quantiser. gemma4_bf16's + * G4Junction without the layer scalar. */ +struct G3Junction { + rad_op op = 0; + rad_op op_ar = 0; + rad_buf x = 0, res = 0, q8 = 0, s8 = 0; + rad_weight w = 0, wp = 0; + + int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_, + rad_weight wp_, const G3Linear& into) { + x = x_; res = res_; w = w_; wp = wp_; q8 = into.q8; s8 = into.s8; + if (!into.quant || into.shared_in || !q8 || !s8 || !w || (wp && !res)) + return RAD_E_INVAL; + const RadParam p[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype), + RAD_F64("wadd", g.wadd) }; + const rad_weight ws[2] = { w, wp }; + const int nw = wp ? 2 : 1; + if (rad_op_declared(b, "rmsnorm_quant_i8")) + op = rad_decl_op(b, "rmsnorm_quant_i8", p, (int)(sizeof p / sizeof p[0]), ws, nw); + if (!op) return RAD_OK; + const rad_buf rd[2] = { x, res }; + const rad_buf wr[3] = { q8, s8, res }; + rad_op_reads (b, op, rd, res ? 2 : 1); + rad_op_writes(b, op, wr, res ? 3 : 2); + if (res && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_quant_i8")) { + const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_INT("world_size", g.world), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) }; + op_ar = rad_decl_op(b, "ar_rmsnorm_quant_i8", pa, (int)(sizeof pa / sizeof pa[0]), ws, nw); + if (op_ar) { + const rad_buf wa[4] = { x, q8, s8, res }; + rad_op_reads (b, op_ar, rd, 2); + rad_op_writes(b, op_ar, wa, 4); + } + } + return RAD_OK; + } + void step(RadCtx* c, int64_t T, bool with_ar = false) const { + RAD_ISSUE_N(c, with_ar ? op_ar : op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w), + brows(q8, T), brows(s8, T), RAD_NONE, + wp ? RAD_W(wp) : RAD_NONE, RAD_NONE); + } +}; + +/* ---- the MXFP4 trunk's junction (libr4d `rmsnorm_quant_fp8`): the add of the branch `x` into + * the stream `res`, the next block's norm and its E4M3 quantiser, in one op. It has no post-norm + * slot (rmsnorm_quant_i8's w_post is Gemma 4's), so the branch's post-norm runs just before it: + * four launches a junction become two. With `res` null it is the first block's norm of the + * embedding stream. */ +struct G3JunctionFP8 { + rad_op op = 0; + /* At two ranks on the exact wire: the branch's all-reduce and post-norm folded in front + * (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. */ + rad_op op_ar = 0; + rad_buf x = 0, res = 0, q = 0, s = 0; + rad_weight w = 0, wp = 0; + int64_t n = 0; + + int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_, + const G3Linear& into, rad_weight wp_ = 0) { + x = x_; res = res_; w = w_; wp = wp_; q = into.q8; s = into.s8; n = g.n_embd; + if (!into.mx || into.shared_in || !q || !s || !w) return RAD_E_INVAL; + if (!rad_op_declared(b, "rmsnorm_quant_fp8")) return RAD_OK; + op = RAD_OP(b, "rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), + RAD_F64("wadd", g.wadd)), + RAD_WEIGHTS(w)); + if (!op) return RAD_OK; + const rad_buf rd[2] = { x, res }; + const rad_buf wr[3] = { q, s, res }; + rad_op_reads (b, op, rd, res ? 2 : 1); + rad_op_writes(b, op, wr, res ? 3 : 2); + if (res && wp && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) { + const rad_weight ws[2] = { w, wp }; + const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps), + RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("world_size", g.world), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) }; + op_ar = rad_decl_op(b, "ar_rmsnorm_post_quant_fp8", pa, (int)(sizeof pa / sizeof pa[0]), ws, 2); + if (op_ar) { + const rad_buf wa[4] = { x, q, s, res }; + rad_op_reads (b, op_ar, rd, 2); + rad_op_writes(b, op_ar, wa, 4); + } + } + return RAD_OK; + } + /* x, residual?, w -> q, scale, out_bf16?[, w_post]: the bf16 normed copy is not wanted. */ + void step(RadCtx* c, int64_t T, bool with_ar = false) const { + if (with_ar) + RAD_ISSUE_N(c, op_ar, T, brows(x, T), brows(res, T), RAD_W(w), brows(q, T), brows(s, T), + RAD_NONE, RAD_W(wp)); + else + RAD_ISSUE_N(c, op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w), + brows(q, T), brows(s, T), RAD_NONE); + } +}; + +struct Layer { + bool global = false; + Gemma3Attn attn{}; + Gemma3Mlp mlp{}; + G3Junction j_am{}, j_ma{}; + G3JunctionFP8 jf_am{}, jf_ma{}; +}; + +struct Model { + Names nm{""}; + Geom g{}; + ClassGeom cs{}; /* sliding class */ + ClassGeom cg{}; /* global class */ + + rad_kvgroup kv_s = 0, kv_g = 0; + + rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0; + rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0; + rad_buf b_gu = 0, b_ffn = 0; + + rad_weight w_tok = 0, w_out = 0, w_lm = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_final = 0, op_gather = 0, op_logits = 0; + + std::vector layers; + + G3Junction j0{}; + bool fuse = false; + G3JunctionFP8 jf0{}; + bool fuse_mx = false; /* the MXFP4 trunk's junctions (G3JunctionFP8) */ + bool fuse_mx_ar = false; /* ... each with the all-reduce and post-norm folded in */ + bool fuse_ar = false; + + /* The DFlash2 drafter and the trunk taps it reads, only when the container carries one and + * the deployment speculates (declare_dflash2). */ + Dflash2 df{}; + Dflash2::Wire dfw{}; + rad_kvgroup kv_draft = 0; + bool have_df = false; + enum { MAX_TAPS = 8 }; + int n_taps = 0; + int tap_layer[MAX_TAPS] = {}; + rad_buf b_dfsrc = 0; /* [max_tok, n_taps * n_embd] */ + rad_op op_tap = 0; + + /* The calibration tap: on while `tap_live`, over layers [calib_lo, calib_hi). */ + bool calib = false, tap_live = false; + int64_t calib_lo = 0, calib_hi = 0; + long long calib_rows = 0; +}; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== the DFlash2 drafter + * + * A second model at absolute layers n_layer.. with its own KV group (rad_block_dflash2.h), as + * qwen35_fp8 declares it. What is Gemma's here: + * - the query block's embedding is scaled as the trunk's is (input_embedding_scale, sqrt(hidden) + * in bf16), which the block applies through embed_lookup's `mult`; + * - the head is tied: the 2-bit draft head is a copy of the embedding table. + * The taps are the residual stream after the layers dflash_config.target_layer_ids names, which + * NeMo's trainer captures as HF's hidden_states[i + 1]. */ +static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m, int base_layer, const char* ck_embd) { + Names& nm = m.nm; + Geom dg{}; + RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma3 DFlash2")); + + Dflash2::Config dc{}; + dc.n_taps = m.n_taps; + dc.block = ctx->max_spec + 1; + dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); + dc.group = rad_meta_geti(meta, "draft.dflash_config.conv_group_size", 16); + dc.sel_rank = rad_meta_geti(meta, "draft.dflash_config.selector_rank", 0); + dc.sel_topk = rad_meta_geti(meta, "draft.dflash_config.selector_top_k", 0); + dc.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0; + if (rad_meta_geti(meta, "draft.use_sliding_window", 0)) + dc.window = rad_meta_geti(meta, "draft.sliding_window", 0); + dc.escale = rad_meta_getf(meta, "draft.dflash_config.input_embedding_scale", 1.0); + if (dc.sel_rank <= 0 || dc.sel_topk <= 0) { + fprintf(stderr, "radiance: gemma3: the DFlash2 drafter states no selector geometry\n"); + return RAD_E_INVAL; + } + const long long trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + if (dc.block < 2 || (dc.block & (dc.block - 1))) { + fprintf(stderr, "radiance: gemma3: DFlash2's query block has to be a power of two; this " + "serve asks for %d draft tokens (trained at %lld)\n", ctx->max_spec, trained - 1); + return RAD_E_UNSUPPORTED; + } + if (trained > 0 && trained != dc.block) + rad_note(b, "DFlash2 was trained at block_size %lld and runs at %lld", trained, + (long long)dc.block); + const double omul = rad_meta_getf(meta, "draft.dflash_config.output_multiplier", 1.0); + const double scap = rad_meta_getf(meta, "draft.dflash_config.final_logit_softcapping", 0.0); + if (omul != 1.0 || scap != 0.0) { + fprintf(stderr, "radiance: gemma3: the drafter multiplies (%g) or soft-caps (%g) its logits, " + "which is not implemented\n", omul, scap); + return RAD_E_UNSUPPORTED; + } + const double emult = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)m.g.n_embd))); + if (dc.escale != 1.0 && std::fabs(dc.escale - emult) > 1e-3) + rad_note(b, "the drafter's input_embedding_scale %g is not the trunk's %g", dc.escale, emult); + + RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, base_layer, &m.kv_draft)); + + const int64_t qd = dg.n_head * dg.head_dim; + const int64_t kvd = dg.n_head_kv * dg.head_dim; + int64_t qr = dg.max_seqs * dc.block; + if (qr > dg.max_tok) qr = dg.max_tok; + const int64_t sr = dg.max_seqs * dc.steps(); + const int64_t spad = ((sr + 15) / 16) * 16; + + Dflash2::Wire& dw = m.dfw; + dw.src = m.b_dfsrc; + dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd}); + dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd}); + dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd}); + dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd}); + dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd}); + dw.h2 = decl_b(b, nm.f("df_h2"), dg.act_dtype, {qr, dg.n_embd}); + dw.coef = decl_b(b, nm.f("df_coef"), dg.act_dtype, {qr, dc.coef_dim(dg.n_embd)}); + dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd}); + dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd}); + dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd}); + dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd}); + dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff}); + dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff}); + dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd}); + dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)}); + dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd}); + dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)}); + dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd}); + dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)}); + dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd}); + dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)}); + dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); + dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); + dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd}); + dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank}); + dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd}); + dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1}); + dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad}); + dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)}); + /* Rescoring against the trunk's head needs logit_rerank to read its rows; RADIANCE_G3_DF_RERANK=0 + * keeps the coarse head's scores. */ + { + const char* rr = std::getenv("RADIANCE_G3_DF_RERANK"); + const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16); + if (!(rr && rr[0] == '0') && (hd == RAD_F8E4M3 || hd == RAD_I8) && + (Dflash2::head_sharded(dg) || dg.world <= 1)) { + m.df.w_lm = m.w_lm; + m.df.top_w = Dflash2::kRerankR; + } + } + const int64_t tw = m.df.w_lm ? m.df.top_w : dc.sel_topk; + dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw}); + dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw}); + if (Dflash2::head_sharded(dg)) { + dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2}); + dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2}); + } + dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()}); + + RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", + nm.ckpt("%s", ck_embd), dw)); + m.have_df = true; + + RadDrafterDecl drf{}; + drf.name = "dflash2"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + drf.block = dc.block; + drf.proposal = dw.tokens; + drf.proposal_pitch = dc.steps(); + drf.window = dc.window; + drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: gemma3: the DFlash2 checkpoint declares no mask_token_id\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + rad_note(b, "DFlash2 drafter: %lld layers at absolute %d.., %lld heads / %lld kv x %lld, ffn %lld, " + "%s attention with a %lld-token window, %d trunk taps, embedding x %g, %s head", + (long long)dg.n_layer, base_layer, (long long)dg.n_head, (long long)dg.n_head_kv, + (long long)dg.head_dim, (long long)dg.n_ff, dc.causal ? "causal" : "non-causal", + (long long)dc.window, m.n_taps, dc.escale, m.df.w_lm ? "reranked 2-bit" : "2-bit"); + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + /* The rotary scaling (linear, factor 8 on the 27B) into g.rope_scale, for the global class. */ + RAD_ARCH_TRY(yarn_from(m.g, meta, "", m.g.head_dim)); + if (m.g.yarn.factor != 0.0f) { + fprintf(stderr, "radiance: gemma3: YaRN rotary scaling is not what Gemma 3 uses; refusing\n"); + return RAD_E_UNSUPPORTED; + } + + Geom& g = m.g; + Names& nm = m.nm; + + const int64_t sliding_win = meta_text_geti(meta, "sliding_window", 0); + const double theta_s = meta_text_getf(meta, "rope_local_base_freq", 0.0); + const double theta_g = meta_text_getf(meta, "rope_theta", 0.0); + const double qpas = meta_text_getf(meta, "query_pre_attn_scalar", 0.0); + const double cap_attn = meta_text_getf(meta, "attn_logit_softcapping", 0.0); + const double cap_final = meta_text_getf(meta, "final_logit_softcapping", 0.0); + + if (sliding_win <= 0) { fprintf(stderr, "radiance: gemma3: sliding_window %lld is required\n", (long long)sliding_win); return RAD_E_INVAL; } + if (!(theta_s > 0.0) || !(theta_g > 0.0)) { + fprintf(stderr, "radiance: gemma3: rope_local_base_freq and rope_theta are both required\n"); + return RAD_E_INVAL; + } + if (!(qpas > 0.0)) { fprintf(stderr, "radiance: gemma3: query_pre_attn_scalar is required\n"); return RAD_E_INVAL; } + /* Gemma 2 soft-caps; Gemma 3 does not, and these kernels cannot. A config that asks is + * refused rather than served without it. */ + if (cap_attn > 0.0 || cap_final > 0.0) { + fprintf(stderr, "radiance: gemma3: logit soft-capping (attn %g, final %g) is not implemented\n", + cap_attn, cap_final); + return RAD_E_UNSUPPORTED; + } + + /* GemmaRMSNorm everywhere: x_hat * (1 + w). */ + g.wadd = 1.0f; + g.wadd_qk = 1.0f; + + std::vector is_global; + RAD_ARCH_TRY(g3_schedule(meta, g.n_layer, is_global)); + int n_global = 0; + for (int v : is_global) n_global += v; + + m.cs.n_head = g.n_head; m.cs.n_head_kv = g.n_head_kv; m.cs.head_dim = g.head_dim; + m.cs.window = sliding_win; m.cs.theta = theta_s; m.cs.scale = 1.0f; + m.cg = m.cs; + m.cg.window = 0; m.cg.theta = theta_g; m.cg.scale = g.rope_scale; + const double attn_scale = 1.0 / std::sqrt(qpas); + + const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16); + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_WINDOW; sd.dtype = kvdt; sd.window = sliding_win; + sd.n_head_kv = g.n_head_kv; sd.head_dim = g.head_dim; + m.kv_s = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd); + RadKVGroupDecl gd{}; + gd.kind = RAD_KV_FULL; gd.dtype = kvdt; gd.window = 0; + gd.n_head_kv = g.n_head_kv; gd.head_dim = g.head_dim; + m.kv_g = rad_decl_kv_group(b, nm.f("kv_global"), &gd); + g.kv_dtype = rad_dtype_name(kvdt); + if (m.kv_s == 0 || m.kv_g == 0) { fprintf(stderr, "radiance: gemma3: a KV group failed to declare\n"); return RAD_E_INVAL; } + + /* One head geometry, so the two classes share their rows. */ + m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd}); + m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd}); + m.b_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, m.cs.q_dim()}); + m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, m.cs.kv_dim()}); + m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, m.cs.kv_dim()}); + m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, m.cs.q_dim()}); + m.b_gu = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff}); + m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff}); + m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd}); + m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); + RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + + /* The drafter's taps: one residual stream per tapped layer, copied into a column slice. */ + if (ctx->max_spec > 0) { + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "DFlash")) { + m.n_taps = parse_layer_ids(rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr), + g.n_layer, m.tap_layer, Model::MAX_TAPS); + if (m.n_taps <= 0) { + fprintf(stderr, "radiance: gemma3: the DFlash drafter names no target_layer_ids\n"); + return RAD_E_INVAL; + } + m.b_dfsrc = decl_b(b, nm.f("dflash_src"), g.act_dtype, {g.max_tok, (int64_t)m.n_taps * g.n_embd}); + m.op_tap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_dfsrc}); + } + } + + /* The vocabulary edges: the head is tied to the embedding. */ + char ck_embd[96], ck_norm[96]; + std::snprintf(ck_embd, sizeof ck_embd, "%sembed_tokens.weight", kPre); + std::snprintf(ck_norm, sizeof ck_norm, "%snorm.weight", kPre); + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("%s", ck_embd))); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("%s", ck_norm))); + RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"), nm.ckpt("%s", ck_embd))); + m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd}, + RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + m.w_out = decl_w(b, nm.f("output_norm.weight"), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.w_lm = decl_w(b, nm.f("output.weight"), weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16), + {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + + /* HF scales the embedding by its embed_scale buffer cast to the weight dtype: sqrt(hidden) + * rounded to bf16 (73.5 on the 27B). */ + const double emult = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)g.n_embd))); + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), + RAD_F64("mult", emult)), + RAD_WEIGHTS(m.w_tok)), + {}, {m.b_x}); + if (g.world > 1) + m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + Gemma3Attn::Wire aw{}; aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn; + Gemma3Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn; + + m.layers.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.global = (is_global[(size_t)l] == 1); + const ClassGeom& cgeo = lay.global ? m.cg : m.cs; + const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s; + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, attn_scale)); + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw)); + } + + /* The fused junctions, used only when every one resolves and every linear a junction feeds + * reads its int8 pair (see gemma4_bf16). */ + if (g.n_layer > 0) { + bool ok = true; + for (const Layer& lay : m.layers) + ok = ok && lay.attn.ln_q.quant && lay.attn.ln_k.shared_in && lay.attn.ln_v.shared_in && + lay.mlp.ln_gu.quant; + if (ok) { + RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, m.layers[0].attn.ln_q)); + ok = m.j0.op != 0; + for (int64_t l = 0; ok && l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + RAD_ARCH_TRY(lay.j_am.declare(b, g, m.b_h, m.b_x, lay.mlp.w_norm, lay.attn.w_post, + lay.mlp.ln_gu)); + ok = lay.j_am.op != 0; + if (ok && l + 1 < g.n_layer) { + const Layer& nx = m.layers[(size_t)l + 1]; + RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm, lay.mlp.w_post, + nx.attn.ln_q)); + ok = lay.j_ma.op != 0; + } + } + } + m.fuse = ok; + bool ar = ok && g.world == 2; + for (int64_t l = 0; ar && l < g.n_layer; ++l) { + const Layer& lay = m.layers[(size_t)l]; + ar = lay.j_am.op_ar != 0 && (l + 1 >= g.n_layer || lay.j_ma.op_ar != 0); + } + m.fuse_ar = ar; + } + + /* ---- the MXFP4 trunk's junctions, when every block's inputs are E4M3 pairs it can write. */ + if (g.n_layer > 0 && !m.fuse) { + bool ok = true; + for (const Layer& lay : m.layers) + ok = ok && lay.attn.ln_q.mx && !lay.attn.ln_q.shared_in && lay.attn.ln_k.shared_in && + lay.attn.ln_v.shared_in && lay.mlp.ln_gu.mx && !lay.mlp.ln_gu.shared_in; + if (ok) { + RAD_ARCH_TRY(m.jf0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, m.layers[0].attn.ln_q)); + ok = m.jf0.op != 0; + for (int64_t l = 0; ok && l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + RAD_ARCH_TRY(lay.jf_am.declare(b, g, m.b_h, m.b_x, lay.mlp.w_norm, lay.mlp.ln_gu, + lay.attn.w_post)); + ok = lay.jf_am.op != 0; + if (ok && l + 1 < g.n_layer) { + RAD_ARCH_TRY(lay.jf_ma.declare(b, g, m.b_h, m.b_x, m.layers[(size_t)l + 1].attn.w_norm, + m.layers[(size_t)l + 1].attn.ln_q, lay.mlp.w_post)); + ok = lay.jf_ma.op != 0; + } + } + } + m.fuse_mx = ok; + bool ar = ok && g.world == 2; + for (int64_t l = 0; ar && l < g.n_layer; ++l) { + const Layer& lay = m.layers[(size_t)l]; + ar = lay.jf_am.op_ar != 0 && (l + 1 >= g.n_layer || lay.jf_ma.op_ar != 0); + } + m.fuse_mx_ar = ar; + } + + /* ---- the calibration tap. It reads the bf16 input of every linear, which the fused junctions + * never write, so it needs an unfused container (bf16, i8a8). */ + if (calib_dir()) { + if (m.fuse) { + fprintf(stderr, "radiance: gemma3: calibration reads each linear's bf16 input, which this " + "container's fused junctions do not write; calibrate on the bf16 or an " + "i8a8 container\n"); + return RAD_E_INVAL; + } + m.calib_lo = 0; + m.calib_hi = g.n_layer; + if (const char* s = std::getenv("RADIANCE_G3_CALIB_LAYERS")) { + long long lo = 0, hi = 0; + if (std::sscanf(s, "%lld:%lld", &lo, &hi) != 2 || lo < 0 || hi > g.n_layer || lo >= hi) { + fprintf(stderr, "radiance: gemma3: RADIANCE_G3_CALIB_LAYERS '%s' is not lo:hi within " + "0:%lld\n", s, (long long)g.n_layer); + return RAD_E_INVAL; + } + m.calib_lo = lo; + m.calib_hi = hi; + } + for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) { + Layer& lay = m.layers[(size_t)l]; + RAD_ARCH_TRY(lay.attn.tap_in.declare(b, nm, g, nm.f("blk.%d.attn_in", (int)l), m.b_h, g.n_embd)); + RAD_ARCH_TRY(lay.attn.tap_o.declare(b, nm, g, nm.f("blk.%d.attn_o", (int)l), m.b_attn, m.cs.q_dim())); + RAD_ARCH_TRY(lay.mlp.tap_gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", (int)l), m.b_h, g.n_embd)); + RAD_ARCH_TRY(lay.mlp.tap_dn.declare(b, nm, g, nm.f("blk.%d.ffn_down", (int)l), m.b_ffn, g.n_ff)); + } + m.calib = true; + m.tap_live = true; + for (Layer& lay : m.layers) { lay.attn.tap_live = &m.tap_live; lay.mlp.tap_live = &m.tap_live; } + } + + m.op_final = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_out)), + {m.b_x}, {m.b_h}); + m.op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_h}, {m.b_hout}); + m.op_logits = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab), + RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_lm)), + {m.b_hout}, {m.b_logits}); + + if (m.n_taps > 0) + RAD_ARCH_TRY(declare_dflash2(b, meta, ctx, m, (int)g.n_layer, ck_embd)); + + rad_note(b, "rank %d/%d: %lld layers (%lld global, %lld sliding over %lld), %lld heads / %lld kv " + "x %lld, attention scale 1/sqrt(%g), rotary %g / %g (global position / %g), " + "embedding x %g%s", + g.rank, g.world, (long long)g.n_layer, (long long)n_global, + (long long)(g.n_layer - n_global), (long long)sliding_win, (long long)g.n_head, + (long long)g.n_head_kv, (long long)g.head_dim, qpas, theta_s, theta_g, + (double)g.rope_scale, emult, + m.fuse ? ", fused junctions" : + m.fuse_mx_ar ? ", fused fp8 junctions with the all-reduce" : + m.fuse_mx ? ", fused fp8 junctions" : ""); + return RAD_OK; +} + +static void step(RadCtx* c, const RadBatch* batch) { + Model& m = g_model[rad_rank(c)]; + if (batch->enc) { + rad_step_fail(c, "gemma3 serves text only"); + return; + } + /* A drafter pass runs only the drafter: positive is the query pass proposing the whole block, + * negative the context pass turning committed tokens into the drafter's own K and V. */ + if (batch->draft_pass != 0) { + if (!m.have_df) { + rad_step_fail(c, "the batch asks for a drafter pass and this gemma3 container declares none"); + return; + } + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(c, batch); + return; + } + const int64_t T = batch->n_tok; + /* The drafter conditions on a tapped layer's output, which the next layer overwrites: copy it + * into the tap's column slice once the layer's residual is complete. */ + auto tap = [&](size_t li) { + for (int t = 0; t < m.n_taps; ++t) + if (m.tap_layer[t] == (int)li) + RAD_ISSUE(c, m.op_tap, brows(m.b_x, T), + bcol(m.b_dfsrc, (int64_t)t * m.g.n_embd, m.g.n_embd, T)); + }; + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); + if (m.op_embed_ar) + RAD_ISSUE_N(c, m.op_embed_ar, T * m.g.n_embd, brows(m.b_x, T), RAD_NONE); + + if (m.fuse_mx) { + /* MXFP4 trunk: [post-norm, then add + next norm + quantiser as one op] at every junction; + * the last block's tail runs unfused into the final norm. */ + m.jf0.step(c, T); + for (size_t li = 0; li < m.layers.size(); ++li) { + const Layer& l = m.layers[li]; + const bool last = li + 1 == m.layers.size(); + const bool far = m.fuse_mx_ar; + l.attn.step(c, batch, true, true, far); + if (!far) l.attn.post(c, T); + l.jf_am.step(c, T, far); + l.mlp.step(c, batch, true, !last, far); + if (!last) { + if (!far) l.mlp.post(c, T); + l.jf_ma.step(c, T, far); + } + tap(li); + } + } + if (m.fuse) m.j0.step(c, T); + for (size_t li = 0; !m.fuse_mx && li < m.layers.size(); ++li) { + const Layer& l = m.layers[li]; + const bool last = li + 1 == m.layers.size(); + l.attn.step(c, batch, m.fuse, m.fuse, m.fuse_ar); + if (m.fuse) l.j_am.step(c, T, m.fuse_ar); + l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar); + if (m.fuse && !last) l.j_ma.step(c, T, m.fuse_ar); + tap(li); + } + /* With fused junctions the last layer's tail ran unfused (tail_fused false), so the stream is + * complete here either way. */ + RAD_ISSUE(c, m.op_final, brows(m.b_x, T), RAD_W(m.w_out), brows(m.b_h, T)); + + /* The tap's rows, and its files once the corpus reached RADIANCE_CALIB_TOKENS. The row-split + * linears' input is whole on every rank, so rank 0 writes it, once per linear that reads it. + * The column-split ones (o, down) see this rank's columns only: each rank writes its block as + * `.part`, which libquant's calib_sum assembles into the full K x K (block diagonal: the + * cross-rank products are never formed on one card). */ + if (m.calib && m.tap_live) { + m.calib_rows += T; + if (m.calib_rows >= calib_target()) { + const int rk = rad_rank(c); + bool ok = true; + for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) { + const Layer& lay = m.layers[(size_t)l]; + char stem[96]; + if (rk == 0) { + for (const char* which : { "attn_q", "attn_k", "attn_v" }) { + std::snprintf(stem, sizeof stem, "blk.%d.%s", (int)l, which); + ok = calib_write(c, lay.attn.tap_in.h, m.g.n_embd, m.calib_rows, stem, 0) && ok; + } + std::snprintf(stem, sizeof stem, "blk.%d.ffn_gate_up", (int)l); + ok = calib_write(c, lay.mlp.tap_gu.h, m.g.n_embd, m.calib_rows, stem, 0) && ok; + } + std::snprintf(stem, sizeof stem, "blk.%d.attn_o.part", (int)l); + ok = calib_write(c, lay.attn.tap_o.h, lay.attn.tap_o.K, m.calib_rows, stem, 0) && ok; + std::snprintf(stem, sizeof stem, "blk.%d.ffn_down.part", (int)l); + ok = calib_write(c, lay.mlp.tap_dn.h, lay.mlp.tap_dn.K, m.calib_rows, stem, 0) && ok; + } + m.tap_live = false; + std::fprintf(stderr, "radiance: gemma3: rank %d wrote the Hessians of layers %lld:%lld " + "after %lld tokens to %s%s\n", rk, (long long)m.calib_lo, + (long long)m.calib_hi, m.calib_rows, calib_dir(), ok ? "" : ", with errors"); + } + } + + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.op_gather, batch->n_out, + brows(m.b_h, T), praw(batch->out_ids, RAD_I32, batch->n_out), + brows(m.b_hout, batch->n_out)); + RAD_ISSUE_N(c, m.op_logits, batch->n_out, + brows(m.b_hout, batch->n_out), RAD_W(m.w_lm), + brows(m.b_logits, batch->n_out)); + } +} + +/* The speculation depth this container's drafter supports, answered before declare: a DFlash2 + * drafter proposes its trained block in one pass (block_size 8: 7 drafts), as qwen35_fp8 answers; + * 0 without a drafter. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (da && std::strstr(da, "DFlash2")) { + const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8); + out->draft_depth = bs > 1 ? (int)(bs - 1) : 7; + out->draft_depth_fixed = 1; /* as qwen35_fp8: the trained block */ + } + return RAD_OK; +} + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(gemma3) +RAD_ARCH_PLUGIN(gemma3, "gemma3", "", "0.1.0", + "Gemma 3 dense text trunk (TranslateGemma), bf16 or w4a8 at convert: sliding-window " + "and linearly-scaled global attention over a (1 + w) RMSNorm stream with GELU " + "feed-forward") +#endif + +} /* namespace gemma3 */ diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 29aa356e..57ace73d 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -451,6 +451,7 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s /* Gemma 4 dense: two attention classes (sliding-window + proportional-RoPE global) on one stream. */ #include "../arch/gemma4_bf16/gemma4_bf16.cpp" /* The bf16 / fp8-expert Gemma 4 plugin: the 26B-A4B's dense and routed arms side by side. */ +#include "../arch/gemma3/gemma3.cpp" #include "../arch/gemma4/gemma4.cpp" /* Qwen3-ASR: a Whisper-style audio tower over a dense Qwen3 decoder. */ #include "../arch/qwen3asr_bf16/qwen3asr_bf16.cpp" @@ -5865,6 +5866,220 @@ TEST(qwen35_fp8_steps_lint_clean_with_a_dflash2_drafter) { lint_qwen35_fp8_family(qwen35_fp8::declare, qwen35_fp8::step, mk.meta(), 7, true, 8); } +/* =============================== gemma3: TranslateGemma 27B's trunk =========================== */ + +namespace { + +/* TranslateGemma 27B's text geometry cut to twelve layers, two global (5 and 11) over ten sliding + * ones by the legacy (l + 1) % 6 rule. One head geometry for both classes (head_dim 128, 32 / 16), + * scores scaled by query_pre_attn_scalar^-0.5, linear rotary scaling on the global class only. */ +MetaKV gemma3_meta() { + RadModelMeta m{}; + m.arch_id = "gemma3"; + m.name = "test-translategemma-27b"; + m.quant = ""; + m.n_layers = 12; + m.n_embd = 5376; + m.n_head = 32; + m.n_head_kv = 16; + m.head_dim = 128; + m.n_ff = 21504; + m.n_vocab = 262208; + m.n_ctx_train = 131072; + m.rms_eps = 1e-6f; + m.rope_theta = 1e6f; + m.rope_scale = 1.0f; + MetaKV k(m); + k.set("sliding_window", "1024") + .set("_sliding_window_pattern", "6") + .set("rope_local_base_freq", "10000") + .set("rope_theta", "1000000") + .set("query_pre_attn_scalar", "168") + .set("rope_scaling.rope_type", "linear") + .set("rope_scaling.factor", "8"); + return k; +} + +MetaKV gemma3_dflash2_meta() { + MetaKV k = gemma3_meta(); + k.set("draft.architectures", "DFlash2DraftModel") + .set("draft.num_hidden_layers", "2") + .set("draft.head_dim", "128") + .set("draft.num_attention_heads", "32") + .set("draft.num_key_value_heads", "8") + .set("draft.hidden_size", "5376") + .set("draft.intermediate_size", "8192") + .set("draft.rms_norm_eps", "1e-06") + .set("draft.rope_theta", "1000000") + .set("draft.vocab_size", "262208") + .set("draft.use_sliding_window", "1") + .set("draft.sliding_window", "2048") + .set("draft.dflash_config.input_embedding_scale", "73.5") + .set("draft.dflash_config.target_layer_ids", "1 5 10") + .set("draft.dflash_config.block_size", "8") + .set("draft.dflash_config.mask_token_id", "6") + .set("draft.dflash_config.selector_rank", "64") + .set("draft.dflash_config.selector_top_k", "8") + .set("draft.dflash_config.conv_kernel_size", "2") + .set("draft.dflash_config.conv_group_size", "16"); + return k; +} + +} /* namespace */ + +/* Sliding layers in a window group declared first, the global ones in a full group, both at the + * one head geometry; layers bound by the (l + 1) % 6 rule. */ +TEST(gemma3_declares_two_kv_groups_and_binds_the_schedule) { + MetaKV mk = gemma3_meta(); + RadBuilder b; + RadBuildCtx ctx = build_ctx(); + REQUIRE_EQ(gemma3::declare(&b, mk.meta(), &ctx), RAD_OK); + REQUIRE_EQ((int)b.kv_groups.size(), 2); + CHECK_EQ(b.kv_groups[0].name, std::string("kv_sliding")); + CHECK_EQ((int)b.kv_groups[0].d.kind, RAD_KV_WINDOW); + CHECK_EQ(b.kv_groups[0].d.window, 1024); + CHECK_EQ(b.kv_groups[0].d.n_head_kv, 16); + CHECK_EQ(b.kv_groups[0].d.head_dim, 128); + CHECK_EQ(b.kv_groups[1].name, std::string("kv_global")); + CHECK_EQ((int)b.kv_groups[1].d.kind, RAD_KV_FULL); + CHECK_EQ(b.kv_groups[1].d.window, 0); + CHECK_EQ(b.kv_groups[1].d.head_dim, 128); + CHECK_EQ((int)b.binds.size(), 12); + for (int l = 0; l < 12; ++l) { + CHECK_EQ((int)b.binds[(size_t)l].first, l); + CHECK_EQ((int)b.binds[(size_t)l].second, (l + 1) % 6 == 0 ? 2 : 1); + } +} + +/* layer_types, where the config has it, names the schedule instead of the legacy pattern, and a + * count that is not the model's is refused. */ +TEST(gemma3_layer_types_name_the_global_layers) { + MetaKV mk = gemma3_meta(); + mk.set("layer_types", "[\"full_attention\", \"sliding_attention\", \"sliding_attention\", " + "\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", " + "\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", " + "\"sliding_attention\", \"sliding_attention\", \"full_attention\"]"); + RadBuilder b; + RadBuildCtx ctx = build_ctx(); + REQUIRE_EQ(gemma3::declare(&b, mk.meta(), &ctx), RAD_OK); + for (int l = 0; l < 12; ++l) + CHECK_EQ((int)b.binds[(size_t)l].second, (l == 0 || l == 11) ? 2 : 1); + + mk.set("layer_types", "[\"full_attention\", \"sliding_attention\"]"); + RadBuilder c; + CHECK(stderr_of_rc([&] { return gemma3::declare(&c, mk.meta(), &ctx); }) != RAD_OK); +} + +/* Both classes attend at 1/sqrt(query_pre_attn_scalar), not 1/sqrt(head_dim); the sliding class + * is windowed and rotates at rope_local_base_freq unscaled, the global class at rope_theta with + * the linear factor; every norm is GemmaRMSNorm (wadd 1). */ +TEST(gemma3_attention_scale_rope_and_norms_per_class) { + MetaKV mk = gemma3_meta(); + RadBuilder b; + RadBuildCtx ctx = build_ctx(); + REQUIRE_EQ(gemma3::declare(&b, mk.meta(), &ctx), RAD_OK); + std::vector at; + for (const auto& o : b.ops) if (o.op == "attn_paged") at.push_back(&o); + REQUIRE(!at.empty()); + bool windowed = false, full = false; + for (const RecOp* o : at) { + CHECK_EQ(pint(o, "head_dim"), 128); + CHECK_EQ(pint(o, "gqa"), 2); + CHECK(std::fabs(pflt(o, "scale") - 1.0 / std::sqrt(168.0)) < 1e-9); + if (pint(o, "window") == 1024) windowed = true; + if (pint(o, "window") == 0) full = true; + } + CHECK(windowed && full); + std::set> rot; /* (theta, scale) of every rotary op */ + for (const auto& o : b.ops) + if (param(&o, "theta")) rot.insert({ pflt(&o, "theta"), pflt(&o, "scale") }); + CHECK(rot.count({ 10000.0, 1.0 }) == 1); + CHECK(rot.count({ 1000000.0, 0.125 }) == 1 || rot.count({ 1000000.0, 8.0 }) == 1); + for (const auto& o : b.ops) + if (param(&o, "wadd")) CHECK_EQ(pflt(&o, "wadd"), 1.0); +} + +/* Gemma 2's soft-capping and a YaRN scaling are refused rather than served without them. */ +TEST(gemma3_refuses_softcapping_and_yarn) { + RadBuildCtx ctx = build_ctx(); + { + MetaKV mk = gemma3_meta(); + mk.set("final_logit_softcapping", "30"); + RadBuilder b; + CHECK_EQ(stderr_of_rc([&] { return gemma3::declare(&b, mk.meta(), &ctx); }), RAD_E_UNSUPPORTED); + } + { + MetaKV mk = gemma3_meta(); + mk.set("rope_scaling.rope_type", "yarn").set("rope_scaling.original_max_position_embeddings", "8192"); + RadBuilder b; + CHECK(stderr_of_rc([&] { return gemma3::declare(&b, mk.meta(), &ctx); }) != RAD_OK); + } +} + +TEST(gemma3_every_op_declares_its_buffers_and_every_weight_has_a_name_map) { + MetaKV mk = gemma3_meta(); + RadBuilder b; + RadBuildCtx ctx = build_ctx(); + REQUIRE_EQ(gemma3::declare(&b, mk.meta(), &ctx), RAD_OK); + for (const auto& o : b.ops) + if (o.resolved) CHECK(o.uses_declared); + for (const auto& w : b.weights) + if (!w.d.source) CHECK(find_map(b, w.name) != nullptr); +} + +/* A decode step and a prefill step lint clean at one and two ranks. */ +TEST(gemma3_steps_lint_clean_at_one_and_two_ranks) { + MetaKV mk = gemma3_meta(); + for (int world : { 1, 2 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + RadBuildCtx ctx = build_ctx(rank, world); + REQUIRE_EQ(gemma3::declare(&b, mk.meta(), &ctx), RAD_OK); + RadBatch batch = decode_batch(); + RadCtx c{ .b = &b, .batch = &batch }; + gemma3::step(&c, &batch); + CHECK_LINT(b, &c); + CHECK(c.step_fail.empty()); + CHECK_EQ(count_op(b, "all_reduce") + count_op(b, "ar_rmsnorm_quant_fp8") > 0, world == 2); + } +} + +/* The DFlash2 drafter: a block of 8 (depth 7, fixed), taps copied out after the named layers into + * one column-sliced buffer, the mask token from the config, and the drafter's own KV group after + * the trunk's two. Its input_embedding_scale must be the trunk's sqrt(hidden) held in bf16 + * (73.5 on the 27B), which the embedding lookup applies. */ +TEST(gemma3_dflash2_drafter_taps_and_block) { + MetaKV mk = gemma3_dflash2_meta(); + RadBuilder b; + RadBuildCtx ctx = spec_ctx(0, 1, 7); + REQUIRE_EQ(gemma3::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_BLOCK); + CHECK_EQ(b.drafter.depth, 7); + CHECK_EQ(b.drafter.block, 8); + CHECK_EQ(b.drafter.mask_token, 6); + const RecBuf* src = find_b(b, "dflash_src"); + REQUIRE(src != nullptr); + CHECK_EQ(src->d.shape[1], 3 * 5376); + CHECK_EQ((int)b.kv_groups.size(), 3); + CHECK(!noted(b, "input_embedding_scale")); + { /* A drafter trained at another embedding scale still serves, with a note. */ + MetaKV other = gemma3_dflash2_meta(); + other.set("draft.dflash_config.input_embedding_scale", "64"); + RadBuilder o; + REQUIRE_EQ(gemma3::declare(&o, other.meta(), &ctx), RAD_OK); + CHECK(noted(o, "input_embedding_scale")); + } + + RadArchProbe p{}; + CHECK_OK(gemma3::probe(mk.meta(), &p)); + CHECK_EQ(p.draft_depth, 7); + CHECK_EQ(p.draft_depth_fixed, 1); + MetaKV plain = gemma3_meta(); + RadArchProbe q{}; + CHECK_OK(gemma3::probe(plain.meta(), &q)); + CHECK_EQ(q.draft_depth, 0); +} + /* The 35B-A3B: a replicated router over every expert, a normalised top-k (norm_topk_prob * defaults on in this family; without it the weights sum to about 0.4), fp8a8 grouped GEMMs over * the expert planes, and the shared expert folded into the gather behind a sigmoid gate. */ diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index 638c8118..e471b4c5 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -88,7 +88,7 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second); } const std::set> want = { - { "breeze", "" }, { "embeddinggemma2", "" }, { "gemma4", "" }, + { "breeze", "" }, { "embeddinggemma2", "" }, { "gemma3", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, From f2c0468335e65acb8248f2bdeca47a60c47ac0f9 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 032/152] docs, recipes, compose: TranslateGemma 27B The gemma3 section of ARCHITECTURES.md (geometry, traps, KV groups, linears, calibration, measurements, the DFlash2 drafter), the calibration variable and the conversion of record in GUIDE.md, the README's models table. Recipes: the int8 calibration container (KL 0.003), MXFP4 + GPTQ (KL 0.042, 56 tok/s a stream on two R9700s), and with a drafter. The compose file serves a plain Gemma 3 template: TranslateGemma's own refuses the startup render's plain turn. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 ++ data/recipes/translategemma-27b-i8a8.recipe | 14 +++ .../translategemma-27b-mxfp4-gptq-df2.recipe | 25 +++++ .../translategemma-27b-mxfp4-gptq.recipe | 16 ++++ deploy/compose/gemma3.jinja | 4 + deploy/compose/translategemma-27b.yaml | 20 ++++ docs/ARCHITECTURES.md | 96 +++++++++++++++++++ docs/GUIDE.md | 9 ++ 8 files changed, 194 insertions(+) create mode 100644 data/recipes/translategemma-27b-i8a8.recipe create mode 100644 data/recipes/translategemma-27b-mxfp4-gptq-df2.recipe create mode 100644 data/recipes/translategemma-27b-mxfp4-gptq.recipe create mode 100644 deploy/compose/gemma3.jinja create mode 100644 deploy/compose/translategemma-27b.yaml diff --git a/README.md b/README.md index b31cc68f..594c02e5 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` | | Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` | | Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | +| TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` | | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | | EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` | @@ -54,6 +55,15 @@ with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkp that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's, and accepts 0.46 of its drafts on prose against 0.50. +TranslateGemma 27B is converted from Google's bf16 checkpoint in three steps: an int8 container to +calibrate in, its Gram matrices over translation prompts, then MXFP4 with GPTQ +(`data/recipes/translategemma-27b-*.recipe`, the steps in docs/ARCHITECTURES.md). On two R9700s it +decodes 56 tok/s a stream (205 at four) and scores mean KL 0.042 against the bf16 model on held-out +translations; with a DFlash2 drafter, 152 a stream. Its chat template takes structured turns +naming the two languages and refuses the plain turn the server renders at startup, so +`translategemma-27b.yaml` serves a plain Gemma 3 template (`deploy/compose/gemma3.jinja`) and a +client sends on `/v1/completions` the prompt the checkpoint's template renders. + The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from `Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with diff --git a/data/recipes/translategemma-27b-i8a8.recipe b/data/recipes/translategemma-27b-i8a8.recipe new file mode 100644 index 00000000..3a0b7030 --- /dev/null +++ b/data/recipes/translategemma-27b-i8a8.recipe @@ -0,0 +1,14 @@ +# translategemma-27b-i8a8.recipe -- TranslateGemma 27B (arch/gemma3) for calibration: every linear +# int8 with a bf16 scale a 128 columns, served at i8a8 over an int8 activation scaled per (row, 128). +# KL 0.003 against the bf16 model, and it fits two 32 GB cards with room for the tap's Grams. +# +# rad-convert --recipe data/recipes/translategemma-27b-i8a8.recipe \ +# -o translategemma-27b-i8a8.rad + +blk.*.attn_q.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.*.attn_o.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.*.ffn_down.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym diff --git a/data/recipes/translategemma-27b-mxfp4-gptq-df2.recipe b/data/recipes/translategemma-27b-mxfp4-gptq-df2.recipe new file mode 100644 index 00000000..a88ca9d8 --- /dev/null +++ b/data/recipes/translategemma-27b-mxfp4-gptq-df2.recipe @@ -0,0 +1,25 @@ +# translategemma-27b-mxfp4-gptq-df2.recipe -- translategemma-27b-mxfp4-gptq.recipe with a DFlash2 +# drafter (rad-convert --draft-model). The drafter's linears are MXFP4 (read whole every draft pass; +# drafts are verified, so this changes only what is proposed) and its head a 2-bit copy of the tied +# embedding, rescored against output.weight, as q38-27b-quark-mxfp4-df2.recipe makes Qwen's. +# `--reuse` of a container made by the recipe above copies its trunk. +# +# CALIB= rad-convert --draft-model \ +# --recipe data/recipes/translategemma-27b-mxfp4-gptq-df2.recipe -o translategemma-27b-mxfp4-gptq-df2.rad + +blk.*.attn_q.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.attn_k.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.attn_v.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.attn_o.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.ffn_down.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.ffn_gate_up.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search +dflash.fc.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 diff --git a/data/recipes/translategemma-27b-mxfp4-gptq.recipe b/data/recipes/translategemma-27b-mxfp4-gptq.recipe new file mode 100644 index 00000000..db76594b --- /dev/null +++ b/data/recipes/translategemma-27b-mxfp4-gptq.recipe @@ -0,0 +1,16 @@ +# translategemma-27b-mxfp4-gptq.recipe -- TranslateGemma 27B (arch/gemma3): every linear MXFP4 by +# GPTQ against the Grams a calibration run wrote (CALIB, see docs/ARCHITECTURES.md), served at +# mxfp4a8 over an E4M3 activation scaled per (row, 128). The tied lm_head is int8 a 128 columns: +# block fp8 cannot be split at --tp 2, where a rank holds 131104 vocabulary rows. Norms and the +# embedding stay bf16. KL 0.042 against the bf16 model. +# +# CALIB= rad-convert \ +# --recipe data/recipes/translategemma-27b-mxfp4-gptq.recipe -o translategemma-27b-mxfp4-gptq.rad + +blk.*.attn_q.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.attn_k.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.attn_v.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.attn_o.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.ffn_down.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +blk.*.ffn_gate_up.weight gptq codes=fp4_e2m1 group=32 scale=e8m0 calib=$CALIB +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym diff --git a/deploy/compose/gemma3.jinja b/deploy/compose/gemma3.jinja new file mode 100644 index 00000000..e882ddba --- /dev/null +++ b/deploy/compose/gemma3.jinja @@ -0,0 +1,4 @@ +{{ bos_token }}{% for message in messages %}{% set role = "model" if message["role"] == "assistant" else "user" %}{{ role }} +{{ message["content"] | trim }} +{% endfor %}{% if add_generation_prompt %}model +{% endif %} diff --git a/deploy/compose/translategemma-27b.yaml b/deploy/compose/translategemma-27b.yaml new file mode 100644 index 00000000..261440b3 --- /dev/null +++ b/deploy/compose/translategemma-27b.yaml @@ -0,0 +1,20 @@ +# TranslateGemma 27B, MXFP4 by GPTQ (data/recipes/translategemma-27b-mxfp4-gptq.recipe; the -df2 +# recipe adds a DFlash2 drafter, whose depth the server takes from the container). +# +# The checkpoint's chat template takes structured turns naming the source and target languages and +# refuses the plain turn the server renders at startup (a user turn must read +# <<>>en<<>>cs<<>>...), so a plain Gemma 3 template (gemma3.jinja, beside this +# file) stands in, and a client sends on /v1/completions the prompt the checkpoint's template renders +# ("You are a professional English (en) to Czech (cs) translator. ..."; its README shows it whole). +name: radiance-translategemma-27b +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-translategemma-27b + volumes: + - ./gemma3.jinja:/templates/gemma3.jinja:ro + command: > + --model /models/translategemma-27b-mxfp4-gptq.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 16384 --kv-cache-dtype fp8 + --override-chat-template /templates/gemma3.jinja diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index cec30f76..07f9ee9c 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -17,6 +17,7 @@ plugin claims. | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | | `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release, served w4a8. Optional draft head: Google's assistant (`rad-convert --draft-model`), with no cache of its own (`rad_drafter_shared_kv`) | +| `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) | | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 | | `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 | | `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text | @@ -559,6 +560,101 @@ under a tenth of the weight bytes, and the dense arm's 2112 is not whole 128-blo --- +# `gemma3`: Gemma 3 text (TranslateGemma) + +`arch/gemma3` serves the language model of a `Gemma3ForConditionalGeneration` checkpoint (the +vision tower and projector are not mapped, so never converted): TranslateGemma 27B, and the Gemma 3 +text sizes with its config keys. It is `gemma4_bf16`'s block structure with Gemma 3's differences; +the reference is transformers' `modeling_gemma3` (4.57). + +``` +TranslateGemma 27B (google/translategemma-27b-it) + 62 layers, hidden 5376, vocab 262208 tied to the embedding, rms_norm_eps 1e-6 + layer_types: five sliding_attention then one full_attention (without it, every + _sliding_window_pattern-th layer is global: (l + 1) % 6 == 0) + sliding 32 heads / 16 kv x 128, rope theta 1e4 (rope_local_base_freq), unscaled, window 1024 + global 32 heads / 16 kv x 128, rope theta 1e6, linear scaling factor 8 + scores scaled by query_pre_attn_scalar^-0.5 = 1/sqrt(168); q and k RMS-normed per head, v not + every norm GemmaRMSNorm, x_hat * (1 + w); sandwich norms around attention and feed-forward + feed-forward gate|up 2 x 21504 (gelu-tanh) -> down + embedding * sqrt(5376) held in bf16 (73.5); final norm; tied head; no soft-capping +``` + +Traps: + +- **The rotary scaling is the global class's only.** HF applies `rope_scaling` (linear, 8) to the + full-attention layers; the sliding ones rotate at `rope_local_base_freq` unscaled. transformers + 5.x reads TranslateGemma's flat `rope_parameters` as unscaled global layers, and llama.cpp's + current converter misses the factor too; a reference made either way is wrong by KL 0.024. +- **The scale is query_pre_attn_scalar's**, not 1/sqrt(head_dim): 1/sqrt(128) costs KL 0.013. +- **The embedding scale is sqrt(hidden) held in bf16**: 73.5, not 73.32, as HF's buffer is. +- **One int8 scale a row does not fit Gemma 3's activations**: a few channels run hundreds of times + the rest. `gemma4_bf16`'s w8a8 linears cost KL 0.097 against bf16 on TranslateGemma, w4a8 0.225, + where int8 weights alone cost 0.003. The quantised linears here scale the activation per (row, + 128). +- **Soft-capping and YaRN are refused**, not ignored: Gemma 2's caps are absent from Gemma 3, and + these kernels cannot apply them. + +Checked against transformers' float32 forward on a tiny random Gemma 3 with TranslateGemma's head +geometry, a 16-token window and the real tokenizer: KL 0.00016 on the host backend and on the cards, +at prefill and at 16-token chunks. The wrong attention scale, the missing linear scaling, a window of +15 or 17 and no window score 80 to 1600 times worse. + +**KV groups.** `kv_sliding` (`RAD_KV_WINDOW`, the 1024-token window) and `kv_global` +(`RAD_KV_FULL`), 16 heads of 128 each, 8 a rank at two. The sliding layers' group holds the window, +not the context: at a 16k context a sequence's sliding layers keep a sixteenth of what a full group +would. The cost is the prefix cache: a window group is not reused across requests (see `gemma4` +above), which matters little for translation prompts, whose shared prefix is a line. + +**Linears.** Each weight is served as its encoding stores it: + +| recipe rule | served | activation | +|---|---|---| +| none (bf16) | `gemm_nt` | bf16 | +| `codes=i4\|i8 group=128 scale=f16` | `gemm_nt_q` w4a8 / w8a8, as `gemma4_bf16` | int8, one scale a row | +| `codes=i8 group=128 scale=bf16` | `gemm_nt_q` i8a8 | int8, an f32 scale per (row, 128) (`quant_act_i8g`) | +| `codes=fp4_e2m1 group=32 scale=e8m0` (MXFP4) | `gemm_nt_q` mxfp4a8 | E4M3, a scale per (row, 128) (`quant_act_fp8`) | +| `codes=u4 zero=u8 group=128 scale=f16` | `gemm_nt_q` w4a8i8_asym | int8, a scale per (row, 128) | + +A linear reading the same activation as the one before it (k and v after q, up after gate) reuses +its codes. On an MXFP4 or int8 trunk the q and k norms and both rotaries are one `qkv_norm_rope` at +`v_norm` 0, and each junction (the branch's post-norm, the residual add, the next norm and the next +linear's quantiser) is one `ar_rmsnorm_post_quant_fp8` at two ranks on the exact wire, the branch's +all-reduce in the same launch, or a post-norm and `rmsnorm_quant_fp8` otherwise. Where a row is +missing the plugin declares the chain, and the startup notes say which form each took. + +**Calibration.** Serve a calibration container (int8, `translategemma-27b-i8a8.recipe`: KL 0.003 +against bf16, and it fits two 32 GB cards) with `RADIANCE_CALIB_DIR` set, push a corpus of the +prompts you will serve through prefill, and each linear's input Gram is written once +`RADIANCE_CALIB_TOKENS` have passed. `RADIANCE_G3_CALIB_LAYERS=lo:hi` limits the tap to a layer +slice, so the 21504-wide down projections of 62 layers can be taken in passes. At two ranks the +column-split linears (o, down) see their rank's columns only and write `.part`; libquant +assembles the parts block diagonally (docs/TOOLS.md). Give every prompt a distinct first line, or +prefix-cache hits keep tokens from the tap. + +**Measured** on two R9700s, against the bf16 model on 32 held-out translation texts (chunked at +2048 tokens), decode on an 800-token translation: + +| container | mean KL | top-1 | decode, 1 / 2 / 4 streams | +|---|---|---|---| +| int8 (calibration) | 0.003 | 98.0% | | +| **MXFP4 + GPTQ** | **0.042** | **93.2%** | **56 / 108 / 205 tok/s** | +| asymmetric int4 + GPTQ | 0.043 | 93.4% | 22 tok/s (the tiled kernel) | +| MXFP4, round to nearest | 0.142 | 87.5% | | +| w4a8, round to nearest | 0.225 | 84.1% | | + +**DFlash2.** No public drafter exists for Gemma 3. One trained with NeMo AutoModel's +`TrainDFlash2Recipe` on the target's own translations (a Qwen3-shaped draft config: plain RoPE 1e6 +and SiLU; target layers 1, 16, 30, 44, 59; mask token ``, 6; block 8; window 2048; +`dflash_config.input_embedding_scale` 73.5) is merged with `--draft-model` and served as +`qwen35_fp8` serves Qwen's: the trunk copies the residual stream after each tapped layer's junction +into `dflash_src`, the probe fixes the depth at block - 1, and `rad_block_dflash2.h` applies the +embedding scale through `embed_lookup`'s `mult` (only when it is not 1, so other drafters' graphs are +unchanged). On held-out translation prompts it accepts 3.3 tokens a verify step: 152 tok/s a stream +and 364 at four, against 56 and 175 without it. + +--- + # `qwenimage21`: Qwen-Image 2.1 and 2.1-Turbo, an image generator `arch/qwenimage21` declares a generator (`rad_declare_generator`), which makes the program a diff --git a/docs/GUIDE.md b/docs/GUIDE.md index c7d00abf..5aec839e 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -471,6 +471,14 @@ rad-convert /srv/models/MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2 --draft-model /srv rad-convert /srv/models/Launch80/Qwen3.8-27B-PARO-int5 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \ --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe -o q38-27b-paro-int5-df2.rad +# TranslateGemma 27B from Google's bf16 checkpoint: an int8 container to calibrate in, its Grams +# (serve it with RADIANCE_CALIB_DIR set and push translation prompts through prefill, see +# docs/ARCHITECTURES.md), then MXFP4 + GPTQ; with a DFlash2 drafter, the -df2 recipe and --draft-model +rad-convert /srv/models/google/translategemma-27b-it \ + --recipe data/recipes/translategemma-27b-i8a8.recipe -o translategemma-27b-i8a8.rad +CALIB=/srv/calib/translategemma rad-convert /srv/models/google/translategemma-27b-it \ + --recipe data/recipes/translategemma-27b-mxfp4-gptq.recipe -o translategemma-27b-mxfp4-gptq.rad + # unsloth's NVFP4 Qwen3.8-27B with the DFlash2 drafter: the NVFP4 MLPs and the FP8 linears beside # them made MXFP4 by one recipe, the head block fp8 rad-convert /srv/models/unsloth/Qwen3.8-27B-NVFP4 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \ @@ -2674,6 +2682,7 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_TUNE` | pin a kernel's tunable axes instead of reading the tune cache: `op:key=value[,key=value][;op:...]`. For comparing tunings, not for deployment | | `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` | | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | +| `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) | From 44aecb0ab89383cbcbbdde88cc5b7992194473ba Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 17:41:03 +0000 Subject: [PATCH 033/152] arch/gemma3: review fixes -- calibration declares no fused junction, so no container writes zero Grams; docs corrected On an MXFP4 container the fused junctions skip the bf16 activations the tap reads, and q/k/v and gate_up Grams came out zero without a word (down likewise behind gelu_mul_quant_i8). Under RADIANCE_CALIB_DIR no junction or fused down-quantiser is declared, so any container calibrates, unfused; checked on the production MXFP4 container. RADIANCE_G3_CALIB_LAYERS refuses trailing characters. Docs: which trunk fuses what, the four-stream numbers' two workloads, which sizes are tested. arch_test's world-2 check counts the post-norm op. Co-Authored-By: Claude Opus 5.5 --- arch/gemma3/gemma3.cpp | 21 ++++++++++----------- docs/ARCHITECTURES.md | 26 ++++++++++++++++---------- tests/arch_test.cpp | 3 ++- 3 files changed, 28 insertions(+), 22 deletions(-) diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index 245ee4a8..058635f8 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -576,7 +576,8 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.gu}, {w.ffn}); - if (ln_down.quant && !ln_down.shared_in && rad_op_declared(b, "gelu_mul_quant_i8")) + // Not under calibration: the tap reads the bf16 activation this fusion never writes. + if (ln_down.quant && !ln_down.shared_in && !calib_dir() && rad_op_declared(b, "gelu_mul_quant_i8")) op_gq = rw(b, RAD_OP(b, "gelu_mul_quant_i8", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), @@ -1058,7 +1059,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* The fused junctions, used only when every one resolves and every linear a junction feeds * reads its int8 pair (see gemma4_bf16). */ - if (g.n_layer > 0) { + // Neither junction family under calibration: the tap reads each linear's bf16 input, which + // the fused junctions never write (an MXFP4 container wrote zero Grams for q/k/v and gate_up). + if (g.n_layer > 0 && !calib_dir()) { bool ok = true; for (const Layer& lay : m.layers) ok = ok && lay.attn.ln_q.quant && lay.attn.ln_k.shared_in && lay.attn.ln_v.shared_in && @@ -1089,7 +1092,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } /* ---- the MXFP4 trunk's junctions, when every block's inputs are E4M3 pairs it can write. */ - if (g.n_layer > 0 && !m.fuse) { + if (g.n_layer > 0 && !m.fuse && !calib_dir()) { bool ok = true; for (const Layer& lay : m.layers) ok = ok && lay.attn.ln_q.mx && !lay.attn.ln_q.shared_in && lay.attn.ln_k.shared_in && @@ -1119,19 +1122,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } /* ---- the calibration tap. It reads the bf16 input of every linear, which the fused junctions - * never write, so it needs an unfused container (bf16, i8a8). */ + * never write, so under it none is declared (above): any container calibrates, unfused. */ if (calib_dir()) { - if (m.fuse) { - fprintf(stderr, "radiance: gemma3: calibration reads each linear's bf16 input, which this " - "container's fused junctions do not write; calibrate on the bf16 or an " - "i8a8 container\n"); - return RAD_E_INVAL; - } m.calib_lo = 0; m.calib_hi = g.n_layer; if (const char* s = std::getenv("RADIANCE_G3_CALIB_LAYERS")) { long long lo = 0, hi = 0; - if (std::sscanf(s, "%lld:%lld", &lo, &hi) != 2 || lo < 0 || hi > g.n_layer || lo >= hi) { + int used = 0; + if (std::sscanf(s, "%lld:%lld%n", &lo, &hi, &used) != 2 || s[used] != '\0' || lo < 0 || + hi > g.n_layer || lo >= hi) { fprintf(stderr, "radiance: gemma3: RADIANCE_G3_CALIB_LAYERS '%s' is not lo:hi within " "0:%lld\n", s, (long long)g.n_layer); return RAD_E_INVAL; diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 07f9ee9c..415f04a0 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -563,8 +563,10 @@ under a tenth of the weight bytes, and the dense arm's 2112 is not whole 128-blo # `gemma3`: Gemma 3 text (TranslateGemma) `arch/gemma3` serves the language model of a `Gemma3ForConditionalGeneration` checkpoint (the -vision tower and projector are not mapped, so never converted): TranslateGemma 27B, and the Gemma 3 -text sizes with its config keys. It is `gemma4_bf16`'s block structure with Gemma 3's differences; +vision tower and projector are not mapped, so never converted). Written and measured for +TranslateGemma 27B; another Gemma 3 size with the same config keys should declare (4B and 12B have +a 256 head, served by the h256 rows) but is untested, and the 1B, a `Gemma3ForCausalLM`, keeps its +tensors under names this plugin does not map. It is `gemma4_bf16`'s block structure with Gemma 3's differences; the reference is transformers' `modeling_gemma3` (4.57). ``` @@ -617,16 +619,19 @@ above), which matters little for translation prompts, whose shared prefix is a l | `codes=u4 zero=u8 group=128 scale=f16` | `gemm_nt_q` w4a8i8_asym | int8, a scale per (row, 128) | A linear reading the same activation as the one before it (k and v after q, up after gate) reuses -its codes. On an MXFP4 or int8 trunk the q and k norms and both rotaries are one `qkv_norm_rope` at -`v_norm` 0, and each junction (the branch's post-norm, the residual add, the next norm and the next -linear's quantiser) is one `ar_rmsnorm_post_quant_fp8` at two ranks on the exact wire, the branch's -all-reduce in the same launch, or a post-norm and `rmsnorm_quant_fp8` otherwise. Where a row is -missing the plugin declares the chain, and the startup notes say which form each took. +its codes. On every trunk the q and k norms and both rotaries are one `qkv_norm_rope` at `v_norm` 0. +On an MXFP4 trunk each junction (the branch's post-norm, the residual add, the next norm and the +next linear's E4M3 quantiser) is one `ar_rmsnorm_post_quant_fp8` at two ranks on the exact wire, +the branch's all-reduce in the same launch, or a post-norm and `rmsnorm_quant_fp8` otherwise; a +w4a8 / w8a8 trunk takes `gemma4_bf16`'s fused junctions; an i8a8 or asymmetric-int4 trunk runs the +chain. Where a row is missing the plugin declares the chain, and the startup notes say which form +each took. Under calibration no junction is fused (below). **Calibration.** Serve a calibration container (int8, `translategemma-27b-i8a8.recipe`: KL 0.003 against bf16, and it fits two 32 GB cards) with `RADIANCE_CALIB_DIR` set, push a corpus of the prompts you will serve through prefill, and each linear's input Gram is written once -`RADIANCE_CALIB_TOKENS` have passed. `RADIANCE_G3_CALIB_LAYERS=lo:hi` limits the tap to a layer +`RADIANCE_CALIB_TOKENS` have passed; the junctions run unfused meanwhile, so the tap sees every +linear's bf16 input from any container. `RADIANCE_G3_CALIB_LAYERS=lo:hi` limits the tap to a layer slice, so the 21504-wide down projections of 62 layers can be taken in passes. At two ranks the column-split linears (o, down) see their rank's columns only and write `.part`; libquant assembles the parts block diagonally (docs/TOOLS.md). Give every prompt a distinct first line, or @@ -650,8 +655,9 @@ and SiLU; target layers 1, 16, 30, 44, 59; mask token ``, 6; block 8; w `qwen35_fp8` serves Qwen's: the trunk copies the residual stream after each tapped layer's junction into `dflash_src`, the probe fixes the depth at block - 1, and `rad_block_dflash2.h` applies the embedding scale through `embed_lookup`'s `mult` (only when it is not 1, so other drafters' graphs are -unchanged). On held-out translation prompts it accepts 3.3 tokens a verify step: 152 tok/s a stream -and 364 at four, against 56 and 175 without it. +unchanged). On 64 held-out translation pieces it accepts 3.3 tokens a verify step: 152 tok/s a +stream and 364 at four, against 56 and 175 without it on the same pieces (the table's 205 at four +is one 800-token translation run four times). --- diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 57ace73d..b4e70477 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -6040,7 +6040,8 @@ TEST(gemma3_steps_lint_clean_at_one_and_two_ranks) { gemma3::step(&c, &batch); CHECK_LINT(b, &c); CHECK(c.step_fail.empty()); - CHECK_EQ(count_op(b, "all_reduce") + count_op(b, "ar_rmsnorm_quant_fp8") > 0, world == 2); + CHECK_EQ(count_op(b, "all_reduce") + count_op(b, "ar_rmsnorm_quant_fp8") + + count_op(b, "ar_rmsnorm_post_quant_fp8") > 0, world == 2); } } From 748f63637e51046a2de896ecdd0c817db9408e7d Mon Sep 17 00:00:00 2001 From: Nunze Date: Mon, 19 Oct 2026 13:16:45 +0200 Subject: [PATCH 034/152] docker: the test stage's parallelism and CPU budgets apart from the compile (build.sh -J, -B) The per-binary CPU budgets are set on a fast machine. A VM on an EPYC 7302 spends 4.6x the quoted CPU time on tokenizer_test's reference pass, so the image's test stage failed there on a correct tree, and -j sized for the compile also sized the tests: twelve at once on a 24-thread host put tests on busy SMT siblings, which costs CPU seconds too. RAD_TEST_CPU_BUDGET_SCALE multiplies the budget where rad_test.h reads it, at run time, so a direct ctest takes it as well and the build layer is untouched by it. The stage takes it as TEST_CPU_BUDGET_SCALE (build.sh -B) and its parallelism as TEST_JOBS (build.sh -J), each empty by default, which is the stage as before. harness_test checks the factor and keeps it out of its fixture's environment; docs/DOCKER.md. Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 15 +++++++++++---- docker/build.sh | 8 ++++++++ docs/DOCKER.md | 2 ++ tests/harness_test.cpp | 8 +++++++- tests/rad_test.h | 6 +++++- 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/Dockerfile b/Dockerfile index 151fd6ba..a3e09394 100644 --- a/Dockerfile +++ b/Dockerfile @@ -202,21 +202,28 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ # ------------------------------------------------------------------------------------------- test FROM build AS test ARG JOBS= +# Tests at a time when it should differ from JOBS (below). +ARG TEST_JOBS= +# A factor on every test's CPU budget (RAD_TEST_CPU_BUDGET_SCALE, tests/rad_test.h), for a host +# slower per thread than the one the budgets were set on: a VM on an EPYC 7302 spends 4.6x the +# quoted CPU time on tokenizer_test's reference pass. +ARG TEST_CPU_BUDGET_SCALE= # Host-only: a build container has no /dev/kfd. The `gpu`-labelled tests (the *_card entries, # r4d_selftest, kbench) run against a card from this stage: # docker buildx build --target build -t radiance-build . && docker run --rm \ # --device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined radiance-build \ # ctest --test-dir /build -L gpu --output-on-failure -# Tests run JOBS at a time (default one per two hardware threads, about one per core on an SMT -# machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do not share a -# core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build +# Tests run TEST_JOBS at a time, else JOBS (default one per two hardware threads, about one per +# core on an SMT machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do +# not share a core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build # sandbox forbids io_uring, so avx_check skips its file-backed gather case, and perf_event_open, so # the tests that bound work count CPU time rather than instructions (tests/work_counter.h). The # `oot` suite (every shipped plugin rebuilt against the installed package) repeats this stage's # whole compile, so it runs from the development tree instead (tests/oot_plugins.sh). RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ bash /src/docker/llvm-check.sh /build \ - && ctest --test-dir /build -LE 'gpu|oot' -j"${JOBS:-$(( ($(nproc) + 1) / 2 ))}" --output-on-failure \ + && RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \ + ctest --test-dir /build -LE 'gpu|oot' -j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \ && touch /build/host-tests-passed # ----------------------------------------------------------------------------------------- rootfs diff --git a/docker/build.sh b/docker/build.sh index 5a632e7e..1befd3ca 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -11,6 +11,9 @@ # docker/build.sh -r COMMIT another commit # docker/build.sh -t 'gfx1200;gfx1201' other GPU architectures (default gfx1201) # docker/build.sh -j 8 fewer compile jobs, for a host that is also serving +# docker/build.sh -J 4 fewer tests at a time (default: the compile jobs) +# docker/build.sh -B 5 multiply every test's CPU budget, for a host slower per +# thread than the one the budgets were set on # docker/build.sh --target build stop at a stage (tagged radiance-), e.g. for the # GPU test suites # @@ -22,6 +25,8 @@ REV=HEAD HOST= TARGETS=gfx1201 JOBS= +TEST_JOBS= +BUDGET_SCALE= STAGE= while [ $# -gt 0 ]; do case "$1" in @@ -29,6 +34,8 @@ while [ $# -gt 0 ]; do -r) shift; REV="$1" ;; -t) shift; TARGETS="$1" ;; -j) shift; JOBS="$1" ;; + -J) shift; TEST_JOBS="$1" ;; + -B) shift; BUDGET_SCALE="$1" ;; --target) shift; STAGE="$1" ;; *) echo "docker/build.sh: unknown option $1" >&2; exit 2 ;; esac @@ -45,6 +52,7 @@ else TAGS="-t radiance:$VERSION -t radiance:$SHA -t radiance:latest" fi CMD="docker buildx build --load --build-arg GPU_TARGETS='$TARGETS' --build-arg JOBS='$JOBS'" +CMD="$CMD --build-arg TEST_JOBS='$TEST_JOBS' --build-arg TEST_CPU_BUDGET_SCALE='$BUDGET_SCALE'" CMD="$CMD --build-arg VERSION='$VERSION' --build-arg REVISION='$SHA' $TAGS -" echo "radiance $VERSION ($SHA) for $TARGETS${HOST:+ on $HOST}${STAGE:+, stage $STAGE}" diff --git a/docs/DOCKER.md b/docs/DOCKER.md index d57937e1..152dbfbc 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -23,6 +23,8 @@ the build if a file in the image cannot be traced to a package. docker/build.sh # HEAD, tagged radiance:, radiance:, radiance:latest docker/build.sh -s gpu-host # stream the commit over ssh; gpu-host builds and keeps the image docker/build.sh -j 8 # cap compile jobs (a device kernel takes 2-3 GB under hipcc) +docker/build.sh -J 4 # tests at a time (default: the compile jobs) +docker/build.sh -B 5 # every test's CPU budget times 5, for a host slower per thread docker/build.sh -t 'gfx1200;gfx1201' # GPU architectures to compile kernels for (default gfx1201) docker/build.sh -r # any other commit docker/build.sh --target build # stop at a stage, tagged radiance- diff --git a/tests/harness_test.cpp b/tests/harness_test.cpp index e2245705..df74d726 100644 --- a/tests/harness_test.cpp +++ b/tests/harness_test.cpp @@ -23,7 +23,7 @@ struct Run { * inherited from ctest. */ Run fixture(const std::string& args, const std::string& env = "") { const std::string cmd = "env -u RAD_TEST_FILTER -u RAD_TEST_STRICT -u RAD_TEST_LEVEL " - "-u RAD_TEST_CPU_BUDGET " + env + " '" RAD_HARNESS_FIXTURE "' " + + "-u RAD_TEST_CPU_BUDGET -u RAD_TEST_CPU_BUDGET_SCALE " + env + " '" RAD_HARNESS_FIXTURE "' " + args + " 2>&1"; Run r; FILE* p = popen(cmd.c_str(), "r"); @@ -194,6 +194,12 @@ TEST(a_binary_over_its_cpu_budget_fails) { CHECK(has(r.out, "slowest: burns_cpu ")); r = fixture("passes_one", "RAD_TEST_CPU_BUDGET=60"); CHECK_EQ(r.status, 0); + /* A slower host scales every budget by one factor. */ + r = fixture("burns_cpu passes_one", "RAD_TEST_CPU_BUDGET=0.05 RAD_TEST_CPU_BUDGET_SCALE=2"); + CHECK_EQ(r.status, 1); + CHECK(has(r.out, "over its budget of 0.1 s")); + r = fixture("burns_cpu passes_one", "RAD_TEST_CPU_BUDGET=0.05 RAD_TEST_CPU_BUDGET_SCALE=100"); + CHECK_EQ(r.status, 0); } /* A command line the harness does not understand is refused rather than read as a filter. */ diff --git a/tests/rad_test.h b/tests/rad_test.h index 426064a8..5872ad56 100644 --- a/tests/rad_test.h +++ b/tests/rad_test.h @@ -14,6 +14,8 @@ * RAD_TEST_TMPDIR where tmpdir() is made, before $TMPDIR and /tmp * RAD_TEST_CPU_BUDGET seconds of process CPU time the binary may spend; over it, it fails * tests/CMakeLists.txt sets the last three for every ctest entry. + * RAD_TEST_CPU_BUDGET_SCALE a factor on that budget, for a host slower per thread than the + * one the budgets were set on; unset or 0 is 1 * * Exit status: 1 when a check failed (an exception escaping a case is a failed check), 77 when * nothing failed and no check ran, 2 for a command line it does not understand, else 0. 77 is @@ -288,7 +290,9 @@ inline int run_all(int argc, char** argv) { * so a slow case or a spinning thread pool is caught when it lands. CPU time rather than wall * time, so a loaded machine does not fail a correct binary. */ if (const char* b = std::getenv("RAD_TEST_CPU_BUDGET")) { - const double budget = std::atof(b); + double budget = std::atof(b); + if (const char* s = std::getenv("RAD_TEST_CPU_BUDGET_SCALE"); s && std::atof(s) > 0) + budget *= std::atof(s); if (budget > 0 && cpu > budget && rc != 1) { fprintf(stderr, " FAIL the binary spent %.2f s of CPU, over its budget of %g s " "(RAD_TEST_CPU_BUDGET)\n", cpu, budget); From da1ffff9a8db53adec4940966c2ecffb8c4ae41d Mon Sep 17 00:00:00 2001 From: Nunze Date: Mon, 19 Oct 2026 13:17:03 +0200 Subject: [PATCH 035/152] docker: the test stage can leave entries out (TEST_EXCLUDE, build.sh -E) Without perf_event_open in the build sandbox, tokenizer_perf_test bounds the encoder's linearity by CPU time. Its 500 KB single word reads a ratio of 10 to 12 against the threshold of 9 on a Zen 2 VM with 512 KiB of L2, every run, with the tokenizer unchanged. A ctest -E regex lets such a host build the image without the threshold moving for everyone. Empty by default. docs/DOCKER.md. Co-Authored-By: Claude Opus 5.5 --- Dockerfile | 7 ++++++- docker/build.sh | 4 ++++ docs/DOCKER.md | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index a3e09394..14cd05d7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -208,6 +208,10 @@ ARG TEST_JOBS= # slower per thread than the one the budgets were set on: a VM on an EPYC 7302 spends 4.6x the # quoted CPU time on tokenizer_test's reference pass. ARG TEST_CPU_BUDGET_SCALE= +# A ctest -E regex of entries to leave out, for a host where a timing assertion does not hold: +# tokenizer_perf_test's one-word ratio reads 10-12 against its 9 on a Zen 2 VM with 512 KiB of L2, +# where the sandbox leaves it CPU time rather than instructions to count. +ARG TEST_EXCLUDE= # Host-only: a build container has no /dev/kfd. The `gpu`-labelled tests (the *_card entries, # r4d_selftest, kbench) run against a card from this stage: # docker buildx build --target build -t radiance-build . && docker run --rm \ @@ -223,7 +227,8 @@ ARG TEST_CPU_BUDGET_SCALE= RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ bash /src/docker/llvm-check.sh /build \ && RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \ - ctest --test-dir /build -LE 'gpu|oot' -j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \ + ctest --test-dir /build -LE 'gpu|oot' ${TEST_EXCLUDE:+-E "${TEST_EXCLUDE}"} \ + -j"${TEST_JOBS:-${JOBS:-$(( ($(nproc) + 1) / 2 ))}}" --output-on-failure \ && touch /build/host-tests-passed # ----------------------------------------------------------------------------------------- rootfs diff --git a/docker/build.sh b/docker/build.sh index 1befd3ca..db5c59fd 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -14,6 +14,7 @@ # docker/build.sh -J 4 fewer tests at a time (default: the compile jobs) # docker/build.sh -B 5 multiply every test's CPU budget, for a host slower per # thread than the one the budgets were set on +# docker/build.sh -E tokenizer_perf_test leave tests matching a regex out of the test stage # docker/build.sh --target build stop at a stage (tagged radiance-), e.g. for the # GPU test suites # @@ -27,6 +28,7 @@ TARGETS=gfx1201 JOBS= TEST_JOBS= BUDGET_SCALE= +TEST_EXCLUDE= STAGE= while [ $# -gt 0 ]; do case "$1" in @@ -36,6 +38,7 @@ while [ $# -gt 0 ]; do -j) shift; JOBS="$1" ;; -J) shift; TEST_JOBS="$1" ;; -B) shift; BUDGET_SCALE="$1" ;; + -E) shift; TEST_EXCLUDE="$1" ;; --target) shift; STAGE="$1" ;; *) echo "docker/build.sh: unknown option $1" >&2; exit 2 ;; esac @@ -53,6 +56,7 @@ else fi CMD="docker buildx build --load --build-arg GPU_TARGETS='$TARGETS' --build-arg JOBS='$JOBS'" CMD="$CMD --build-arg TEST_JOBS='$TEST_JOBS' --build-arg TEST_CPU_BUDGET_SCALE='$BUDGET_SCALE'" +CMD="$CMD --build-arg TEST_EXCLUDE='$TEST_EXCLUDE'" CMD="$CMD --build-arg VERSION='$VERSION' --build-arg REVISION='$SHA' $TAGS -" echo "radiance $VERSION ($SHA) for $TARGETS${HOST:+ on $HOST}${STAGE:+, stage $STAGE}" diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 152dbfbc..9df15ae7 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -25,6 +25,7 @@ docker/build.sh -s gpu-host # stream the commit over ssh; gpu-host bu docker/build.sh -j 8 # cap compile jobs (a device kernel takes 2-3 GB under hipcc) docker/build.sh -J 4 # tests at a time (default: the compile jobs) docker/build.sh -B 5 # every test's CPU budget times 5, for a host slower per thread +docker/build.sh -E tokenizer_perf_test # leave tests matching a regex out of the test stage docker/build.sh -t 'gfx1200;gfx1201' # GPU architectures to compile kernels for (default gfx1201) docker/build.sh -r # any other commit docker/build.sh --target build # stop at a stage, tagged radiance- From a14fab231779e95041a0457b1976471711f726ca Mon Sep 17 00:00:00 2001 From: Nunze Date: Mon, 19 Oct 2026 13:13:24 +0200 Subject: [PATCH 036/152] jinja: a dotted integer is an index, as in jinja2 -- llama.cpp's #28817 jinja2 reads `obj.0` as `obj[0]`; the engine threw "Static member property must be an identifier". GLM-5's template tests a tool result with `m.content.0.type`, and the capability probe swallows the throw, so the template came back as tools=0 tool_calls=0 and every request with `tools` was refused. The fix is llama.cpp's ae9afff8, which landed after the lifted commit, taken as it is so the next refresh drops it. vendor/patches/0021, vendor/UPSTREAM; chat_test (a_dotted_integer_is_an_index_as_in_jinja2) fails without it on both counts. Co-Authored-By: Claude Opus 5.5 --- tests/chat_test.cpp | 27 +++++++++++++++++++ vendor/UPSTREAM | 10 +++++++ vendor/llama/common/jinja/runtime.cpp | 6 +++++ ...1-jinja-a-dotted-integer-is-an-index.patch | 17 ++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 vendor/patches/0021-jinja-a-dotted-integer-is-an-index.patch diff --git a/tests/chat_test.cpp b/tests/chat_test.cpp index 32c04564..7bdb06bc 100644 --- a/tests/chat_test.cpp +++ b/tests/chat_test.cpp @@ -1016,6 +1016,33 @@ TEST(the_capability_probe_reads_what_the_template_actually_does) { CHECK(c.system_role); } +/* jinja2 reads `obj.0` as `obj[0]`, and GLM-5's template tests a tool result with + * `m.content.0.type`. The engine threw on it, and the probe, which swallows a throw, reported a + * template that renders tools as one that cannot: every request with `tools` was refused. */ +TEST(a_dotted_integer_is_an_index_as_in_jinja2) { + ChatTemplate glm; + CHECK_OK(glm.load( + "{%- if tools %}{% for t in tools %}{{ t.function.name }};{% endfor %}{% endif %}" + "{%- for m in messages %}" + "{%- if m.role == 'tool' and m.content is not mapping and m.content.0.type == 'tool_reference' %}" + "{%- else %}<{{ m.role }}>{{ m.content }}" + "{%- if m.tool_calls %}{% for c in m.tool_calls %}{{ c.function.name }}{% endfor %}{% endif %}" + "{%- endif %}" + "{%- endfor %}" + "{%- if add_generation_prompt %}{% endif %}", "", "")); + CHECK(glm.caps().tools); + CHECK(glm.caps().tool_calls); + + ChatTemplate first; + CHECK_OK(first.load("{{ messages.0.content }}|{{ messages.1.role }}", "", "")); + json msgs = json::array(); + msgs.push_back({{"role", "user"}, {"content", "hi"}}); + msgs.push_back({{"role", "assistant"}, {"content", "hello"}}); + ChatPrompt p; + CHECK_OK(first.apply(msgs, json(), ChatOptions{}, &p)); + CHECK_EQ(p.prompt, std::string("hi|assistant")); +} + /* Unparseable Jinja (common in hand-built containers) is reported at load time as an error value; * a throw would cross the bringup path. */ TEST(a_template_that_does_not_parse_is_a_value_and_not_a_throw) { diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index a2fcf8ef..12b439eb 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -64,6 +64,7 @@ vendor/llama/common/jinja/ <- llama.cpp common/jinja/ llama.h, no common.h -- which is why it lifts cleanly and chat.cpp did not. LOCAL CHANGES: patches/0015-jinja-print-a-list-or-a-dict-as-its-repr.patch + patches/0021-jinja-a-dotted-integer-is-an-index.patch vendor/llama/common/chat.{h,cpp} vendor/llama/common/chat-auto-parser.h @@ -554,3 +555,12 @@ PATCH SERIES \u form of a character it leaves out (\u0009 for \t), and a positive class admits \t \n \r \f \b only in their short form. gbnf_test covers each escape in and out of a class, quantified, and negated, and the refusals. + + patches/0021-jinja-a-dotted-integer-is-an-index.patch + + llama.cpp's ae9afff8 ("jinja : support dot property integer literals (#28817)"), after the + lifted commit; drop it on the next refresh. jinja2 reads `obj.0` as `obj[0]`; the engine + threw "Static member property must be an identifier". GLM-5's template tests a tool result + with `m.content.0.type`, and since the probe swallows the throw the template came back as + tools=0 tool_calls=0, as 0006 describes: every request with `tools` was refused. + tests/chat_test.cpp (a_dotted_integer_is_an_index_as_in_jinja2). diff --git a/vendor/llama/common/jinja/runtime.cpp b/vendor/llama/common/jinja/runtime.cpp index f81d98d9..5a089d3d 100644 --- a/vendor/llama/common/jinja/runtime.cpp +++ b/vendor/llama/common/jinja/runtime.cpp @@ -779,6 +779,12 @@ value member_expression::execute_impl(context & ctx) { } else { property = this->property->execute(ctx); } + } else if (is_stmt(this->property)) { + // syntax: obj.index + property = mk_val(cast_stmt(this->property)->val); + if (property->as_int() < 0) { + throw std::runtime_error("Static member property cannot be negative"); + } } else { // syntax: obj.prop if (!is_stmt(this->property)) { diff --git a/vendor/patches/0021-jinja-a-dotted-integer-is-an-index.patch b/vendor/patches/0021-jinja-a-dotted-integer-is-an-index.patch new file mode 100644 index 00000000..435443f3 --- /dev/null +++ b/vendor/patches/0021-jinja-a-dotted-integer-is-an-index.patch @@ -0,0 +1,17 @@ +diff --git a/common/jinja/runtime.cpp b/common/jinja/runtime.cpp +index f81d98d..5a089d3 100644 +--- a/common/jinja/runtime.cpp ++++ b/common/jinja/runtime.cpp +@@ -779,6 +779,12 @@ value member_expression::execute_impl(context & ctx) { + } else { + property = this->property->execute(ctx); + } ++ } else if (is_stmt(this->property)) { ++ // syntax: obj.index ++ property = mk_val(cast_stmt(this->property)->val); ++ if (property->as_int() < 0) { ++ throw std::runtime_error("Static member property cannot be negative"); ++ } + } else { + // syntax: obj.prop + if (!is_stmt(this->property)) { From c00a650bce641073000068f5b66e594806677712 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 037/152] libr4d: fp8_v4 and k6_v4 caches -- stores, folded prologues, h256/gqa6 attention Two narrower layouts of an attention cache, a head's dims in groups of 32 with an f16 scale: fp8_v4 (E4M3 K, int4 V; 25 * head_dim / 16 bytes a token and head) and k6_v4 (int6 K, int4 V; 22 / 16). kv_store and qk_norm_rope_gate_kv_store write them (the folds byte-identical to the pairs); attn_prefill / attn_decode at h256 gqa6 widen the codes to f16 in a tile's staging, V a key pair's 8 dims a thread fetched a tile ahead and widened with packed f16 (one rounding, a dword store holding both keys), K6's high bits laid out so one mask and shift join them to the low nibbles. r4d_selftest: the stores against an exactly representable set, the folds, and the attention rows against the inline oracle extended to the layouts. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_attn_args.h | 12 +- libr4d/r4d_attn_decode_h256_gqa6.hip | 93 +++++++++++- libr4d/r4d_attn_paged_h256_gqa6.hip | 70 ++++++++- libr4d/r4d_attn_prefill_h256_gqa6.hip | 95 +++++++++++- libr4d/r4d_dt16.h | 25 +++ libr4d/r4d_model_bf16.hip | 111 +++++++++++++- libr4d/r4d_plugin.h | 10 ++ libr4d/r4d_qk_norm_rope_gate.hip | 91 ++++++++++- libr4d/r4d_rows.cpp | 110 ++++++++++++++ libr4d/r4d_selftest.cpp | 209 ++++++++++++++++++++++++-- 10 files changed, 781 insertions(+), 45 deletions(-) diff --git a/libr4d/r4d_attn_args.h b/libr4d/r4d_attn_args.h index 13a8e5c6..b171226c 100644 --- a/libr4d/r4d_attn_args.h +++ b/libr4d/r4d_attn_args.h @@ -40,7 +40,9 @@ enum { AP_Q = 0, AP_KV, AP_BT, AP_SEQ, AP_KDS, AP_VDS, AP_CU, AP_OUT }; * (q_len = total_q / num_seqs) only when it is not. In the ragged case q_len is the batch maximum, * taken from the parameter the arch block issued the op with (batch->max_q_len). */ -static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) { +/* `row` is a token's bytes (elements for a 16-bit cache) in a (block, head) page: 2 * head_dim, + * or 25 * head_dim / 16 for the fp8_v4 cache (E4M3 K, int4 V, f16 group scales). */ +static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_dim, long long row) { const RadTensor* q = r4d_opt(a, AP_Q); const RadTensor* kv = r4d_opt(a, AP_KV); const RadTensor* bt = r4d_opt(a, AP_BT); @@ -83,8 +85,8 @@ static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) * Each (block, head) slot must be dense, because the kernel walks it with vector loads. */ const long long block_size = kv->shape[2]; if (kv->stride[3] != 1) return R4D_NO(RAD_E_STRIDE); - if (kv->stride[2] != 2 * head_dim) return R4D_NO(RAD_E_STRIDE); - if (kv->shape[3] != 2 * head_dim) return R4D_NO(RAD_E_SHAPE); + if (kv->stride[2] != row) return R4D_NO(RAD_E_STRIDE); + if (kv->shape[3] != row) return R4D_NO(RAD_E_SHAPE); /* 16-byte alignment for 128-bit loads. */ if (!r4d_aligned(q->data, 16) || !r4d_aligned(o->data, 16) || !r4d_aligned(kv->data, 16)) @@ -150,4 +152,8 @@ static inline int split_of(const RadArgs* a) { } +static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) { + return fill_paged_row(a, r, expect_head_dim, 2LL * expect_head_dim); +} + #endif /* R4D_ATTN_ARGS_H */ diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index 574b6c91..aaacdc36 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -52,6 +52,10 @@ // fragment for fp8, 16 for bf16), costing 2 or 4 x HEAD_DIM/16 VGPRs; PF = HEAD_DIM/16 would hold // converted fragments and cost occupancy. Results are unchanged. #define O_KRAW 16777216 +// O_V4: the fp8_v4 cache (E4M3 K, int4 V in groups of 32 with an f16 scale), and with O_K6 the +// k6_v4 cache (int6 K, int4 V); a token's row layout is RadBuildCtx::kv_quant's (abi/rad_builder.h). +#define O_V4 33554432 +#define O_K6 67108864 __host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; } __host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) { int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits; @@ -85,10 +89,20 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16)) ? 1 : 0; constexpr int BTS = (OPT & O_BTS) ? 1 : 0; constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0; - constexpr int V8 = ((OPT & O_V8) && !KVP) ? 1 : 0; + constexpr int V4 = ((OPT & O_V4) && !KVP) ? 1 : 0; + constexpr int K6 = ((OPT & O_K6) && V4) ? 1 : 0; + // A token's row in a page, and where in it V's codes, V's scales and K's scales start. + constexpr int ROWB = K6 ? HEAD_DIM * 22 / 16 : V4 ? HEAD_DIM * 25 / 16 : 2 * HEAD_DIM; + constexpr int VOFF = K6 ? HEAD_DIM * 3 / 4 : HEAD_DIM; + constexpr int VSOFF = K6 ? HEAD_DIM * 21 / 16 : HEAD_DIM * 3 / 2; + constexpr int KSOFF = HEAD_DIM * 5 / 4; + constexpr int V8 = ((OPT & O_V8) && !KVP && !V4) ? 1 : 0; static_assert(!V8 || (OPT & O_CONTIG), "the code tile is read in the contiguous layout"); constexpr int KRAW = ((OPT & O_KRAW) && !KLDS) ? 1 : 0; static_assert(!KRAW || (OPT & O_CONTIG), "the raw K round reads the contiguous layout"); + static_assert(!K6 || (!KLDS && (OPT & O_CONTIG) && !KRAW), + "k6_v4 K is widened from the paged cache, a lane's eight dims contiguous"); + static_assert(!V4 || (OPT & O_F16), "fp8_v4 widens to f16"); typedef DT16 D; typedef typename D::frag frag16; @@ -104,7 +118,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) // Up to three uint4 it fits in 255 VGPRs without spilling (two: +6-8% at depth; three, the // 48-row shape q_len 8 x gqa 6 at NWARPS 3: a further 2-15%). At four or more (NWARPS 1-2, or a // bf16 cache) it spills and loses ~10%, so the geometry gates it, not just the flag. - constexpr int GPREV = ((OPT & O_GPREV) && VREGS <= 3) ? 1 : 0; + constexpr int GPREV = ((OPT & O_GPREV) && VREGS <= 3 && !V4) ? 1 : 0; constexpr float PSHIFT = D::SHIFT; constexpr float PGROW = D::GROW; @@ -185,6 +199,62 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int vg = lane >> 3, vj = lane & 7; uint4 vreg[VREGS]; + // ---- fp8_v4 / k6_v4: V's int4 codes into sV16 ([dim][key]) as the prefill kernel stages them + // (r4d_attn_prefill_h256_gqa6.hip: a key pair's 8 dims a thread, two code words and the pair's + // scale, widened with packed f16 into one dword a dim), fetched in the tile: no prefetch. + constexpr int NP4 = (TILE / 2) * (HEAD_DIM / 8); + constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1; + uint32_t v4c[U4][2], v4s[U4]; + auto fetchV4 = [&](int k0, const int* blks) { + #pragma unroll + for (int r = 0; r < U4; ++r) { + const int u = tid + r * NTHR; + if (NP4 % NTHR == 0 || u < NP4) { + const int kp = u % (TILE / 2), o = u / (TILE / 2); + uint32_t sc[2]; + #pragma unroll + for (int j = 0; j < 2; ++j) { + int kk = min(k0 + 2 * kp + j, ctx - 1); + if (WIN && kk < wlo0) kk = wlo0; + const int bk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS]; + const uint8_t* base = (const uint8_t*)a.kv + (size_t)bk * a.kv_block_stride + + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB; + v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4); + sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2); + } + v4s[r] = sc[0] | (sc[1] << 16); + } + } + }; + auto storeV4 = [&]() { + typedef _Float16 h2 __attribute__((ext_vector_type(2))); + #pragma unroll + for (int r = 0; r < U4; ++r) { + const int u = tid + r * NTHR; + if (NP4 % NTHR == 0 || u < NP4) { + const int kp = u % (TILE / 2), o = u / (TILE / 2); + // Two's complement nibbles; ^ 8 makes them offset binary (value + 8). + const uint32_t n0 = (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u; + const uint32_t m0 = ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; + const uint32_t n1 = (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u; + const uint32_t m1 = ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; + const h2 s2 = __builtin_bit_cast(h2, v4s[r]); + const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f }; + uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp]; + #pragma unroll + for (int b = 0; b < 4; ++b) { + const uint32_t sel = (uint32_t)b | 0x0c00u | ((uint32_t)(4 + b) << 16) | 0x0c000000u; + const uint32_t lo = __builtin_amdgcn_perm(n1, n0, sel) | 0x64006400u; + const uint32_t hi = __builtin_amdgcn_perm(m1, m0, sel) | 0x64006400u; + const h2 vl = (__builtin_bit_cast(h2, lo) - bias) * s2; + const h2 vh = (__builtin_bit_cast(h2, hi) - bias) * s2; + *(uint32_t*)(dst + (2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl); + *(uint32_t*)(dst + (2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh); + } + } + } + }; + auto fetchV = [&](int k0, const int* blks) { #pragma unroll for (int r = 0; r < VREGS; ++r) { @@ -198,7 +268,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS]; const size_t o = (size_t)blk * a.kv_block_stride + (size_t)kvh * a.kv_head_stride - + (size_t)(kk % BS) * (2 * HEAD_DIM) + HEAD_DIM + d0; + + (size_t)(kk % BS) * ROWB + HEAD_DIM + d0; const void* p = KVP ? (const void*)((const uint16_t*)a.kv + o) : (const void*)((const uint8_t*)a.kv + o); vreg[r] = __builtin_bit_cast(uint4, load_tr_b128(p)); @@ -275,7 +345,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) if (WIN && kk < wlo0) kk = wlo0; const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS]; const size_t o = (size_t)kb * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM); + + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB; uint16_t* kd = &sK[key * KSTR]; uint32_t w4[4]; if (KVP) { @@ -289,8 +359,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) *(uint2*)(kd + ch * 8 + 4) = make_uint2(w4[2], w4[3]); } } - if (!GPREV) fetchV(k0, blk); - storeV(); + if constexpr (V4) { fetchV4(k0, blk); storeV4(); } + else { if (!GPREV) fetchV(k0, blk); storeV(); } if (LDSB) lds_barrier(); else __syncthreads(); if (GPREV && ti + 1 < t_hi) fetchV(k0 + TILE, blkn); @@ -302,7 +372,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) if (WIN && kk < wlo0) kk = wlo0; const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS]; grow = (const uint8_t*)a.kv + ((size_t)kb * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM)) + + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB) * (KVP ? 2 : 1); } // A fragment's raw K: 8 elements of 1 byte (fp8) or 2 (bf16). @@ -341,6 +411,15 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) } kb[j] = D::mk(make_uint2(D::from_bf16w(l0.x), D::from_bf16w(l0.y)), make_uint2(D::from_bf16w(h0.x), D::from_bf16w(h0.y))); + } else if constexpr (K6) { + // k6_v4: this lane's eight dims (16t + 8h ..) from their low nibbles, the + // chunk's high-bit word and the group's scale. + uint32_t w4[4]; + const uint32_t sb = *(const uint16_t*)(grow + KSOFF + (t >> 1) * 2); + k6x8_to_f16x4w(*(const uint32_t*)(grow + 8 * t + 4 * h), + *(const uint32_t*)(grow + HEAD_DIM / 2 + 4 * t), h, + sb | (sb << 16), w4); + kb[j] = D::mk(make_uint2(w4[0], w4[1]), make_uint2(w4[2], w4[3])); } else { const uint8_t* kp = grow + 16 * t; uint32_t w4[4]; diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 6a94e226..8ea978a6 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -50,14 +50,14 @@ extern "C" void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max #define P_OPT 3954187 // KVP: 0 = fp8 e4m3 cache, 1 = bf16 cache. Reached only through the two named wrappers below. -template +template static int prefill_launch(const R4DArgs* a, hipStream_t s) { if (a->head_dim != A_HEAD_DIM || a->block_size != A_BLOCK_SIZE) return -1; if (a->q_heads / a->kv_heads != A_GQA) return -2; constexpr int BQ = (P_NWARPS * 16) / A_GQA; dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs); hipLaunchKernelGGL((r4d_attn_prefill_kernel), + KVP, P_OPT | XOPT>), grid, dim3(P_NWARPS * 32), 0, s, *a); CHK(); return 0; @@ -69,6 +69,12 @@ extern "C" int r4d_attn_prefill_h256_gqa6_fp8kv(const R4DArgs* a, hipStream_t s) extern "C" int r4d_attn_prefill_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s) { return prefill_launch<1>(a, s); } +extern "C" int r4d_attn_prefill_h256_gqa6_fp8v4kv(const R4DArgs* a, hipStream_t s) { + return prefill_launch<0, O_V4>(a, s); +} +extern "C" int r4d_attn_prefill_h256_gqa6_k6v4kv(const R4DArgs* a, hipStream_t s) { + return prefill_launch<0, O_V4 | O_K6>(a, s); +} // ---- decode ---------------------------------------------------------------------------------- #define D_TILE 16 @@ -90,7 +96,7 @@ extern "C" long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a) { return r4d_decode_scratch(a, r4d_decode_splits(a, D_TILE), D_OPT); } -template +template static int decode_launch(const R4DArgs* a, hipStream_t s) { if (a->head_dim != A_HEAD_DIM || a->block_size != A_BLOCK_SIZE) return -1; if (a->q_heads / a->kv_heads != A_GQA) return -2; @@ -101,7 +107,7 @@ static int decode_launch(const R4DArgs* a, hipStream_t s) { #define D_LAUNCH(NW) \ hipLaunchKernelGGL((r4d_attn_decode_kernel), \ + KVP, D_OPT | XOPT>), \ dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits) if (nw == 1) D_LAUNCH(1); else if (nw == 2) D_LAUNCH(2); @@ -138,6 +144,12 @@ extern "C" int r4d_attn_decode_h256_gqa6_fp8kv(const R4DArgs* a, hipStream_t s) extern "C" int r4d_attn_decode_h256_gqa6_bf16kv(const R4DArgs* a, hipStream_t s) { return decode_launch<1>(a, s); } +extern "C" int r4d_attn_decode_h256_gqa6_fp8v4kv(const R4DArgs* a, hipStream_t s) { + return decode_launch<0, O_V4>(a, s); +} +extern "C" int r4d_attn_decode_h256_gqa6_k6v4kv(const R4DArgs* a, hipStream_t s) { + return decode_launch<0, O_V4 | O_K6>(a, s); +} // ============================================================== the plugin ABI entry points // @@ -190,7 +202,7 @@ static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) { return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r); } -static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) { +static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long long row = 0) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); @@ -220,7 +232,7 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) { return worst; } - int rc = fill_paged(a, &r, head_dim); + int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim); if (rc != RAD_OK) return rc; r.splits = sp; return decode_scratch_bytes_of(&r, which); @@ -234,10 +246,10 @@ extern "C" int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs* a) { return decode_scratch(a, 128, 1); } -static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which) { +static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which, long long row = 0) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); - int rc = fill_paged(a, r, head_dim); + int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim); if (rc != RAD_OK) return rc; r->splits = sp; const int64_t need = decode_scratch_bytes_of(r, which); @@ -254,6 +266,48 @@ extern "C" int r4d_rad_attn_decode_h256_fp8(const RadArgs* a, RadStream s) { return r4d_attn_decode_h256_gqa6_fp8kv(&r, (hipStream_t)s); } +/* The fp8_v4 cache: a token's row is 25 * 256 / 16 = 400 bytes (E4M3 K, int4 V, f16 scales). */ +extern "C" int r4d_rad_attn_prefill_h256_fp8v4(const RadArgs* a, RadStream s) { + if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE); + R4DArgs r; + int rc = fill_paged_row(a, &r, 256, 400); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h256_gqa6_fp8v4kv(&r, (hipStream_t)s); +} + +extern "C" int64_t r4d_rad_attn_decode_h256_v4_scratch(const RadArgs* a) { + return decode_scratch(a, 256, 0, 400); +} + +extern "C" int r4d_rad_attn_decode_h256_fp8v4(const RadArgs* a, RadStream s) { + if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE); + R4DArgs r; + int rc = decode_common(a, &r, 256, 0, 400); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa6_fp8v4kv(&r, (hipStream_t)s); +} + +/* The k6_v4 cache: a token's row is 22 * 256 / 16 = 352 bytes (int6 K, int4 V, f16 scales). */ +extern "C" int r4d_rad_attn_prefill_h256_k6v4(const RadArgs* a, RadStream s) { + if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE); + R4DArgs r; + int rc = fill_paged_row(a, &r, 256, 352); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h256_gqa6_k6v4kv(&r, (hipStream_t)s); +} + +extern "C" int64_t r4d_rad_attn_decode_h256_k6_scratch(const RadArgs* a) { + return decode_scratch(a, 256, 0, 352); +} + +extern "C" int r4d_rad_attn_decode_h256_k6v4(const RadArgs* a, RadStream s) { + if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE); + R4DArgs r; + int rc = decode_common(a, &r, 256, 0, 352); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa6_k6v4kv(&r, (hipStream_t)s); +} + extern "C" int r4d_rad_attn_decode_h256_bf16(const RadArgs* a, RadStream s) { if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE); R4DArgs r; diff --git a/libr4d/r4d_attn_prefill_h256_gqa6.hip b/libr4d/r4d_attn_prefill_h256_gqa6.hip index 57f643f2..73c071d0 100644 --- a/libr4d/r4d_attn_prefill_h256_gqa6.hip +++ b/libr4d/r4d_attn_prefill_h256_gqa6.hip @@ -53,6 +53,9 @@ // LDSB: an LDS-scoped barrier instead of __syncthreads() (lds_barrier() in r4d_common.h). The // default fence invalidates the vector cache twice per tile, though only LDS needs ordering. #define O_LDSB 2097152 +// O_V4: the fp8_v4 cache, O_V4 | O_K6 the k6_v4 cache (see r4d_attn_decode_h256_gqa6.hip). +#define O_V4 33554432 +#define O_K6 67108864 // bf16 dword -> 16-bit dword in the target format, optionally scaled. Used once per kernel on Q. template @@ -77,7 +80,14 @@ void r4d_attn_prefill_kernel(const R4DArgs a) constexpr int SGB = (OPT & O_SGB) ? 1 : 0; constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16)) ? 1 : 0; constexpr int BTS = (OPT & O_BTS) ? 1 : 0; - constexpr int GPREV = (OPT & O_GPREV) ? 1 : 0; + constexpr int V4 = ((OPT & O_V4) && !KVP) ? 1 : 0; + constexpr int K6 = ((OPT & O_K6) && V4) ? 1 : 0; + // A token's row in a page, and where in it V's codes, V's scales and K's scales start. + constexpr int ROWB = K6 ? HEAD_DIM * 22 / 16 : V4 ? HEAD_DIM * 25 / 16 : 2 * HEAD_DIM; + constexpr int VOFF = K6 ? HEAD_DIM * 3 / 4 : HEAD_DIM; + constexpr int VSOFF = K6 ? HEAD_DIM * 21 / 16 : HEAD_DIM * 3 / 2; + constexpr int KSOFF = HEAD_DIM * 5 / 4; + constexpr int GPREV = ((OPT & O_GPREV) && !V4) ? 1 : 0; constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0; constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0; typedef DT16 D; @@ -100,6 +110,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a) constexpr float PSHIFT = D::SHIFT; constexpr float PGROW = D::GROW; static_assert(!KWIDE || KPASS == 1, "the wide K fetch is one straight-line pass"); + static_assert(!K6 || KWIDE, "k6_v4 K is staged sixteen dims a thread"); __shared__ uint16_t sK[TILE * KSTR]; __shared__ uint16_t sV16[HEAD_DIM * VSTR]; @@ -173,6 +184,69 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const int vg = lane >> 3, vj = lane & 7; uint4 kreg[KREGS], vreg[VREGS]; + // ---- fp8_v4 / k6_v4: V is int4 in groups of 32 with an f16 scale (absmax / 7): 16 bytes of + // codes a group at VOFF (dim d at bits 4*(d%8) of word d/8), the group scales at VSOFF. A thread stages one key pair's 8 dims: two code words and the pair's scale, + // fetched a tile ahead like GPREV's V, so the loads are in flight across the m-tile loop. They + // widen into sV16 ([dim][key]) as a dword per dim holding both keys: with u = code ^ 8 (offset + // binary), 0x6400 | u is the f16 1024 + u, so (x - 1032) * s is the value times s, rounded + // once. Key pairs run fastest across lanes, + // which keeps the dword stores of one dim row in distinct banks. + static_assert(!V4 || F16, "fp8_v4 widens V to f16"); + constexpr int NP4 = (TILE / 2) * (HEAD_DIM / 8); + constexpr int U4 = V4 ? (NP4 + NTHR - 1) / NTHR : 1; + uint32_t v4c[U4][2], v4s[U4]; + auto fetchV4 = [&](int k0, const int* blks) { + #pragma unroll + for (int r = 0; r < U4; ++r) { + const int u = tid + r * NTHR; + if (NP4 % NTHR == 0 || u < NP4) { + const int kp = u % (TILE / 2), o = u / (TILE / 2); + uint32_t sc[2]; + #pragma unroll + for (int j = 0; j < 2; ++j) { + const int kk = min(k0 + 2 * kp + j, ctx - 1); + const int bk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS]; + const uint8_t* base = (const uint8_t*)a.kv + (size_t)bk * a.kv_block_stride + + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB; + v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4); + sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2); + } + v4s[r] = sc[0] | (sc[1] << 16); + } + } + }; + auto storeV4 = [&]() { + typedef _Float16 h2 __attribute__((ext_vector_type(2))); + #pragma unroll + for (int r = 0; r < U4; ++r) { + const int u = tid + r * NTHR; + if (NP4 % NTHR == 0 || u < NP4) { + const int kp = u % (TILE / 2), o = u / (TILE / 2); + // Codes are two's complement nibbles; ^ 8 makes them offset binary (value + 8). + const uint32_t n0 = (v4c[r][0] & 0x0F0F0F0Fu) ^ 0x08080808u; + const uint32_t m0 = ((v4c[r][0] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; + const uint32_t n1 = (v4c[r][1] & 0x0F0F0F0Fu) ^ 0x08080808u; + const uint32_t m1 = ((v4c[r][1] >> 4) & 0x0F0F0F0Fu) ^ 0x08080808u; + const h2 s2 = __builtin_bit_cast(h2, v4s[r]); + const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f }; + uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp]; + #pragma unroll + for (int b = 0; b < 4; ++b) { + // Byte b of the first key's word low, of the second key's word in the high half: + // perm selects source bytes 0-3 from its second operand, 4-7 from its first, + // and 0x0c is a zero byte. + const uint32_t sel = (uint32_t)b | 0x0c00u | ((uint32_t)(4 + b) << 16) | 0x0c000000u; + const uint32_t lo = __builtin_amdgcn_perm(n1, n0, sel) | 0x64006400u; // dim 2b + const uint32_t hi = __builtin_amdgcn_perm(m1, m0, sel) | 0x64006400u; // dim 2b+1 + const h2 vl = (__builtin_bit_cast(h2, lo) - bias) * s2; + const h2 vh = (__builtin_bit_cast(h2, hi) - bias) * s2; + *(uint32_t*)(dst + (2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl); + *(uint32_t*)(dst + (2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh); + } + } + } + }; + auto fetchK = [&](int k0, const int* blks) { #pragma unroll for (int p = 0; p < KPASS; ++p) { @@ -184,12 +258,18 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const int kk = min(k0 + key, ctx - 1); const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS]; const size_t o = (size_t)blk * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM); + + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB; if (KVP) { const uint16_t* g = (const uint16_t*)a.kv + o + ch * KEL; #pragma unroll for (int q = 0; q < (KVP ? (KEL / 8) : 1); ++q) kreg[p * (KEL / 8) + q] = *(const uint4*)(g + 8 * q); + } else if (K6) { + // k6_v4: the chunk's sixteen low nibbles, its high-bit word, its group's scale. + const uint8_t* rp = (const uint8_t*)a.kv + o; + const uint2 lo = *(const uint2*)(rp + ch * 8); + kreg[p] = make_uint4(lo.x, lo.y, *(const uint32_t*)(rp + HEAD_DIM / 2 + ch * 4), + *(const uint16_t*)(rp + KSOFF + (ch >> 1) * 2)); } else if (KWIDE) { kreg[p] = *(const uint4*)((const uint8_t*)a.kv + o + ch * 16); } else { @@ -212,7 +292,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS]; const size_t o = (size_t)blk * a.kv_block_stride + (size_t)kvh * a.kv_head_stride - + (size_t)(kk % BS) * (2 * HEAD_DIM) + HEAD_DIM + d0; + + (size_t)(kk % BS) * ROWB + HEAD_DIM + d0; const void* p = KVP ? (const void*)((const uint16_t*)a.kv + o) : (const void*)((const uint8_t*)a.kv + o); vreg[r] = __builtin_bit_cast(uint4, load_tr_b128(p)); @@ -238,7 +318,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a) w4[2] = D::from_bf16w(r.z); w4[3] = D::from_bf16w(r.w); } else { const uint4 r = kreg[p]; - fp8x8_to_16x4w(q ? make_uint2(r.z, r.w) : make_uint2(r.x, r.y), w4); + if constexpr (K6) k6x8_to_f16x4w(q ? r.y : r.x, r.z, q, r.w | (r.w << 16), w4); + else fp8x8_to_16x4w(q ? make_uint2(r.z, r.w) : make_uint2(r.x, r.y), w4); } *(uint2*)(kd + 8 * q) = make_uint2(w4[0], w4[1]); *(uint2*)(kd + 8 * q + 4) = make_uint2(w4[2], w4[3]); @@ -296,6 +377,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a) int blk[NB]; if (BTS) load_bt(tstart * NB, blk); if (GPREV) fetchV(tstart * TILE, blk); + if (V4) fetchV4(tstart * TILE, blk); for (int ti = tstart; ti < ntiles; ++ti) { const int k0 = ti * TILE; @@ -305,13 +387,14 @@ void r4d_attn_prefill_kernel(const R4DArgs a) } if (LDSB) lds_barrier(); else __syncthreads(); fetchK(k0, blk); - if (!GPREV) fetchV(k0, blk); - storeV(); // V first: already in registers, so it covers K's load latency + // V first: already in registers, so it covers K's load latency. + if constexpr (V4) { storeV4(); } else { if (!GPREV) fetchV(k0, blk); storeV(); } storeK(); if (LDSB) lds_barrier(); else __syncthreads(); // Issue the next tile's V loads before the WMMAs below; they are consumed after the next // barrier. if (GPREV && ti + 1 < ntiles) fetchV(k0 + TILE, blkn); + if (V4 && ti + 1 < ntiles) fetchV4(k0 + TILE, blkn); #pragma unroll 1 for (int mt = 0; mt < MT; ++mt) { diff --git a/libr4d/r4d_dt16.h b/libr4d/r4d_dt16.h index d7a241c1..9148307b 100644 --- a/libr4d/r4d_dt16.h +++ b/libr4d/r4d_dt16.h @@ -67,6 +67,31 @@ template<> struct DT16<1> { // f16: 3 more mantissa bits, }; // Widen 8 fp8 (2 dwords) to 8 16-bit values (4 dwords) in element order. +// Eight K dims of the k6_v4 cache as four f16 dwords, dims (2i, 2i+1) in dword i. `lo` holds +// their low nibbles (dim 2i in bits 8i..8i+3, 2i+1 in 8i+4..8i+7) and `hb` their 16-dim chunk's +// high-bit word (byte j: bits 0-1 dim 2j, 2-3 dim 2j+1, 4-5 dim 8+2j, 6-7 dim 9+2j); `half` says +// which eight of the sixteen these are. One mask and shift put the high bits beside the low +// nibbles, a byte a dim. Codes are 6-bit two's complement: ^ 32 makes them offset binary u, +// 0x6400 | u is the f16 1024 + u, and (x - 1056) * s is the value times the group scale `s2` (the +// f16 in both halves), rounded once. +__device__ __forceinline__ void k6x8_to_f16x4w(uint32_t lo, uint32_t hb, int half, uint32_t s2, + uint32_t* w4) { + typedef _Float16 h2 __attribute__((ext_vector_type(2))); + const uint32_t ev = ((lo & 0x0F0F0F0Fu) | ((half ? hb : hb << 4) & 0x30303030u)) ^ 0x20202020u; + const uint32_t od = (((lo >> 4) & 0x0F0F0F0Fu) | ((half ? hb >> 2 : hb << 2) & 0x30303030u)) + ^ 0x20202020u; + const h2 s = __builtin_bit_cast(h2, s2); + const h2 bias = { (_Float16)1056.0f, (_Float16)1056.0f }; +#pragma unroll + for (int b = 0; b < 4; ++b) { + // Byte b of the even dims low, of the odd dims high; perm takes bytes 0-3 from its second + // operand, 4-7 from its first, and 0x0c is a zero byte. + const uint32_t sel = (uint32_t)b | 0x0c00u | ((uint32_t)(4 + b) << 16) | 0x0c000000u; + const uint32_t x = __builtin_amdgcn_perm(od, ev, sel) | 0x64006400u; + w4[b] = __builtin_bit_cast(uint32_t, (__builtin_bit_cast(h2, x) - bias) * s); + } +} + template __device__ __forceinline__ void fp8x8_to_16x4w(uint2 raw, uint32_t* w4) { #pragma unroll diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 2c117ed6..f9fcc1df 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -570,6 +570,83 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel( } } +// The fp8_v4 store: K as kv_store_fp8 writes it, V as int4 in groups of 32 with an f16 scale +// (absmax / 7). Four columns a thread as above, so a group of 32 is 8 lanes; head_dim is a multiple +// of 32, so a group never straddles two heads. A token's row is `row` bytes. K6 is the k6_v4 store: +// K as int6 in groups of 32 (absmax / 31) in the row layout of abi/rad_builder.h's RAD_KVQ_K6V4, V +// as above after it. +template +__global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel( + const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, + const int32_t* __restrict__ slot, uint8_t* __restrict__ kv, + uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, uint32_t n_blocks, + uint32_t k_ld, uint32_t v_ld, float k_inv, uint32_t row) { + const uint32_t t = blockIdx.x; + const int32_t s = slot[t]; + if (s < 0 || (uint32_t)s / block_size >= n_blocks) return; + const uint32_t blk = (uint32_t)s / block_size, off = (uint32_t)s % block_size; + const size_t slot_base = ((size_t)blk * kv_heads * block_size + (size_t)off) * row; + const size_t head_step = (size_t)block_size * row; + + for (uint32_t j = threadIdx.x * 4u; j < kv_heads * head_dim; j += kThreads * 4u) { + const uint32_t h = j / head_dim, d = j % head_dim; + uint8_t* __restrict__ c = kv + slot_base + (size_t)h * head_step; + float kf[4], vf[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + kf[e] = bf16_to_f32(k[(size_t)t * k_ld + j + (uint32_t)e]) * k_inv; + vf[e] = bf16_to_f32(v[(size_t)t * v_ld + j + (uint32_t)e]); + } + const uint32_t voff = K6 ? head_dim * 3 / 4 : head_dim; + const uint32_t vsoff = K6 ? head_dim * 21 / 16 : head_dim * 3 / 2; + if constexpr (K6) { + // A group of 32 is 8 lanes; its scale absmax / 31 in f16, codes 6-bit two's complement. + float kmax = fmaxf(fmaxf(fabsf(kf[0]), fabsf(kf[1])), fmaxf(fabsf(kf[2]), fabsf(kf[3]))); + for (int m = 4; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32)); + const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 65504.0f); + const float ksc = (float)k16; + uint32_t q[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const float r = ksc > 0.0f ? rintf(kf[e] / ksc) : 0.0f; + q[e] = (uint32_t)((int)fminf(fmaxf(r, -31.0f), 31.0f)) & 0x3Fu; + } + *(uint16_t*)(c + d / 2) = (uint16_t)((q[0] & 15u) | ((q[1] & 15u) << 4) | + ((q[2] & 15u) << 8) | ((q[3] & 15u) << 12)); + // The high bits of dims x..x+3 of a 16-dim chunk (x = d % 16 in 0, 4, 8, 12): bits + // 0-3 of bytes x/2 and x/2+1 for x < 8, bits 4-7 of bytes (x-8)/2 and (x-8)/2+1 for + // x >= 8. The lane two over holds the dims eight on, so the lower lane writes both. + const uint32_t hb = ((q[0] >> 4) | ((q[1] >> 4) << 2)) | ((((q[2] >> 4) | ((q[3] >> 4) << 2))) << 8); + const uint32_t up = (uint32_t)__shfl_xor((int)hb, 2, 32); + if ((d & 15u) < 8u) + *(uint16_t*)(c + head_dim / 2 + (d / 16) * 4 + (d & 7u) / 2) = (uint16_t)(hb | (up << 4)); + if ((d & 31u) == 0) + *(uint16_t*)(c + head_dim * 5 / 4 + (d / 32) * 2) = __builtin_bit_cast(uint16_t, k16); + } else { + int pk = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[0], -448.0f), 448.0f), + fminf(fmaxf(kf[1], -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[2], -448.0f), 448.0f), + fminf(fmaxf(kf[3], -448.0f), 448.0f), pk, true); + *(uint32_t*)(c + d) = (uint32_t)pk; + } + + float amax = fmaxf(fmaxf(fabsf(vf[0]), fabsf(vf[1])), fmaxf(fabsf(vf[2]), fabsf(vf[3]))); + for (int m = 4; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32)); + const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 65504.0f); + const float sc = (float)s16; + uint32_t q[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const float r = sc > 0.0f ? rintf(vf[e] / sc) : 0.0f; + q[e] = (uint32_t)((int)fminf(fmaxf(r, -7.0f), 7.0f)) & 0xFu; + } + *(uint16_t*)(c + voff + d / 2) = (uint16_t)(q[0] | (q[1] << 4) | (q[2] << 8) | (q[3] << 12)); + if ((d & 31u) == 0) + *(uint16_t*)(c + vsoff + (d / 32) * 2) = __builtin_bit_cast(uint16_t, s16); + } +} + } // namespace // ================================================================================ entry points @@ -1709,7 +1786,7 @@ struct KvStoreGeom { long long head_dim, block_size, kv_heads, n_blocks, k_ld, v_ld, T; }; -static int kv_store_geom(const RadArgs* a, KvStoreGeom* g) { +static int kv_store_geom(const RadArgs* a, KvStoreGeom* g, long long row_per_hd16 = 32) { g->k = r4d_opt(a, KS_K); g->v = r4d_opt(a, KS_V); g->sm = r4d_opt(a, KS_SLOT); @@ -1728,7 +1805,7 @@ static int kv_store_geom(const RadArgs* a, KvStoreGeom* g) { * disagrees. */ if (g->kv->rank != 4) return R4D_NO(RAD_E_SHAPE); if (g->kv->shape[1] != g->kv_heads || g->kv->shape[2] != g->block_size || - g->kv->shape[3] != 2 * g->head_dim) return R4D_NO(RAD_E_SHAPE); + g->kv->shape[3] != g->head_dim * row_per_hd16 / 16) return R4D_NO(RAD_E_SHAPE); g->n_blocks = g->kv->shape[0]; const long long lane = g->kv_heads * g->head_dim; @@ -1774,6 +1851,36 @@ extern "C" int r4d_rad_kv_store_fp8(const RadArgs* a, RadStream stream) { (float)ks, (float)vs, stream) == 0 ? RAD_OK : RAD_E_DEVICE; } +/* The fp8_v4 and k6_v4 stores: the cache's last extent is a token's row, 25 or 22 * head_dim / 16 + * bytes. */ +static int kv_store_q4(const RadArgs* a, RadStream stream, int k6) { + const long long r16 = k6 ? 22 : 25; + KvStoreGeom g{}; + const int rc = kv_store_geom(a, &g, r16); + if (rc != RAD_OK) return rc; + if (g.kv->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE); + if (g.head_dim % 32) return R4D_NO(RAD_E_SHAPE); + const double ks = r4d_getf(a, "k_scale", 1.0); + if (!(ks > 0.0)) return R4D_NO(RAD_E_INVAL); + long long k_ld = g.k_ld ? g.k_ld : g.kv_heads * g.head_dim; + long long v_ld = g.v_ld ? g.v_ld : g.kv_heads * g.head_dim; + if (k6) + return R4D_EMIT(stream, kv_store_fp8v4_kernel<1>, dim3((uint32_t)g.T), dim3(kThreads), 0, + (const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v), + (const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv), + (uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size, + (uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, (float)(1.0 / ks), + (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE; + return R4D_EMIT(stream, kv_store_fp8v4_kernel<0>, dim3((uint32_t)g.T), dim3(kThreads), 0, + (const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v), + (const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv), + (uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size, + (uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, (float)(1.0 / ks), + (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE; +} +extern "C" int r4d_rad_kv_store_fp8v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 0); } +extern "C" int r4d_rad_kv_store_k6v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 1); } + /* ------------------------------------------------------------------ logits_gemm * * gemm_nt's arithmetic with `n_vocab`/`n_embd` for N/K, but writing f32 (see the kernel above). diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 41253c21..52e747c4 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -91,6 +91,12 @@ extern "C" { int r4d_rad_attn_prefill_h256_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_prefill_h256_bf16(const RadArgs*, RadStream); int r4d_rad_attn_decode_h256_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_fp8v4(const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h256_fp8v4(const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h256_v4_scratch(const RadArgs*); +int r4d_rad_attn_decode_h256_k6v4(const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h256_k6v4(const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h256_k6_scratch(const RadArgs*); int r4d_rad_attn_decode_h256_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_bf16 (const RadArgs*, RadStream); @@ -410,6 +416,8 @@ int r4d_rad_gated_had_quant_i8 (const RadArgs*, RadStream); int r4d_rad_gdn_gated_norm_hq_i8 (const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate (const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs*, RadStream); +int r4d_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs*, RadStream); +int r4d_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs*, RadStream); int r4d_rad_rope_table (const RadArgs*, RadStream); /* -- block-scaled fp8, and the device sampler (r4d_gemm_fp8*.hip / r4d_fp8_layout.cpp) -- @@ -607,6 +615,8 @@ int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream); int r4d_rad_gemm_f32_nt_bias(const RadArgs*, RadStream); int r4d_rad_kv_store (const RadArgs*, RadStream); int r4d_rad_kv_store_fp8 (const RadArgs*, RadStream); +int r4d_rad_kv_store_fp8v4 (const RadArgs*, RadStream); +int r4d_rad_kv_store_k6v4 (const RadArgs*, RadStream); int r4d_rad_logits_gemm (const RadArgs*, RadStream); /* -- the decomposed sampler chain (r4d_sample_stages_f32.hip) -- diff --git a/libr4d/r4d_qk_norm_rope_gate.hip b/libr4d/r4d_qk_norm_rope_gate.hip index 51b7f7c2..12a6fe97 100644 --- a/libr4d/r4d_qk_norm_rope_gate.hip +++ b/libr4d/r4d_qk_norm_rope_gate.hip @@ -49,10 +49,11 @@ struct QkKvStore { void* cache; int v_pitch, block_size, n_blocks; float k_inv, v_inv; + int row; /* fp8_v4 / k6_v4: a token's bytes in a page, 25 or 22 * HD / 16 */ }; /* The cache forms KV selects. */ -enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2 }; +enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4 }; /* KV folds kv_store in: a k head's block, holding the token's rotated k one element per lane, also * writes that element and the head's v element into the cache at the token's slot, as E4M3 with @@ -153,14 +154,53 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.n_blocks) { const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size; const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size; - const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * 2 * HD + - (size_t)lh * kvs.block_size * 2 * HD; + const size_t rowb = (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) ? (size_t)kvs.row : (size_t)(2 * HD); + const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * rowb + + (size_t)lh * kvs.block_size * rowb; const __hip_bfloat16 kb = __float2bfloat16(res); const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t]; if constexpr (KV == QK_KV_BF16) { __hip_bfloat16* c = (__hip_bfloat16*)kvs.cache + at; c[t] = kb; c[HD + t] = vb; + } else if constexpr (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) { + // fp8_v4: K as the E4M3 form writes it. k6_v4: K as int6 in groups of 32 (one wave) + // with an f16 scale, absmax / 31, in kv_store_k6v4's layout. V as int4 in groups of 32 + // with an f16 scale, absmax / 7. The even lane of a pair writes the pair's nibble byte. + unsigned char* c = (unsigned char*)kvs.cache + at; + const float kf = __bfloat162float(kb) * kvs.k_inv; + constexpr int voff = KV == QK_KV_K6V4 ? HD * 3 / 4 : HD; + constexpr int vsoff = KV == QK_KV_K6V4 ? HD * 21 / 16 : HD * 3 / 2; + if constexpr (KV == QK_KV_K6V4) { + float kmax = fabsf(kf); + for (int m = 16; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32)); + const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 65504.0f); + const float ksc = (float)k16; + const float r = ksc > 0.0f ? rintf(kf / ksc) : 0.0f; + const int q = ((int)fminf(fmaxf(r, -31.0f), 31.0f)) & 0x3F; + const int qn = __shfl_xor(q & 15, 1, 32); + if ((t & 1) == 0) c[t / 2] = (unsigned char)((q & 15) | (qn << 4)); + // High bits: a pair's four into bits 0-3 at its even lane, then the pair eight dims on + // into bits 4-7; lane 2j of a 16-dim chunk writes byte j. + const int h01 = (q >> 4) | (__shfl_xor(q >> 4, 1, 32) << 2); + const int hb = h01 | (__shfl_xor(h01, 8, 32) << 4); + if ((t & 1) == 0 && (t & 15) < 8) c[HD / 2 + (t / 16) * 4 + (t & 7) / 2] = (unsigned char)hb; + if ((t & 31) == 0) *(uint16_t*)(c + HD * 5 / 4 + (t / 32) * 2) = __builtin_bit_cast(uint16_t, k16); + } else { + const int pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f, + 0, false); + c[t] = (unsigned char)(pk & 0xFF); + } + const float vf = __bfloat162float(vb); + float amax = fabsf(vf); + for (int m = 16; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32)); + const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 65504.0f); + const float sc = (float)s16; + const float r = sc > 0.0f ? rintf(vf / sc) : 0.0f; + const int q = ((int)fminf(fmaxf(r, -7.0f), 7.0f)) & 0xF; + const int qn = __shfl_xor(q, 1, 32); + if ((t & 1) == 0) c[voff + t / 2] = (unsigned char)(q | (qn << 4)); + if ((t & 31) == 0) *(uint16_t*)(c + vsoff + (t / 32) * 2) = __builtin_bit_cast(uint16_t, s16); } else { unsigned char* c = (unsigned char*)kvs.cache + at; const float kf = __bfloat162float(kb) * kvs.k_inv; @@ -346,6 +386,51 @@ extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream : qk_body(args, stream, kvs); } +/* The fp8_v4 and k6_v4 forms: the same operands, the cache [n_blocks, kv_heads, block_size, + * 25 or 22 * HD / 16] E4M3-typed bytes (fp8_v4: E4M3 K; k6_v4: int6 K; both int4 V, f16 scales). */ +static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) { + const long long r16 = k6 ? 22 : 25; + const RadTensor* k = r4d_opt(args, QK_K); + const RadTensor* qg = r4d_opt(args, QK_QGATE); + const RadTensor* v = r4d_opt(args, QK_V); + const RadTensor* sm = r4d_opt(args, QK_SLOT); + const RadTensor* kv = r4d_opt(args, QK_CACHE); + if (!k || !v || !sm || !kv) return R4D_NO(RAD_E_INVAL); + if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != RAD_F8E4M3) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE); + const long long hd = r4d_geti_or(args, "head_dim", 0); + const long long nkv = r4d_geti_or(args, "n_head_kv", 0); + const long long bs = r4d_geti_or(args, "block_size", 0); + if (hd <= 0 || nkv <= 0 || bs <= 0 || hd % 32) return R4D_NO(RAD_E_SHAPE); + if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != hd * r16 / 16) + return R4D_NO(RAD_E_SHAPE); + const long long M = qg ? qg->shape[0] : k->shape[0]; + long long Mv = 0; + const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv); + if (v_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (Mv < M || r4d_numel(sm) != M) return R4D_NO(RAD_E_SHAPE); + const double ks = r4d_getf(args, "k_scale", 1.0); + if (!(ks > 0.0)) return R4D_NO(RAD_E_INVAL); + QkKvStore kvs{}; + kvs.v = (const __hip_bfloat16*)r4d_p(v); + kvs.slot = (const int32_t*)r4d_p(sm); + kvs.cache = r4d_wp(kv); + kvs.v_pitch = (int)v_ld; + kvs.block_size = (int)bs; + kvs.n_blocks = (int)kv->shape[0]; + kvs.k_inv = 1.0f / (float)ks; + kvs.v_inv = 1.0f; + kvs.row = (int)(hd * r16 / 16); + return k6 ? qk_body(args, stream, kvs) : qk_body(args, stream, kvs); +} +extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs* args, RadStream stream) { + return qk_kv_q4(args, stream, 0); +} +extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs* args, RadStream stream) { + return qk_kv_q4(args, stream, 1); +} + // The cos/sin plane the fused prologue reads: one launch a step, against `rope`'s one per layer. // `qk_norm_rope_gate` takes a table, not a theta, so this row is what makes it usable. // diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 77bc9c73..df590570 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -3130,6 +3130,24 @@ static const RadConstraint cAttnDecodeFp8[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), C_EQ("causal", 1), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), }; +/* The fp8_v4 cache (E4M3 K, int4 V in groups of 32 with f16 scales) and the k6_v4 cache (int6 K, + * int4 V); the row layouts are RAD_KVQ_*'s (abi/rad_builder.h). */ +static const RadConstraint cAttnPrefillK6v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"), +}; +static const RadConstraint cAttnDecodeK6v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), + C_EQ("causal", 1), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"), +}; +static const RadConstraint cAttnPrefillFp8v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"), +}; +static const RadConstraint cAttnDecodeFp8v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), + C_EQ("causal", 1), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"), +}; static const RadConstraint cAttnDecodeBf16[] = { C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), C_EQ("causal", 1), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), @@ -3965,6 +3983,14 @@ static const RadConstraint cQkNormRopeGateKv[] = { C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3"), }; +static const RadConstraint cQkNormRopeGateKvFp8v4[] = { + C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), + C_GE("block_size", 1), C_IN("kv_dtype", "fp8_v4"), +}; +static const RadConstraint cQkNormRopeGateKvK6v4[] = { + C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), + C_GE("block_size", 1), C_IN("kv_dtype", "k6_v4"), +}; static const RadConstraint cQkNormRopeGateKvBf16[] = { C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), C_GE("block_size", 1), C_IN("kv_dtype", "bf16"), @@ -4248,6 +4274,10 @@ static const RadConstraint cCausalConv[] = { C_IN("dtype", "bf16"), C_GE("width" C_LE("width", 8) }; static const RadConstraint cKvStore[] = { C_GE("block_size", 1), C_IN("kv_dtype", "bf16") }; static const RadConstraint cKvStoreFp8[] = { C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3") }; +static const RadConstraint cKvStoreFp8v4[] = { C_GE("block_size", 1), C_DIV("head_dim", 32), + C_IN("kv_dtype", "fp8_v4") }; +static const RadConstraint cKvStoreK6v4[] = { C_GE("block_size", 1), C_DIV("head_dim", 32), + C_IN("kv_dtype", "k6_v4") }; static const RadConstraint cRopeRow[] = { C_GE("head_dim", 1), C_IN("mode", "neox mrope gptj imrope axial") }; /* The vision tower's rows. The GEMM stages 16-byte chunks, so K is a multiple of 8; the norm and @@ -4821,6 +4851,26 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_kv_store_fp8, nullptr, nullptr, nullptr, r4d_shape_kv_store }, +{ "kv_store_fp8v4", "kv_store", "attn", + "scatter k and v into a paged fp8_v4 cache, one workgroup a token", + "cache exactly [n_blocks, kv_heads, block_size, 25*head_dim/16]; head_dim a multiple of 32; a " + "negative or out-of-range slot stores nothing", + "bf16 k / v, E4M3 K and int4 V in groups of 32 with f16 scales, i32 slot mapping", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvStoreFp8v4), NOTUNE, + nullptr, nullptr, r4d_rad_kv_store_fp8v4, nullptr, nullptr, nullptr, + nullptr }, + +{ "kv_store_k6v4", "kv_store", "attn", + "scatter k and v into a paged k6_v4 cache, one workgroup a token", + "cache exactly [n_blocks, kv_heads, block_size, 22*head_dim/16]; head_dim a multiple of 32; a " + "negative or out-of-range slot stores nothing", + "bf16 k / v, int6 K and int4 V in groups of 32 with f16 scales, i32 slot mapping", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvStoreK6v4), NOTUNE, + nullptr, nullptr, r4d_rad_kv_store_k6v4, nullptr, nullptr, nullptr, + nullptr }, + { "logits_gemm_bf16", "logits_gemm", "vocab", "the lm_head projection: C[M, n_vocab] f32 = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T", "any M and any vocabulary; n_embd a multiple of 8. One workgroup a vocabulary column", @@ -5005,6 +5055,24 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8, nullptr, nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_prefill_h256_gqa6_fp8v4", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 256, 6 queries per kv head, paged block 16, varlen", + "bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillFp8v4), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8v4, nullptr, nullptr, nullptr, + nullptr }, + +{ "attn_prefill_h256_gqa6_k6v4", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 256, 6 queries per kv head, paged block 16, varlen", + "bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillK6v4), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_k6v4, nullptr, nullptr, nullptr, + nullptr }, + { "attn_prefill_h256_gqa6_bf16kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 6 queries per kv head, paged block 16, varlen", @@ -5024,6 +5092,26 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_decode_h256_gqa6_fp8v4", "attn_paged", "attn", + "paged causal attention, split-KV (decode / speculative verify)", + "head_dim 256, 6 queries per kv head, paged block 16, q_len*gqa <= 64", + "bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeFp8v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_fp8v4, r4d_rad_attn_decode_h256_v4_scratch, + nullptr, nullptr, + nullptr }, + +{ "attn_decode_h256_gqa6_k6v4", "attn_paged", "attn", + "paged causal attention, split-KV (decode / speculative verify)", + "head_dim 256, 6 queries per kv head, paged block 16, q_len*gqa <= 64", + "bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeK6v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_k6v4, r4d_rad_attn_decode_h256_k6_scratch, + nullptr, nullptr, + nullptr }, + { "attn_decode_h256_gqa6_bf16kv", "attn_paged", "attn", "paged causal attention, split-KV (decode / speculative verify)", "head_dim 256, 6 queries per kv head, paged block 16, q_len*gqa <= 64", @@ -6820,6 +6908,28 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store, nullptr, nullptr, nullptr, r4d_shape_qk_norm_rope_gate_kv_store, nullptr, r4d_fuse_qk_norm_rope_gate_kv_store }, +/* The fold into an fp8_v4 cache: E4M3 K, int4 V in groups of 32 (a wave) with f16 scales. */ +{ "qk_norm_rope_gate_kv_store_fp8v4", "qk_norm_rope_gate_kv_store", "attn", + "qk_norm_rope_gate, and kv_store into an fp8_v4 paged cache from the same launch", + "qk_norm_rope_gate's shapes; cache exactly [n_blocks, kv_heads, block_size, 25*head_dim/16], " + "head_dim a multiple of 32, one slot a row; a negative or out-of-range slot stores nothing", + "bf16 in and out, E4M3 K and int4 V with f16 scales, i32 slot mapping", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkNormRopeGateKvFp8v4), NOTUNE, + nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store_fp8v4, nullptr, nullptr, nullptr, + nullptr }, + +/* The fold into a k6_v4 cache: int6 K and int4 V in groups of 32 (a wave) with f16 scales. */ +{ "qk_norm_rope_gate_kv_store_k6v4", "qk_norm_rope_gate_kv_store", "attn", + "qk_norm_rope_gate, and kv_store into a k6_v4 paged cache from the same launch", + "qk_norm_rope_gate's shapes; cache exactly [n_blocks, kv_heads, block_size, 22*head_dim/16], " + "head_dim a multiple of 32, one slot a row; a negative or out-of-range slot stores nothing", + "bf16 in and out, int6 K and int4 V with f16 scales, i32 slot mapping", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkNormRopeGateKvK6v4), NOTUNE, + nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store_k6v4, nullptr, nullptr, nullptr, + nullptr }, + /* The same fold into a bf16 cache: the store is the two values the pair's kv_store_bf16 copies. */ { "qk_norm_rope_gate_kv_store_bf16", "qk_norm_rope_gate_kv_store", "attn", "qk_norm_rope_gate, and kv_store into a bf16 paged cache from the same launch", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index bf57bd61..4b72ee15 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -860,17 +860,39 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8 int64_t head_dim, int64_t kv_heads, int64_t block_size, int64_t kh, const int* block_table, int64_t max_blocks, int ctx, float kds, float vds, int causal, int window, float scale, - int64_t qlen, int64_t i, float* out) { + int64_t qlen, int64_t i, float* out, int kvq = 0) { const int ew = kv_is_fp8 ? 1 : 2; const int64_t pos = ctx - qlen + i; - const int64_t sb = kv_heads * block_size * 2 * head_dim; - const int64_t sh = block_size * 2 * head_dim; - const int64_t so = 2 * head_dim; + /* kvq 1, fp8_v4: a token's row is head_dim E4M3 K bytes, then V's codes (dim d in the nibble + * at bit 4 * (d % 2) of byte d / 2), then an f16 scale per 32 dims; V is (code ^ 8) - 8 times + * it. kvq 2, k6_v4: K's low nibbles, its high-bit words, V's codes, K's scales, V's scales + * (RAD_KVQ_K6V4 in abi/rad_builder.h); K is (code ^ 32) - 32 times its scale. */ + const int v4 = kvq != 0; + const int64_t so = kvq == 2 ? 22 * head_dim / 16 : v4 ? 25 * head_dim / 16 : 2 * head_dim; + 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 auto f16at = [](const uint8_t* p) { + uint16_t b; std::memcpy(&b, p, 2); return (float)__builtin_bit_cast(_Float16, b); + }; + const int64_t sb = kv_heads * block_size * so; + const int64_t sh = block_size * so; const auto kslot = [&](int64_t blk, int64_t slot, int64_t d) { + if (kvq == 2) { + const uint8_t* row = kv + blk * sb + kh * sh + slot * so; + const int lo = (row[d / 2] >> (4 * (d & 1))) & 0xF; + const int x = (int)(d % 16); + const int hi = (row[head_dim / 2 + (d / 16) * 4 + (x & 7) / 2] >> ((x & 1) * 2 + (x >> 3) * 4)) & 3; + return (float)(((lo | (hi << 4)) ^ 32) - 32) * f16at(row + head_dim * 5 / 4 + (d / 32) * 2); + } const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + d) * ew; return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p); }; const auto vslot = [&](int64_t blk, int64_t slot, int64_t d) { + if (v4) { + const uint8_t* row = kv + blk * sb + kh * sh + slot * so; + const int nib = (row[voff + d / 2] >> (4 * (d & 1))) & 0xF; + return (float)((nib ^ 8) - 8) * f16at(row + vsoff + (d / 32) * 2); + } const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + head_dim + d) * ew; return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p); }; @@ -922,19 +944,42 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d const int64_t max_blocks = ctx / bs; const int64_t total_q = seqs * q_len; const int kv_is_fp8 = std::strcmp(kv_dtype, "bf16") != 0; + const int kvq = !std::strcmp(kv_dtype, "fp8_v4") ? 1 : !std::strcmp(kv_dtype, "k6_v4") ? 2 : 0; + const int v4 = kvq != 0; const uint32_t kvdt = kv_is_fp8 ? RAD_F8E4M3 : RAD_BF16; const int ew = kv_is_fp8 ? 1 : 2; + const int64_t rowe = kvq == 2 ? 22 * head_dim / 16 : v4 ? 25 * head_dim / 16 : 2 * head_dim; + 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); std::vector qh((size_t)total_q * q_heads * head_dim); for (size_t i = 0; i < qh.size(); ++i) qh[i] = st_rand_bf16(i); - const int64_t nelem = max_blocks * kv_heads * bs * 2 * head_dim; + const int64_t nelem = max_blocks * kv_heads * bs * rowe; std::vector kv((size_t)nelem * ew); for (int64_t e = 0; e < nelem; ++e) { const size_t bo = (size_t)e * ew; if (kv_is_fp8) kv[bo] = st_rand_e4m3(e); else { const uint16_t h = st_rand_bf16(e); kv[bo] = (uint8_t)h; kv[bo + 1] = (uint8_t)(h >> 8); } } + if (v4) /* V: random codes, and scales from 1/64 to 1/4 so V spans about +-2 */ + 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) { /* K: random codes, scales from 1/256 to 1/16 so K spans about +-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 std::vector bt = iota_i32(max_blocks); void* d_q = dalloc((size_t)total_q * q_heads * head_dim * 2); @@ -945,7 +990,7 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d std::vector ts = { T(d_q, RAD_BF16, { total_q, q_heads, head_dim }), - T(d_kv, kvdt, { max_blocks, kv_heads, bs, 2 * head_dim }), + T(d_kv, kvdt, { max_blocks, kv_heads, bs, rowe }), TI32({ seqs, max_blocks }, bt), TI32({ seqs }, rep_i32(seqs, (int32_t)ctx)), TF32({ seqs, kv_heads }, 1.0f), @@ -973,7 +1018,7 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d float o[512]; attn_oracle_one(&qh[(tok * q_heads + h) * head_dim], kv.data(), kv_is_fp8, head_dim, kv_heads, bs, kh, bt.data(), max_blocks, ctx, - 1.0f, 1.0f, 1, window, scale, q_len, tok, o); + 1.0f, 1.0f, 1, window, scale, q_len, tok, o, kvq); for (int64_t d = 0; d < head_dim; ++d) { const size_t idx = (size_t)(tok * q_heads + h) * head_dim + d; oref[idx] = o[d]; @@ -1621,17 +1666,19 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal * The inputs span the clamp (v up to +-2000, k normed and rotated), reaching E4M3's +-448 * saturation and its subnormals. A pad row (slot -1) and a slot past the cache's end must store * nothing. The engine's geometry: 12 query heads and 2 kv heads of 256, rot 64. */ -static void qk_kv_fold_case(const Plugin& pl, bool bf16) { - const char* row = bf16 ? "qk_norm_rope_gate_kv_store_bf16" : "qk_norm_rope_gate_kv_store_fp8"; +static void qk_kv_fold_case(const Plugin& pl, bool bf16, int kvq = 0) { + const char* row = bf16 ? "qk_norm_rope_gate_kv_store_bf16" + : kvq == 1 ? "qk_norm_rope_gate_kv_store_fp8v4" + : kvq == 2 ? "qk_norm_rope_gate_kv_store_k6v4" : "qk_norm_rope_gate_kv_store_fp8"; if (!sel(row)) return; - const char* name = bf16 - ? "qk_norm_rope_gate_kv_store_bf16 is byte-identical to the prologue + kv_store" - : "qk_norm_rope_gate_kv_store_fp8 is byte-identical to the prologue + kv_store"; + const std::string nm_s = std::string(row) + " is byte-identical to the prologue + kv_store"; + const char* name = nm_s.c_str(); const uint32_t cdt = bf16 ? RAD_BF16 : RAD_F8E4M3; - const char* cname = bf16 ? "bf16" : "fp8_e4m3"; + const char* cname = bf16 ? "bf16" : kvq == 1 ? "fp8_v4" : kvq == 2 ? "k6_v4" : "fp8_e4m3"; const RadKernelInfo* rk = find(pl, row); const RadKernelInfo* rf = find(pl, "qk_norm_rope_gate"); - const RadKernelInfo* rs = find(pl, bf16 ? "kv_store_bf16" : "kv_store_fp8"); + const RadKernelInfo* rs = find(pl, bf16 ? "kv_store_bf16" : kvq == 1 ? "kv_store_fp8v4" + : kvq == 2 ? "kv_store_k6v4" : "kv_store_fp8"); const RadKernelInfo* rt = find(pl, "rope_table_f32"); if (!rk || !rf || !rs || !rt) { ok(name, false, "row absent"); return; } @@ -1657,7 +1704,8 @@ static void qk_kv_fold_case(const Plugin& pl, bool bf16) { for (auto& x : hv) x = h_to_bf16(rnd(2000.0f)); std::vector fwq((size_t)hd), fwk((size_t)hd); for (int64_t d = 0; d < hd; ++d) { fwq[(size_t)d] = rnd(0.5f); fwk[(size_t)d] = rnd(0.5f); } - const size_t cbytes = (size_t)(nb * nkv * bs * 2 * hd) * (bf16 ? 2 : 1); + const int64_t crow = kvq == 2 ? 22 * hd / 16 : kvq ? 25 * hd / 16 : 2 * hd; /* a token's row */ + const size_t cbytes = (size_t)(nb * nkv * bs * crow) * (bf16 ? 2 : 1); std::vector hc(cbytes); for (auto& x : hc) x = (uint8_t)(rnd(128.0f) + 128.0f); @@ -1699,7 +1747,7 @@ static void qk_kv_fold_case(const Plugin& pl, bool bf16) { T(q, RAD_BF16, { M, nq * hd }), T(k, RAD_BF16, { M, nkv * hd }), RadTensor{} }; }; - auto cache = [&](void* c) { return T(c, cdt, { nb, nkv, bs, 2 * hd }); }; + auto cache = [&](void* c) { return T(c, cdt, { nb, nkv, bs, crow }); }; /* ---- the pair ---- */ { @@ -2735,6 +2783,121 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = * A negative or out-of-range slot (a pad row) must store nothing: the cache is prefilled with a * sentinel and those slots must still hold it. Slot 0 is a real slot (as in libref and * r4d_gdn_conv_w4_h128_bf16.hip) and is used deliberately. */ +/* kv_store into the fp8_v4 cache (E4M3 K, int4 V in groups of 32 with an f16 scale, absmax / 7), + * against values the format holds exactly: K as in kv_store_case, V an integer from -7 to 7 times + * a per-head step, with a 7 or -7 in every group, so the scale is the step and every code decodes + * back to the input. A pad slot and one past the cache must leave the sentinel row untouched. */ +static void kv_store_v4_case(const Plugin& pl, bool k6 = false) { + const char* name = k6 ? "kv_store_k6v4" : "kv_store_fp8v4"; + if (!sel(name)) return; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t head_dim = 256, kv_heads = 2, block_size = 16, n_blocks = 4; + const int64_t lane = kv_heads * head_dim, rowb = (k6 ? 22 : 25) * head_dim / 16; + const int64_t voff = k6 ? head_dim * 3 / 4 : head_dim; + const int64_t vsoff = k6 ? head_dim * 21 / 16 : head_dim * 3 / 2; + /* k6_v4's K: an integer from -31 to 31 times a per-(token, head) step, with a 31 and a -31 in + * every group, so the scale is the step and every code decodes back to the input. */ + auto k6int = [&](int64_t t, int64_t h, int64_t d) -> int { + if (d % 32 == 3) return -31; + if (d % 32 == 26) return 31; + return (int)((t * 7 + h * 11 + d) % 63) - 31; + }; + auto kstep = [&](int64_t t, int64_t h) { return 0.0625f * (float)(1 + (t + 2 * h) % 4); }; + const std::vector slots = { 0, 17, 63, -1, (int32_t)(n_blocks * block_size), 33 }; + const int64_t T_tok = (int64_t)slots.size(); + auto kval = [&](int64_t t, int64_t h, int64_t d) { + static const float mag[8] = { 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 8.0f }; + return k6 ? (float)k6int(t, h, d) * kstep(t, h) : mag[(size_t)((t * 3 + h * 5 + d) % 8)]; + }; + auto vint = [&](int64_t t, int64_t h, int64_t d) -> int { + if (d % 32 == 0) return -7; + if (d % 32 == 17) return 7; + return (int)((t * 5 + h * 3 + d) % 15) - 7; + }; + auto step = [&](int64_t t, int64_t h) { return 0.125f * (float)(1 + (t + h) % 4); }; + std::vector hk((size_t)T_tok * lane), hv((size_t)T_tok * lane); + for (int64_t t = 0; t < T_tok; ++t) + for (int64_t h = 0; h < kv_heads; ++h) + for (int64_t d = 0; d < head_dim; ++d) { + hk[(size_t)(t * lane + h * head_dim + d)] = h_to_bf16(kval(t, h, d)); + hv[(size_t)(t * lane + h * head_dim + d)] = h_to_bf16((float)vint(t, h, d) * step(t, h)); + } + const size_t cbytes = (size_t)(n_blocks * kv_heads * block_size * rowb); + void* d_k = dalloc((size_t)T_tok * lane * 2); + void* d_v = dalloc((size_t)T_tok * lane * 2); + void* d_sm = dalloc((size_t)T_tok * 4); + void* d_c = dalloc(cbytes); + if (!d_k || !d_v || !d_sm || !d_c) { ok(name, false, "hipMalloc failed"); return; } + st_memcpy(d_k, hk.data(), (size_t)T_tok * lane * 2, hipMemcpyHostToDevice); + st_memcpy(d_v, hv.data(), (size_t)T_tok * lane * 2, hipMemcpyHostToDevice); + st_memcpy(d_sm, slots.data(), (size_t)T_tok * 4, hipMemcpyHostToDevice); + st_memset(d_c, 0x7f, cbytes); + std::vector ts = { + T(d_k, RAD_BF16, { T_tok, lane }), + T(d_v, RAD_BF16, { T_tok, lane }), + T(d_sm, RAD_I32, { T_tok }), + T(d_c, RAD_F8E4M3, { n_blocks, kv_heads, block_size, rowb }), + }; + std::vector ps = { + PI("M", T_tok), PI("head_dim", head_dim), PI("n_head_kv", kv_heads), + PI("block_size", block_size), PS("kv_dtype", k6 ? "k6_v4" : "fp8_v4"), + }; + run_case(r, ts, ps); + std::vector got(cbytes); + st_memcpy(got.data(), d_c, cbytes, hipMemcpyDeviceToHost); + + int bad = 0; + std::string first; + std::vector live_row((size_t)(n_blocks * block_size), false); + for (int64_t t = 0; t < T_tok; ++t) { + const int32_t s = slots[(size_t)t]; + if (s < 0 || s / block_size >= n_blocks) continue; + live_row[(size_t)s] = true; + for (int64_t h = 0; h < kv_heads; ++h) { + const uint8_t* row = &got[(size_t)(((s / block_size) * kv_heads + h) * block_size + + s % block_size) * rowb]; + for (int64_t d = 0; d < head_dim && bad < 4; ++d) { + float k; + if (k6) { + const int lo = (row[d / 2] >> (4 * (d & 1))) & 0xF; + const int x = (int)(d % 16); + const int hi = (row[head_dim / 2 + (d / 16) * 4 + (x & 7) / 2] + >> ((x & 1) * 2 + (x >> 3) * 4)) & 3; + uint16_t kb; + std::memcpy(&kb, row + head_dim * 5 / 4 + (d / 32) * 2, 2); + k = (float)(((lo | (hi << 4)) ^ 32) - 32) * (float)__builtin_bit_cast(_Float16, kb); + } else { + k = h_e4m3(row[d]); + } + const int nib = (row[voff + d / 2] >> (4 * (d & 1))) & 0xF; + uint16_t sb; + std::memcpy(&sb, row + vsoff + (d / 32) * 2, 2); + const float sc = (float)__builtin_bit_cast(_Float16, sb); + const float v = (float)((nib ^ 8) - 8) * sc; + const float wv = (float)vint(t, h, d) * step(t, h); + if (k != kval(t, h, d) || v != wv || sc != step(t, h)) { + if (!bad) first = fmt("t%lld h%lld d%lld: k %g (want %g) v %g (want %g) scale %g", + (long long)t, (long long)h, (long long)d, k, + kval(t, h, d), v, wv, sc); + ++bad; + } + } + } + } + int touched = 0; + for (int64_t s = 0; s < n_blocks * block_size; ++s) { + if (live_row[(size_t)s]) continue; + for (int64_t h = 0; h < kv_heads; ++h) { + const uint8_t* row = &got[(size_t)(((s / block_size) * kv_heads + h) * block_size + + s % block_size) * rowb]; + for (int64_t b = 0; b < rowb; ++b) touched += row[b] != 0x7f; + } + } + ok(name, bad == 0 && touched == 0, + bad ? first : fmt("every live row decodes exactly; %d bytes of other rows touched", touched)); +} + static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dtype) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); @@ -18351,6 +18514,8 @@ static void device_phase(const Plugin& pl) { /* --- the paged cache's write side --- */ kv_store_case(pl, "kv_store_bf16", "bf16"); kv_store_case(pl, "kv_store_fp8", "fp8_e4m3"); + kv_store_v4_case(pl); + kv_store_v4_case(pl, true); /* --- attention --- */ attn_case(pl, "attn_prefill_h256_gqa6_fp8kv", 256, 6, 32, "fp8_e4m3", 1); @@ -18388,6 +18553,16 @@ static void device_phase(const Plugin& pl) { * tstart = 961/48 = 20. This exercises the window mask and the below-window tile skip (tiles * 0..19 are never walked). */ attn_numeric_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 64, "fp8_e4m3", 1024, 2048); + /* fp8_v4 (Qwen3.8-27B's h256 gqa6): a prefill of several tiles over a longer history, a + * ragged last tile, and decode and verify rows. */ + attn_numeric_case(pl, "attn_prefill_h256_gqa6_fp8v4", 256, 6, 64, "fp8_v4", 0, 256); + attn_numeric_case(pl, "attn_prefill_h256_gqa6_fp8v4", 256, 6, 100, "fp8_v4", 0, 1024); + attn_numeric_case(pl, "attn_decode_h256_gqa6_fp8v4", 256, 6, 1, "fp8_v4", 0, 1024); + attn_numeric_case(pl, "attn_decode_h256_gqa6_fp8v4", 256, 6, 4, "fp8_v4", 0, 2048); + attn_numeric_case(pl, "attn_prefill_h256_gqa6_k6v4", 256, 6, 64, "k6_v4", 0, 256); + attn_numeric_case(pl, "attn_prefill_h256_gqa6_k6v4", 256, 6, 100, "k6_v4", 0, 1024); + attn_numeric_case(pl, "attn_decode_h256_gqa6_k6v4", 256, 6, 1, "k6_v4", 0, 1024); + attn_numeric_case(pl, "attn_decode_h256_gqa6_k6v4", 256, 6, 4, "k6_v4", 0, 2048); attn_numeric_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 64, "bf16", 1024, 2048); attn_numeric_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 1024); attn_numeric_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 1024); @@ -19841,6 +20016,8 @@ static void device_phase(const Plugin& pl) { qk_prologue_case(pl, RAD_F32, true, 128); qk_kv_fold_case(pl, false); qk_kv_fold_case(pl, true); + qk_kv_fold_case(pl, false, 1); + qk_kv_fold_case(pl, false, 2); qsa_qprep_case(pl); topk_scatter_case(pl); router_gemm_fused_case(pl); From 1823ccd5e9b5e77ebfaf20a37c8329e76a50f725 Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 14:13:45 +0000 Subject: [PATCH 038/152] --kv-cache-dtype fp8_v4 | k6_v4 (RadBuildCtx::kv_quant, RadArchProbe::kv_quant_ok; ABI 23) The flag sets the trunk's cache to E4M3 plus a RAD_KVQ_* layout; a plugin offers the layouts it serves in its probe and the server refuses any other, naming the plugin. qwen35_fp8 offers both at head_dim 256, gqa 6, and declares the group at head_dim 200 / 176 (the row's bytes / 2), so the core sizes pages as for fp8; a drafter's cache stays fp8. Qwen3.8-27B on two R9700s, KL against bf16 on 17 long documents: fp8 0.039963 (518,800 tokens of KV), fp8_v4 0.040076 (664,400), k6_v4 0.039965 (755,184); prefill and decode at fp8's speed. ABI 23: two trailing fields, the layout table regenerated. Co-Authored-By: Claude Opus 5.5 --- abi/rad_abi.h | 2 +- abi/rad_builder.h | 38 ++++++++++++++- arch/qwen35_fp8/qwen35_fp8.cpp | 34 +++++++++++++- core/config.cpp | 9 ++-- core/engine_bringup.cpp | 17 ++++++- core/rad_core.h | 9 ++-- docs/ARCHITECTURES.md | 2 +- docs/GUIDE.md | 19 +++++++- docs/OPS.md | 19 ++++++++ tests/abi_layout_rows.h | 2 + tests/abi_layout_table.h | 6 ++- tests/abi_layout_test.cpp | 6 +-- tests/arch_test.cpp | 86 ++++++++++++++++++++++++++++++++++ tests/config_test.cpp | 9 +++- 14 files changed, 238 insertions(+), 20 deletions(-) diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 834efdd1..ad302026 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -17,7 +17,7 @@ extern "C" { * kind of plugin reports it, and a plugin that does not report exactly this version is refused at * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 22u +#define RAD_ABI_VERSION 23u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_builder.h b/abi/rad_builder.h index d9b667af..70993b69 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -56,6 +56,29 @@ double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt); const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt); /* ================================================================== build context */ +/* RadBuildCtx::kv_quant. A layout groups each head's dims by 32 with an f16 scale per group, the + * group's absmax over the largest code. A token's row in a head, at head_dim HD (a multiple of 32): + * + * RAD_KVQ_V4 (fp8_v4), 25 * HD / 16 bytes: + * [0, HD) K, E4M3 as the fp8 cache stores it + * [HD, 3HD/2) V's int4 codes, dim d in the nibble at bit 4 * (d % 2) of byte d / 2 + * [3HD/2, 25HD/16) V's scales (absmax / 7) + * RAD_KVQ_K6V4 (k6_v4), 22 * HD / 16 bytes: + * [0, HD/2) K's low four bits, as V's codes above + * [HD/2, 3HD/4) K's high two bits, a 4-byte word per 16 dims whose byte j holds dims 2j + * and 2j+1 in bits 0-3 and dims 8+2j and 9+2j in bits 4-7 + * [3HD/4, 5HD/4) V's int4 codes + * [5HD/4, 21HD/16) K's scales (absmax / 31) + * [21HD/16, 22HD/16) V's scales (absmax / 7) + * + * Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with + * head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read it. */ +enum { + RAD_KVQ_NONE = 0, + RAD_KVQ_V4 = 1, + RAD_KVQ_K6V4 = 2 +}; + typedef struct RadBuildCtx { int rank; /* declare runs once per rank; the plugin declares dimensions */ int world_size; /* already divided -- the core inserts no collectives (spec §9) */ @@ -86,7 +109,7 @@ typedef struct RadBuildCtx { * RAD_DT_INVALID (the zero-initialised default) means the plugin's default, bf16 for every * architecture in this tree. RAD_F8E4M3 is the only other implemented value: the fp8kv * attention family is band-gated on it, and the store side writes E4M3 with per-(sequence, - * head) descales. + * head) descales. `kv_quant` below narrows the trunk's attention cache further. * * An ABI field rather than an environment variable because it changes what the model * computes, so it must have one visible answer: --kv-cache-dtype. */ @@ -140,6 +163,15 @@ typedef struct RadBuildCtx { * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int64_t max_mixed_tok; + + /* A narrower layout of the trunk's attention cache under kv_dtype RAD_F8E4M3, from + * --kv-cache-dtype fp8_v4 or k6_v4: a RAD_KVQ_* (below). The engine sets it only for a plugin + * whose probe has the layout's bit in RadArchProbe::kv_quant_ok and refuses the flag + * otherwise, so no plugin sees it that would store plain E4M3 instead. A drafter's cache stays + * E4M3. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + int kv_quant; } RadBuildCtx; /* ================================================================== weights */ @@ -993,6 +1025,10 @@ typedef struct RadArchProbe { * `gen_rows` (its largest pass: a step's packed sequence at the largest size and length). It * keeps no KV. */ int32_t gen_video; + /* The RadBuildCtx::kv_quant layouts the plugin serves for this model, bit 1 << RAD_KVQ_*: + * libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at + * startup with the plugin named. */ + int32_t kv_quant_ok; } RadArchProbe; int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index c1b80735..915e7238 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -554,9 +554,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); fd.n_head_kv = g.n_head_kv; fd.head_dim = g.head_dim; + /* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with f16 + * scales, K E4M3 as above or int6 the same way (libr4d's fp8_v4 / k6_v4 rows). A token's row + * is 25 or 22 * head_dim / 16 bytes instead of 2 * head_dim, so the group is declared at half + * that and the core sizes pages from it; only those kernels read the layout. The drafter's + * group stays E4M3 (declare_dflash2). The engine asks only for a layout probe() offered. */ + const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE; + const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4" : nullptr; + if (kvq != RAD_KVQ_NONE && !kvq_name) { + fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq); + return RAD_E_UNSUPPORTED; + } + if (kvq_name && !(g.head_dim == 256 && g.n_head == 6 * g.n_head_kv)) { + fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256, gqa 6 " + "only; this model is head_dim %lld, gqa %lld\n", kvq_name, + (long long)g.head_dim, (long long)(g.n_head_kv ? g.n_head / g.n_head_kv : 0)); + return RAD_E_UNSUPPORTED; + } + const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32; + fd.head_dim = g.head_dim * row16 / 32; m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); /* The op parameter must use the spelling the rows band on, which is rad_dtype_name's. */ - g.kv_dtype = rad_dtype_name(fd.dtype); + g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype); + if (kvq_name) + rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a token " + "and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6", + (long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim)); /* The SSM state cache is f32. * @@ -1175,6 +1198,15 @@ static void step(RadCtx* c, const RadBatch* batch) { * 0 when the container carries no drafter. */ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; + /* --kv-cache-dtype fp8_v4 / k6_v4: libr4d's rows for them are the h256/gqa6 attention + * family's (Qwen3.8-27B), so other geometries are refused at startup rather than in declare. */ + { + const long long hd = meta->head_dim ? meta->head_dim + : (meta->n_head ? meta->n_embd / meta->n_head : 0); + const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head; + if (hd == 256 && nkv > 0 && meta->n_head == 6 * nkv) + out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4); + } const char* da = rad_meta_gets(meta, "draft.architectures", ""); if (da && std::strstr(da, "DFlash2")) { const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8); diff --git a/core/config.cpp b/core/config.cpp index 871f9820..c3eeb23e 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -71,7 +71,9 @@ static const Flag g_flags[] = { "keys, no reconvert (docs/YARN.md); none: off" }, { "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" }, - { "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" }, + { "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n" + "context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n" + "also K in 6 (0.69); both Qwen3.8-27B" }, { "--host-pool-mib", "N", "pinned host tier" }, { "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n" " pins its host memory at startup (default 4096)" }, @@ -466,8 +468,9 @@ int config_parse(int argc, char** argv, Config* c) { else if (S("--host-headroom-mib")) { if (!num(0, INT64_MAX, &c->host_headroom_mib)) return RAD_E_INVAL; } else if (S("--kv-cache-dtype")) { if (!(v = need(i))) return RAD_E_INVAL; - if (std::strcmp(v, "bf16") && std::strcmp(v, "fp8")) { - RAD_ERR("--kv-cache-dtype takes bf16 or fp8, not '%s'", v); + if (std::strcmp(v, "bf16") && std::strcmp(v, "fp8") && std::strcmp(v, "fp8_v4") && + std::strcmp(v, "k6_v4")) { + RAD_ERR("--kv-cache-dtype takes bf16, fp8, fp8_v4 or k6_v4, not '%s'", v); return RAD_E_INVAL; } c->kv_cache_dtype = v; diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 934dca63..58046b1e 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -881,7 +881,9 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { bc.tp_wire_lossy = cfg_.tp_wire_exact ? 0 : 1; /* The engine always states the KV dtype. RAD_DT_INVALID (zero) remains valid in the ABI for * other callers and means the plugin's default. */ - bc.kv_dtype = cfg_.kv_cache_dtype == "fp8" ? RAD_F8E4M3 : RAD_BF16; + bc.kv_dtype = cfg_.kv_cache_dtype == "bf16" ? RAD_BF16 : RAD_F8E4M3; + bc.kv_quant = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4 + : cfg_.kv_cache_dtype == "k6_v4" ? RAD_KVQ_K6V4 : RAD_KVQ_NONE; bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024; bc.scope = ""; bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0; @@ -987,6 +989,19 @@ int Engine::declare() { cfg_.prefix_cache = false; } } + /* fp8_v4 and k6_v4 are layouts only the plugin and libr4d's rows for them know. A plugin that + * does not say it serves one (RadArchProbe::kv_quant_ok) would store plain E4M3 under a name + * that promised a smaller cache, so the flag is refused rather than ignored. */ + if (cfg_.kv_cache_dtype == "fp8_v4" || cfg_.kv_cache_dtype == "k6_v4") { + const int q = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4 : RAD_KVQ_K6V4; + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + if (!(pb.kv_quant_ok & (1 << q))) { + RAD_ERR("--kv-cache-dtype %s: the '%s' plugin does not serve it for this model " + "(fp8 does)", cfg_.kv_cache_dtype.c_str(), plugins_.arch_plugin.c_str()); + return RAD_E_UNSUPPORTED; + } + } /* Resolved here, not at argument parsing: the plugin states its drafter's depth, and it is * selected only once the container is open. Every consumer of `n_spec` (buffer sizing, kernel * bands, the scheduler's window) runs after this. rad_arch_probe is the core's only source of diff --git a/core/rad_core.h b/core/rad_core.h index 3e625702..a0dab54a 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -737,10 +737,11 @@ struct Config { int64_t vram_weights_mib = 0; int64_t vram_kv_mib = 0; int64_t gpu_headroom_mib = 96; /* --gpu-headroom-mib, left unclaimed on every card */ - /* --kv-cache-dtype bf16|fp8. fp8 is an E4M3 cache with per-(sequence, head) descales; it - * halves the per-token cost, most of the KV pool at production context. It changes the - * model's output slightly, so it is explicit and bf16 is the default. No "auto": it would - * always resolve to bf16 and only add a third name. */ + /* --kv-cache-dtype bf16|fp8|fp8_v4|k6_v4. fp8 is an E4M3 cache with per-(sequence, head) + * descales; it halves the per-token cost, most of the KV pool at production context. fp8_v4 + * keeps K as E4M3 and V as int4 in groups of 32, k6_v4 also K as int6 (RadBuildCtx::kv_quant), + * served only where the plugin says so. Each changes the model's output slightly, so it is explicit and bf16 is the + * default. No "auto": it would always resolve to bf16 and only add another name. */ std::string kv_cache_dtype = "bf16"; int64_t host_pool_mib = 0; int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */ diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 415f04a0..8a946764 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -194,7 +194,7 @@ Three groups, which is why hybrid KV groups are first-class: | group | kind | geometry | |---|---|---| -| full attention | `RAD_KV_FULL` | 16 layers, head_dim 256, 4 KV heads; block size from the resolved kernel | +| full attention | `RAD_KV_FULL` | 16 layers, head_dim 256, 4 KV heads; block size from the resolved kernel. `--kv-cache-dtype fp8_v4` / `k6_v4` (`qwen35_fp8` only) declare it at head_dim 200 / 176, the bytes of a token's quantised row over two (docs/OPS.md) | | GDN recurrent state | `RAD_KV_LINEAR` | 48 layers, 48 states of 128 x 128 | | GDN conv state | `RAD_KV_CONV` | 48 layers, 2*16 + 48 = 80 heads x 128 = 10240 channels, a rolling `conv_width - 1 + n_spec` window | diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 5aec839e..56967b33 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -783,6 +783,23 @@ widths, and the flag sets every attention cache of the deployment, a drafter's ( included. The delta-net state and the QSA indexer's key tail are recurrent state and keep their own widths. +`fp8_v4` and `k6_v4` narrow the trunk's attention cache further, in groups of 32 dimensions with an +f16 scale each: `fp8_v4` keeps K in E4M3 and stores V as int4, `k6_v4` stores K as int6 too. A token +then costs 25/32 or 22/32 of what fp8 costs, and a drafter's cache stays fp8. libr4d has their +kernels for Qwen3.8-27B's attention (head_dim 256, gqa 6), so the plugin offers them there and the +server refuses them, naming the plugin, anywhere else. On two R9700s at the serve flags of +`qwen3.8-27b-mxfp4.yaml` with `--max-num-batched-tokens 2048` and 12 GiB a card left to another +engine, against the bf16 model on 17 long log-analysis documents (60 368 scored positions): + +| `--kv-cache-dtype` | KV pool | mean KL | top-1 | 41k-token prefill | decode, 1 / 16 streams | +|---|---|---|---|---|---| +| `fp8` | 518 800 tokens | 0.039963 | 94.03% | 9.76 s | 134-140 / 550-555 tok/s | +| `fp8_v4` | 664 400 (+28%) | 0.040076 | 94.03% | 9.76 s | 130-139 / 553-557 | +| `k6_v4` | 755 184 (+46%) | 0.039965 | 94.06% | 9.84 s | 136-138 / 553-561 | + +The decode spread is run to run; the three are the same speed there. Each layout's row and the +kernels that read it are in [OPS.md](OPS.md#the-kv-cache-operand). + **Many sequences.** Every model here serves `--max-num-seqs` up to 32. A sequence holds only the blocks its tokens occupy, but two costs exist per sequence regardless: @@ -1322,7 +1339,7 @@ still verified by the adapter, so output is exact and only the acceptance rate c | flag | default | | |---|---|---| | `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card | -| `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` | +| `--kv-cache-dtype T` | bf16 | `bf16`, `fp8`, or on Qwen3.8-27B `fp8_v4` or `k6_v4` (§4.4) | | `--host-pool-mib N` | 0 | pinned host tier (weights) | | `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3) | | `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card (§4.3) | diff --git a/docs/OPS.md b/docs/OPS.md index 3592b153..77c6c0ad 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -812,6 +812,25 @@ declares bound it lower. `RadKVGroupBatch` carries the slot mapping, the block table and the sequence lengths, but the pool base belongs to the block manager, not the batch. +**`kv_dtype` `fp8_v4` and `k6_v4`** (device-only) are the quantised layouts of +`--kv-cache-dtype` (`RadBuildCtx::kv_quant`). A head's dims are grouped by 32, each group with an +f16 scale (its absmax over the largest code), codes two's complement. A token's row in a head, at +head_dim HD: + +| bytes | `fp8_v4` (25 HD / 16) | `k6_v4` (22 HD / 16) | +|---|---|---| +| K | [0, HD): E4M3, as `fp8_e4m3` | [0, HD/2): the codes' low four bits; [HD/2, 3HD/4): their high two bits, a word per 16 dims whose byte j holds dims 2j, 2j+1 in bits 0-3 and 8+2j, 9+2j in bits 4-7 | +| V | [HD, 3HD/2): int4 codes, dim d in the nibble at bit 4 (d mod 2) of byte d/2 | [3HD/4, 5HD/4): the same | +| scales | [3HD/2, 25HD/16): V's (absmax / 7) | [5HD/4, 21HD/16): K's (absmax / 31); [21HD/16, 22HD/16): V's | + +The group is declared at `RAD_F8E4M3` with head_dim the row's bytes / 2, so the core sizes pages +as it does for fp8, and the cache operand's last extent is the row. The ops take the model's +head_dim. libr4d's rows are `kv_store_fp8v4` / `kv_store_k6v4`, +`qk_norm_rope_gate_kv_store_fp8v4` / `_k6v4` (byte-identical to the prologue and the store, as at +the other widths), and `attn_prefill_h256_gqa6_{fp8v4,k6v4}` and `attn_decode_h256_gqa6_{fp8v4,k6v4}`, +which widen the codes to f16 in a tile's staging. `r4d_selftest` holds the stores to an exactly +representable set and the attention rows to its inline oracle. + ### `qk_norm_rope_gate` (device-only) | op | params | operands | diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 26fac72c..22691472 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -16,6 +16,7 @@ ABI_FIELD(RadArchProbe, gen_patches) ABI_FIELD(RadArchProbe, gen_audio) ABI_FIELD(RadArchProbe, gen_ctx) ABI_FIELD(RadArchProbe, gen_video) +ABI_FIELD(RadArchProbe, kv_quant_ok) ABI_STRUCT(RadArgs) ABI_FIELD(RadArgs, t) ABI_FIELD(RadArgs, n_t) @@ -99,6 +100,7 @@ ABI_FIELD(RadBuildCtx, max_enc_patches) ABI_FIELD(RadBuildCtx, max_out_rows) ABI_FIELD(RadBuildCtx, max_audio_frames) ABI_FIELD(RadBuildCtx, max_mixed_tok) +ABI_FIELD(RadBuildCtx, kv_quant) ABI_STRUCT(RadAudioGenBatch) ABI_FIELD(RadAudioGenBatch, n_lane) ABI_FIELD(RadAudioGenBatch, lane) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 1217e181..67222040 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,4 +1,4 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 21 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 23 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ @@ -13,6 +13,7 @@ { "RadArchProbe", "gen_audio", 48, 4 }, { "RadArchProbe", "gen_ctx", 56, 8 }, { "RadArchProbe", "gen_video", 64, 4 }, +{ "RadArchProbe", "kv_quant_ok", 68, 4 }, { "RadArgs", "", 0, 64 }, { "RadArgs", "t", 0, 8 }, { "RadArgs", "n_t", 8, 4 }, @@ -79,7 +80,7 @@ { "RadBufDecl", "domain", 60, 4 }, { "RadBufDecl", "derive", 64, 8 }, { "RadBufDecl", "kv", 72, 4 }, -{ "RadBuildCtx", "", 0, 104 }, +{ "RadBuildCtx", "", 0, 112 }, { "RadBuildCtx", "rank", 0, 4 }, { "RadBuildCtx", "world_size", 4, 4 }, { "RadBuildCtx", "max_tok", 8, 8 }, @@ -96,6 +97,7 @@ { "RadBuildCtx", "max_out_rows", 80, 8 }, { "RadBuildCtx", "max_audio_frames", 88, 8 }, { "RadBuildCtx", "max_mixed_tok", 96, 8 }, +{ "RadBuildCtx", "kv_quant", 104, 4 }, { "RadAudioGenBatch", "", 0, 264 }, { "RadAudioGenBatch", "n_lane", 0, 8 }, { "RadAudioGenBatch", "lane", 8, 8 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index eae119e5..bc804bc0 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -8,7 +8,7 @@ * * Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every * struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and - * the layout agrees with the table below, taken at RAD_ABI_VERSION 22 and RAD_FORMAT_VER 2. Under + * the layout agrees with the table below, taken at RAD_ABI_VERSION 23 and RAD_FORMAT_VER 2. Under * those versions a listed field may not move or change size, an ABI struct may only grow by fields * past its old end, and an on-disk struct may not change at all. The table is a snapshot of the * headers: nothing else states the layout. When it disagrees the test prints the live table. @@ -57,8 +57,8 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 22 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 22, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 23 / RAD_FORMAT_VER 2 (see the file header). */ +constexpr uint32_t kTableAbi = 23, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index b4e70477..f858d8ba 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -6081,6 +6081,92 @@ TEST(gemma3_dflash2_drafter_taps_and_block) { CHECK_EQ(q.draft_depth, 0); } +/* --kv-cache-dtype fp8_v4: the trunk's attention cache is E4M3 K (256 bytes), int4 V (128) and + * eight f16 scales, 400 bytes a token and head, declared as 25 * 256 / 32 = 200 E4M3 columns so the + * core sizes its pages; every trunk op on it bands on kv_dtype fp8_v4. The DFlash2 drafter's own + * group stays E4M3 at its head_dim. Without kv_quant the same build is plain fp8. */ +TEST(qwen35_fp8_fp8_v4_cache_is_400_bytes_a_token_and_head) { + MetaKV mk = with_dflash2(q35fp8_meta()); + auto count = [](const RadBuilder& b, const char* kd) { + int n = 0; + for (const auto& o : b.ops) if (pstr(&o, "kv_dtype") == kd) ++n; + return n; + }; + RadBuilder f8; + RadBuildCtx c8 = spec_ctx(0, 1, 7); + c8.kv_dtype = RAD_F8E4M3; + REQUIRE_EQ(qwen35_fp8::declare(&f8, mk.meta(), &c8), RAD_OK); + CHECK_EQ(f8.kv_groups[0].d.head_dim, 256); + CHECK_EQ(count(f8, "fp8_v4"), 0); + const int n8 = count(f8, "fp8_e4m3"); + + RadBuilder b; + RadBuildCtx ctx = c8; + ctx.kv_quant = RAD_KVQ_V4; + REQUIRE_EQ(qwen35_fp8::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK_EQ(b.kv_groups[0].name, std::string("kv_attn")); + const RadKVGroupDecl& f = b.kv_groups[0].d; + CHECK_EQ(f.kind, RAD_KV_FULL); + CHECK_EQ(f.dtype, (uint32_t)RAD_F8E4M3); + CHECK_EQ(f.n_head_kv, 4); + CHECK_EQ(f.head_dim, 200); + const RadKVGroupDecl& d = b.kv_groups.back().d; + CHECK_EQ(d.dtype, (uint32_t)RAD_F8E4M3); + CHECK_EQ(d.head_dim, 128); + const int v4 = count(b, "fp8_v4"), e4 = count(b, "fp8_e4m3"); + CHECK(v4 > 0); + CHECK(e4 > 0); /* the drafter's attention */ + CHECK_EQ(v4 + e4, n8); + CHECK(noted(b, "kv cache fp8_v4")); + + RadArchProbe p{}; + CHECK_OK(qwen35_fp8::probe(mk.meta(), &p)); + CHECK_EQ(p.kv_quant_ok, (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4)); +} + +/* --kv-cache-dtype k6_v4: int6 K and int4 V, each in groups of 32 with an f16 scale, 352 bytes a + * token and head, declared as 176 E4M3 columns; the trunk's ops band on kv_dtype k6_v4 and the + * drafter's group stays E4M3. */ +TEST(qwen35_fp8_k6_v4_cache_is_352_bytes_a_token_and_head) { + MetaKV mk = with_dflash2(q35fp8_meta()); + RadBuilder b; + RadBuildCtx ctx = spec_ctx(0, 1, 7); + ctx.kv_dtype = RAD_F8E4M3; + ctx.kv_quant = RAD_KVQ_K6V4; + REQUIRE_EQ(qwen35_fp8::declare(&b, mk.meta(), &ctx), RAD_OK); + const RadKVGroupDecl& f = b.kv_groups[0].d; + CHECK_EQ(f.dtype, (uint32_t)RAD_F8E4M3); + CHECK_EQ(f.head_dim, 176); + CHECK_EQ(b.kv_groups.back().d.head_dim, 128); + int k6 = 0, v4 = 0, e4 = 0; + for (const auto& o : b.ops) { + const std::string kd = pstr(&o, "kv_dtype"); + k6 += kd == "k6_v4"; v4 += kd == "fp8_v4"; e4 += kd == "fp8_e4m3"; + } + CHECK(k6 > 0); + CHECK(e4 > 0); + CHECK_EQ(v4, 0); + CHECK(noted(b, "kv cache k6_v4")); +} + +/* libr4d's fp8_v4 and k6_v4 rows are h256/gqa6 only: the probe answers no for another geometry, so the + * engine refuses the flag at startup, and declare refuses it too if asked anyway. */ +TEST(qwen35_fp8_quantised_kv_is_refused_outside_h256_gqa6) { + MetaKV mk = q35fp8_meta(); + mk.m.n_head_kv = 2; /* gqa 12 */ + RadArchProbe p{}; + CHECK_OK(qwen35_fp8::probe(mk.meta(), &p)); + CHECK_EQ(p.kv_quant_ok, 0); + for (int q : { (int)RAD_KVQ_V4, (int)RAD_KVQ_K6V4 }) { + RadBuilder b; + RadBuildCtx ctx = build_ctx(); + ctx.kv_dtype = RAD_F8E4M3; + ctx.kv_quant = q; + CHECK_EQ(stderr_of_rc([&] { return qwen35_fp8::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } +} + /* The 35B-A3B: a replicated router over every expert, a normalised top-k (norm_topk_prob * defaults on in this family; without it the weights sum to about 0.4), fp8a8 grouped GEMMs over * the expert planes, and the shared expert folded into the gather behind a sigmoid gate. */ diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 3f43b87d..78af66f2 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -621,16 +621,21 @@ TEST(the_p2p_mode_is_one_of_three_names) { CHECK_EQ(parse({ "--p2p", "OFF" }, &c), RAD_E_INVAL); } -TEST(the_kv_cache_dtype_is_one_of_two_names) { +TEST(the_kv_cache_dtype_is_one_of_four_names) { Config c; CHECK_EQ(parse({ "--kv-cache-dtype", "bf16" }, &c), RAD_OK); CHECK_EQ(c.kv_cache_dtype, std::string("bf16")); CHECK_EQ(parse({ "--kv-cache-dtype", "fp8" }, &c), RAD_OK); CHECK_EQ(c.kv_cache_dtype, std::string("fp8")); - /* Two values only: an "auto" resolving to bf16 would be a second name for the default, and + CHECK_EQ(parse({ "--kv-cache-dtype", "fp8_v4" }, &c), RAD_OK); + CHECK_EQ(c.kv_cache_dtype, std::string("fp8_v4")); + CHECK_EQ(parse({ "--kv-cache-dtype", "k6_v4" }, &c), RAD_OK); + CHECK_EQ(c.kv_cache_dtype, std::string("k6_v4")); + /* Four values only: an "auto" resolving to bf16 would be a second name for the default, and * each value should be unambiguous in a log. */ CHECK_EQ(parse({ "--kv-cache-dtype", "auto" }, &c), RAD_E_INVAL); CHECK_EQ(parse({ "--kv-cache-dtype", "fp16" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--kv-cache-dtype", "v4" }, &c), RAD_E_INVAL); Config d; CHECK_EQ(parse({}, &d), RAD_OK); From 3e656f0b023798e7313d91930c73bac10ff78f2a Mon Sep 17 00:00:00 2001 From: mici81 Date: Sun, 18 Oct 2026 17:41:15 +0000 Subject: [PATCH 039/152] libr4d: review fixes -- the quantised stores apply v_scale; scales clamped so every code decodes finite; two more selftest shapes kv_store_fp8v4 / k6v4 and the folds now read v_scale as the fp8 store does (attention already applied v_descale). Scales are clamped to 8188 (V) and 2112 (K) so 7 or 31 times them stays an f16: a group gone inf or NaN decodes finite, as E4M3's clamp to 448 does. r4d_selftest adds decode at ctx 1000 (a partial last block) and q_len 7 (three waves) for both layouts. Co-Authored-By: Claude Opus 5.5 --- docs/OPS.md | 3 ++- libr4d/r4d_model_bf16.hip | 18 +++++++++++------- libr4d/r4d_qk_norm_rope_gate.hip | 11 ++++++----- libr4d/r4d_selftest.cpp | 9 ++++++++- 4 files changed, 27 insertions(+), 14 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index 77c6c0ad..f5cd2275 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -814,7 +814,8 @@ base belongs to the block manager, not the batch. **`kv_dtype` `fp8_v4` and `k6_v4`** (device-only) are the quantised layouts of `--kv-cache-dtype` (`RadBuildCtx::kv_quant`). A head's dims are grouped by 32, each group with an -f16 scale (its absmax over the largest code), codes two's complement. A token's row in a head, at +f16 scale (its absmax over the largest code, clamped so every code decodes finite in f16), +codes two's complement. A token's row in a head, at head_dim HD: | bytes | `fp8_v4` (25 HD / 16) | `k6_v4` (22 HD / 16) | diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index f9fcc1df..aa48c382 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -580,7 +580,7 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel( const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, const int32_t* __restrict__ slot, uint8_t* __restrict__ kv, uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, uint32_t n_blocks, - uint32_t k_ld, uint32_t v_ld, float k_inv, uint32_t row) { + uint32_t k_ld, uint32_t v_ld, float k_inv, float v_inv, uint32_t row) { const uint32_t t = blockIdx.x; const int32_t s = slot[t]; if (s < 0 || (uint32_t)s / block_size >= n_blocks) return; @@ -595,7 +595,7 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel( #pragma unroll for (int e = 0; e < 4; ++e) { kf[e] = bf16_to_f32(k[(size_t)t * k_ld + j + (uint32_t)e]) * k_inv; - vf[e] = bf16_to_f32(v[(size_t)t * v_ld + j + (uint32_t)e]); + vf[e] = bf16_to_f32(v[(size_t)t * v_ld + j + (uint32_t)e]) * v_inv; } const uint32_t voff = K6 ? head_dim * 3 / 4 : head_dim; const uint32_t vsoff = K6 ? head_dim * 21 / 16 : head_dim * 3 / 2; @@ -603,7 +603,9 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel( // A group of 32 is 8 lanes; its scale absmax / 31 in f16, codes 6-bit two's complement. float kmax = fmaxf(fmaxf(fabsf(kf[0]), fabsf(kf[1])), fmaxf(fabsf(kf[2]), fabsf(kf[3]))); for (int m = 4; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32)); - const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 65504.0f); + // Clamped so 31 times it stays an f16 (65504): a group gone inf + // or NaN decodes finite, as the E4M3 form's clamp to 448 does. + const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 2112.0f); const float ksc = (float)k16; uint32_t q[4]; #pragma unroll @@ -633,7 +635,8 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel( float amax = fmaxf(fmaxf(fabsf(vf[0]), fabsf(vf[1])), fmaxf(fabsf(vf[2]), fabsf(vf[3]))); for (int m = 4; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32)); - const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 65504.0f); + // Clamped so 7 times it stays an f16: see the K scale above. + const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 8188.0f); const float sc = (float)s16; uint32_t q[4]; #pragma unroll @@ -1861,7 +1864,8 @@ static int kv_store_q4(const RadArgs* a, RadStream stream, int k6) { if (g.kv->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE); if (g.head_dim % 32) return R4D_NO(RAD_E_SHAPE); const double ks = r4d_getf(a, "k_scale", 1.0); - if (!(ks > 0.0)) return R4D_NO(RAD_E_INVAL); + const double vs = r4d_getf(a, "v_scale", 1.0); + if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL); long long k_ld = g.k_ld ? g.k_ld : g.kv_heads * g.head_dim; long long v_ld = g.v_ld ? g.v_ld : g.kv_heads * g.head_dim; if (k6) @@ -1870,13 +1874,13 @@ static int kv_store_q4(const RadArgs* a, RadStream stream, int k6) { (const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv), (uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size, (uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, (float)(1.0 / ks), - (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE; + (float)(1.0 / vs), (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE; return R4D_EMIT(stream, kv_store_fp8v4_kernel<0>, dim3((uint32_t)g.T), dim3(kThreads), 0, (const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v), (const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv), (uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size, (uint32_t)g.n_blocks, (uint32_t)k_ld, (uint32_t)v_ld, (float)(1.0 / ks), - (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE; + (float)(1.0 / vs), (uint32_t)(g.head_dim * r16 / 16)) == RAD_OK ? RAD_OK : RAD_E_DEVICE; } extern "C" int r4d_rad_kv_store_fp8v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 0); } extern "C" int r4d_rad_kv_store_k6v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 1); } diff --git a/libr4d/r4d_qk_norm_rope_gate.hip b/libr4d/r4d_qk_norm_rope_gate.hip index 12a6fe97..9274a31f 100644 --- a/libr4d/r4d_qk_norm_rope_gate.hip +++ b/libr4d/r4d_qk_norm_rope_gate.hip @@ -174,7 +174,7 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( if constexpr (KV == QK_KV_K6V4) { float kmax = fabsf(kf); for (int m = 16; m >= 1; m >>= 1) kmax = fmaxf(kmax, __shfl_xor(kmax, m, 32)); - const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 65504.0f); + const __fp16 k16 = (__fp16)fminf(kmax / 31.0f, 2112.0f); // finite codes, as kv_store_k6v4 const float ksc = (float)k16; const float r = ksc > 0.0f ? rintf(kf / ksc) : 0.0f; const int q = ((int)fminf(fmaxf(r, -31.0f), 31.0f)) & 0x3F; @@ -191,10 +191,10 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( 0, false); c[t] = (unsigned char)(pk & 0xFF); } - const float vf = __bfloat162float(vb); + const float vf = __bfloat162float(vb) * kvs.v_inv; float amax = fabsf(vf); for (int m = 16; m >= 1; m >>= 1) amax = fmaxf(amax, __shfl_xor(amax, m, 32)); - const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 65504.0f); + const __fp16 s16 = (__fp16)fminf(amax / 7.0f, 8188.0f); // finite codes, as kv_store_fp8v4 const float sc = (float)s16; const float r = sc > 0.0f ? rintf(vf / sc) : 0.0f; const int q = ((int)fminf(fmaxf(r, -7.0f), 7.0f)) & 0xF; @@ -411,7 +411,8 @@ static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) { if (v_ld < 0) return R4D_NO(RAD_E_STRIDE); if (Mv < M || r4d_numel(sm) != M) return R4D_NO(RAD_E_SHAPE); const double ks = r4d_getf(args, "k_scale", 1.0); - if (!(ks > 0.0)) return R4D_NO(RAD_E_INVAL); + const double vs = r4d_getf(args, "v_scale", 1.0); + if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL); QkKvStore kvs{}; kvs.v = (const __hip_bfloat16*)r4d_p(v); kvs.slot = (const int32_t*)r4d_p(sm); @@ -420,7 +421,7 @@ static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) { kvs.block_size = (int)bs; kvs.n_blocks = (int)kv->shape[0]; kvs.k_inv = 1.0f / (float)ks; - kvs.v_inv = 1.0f; + kvs.v_inv = 1.0f / (float)vs; kvs.row = (int)(hd * r16 / 16); return k6 ? qk_body(args, stream, kvs) : qk_body(args, stream, kvs); } diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 4b72ee15..e9c4748d 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -941,7 +941,7 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d if (!r) { ok(name, false, "row absent"); return; } const int64_t seqs = 1, kv_heads = 2, bs = 16; const int64_t q_heads = kv_heads * gqa; - const int64_t max_blocks = ctx / bs; + const int64_t max_blocks = (ctx + bs - 1) / bs; /* a ctx past a whole block: a partial last one */ const int64_t total_q = seqs * q_len; const int kv_is_fp8 = std::strcmp(kv_dtype, "bf16") != 0; const int kvq = !std::strcmp(kv_dtype, "fp8_v4") ? 1 : !std::strcmp(kv_dtype, "k6_v4") ? 2 : 0; @@ -18563,6 +18563,13 @@ static void device_phase(const Plugin& pl) { attn_numeric_case(pl, "attn_prefill_h256_gqa6_k6v4", 256, 6, 100, "k6_v4", 0, 1024); attn_numeric_case(pl, "attn_decode_h256_gqa6_k6v4", 256, 6, 1, "k6_v4", 0, 1024); attn_numeric_case(pl, "attn_decode_h256_gqa6_k6v4", 256, 6, 4, "k6_v4", 0, 2048); + /* A ctx past a whole block (a partial last tile), and q_len 7: three waves, where the V + * staging's unit count is not a multiple of the threads. */ + for (const char* kv : { "fp8_v4", "k6_v4" }) { + const std::string dec = std::string("attn_decode_h256_gqa6_") + (kv[0] == 'f' ? "fp8v4" : "k6v4"); + attn_numeric_case(pl, dec.c_str(), 256, 6, 1, kv, 0, 1000); + attn_numeric_case(pl, dec.c_str(), 256, 6, 7, kv, 0, 1000); + } attn_numeric_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 64, "bf16", 1024, 2048); attn_numeric_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 1024); attn_numeric_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 1024); From 5ac0bc9690096ffebf7529e33c1dcc301a0a55ed Mon Sep 17 00:00:00 2001 From: Nunze Date: Mon, 19 Oct 2026 14:42:52 +0200 Subject: [PATCH 040/152] tests/data/chat: GLM-5.3's template as a fifth reference render The template as GLM-5.3-Flash ships it, in cases.json beside the other four, with its goldens from mkchatgolden.py (jinja2 3.1.6); bos is empty, eos <|endoftext|>, and no media, since no architecture here reads its pictures. It needs the dotted index (vendor/patches/0021). Two cases leave it out: an assistant turn with tool calls and content null. The template prints that content bare ({{- content }} in visible_text), so jinja2 writes "None" into the turn, and the engine, as llama.cpp's runtime does, writes nothing. The golden would hold the engine to a template bug; the reply-side tests for this format read those turns instead. Co-Authored-By: Claude Opus 5.5 --- tests/chat_test.cpp | 4 +- tests/data/chat/glm53/chat_template.jinja | 257 ++++++++++++++++++ tests/data/chat/glm53/golden/effort_low.txt | 1 + .../golden/effort_the_template_refuses.txt | 1 + .../glm53/golden/history_with_reasoning.txt | 1 + .../golden/history_with_reasoning_dropped.txt | 1 + .../history_with_reasoning_preserved.txt | 1 + .../glm53/golden/no_generation_prompt.txt | 1 + .../parallel_calls_with_typed_arguments.txt | 15 + .../chat/glm53/golden/system_and_user.txt | 1 + tests/data/chat/glm53/golden/thinking_off.txt | 1 + .../tool_calls_preserving_reasoning.txt | 15 + .../data/chat/glm53/golden/tools_and_user.txt | 14 + .../glm53/golden/tools_system_and_user.txt | 14 + tests/data/chat/glm53/golden/unicode_text.txt | 14 + tests/data/chat/golden/cases.json | 5 +- 16 files changed, 343 insertions(+), 3 deletions(-) create mode 100644 tests/data/chat/glm53/chat_template.jinja create mode 100644 tests/data/chat/glm53/golden/effort_low.txt create mode 100644 tests/data/chat/glm53/golden/effort_the_template_refuses.txt create mode 100644 tests/data/chat/glm53/golden/history_with_reasoning.txt create mode 100644 tests/data/chat/glm53/golden/history_with_reasoning_dropped.txt create mode 100644 tests/data/chat/glm53/golden/history_with_reasoning_preserved.txt create mode 100644 tests/data/chat/glm53/golden/no_generation_prompt.txt create mode 100644 tests/data/chat/glm53/golden/parallel_calls_with_typed_arguments.txt create mode 100644 tests/data/chat/glm53/golden/system_and_user.txt create mode 100644 tests/data/chat/glm53/golden/thinking_off.txt create mode 100644 tests/data/chat/glm53/golden/tool_calls_preserving_reasoning.txt create mode 100644 tests/data/chat/glm53/golden/tools_and_user.txt create mode 100644 tests/data/chat/glm53/golden/tools_system_and_user.txt create mode 100644 tests/data/chat/glm53/golden/unicode_text.txt diff --git a/tests/chat_test.cpp b/tests/chat_test.cpp index 7bdb06bc..46b5e9cb 100644 --- a/tests/chat_test.cpp +++ b/tests/chat_test.cpp @@ -288,8 +288,8 @@ TEST(every_shipped_template_renders_as_reference_jinja_does) { "reference render " + first_difference(ref, got)); } } - /* Four templates, every case each one renders. */ - CHECK(compared >= 60); + /* Five templates, every case each one renders. */ + CHECK(compared >= 73); } /* ------------------------------------------------------------------ reading the reply back */ diff --git a/tests/data/chat/glm53/chat_template.jinja b/tests/data/chat/glm53/chat_template.jinja new file mode 100644 index 00000000..fb94d40d --- /dev/null +++ b/tests/data/chat/glm53/chat_template.jinja @@ -0,0 +1,257 @@ +[gMASK] +{%- set effective_reasoning_effort = reasoning_effort if reasoning_effort is defined and reasoning_effort in ['low', 'high'] else 'max' -%} +{%- if effective_reasoning_effort is not none -%}<|system|>Reasoning Effort: {{ effective_reasoning_effort | capitalize }}{%- endif -%} +{%- set clear_thinking = clear_thinking if clear_thinking is defined else false -%} +{%- if tools -%} +{%- macro tool_to_json(tool) -%} + {%- set ns_tool = namespace(first=true) -%} + {{ '{' -}} + {%- for k, v in tool.items() -%} + {%- if k != 'defer_loading' and k != 'strict' -%} + {%- if not ns_tool.first -%}{{- ', ' -}}{%- endif -%} + {%- set ns_tool.first = false -%} + "{{ k }}": {{ v | tojson(ensure_ascii=False) }} + {%- endif -%} + {%- endfor -%} + {{- '}' -}} +{%- endmacro -%} +{%- macro tool_references_to_response(refs) -%} + {{- '\n' -}} + {%- for tr in refs -%} + {%- for tool in tools -%} + {%- if 'function' in tool -%} + {%- set tool = tool['function'] -%} + {%- endif -%} + {%- if tool.name == tr.name -%} + {{- tool_to_json(tool) + '\n' -}} + {%- endif -%} + {%- endfor -%} + {%- endfor -%} + {{- '' -}} +{%- endmacro -%} +<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{% for tool in tools %} +{%- if 'function' in tool -%} + {%- set tool = tool['function'] -%} +{%- endif -%} +{% if tool.defer_loading is not defined or not tool.defer_loading %} +{{ tool_to_json(tool) }} +{% endif %} +{% endfor %} + + +For each function call, output the function name and arguments within the following XML format: +{function-name}{arg-key-1}{arg-value-1}{arg-key-2}{arg-value-2}...{%- endif -%} +{%- macro emit_image() -%}<|begin_of_image|><|image|><|end_of_image|>{%- endmacro -%} +{%- macro emit_video() -%}<|begin_of_video|><|video|><|end_of_video|>{%- endmacro -%} +{%- macro emit_audio() -%}<|begin_of_audio|><|end_of_audio|>{%- endmacro -%} +{%- macro visible_text(content) -%} + {%- if content is string -%} + {{- content -}} + {%- elif content is iterable and content is not mapping -%} + {%- for item in content -%} + {%- if item is mapping and item.type == 'text' -%} + {{- item.text -}} + {%- elif item is string -%} + {{- item -}} + {%- elif item is mapping and item.type in ['image', 'image_url'] -%} + {{- emit_image() -}} + {%- elif item is mapping and item.type in ['video', 'video_url'] -%} + {{- emit_video() -}} + {%- elif item is mapping and item.type in ['audio', 'audio_url', 'input_audio'] -%} + {{- emit_audio() -}} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{- content }} + {%- endif -%} +{%- endmacro -%} +{%- macro tool_response(text) -%} +{{- '' + text + '' -}} +{%- endmacro -%} +{%- macro render_tool_response(m) -%} +{%- if m.content is string -%} + {{- tool_response(m.content) -}} +{%- elif m.content and m.content is not mapping and m.content.0.type == "tool_reference" -%} + {{- tool_references_to_response(m.content) -}} +{%- elif is_list_of_outputs(m) -%} + {%- for tr in m.content -%} + {%- if tr.output is iterable and tr.output is not string and tr.output is not mapping and tr.output and tr.output.0.type == "tool_reference" -%} + {{- tool_references_to_response(tr.output) -}} + {%- else -%} + {{- tool_response(visible_text(tr.output)) -}} + {%- endif -%} + {%- endfor -%} +{%- else -%} + {{- tool_response(visible_text(m.content)) -}} +{%- endif -%} +{%- endmacro -%} +{%- macro id_of(obj) -%} + {%- if obj.tool_call_id -%} + {{- obj.tool_call_id -}} + {%- elif obj.id -%} + {{- obj.id -}} + {%- endif -%} +{%- endmacro -%} +{%- macro is_list_of_outputs(m) -%} + {%- if m.content and m.content.0.output is defined -%}1{%- endif -%} +{%- endmacro -%} +{%- macro has_dup_tool_result_id(lo, hi, target) -%} + {%- set ns_cnt = namespace(n=0) -%} + {%- for k in range(lo, hi + 1) -%} + {%- set m = messages[k] -%} + {%- if is_list_of_outputs(m) -%} + {%- for entry in m.content -%} + {%- if id_of(entry) == target -%} + {%- set ns_cnt.n = ns_cnt.n + 1 -%} + {%- endif -%} + {%- endfor -%} + {%- elif id_of(m) == target -%} + {%- set ns_cnt.n = ns_cnt.n + 1 -%} + {%- endif -%} + {%- if ns_cnt.n > 1 -%}{%- break -%}{%- endif -%} + {%- endfor -%} + {%- if ns_cnt.n > 1 -%}1{%- endif -%} +{%- endmacro -%} +{%- macro tc_id_exists(tcs, target) -%} + {%- set ns_f = namespace(found=false) -%} + {%- for tc in tcs -%} + {%- if id_of(tc) == target -%} + {%- set ns_f.found = true -%} + {%- break -%} + {%- endif -%} + {%- endfor -%} + {%- if ns_f.found -%}1{%- endif -%} +{%- endmacro -%} +{%- set ns = namespace(last_user_index=-1) -%} +{%- for m in messages %} + {%- if m.role == 'user' %} + {%- set ns.last_user_index = loop.index0 -%} + {%- endif %} +{%- endfor %} +{%- for m in messages -%} +{%- if m.role == 'user' -%}<|user|>{{ visible_text(m.content) }} +{%- elif m.role == 'assistant' -%} +<|assistant|> +{%- set content = visible_text(m.content) %} +{%- if m.reasoning_content is string %} + {%- set reasoning_content = m.reasoning_content %} +{%- elif '' in content %} + {%- set reasoning_content = content.split('')[0].split('')[-1] %} + {%- set content = content.split('')[-1] %} +{%- endif %} +{%- if (not clear_thinking or loop.index0 > ns.last_user_index) and reasoning_content is defined -%} +{{ '' + reasoning_content + ''}} +{%- else -%} +{{ '' }} +{%- endif -%} +{%- if content.strip() -%} +{{ content.strip() }} +{%- endif -%} +{% if m.tool_calls %} +{% for tc in m.tool_calls %} +{%- if tc.function %} + {%- set tc = tc.function %} +{%- endif %} +{{- '' + tc.name -}} +{% set _args = tc.arguments %}{% for k, v in _args.items() %}{{ k }}{{ v | tojson(ensure_ascii=False) if v is not string else v }}{% endfor %}{% endfor %} +{% endif %} +{%- elif m.role == 'tool' -%} +{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|observation|>' -}} + {%- set block_start = loop.index0 -%} + {%- set ns_blk = namespace(end=block_start) -%} + {%- for j in range(block_start, messages|length) -%} + {%- if messages[j].role == 'tool' -%} + {%- set ns_blk.end = j -%} + {%- else -%} + {%- break -%} + {%- endif -%} + {%- endfor -%} + {%- set ns_a = namespace(tool_calls=none) -%} + {%- if block_start > 0 and messages[block_start - 1].role == 'assistant' and messages[block_start - 1].tool_calls -%} + {%- set ns_a.tool_calls = messages[block_start - 1].tool_calls -%} + {%- endif -%} + {%- set ns_chk = namespace(can_sort=true) -%} + {%- if not ns_a.tool_calls -%} + {%- set ns_chk.can_sort = false -%} + {%- else -%} + {%- for k in range(block_start, ns_blk.end + 1) -%} + {%- set m = messages[k] -%} + {%- if is_list_of_outputs(m) -%} + {%- for entry in m.content -%} + {%- set eid = id_of(entry) -%} + {%- if not eid -%} + {%- set ns_chk.can_sort = false -%} + {%- elif has_dup_tool_result_id(block_start, ns_blk.end, eid) -%} + {%- set ns_chk.can_sort = false -%} + {%- elif not tc_id_exists(ns_a.tool_calls, eid) -%} + {%- set ns_chk.can_sort = false -%} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {%- set tk_id = id_of(m) -%} + {%- if not tk_id -%} + {%- set ns_chk.can_sort = false -%} + {%- elif has_dup_tool_result_id(block_start, ns_blk.end, tk_id) -%} + {%- set ns_chk.can_sort = false -%} + {%- elif not tc_id_exists(ns_a.tool_calls, tk_id) -%} + {%- set ns_chk.can_sort = false -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {%- for i in range(ns_a.tool_calls | length) -%} + {%- set tc_id = id_of(ns_a.tool_calls[i]) -%} + {%- if not tc_id -%} + {%- set ns_chk.can_sort = false -%} + {%- endif -%} + {%- for j in range(i + 1, ns_a.tool_calls | length) -%} + {%- if id_of(ns_a.tool_calls[j]) == tc_id -%} + {%- set ns_chk.can_sort = false -%} + {%- endif -%} + {%- endfor -%} + {%- endfor -%} + {%- endif -%} + {%- if ns_chk.can_sort -%} + {%- for tc in ns_a.tool_calls -%} + {%- set tc_id = id_of(tc) -%} + {%- for k in range(block_start, ns_blk.end + 1) -%} + {%- set m = messages[k] -%} + {%- if is_list_of_outputs(m) -%} + {%- for entry in m.content -%} + {%- set eid = id_of(entry) -%} + {%- if eid == tc_id -%} + {%- if entry.output is iterable and entry.output is not string and entry.output is not mapping and entry.output and entry.output.0.type == "tool_reference" -%} + {{- tool_references_to_response(entry.output) -}} + {%- else -%} + {{- tool_response(visible_text(entry.output)) -}} + {%- endif -%} + {%- endif -%} + {%- endfor -%} +{%- else -%} + {%- set tk_id = id_of(m) -%} + {%- if tk_id == tc_id -%} + {{- render_tool_response(m) -}} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {%- endfor -%} + {%- else -%} + {%- for k in range(block_start, ns_blk.end + 1) -%} + {{- render_tool_response(messages[k]) -}} + {%- endfor -%} + {%- endif -%} +{% endif -%} +{%- elif m.role == 'system' -%} +<|system|>{{ visible_text(m.content) }} +{%- endif -%} +{%- endfor -%} +{%- if add_generation_prompt -%} + <|assistant|>{{- '' -}} +{%- endif -%} diff --git a/tests/data/chat/glm53/golden/effort_low.txt b/tests/data/chat/glm53/golden/effort_low.txt new file mode 100644 index 00000000..7188283b --- /dev/null +++ b/tests/data/chat/glm53/golden/effort_low.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: Low<|user|>Hi.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/effort_the_template_refuses.txt b/tests/data/chat/glm53/golden/effort_the_template_refuses.txt new file mode 100644 index 00000000..976e5d25 --- /dev/null +++ b/tests/data/chat/glm53/golden/effort_the_template_refuses.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: High<|user|>Hi.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/history_with_reasoning.txt b/tests/data/chat/glm53/golden/history_with_reasoning.txt new file mode 100644 index 00000000..73d8b40c --- /dev/null +++ b/tests/data/chat/glm53/golden/history_with_reasoning.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: Max<|user|>First question.<|assistant|>Thinking about the first.First answer.<|user|>Second question.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/history_with_reasoning_dropped.txt b/tests/data/chat/glm53/golden/history_with_reasoning_dropped.txt new file mode 100644 index 00000000..73d8b40c --- /dev/null +++ b/tests/data/chat/glm53/golden/history_with_reasoning_dropped.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: Max<|user|>First question.<|assistant|>Thinking about the first.First answer.<|user|>Second question.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/history_with_reasoning_preserved.txt b/tests/data/chat/glm53/golden/history_with_reasoning_preserved.txt new file mode 100644 index 00000000..73d8b40c --- /dev/null +++ b/tests/data/chat/glm53/golden/history_with_reasoning_preserved.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: Max<|user|>First question.<|assistant|>Thinking about the first.First answer.<|user|>Second question.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/no_generation_prompt.txt b/tests/data/chat/glm53/golden/no_generation_prompt.txt new file mode 100644 index 00000000..f589f254 --- /dev/null +++ b/tests/data/chat/glm53/golden/no_generation_prompt.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: Max<|user|>Hi.<|assistant|>Hello. \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/parallel_calls_with_typed_arguments.txt b/tests/data/chat/glm53/golden/parallel_calls_with_typed_arguments.txt new file mode 100644 index 00000000..45fc1f36 --- /dev/null +++ b/tests/data/chat/glm53/golden/parallel_calls_with_typed_arguments.txt @@ -0,0 +1,15 @@ +[gMASK]<|system|>Reasoning Effort: Max<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}} +{"name": "edit", "description": "Apply edits — exact text, «quoted» & , 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}} +{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}} + + +For each function call, output the function name and arguments within the following XML format: +{function-name}{arg-key-1}{arg-value-1}{arg-key-2}{arg-value-2}...<|user|>Edit both files, then ping.<|assistant|>Doing all three.editpath/work/a.pyedits[{"oldText": " return a\n", "newText": " return a < b & c # it's\n"}, {"oldText": "x\ty", "newText": "\\\""}]dry_runfalsemodesafereadpath/work/über.pylimit3ping<|observation|>{"ok": true}x = 1 +pong<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/system_and_user.txt b/tests/data/chat/glm53/golden/system_and_user.txt new file mode 100644 index 00000000..c5e96b1e --- /dev/null +++ b/tests/data/chat/glm53/golden/system_and_user.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: Max<|system|>You are terse.<|user|>What is 2+2?<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/thinking_off.txt b/tests/data/chat/glm53/golden/thinking_off.txt new file mode 100644 index 00000000..5dd58436 --- /dev/null +++ b/tests/data/chat/glm53/golden/thinking_off.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: Max<|user|>Hi.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/tool_calls_preserving_reasoning.txt b/tests/data/chat/glm53/golden/tool_calls_preserving_reasoning.txt new file mode 100644 index 00000000..d424f5e0 --- /dev/null +++ b/tests/data/chat/glm53/golden/tool_calls_preserving_reasoning.txt @@ -0,0 +1,15 @@ +[gMASK]<|system|>Reasoning Effort: Max<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}} +{"name": "edit", "description": "Apply edits — exact text, «quoted» & , 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}} +{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}} + + +For each function call, output the function name and arguments within the following XML format: +{function-name}{arg-key-1}{arg-value-1}{arg-key-2}{arg-value-2}...<|user|>Fix /work/a.py.<|assistant|>Read it first.readpath/work/a.py<|observation|>print(1) +<|user|>Go on.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/tools_and_user.txt b/tests/data/chat/glm53/golden/tools_and_user.txt new file mode 100644 index 00000000..c8145d94 --- /dev/null +++ b/tests/data/chat/glm53/golden/tools_and_user.txt @@ -0,0 +1,14 @@ +[gMASK]<|system|>Reasoning Effort: Max<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}} +{"name": "edit", "description": "Apply edits — exact text, «quoted» & , 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}} +{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}} + + +For each function call, output the function name and arguments within the following XML format: +{function-name}{arg-key-1}{arg-value-1}{arg-key-2}{arg-value-2}...<|user|>Read /work/a.py.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/tools_system_and_user.txt b/tests/data/chat/glm53/golden/tools_system_and_user.txt new file mode 100644 index 00000000..8417fa62 --- /dev/null +++ b/tests/data/chat/glm53/golden/tools_system_and_user.txt @@ -0,0 +1,14 @@ +[gMASK]<|system|>Reasoning Effort: Max<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}} +{"name": "edit", "description": "Apply edits — exact text, «quoted» & , 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}} +{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}} + + +For each function call, output the function name and arguments within the following XML format: +{function-name}{arg-key-1}{arg-value-1}{arg-key-2}{arg-value-2}...<|system|>You are a coding agent.<|user|>Read /work/a.py.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/glm53/golden/unicode_text.txt b/tests/data/chat/glm53/golden/unicode_text.txt new file mode 100644 index 00000000..67d65c8b --- /dev/null +++ b/tests/data/chat/glm53/golden/unicode_text.txt @@ -0,0 +1,14 @@ +[gMASK]<|system|>Reasoning Effort: Max<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{"name": "read", "description": "Read a file.", "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Absolute path"}, "limit": {"type": "integer"}}, "required": ["path"]}} +{"name": "edit", "description": "Apply edits — exact text, «quoted» & , 日本語.", "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"oldText": {"type": "string"}, "newText": {"type": "string"}}, "required": ["oldText", "newText"]}}, "dry_run": {"type": "boolean"}, "mode": {"type": "string", "enum": ["fast", "safe"]}}, "required": ["path", "edits"]}} +{"name": "ping", "description": "Takes no arguments.", "parameters": {"type": "object", "properties": {}}} + + +For each function call, output the function name and arguments within the following XML format: +{function-name}{arg-key-1}{arg-value-1}{arg-key-2}{arg-value-2}...<|user|>Übersetze: 日本語 🙂 "quoted" \ back<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/golden/cases.json b/tests/data/chat/golden/cases.json index d75130b6..9c7aaaf1 100644 --- a/tests/data/chat/golden/cases.json +++ b/tests/data/chat/golden/cases.json @@ -4,7 +4,8 @@ "qwen3.8": { "bos": "", "eos": "<|im_end|>", "media": "<|vision_start|><|image_pad|><|vision_end|>" }, "qwen3.6": { "bos": "", "eos": "<|im_end|>", "media": "<|vision_start|><|image_pad|><|vision_end|>" }, "minicpm5": { "bos": "", "eos": "", "media": "" }, - "gemma4": { "bos": "", "eos": "", "media": "<|image|>" } + "gemma4": { "bos": "", "eos": "", "media": "<|image|>" }, + "glm53": { "bos": "", "eos": "<|endoftext|>", "media": "" } }, "tools": [ { "type": "function", "function": { "name": "read", "description": "Read a file.", @@ -58,6 +59,7 @@ { "role": "assistant", "reasoning_content": "Thinking about the first.", "content": "First answer." }, { "role": "user", "content": "Second question." } ] }, { "name": "tool_call_then_result", + "models": ["qwen3.8", "qwen3.6", "minicpm5", "gemma4"], "tools": true, "messages": [ { "role": "user", "content": "Fix /work/a.py." }, @@ -66,6 +68,7 @@ "function": { "name": "read", "arguments": "{\"path\": \"/work/a.py\", \"limit\": 40}" } } ] }, { "role": "tool", "tool_call_id": "call_1", "content": "print(1)\n" } ] }, { "name": "tool_call_answered_then_user", + "models": ["qwen3.8", "qwen3.6", "minicpm5", "gemma4"], "tools": true, "messages": [ { "role": "user", "content": "Fix /work/a.py." }, From e60810116cf95f7d968dce28b39446a4aabea8cf Mon Sep 17 00:00:00 2001 From: Nunze Date: Mon, 19 Oct 2026 14:43:02 +0200 Subject: [PATCH 041/152] chat: tagged calls whose name the opener opens -- GLM-5's NAME GLM-5 writes NAMEKV...: no prefix of the name's own and no suffix, the name ends at the first argument or at the call's close. The tagged family now takes an empty name_suffix when name_prefix opens the call (no call_open): the derivation from the template makes the per-call opener the prefix and its closer call_end, the grammar takes eps() for the suffix, and the streaming parser finds the name's end byte by byte (name_stop, name_plausible) and reads the closing tag as the first item of the body. arg_name_suffix and arg_value_prefix may both be set and are read back to back, so chat_format_markers keeps both tags. value_newlines comes from a probe render of the template rather than a constant (GLM and MiniCPM false, Qwen true). The ABI struct is unchanged; its comments say what an empty name_suffix means now. chatparse_test: GLM's template serves tools; the derived format equals the one a plugin would declare; every rendered reply in the corpus reads back as the message it rendered, split at every byte; and replies that stray from the grammar. Each fails without this change. The Gemma refusal names call_end. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- abi/rad_builder.h | 5 +- core/text/chatfmt.cpp | 60 +++++- core/text/chatfmt.h | 17 +- core/text/chatparse.cpp | 100 ++++++++- tests/chatparse_gemma4_test.cpp | 2 +- tests/chatparse_test.cpp | 345 +++++++++++++++++++++++++++++++- 6 files changed, 507 insertions(+), 22 deletions(-) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 70993b69..839904da 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1110,10 +1110,13 @@ typedef struct RadChatFormat { const char* call_open; /* around each call; "" when calls are not wrapped */ const char* call_close; const char* name_prefix; /* "" when the model has no tool calls */ + /* "" when nothing of its own ends the name: then the object's `{` does, or, for tagged + * arguments in an unwrapped call, the first arg_prefix or call_end, which begin the body */ const char* name_suffix; const char* call_end; const char* arg_prefix; - const char* arg_name_suffix; /* "" when arg_value_prefix alone ends the name */ + /* "" when arg_value_prefix alone ends the name; both set are written back to back */ + const char* arg_name_suffix; const char* arg_value_prefix; const char* arg_value_suffix; diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index df5a7b54..fb588d6f 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -7,6 +7,7 @@ * reply. */ #include "llama/common/chat.h" #include "llama/common/chat-auto-parser.h" +#include "llama/common/chat-auto-parser-helpers.h" #include "llama/common/json-schema-to-grammar.h" #include "shim/log.h" @@ -120,6 +121,29 @@ int reasoning_anywhere_check(const ChatFormat& f, std::string* why) { return RAD_OK; } +/* Does the template write an argument's value on lines of its own? Then one newline at each end + * is the tags' (ChatFormat::value_newlines). A template that writes it flush against its tags + * (`VALUE`) leaves those newlines to the value; reading them as the tags' + * would drop a written file's last line break. A render that fails counts as own lines. */ +bool value_on_own_lines(const common_chat_template& tmpl, const ChatFormat& c) { + static const char* const kValue = "RADIANCE_VALUE_PROBE"; + ojson call = { { "id", "call_0" }, { "type", "function" } }; + call["function"] = { { "name", "probe" }, { "arguments", { { "arg", kValue } } } }; + ojson reply = { { "role", "assistant" }, { "content", "" } }; + reply["tool_calls"] = ojson::array({ call }); + ojson params = { { "type", "object" } }; + params["properties"]["arg"]["type"] = "string"; + ojson tool = { { "type", "function" } }; + tool["function"] = { { "name", "probe" }, { "description", "probe" } }; + tool["function"]["parameters"] = params; + template_params tp; + tp.messages = ojson::array({ ojson{ { "role", "user" }, { "content", "hi" } }, reply }); + tp.tools = ojson::array({ tool }); + const std::string r = autoparser::apply_template(tmpl, tp); + const std::string flush = c.arg_name_suffix + c.arg_value_prefix + kValue + c.arg_value_suffix; + return r.find(flush) == std::string::npos; +} + } /* namespace */ /* ================================================================== validity */ @@ -162,9 +186,10 @@ int chat_format_check(const ChatFormat& f, std::string* why) { if (f.call_open.empty() && !f.call_close.empty()) return no("call_close without call_open"); const bool object = f.object_args(); - /* An object's own `{` may be what ends the name; anything else needs its suffix. */ - if (!object || !f.name_suffix.empty()) { - if (f.name_suffix.empty() || trim_ws(f.name_suffix).empty()) + /* Without a suffix the name ends at what follows it: the object's `{`, or a tagged call's + * first argument or close. */ + if (!f.name_suffix.empty()) { + if (trim_ws(f.name_suffix).empty()) return no("name_suffix must end the function name with something besides whitespace"); if (is_ws((unsigned char)f.name_suffix[0])) return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace"); @@ -176,9 +201,17 @@ int chat_format_check(const ChatFormat& f, std::string* why) { if (f.arg_name_suffix.empty() && f.arg_value_prefix.empty()) return no("nothing ends an argument name: arg_name_suffix and arg_value_prefix are " "empty"); - if (!f.arg_name_suffix.empty() && !f.arg_value_prefix.empty()) - return no("arg_name_suffix and arg_value_prefix are both set; the streaming parser " - "reads one delimiter between an argument's name and its value"); + if (f.name_suffix.empty()) { + /* The name runs to the first arg_prefix or call_end. A wrapped format also reads + * name_prefix alone as a call, told from prose only by its closed name tag, and + * without a suffix there is none. */ + if (!f.call_open.empty()) + return no("name_suffix is empty, which a tagged call allows only when name_prefix " + "opens it, and call_open is set"); + if (is_ws((unsigned char)f.arg_prefix[0])) + return no("arg_prefix " + show(f.arg_prefix) + " may not begin with whitespace " + "when it is what ends the function name"); + } if (f.string_value != ChatValue::Raw && f.string_value != ChatValue::Cdata) return no("string_value must be RAD_CHAT_VALUE_RAW or RAD_CHAT_VALUE_CDATA"); if ((uint32_t)f.other_value > (uint32_t)ChatValue::Json) @@ -362,9 +395,18 @@ int chat_format_from_template(const std::string& jinja, const std::string& bos, c.arg_name_suffix = t.arguments.name_suffix; c.arg_value_prefix = t.arguments.value_prefix; c.arg_value_suffix = t.arguments.value_suffix; + /* A name the per-call opener itself opens, with no tag of its own around it + * (GLM's `NAME`): the opener is the name's prefix and the + * per-call close the call's own, so the name ends at the first argument or close. */ + if (c.name_prefix.empty() && !c.call_open.empty() && c.call_end.empty()) { + c.name_prefix = c.call_open; + c.call_end = c.call_close; + c.call_open.clear(); + c.call_close.clear(); + } c.string_value = ChatValue::Cdata; c.other_value = ChatValue::Json; - c.value_newlines = true; + c.value_newlines = value_on_own_lines(tmpl, c); /* The section or per-call opener both triggers the lazy grammar and ends an * unclosed reasoning block. A format with neither gets no grammar and no break, * since its calls open with the name prefix, which a model also writes in prose. */ @@ -853,7 +895,9 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat if (!req_arms.empty()) args = seq({ any_arg, rep(seq({ space(), any_arg }), 0, -1) }); else if (!opt_arms.empty()) args = seq({ eps(), rep(seq({ space(), any_arg }), 0, -1) }); - G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), lit(f.name_suffix) })); + /* Without a suffix the name ends where its arguments or close begin. */ + G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), + f.name_suffix.empty() ? eps() : lit(f.name_suffix) })); G func = seq({ open, eps(), space(), args, space(), wrap(lit(f.call_end)) }); b.add_rule(rule_name("tool-" + name), render(func)); choices.push_back(rule_ref(rule_name("tool-" + name))); diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h index 43903b35..c2b72444 100644 --- a/core/text/chatfmt.h +++ b/core/text/chatfmt.h @@ -22,12 +22,16 @@ * Qwen3.6 / Qwen3.8 \n\n\nVALUE\n\n * \n * MiniCPM5 VALUE + * GLM-5 NAMEARGVALUE + * * * A call's name sits between a prefix and a suffix and the call ends with its own close; each * argument is a name between a prefix and a suffix, then a value ending at its own suffix; calls - * may be wrapped one by one. Arguments are typed by the tool's JSON schema: a string-typed one is - * raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as - * JSON is taken raw, since models often write Python literals into a tag. + * may be wrapped one by one. A name may also have no suffix of its own (GLM): it then ends where + * the first argument or the call's close begins, and that tag is read as what it is. Arguments + * are typed by the tool's JSON schema: a string-typed one is raw text (optionally CDATA-wrapped), + * any other type is JSON, and text that does not parse as JSON is taken raw, since models often + * write Python literals into a tag. * * Object family (ChatArgs::Object): a call is its name and one object holding the arguments. * @@ -107,8 +111,9 @@ struct ChatFormat { /* Around each call: "\n", "". When set, a call written without it * (name_prefix alone) is still read as a call (chatparse.h). */ std::string call_open, call_close; - /* "\n". In the object family name_suffix may be empty; the name then ends at - * the object's `{`. */ + /* "\n". name_suffix may be empty: in the object family the name then ends at + * the object's `{`; in the tagged family, where name_prefix must open the call (no + * call_open), at the first arg_prefix or call_end, which stay part of the call's body. */ std::string name_prefix, name_suffix; std::string call_end; /* "\n"; may be empty for an object */ @@ -120,6 +125,8 @@ struct ChatFormat { bool object_bare_keys = false; std::string arg_prefix; /* "", ""): + * they are then read as one delimiter, written back to back. */ std::string arg_name_suffix; /* ">\n" (MiniCPM: empty, the value prefix ends it) */ std::string arg_value_prefix; /* "" (MiniCPM: "\">") */ std::string arg_value_suffix; /* "\n" */ diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index d65c1c1d..5222a659 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -726,7 +726,8 @@ struct ReplyFormat::Impl { * second, since models often write a call without its wrapper; a wrapper written without * its trailing whitespace is read too. */ std::vector openers; - std::string name_end; /* what ends an argument name */ + /* What ends an argument name: arg_name_suffix and arg_value_prefix, back to back. */ + std::string name_end; /* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so it was * written unconstrained; its argument tags, like its name and close, are read with their * surrounding whitespace optional. */ @@ -740,6 +741,9 @@ struct ReplyFormat::Impl { /* Object family. `object`: a call's arguments are one object. `ns_object`: the object's own * `{` ends the name (name_suffix empty), and ns_core is "{". */ bool object = false, ns_object = false; + /* Tagged family, name_suffix empty: a call's name ends where arg_prefix or end_core begins, + * and that tag is the first of the call's body. */ + bool name_open = false; /* Where a key or value may begin, besides the object's punctuation: the dialect string's * opener, and the call's close and end (written there by a reply that leaves its object * unclosed). Matched anchored, by first byte; chat_format_check keeps them distinct. */ @@ -788,8 +792,9 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr split_ws(f.call_open, &m.co_core, &m.co_trail); if (f.call_open.empty()) m.openers = { f.name_prefix }; else m.openers = { m.co_core, f.name_prefix }; - m.name_end = f.arg_name_suffix.empty() ? f.arg_value_prefix : f.arg_name_suffix; + m.name_end = f.arg_name_suffix + f.arg_value_prefix; m.object = f.has_tools() && f.object_args(); + m.name_open = f.has_tools() && !m.object && f.name_suffix.empty(); if (m.object && f.name_suffix.empty()) { m.ns_object = true; m.ns_core = "{"; @@ -976,7 +981,15 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse t.params.emplace(pname, p); } t.arms.insert(t.arms.end(), optional.begin(), optional.end()); - if (t.name.find(F.ns_core) != std::string::npos || + if (F.name_open) { + for (const std::string* d : { &F.f.arg_prefix, &F.end_core }) + if ((t.name + *d).find(*d) != t.name.size()) { + *why = "tool '" + t.name + "' has a name running into '" + *d + + "', which this model's tool-call format uses to end a function " + "name"; + return RAD_E_INVAL; + } + } else if (t.name.find(F.ns_core) != std::string::npos || (!F.ns_object && (t.name + F.f.name_suffix).find(F.f.name_suffix) != t.name.size())) { *why = "tool '" + t.name + "' has a name containing '" + F.ns_core + @@ -1053,7 +1066,8 @@ enum class St : uint8_t { OpenCoTail, /* the whitespace that ends call_open, after its core */ OpenWs, /* after call_open: whitespace */ OpenPrefix, /* name_prefix, after call_open */ - OpenName, /* the function name, to the core of name_suffix */ + OpenName, /* the function name, to the core of name_suffix (or, without one, to the + first argument or the call's end) */ OpenTail, /* the whitespace that ends name_suffix */ OpenPeek, /* a loose call's name is read: whitespace, then an argument or the close */ OpenPeekArg, /* ... and the first argument's name, which must close as a name */ @@ -1330,6 +1344,75 @@ struct ReplyStream::Impl { return false; } + /* A suffixless name (ReplyFormat::Impl::name_open) ends where arg_prefix or end_core begins. + * Returns which one ended it (0, 1), with *len the name's length before it; or -1, with *len + * the bytes that are the name's for certain, the rest possibly beginning either. */ + int name_stop(size_t* len) const { + const std::string* const stops[] = { &F.f.arg_prefix, &F.end_core }; + size_t pend = 0; + for (int i = 0; i < 2; ++i) { + const std::string& t = *stops[i]; + if (name.size() >= t.size() && name.compare(name.size() - t.size(), t.size(), t) == 0) { + *len = name.size() - t.size(); + return i; + } + for (size_t k = std::min(t.size() - 1, name.size()); k > pend; --k) + if (name.compare(name.size() - k, k, t, 0, k) == 0) { pend = k; break; } + } + *len = name.size() - pend; + return -1; + } + + /* Could these bytes, after any leading whitespace, still be a function name? One holds no + * '<' and no whitespace before more text, unless a declared name does. Without a tag of its + * own to close it, a name read from prose that mentions the opener would otherwise be held + * up to kMaxLooseName bytes. */ + bool name_plausible(std::string_view n) const { + size_t i = 0; + while (i < n.size() && is_ws((unsigned char)n[i])) ++i; + bool gap = false; + for (; i < n.size(); ++i) { + const unsigned char c = (unsigned char)n[i]; + if (c == '<') return declared_prefix(n); + if (is_ws(c)) gap = true; + else if (gap) return declared_prefix(n); + } + return true; + } + + /* OpenName for a suffixless name. The tag that ends it is read here, as the first of the + * call's body: an argument's opener, or the call's end. Whitespace around the name is + * dropped; before it, the grammar does not admit it. */ + const char* open_name_byte(const char* p) { + size_t len = 0; + const int stop = name_stop(&len); + if (stop < 0) { + if (len > kMaxLooseName || !name_plausible(std::string_view(name).substr(0, len))) + fail_attempt(); + return p + 1; + } + size_t a = 0; + while (a < len && is_ws((unsigned char)name[a])) ++a; + const std::string nm(trim_trailing_ws(std::string_view(name).substr(a, len - a))); + auto it = P.by_name.find(nm); + tool = it == P.by_name.end() ? -1 : (int)it->second; + if (tool < 0 && (nm.empty() || nm.find('<') != std::string::npos)) { + fail_attempt(); + return p + 1; + } + name = nm; + begin_call(a == 0); + lpos = 0; + lhold.clear(); + if (stop == 0) { + start_arg(); + } else { + finish_call_strictness(); + end_core_done(); + } + return p + 1; + } + /* The call opener has matched at `att`; whether a call follows is decided below. */ void begin_attempt(St from) { origin = from; @@ -1966,6 +2049,7 @@ struct ReplyStream::Impl { const char c = *p; att.push_back(c); name.push_back(c); + if (F.name_open) return open_name_byte(p); const size_t k = F.ns_core.size(); if (name.size() >= k && name.compare(name.size() - k, k, F.ns_core) == 0) { const std::string nm = name.substr(0, name.size() - k); @@ -2640,8 +2724,12 @@ struct ReplyStream::Impl { case St::OpenWs: case St::OpenPrefix: return true; - case St::OpenName: - return declared_prefix(name); + case St::OpenName: { + if (!F.name_open) return declared_prefix(name); + size_t len = 0; + name_stop(&len); + return declared_prefix(std::string_view(name).substr(0, len)); + } case St::OpenTail: return tool >= 0; default: diff --git a/tests/chatparse_gemma4_test.cpp b/tests/chatparse_gemma4_test.cpp index f2cdd0cb..6cf152e3 100644 --- a/tests/chatparse_gemma4_test.cpp +++ b/tests/chatparse_gemma4_test.cpp @@ -196,7 +196,7 @@ TEST(an_older_struct_reads_the_object_fields_as_zero) { CHECK(!f.object_bare_keys); CHECK(!f.reasoning_anywhere); CHECK(chat_format_check(f, &why) == RAD_E_UNSUPPORTED); - CHECK(why.find("name_suffix") != std::string::npos); + CHECK(why.find("call_end") != std::string::npos); } TEST(an_object_format_the_parser_cannot_read_is_refused_by_name) { diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index f9b821fd..53747dbe 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -995,6 +995,8 @@ TEST(the_derived_formats_are_the_ones_in_service) { CHECK(refused.empty()); CHECK_EQ(f.reasoning_open, std::string("\n")); CHECK_EQ(f.reasoning_close, std::string("\n\n\n")); + /* Qwen writes a value on lines of its own, MiniCPM flush against its tags. */ + CHECK_EQ(f.value_newlines, is_qwen(m)); if (is_qwen(m)) { CHECK_EQ(f.call_open, std::string("\n")); CHECK_EQ(f.call_close, std::string("")); @@ -1260,7 +1262,9 @@ TEST(a_format_the_parser_cannot_read_is_refused_by_name) { CHECK(refused([](RadChatFormat& c) { c.name_suffix = ""; }, "name_suffix")); CHECK(refused([](RadChatFormat& c) { c.call_end = ""; }, "call_end")); CHECK(refused([](RadChatFormat& c) { c.arg_value_suffix = ""; }, "arg_value_suffix")); - CHECK(refused([](RadChatFormat& c) { c.arg_value_prefix = "\""; }, "both set")); + CHECK(refused([](RadChatFormat& c) { + c.call_open = ""; c.call_close = ""; c.name_suffix = ""; c.arg_prefix = "\n" }; @@ -1442,6 +1446,48 @@ TEST(the_chat_bridge_derives_the_whole_request_from_one_format) { CHECK(why.find("a>b") != std::string::npos); } +/* GLM-5.3-Flash's template reads list items as `m.content.0.type`, jinja2's dotted index, and + * writes calls as `NAMEKV`. The + * capability probe renders with tools and tool calls, so a runtime that throws on the dotted index + * reports no tool support; and a name the opener opens, with no tag of its own, must be a format + * the derivation describes, or every request with tools is refused. */ +TEST(glm53_serves_tools_from_its_template) { + std::shared_ptr v = vocab_with(fixture("glm53")); + REQUIRE(v != nullptr); + server::ChatTemplateBridge br; + CHECK_OK(br.init(*v)); + CHECK(br.supports_tools()); + CHECK_EQ(br.tool_refusal(), std::string()); + const server::ChatRender r = bridge_render(br, agent_tools()); + REQUIRE(!r.prompt.empty()); + CHECK(r.prompt.find("") != std::string::npos); + for (const auto& t : agent_tools()) + CHECK(r.prompt.find("\"name\": \"" + t["function"]["name"].get() + "\"") != + std::string::npos); + CHECK(!r.grammar.empty()); + CHECK(r.grammar_lazy); + REQUIRE(r.grammar_triggers.size() == 1); + CHECK_EQ(r.grammar_triggers[0].type, 1); + CHECK_EQ(r.grammar_triggers[0].value, std::string("")); + /* Each tag is a marker of its own: one the decoder suppresses as a control token is + * structure the parser never sees. */ + for (const char* t : { "", "", "", "", "", + "", "", "" }) + CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), t) != + r.preserved_tokens.end()); + REQUIRE(r.parser != nullptr); + std::unique_ptr rd = r.parser->open(); + rd->feed("Look.\nreadpath/a" + "limit3", nullptr); + rd->finish(nullptr); + const server::ParsedMessage pm = rd->message(); + CHECK_EQ(pm.reasoning, std::string("Look.")); + CHECK_EQ(pm.content, std::string()); + REQUIRE(pm.tool_calls.size() == 1); + CHECK_EQ(pm.tool_calls[0].name, std::string("read")); + CHECK_EQ(pm.tool_calls[0].arguments, std::string("{\"path\":\"/a\",\"limit\":3}")); +} + /* A template writing each call as a JSON object is not a describable format: the model still * chats with reasoning split, and a request with tools is refused with the reason. */ TEST(a_template_whose_calls_cannot_be_described_refuses_tools_and_still_chats) { @@ -1654,6 +1700,302 @@ TEST(an_object_format_the_parser_cannot_read_is_refused) { "name_prefix is empty")); } +/* ================================================================== a name the opener opens + * + * GLM-5 writes a call as `NAMEKV... + * `: the per-call opener opens the name, nothing of its own closes it, and it ends at + * the first argument or the call's close. Values are flush against their tags, strings raw and + * anything else JSON. The legacy path reads the opener as a wrapper around a call with an empty + * name tag, which is a different format, so these replies are checked against the messages they + * were rendered from rather than against the old parser. */ + +static const char* const kGlmOpener[] = { "" }; + +static RadChatFormat glm_abi() { + RadChatFormat c; + std::memset(&c, 0, sizeof c); + c.struct_size = sizeof c; + c.name = "glm-declared"; + c.reasoning_open = ""; + c.reasoning_close = ""; + c.reasoning_breaks = kGlmOpener; + c.n_reasoning_breaks = 1; + c.name_prefix = ""; + c.name_suffix = ""; + c.call_end = ""; + c.arg_prefix = ""; + c.arg_name_suffix = ""; + c.arg_value_prefix = ""; + c.arg_value_suffix = ""; + c.string_value = RAD_CHAT_VALUE_CDATA; + c.other_value = RAD_CHAT_VALUE_JSON; + c.value_newlines = 0; + c.triggers = kGlmOpener; + c.n_triggers = 1; + return c; +} + +/* The agent's tools and one that takes no arguments. */ +static const json& glm_tools() { + static const json t = [] { + json v = agent_tools(); + v.push_back(json::parse(R"({"type":"function","function":{"name":"now", + "description":"The time.","parameters":{"type":"object","properties":{}}}})")); + return v; + }(); + return t; +} + +/* GLM's template, the format derived from it, and the request every reply here answers. */ +struct Glm { + ChatTemplate tmpl; + ChatFormat f; + ChatPrompt head; + std::shared_ptr parser; + std::string grammar; +}; + +static const Glm* glm() { + static std::unique_ptr g = []() -> std::unique_ptr { + auto g = std::make_unique(); + std::string why, refused; + const std::string src = fixture("glm53"); + if (g->tmpl.load(src, "", "<|user|>") < 0) return nullptr; + if (chat_format_from_template(src, "", "<|user|>", &g->f, &refused, &why) < 0 || + !refused.empty()) + return nullptr; + ChatOptions opt; + opt.parallel_tool_calls = true; + const json user = json::array({ { { "role", "user" }, { "content", "Fix the failing test in /work." } } }); + if (g->tmpl.apply(user, glm_tools(), opt, &g->head) < 0) return nullptr; + ReplyOptions ro; + ro.generation_prompt = g->head.generation_prompt; + ro.tools = &glm_tools(); + ro.terminators = { "<|user|>", "<|observation|>", "<|endoftext|>" }; + g->parser = parser_of(g->f, ro); + ChatGrammarRequest gq; + gq.tools = &glm_tools(); + gq.generation_prompt = g->head.generation_prompt; + ChatGrammar gr; + if (chat_format_grammar(g->f, gq, &gr, &why) < 0) return nullptr; + g->grammar = gr.text; + return g->parser ? std::move(g) : nullptr; + }(); + return g.get(); +} + +/* The assistant turn as GLM's template writes it after the generation prompt. */ +static std::string glm_reply(const Glm& g, const json& assistant) { + json msgs = json::array({ { { "role", "user" }, { "content", "Fix the failing test in /work." } } }); + msgs.push_back(assistant); + ChatOptions opt; + opt.add_generation_prompt = false; + opt.parallel_tool_calls = true; + ChatPrompt whole; + if (g.tmpl.apply(msgs, glm_tools(), opt, &whole) < 0) return ""; + const std::string& head = g.head.prompt; + if (whole.prompt.compare(0, head.size(), head) != 0) return ""; + std::string r = whole.prompt.substr(head.size()); + while (!r.empty() && r.back() == '\n') r.pop_back(); + return r; +} + +static bool no_markup(const std::string& s) { + for (const char* t : { "", "", "", "", "", + "", "", "" }) + if (s.find(t) != std::string::npos) return false; + return true; +} + +TEST(glm53_derives_a_name_the_opener_opens) { + const Glm* g = glm(); + REQUIRE(g != nullptr); + const ChatFormat& f = g->f; + CHECK_EQ(f.reasoning_open, std::string("")); + CHECK_EQ(f.reasoning_close, std::string("")); + CHECK(f.call_open.empty() && f.call_close.empty()); + CHECK_EQ(f.name_prefix, std::string("")); + CHECK(f.name_suffix.empty()); + CHECK_EQ(f.call_end, std::string("")); + CHECK_EQ(f.arg_prefix, std::string("")); + CHECK_EQ(f.arg_name_suffix, std::string("")); + CHECK_EQ(f.arg_value_prefix, std::string("")); + CHECK_EQ(f.arg_value_suffix, std::string("")); + /* The template writes a value flush against its tags, so its newlines are its own. */ + CHECK(!f.value_newlines); + CHECK(f.triggers == std::vector{ "" }); + CHECK(f.reasoning_breaks == std::vector{ "" }); + CHECK(g->head.generation_prompt.find("") != std::string::npos); + CHECK(g->parser->reasoning().starts_open); + + /* A plugin declares the same format through the ABI, unchanged, and gets the same grammar. */ + RadChatFormat c = glm_abi(); + ChatFormat declared; + std::string why; + CHECK_OK(chat_format_from_abi(&c, &declared, &why)); + CHECK_OK(chat_format_check(declared, &why)); + ChatFormat derived = f; + derived.name = declared.name; + CHECK_EQ(chat_format_describe(derived), chat_format_describe(declared)); + CHECK(chat_format_markers(derived) == chat_format_markers(declared)); + ChatGrammarRequest gq; + gq.tools = &glm_tools(); + gq.generation_prompt = g->head.generation_prompt; + ChatGrammar gr; + CHECK_OK(chat_format_grammar(declared, gq, &gr, &why)); + CHECK_EQ(gr.text, g->grammar); + CHECK(gr.lazy); + CHECK(gr.trigger_words == std::vector{ "" }); + + /* Wrapped, a suffixless name would make the bare name_prefix in prose a call. */ + c.call_open = ""; + c.call_close = ""; + static const char* const wrap[] = { "" }; + c.reasoning_breaks = wrap; + CHECK_OK(chat_format_from_abi(&c, &declared, &why)); + CHECK(chat_format_check(declared, &why) < 0); + CHECK(why.find("name_suffix") != std::string::npos); +} + +TEST(glm53_replies_read_back_as_the_messages_they_render) { + const Glm* g = glm(); + REQUIRE(g != nullptr); + const ReplyParser& p = *g->parser; + struct Case { const char* what; json msg; }; + const std::vector cases = { + { "one call, string and integer", + message("Look.", "", { call("read", { { "path", "/a" }, { "limit", 3 } }) }) }, + { "two calls", + message("Two.", "", { call("bash", { { "command", "ls -la" }, { "timeout", 30 } }), + call("read", { { "path", "/b" } }) }) }, + { "a call with no arguments", message("", "", { call("now", json::object()) }) }, + { "content, then a call", + message("Plan.", "I will read it.", { call("read", { { "path", "/c" } }) }) }, + { "values holding tags and newlines", + message("", "", { call("write", { { "path", "/x.html" }, + { "content", "\n

a & b

\nk " + "f\nend\n" } }) }) }, + { "a structured value", + message("", "", { call("edit", { { "path", "/d" }, + { "edits", json::parse(R"([{"oldText":"a","newText":"b"}])") } }) }) }, + }; + for (const Case& k : cases) { + const std::string reply = glm_reply(*g, k.msg); + REQUIRE(!reply.empty()); + bool strict = false; + const ReplyMessage m = reply_parse(p, reply, &strict); + const std::string where = std::string(k.what) + ": " + quote(reply) + "\n " + show(m); + if (!strict) ::radtest::fail(__FILE__, __LINE__, "left the grammar: " + where); + CHECK_EQ(m.reasoning, k.msg.value("reasoning_content", std::string())); + CHECK_EQ(m.content, k.msg["content"].get()); + CHECK(no_markup(m.content)); + const json& calls = k.msg["tool_calls"]; + if (m.calls.size() != calls.size()) { + ::radtest::fail(__FILE__, __LINE__, "call count: " + where); + continue; + } + for (size_t i = 0; i < calls.size(); ++i) { + const json& fn = calls[i]["function"]; + CHECK_EQ(m.calls[i].name, fn["name"].get()); + CHECK(m.calls[i].closed); + /* The arguments as written, in the reply's order; JSON values keep their spacing. */ + CHECK(json::parse(m.calls[i].arguments) == json::parse(fn["arguments"].get())); + } + const std::string s = stream_all(p, reply); + if (!s.empty()) ::radtest::fail(__FILE__, __LINE__, std::string(k.what) + ": " + s); + /* What constrained decoding admits from the trigger on is the reply's call text. */ + const size_t at = reply.find(""); + REQUIRE(at != std::string::npos); + CHECK_EQ(object_admits(g->grammar, reply.substr(at)), 1); + } + CHECK_EQ(reply_parse(p, glm_reply(*g, cases[0].msg)).calls[0].arguments, + std::string("{\"path\":\"/a\",\"limit\":3}")); + + /* Every message the other formats are checked with, too. */ + size_t n = 0; + for (const json& msg : rendered_corpus()) { + const std::string reply = glm_reply(*g, msg); + if (reply.empty()) continue; + const ReplyMessage m = reply_parse(p, reply); + const size_t want = msg.contains("tool_calls") ? msg["tool_calls"].size() : 0; + bool ok = m.calls.size() == want && no_markup(m.content); + for (size_t i = 0; ok && i < want; ++i) { + const json& fn = msg["tool_calls"][i]["function"]; + ok = m.calls[i].name == fn["name"].get() && + round_trips(json::parse(fn["arguments"].get()), + json::parse(m.calls[i].arguments), true); + } + if (!ok) ::radtest::fail(__FILE__, __LINE__, "rendered: " + quote(reply) + "\n " + show(m)); + const std::string s = stream_all(p, reply, 512); + if (!s.empty()) ::radtest::fail(__FILE__, __LINE__, "rendered: " + s + "\n " + quote(reply)); + ++n; + } + CHECK(n > 10); +} + +/* Without a tag of its own the name is read until something shows it is no name, so an opener + * in prose, a stray name and a reply cut off anywhere must all stay readable. */ +TEST(glm53_reads_what_strays_from_its_grammar) { + const Glm* g = glm(); + REQUIRE(g != nullptr); + const ReplyParser& p = *g->parser; + bool strict = true; + + ReplyMessage m = reply_parse(p, "
Wrap a call in tags, then stop.", &strict); + CHECK(m.calls.empty()); + CHECK_EQ(m.content, std::string("Wrap a call in tags, then stop.")); + + /* GLM-4.5 put newlines around its tags. */ + m = reply_parse(p, "
read\npath/a\n" + "", &strict); + CHECK(strict); + REQUIRE(m.calls.size() == 1); + CHECK_EQ(m.calls[0].name, std::string("read")); + CHECK_EQ(m.calls[0].arguments, std::string("{\"path\":\"/a\"}")); + + m = reply_parse(p, "
\nreadpath/a" + "", &strict); + CHECK(!strict); + REQUIRE(m.calls.size() == 1); + CHECK_EQ(m.calls[0].name, std::string("read")); + + m = reply_parse(p, "
nopea1" + "", &strict); + CHECK(!strict); + REQUIRE(m.calls.size() == 1); + CHECK_EQ(m.calls[0].name, std::string("nope")); + CHECK_EQ(m.calls[0].arguments, std::string("{\"a\":\"1\"}")); + + /* An unclosed reasoning block ends where a call begins. */ + m = reply_parse(p, "thinkingnow", &strict); + CHECK_EQ(m.reasoning, std::string("thinking")); + REQUIRE(m.calls.size() == 1); + CHECK_EQ(m.calls[0].name, std::string("now")); + + /* Cut off anywhere, the reply holds no markup in its content and names no other call. */ + const std::string reply = glm_reply(*g, message("Look.", "Reading.", + { call("read", { { "path", "/a" }, { "limit", 3 } }), call("now", json::object()) })); + for (size_t k = 0; k <= reply.size(); ++k) { + const ReplyMessage t = reply_parse(p, reply.substr(0, k)); + if (!no_markup(t.content) || t.calls.size() > 2 || + (!t.calls.empty() && t.calls[0].name != "read") || + (t.calls.size() == 2 && t.calls[1].name != "now")) + ::radtest::fail(__FILE__, __LINE__, "cut at " + std::to_string(k) + ": " + + quote(reply.substr(0, k)) + "\n " + show(t)); + } + + /* A tool whose name runs into a tag that ends names is refused at admission, by name. */ + const json bad = json::parse(R"([{"type":"function","function":{"name":"ab"}}])"); + ReplyOptions ro; + ro.tools = &bad; + std::shared_ptr rf; + std::shared_ptr rp; + std::string why; + CHECK_OK(ReplyFormat::compile(g->f, &rf, &why)); + CHECK(ReplyParser::create(rf, ro, &rp, &why) < 0); + CHECK(why.find("ab") != std::string::npos); +} + /* ================================================================== cost * * The legacy path re-parses the whole reply per chunk, O(n^2). The parser's own count of what it @@ -1802,3 +2144,4 @@ TEST(a_long_reply_holds_a_constant_number_of_bytes) { } RAD_TEST_MAIN() + From 51e602099829c354d4e9ba93592cdd3a4a107af7 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 16:15:30 +0000 Subject: [PATCH 042/152] dashboard: give the sparklines back their amplitude Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI (cherry picked from commit d1dd050d5165536885840fb485f7041706938f8c) --- core/server/dashboard.cpp | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 4c4e24b2..4a64fff5 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1354,16 +1354,41 @@ for (const k of METRICS) { } /* The axis follows the WINDOW's own minimum and maximum, not zero. This is a sparkline: what it * is for is the variation, and the number above it already states the level -- scaled from zero - * every steady state is a flat line on the floor. No variation draws down the middle. */ + * every steady state is a flat line on the floor. No variation draws down the middle. + * + * THE ENDS OF THAT RANGE ARE PERCENTILES, not the extremes. On a min/max axis one rare spike + * owns the whole box and the typical variation is squeezed into a couple of pixels: measured over + * real /stats samples, prefill sits at zero on a third of polls and spikes past 4,000 on the rest, + * which leaves its middle band 0.1px of the 15px available -- a flat line for a metric that is + * anything but. Taking the 5th and 95th percentiles and clamping to them gives the ordinary + * movement the height it was being denied (the same samples' middle band rises 1.2x to 3.9x + * depending on the metric). The cost is stated rather than hidden: a spike beyond the 95th now + * draws pinned to the top of the box instead of towering over the line, so the box shows how the + * metric has been behaving and not how bad its worst poll was. The number above still carries the + * level, and the detail line still carries the extremes. + * + * THE INSET IS ONE UNIT, not two and three. The stroke is 1.25 units wide, so a half-unit of + * clearance keeps it off the edge of the box; the extra it used to leave was a fifth of the + * height spent on nothing, and on a 17px box that is the difference between a line that moves + * and one that merely shifts. */ function spark(key, vals) { const s = M[key], w = 200, h = 22; if (vals.length < 3) { s.line.setAttribute("d", ""); return; } - const hi = Math.max(...vals), lo = Math.min(...vals), span = hi - lo; + const q = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.floor(p * (sorted.length - 1)))]; + const sorted = [...vals].sort((a, b) => a - b); + let lo = q(sorted, 0.05), hi = q(sorted, 0.95); + /* WHEN THE PERCENTILES COLLAPSE, fall back to the extremes. If nine tenths of the window holds + * one value, the 5th and 95th land on it and carry nothing -- and a metric that is constant + * apart from rare spikes has those spikes as its ONLY news, so pinning them outside the axis + * would draw a flat line where the old axis at least showed them. */ + if (!(hi > lo)) { lo = sorted[0]; hi = sorted[sorted.length - 1]; } + const span = hi - lo; const dx = w / (vals.length - 1); let d = ""; for (let i = 0; i < vals.length; i++) { - const t = span > Math.abs(hi) * 1e-3 ? (vals[i] - lo) / span : 0.5; - d += (i ? "L" : "M") + (i * dx).toFixed(1) + "," + (h - 2 - (h - 5) * t).toFixed(1); + let t = span > Math.abs(hi) * 1e-3 ? (vals[i] - lo) / span : 0.5; + if (t < 0) t = 0; else if (t > 1) t = 1; + d += (i ? "L" : "M") + (i * dx).toFixed(1) + "," + (h - 1 - (h - 2) * t).toFixed(1); } s.line.setAttribute("d", d); } From ed2da8c9dacae4576dcc36b8f70d4830a9622cda Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 16:37:42 +0000 Subject: [PATCH 043/152] sched: record the fastest single-sequence decode step, for the dashboard to read The dashboard's restart advice needs a reference the degraded engine is read against. Asking a human to type a ruler is fragile (a stale or mistyped number silently mis-advises) and cannot see steps taken while the dashboard tab is closed. The engine sees every step and knows the concurrency of the exact step it just timed (plan_.n_seq_decode), so it can keep the reference itself. Records two figures over single-sequence decode steps: the floor (the fastest window mean this process has measured) and the current (the most recent window mean). Both are window means of one stream at one size, so the advisory compares like with like. A min, not a max: drift only raises the CURRENT step, so the reference a degraded engine is read against is its own demonstrated floor. Single-sequence on purpose -- a decode step at eight sequences is a different measurement, so keying the floor to one row keeps a batch arriving from being misread as drift. A mixed step is excluded by the phase gate even when it carries one decode row: that row shared the step with a prefill chunk an order of magnitude dearer. Why not a raw min over step brackets: step timing is host-side, and with pipelining on the next forward pass is issued behind the current step's commit. Behind a step with long host work -- a prefill chunk, or a decode step that saves a KV checkpoint -- the decode pass is finished before its own bracket opens, so the bracket holds readback and commit and no GPU work. It is a real step advancing a real token, so no token-count or predecessor-phase guard catches it. A raw min latches that degenerate on the first occurrence and never recovers: measured live 2026-10-18 on a TP2 R9700 lane, 1.16 ms against a 15.55 ms mean on the first request after bringup. Why averaging alone is not enough: these degenerate brackets are not rare. At the observed ~1.4% rate a min over hundreds of windows reliably lands on a degenerate-heavy window, and the floor sits ~10% below the true floor -- still phantom drift, because the engine can never reach a floor that was an artifact. So a candidate is rejected BEFORE it enters a window when it is under half the running mean of accepted steps: degenerate brackets sit at ~9% of a real step and real single-sequence steps at ~96%, so the populations are ~10x apart and any threshold between them separates them -- 0.5 is the midpoint of that gap, not a value tuned to one distribution. Filtering at the step level is essential; at this rate a degenerate dilutes inside a 32-step window to ~0.91x, which no window-level threshold would catch. The first window is recorded by neither figure. The rejection gate needs a window's worth of accepted samples before it can judge one, so the first window is un-gated by construction; recording it lets the floor latch an unreachable value forever (measured: a 5% degenerate rate put the floor ~2% low through bootstrap alone). The cost is one window -- about a second of single-stream decode -- against a 46 s bringup and a 10 s repaint, so it is never observed. The estimator is a small struct (rad::DecodeFloor) so it is testable on a synthetic stream: the scheduler fixture runs steps in microseconds and cannot manufacture a degenerate bracket, which is why the first round of tests missed this. The tests feed streams laced with degenerate-short samples, assert a raw min latches them, assert the estimator rejects them and tracks the true floor, and assert the rejection does not eat real steps. Emitted on /stats as step_ns_decode_best and step_ns_decode_recent (0 until the first gated window completes). Trailing zero-defaulted fields on both SchedMetrics structs plus the adapter copy -- neither struct is ABI-pinned (scheduler<->server internal), so this is the sanctioned append. Matches the kv_tokens_max running-extremum precedent. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI (cherry picked from commit bf5a803deaa08ae0c2d94e2c3dda0d518c08d9aa) --- core/sched/metrics.h | 96 ++++++++++++ core/sched/scheduler.cpp | 16 +- core/sched/scheduler.h | 4 + core/server/adapters.h | 2 + core/server/dashboard.cpp | 2 + core/server/iface.h | 6 + tests/sched_test.cpp | 306 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 431 insertions(+), 1 deletion(-) diff --git a/core/sched/metrics.h b/core/sched/metrics.h index 81dfeff8..ce0218ed 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -51,6 +51,21 @@ struct SchedMetrics { int64_t step_ns = 0; int64_t step_ns_decode = 0; + /* The single-sequence decode floor, nanoseconds; 0 until a window of eligible steps fills. + * A min over WINDOW MEANS of single-sequence decode steps (see DecodeFloor), not over raw + * brackets -- a raw min latches a degenerate bracket forever. Single-sequence on purpose: a + * decode step at eight sequences is a different measurement, so keying the floor to one row + * keeps a batch arriving from being misread as drift. Scheduler::step_finished feeds DecodeFloor. */ + int64_t step_ns_decode_best = 0; + + /* The most recent completed window mean of single-sequence decode steps, nanoseconds; 0 until + * the first gated window completes. The advisory's OTHER side: best() is how fast the engine + * has ever been, recent() is how fast it is now, and both are window means of the same stream + * at the same size -- so they cannot disagree by order statistics the way the engine's floor + * disagreed with the browser's per-poll min (7.7% phantom drift on a flat lane, 2026-10-18). + * Scheduler::step_finished records it. */ + int64_t step_ns_decode_recent = 0; + /* Per KV group. `name` points into the Program, which outlives any scrape. */ int n_kv_groups = 0; struct Group { @@ -131,4 +146,85 @@ struct SchedMetrics { int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {}; }; + +/* Estimator for the single-sequence decode floor (SchedMetrics::step_ns_decode_best). + * + * A min over RAW step brackets is unbounded below: a decode step issued ahead behind a step with + * long host work (a prefill chunk, or a decode step that saves a KV checkpoint) has its forward + * pass finished before its own bracket opens, so the bracket holds only readback and commit -- + * about a millisecond, no GPU work. A min latches that degenerate on the first occurrence and + * never recovers. Measured live 2026-10-18: floor 1.34 ms against a 15.70 ms mean, after which + * the dashboard's restart advice read "heavily drifted, pays back fast" on a healthy engine -- + * a systematically wrong advisory, worse than none, because it recommends a restart that cannot + * help. + * + * The fix mirrors the construction the dashboard already proves clean on this lane: a min over + * WINDOW MEANS, not over raw samples. Each full window of single-sequence decode steps + * contributes one mean; a degenerate is diluted by the honest steps sharing its window, so the + * floor tracks the real floor. Two biases on that floor partially cancel: a window MEAN sits + * above the true floor (it averages, so it cannot reach a lone fast step), while min-over-windows + * picks the window with the most degenerates and pulls back down. A simulation of the live lane + * (real ~15.9 ms, true floor ~14.4 ms, degenerate ~1.34 ms) puts the estimate at 14.3 ms median + * at the observed ~1.4% degenerate rate, worst case ~13.6 ms -- within a few percent of the true + * floor, and never the 12x latch of the raw min. The residual can sit slightly BELOW the true + * floor (a degenerate-heavy window), which mildly OVER-reports drift; it is bounded and small, + * not the unbounded latch. kWindow is a structural count of samples to average, not a magic + * threshold a real step could fall below. Scheduler::step_finished feeds it one update per + * single-sequence decode step. */ +struct DecodeFloor { + /* Single-sequence decode steps averaged into one floor candidate. 32 approximates the number + * of decode steps the dashboard's 500 ms poll spans at this lane's step time, so the engine + * floor and the page's own c1 floor are computed over comparable windows. */ + static constexpr int kWindow = 32; + + void update(int64_t ns) { + /* Reject degenerate brackets BEFORE they enter a window. A decode step issued ahead behind + * a long host commit (a prefill chunk, or a KV checkpoint every 256 tokens) brackets at + * ~9% of a real step; real single-sequence steps bracket at ~96%. The populations are ~10x + * apart, so any threshold between them separates them -- 0.5 is the midpoint of that gap, + * not a value tuned to one distribution. Filtering at the STEP level is essential: at the + * observed ~1.4% rate a degenerate dilutes inside a 32-step window to a mean of ~0.91x, + * which no window-level threshold would catch, and a min over hundreds of windows then + * reliably lands on a degenerate-heavy window ~10% below the true floor. + * No rejection until a window's worth of samples has been accepted, so the running mean is + * never bootstrapped from a degenerate. */ + if (accepted_ >= kWindow && ns * 2 < mean_) return; + ++accepted_; + mean_ += (ns - mean_) / (double)accepted_; + sum_ += ns; + if (++count_ < kWindow) return; + const int64_t mean = sum_ / count_; + /* The FIRST window is recorded by neither side. The rejection gate needs a window's worth + * of accepted samples before it can judge one, so the first window is by construction + * un-gated and can carry degenerates; recording it would let the floor latch a value the + * engine can no longer reach -- the same artifact the gate exists to remove, smuggled in + * through bootstrap. Measured: at a 5% degenerate rate the un-gated first window put the + * floor ~2% below the true floor and it stuck there forever. */ + if (warmed_) { + if (best_ == 0 || mean < best_) best_ = mean; + recent_ = mean; /* most recent completed window, same size as best_ */ + } + warmed_ = true; + sum_ = 0; + count_ = 0; + } + /* The floor: the fastest window mean ever seen. A restart is priced against this. */ + int64_t best() const { return best_; } + /* The CURRENT speed: the most recent completed window mean, from the SAME stream and window + * size as best(). The advisory compares best() against recent() -- both window means of one + * population -- so the two sides cannot disagree by order statistics the way the engine's + * floor disagreed with the browser's per-poll min (a 7.7% phantom gap on a flat lane, + * 2026-10-18). 0 until the first window completes; the page must not divide by it. */ + int64_t recent() const { return recent_; } + +private: + int64_t sum_ = 0; + int count_ = 0; /* samples in the window being accumulated */ + int64_t best_ = 0; + int64_t recent_ = 0; + bool warmed_ = 0; /* false until one window has completed (the un-gated bootstrap) */ + int64_t accepted_ = 0; /* samples accepted across all windows (rejection gate's support) */ + double mean_ = 0.0; /* running mean of ACCEPTED steps -- the rejection reference */ +}; + } /* namespace rad */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 6f5d92d3..ffb88f74 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -2008,7 +2008,21 @@ void Scheduler::step_finished() { const int64_t ns = std::chrono::duration_cast(step_end - step_start_).count(); m_.step_ns += ns; - if (plan_.phase == RAD_PHASE_DECODE) m_.step_ns_decode += ns; + if (plan_.phase == RAD_PHASE_DECODE) { + m_.step_ns_decode += ns; + /* The single-sequence floor, keyed to the concurrency of THIS step (plan_.n_seq_decode is + * the row count that was just timed, not a later snapshot). A mixed step is excluded by the + * phase gate even when it carries one decode row: its lone row shares the step with a + * prefill chunk and is not the mechanical floor. The estimator is a min over WINDOW MEANS, + * not raw brackets: a decode step issued ahead behind a long host commit has no GPU work + * in its bracket, and a raw min latches that degenerate forever; averaging a window of + * single-row steps first dilutes it. See rad::DecodeFloor. */ + if (plan_.n_seq_decode == 1) { + decode_floor_.update(ns); + m_.step_ns_decode_best = decode_floor_.best(); + m_.step_ns_decode_recent = decode_floor_.recent(); + } + } const auto from = step_start_ - last_step_at_ < std::chrono::milliseconds(500) ? last_step_at_ : step_start_; diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index bcfe6106..803aab0e 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -604,6 +604,10 @@ private: * covered, both decayed with the same time constant, so their ratio is tokens over time. */ double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0; bool step_open_ = false; + /* Estimator for the single-sequence decode floor (see rad::DecodeFloor). Replaces a raw min + * over step brackets, which latched a degenerate bracket forever (live defect 2026-10-18: + * 1.16 ms against a 15.55 ms mean). step_finished feeds it each single-sequence decode step. */ + DecodeFloor decode_floor_; /* arrival; mu_ held */ int add_locked(std::unique_ptr r); diff --git a/core/server/adapters.h b/core/server/adapters.h index e2d2839f..6da4c418 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -138,6 +138,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) { o.steps_held = m.steps_held; o.decode_rows_unspeculated = m.decode_rows_unspeculated; o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode; + o.step_ns_decode_best = m.step_ns_decode_best; + o.step_ns_decode_recent = m.step_ns_decode_recent; return o; } diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 4a64fff5..2b35ad94 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -182,6 +182,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) { * covers idle time (see SchedMetrics::step_ns). */ o["step_ns"] = m.step_ns; o["step_ns_decode"] = m.step_ns_decode; + o["step_ns_decode_best"] = m.step_ns_decode_best; + o["step_ns_decode_recent"] = m.step_ns_decode_recent; o["rows_unspec"] = m.decode_rows_unspeculated; /* Conditional rate per position with its reach count: a rate of 0.0 over a reach of 3 is diff --git a/core/server/iface.h b/core/server/iface.h index 04db5e67..ac1d9968 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -127,6 +127,12 @@ struct SchedMetrics { * a decode step regardless of load. */ int64_t step_ns = 0; int64_t step_ns_decode = 0; + /* The fastest single-sequence decode step this process has measured, nanoseconds; 0 until one + * runs. The dashboard reads this instead of asking a human to type a ruler (see the same field + * on rad::SchedMetrics, where it is recorded). */ + int64_t step_ns_decode_best = 0; + /* The most recent completed single-sequence decode window mean; see SchedMetrics. */ + int64_t step_ns_decode_recent = 0; }; diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 858fa3e6..a5f229d3 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -2546,6 +2546,312 @@ TEST(the_adaptive_window_times_its_steps_and_the_next_cycle_reads_them) { } /* ================================================================== the step path */ +/* The single-sequence decode floor the dashboard reads instead of a typed ruler. Timing is real + * wall clock, so the assertions are the ones that hold whatever the machine measured: a step of a + * shape that must not sample leaves the floor at zero (a min only ever goes down, so a wrongly + * sampled step could never be told apart later -- it has to be caught while the floor is still + * unset), and a single-sequence step sets it. */ +TEST(the_decode_floor_estimator_does_not_latch_a_degenerate_bracket) { + /* The estimator is tested on a SYNTHETIC stream because the defect is a property of the + * estimator, not of the scheduler's ability to produce a degenerate bracket: the fixture runs + * steps in microseconds and cannot manufacture a 1.34 ms bracket behind a 15 ms one. What the + * live lane showed -- floor 1.34 ms against a 15.70 ms mean -- is reproduced here directly. */ + using Est = rad::DecodeFloor; + + /* First, the OLD construction, shown to fail. A min over raw brackets latches the single + * degenerate sample and never recovers, no matter how many honest steps follow. This is the + * defect, encoded as a test so the fix is measured against it rather than asserted. */ + { + int64_t best = 0; + const int64_t real = 15'000'000, degenerate = 1'340'000; + auto old_min = [&](int64_t ns) { if (best == 0 || ns < best) best = ns; }; + old_min(degenerate); /* one degenerate, early */ + for (int i = 0; i < 500; ++i) old_min(real); + CHECK_EQ(best, degenerate); /* latched -- this is the bug */ + } + + /* The NEW construction: a min over WINDOW MEANS. The same single degenerate is diluted by + * the honest steps sharing its window, so the floor tracks the real floor instead. */ + { + Est est; + const int64_t real = 15'000'000, degenerate = 1'340'000; + est.update(degenerate); /* same degenerate, same position */ + for (int i = 0; i < 500; ++i) est.update(real); + const int64_t floor = est.best(); + CHECK(floor > 0); + CHECK(floor > degenerate); /* did NOT latch the degenerate */ + /* Within 25% of the real floor: the window mean is a faithful estimator. */ + CHECK(floor >= real * 3 / 4 && floor <= real); + } + + /* Robust to a HIGH rate of degenerates: the live lane's checkpoint interval (256 tokens) + * implies they recur. One in four here. The assertion is that the floor tracks the REAL step + * time, not merely that it beats the degenerate -- with the rejection gate in place the latter + * would be trivially true and prove nothing. */ + { + Est est; + const int64_t real = 15'000'000, degenerate = 1'340'000; + for (int i = 0; i < 400; ++i) est.update((i % 4 == 0) ? degenerate : real); + const int64_t floor = est.best(); + CHECK(floor >= real * 90 / 100); /* tracks the real step, not the poison */ + CHECK(floor <= real); + } + + /* A steady stream with no degenerates: the floor equals the true floor. */ + { + Est est; + const int64_t real = 14'500'000; + for (int i = 0; i < 200; ++i) est.update(real); + CHECK_EQ(est.best(), real); + } +} + +TEST(the_decode_floor_rejects_degenerate_brackets_so_the_floor_is_the_true_floor) { + /* Window-averaging dilutes a LONE degenerate but not a RECURRENT one. At the live lane's + * observed ~1.4% degenerate rate (a decode step issued ahead behind a long host commit -- + * prefill, or a KV checkpoint every 256 tokens), a min over hundreds of windows reliably + * catches a window holding two or three degenerates, and the floor lands ~10% below the true + * floor. That residual is phantom drift: a healthy engine reads "restart pays back" against a + * floor it can no longer reach because the floor was never reachable -- it was an artifact. + * So a candidate far below the running mean of accepted steps is rejected outright: the + * degenerates sit at ~9% of the mean, real single-sequence steps at ~96%, so the two + * populations are ~10x apart and any threshold between them separates them. 0.5 is the + * midpoint of that gap, not a value tuned to a single distribution. */ + using Est = rad::DecodeFloor; + const int64_t true_floor = 14'400'000, typical = 15'000'000, degen = 1'340'000; + + /* A realistic stream: ~1.4% degenerates, the rest jittered around the typical step, with the + * true floor occasionally reached. The floor must land near the TRUE floor, not near the + * degenerate-contaminated window mean. */ + Est est; + uint32_t rng = 12345; + for (int i = 0; i < 400 * Est::kWindow; ++i) { + rng = rng * 1664525u + 1013904223u; + const bool d = ((rng >> 16) % 1000u) < 14u; /* ~1.4% */ + int64_t ns; + if (d) ns = degen; + else { + rng = rng * 1664525u + 1013904223u; + ns = true_floor + (int64_t)((rng >> 8) % (typical - true_floor + 1)); /* floor..typical */ + } + est.update(ns); + } + const int64_t floor = est.best(); + /* Within 5% of the true floor. The un-rejected estimator lands ~10% low here, so this fails + * without the rejection gate. */ + CHECK(floor >= true_floor * 95 / 100); + CHECK(floor <= true_floor * 115 / 100); + + /* The bootstrap hole: the gate needs a window of accepted samples before it can judge one, so + * the first window is un-gated. A degenerate-heavy FIRST window must therefore be recorded by + * neither side, or the floor latches an unreachable value forever. */ + { + Est est; + for (int i = 0; i < Est::kWindow; ++i) est.update(degen); /* whole first window poisoned */ + CHECK_EQ(est.best(), (int64_t)0); + CHECK_EQ(est.recent(), (int64_t)0); + for (int i = 0; i < 40 * Est::kWindow; ++i) est.update(typical); + CHECK(est.best() >= typical * 95 / 100); /* floor came from a gated window, not bootstrap */ + } + + /* And the rejection must NOT eat real steps: a stream of only real steps (no degenerates) + * still records a floor equal to the true floor. */ + Est clean; + for (int i = 0; i < 100 * Est::kWindow; ++i) clean.update(true_floor); + CHECK_EQ(clean.best(), true_floor); +} + +TEST(the_decode_floor_reports_a_recent_window_for_like_for_like_drift) { + /* The advisory compares "how fast is it now" against "how fast has it ever been". If those two + * numbers come from different instruments -- the engine's floor versus the browser's per-poll + * mean -- they disagree by pure order statistics: a min over hundreds of windows sits below a + * min over the last sixty samples even on a perfectly flat engine. Measured live 2026-10-18: + * a 7.7% phantom gap on a lane that had not changed. So the engine reports BOTH sides of the + * comparison, from the same stream and the same window size. */ + using Est = rad::DecodeFloor; + const int64_t base = 15'000'000; + + /* A steady engine with realistic run-to-run jitter: the recent window and the floor are both + * window means of the same population, so they must agree closely. */ + { + Est est; + for (int i = 0; i < 400 * Est::kWindow; ++i) { + const int64_t jitter = ((i % 7) - 3) * 200'000; /* +/- 0.6 ms, deterministic */ + est.update(base + jitter); + } + const int64_t floor = est.best(), recent = est.recent(); + CHECK(floor > 0); + CHECK(recent > 0); + /* The phantom gap must be small: this is the number the deadband is sized against. */ + const int64_t gap_pct = 100 * (recent - floor) / floor; + CHECK(gap_pct >= 0); + CHECK(gap_pct < 3); + } + + /* A degraded engine: the recent window rises, the floor remembers the old best. The verdict + * must separate -- that is the whole point of the advisory. */ + { + Est est; + for (int i = 0; i < 200 * Est::kWindow; ++i) est.update(base); + const int64_t floor = est.best(); + for (int i = 0; i < 20 * Est::kWindow; ++i) est.update(base * 6 / 5); /* 20% slower */ + const int64_t recent = est.recent(); + CHECK(recent > floor * 115 / 100); + /* The floor does not chase the degradation: a restart is exactly what would restore it. */ + CHECK_EQ(est.best(), floor); + } + + /* Before any window completes there is no recent reading -- the page must not divide by it. */ + { + Est est; + for (int i = 0; i < Est::kWindow - 1; ++i) est.update(base); + CHECK_EQ(est.recent(), (int64_t)0); + est.update(base); /* completes window 1: the un-gated warmup */ + CHECK_EQ(est.recent(), (int64_t)0); /* warmup is recorded by neither side */ + for (int i = 0; i < Est::kWindow; ++i) est.update(base); + CHECK(est.recent() > 0); + } +} + +TEST(the_decode_floor_records_only_single_sequence_decode_steps) { + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64); + CHECK_OK(f.start()); + + /* A prefill step samples nothing. Budget 128 tokens: this test walks 1 prefill + + * (kWindow-1) + 1 + kWindow = 65 steps, so 64 would run dry one step short. */ + uint64_t a = f.submit(160, 128, /*priority=*/0, /*ignore_eos=*/true); + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(11); + f.sch.step_finished(); + CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0); + + /* The floor is a min over WINDOW MEANS of single-sequence decode steps, so it stays 0 until a + * full window (DecodeFloor::kWindow) has run -- unlike the old raw min, which latched the very + * first bracket. One short of a window and the floor is still unset. */ + for (int i = 1; i < rad::DecodeFloor::kWindow; ++i) { + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().n_seq_decode, 1); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE); + f.commit_plain(12); + f.sch.step_finished(); + } + CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0); + + /* The step that completes the FIRST window leaves the floor unset: window 1 is the un-gated + * warmup (the rejection gate needs a window of accepted samples before it can judge one), so + * it is recorded by neither side. */ + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(13); + f.sch.step_finished(); + CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0); + + /* The SECOND window is the first gated one and sets the floor: positive, and no larger than + * the cumulative decode time it was drawn from. */ + for (int i = 0; i < rad::DecodeFloor::kWindow; ++i) { + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(14); + f.sch.step_finished(); + } + const int64_t floor1 = f.sch.metrics().step_ns_decode_best; + CHECK(floor1 > 0); + CHECK(floor1 <= f.sch.metrics().step_ns_decode); + + /* A further full window can only lower the floor or leave it: it is a min over windows. */ + for (int i = 0; i < rad::DecodeFloor::kWindow; ++i) { + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(15); + f.sch.step_finished(); + } + const int64_t floor2 = f.sch.metrics().step_ns_decode_best; + CHECK(floor2 > 0); + CHECK(floor2 <= floor1); + (void)a; +} + +TEST(the_decode_floor_ignores_a_decode_step_issued_behind_a_prefill) { + /* The live defect was a raw min latching the first decode step, which is issued ahead behind + * the prefill's host-side staging and whose bracket holds no GPU work. The fix does NOT + * exclude that step -- it is a real single-sequence decode step and belongs in the floor. It + * is made harmless by averaging: the floor is a min over window means, so the one degenerate + * bracket is diluted by the honest steps sharing its window. This pins that the + * prefill-following decode step IS eligible: a full window of decode steps that BEGINS with it + * produces a floor. Under the old predecessor-phase gate the first step was dropped, so a + * window of exactly kWindow decode steps fed only kWindow-1 samples and left the floor unset + * -- this test would have failed on that design. */ + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64); + CHECK_OK(f.start()); + + uint64_t a = f.submit(160, 128, /*priority=*/0, /*ignore_eos=*/true); + REQUIRE(f.sch.step() != nullptr); /* prefill */ + f.commit_plain(21); + f.sch.step_finished(); + + /* Two windows: window 1 (holding the prefill-following step) is the un-gated warmup, so the + * floor only appears once a second, gated window completes. */ + for (int i = 0; i < 2 * rad::DecodeFloor::kWindow; ++i) { + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE); + CHECK_EQ(f.sch.plan().n_seq_decode, 1); + CHECK(f.sch.plan().n_tok_decode >= 1); /* a token DID advance; token count is not the guard */ + f.commit_plain(22); + f.sch.step_finished(); + } + /* The window filled, counting the prefill-following step: the floor is set. */ + CHECK(f.sch.metrics().step_ns_decode_best > 0); + (void)a; +} + +TEST(the_decode_floor_ignores_batched_and_mixed_steps) { + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64); + CHECK_OK(f.start()); + + /* Two requests prefilled, then decoding TOGETHER: every decode step here carries two rows, so + * the floor must still be unset at the end -- a batched step is a different measurement and + * keying the floor to it would report the batch arriving as drift. */ + uint64_t a = f.submit(160, 64); + uint64_t b = f.submit(160, 64); + REQUIRE(f.sch.step() != nullptr); /* both prompts */ + f.commit_plain(11); + f.sch.step_finished(); + for (int i = 0; i < 4; ++i) { + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().n_seq_decode, 2); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE); + f.commit_plain(12); + f.sch.step_finished(); + } + CHECK(f.sch.metrics().steps_decode > 0); /* decode steps really ran ... */ + CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0); /* ... and none of them sampled */ + (void)a; (void)b; +} + +TEST(the_decode_floor_ignores_a_lone_decode_row_inside_a_mixed_step) { + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64); + CHECK_OK(f.start()); + + /* The subtle case: a mixed step carrying exactly ONE decode row alongside a prefill chunk. + * n_seq_decode is 1, so a check on the row count alone would sample it -- but that row shared + * the step with a chunk an order of magnitude dearer, and its time is not the mechanical floor. + * The phase gate is what excludes it. */ + uint64_t b = f.submit(1000, 64, /*priority=*/1); /* several chunks */ + uint64_t a = f.submit(160, 64, /*priority=*/0); /* one chunk, then decodes */ + REQUIRE(f.sch.step() != nullptr); /* both prompts */ + f.commit_plain(11); + f.sch.step_finished(); + + REQUIRE(f.sch.step() != nullptr); /* a decodes, b still chunking */ + CHECK_EQ(f.sch.plan().n_seq_decode, 1); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + f.commit_plain(12); + f.sch.step_finished(); + CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0); + (void)a; (void)b; +} + TEST(the_step_path_does_not_allocate) { Fixture f; f.build(/*blocks=*/4096, /*states=*/64); From d4998b1f75b3edb3d2bfe664e276c652792d7d39 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 16:56:38 +0000 Subject: [PATCH 044/152] server: report how long bringup took, as a raw figure A restart's cost is the one number a reader needs in order to decide whether one is worth suffering, and any guess at it would decide the answer by itself. The server knows it exactly: the interval from process start to the socket listening, on this machine, with this model and this cache state. Emitted on /stats as startup_s, 0 until the server has listened. Raw figure only -- the page no longer consumes it. It is here because it is the missing half of any restart decision a human or a tool makes downstream, and because the decode-step advisory that did consume it was withdrawn the same day it shipped (see the following commit for what the live data showed). Trailing zero-defaulted field on both SchedMetrics structs plus the adapter copy; neither struct is ABI-pinned, so this is the sanctioned append. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI (cherry picked from commit 76a9e2f7a28b8e034cfd56caa091792c68fe19b6) --- core/engine.cpp | 1 + core/engine.h | 3 +++ core/engine_bringup.cpp | 2 ++ core/server/dashboard.cpp | 3 +++ core/server/server.cpp | 10 ++++++++++ core/server/server.h | 9 +++++++++ tests/dashboard_test.cpp | 25 +++++++++++++++++++++++++ 7 files changed, 53 insertions(+) diff --git a/core/engine.cpp b/core/engine.cpp index 9f40fcc5..c2625599 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2629,6 +2629,7 @@ int Engine::run_server() { /* Startup ends here; a quiet server from now on is an idle one. */ startup_watch_.reset(); + srv.note_ready(startup_begin_ns_); const int rc = srv.run(); /* The watcher tests `watching` first, so clearing it ends the thread without a second stop; * run() has already torn the transport down. Joining costs up to one sleep interval. */ diff --git a/core/engine.h b/core/engine.h index 47de51c3..7ffa8bab 100644 --- a/core/engine.h +++ b/core/engine.h @@ -98,6 +98,9 @@ private: /* serve()'s startup stall watch, released when the server listens (run_server) or the KL * mode starts (run_kld). */ std::unique_ptr startup_watch_; + /* rad_mono_ns at the top of start(), so serve() can report how long bringup took. The same + * span the startup watch covers (main.cpp creates it here and ends it at the listen). */ + uint64_t startup_begin_ns_ = 0; std::vector rank_threads_; Config cfg_; diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 58046b1e..0f84c216 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -5,6 +5,7 @@ * Separate from engine.cpp (the hot step loop), with which it shares only the Engine's fields. */ #include "engine_priv.h" +#include "rad_internal.h" #include "engine_hostmem.h" #include "gen/driver.h" #include "gen/audio_driver.h" @@ -3124,6 +3125,7 @@ int Engine::configure_kv() { /* ================================================================== start */ int Engine::start() { + startup_begin_ns_ = rad_mono_ns(); std::vector devs; std::string inventory; std::string devnote; diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 2b35ad94..783817d5 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -125,6 +125,9 @@ HttpResponse Server::handle_stats(const HttpRequest&) { o["model"] = opt_.model_id; o["version"] = opt_.version; o["uptime_s"] = unix_now() - started_at_; + /* How long this process took to come up, measured on this machine: the price of a restart, + * which the page needs to say whether a restart pays back. 0 before the server listens. */ + o["startup_s"] = startup_s_; o["in_flight"] = in_flight_.load(std::memory_order_relaxed); o["queue_cap"] = queue_depth_; o["now_ms"] = (int64_t)std::time(nullptr) * 1000; diff --git a/core/server/server.cpp b/core/server/server.cpp index 52cc164a..5f0a5530 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -207,6 +207,16 @@ void Server::register_routes() { * number bounds the connections that may wait once the reserve is busy too. */ static const int64_t kSpareWorkers = 64; +void Server::note_ready(uint64_t begin_ns) { + if (begin_ns == 0) return; + const uint64_t now = rad_mono_ns(); + /* Only a start in the past is a duration. A stamp that arrives out of order is ignored rather + * than written as zero: the page divides by this figure, and a zero cost would price every + * restart as free. */ + if (now <= begin_ns) return; + startup_s_ = (int64_t)((now - begin_ns) / 1000000000ull); +} + int Server::run() { TransportOptions t; t.host = opt_.host; diff --git a/core/server/server.h b/core/server/server.h index 99822fe2..12360f1f 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -191,6 +191,12 @@ public: /* The admission ceiling as resolved: ServerOptions::queue_depth, or 8 x max_seqs for 0. */ int64_t queue_cap() const { return queue_depth_; } + /* Records how long bringup took, called by Engine::serve just before it starts listening + * (the same moment the startup watch ends). `begin_ns` is rad_mono_ns from the top of + * Engine::start(); 0 leaves the figure unset. run() blocks serving forever, so the value is + * handed in rather than taken inside it. */ + void note_ready(uint64_t begin_ns); + private: struct Generation; struct TranscriptionJob; /* speech.cpp */ @@ -351,6 +357,9 @@ private: std::atomic speech_sessions_{0}; std::atomic stopping_{false}; int64_t started_at_ = 0; + /* Seconds from the top of Engine::start() to the moment the server began listening -- the + * cost of a restart, measured on this machine rather than guessed. 0 until note_ready(). */ + int64_t startup_s_ = 0; /* Sinks whose HTTP side is gone but whose engine side may still be mid-step. Held until the * scheduler reports the request terminal, because Request::sink is a raw pointer and freeing diff --git a/tests/dashboard_test.cpp b/tests/dashboard_test.cpp index cdb98f20..8c4a1564 100644 --- a/tests/dashboard_test.cpp +++ b/tests/dashboard_test.cpp @@ -8,6 +8,7 @@ * groups, where summing or picking the wrong group goes wrong silently. */ #include "server_fakes.h" +#include "rad_internal.h" /* rad_mono_ns: a synthetic bringup start */ #include @@ -246,6 +247,30 @@ TEST(sessions_lists_each_conversation_and_what_the_tiers_did) { /* Every field the page's script reads from /stats (in its update and the request table) and from * /sessions (its loader and the session rows) is one the routes emit for a populated engine. A * rename on either side otherwise blanks a panel and reports nothing. */ +/* The price of a restart, measured rather than guessed: whatever decides whether a restart is + * worth suffering needs this figure, and a guessed cost would decide the answer by itself. The + * page stopped consuming it on 2026-10-18, when the payback clause it fed was withdrawn -- the + * field stays because it is the missing half of that decision made downstream, by a human or a + * tool. A test runs in microseconds, so a real note_ready() would compute 0 -- indistinguishable + * from "never called". Passing a synthetic start exercises the arithmetic through the real route. */ +TEST(stats_reports_how_long_bringup_took_once_the_server_listens) { + Dash d(false); + /* Before the server has listened, there is no measured cost to report. */ + CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)0); + + d.srv->note_ready(rad_mono_ns() - 47ull * 1000000000ull); + CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)47); + + /* A start in the future is not a negative cost: the figure is a duration, and a page that + * divided by it would otherwise be handed a sign flip. */ + d.srv->note_ready(rad_mono_ns() + 10ull * 1000000000ull); + CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)47); + + /* 0 means "not yet", so it must not overwrite a measured figure. */ + d.srv->note_ready(0); + CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)47); +} + TEST(every_field_the_page_reads_is_one_the_routes_emit) { Dash d(false); HttpResponse page = d.srv->router().call("GET", "/"); From 845f0a5646195a144553bec309ab2d359b520c6d Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 17:05:51 +0000 Subject: [PATCH 045/152] dashboard: state the engine's decode floor and recent window, without a verdict The decode step's detail line now shows two figures the engine measures itself: the fastest single-sequence decode window this process has run, and its most recent one. Nothing is asked of the reader -- no ruler to type, no panel to open -- and no conclusion is drawn. Both come from the engine rather than the browser because the browser cannot produce either well. A tab only sees the steps taken while it is open, and a floor learned from a lane that was already degraded says "at your best" forever. The engine sees every step and knows the concurrency of the step it timed. Single-stream on both sides of the engine's own measurement. The floor is a single-sequence window, so the engine keys it to one row: a decode step at eight sequences is a different measurement, and reading it against a single-sequence floor would report a batch arriving as a slowdown. On an engine too old to emit the field, the page falls back to the fastest single-stream step this tab has seen. This commit previously also priced a restart, and that clause is removed here after being built, deployed, measured, and refuted on live traffic the same day. It compared the floor against the recent window, called the gap drift, and computed a payback from startup_s. The gap is not drift. On a healthy shared lane the floor held flat at 14.79 ms while the recent window moved between 15.2 and 16.5 ms -- 3% to 11% -- tracking what else the lane was doing: it froze when the lane went idle and rose on a fresh short request, so it was neither context length nor engine age. The payback formula assumes a restart's improvement is permanent, so following it pays the measured 49 s bringup and re-drifts within minutes; the line was advising a restart every 12 to 19 minutes forever, for a gain that was never there. What floor-vs-recent actually measures is the distance between the lane's most favorable moment and its typical one. An earlier version of this clause also compared the engine's floor against a median of the browser's per-poll means -- two instruments over different sample counts, disagreeing by pure order statistics on a flat engine, a measured 7.7% phantom drift. That is why the two figures shown now are both engine window means of one stream at one size. They are honest numbers; only the interpretation was withdrawn. A verdict can return once someone observes what none of this data shows: step time rising with engine age and staying up. Every excursion measured was load. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI (cherry picked from commit 2eaf32201cb1a8c45857dfbb509a12acaa9ee216) --- core/server/dashboard.cpp | 57 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 783817d5..b6b51485 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -125,8 +125,10 @@ HttpResponse Server::handle_stats(const HttpRequest&) { o["model"] = opt_.model_id; o["version"] = opt_.version; o["uptime_s"] = unix_now() - started_at_; - /* How long this process took to come up, measured on this machine: the price of a restart, - * which the page needs to say whether a restart pays back. 0 before the server listens. */ + /* How long this process took to come up, measured on this machine. Raw figure: a restart's + * real cost, for whoever is deciding whether one is worth it. 0 before the server listens. + * The page no longer consumes it -- see the note on the decode-step detail line for why the + * payback arithmetic that used to live there was removed. */ o["startup_s"] = startup_s_; o["in_flight"] = in_flight_.load(std::memory_order_relaxed); o["queue_cap"] = queue_depth_; @@ -1684,6 +1686,34 @@ function renderRequests(list, poolTokens) { let prev = null, prevAt = 0, bars = [], devs = [], layerBars = []; let lastStepMs = null, lastTps = null; +/* THE SINGLE-STREAM FLOOR and the engine's most recent window, shown as two numbers and + * interpreted by nobody. The engine records the fastest single-sequence decode window it has + * measured (step_ns_decode_best) and its most recent one (step_ns_decode_recent); the page states + * both and draws no conclusion. Neither is asked of a human: a typed ruler goes stale and + * mis-advises silently, and a browser meter sees only the steps taken while this tab is open. On + * an engine too old to emit the floor, the page falls back to the fastest single-stream step this + * tab has seen. + * + * THERE IS DELIBERATELY NO RESTART ADVICE HERE, and it was not never-built -- it was built, + * deployed, measured, and removed the same day (2026-10-18). It compared the floor against the + * recent window, called the gap drift, and priced a payback from startup_s. The gap is not drift. + * On a HEALTHY shared lane the floor sat flat at 14.79 ms while the recent window moved between + * 15.2 and 16.5 ms -- 3% to 11% -- tracking what else the lane was doing: it froze when the lane + * went idle and ROSE on a fresh short request, so it was neither context length nor engine age. + * The payback formula assumes a restart's improvement is permanent, so acting on it pays the 49 s + * bringup and re-drifts within minutes; the line was telling the operator to restart every 12-19 + * minutes forever, for a gain that was never there. What best-vs-recent actually measures is the + * distance between the lane's most favorable moment and its typical one. + * + * A verdict could go back here IF someone first observes the thing none of today's data shows: + * step time rising with ENGINE AGE and STAYING up. Every excursion seen so far was load. The + * full chain, including the estimator that survives this, is in patches/CHANGELOG-SOURCE.md. */ +let c1hist = []; +const C1CAP = 7200; /* an hour at 2 polls/s of single-stream samples */ +let bestEver = 0; /* the best engine floor ever seen here, across restarts */ +try { bestEver = parseFloat(localStorage.getItem("radiance.c1best")) || 0; } catch (e) {} + + function update(s, dt) { $("ver").textContent = s.version + " · up " + dur(s.uptime_s); @@ -1702,6 +1732,29 @@ function update(s, dt) { const st = stepTime(lastStepMs); M.step.u.textContent = st.u; setMetric("step", lastStepMs, st.n); + + /* THE FLOOR, single-stream on both sides of the engine's own measurement. The floor is a + * single-sequence window, so the engine keys it to one row deliberately: a decode step at eight + * sequences is a different measurement, and reading it against a single-sequence floor would + * report a batch arriving as a slowdown. */ + if (s.running === 1 && stepMs != null) { c1hist.push(stepMs); if (c1hist.length > C1CAP) c1hist.shift(); } + const engBestMs = s.step_ns_decode_best > 0 ? s.step_ns_decode_best / 1e6 : 0; + const engRecentMs = s.step_ns_decode_recent > 0 ? s.step_ns_decode_recent / 1e6 : 0; + if (engBestMs > 0 && (bestEver === 0 || engBestMs < bestEver)) { + bestEver = engBestMs; + try { localStorage.setItem("radiance.c1best", String(bestEver)); } catch (e) {} + } + const floorMs = engBestMs > 0 ? engBestMs : (c1hist.length ? Math.min(...c1hist) : 0); + /* The two engine figures, stated plainly. Painted every poll: without a verdict there is + * nothing for a fast repaint to make unactionable, and `recent` only moves when a window of 32 + * single-sequence steps completes anyway. */ + let det = ""; + if (floorMs > 0) { + det = "best " + floorMs.toFixed(2) + "ms"; + if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms"; + } + $("m-stepdet").textContent = det; + setMetric("decode", s.decode_tps, tps(s.decode_tps)); setMetric("prefill", s.prefill_tps, tps(s.prefill_tps)); setMetric("flight", s.in_flight, String(s.in_flight)); From cb6cd3f69a325523b44916c0ea4af2695a30f846 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 21:30:19 +0000 Subject: [PATCH 046/152] docs: explain the decode floor and recent window, and what their gap is not MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tile now shows two engine figures and no verdict, so the guide says what they are: window means of 32 single-sequence steps, best the lane's most favorable moment and recent its current one. The load-bearing sentence is the one nobody can derive from the numbers: a gap of a few percent up to ~11% is operating load on a shared card, not degradation, and not a reason to restart. That claim is measured, not stylistic — the live lane held a flat floor while its recent window moved 3-11% with what else the machine was doing. Cross-references rad::DecodeFloor and the devlog for how the interpretation was tested and withdrawn. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI (cherry picked from commit 604617bd72b7360d3855acac5e96d82e51ef91b7) --- docs/GUIDE.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 56967b33..ee1302c3 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2444,6 +2444,40 @@ finished turns kept for reuse, which gives way the moment a live request needs i figure with a high hit rate is the cache working, not a leak. Both segments take their warning colour from the total fill, since a full pool causes preemption. +The decode step tile carries two figures under the big number: + +``` +best 14.79ms · recent 15.21ms +``` + +Both are window means of single-sequence decode steps, measured by the engine: +`best` is the fastest window of 32 consecutive single-stream steps this process +has run, `recent` its most recent one. Individual steps vary a lot — a step that +saves a KV checkpoint, or finishes while other engine work is committing, can +take twice as long as its neighbour — so nothing is compared until 32 have been +averaged. A single slow step moves neither figure. + +The gap between them is normal, and it is not degradation. `best` is the most +favorable moment the lane has hit; `recent` is what it is doing now. On a healthy +lane sharing the card with other work the gap moves between 3% and 11% while the +engine is in good shape: it tracks what else the machine is doing, and it freezes +when the lane goes idle, because no new window is completing. "Recent is 8% above +best" is not "8% degraded", and it is not a reason to restart. + +What is worth acting on is `best` itself getting worse across days — the engine +no longer reaching the speeds it used to. That is a hardware, driver, or +configuration question rather than a restart question, and the honest check is +comparing `best` across restarts against a known-good value for the machine. + +Both figures are per-process and reset when the engine restarts, so a freshly +restarted lane has not yet seen its own best moment and will report a `best` that +later improves. `/stats` carries the raw values as `step_ns_decode_best` and +`step_ns_decode_recent` (nanoseconds; 0 until the first window completes), plus +`startup_s` — how long bringup took on this machine, which is the real cost of a +restart if one is decided on. The estimator is `rad::DecodeFloor` in +`core/sched/metrics.h`; `docs/DEVLOG-decode-floor.md` is the log of how these +figures came to be shown without a verdict attached. + **Sessions**: one row per stored conversation: how many tokens, which tier it is in, and whether its linear half is still reachable. Sizes overlap and cannot be added: two sessions sharing a system prompt share its blocks. From 5dfa61372ab45329371bcd5e0b3e46f63592d5cb Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 21:30:48 +0000 Subject: [PATCH 047/152] =?UTF-8?q?docs:=20devlog=20for=20the=20decode=20f?= =?UTF-8?q?loor=20=E2=80=94=20the=20failures,=20and=20why=20they=20ended?= =?UTF-8?q?=20in=20simplification?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The five-rung chain that produced step_ns_decode_best/recent: the raw min that latched 1.16 ms, the two guards refuted by measurement before being built, the phase gate that passed 38,820 checks and failed live, window averaging that kept a 10%-low floor, and the advisory whose premise — step time ratchets with engine age — survived a day of watching zero observations. The advisory was deleted, not tuned: the gap it priced is operating load (3-11% on a healthy lane), and the payback formula assumed a permanent gain the lane never offered. Written for the next contributor tempted to add a gate, a smoother, or a verdict here: each rung's temptation was to add mechanism, and each rung's cheap move was to measure the premise first. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (xhigh) via Open WebUI (cherry picked from commit 9260f8e646c95aa8537d5e632a948bc54653c2ba) --- docs/DEVLOG-decode-floor.md | 141 ++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 docs/DEVLOG-decode-floor.md diff --git a/docs/DEVLOG-decode-floor.md b/docs/DEVLOG-decode-floor.md new file mode 100644 index 00000000..672c3011 --- /dev/null +++ b/docs/DEVLOG-decode-floor.md @@ -0,0 +1,141 @@ +# Devlog: the decode floor, and the advice that had to die + +The story behind `step_ns_decode_best`, `step_ns_decode_recent`, and why the +dashboard shows them without a verdict. Written 2026-10-18, the day all of it +happened. The user-facing explanation is §6.1 of the guide; this is the log of +how we got there, including the parts that failed. + +## What shipped + +Two engine-measured figures on the decode step tile and on `/stats`: the fastest +window of 32 single-sequence decode steps (`best`) and the most recent one +(`recent`), plus `startup_s` (bringup cost) as a raw field. The estimator is +`rad::DecodeFloor` in `core/sched/metrics.h`. No verdict, no restart advice. + +## The chain of failures + +Every rung below was built, tested, and — for the first and fourth — deployed +before it was refuted. None of them failed because of a coding mistake; each +failed because a premise nobody had measured turned out to be false. + +### 1. A raw min over step brackets latched an artifact (deployed, failed live) + +The first floor was a plain minimum over host-side decode-step brackets. On a +live TP2 lane it latched **1.16 ms** against a **15.55 ms** mean on the first +request after bringup — and a min never recovers, so the advisory read +"heavily drifted, restart pays back fast" forever. + +The artifact: step timing is host-side, and with pipelining on, the next forward +pass is issued behind the current step's commit. Behind a step with long host +work (a prefill chunk, a KV checkpoint save), the decode pass finishes before +its own bracket opens — the bracket holds readback and commit and no GPU work. +It is a real step advancing a real token, so no token-count guard catches it. + +### 2. Two plausible guards, refuted by measurement, not built + +- *"The bracket is rare — only steps issued ahead are affected."* Refuted: + `engine_steps_ahead_total == engine_steps_decode_total` (27934 == 27934). + With pipelining, issue-ahead is universal. +- *"A zero-token decode step produces the degenerate bracket."* Refuted in + source: `want <= 0` breaks before the bracket opens. The scheduler cannot + make one. + +### 3. The predecessor-phase gate: passed every test, failed live + +Hypothesis: a decode step timed behind a *prefill* is the confound; gate the +floor on "previous step was also decode-only." Built, passed **38,820** unit +checks, deployed. Floor still latched: **1.34 ms** vs a 15.70 ms mean. + +The confound was predecessor *host work*, not predecessor *phase*. Prefill is +one source of long host work; a KV checkpoint save every 256 tokens is another. +A gate on the phase can see neither. This is the most instructive failure of the +day: a test suite can be green, large, and completely blind, because the fixture +runs steps in microseconds and cannot manufacture the degenerate bracket the +test was about. + +### 4. Window averaging: fixed the latch, kept the phantom (deployed, failed live) + +Averaging a window of single-row steps before the min dilutes a *lone* +degenerate. But they are not rare — ~1.4% of steps — and a min over hundreds of +windows reliably lands on a degenerate-heavy window. The floor sat ~10% below +the true floor: still unreachable, still phantom drift. Simulation showed this +before deployment; the unit tests, again, could not see it. + +The fix that worked: reject candidates at the **step level**, before they enter +a window — a step under half the running mean of accepted steps is a degenerate. +The two populations are ~10x apart (degenerates ~9% of a real step, real steps +~96%), so the threshold is the midpoint of a gap, not a tuned constant. Window +1 is recorded by neither figure: the gate needs a window of accepted samples to +judge one, and recording the un-gated first window latches an unreachable floor. + +### 5. The advisory itself: right numbers, wrong premise (deployed, removed live) + +With a sound floor, the advisory compared it against the browser's per-poll +statistics. Two instruments, different sample counts — a measured **7.7%** +phantom drift on a lane that had not changed. Fixed by having the engine report +both sides (`recent` added), same stream, same window size. + +Then the operator watched the live line: *"best 14.89 · restart pays back in +18m56s"* on an engine minutes from its restart, then *"12 minutes"*. His +reductio — "do I restart every 18 minutes?" — was the falsification, and the +instrument agreed immediately: + +- `best` held flat at 14.79 ms all session. +- `recent` moved between 15.2 and 16.5 ms — **3% to 11%** — on a healthy lane. +- It **froze** when the lane went idle and **rose** on a fresh short request: + neither context length nor engine age. Operating load. + +The payback formula assumes a restart's improvement is permanent. The measured +"drift" was transient, so acting on it pays the 49 s bringup and re-drifts +within minutes. The premise underneath the whole advisory — *step time ratchets +up with engine age* — had zero observations in a full day of watching. Every +excursion was load. + +## Why the failures ended in simplification + +Each failure removed an interpretation layer rather than adding a mechanism: + +- The raw min said "the fastest bracket is the truth." It wasn't; the window + mean replaced it — one statistic instead of a hoped-for exact instrument. +- The phase gate tried to *classify* steps away. Measurement said the + confounder is unclassifiable from phase; the rejection gate just compares + magnitudes — simpler, and it works because the populations are far apart. +- The advisory tried to *decide* for the operator. The data said the signal it + was deciding on is load noise, and no persistence gate or wider band can fix + a premise that does not exist. So the verdict was deleted, not tuned. The + honest artifact is two numbers and a guide section that says what the gap + between them is not. + +The temptation at each rung was to add: another gate, another smoothing window, +another confidence band. Every time, the cheaper move — measure the premise +first — was available and was skipped. The day's cost is mostly the price of +fixes built before their premises were probed. The surviving code is the part +that was probed: the estimator (sound, still live) and the raw fields. + +## Method notes worth keeping + +- **A check that cannot fail is not a check.** The contract test passed at the + same check count after a new field was added — it had silently not covered + it. Proving coverage means deleting the emit line and watching the test name + it. Six vacuous checks were caught this way in one day. +- **Like-for-like means same statistic, same instrument, same operating + condition.** Two of the three failures were comparisons between different + instruments wearing the same units. +- **Score predictions on representative encounters.** The advisory was scored + "working" on one lucky sample at uptime 141 s; the next sample was the + normal behavior. One claim per prediction, or the score means nothing. +- **Comments are load-bearing.** A stale rationale ("the page needs this to + say whether a restart pays back") survived a green suite after the code it + described was deleted; it would have re-taught the phantom to the next + reader. Sweep added code lines per patch for vocabulary the final tree no + longer supports. + +## Open question + +Whether engine age degrades step time at all is still unmeasured — every +excursion seen was load. The discriminating experiment: restart under steady +sustained load and watch whether `recent` re-lands at the same value within +minutes. If it does, no restart advisory is ever defensible and these two +numbers stay un-advised forever. If a floor genuinely ratchets up and stays +up, that signature gets a threshold, and a verdict can come back — designed +from the observation this time, not from the vocabulary of the design. From 52a646431aee5f3c9ace8d5730886ebe492c5ac3 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 21:58:06 +0000 Subject: [PATCH 048/152] dashboard: state the decode step as a percentage of the best at its own concurrency The drift line carried a percent-of-best suffix that left with the drift verdict on 10-18. Restored as a raw ratio, keyed by concurrency: a c8 step against the fastest c8 step this process has done, never against the single-stream floor (that cross-read is what made the old line lie about a batch arriving). No threshold, no colour. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI (cherry picked from commit 4fe6ff1c838d67b642cc12782ce6a441368c3d76) --- core/server/dashboard.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index b6b51485..cdcb9bc3 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1712,6 +1712,7 @@ let c1hist = []; const C1CAP = 7200; /* an hour at 2 polls/s of single-stream samples */ let bestEver = 0; /* the best engine floor ever seen here, across restarts */ try { bestEver = parseFloat(localStorage.getItem("radiance.c1best")) || 0; } catch (e) {} +const bestAt = {}; /* fastest step seen at each concurrency, this process */ function update(s, dt) { @@ -1753,6 +1754,16 @@ function update(s, dt) { det = "best " + floorMs.toFixed(2) + "ms"; if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms"; } + /* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY. Keyed by + * concurrency on purpose: a c8 step read against the single-stream floor would report the batch + * arriving as a slowdown -- the mistake that took the old drift line out. Raw ratio, no + * threshold, no colour: the number is the statement. */ + if (s.running > 0 && lastStepMs != null) { + const k = s.running; + if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs; + const ref = k === 1 && floorMs > 0 ? floorMs : bestAt[k]; + if (ref > 0) det += " · now " + Math.round(100 * lastStepMs / ref) + "% of best" + (k === 1 ? "" : "@c" + k); + } $("m-stepdet").textContent = det; setMetric("decode", s.decode_tps, tps(s.decode_tps)); From 46c7dc26bed15f84e2b690e255671437c3da549f Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 23:46:20 +0000 Subject: [PATCH 049/152] dashboard: read the decode step as a percentage of the fastest, not a multiple of it The suffix was a ratio of time (100 * lastStepMs / ref): the fastest step read 100% and anything slower read ABOVE 100% -- 18.75 ms against a 15 ms floor printed "125% of best". Slower meant bigger, which is backwards. Flipped to a ratio of speed (100 * ref / lastStepMs): the fastest reads 100%, anything slower reads a percentage of it (the same pair now reads 80%), and the figure can never exceed 100% because ref is always the minimum. The "% of best" label now says what it shows. Operator-directed 2026-10-18; live-verified on the Tasmania lane (best 33.73ms / recent 35.76ms -> "94% of best"). Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI (cherry picked from commit 6540ff811addc15288e6fcaa09b37b6c82ee7ebb) --- core/server/dashboard.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index cdcb9bc3..8cd74955 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1754,7 +1754,7 @@ function update(s, dt) { det = "best " + floorMs.toFixed(2) + "ms"; if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms"; } - /* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY. Keyed by + /* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY: 100% is the fastest step, anything slower a percentage of it. Keyed by * concurrency on purpose: a c8 step read against the single-stream floor would report the batch * arriving as a slowdown -- the mistake that took the old drift line out. Raw ratio, no * threshold, no colour: the number is the statement. */ @@ -1762,7 +1762,7 @@ function update(s, dt) { const k = s.running; if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs; const ref = k === 1 && floorMs > 0 ? floorMs : bestAt[k]; - if (ref > 0) det += " · now " + Math.round(100 * lastStepMs / ref) + "% of best" + (k === 1 ? "" : "@c" + k); + if (ref > 0) det += " · now " + Math.round(100 * ref / lastStepMs) + "% of best" + (k === 1 ? "" : "@c" + k); } $("m-stepdet").textContent = det; From 0a222c672320ae3d2d88b08d34e4f3a96737618a Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 23:55:53 +0000 Subject: [PATCH 050/152] dashboard: cap the decode-step percentage at 100% `now` is a ~500 ms poll mean; `best` is a 32-step window mean. A fast stretch shorter than a window can therefore read faster than the recorded floor, which the ratio printed as >100% -- "105% of best", which is a contradiction: if it beat the best, the best should have moved. The engine only ratchets the floor on a completed 32-step window, so a sub-window blip is not a new record. Cap the figure at 100: a live window at or above the floor reads "100% of best" (at your best), and anything slower reads a percentage of it. The "best X ms" figure is unchanged. Operator-directed 2026-10-18. Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI (cherry picked from commit e083a2d606c2194539bd0640916fb0ae0852962e) --- core/server/dashboard.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 8cd74955..be2ce26f 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1757,12 +1757,15 @@ function update(s, dt) { /* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY: 100% is the fastest step, anything slower a percentage of it. Keyed by * concurrency on purpose: a c8 step read against the single-stream floor would report the batch * arriving as a slowdown -- the mistake that took the old drift line out. Raw ratio, no - * threshold, no colour: the number is the statement. */ + * threshold, no colour: the number is the statement. Capped at 100: `now` is a ~500 ms poll mean while + * `best` is a 32-step window mean, so a fast stretch shorter than a window can read faster than the + * recorded floor. That is "at your best", not a new record -- the engine only ratchets the floor on a + * completed 32-step window, and a sub-window blip is not one. */ if (s.running > 0 && lastStepMs != null) { const k = s.running; if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs; const ref = k === 1 && floorMs > 0 ? floorMs : bestAt[k]; - if (ref > 0) det += " · now " + Math.round(100 * ref / lastStepMs) + "% of best" + (k === 1 ? "" : "@c" + k); + if (ref > 0) det += " · now " + Math.min(100, Math.round(100 * ref / lastStepMs)) + "% of best" + (k === 1 ? "" : "@c" + k); } $("m-stepdet").textContent = det; From 87882e4c9c18fd04405619894da653241e46b610 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Sun, 18 Oct 2026 23:57:47 +0000 Subject: [PATCH 051/152] docs/GUIDE: document the decode-step percentage and its 100% cap The tile's detail line gained a third figure in 4fe6ff1 (now X% of best) and a 100% cap in e083a2d; the GUIDE still described only the two engine figures. Document the percentage: 100% is the fastest, anything slower a percentage of it, capped at 100 because `now` is a ~500 ms poll mean while `best` is a 32-step window mean, and keyed by concurrency above c1. Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI (cherry picked from commit 7263163748b98c1e5b5c9d4fa3e7fe8fed924678) --- docs/GUIDE.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index ee1302c3..7c1dc707 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2444,10 +2444,10 @@ finished turns kept for reuse, which gives way the moment a live request needs i figure with a high hit rate is the cache working, not a leak. Both segments take their warning colour from the total fill, since a full pool causes preemption. -The decode step tile carries two figures under the big number: +The decode step tile carries two figures and a percentage under the big number: ``` -best 14.79ms · recent 15.21ms +best 14.79ms · recent 15.21ms · now 97% of best ``` Both are window means of single-sequence decode steps, measured by the engine: @@ -2457,6 +2457,18 @@ saves a KV checkpoint, or finishes while other engine work is committing, can take twice as long as its neighbour — so nothing is compared until 32 have been averaged. A single slow step moves neither figure. +The percentage, `now X% of best`, is the page's own live window read against the +floor. `now` is the mean of the steps that completed in the last poll (~500 ms); +the figure is that mean as a fraction of `best`, so 100% is the fastest the lane +has done and anything slower reads a percentage of it (a step at 80% of the +floor's speed reads "80% of best"). It is capped at 100: `now` is a ~500 ms mean +while `best` is a 32-step window mean, so a fast stretch shorter than a window can +read faster than the recorded floor. That is "at your best", not a new record — +the engine only lowers `best` on a completed 32-step window, and a sub-window blip +is not one. At higher concurrency the figure is keyed to that concurrency (`@c8`) +and read against the fastest step seen at that concurrency, because a batched step +is a different measurement and would report a batch arriving as a slowdown. + The gap between them is normal, and it is not degradation. `best` is the most favorable moment the lane has hit; `recent` is what it is doing now. On a healthy lane sharing the card with other work the gap moves between 3% and 11% while the From 8a4816dc8f52097d9ff021e628f92d8e464976ee Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Mon, 19 Oct 2026 00:03:08 +0000 Subject: [PATCH 052/152] dashboard: cap the decode-step percentage at ~99, not 100 100% would claim a sustained floor the ~500 ms poll window cannot confirm, and would read as a bug the moment a fast stretch briefly beat the 32-step floor. Cap at 99 and show it with a tilde: "now ~99% of best" says "at your best" without overclaiming. Anything slower still reads a plain percentage of the floor. Operator-directed 2026-10-18. Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI (cherry picked from commit 7c35068e60d8a7baf61483e4d2a6452d71e0bc6f) --- core/server/dashboard.cpp | 11 +++++++---- docs/GUIDE.md | 8 +++++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index be2ce26f..68ef685b 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1754,18 +1754,21 @@ function update(s, dt) { det = "best " + floorMs.toFixed(2) + "ms"; if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms"; } - /* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY: 100% is the fastest step, anything slower a percentage of it. Keyed by + /* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY: ~99% is the fastest the lane has done, anything slower a percentage of it. Keyed by * concurrency on purpose: a c8 step read against the single-stream floor would report the batch * arriving as a slowdown -- the mistake that took the old drift line out. Raw ratio, no - * threshold, no colour: the number is the statement. Capped at 100: `now` is a ~500 ms poll mean while + * threshold, no colour: the number is the statement. Capped at ~99 (shown with a tilde): `now` is a ~500 ms poll mean while * `best` is a 32-step window mean, so a fast stretch shorter than a window can read faster than the * recorded floor. That is "at your best", not a new record -- the engine only ratchets the floor on a - * completed 32-step window, and a sub-window blip is not one. */ + * completed 32-step window, and a sub-window blip is not one. The cap is 99, not 100: a 500 ms window that briefly beats the + * floor is not a sustained record, and 100% would claim a floor the window cannot confirm -- it + * would read as a bug. ~99% says "at your best" without overclaiming. */ if (s.running > 0 && lastStepMs != null) { const k = s.running; if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs; const ref = k === 1 && floorMs > 0 ? floorMs : bestAt[k]; - if (ref > 0) det += " · now " + Math.min(100, Math.round(100 * ref / lastStepMs)) + "% of best" + (k === 1 ? "" : "@c" + k); + const shown = ref > 0 ? Math.min(99, Math.round(100 * ref / lastStepMs)) : 0; + if (ref > 0) det += " · now " + (shown === 99 ? "~99" : shown) + "% of best" + (k === 1 ? "" : "@c" + k); } $("m-stepdet").textContent = det; diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 7c1dc707..2e7c5c3d 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2459,13 +2459,15 @@ averaged. A single slow step moves neither figure. The percentage, `now X% of best`, is the page's own live window read against the floor. `now` is the mean of the steps that completed in the last poll (~500 ms); -the figure is that mean as a fraction of `best`, so 100% is the fastest the lane +the figure is that mean as a fraction of `best`, so ~99% is the fastest the lane has done and anything slower reads a percentage of it (a step at 80% of the -floor's speed reads "80% of best"). It is capped at 100: `now` is a ~500 ms mean +floor's speed reads "80% of best"). It is capped at ~99, shown with a tilde: `now` is a ~500 ms mean while `best` is a 32-step window mean, so a fast stretch shorter than a window can read faster than the recorded floor. That is "at your best", not a new record — the engine only lowers `best` on a completed 32-step window, and a sub-window blip -is not one. At higher concurrency the figure is keyed to that concurrency (`@c8`) +is not one. The cap is 99 rather than 100 because a 500 ms window that briefly beats the floor is +not a sustained record; 100% would claim a floor the window cannot confirm and would read as a +bug, while ~99% says "at your best" without overclaiming. At higher concurrency the figure is keyed to that concurrency (`@c8`) and read against the fastest step seen at that concurrency, because a batched step is a different measurement and would report a batch arriving as a slowdown. From 14c5c8a68b28673a2ddffe2f8b58563b9eb34bf6 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Mon, 19 Oct 2026 01:07:09 +0000 Subject: [PATCH 053/152] review: fix the stale note_ready comment, drop a tautological check The note_ready comment claimed "the page divides by this figure", but the submitted dashboard does not divide by startup_s (the payback formula that did was removed). Reworded to describe the actual risk: a zero cost would price every restart as free in any payback formula that divides by it. Dropped CHECK(gap_pct >= 0) in the decode-floor drift test: recent >= floor holds by construction (floor is the min of the window means, recent is one of them), so the check can never fail. The load-bearing assertion is the adjacent CHECK(gap_pct < 3). Authored at: Tasmania Qwen 3.8 27B Dense XHigh (level not visible) via Open WebUI (cherry picked from commit 98429a9b15d7da1aa0e644cbd7e519d1bf33d797) --- core/server/server.cpp | 4 ++-- tests/sched_test.cpp | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/core/server/server.cpp b/core/server/server.cpp index 5f0a5530..d7719961 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -211,8 +211,8 @@ void Server::note_ready(uint64_t begin_ns) { if (begin_ns == 0) return; const uint64_t now = rad_mono_ns(); /* Only a start in the past is a duration. A stamp that arrives out of order is ignored rather - * than written as zero: the page divides by this figure, and a zero cost would price every - * restart as free. */ + * than written as zero: a zero cost would price every restart as free in any payback formula + * that divides by it. */ if (now <= begin_ns) return; startup_s_ = (int64_t)((now - begin_ns) / 1000000000ull); } diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index a5f229d3..fe015b94 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -2684,7 +2684,6 @@ TEST(the_decode_floor_reports_a_recent_window_for_like_for_like_drift) { CHECK(recent > 0); /* The phantom gap must be small: this is the number the deadband is sized against. */ const int64_t gap_pct = 100 * (recent - floor) / floor; - CHECK(gap_pct >= 0); CHECK(gap_pct < 3); } From 11334c8ed5ccca05f89361f7ae384dba5fdbc6a3 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Mon, 19 Oct 2026 16:39:41 +0000 Subject: [PATCH 054/152] deploy/compose, README: Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B containers Two containers on Hugging Face (keptn), each with a compose file and a row in the models table. --- README.md | 2 ++ deploy/compose/gemma4-31b-heretic-ara-w4a8.yaml | 14 ++++++++++++++ deploy/compose/ornith-1.5-35b-a3b.yaml | 14 ++++++++++++++ 3 files changed, 30 insertions(+) create mode 100644 deploy/compose/gemma4-31b-heretic-ara-w4a8.yaml create mode 100644 deploy/compose/ornith-1.5-35b-a3b.yaml diff --git a/README.md b/README.md index 594c02e5..7c7a649b 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,11 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` | | Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` | | Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` | +| Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` | | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | +| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` | diff --git a/deploy/compose/gemma4-31b-heretic-ara-w4a8.yaml b/deploy/compose/gemma4-31b-heretic-ara-w4a8.yaml new file mode 100644 index 00000000..9fd27492 --- /dev/null +++ b/deploy/compose/gemma4-31b-heretic-ara-w4a8.yaml @@ -0,0 +1,14 @@ +# Gemma 4 31B-it heretic-ara (Gemma 4 with its refusals removed by Heretic's ARA): the same container +# as gemma4-31b-w4a8.yaml, built from that checkpoint. The vision tower stays in host memory, so its +# VRAM goes to the KV cache. For the full 262,144-token context use --max-model-len 262144 +# --max-num-seqs 2. +name: radiance-gemma4-31b-heretic-ara-w4a8 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-gemma4-31b-heretic-ara-w4a8 + command: > + --model /models/gemma4-31b-heretic-ara-w4a8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 65536 --kv-cache-dtype fp8 --vision-tower-placement ram + --num-speculative-tokens 3 --max-num-batched-tokens 2048 --temp 1.0 --top-p 0.95 --top-k 64 diff --git a/deploy/compose/ornith-1.5-35b-a3b.yaml b/deploy/compose/ornith-1.5-35b-a3b.yaml new file mode 100644 index 00000000..7b5b6bb4 --- /dev/null +++ b/deploy/compose/ornith-1.5-35b-a3b.yaml @@ -0,0 +1,14 @@ +# Ornith-1.5-35B-A3B, FP8 with one scale per 128x128 block, its own MTP head and the vision tower. +# Sampling is Ornith's setting for general tasks; for precise coding use --temp 0.6 +# --presence-penalty 0. Thinking is on by default and switched per request (chat_template_kwargs). +name: radiance-ornith-1.5-35b-a3b +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-35b-a3b + command: > + --model /models/ornith-1.5-35b-a3b-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 From 385754f44fda08b5ba5a01a863437f19bd850998 Mon Sep 17 00:00:00 2001 From: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:44:38 +0200 Subject: [PATCH 055/152] core/format: a Quark export whose excluded layers stay block-FP8; DeepSeek's expert counts GLM-5.3-Flash's Quark export is MXFP4 throughout except the layers it excludes, attention and the MTP layer, which it keeps as 128x128 E4M3 block-FP8 with F32 scales and names in layer_quant_config. Every nonempty override map was refused. Each override is now checked: MXFP4 (fp4, per_group 32, e8m0) or block-FP8 (fp8_e4m3, per_block 128 128) passes, anything else -- including a null or empty weight, which flattening used to drop -- is refused by name. The expert counts read n_routed_experts and n_shared_experts as DeepSeek-style configs spell them (GLM-5's included). checkpoint_test covers both spellings, the mixed export, and the refusals. --- core/format/checkpoint.cpp | 50 ++++++++++++++++++++--- tests/checkpoint_test.cpp | 83 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+), 5 deletions(-) diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 43d66fd1..aa81c61f 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -60,6 +60,13 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met for (auto it = j.begin(); it != j.end(); ++it) { const std::string key = prefix.empty() ? it.key() : prefix + "." + it.key(); const nlohmann::json& v = it.value(); + /* Retain otherwise invisible Quark weight overrides so import validation can reject + * null/empty schemes instead of accidentally inheriting global MXFP4 packing. */ + if (key.rfind("quantization_config.layer_quant_config.", 0) == 0 && + it.key() == "weight" && (v.is_null() || (v.is_object() && v.empty()))) { + out->kv(key, v.is_null() ? "null" : "{}"); + continue; + } if (v.is_object()) flatten_json(v, key, out); else if (v.is_boolean()) out->kv(key, v.get() ? "1" : "0"); else if (v.is_number_integer()) out->kv(key, fmt("%lld", (long long)v.get())); @@ -230,9 +237,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) { m.n_ff = gi("intermediate_size", gi("moe_intermediate_size", 0)); m.n_vocab = gi("vocab_size", 0); m.n_ctx_train = gi("max_position_embeddings", 0); - m.n_expert = gi("num_experts", gi("num_local_experts", 0)); + m.n_expert = gi("num_experts", gi("num_local_experts", gi("n_routed_experts", 0))); m.n_expert_used = gi("num_experts_per_tok", 0); - m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0; + m.n_expert_shared = gi("n_shared_experts", gi("num_shared_experts", + gi("shared_expert_intermediate_size", 0) ? 1 : 0)); m.rms_eps = (float)gf("rms_norm_eps", gf("norm_eps", 1e-6)); /* LFM2: norm_eps */ m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0)); /* Rotary scaling stays in the free-form keys with its type (arch/common/rad_arch.h, @@ -703,13 +711,45 @@ void Checkpoint::detect_import() { else import_why_ = "GPTQ's checkpoint_format '" + cf + "' is not one this reads; 'gptq' is"; } else if (qm == "quark") { const std::string w = "global_quant_config.weight."; + /* Quark can retain block-FP8 attention/MTP weights alongside MXFP4 experts. + * Validate every override rather than rejecting every nonempty override map. + * Keep a lookup here: large exports have tens of thousands of flattened fields. */ + std::map fields; + for (size_t i = 0; i < meta_.keys.size(); ++i) fields.emplace(meta_.keys[i], meta_.vals[i]); + const std::string lp = "quantization_config.layer_quant_config."; + const std::string suffix = ".weight.dtype"; + std::map layers; + for (const auto& [k, v] : fields) + if (k.rfind(lp, 0) == 0 && k.size() > lp.size() + suffix.size() && + k.compare(k.size() - suffix.size(), suffix.size(), suffix) == 0) + layers.emplace(k.substr(0, k.size() - suffix.size()) + ".", true); + bool overrides_ok = true; + for (const auto& [layer, unused] : layers) { + auto f = [&](const char* key) { + auto it = fields.find(layer + "weight." + key); + return it == fields.end() ? std::string() : it->second; + }; + const bool mx = f("dtype") == "fp4" && f("qscheme") == "per_group" && + f("group_size") == "32" && f("scale_format") == "e8m0"; + const bool fp8 = f("dtype") == "fp8_e4m3" && f("qscheme") == "per_block" && + f("block_size") == "128 128"; + overrides_ok = overrides_ok && (mx || fp8); + } + /* A partial/null weight override must not disappear merely because it has no dtype. */ + for (const auto& [k, v] : fields) if (k.rfind(lp, 0) == 0) { + bool covered = false; + for (size_t dot = k.rfind('.'); dot != std::string::npos; + dot = dot ? k.rfind('.', dot - 1) : std::string::npos) + if (layers.count(k.substr(0, dot + 1))) { covered = true; break; } + overrides_ok = overrides_ok && covered; + } if (qc(w + "dtype") == "fp4" && qc(w + "qscheme") == "per_group" && qc(w + "group_size") == "32" && qc(w + "scale_format") == "e8m0" && - !any_under("layer_quant_config.") && !any_under("layer_type_quant_config.")) + overrides_ok && !any_under("layer_type_quant_config.")) import_ = Import::QuarkMx; else - import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) " - "throughout, which is the one this reads"; + import_why_ = "Quark requires global MXFP4 (fp4, per_group 32, e8m0 scales), with " + "only MXFP4 or 128x128 E4M3 block-FP8 layer overrides"; } else if (qm == "compressed-tensors") { /* compressed-tensors states each scheme as a config group with a format. Three are read: * pack-quantized grouped int4, symmetric (e.g. Google's Gemma 4 QAT w4a16-ct) diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index e1cd643e..ffa42b6c 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -128,6 +128,20 @@ TEST(the_metadata_names_the_architecture_and_the_quantisation) { CHECK_EQ(ck.dir(), dir); } +TEST(routed_expert_metadata_accepts_the_deepseek_and_glm_config_spellings) { + const std::string dir = write_checkpoint({ bf16("x", {2, 2}, 0) }, + "{\"model_type\":\"glm5_next\",\"text_config\":{\"hidden_size\":4096," + "\"num_attention_heads\":64,\"head_dim\":0,\"n_routed_experts\":288," + "\"n_shared_experts\":1,\"num_experts_per_tok\":8}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK_EQ(ck.meta().arch, std::string("glm5next")); + CHECK_EQ(ck.meta().m.n_expert, (int64_t)288); + CHECK_EQ(ck.meta().m.n_expert_shared, (int64_t)1); + CHECK_EQ(ck.meta().m.n_expert_used, (int64_t)8); + CHECK_EQ(ck.meta().m.head_dim, (int64_t)0); +} + /* The descriptor derives from quant_method and fmt whoever set them, including rad-convert's * --set: a bf16 checkpoint converted to block fp8 states that format and selects the fp8 plugin, * so the container never names one format and selects another's plugin. */ @@ -613,6 +627,75 @@ TEST(a_quark_mxfp4_weight_is_its_codes_and_exponents) { CHECK(w.trivial && rad_enc_is(&w.enc, "plain")); } +/* GLM-5.3-Flash's Quark export keeps excluded attention and MTP weights block-FP8, with F32 + * `_scale` companions. They multiply the codes; reading the global MXFP4 scheme into these + * weights, or overlooking the scale because it is not called `_scale_inv`, corrupts the model. */ +TEST(quark_refuses_unsupported_or_incomplete_layer_weight_overrides) { + for (const char* override_config : { + "{\"p\":{\"weight\":{\"dtype\":\"fp8_e4m3\",\"qscheme\":\"per_block\",\"block_size\":[64,128]}}}", + "{\"p\":{\"weight\":{\"dtype\":\"int8\",\"qscheme\":\"per_block\",\"block_size\":[128,128]}}}", + "{\"p\":{\"weight\":null}}", + "{\"p\":{\"weight\":{\"dtype\":\"fp8_e4m3\",\"qscheme\":\"per_block\",\"block_size\":[128,128]}}," + "\"other\":{\"weight\":{\"qscheme\":\"per_block\"}}}" }) { + const std::string config = std::string("{\"quantization_config\":{\"quant_method\":\"quark\"," + "\"global_quant_config\":{\"weight\":{\"dtype\":\"fp4\",\"qscheme\":\"per_group\"," + "\"group_size\":32,\"scale_format\":\"e8m0\"}},\"layer_quant_config\":") + + override_config + "}}"; + const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, config.c_str()); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK(ck.imports() != Checkpoint::Import::QuarkMx); + CHECK(!ck.import_refusal().empty()); + } +} + +TEST(a_quark_checkpoint_preserves_excluded_block_fp8_weights) { + T s{ "p.weight_scale", "F32", { 2, 2 }, std::vector(4 * sizeof(float)) }; + for (int i = 0; i < 4; ++i) rad_store_f32(s.bytes.data(), RAD_F32, i, 0.25f * (i + 1)); + T bad = s; + bad.name = "bad.weight_scale"; + bad.shape = { 1, 4 }; /* same number of scales, wrong block geometry */ + const std::string dir = write_checkpoint( + { fp8("p.weight", { 256, 256 }), s, fp8("bad.weight", { 256, 256 }), bad, + bf16("norm.weight", { 4 }, 1.0f) }, + "{\"model_type\":\"glm5_next\",\"quantization_config\":{\"quant_method\":\"quark\"," + "\"global_quant_config\":{\"weight\":{\"dtype\":\"fp4\",\"qscheme\":\"per_group\"," + "\"group_size\":32,\"scale_format\":\"e8m0\"}}," + "\"layer_quant_config\":{\"p\":{\"weight\":{\"dtype\":\"fp8_e4m3\"," + "\"qscheme\":\"per_block\",\"block_size\":[128,128]}}}}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + REQUIRE(ck.imports() == Checkpoint::Import::QuarkMx); + Program prog; + prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" })); + prog.name_map.push_back(map("bad", RAD_MAP_COPY, { "bad.weight" })); + prog.name_map.push_back(map("norm", RAD_MAP_COPY, { "norm.weight" })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK); + REQUIRE(w.trivial); + REQUIRE_EQ(w.enc.n_planes, 2); + CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_F8E4M3); + CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_F32); + CHECK_EQ(w.enc.plane[1].block[0], (int64_t)128); + CHECK_EQ(w.enc.plane[1].block[1], (int64_t)128); + std::vector f(256); + for (int64_t r : { (int64_t)0, (int64_t)129 }) { + REQUIRE_EQ(ckpt_rows_f32(w, r, 1, f.data(), &why), RAD_OK); + for (int64_t c : { (int64_t)0, (int64_t)127, (int64_t)128, (int64_t)255 }) + CHECK_EQ(f[(size_t)c], ((float)((r * 256 + c) % 7) - 3.0f) * + (0.25f * (float)(r / 128 * 2 + c / 128 + 1))); + } + std::vector scales(s.bytes.size()); + REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 2, scales.data(), &why), RAD_OK); + CHECK_EQ(std::memcmp(scales.data(), s.bytes.data(), scales.size()), 0); + REQUIRE_EQ(ckpt_resolve(ck, prog, "bad", false, &w, &why), RAD_OK); + CHECK(!w.trivial); + CHECK(w.why.find("scale plane") != std::string::npos); + REQUIRE_EQ(ckpt_resolve(ck, prog, "norm", false, &w, &why), RAD_OK); + CHECK(w.trivial && rad_enc_is(&w.enc, "plain")); +} + /* A directory merging two checkpoints (a finetune's changed tensors beside links to every base * shard) holds some tensors in two shards. The index decides which copy is read; a name in two * shards that the index does not settle is refused, not read from whichever shard sorts first. */ From 2c67e93342150cf83fdcc20413d3c88e4ca2b76d Mon Sep 17 00:00:00 2001 From: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:45:09 +0200 Subject: [PATCH 056/152] engine: the one-sequence KV floor is the live plan's inverse, its state slots included The floor a KV pool must keep for one --max-model-len request came from a separate plan at max_seqs 1. A hybrid model's recurrent and conv slots are fixed per configured sequence and stay allocated while one request is active, so that plan undercounted and the pool it allowed could not hold max_ctx. The floor is now pool_mib_for_tokens over the real plan's groups. mem_test (hybrid_context_floor_accounts_for_all_configured_state_slots). --- core/engine_bringup.cpp | 19 +++++++------------ core/mem/vram_budget.h | 2 +- tests/mem_test.cpp | 25 +++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 0f84c216..55252355 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -1373,18 +1373,6 @@ int Engine::plan() { ngram_bytes = std::max(ngram_bytes, wf.ngram); ngram_device = ngram_device || wf.ngram_device; ngram_host = ngram_host || wf.ngram_host; - /* One --max-model-len sequence's cache: the least a KV pool can hold and still serve - * every acceptable request (configure_kv warns below it). --ngram-placement auto puts - * the table on the card only if the pool stays above it. */ - { - Config one = cfg_; - one.max_seqs = 1; - KVManager single; - if (single.plan_groups(r->program.kv_groups, one) == RAD_OK) { - kv_floor = std::max(kv_floor, single.ceiling(ctx)); - f.kv_one = single.ceiling(ctx); - } - } /* The staging region is sized only where the arena lends its top: without smaller * levels nothing returns it to the slab at decode, and a deterministic plan moves * nothing. */ @@ -1397,6 +1385,13 @@ int Engine::plan() { ck_slot += probe.checkpoint_bytes(); f.kv_ceiling = probe.ceiling(ctx); f.kv_fixed = probe.fixed_bytes(); + /* One --max-model-len sequence's pool, as the inverse of the real plan: its + * recurrent and conv slots stay allocated with one request active, which a + * separate one-sequence plan would leave out. */ + const int64_t MiB = 1ll << 20; + const int64_t need = probe.pool_mib_for_tokens(ctx, (f.kv_ceiling + MiB - 1) / MiB); + if (need >= 0) f.kv_one = need * MiB; + kv_floor = std::max(kv_floor, f.kv_one); } /* The step batch's device staging, reserved by the scheduler after this split: block * tables for max_seqs sequences at max_ctx, media staging for max_tok encoder rows. diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index 55f8cc46..48e548c8 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -75,7 +75,7 @@ struct VramFacts { /* Experts the pinned host pool cannot hold, plus the slab's spare slots: the expert slab's * floor when the cache lends (expert_vram_floor, core/place/planner.h). */ int64_t expert_floor = 0; - int64_t kv_one = 0; /* the cache for one --max-model-len sequence: the least it may get */ + int64_t kv_one = 0; /* all configured fixed state plus pages for one full-length context */ /* The cache lends idle blocks to the expert slab: a placement that moves units (expert_tiered * or auto), not --deterministic, on a device with virtual memory management. A lending cache * can be sized for what live requests could need; a non-lending one would hold it empty. */ diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index e2eeb1bf..d5eca921 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -385,6 +385,31 @@ TEST(the_cache_keeps_one_full_length_sequence_even_against_the_expert_floor) { CHECK_EQ(b2.experts, b2.elastic - g.kv_ceiling); } +/* A hybrid model's recurrent and conv slots stay allocated with one request active, so the + * one-sequence floor is the inverse of the live plan, not a separate one-sequence plan: that plan + * drops the fixed state and falls short of max_ctx. */ +TEST(hybrid_context_floor_accounts_for_all_configured_state_slots) { + Config c = small_config(); + c.max_seqs = 4; + c.max_ctx = 32768; + c.checkpoint_slots = 0; + auto groups = hybrid_groups(); + KVManager actual, single; + CHECK_OK(actual.plan_groups(groups, c)); + Config one = c; + one.max_seqs = 1; + CHECK_OK(single.plan_groups(groups, one)); + // A one-sequence declaration drops fixed state that the live four-slot plan owns. + CHECK(actual.paged_tokens(single.ceiling(c.max_ctx)) < c.max_ctx); + constexpr int64_t MiB = 1ll << 20; + const int64_t ceiling_mib = (actual.ceiling(c.max_ctx) + MiB - 1) / MiB; + const int64_t floor_mib = actual.pool_mib_for_tokens(c.max_ctx, ceiling_mib); + CHECK(floor_mib > 0); + CHECK(actual.paged_tokens(floor_mib * MiB) >= c.max_ctx); + CHECK((floor_mib - 1) * MiB < actual.fixed_bytes() || + actual.paged_tokens((floor_mib - 1) * MiB) < c.max_ctx); +} + TEST(neither_side_is_given_more_than_it_could_use) { /* A model that fits: 4 GiB of experts and a cache that can address 1.2 GiB cannot use a * 32 GiB card, so the remainder is reported unusable rather than allocated to an idle pool. */ From 9e0e28315d167a0b7e593953a339f75469b647f6 Mon Sep 17 00:00:00 2001 From: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:45:29 +0200 Subject: [PATCH 057/152] vram_budget: the prefill staging region is paid by expert residency before the cache With a lending cache the staging region (two buffers of one layer's off-card experts) always came out of the cache, which left a large-context MoE model short of its configured coverage. Expert residency above the host pool's floor now pays first; the cache pays only when the experts are at their floor, and an expert with no other home is never evicted for it. The startup report names whichever paid. mem_test (prefill_staging_*). --- core/mem/vram_budget.cpp | 16 ++++++++++---- core/mem/vram_budget.h | 5 +++-- tests/mem_test.cpp | 46 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 6 deletions(-) diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 5e613167..844cca7e 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -190,21 +190,29 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg * * The share is what the slab alone leaves off, the most a step can see: KV and arena loans only * add residency. A layer larger than its share stages what fits and streams the rest. */ + bool stage_from_experts = false; if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" && cfg.placement != "layer_offload") { const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling; const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT; if (b.lends) { - /* With a lending cache the cache pays: experts are at their floor, and the region is - * lent to the slab in small steps, as the cache would have lent it. */ - if (b.kv - 2 * one >= kv_one) { + /* Expert residency above its host-pool floor pays first, so the cache keeps its + * configured coverage; otherwise the cache pays. Either way the region is lent to the + * slab in small steps. */ + if (b.experts - 2 * one >= b.expert_floor) { + b.stage = 2 * one; + b.experts -= b.stage; + stage_from_experts = true; + b.weights = b.statics + b.experts; + } else if (b.kv - 2 * one >= kv_one) { b.stage = 2 * one; b.kv -= b.stage; } } else if (2 * one < b.experts) { b.stage = 2 * one; b.experts -= b.stage; + stage_from_experts = true; b.weights = b.statics + b.experts; } } @@ -312,7 +320,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg "non-resident experts,\n" " at the arena's top and lent back to the " "slab while steps are small\n", humanb(b.stage).c_str(), - b.lends ? "cache" : "experts").c_str() + stage_from_experts ? "experts" : "cache").c_str() : "", humanb(cfg.vram_weights_mib * kMiB).c_str(), "static + experts", humanb(cfg.vram_kv_mib * kMiB).c_str(), "the cache's share", diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index 48e548c8..21f80092 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -104,8 +104,9 @@ struct VramBudget { int64_t experts = 0, kv = 0; /* the two shares, each capped at its ceiling */ int64_t unusable = 0; /* elastic neither side could take -- both were full */ /* Prefill staging region: two buffers, each one layer's share of the experts left off the - * card, appended to the top of the activation arena (core/place/stager.h). Zero when every - * expert is resident or the placement cannot move any. */ + * card, funded by cache slack or expert residency above the host-pool floor, appended to the + * top of the activation arena (core/place/stager.h). Zero when every expert is resident or the + * placement cannot move any. */ int64_t stage = 0; int64_t weights = 0; /* statics + experts: what vram_weights is set to */ std::string report; /* the block the engine prints at startup */ diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index d5eca921..31279fcd 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -385,6 +385,52 @@ TEST(the_cache_keeps_one_full_length_sequence_even_against_the_expert_floor) { CHECK_EQ(b2.experts, b2.elastic - g.kv_ceiling); } +/* With a lending cache at its floor, the prefill staging region is paid by expert residency + * above the host pool's floor, and never by an expert that has no other home. */ +TEST(prefill_staging_can_borrow_expert_slack_when_the_cache_is_small) { + VramFacts f = big_moe_facts(); + f.lends = true; + f.kv_one = f.kv_ceiling = 64LL << 20; + f.expert_floor = 16LL << 30; + f.expert_layer_max = 2LL << 30; + Config c = derive_config(); + VramBudget b; + CHECK_OK(vram_budget_resolve(c, { f }, &b)); + CHECK(b.stage > 0); + CHECK(b.report.find("out of the experts") != std::string::npos); + CHECK_EQ(b.kv, f.kv_one); + CHECK(b.experts >= f.expert_floor); + CHECK_EQ(b.weights, b.statics + b.experts); + CHECK_EQ(b.experts + b.kv + b.stage, b.elastic); + + // With no host-pool slack, staging must not evict an expert that has no other home. + f.expert_floor = b.elastic - f.kv_one; + Config tight = derive_config(); + VramBudget no_ring; + CHECK_OK(vram_budget_resolve(tight, { f }, &no_ring)); + CHECK_EQ(no_ring.stage, 0ll); + CHECK_EQ(no_ring.kv, f.kv_one); + CHECK_EQ(no_ring.experts, f.expert_floor); +} + +/* When experts can pay, the staging region leaves the cache at its full coverage. */ +TEST(prefill_staging_preserves_cache_coverage_when_experts_can_pay) { + VramFacts f = big_moe_facts(); + f.lends = true; + f.kv_ceiling = 2LL << 30; + f.kv_one = 768LL << 20; + f.expert_floor = 16LL << 30; + f.expert_layer_max = 2LL << 30; + Config c = derive_config(); + VramBudget b; + CHECK_OK(vram_budget_resolve(c, { f }, &b)); + CHECK(b.stage > 0); + CHECK_EQ(b.kv, f.kv_ceiling); + CHECK(b.experts >= f.expert_floor); + CHECK(b.report.find("out of the experts") != std::string::npos); + CHECK_EQ(b.experts + b.kv + b.stage, b.elastic); +} + /* A hybrid model's recurrent and conv slots stay allocated with one request active, so the * one-sequence floor is the inverse of the live plan, not a separate one-sequence plan: that plan * drops the fixed state and falls short of max_ctx. */ From c8311068d017900ea7101eaf2fe9c8ce0b7fbf0b Mon Sep 17 00:00:00 2001 From: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:04:36 +0200 Subject: [PATCH 058/152] qsa_select: `signed` -- a ranking for indexers whose scores can be negative qsa_select ranks max(score, 0) and treats a score at or below -1e30 as dead: QSA's block scores are sums of relus, so the clamp changes nothing there. GLM-5.3's DSA indexer weights its heads by signed gates, and its block scores can be negative; ranked through the clamp, every negative block ties at zero and the selection is wrong. `signed` 1 ranks finite scores as they are (-0 tying +0) and treats nonfinite ones as dead; absent or 0 is the ranking as it was. libref, libavx and libr4d take it together, since the three declare one schema. docs/OPS.md; tests/r4d_emu/test_qsa.cpp runs both rankings against the reference. --- docs/OPS.md | 10 +++- libavx/avx_qsa.cpp | 67 +++++++++++++++++--------- libavx/avx_registry.cpp | 2 +- libr4d/r4d_qsa_select_bf16.hip | 88 +++++++++++++++++++++++----------- libr4d/r4d_rows.cpp | 7 ++- libref/ref_qsa.cpp | 11 +++-- libref/ref_registry.cpp | 2 +- tests/r4d_emu/test_qsa.cpp | 79 +++++++++++++++++++++++++----- 8 files changed, 197 insertions(+), 69 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index f5cd2275..98a3ef56 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2038,7 +2038,7 @@ order, not a slow one. |---|---|---| | `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `k`, `w`w, `page`?, `pos`? → `out` | | `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` | -| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` | +| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` `signed`/opt | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` | | `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` | | `qsa_work` | `M`(range) `n` `ratio` `ring` `seqs` `work` `dtype` | `k`, `pos`, `cu`, `state`, `sidx`, `bt`, `rope`? → `stage`, `page`, `bpos`, `nc` | @@ -2151,6 +2151,14 @@ with the partial page appended. - **Ties break to the lower block index, through a prefix count.** A block score is a sum of relus over a shared grid, so equal scores are ordinary, and a top-k placed by whichever atomic landed first would not reproduce across runs; the tree checks generated text byte for byte. +- **`signed` chooses the ranking.** Absent or `0`, a block is live when its page id is `>= 0` and + its score `> -1e30`, and ranks by `max(score, 0)`: QSA's scores are sums of relus, so the clamp + changes no ranking there. `1` is for indexers whose scores can be negative (GLM's DSA weights + its heads by signed gates): a block is live when its page id is `>= 0` and its score finite, and + ranks by the score itself, `-0` tying `+0`. The two rankings pick different sets whenever a live + score is negative, so an architecture states the one its indexer needs. libr4d's + `qsa_select_bf16` serves both; the signed ranking keys a score by its float's total order over + all 32 bits. - **`seqused` is why QSA needs no new attention kernel.** `attn_paged` takes its block table and per-sequence length as ordinary operands, so the sparse attention is that op issued with `sel` in place of the sequence's table and this number in place of its length. The KV it walks is `nsel` diff --git a/libavx/avx_qsa.cpp b/libavx/avx_qsa.cpp index fb869202..ce9ab5d4 100644 --- a/libavx/avx_qsa.cpp +++ b/libavx/avx_qsa.cpp @@ -12,9 +12,10 @@ * The keys are read once per tile, which at decode is once per sequence. The dots * sum in vector order (libref's order at the scalar level); the heads in order. * qsa_select Linear time per row: an order key per block (the bits of max(score, 0) plus one, - * 0 for a dead block), a histogram of the keys' top bits, an exact select among the - * keys in the bin that holds the topk-th largest, and one emitting pass in block - * order. The ids match libref's byte for byte. + * 0 for a dead block; with `signed` the float's total order over all 32 bits), a + * histogram of the keys' top bits, an exact select among the keys in the bin that + * holds the topk-th largest, and one emitting pass in block order. The ids match + * libref's byte for byte. * qsa_tail_store, qsa_work Row copies through f32, as libref copies, so every value lands * with the bits libref's would. * dflash_conv Channels across lanes, in blocks of columns that walk their rows, so a block's base @@ -290,25 +291,29 @@ AVX_KERNEL(qsa_score) { /* ================================================================== qsa_select */ namespace { -/* Bins of the first selection pass: the top 10 bits of a key, which is below 2^31. */ -enum { kBins = 1024, kBinShift = 21 }; +/* Bins of the first selection pass: the top 10 bits of a key, which is below 2^31 (a signed + * key uses all 32 bits, so its bins sit one bit higher). */ +enum { kBins = 1024, kBinShift = 21, kBinShiftSigned = 22 }; struct SelJob { const RadTensor *sc, *bt, *nc, *po, *se, *ns, *su; const int64_t* seq; int64_t nb, topk, ratio; int64_t s_rs, s_cs, bt_rs, bt_cs, o_rs, o_cs; + bool sgn; /* the `signed` order */ }; /* The order key of each of the row's first `n` blocks: bits(max(score, 0)) + 1 for a live block * (page id >= 0 and score > -1e30), 0 for a dead one. Non-negative floats order as their bits, so * keys order as libref's values; max(score, 0) maps -0 to +0 as libref's `v > 0 ? v : 0` does. - * Returns the live count. */ + * The signed order makes a block with a finite score live and keys it by the float's total order + * (sign bit flipped for a positive value, every bit for a negative one), -0 keyed as +0, so keys + * order as libref's signed values; no finite score keys to 0. Returns the live count. */ static int64_t order_keys(const SelJob& j, int64_t m, int64_t s, int64_t n, uint32_t* key) { const int64_t sb = m * j.s_rs, bb = s * j.bt_rs; int64_t live = 0, b = 0; #if AVX_LEVEL >= 2 - if (j.sc->dtype == RAD_F32 && j.s_cs == 1 && j.bt->dtype == RAD_I32 && j.bt_cs == 1) { + if (!j.sgn && j.sc->dtype == RAD_F32 && j.s_cs == 1 && j.bt->dtype == RAD_I32 && j.bt_cs == 1) { const float* v = (const float*)j.sc->data + sb; const int32_t* p = (const int32_t*)j.bt->data + bb; #if AVX_LEVEL == 3 @@ -341,6 +346,17 @@ static int64_t order_keys(const SelJob& j, int64_t m, int64_t s, int64_t n, uint #endif } #endif + if (j.sgn) { + for (; b < n; ++b) { + const float v = ldt(j.sc, sb + b * j.s_cs); + if (ldi(j.bt, bb + b * j.bt_cs) < 0 || !std::isfinite(v)) { key[b] = 0; continue; } + uint32_t u = 0; + if (v != 0.0f) std::memcpy(&u, &v, 4); + key[b] = (u & 0x80000000u) ? ~u : (u ^ 0x80000000u); + ++live; + } + return live; + } for (; b < n; ++b) { const float v = ldt(j.sc, sb + b * j.s_cs); if (ldi(j.bt, bb + b * j.bt_cs) < 0 || !(v > -1e30f)) { key[b] = 0; continue; } @@ -355,19 +371,21 @@ static int64_t order_keys(const SelJob& j, int64_t m, int64_t s, int64_t n, uint /* The topk-th largest key of a row with more than `topk` live keys, and how many keys are above * it. A histogram of the top bits finds the bin holding it; the keys in that bin are gathered and - * the exact value taken among them. `cand` holds up to n keys. */ -static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, uint32_t* hist, + * the exact value taken among them. `cand` holds up to n keys. `sgn`: the keys are signed-order + * keys, which use all 32 bits. */ +static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, bool sgn, uint32_t* hist, uint32_t* cand, int64_t* above_out) { + const int shift = sgn ? (int)kBinShiftSigned : (int)kBinShift; /* Four interleaved histograms, so runs of keys in one bin do not serialise on one counter. */ std::memset(hist, 0, 4 * kBins * sizeof(uint32_t)); int64_t b = 0; for (; b + 4 <= n; b += 4) { - ++hist[0 * kBins + (key[b] >> kBinShift)]; - ++hist[1 * kBins + (key[b + 1] >> kBinShift)]; - ++hist[2 * kBins + (key[b + 2] >> kBinShift)]; - ++hist[3 * kBins + (key[b + 3] >> kBinShift)]; + ++hist[0 * kBins + (key[b] >> shift)]; + ++hist[1 * kBins + (key[b + 1] >> shift)]; + ++hist[2 * kBins + (key[b + 2] >> shift)]; + ++hist[3 * kBins + (key[b + 3] >> shift)]; } - for (; b < n; ++b) ++hist[key[b] >> kBinShift]; + for (; b < n; ++b) ++hist[key[b] >> shift]; for (int i = 0; i < kBins; ++i) hist[i] += hist[kBins + i] + hist[2 * kBins + i] + hist[3 * kBins + i]; /* Bin 0 is never counted: it is the last one left, and holds the dead keys (0) beside the @@ -380,8 +398,8 @@ static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, uint32_t } /* The keys of the bin, i.e. in [lo, hi], with key 0 (dead) left out of bin 0. Few keys fall in * one bin, so the vector forms test a vector and walk only its hits. */ - const uint32_t lo = std::max((uint32_t)bin << kBinShift, 1u); - const uint32_t hi = (((uint32_t)bin + 1u) << kBinShift) - 1u; + const uint32_t lo = std::max((uint32_t)bin << shift, 1u); + const uint32_t hi = (((uint32_t)bin + 1u) << shift) - 1u; int64_t nc = 0; b = 0; #if AVX_LEVEL == 3 @@ -393,9 +411,10 @@ static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, uint32_t nc += __builtin_popcount((unsigned)in); } #elif AVX_LEVEL == 2 - /* Keys are below 2^31, so the signed compares order them. */ + /* Keys are below 2^31, so the signed compares order them; signed-order keys take the scalar + * loop. */ const __m256i vlo = _mm256_set1_epi32((int)lo - 1), vhi = _mm256_set1_epi32((int)hi + 1); - for (; b + 8 <= n; b += 8) { + for (; !sgn && b + 8 <= n; b += 8) { const __m256i k = _mm256_loadu_si256((const __m256i*)(key + b)); const __m256i in = _mm256_and_si256(_mm256_cmpgt_epi32(k, vlo), _mm256_cmpgt_epi32(vhi, k)); unsigned hit = (unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(in)); @@ -439,9 +458,10 @@ static void emit(const SelJob& j, const uint32_t* key, int64_t n, int64_t s, uin } } #elif AVX_LEVEL == 2 - /* Keys are below 2^31, so the signed compare orders them. */ + /* Keys are below 2^31, so the signed compare orders them; signed-order keys take the scalar + * loop. */ const __m256i vt = _mm256_set1_epi32((int)thr - 1); - for (; b + 8 <= n && (og < gt || ot < ties); b += 8) { + for (; !j.sgn && b + 8 <= n && (og < gt || ot < ties); b += 8) { const __m256i k = _mm256_loadu_si256((const __m256i*)(key + b)); unsigned hit = (unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(_mm256_cmpgt_epi32(k, vt))); while (hit) { @@ -470,7 +490,7 @@ static void select_row(const SelJob& j, int64_t m) { } else { uint32_t* cand = (uint32_t*)scratch_f32_c((size_t)n); int64_t gt = 0; - const uint32_t thr = threshold(key, n, topk, hist, cand, >); + const uint32_t thr = threshold(key, n, topk, j.sgn, hist, cand, >); emit(j, key, n, s, thr, gt, topk - gt, row); out = topk; } @@ -496,7 +516,7 @@ static void select_row(const SelJob& j, int64_t m) { /* ------------------------------------------------------------------ qsa_select */ /* The page-id table the sparse attention reads (docs/OPS.md): over the query's complete blocks * n = min(nc[seq], (pos + 1) / ratio, width), the live ones (page id >= 0, score > -1e30) ranked - * by max(score, 0). All of them when `topk` or fewer are live, else every block above the topk-th + * by max(score, 0), or with `signed` 1 those with a finite score, ranked by it. All of them when `topk` or fewer are live, else every block above the topk-th * largest value in block order, then the blocks equal to it in block order until topk are taken. * The partial page bt[n] follows when (pos + 1) % ratio != 0 and n < width, and -1 pads the row * to topk + 1. A row no sequence holds reads sequence 0, as libref's and libr4d's do. */ @@ -505,7 +525,9 @@ AVX_KERNEL(qsa_select) { const RadTensor *sc = &a->t[0], *bt = &a->t[1], *nc = &a->t[2], *po = &a->t[3]; const RadTensor *cu = &a->t[4], *se = &a->t[5], *ns = &a->t[6], *su = &a->t[7]; const int64_t topk = p_int(a, "topk", 0), ratio = p_int(a, "ratio", 0); + const int64_t sgn = p_int(a, "signed", 0); if (topk <= 0 || ratio <= 0) return RAD_E_SHAPE; + if (sgn != 0 && sgn != 1) return RAD_E_INVAL; if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return RAD_E_SHAPE; const int64_t M = sc->shape[0], nb = std::min(bt->shape[1], sc->shape[1]); const int64_t n_seq = numel(cu) - 1; @@ -526,6 +548,7 @@ AVX_KERNEL(qsa_select) { j.s_rs = sc->stride[0]; j.s_cs = sc->stride[1]; j.bt_rs = bt->stride[0]; j.bt_cs = bt->stride[1]; j.o_rs = se->stride[0]; j.o_cs = se->stride[1]; + j.sgn = sgn != 0; AVX_PARALLEL_FOR_IF(M * nb >= AVX_PAR_MIN && M > 1) for (int64_t m = 0; m < M; ++m) select_row(j, m); return RAD_OK; diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index edb6ea5a..3c1e9a76 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -305,7 +305,7 @@ static const RadParamSpec pQsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads") static const RadOperandSpec oQsaScore[] = { OPD("q"), OPD("bk"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") }; static const RadParamSpec pQsaSelect[] = { P_INT("M"), P_INT("blocks"), P_INT("topk"), - P_INT("ratio"), P_INT("seqs") }; + P_INT("ratio"), P_INT("seqs"), P_INTO("signed") }; static const RadOperandSpec oQsaSelect[] = { OPD("score"), OPD("bt"), OPD("nc"), OPD("pos"), OPD("cu"), OUT("sel"), OUT("nsel"), OUT("seqused") }; static const RadParamSpec pQsaTailStore[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"), diff --git a/libr4d/r4d_qsa_select_bf16.hip b/libr4d/r4d_qsa_select_bf16.hip index c0b5154d..aeb3c285 100644 --- a/libr4d/r4d_qsa_select_bf16.hip +++ b/libr4d/r4d_qsa_select_bf16.hip @@ -65,15 +65,28 @@ static inline int lds_cap_of() { return v; } +/* The order key, by the op's `signed` parameter: the unsigned order (Signed = false, the + * default) or the signed one. Key 0 means "no block" in both. */ +template __device__ __forceinline__ uint32_t keyof(float v, int page); + /* Order key. Scores are >= 0 or -inf, and non-negative float bit patterns order as unsigned. * `+1` keeps a live score of exactly zero above key 0, which means "no block". The clamp is a * select, not fmaxf: fmaxf(-0.0f, 0.0f) may return -0.0f, whose sign bit would rank it above * every positive score. */ -__device__ __forceinline__ uint32_t keyof(float v, int page) { +template <> __device__ __forceinline__ uint32_t keyof(float v, int page) { if (page < 0 || !(v > -1e30f)) return 0u; return __float_as_uint(v > 0.0f ? v : 0.0f) + 1u; } +/* Signed order key, for indexers whose scores can be negative (GLM's head gates): the float's + * total order over all 32 bits. Absent pages and nonfinite scores are key 0, which no finite + * score maps to (only NaN bit patterns would); both signed zeros map to one key, so they tie. */ +template <> __device__ __forceinline__ uint32_t keyof(float v, int page) { + if (page < 0 || !__builtin_isfinite(v)) return 0u; + const uint32_t bits = v == 0 ? 0u : __float_as_uint(v); + return (bits & 0x80000000u) ? ~bits : (bits ^ 0x80000000u); +} + /* Scans run in registers on DPP (five steps per wave, r4d_common.h); only wave totals go through * LDS, instead of step-doubling LDS rounds with barriers that wait on up to 32 waves. * @@ -115,6 +128,7 @@ __device__ __forceinline__ void counts_before(const uint32_t* wsum, int lane, in * block table and complete-block count. The per-query bound is (pos + 1) / ratio: block b is * entirely in the query's past when b * ratio + ratio - 1 <= pos. At decode this equals the * sequence's complete count. */ +template __global__ __launch_bounds__(kThreads) void qsa_select_kernel( const float* __restrict__ score, const int32_t* __restrict__ bt, const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, @@ -153,7 +167,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( if (cached) { for (int b0 = 0; b0 < n; b0 += kThreads) { const int b = b0 + t; - if (b < n) sh_key[b] = keyof(sc[b], tb[b]); + if (b < n) sh_key[b] = keyof(sc[b], tb[b]); } __syncthreads(); } @@ -168,7 +182,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( __syncthreads(); const uint32_t mask = (shift == 24) ? 0u : (0xFFFFFFFFu << (shift + 8)); for (int b = t; b < n; b += kThreads) { - const uint32_t k = cached ? sh_key[b] : keyof(sc[b], tb[b]); + const uint32_t k = cached ? sh_key[b] : keyof(sc[b], tb[b]); if (k != 0u && (k & mask) == (fixed & mask)) atomicAdd(&hist[(k >> shift) & 255u], 1u); } @@ -214,7 +228,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( for (int b0 = 0; b0 < n; b0 += kThreads) { const int b = b0 + t; uint32_t k = 0; - if (b < n) k = cached ? sh_key[b] : keyof(sc[b], tb[b]); + if (b < n) k = cached ? sh_key[b] : keyof(sc[b], tb[b]); const bool hi = k != 0u && (n <= topk || k > T); const bool eq = k != 0u && n > topk && k == T; @@ -297,7 +311,14 @@ __global__ __launch_bounds__(kThreads) void qsa_select_kernel( * count) does not depend on the digit split, and the emit is the same. r4d_selftest compares the * two byte for byte. */ constexpr int kWideBits = 12; /* the first digit */ -constexpr int kWideShift = 31 - kWideBits; /* a key's bit 31 is clear: see keyof */ +/* The first digit's shift, by key order. */ +template struct WideKey; +template <> struct WideKey { + static constexpr int kWideShift = 31 - kWideBits; /* a key's bit 31 is clear: see keyof */ +}; +template <> struct WideKey { + static constexpr int kWideShift = 32 - kWideBits; /* the signed key uses all 32 bits */ +}; constexpr int kWideBins = 1 << kWideBits; constexpr int kWideCand = kWideBins - kBins; /* keys the second pass may collect */ constexpr int kWidePer = kWideBins / kThreads; /* first-digit bins a thread scans */ @@ -377,6 +398,7 @@ __device__ __forceinline__ void lds_kth(const uint32_t* keys, int cnt, uint32_t *need = want; } +template __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( const float* __restrict__ score, const int32_t* __restrict__ bt, const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, @@ -402,6 +424,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( const int m = blockIdx.x; const int t = threadIdx.x; const int lane = t & (kWave - 1), wave = t >> 5; + constexpr int kWideShift = WideKey::kWideShift; if (t == 0) sh_seq = 0; __syncthreads(); @@ -426,7 +449,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( for (int i = t; i < kSamp; i += kThreads) { const int r = i / kSampRun, j = i % kSampRun; const long b = (long)r * (n - kSampRun) / (kSampRuns - 1) + j; - samp[i] = keyof(sc[b], tb[b]); + samp[i] = keyof(sc[b], tb[b]); } __syncthreads(); uint32_t ms = (uint32_t)(((uint64_t)topk * 2u * kSamp + (uint64_t)n - 1u) / (uint64_t)n) + 8u; @@ -448,14 +471,14 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( if (vec && bb + kPer <= n) { const float4 s0 = *(const float4*)(sc + bb), s1 = *(const float4*)(sc + bb + 4); const int4 p0 = *(const int4*)(tb + bb), p1 = *(const int4*)(tb + bb + 4); - kk[0] = keyof(s0.x, p0.x); kk[1] = keyof(s0.y, p0.y); - kk[2] = keyof(s0.z, p0.z); kk[3] = keyof(s0.w, p0.w); - kk[4] = keyof(s1.x, p1.x); kk[5] = keyof(s1.y, p1.y); - kk[6] = keyof(s1.z, p1.z); kk[7] = keyof(s1.w, p1.w); + kk[0] = keyof(s0.x, p0.x); kk[1] = keyof(s0.y, p0.y); + kk[2] = keyof(s0.z, p0.z); kk[3] = keyof(s0.w, p0.w); + kk[4] = keyof(s1.x, p1.x); kk[5] = keyof(s1.y, p1.y); + kk[6] = keyof(s1.z, p1.z); kk[7] = keyof(s1.w, p1.w); } else { #pragma unroll for (int e = 0; e < kPer; ++e) - kk[e] = bb + e < n ? keyof(sc[bb + e], tb[bb + e]) : 0u; + kk[e] = bb + e < n ? keyof(sc[bb + e], tb[bb + e]) : 0u; } uint32_t mine = 0; #pragma unroll @@ -514,7 +537,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( for (int i = t; i < kWideBins; i += kThreads) wide[i] = 0; __syncthreads(); for (int b = t; b < n; b += kThreads) { - const uint32_t k = keyof(sc[b], tb[b]); + const uint32_t k = keyof(sc[b], tb[b]); if (k != 0u) atomicAdd(&wide[k >> kWideShift], 1u); } __syncthreads(); @@ -565,7 +588,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( uint32_t n_in = 0; for (int b0 = 0; b0 < n; b0 += kThreads) { const int b = b0 + t; - const uint32_t k = b < n ? keyof(sc[b], tb[b]) : 0u; + const uint32_t k = b < n ? keyof(sc[b], tb[b]) : 0u; const bool abv = k != 0u && (k >> kWideShift) > B; const bool inb = k != 0u && (k >> kWideShift) == B; const unsigned long long ma = __ballot(abv), mi = __ballot(inb); @@ -594,7 +617,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( __syncthreads(); } else if (inlds) { for (int b = t; b < n; b += kThreads) { - const uint32_t k = keyof(sc[b], tb[b]); + const uint32_t k = keyof(sc[b], tb[b]); if (k != 0u && (k >> kWideShift) == B) cand[atomicAdd(&sh_cnt, 1u)] = k; } __syncthreads(); @@ -602,7 +625,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( const int ncand = (merged || inlds) ? (int)sh_cnt : n; const uint32_t* const keys = merged ? mkey : cand; - /* ---- the other 19 bits: digits of 8, 8 and 3. */ + /* ---- the other 19 bits: digits of 8, 8 and 3 (20 bits and 8, 8, 4 when signed). */ const int shifts[3] = { kWideShift - 8, kWideShift - 16, 0 }; const int widths[3] = { 8, 8, kWideShift - 16 }; #pragma unroll @@ -613,7 +636,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( for (int i = t; i < kBins; i += kThreads) hist[i] = 0; __syncthreads(); for (int i = t; i < ncand; i += kThreads) { - const uint32_t k = (merged || inlds) ? keys[i] : keyof(sc[i], tb[i]); + const uint32_t k = (merged || inlds) ? keys[i] : keyof(sc[i], tb[i]); if (k != 0u && (k & hm) == (fixed & hm)) atomicAdd(&hist[(k >> shift) & dm], 1u); } __syncthreads(); @@ -687,7 +710,7 @@ __global__ __launch_bounds__(kThreads) void qsa_select_wide_kernel( for (int b0 = 0; b0 < ((merged || sampled) ? 0 : n); b0 += kThreads) { const int b = b0 + t; uint32_t k = 0; - if (b < n) k = keyof(sc[b], tb[b]); + if (b < n) k = keyof(sc[b], tb[b]); const bool hi = k != 0u && (n <= topk || k > T); const bool eq = k != 0u && n > topk && k == T; @@ -887,6 +910,7 @@ __device__ __forceinline__ ParTake par_take(ParEmit& e, uint32_t k, int lane, in } /* ---- pass one: every chunk's own top-k, as (key, block index) in block order. */ +template __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel( const float* __restrict__ score, const int32_t* __restrict__ bt, const int32_t* __restrict__ nc, const int32_t* __restrict__ pos, @@ -921,7 +945,7 @@ __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel( const float* sc = score + (size_t)m * s_ld; const int32_t* tb = bt + (size_t)seq * t_ld; - for (int i = t; i < cn; i += LT) sh_key[i] = keyof(sc[lo + i], tb[lo + i]); + for (int i = t; i < cn; i += LT) sh_key[i] = keyof(sc[lo + i], tb[lo + i]); __syncthreads(); ParEmit e{ wsum, &sh_hi, &sh_ord, 0u, 0u, 0u, cn <= topk }; @@ -955,6 +979,7 @@ __global__ __launch_bounds__(kLocalThreads) void qsa_local_kernel( } /* ---- pass two: merge the chunk lists and emit the page-id table. */ +template __global__ __launch_bounds__(kMergeThreads) void qsa_merge_kernel( const uint32_t* __restrict__ ck, const int32_t* __restrict__ ci, const int32_t* __restrict__ cc, const int32_t* __restrict__ bt, @@ -1071,6 +1096,8 @@ static inline int64_t par_scratch_bytes(long long topk) { // cu [nseq+1] i32, cumulative query counts: which sequence a query row belongs to // sel [M][topk+1] i32, `o_ld` elements a row (0 = topk+1); -1 padded // nsel [M] i32 +// Signed selects the key order (keyof), from the op's `signed` parameter. +template static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long cu, long sel, long nsel, long seqused, int M, int nb, int topk, int ratio, int nseq, int s_ld, int t_ld, int o_ld, @@ -1093,13 +1120,14 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long uint32_t* ck = (uint32_t*)scratch; int32_t* ci = (int32_t*)(ck + (size_t)kParM * kParWMax * topk); int32_t* cc = ci + (size_t)kParM * kParWMax * topk; - const int rc = R4D_EMIT(stream, qsa_local_kernel, dim3((unsigned)nchunk, (unsigned)M), - dim3(kLocalThreads), (size_t)chunk * sizeof(uint32_t), + const int rc = R4D_EMIT(stream, qsa_local_kernel, + dim3((unsigned)nchunk, (unsigned)M), dim3(kLocalThreads), + (size_t)chunk * sizeof(uint32_t), (const float*)score, (const int32_t*)bt, (const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, ck, ci, cc, nb, topk, ratio, nseq, s_ld, t_ld, chunk); if (rc != RAD_OK) return rc; - return R4D_EMIT(stream, qsa_merge_kernel, dim3((unsigned)M), dim3(kMergeThreads), + return R4D_EMIT(stream, qsa_merge_kernel, dim3((unsigned)M), dim3(kMergeThreads), (size_t)nchunk * topk * sizeof(uint32_t), (const uint32_t*)ck, (const int32_t*)ci, (const int32_t*)cc, (const int32_t*)bt, (const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, @@ -1109,7 +1137,8 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long /* A wide launch (prefill chunk, key cache off) takes the wide kernel. */ if (g_qsa_select_form == 2 || (g_qsa_select_form == 0 && M > kCacheMaxM)) { - return R4D_EMIT(stream, qsa_select_wide_kernel, dim3((unsigned)M), dim3(kThreads), 0, + return R4D_EMIT(stream, qsa_select_wide_kernel, dim3((unsigned)M), + dim3(kThreads), 0, (const float*)score, (const int32_t*)bt, (const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, (int32_t*)sel, (int32_t*)nsel, (int32_t*)seqused, nb, topk, ratio, nseq, s_ld, t_ld, @@ -1119,7 +1148,7 @@ static int r4d_qsa_select_bf16_emit(long score, long bt, long nc, long pos, long /* Never more than the table width. */ int cap = (M <= kCacheMaxM) ? lds_cap_of() : 0; if (cap > nb) cap = nb; - return R4D_EMIT(stream, qsa_select_kernel, dim3((unsigned)M), dim3(kThreads), + return R4D_EMIT(stream, qsa_select_kernel, dim3((unsigned)M), dim3(kThreads), (size_t)cap * sizeof(uint32_t), (const float*)score, (const int32_t*)bt, (const int32_t*)nc, (const int32_t*)pos, (const int32_t*)cu, (int32_t*)sel, (int32_t*)nsel, @@ -1151,7 +1180,9 @@ extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) { if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return R4D_NO(RAD_E_SHAPE); const long long topk = r4d_geti_or(a, "topk", 0); const long long ratio = r4d_geti_or(a, "ratio", 0); + const long long sgn = r4d_geti_or(a, "signed", 0); if (topk <= 0 || ratio <= 0) return R4D_NO(RAD_E_INVAL); + if (sgn != 0 && sgn != 1) return R4D_NO(RAD_E_INVAL); /* nb = min of the two widths, as in r4d_qsa_score_bf16.hip. */ const long long M = sc->shape[0]; const long long nb = bt->shape[1] < sc->shape[1] ? bt->shape[1] : sc->shape[1]; @@ -1167,10 +1198,11 @@ extern "C" int r4d_rad_qsa_select(const RadArgs* a, RadStream stream) { const long long sp = r4d_row_pitch(sc), tp = r4d_row_pitch(bt), op = r4d_row_pitch(se); if (sp < 0 || tp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE); /* Scratch is optional: without enough, the non-split kernels run. */ - return r4d_qsa_select_bf16_emit(r4d_addr(sc), r4d_addr(bt), r4d_addr(nc), r4d_addr(po), - r4d_addr(cu), r4d_addr(se), r4d_addr(ns), r4d_addr(su), - (int)M, (int)nb, (int)topk, (int)ratio, (int)nseq, - (int)sp, (int)tp, (int)op, a->scratch, a->scratch_bytes, - stream); + auto* const emit = sgn ? r4d_qsa_select_bf16_emit : r4d_qsa_select_bf16_emit; + return emit(r4d_addr(sc), r4d_addr(bt), r4d_addr(nc), r4d_addr(po), + r4d_addr(cu), r4d_addr(se), r4d_addr(ns), r4d_addr(su), + (int)M, (int)nb, (int)topk, (int)ratio, (int)nseq, + (int)sp, (int)tp, (int)op, a->scratch, a->scratch_bytes, + stream); } diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index df590570..c72dd76b 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1161,6 +1161,10 @@ static const RadParamSpec pQsaSelect[] = { { "topk", RAD_P_INT, RAD_REQUIRED }, { "ratio", RAD_P_INT, RAD_REQUIRED }, { "seqs", RAD_P_INT, RAD_REQUIRED }, + /* The ranking: 0 (absent) ranks max(score, 0) with scores at or below -1e30 dead, the QSA + * indexer's scores being sums of relus; 1 ranks signed finite scores, nonfinite ones dead, for + * indexers whose head weights can be negative. */ + { "signed", RAD_P_INT, RAD_OPTIONAL }, }; static const RadOperandSpec oQsaSelect[] = { { "score", RAD_OPD_IN, 0 }, @@ -2878,7 +2882,8 @@ static const RadOpSchema kSchemas[] = { "complete block, which the query itself lives in -- is appended LAST and is never a " "candidate: last is what makes the attention's own causal bound mask inside it and " "nowhere else, so the effective query position is (nsel-1)*ratio + pos%ratio. Ties " - "break to the LOWER block index through a prefix count, never through atomic order."), + "break to the LOWER block index through a prefix count, never through atomic order. " + "`signed` 1 ranks signed finite scores; absent or 0 ranks max(score, 0)."), SCHEMA("qsa_score", pQsaScore, oQsaScore, "score[m][b] = (sum over heads of relu(q[m][h] . bk[bt[m][b]])) / sqrt(n). THE RELU IS " "PER (BLOCK, HEAD) AND THE SUM IS OVER HEADS, in that order -- four independent votes, " diff --git a/libref/ref_qsa.cpp b/libref/ref_qsa.cpp index afc1c42d..e217c9be 100644 --- a/libref/ref_qsa.cpp +++ b/libref/ref_qsa.cpp @@ -15,6 +15,7 @@ #include "ref_ops.h" #include +#include #include using namespace ref; @@ -101,7 +102,8 @@ int ref_qsa_score(const RadArgs* a, RadStream) { /* ------------------------------------------------------------------ qsa_select */ /* The page-id table the sparse attention reads (docs/OPS.md): over the query's complete blocks * n = min(nc[seq], (pos + 1) / ratio, width), the live ones (page id >= 0, score > -1e30) ranked - * by max(score, 0). At most `topk` are taken: all of them when that many or fewer are live, else + * by max(score, 0); with `signed` 1 the live ones are those with a finite score, ranked by it (so + * -0 ties +0). At most `topk` are taken: all of them when that many or fewer are live, else * every block above the topk-th largest value in block order, then the blocks equal to it in block * order until topk are taken. The partial page bt[n] follows when (pos + 1) % ratio != 0 and * n < width, and -1 pads the row to topk + 1. nsel counts the entries, seqused is @@ -112,7 +114,9 @@ int ref_qsa_select(const RadArgs* a, RadStream) { const RadTensor *sc = &a->t[0], *bt = &a->t[1], *nc = &a->t[2], *po = &a->t[3]; const RadTensor *cu = &a->t[4], *se = &a->t[5], *ns = &a->t[6], *su = &a->t[7]; const int64_t topk = p_int(a, "topk", 0), ratio = p_int(a, "ratio", 0); + const int64_t sgn = p_int(a, "signed", 0); if (topk <= 0 || ratio <= 0) return RAD_E_SHAPE; + if (sgn != 0 && sgn != 1) return RAD_E_INVAL; if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return RAD_E_SHAPE; const int64_t M = sc->shape[0], nb = std::min(bt->shape[1], sc->shape[1]); const int64_t n_seq = numel(cu) - 1; @@ -136,8 +140,9 @@ int ref_qsa_select(const RadArgs* a, RadStream) { std::vector live; for (int64_t b = 0; b < n; ++b) { const float v = ldt(sc, m * s_rs + b * s_cs); - if (ldi(bt, s * bt_rs + b * bt_cs) < 0 || !(v > -1e30f)) continue; - val[(size_t)b] = v > 0.0f ? v : 0.0f; + if (ldi(bt, s * bt_rs + b * bt_cs) < 0) continue; + if (sgn ? !std::isfinite(v) : !(v > -1e30f)) continue; + val[(size_t)b] = sgn ? v : v > 0.0f ? v : 0.0f; live.push_back(b); } std::vector take; diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index fc91dc28..8cdecc32 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -381,7 +381,7 @@ static const RadParamSpec pQsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads") static const RadOperandSpec oQsaScore[] = { OPD("q"), OPD("bk"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") }; static const RadParamSpec pQsaSelect[] = { P_INT("M"), P_INT("blocks"), P_INT("topk"), - P_INT("ratio"), P_INT("seqs") }; + P_INT("ratio"), P_INT("seqs"), P_INTO("signed") }; static const RadOperandSpec oQsaSelect[] = { OPD("score"), OPD("bt"), OPD("nc"), OPD("pos"), OPD("cu"), OUT("sel"), OUT("nsel"), OUT("seqused") }; static const RadParamSpec pQsaTailStore[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"), diff --git a/tests/r4d_emu/test_qsa.cpp b/tests/r4d_emu/test_qsa.cpp index 7baba99b..57359c22 100644 --- a/tests/r4d_emu/test_qsa.cpp +++ b/tests/r4d_emu/test_qsa.cpp @@ -12,7 +12,11 @@ * seeded sweep of small odd shapes (NaN, +-inf, -0.0, denormal and -1e30 scores, pitches, a table * narrower than the scores, rows no sequence holds, topk 1, ratio 1). Which branch a row takes * inside the kernels is predicted from their constants, restated in `Path`; the run fails when the - * fixtures stop reaching one of them. `sweep N` runs N seeded fixtures at serving sizes instead. */ + * fixtures stop reaching one of them. `sweep N` runs N seeded fixtures at serving sizes instead. + * + * Fixtures marked signed run with the op's `signed` parameter: the kernels' signed key order, + * against the port's signed ranking, over negative, mixed and the sweep's odd scores. The unsigned + * fixtures are the same as without the parameter. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -42,6 +46,7 @@ struct Fix { int S = 1, M = 1, nb_s = 1, nb_t = 1; /* sequences, query rows, score and table widths */ int s_ld = 0, t_ld = 0, o_ld = 0; /* row pitches; 0 = tight */ int topk = 1, ratio = 1; + bool sgn = false; /* the op's `signed` parameter */ std::vector sc; /* [M][s_ld] */ std::vector bt; /* [S][t_ld] */ std::vector nc, pos, cu; /* [S], [M], [S + 1] */ @@ -66,7 +71,7 @@ struct Fix { }; /* ---- libref's ref_qsa_select (libref/ref_qsa.cpp), restated over the fixture's arrays: the same - * steps in the same order. */ + * steps in the same order, both rankings. */ void ref_select(const Fix& f, std::vector& se, std::vector& ns, std::vector& su) { const int64_t topk = f.topk, ratio = f.ratio; se.assign((size_t)f.M * (topk + 1), 0); ns.assign((size_t)f.M, 0); su.assign((size_t)f.M, 0); @@ -77,8 +82,9 @@ void ref_select(const Fix& f, std::vector& se, std::vector& ns std::vector live; for (int64_t b = 0; b < n; ++b) { const float v = f.sc[(size_t)(m * f.s_ld + b)]; - if (f.bt[(size_t)(s * f.t_ld + b)] < 0 || !(v > -1e30f)) continue; - val[(size_t)b] = v > 0.0f ? v : 0.0f; + if (f.bt[(size_t)(s * f.t_ld + b)] < 0) continue; + if (f.sgn ? !std::isfinite(v) : !(v > -1e30f)) continue; + val[(size_t)b] = f.sgn ? v : v > 0.0f ? v : 0.0f; live.push_back(b); } std::vector take; @@ -114,6 +120,8 @@ namespace Path { constexpr int kCacheCap = 8192, kCacheMaxM = 64; /* the key cache */ constexpr int kSamp = 2048, kSampRun = 32, kSampRuns = 64, kSampMinN = 3 * kSamp, kSampCap = 1920; constexpr int kWideShift = 19, kWideCand = 3840, kMergeAbove = 512, kMergeCand = 1664; +constexpr int kWideShiftSigned = 20; /* the signed key's 32 bits */ +int wide_shift(bool sgn) { return sgn ? kWideShiftSigned : kWideShift; } constexpr int kParM = 32, kParWMax = 16, kParCap = 8192; /* the split path */ int par_chunks(int nb) { return std::max(1, std::min(kParWMax, (nb + 4095) / 4096)); } } @@ -126,6 +134,14 @@ uint32_t keyof(float v, int32_t page) { return u + 1u; } +/* The signed order: the float's total order over 32 bits, -0 keyed as +0, nonfinite dead. */ +uint32_t keyof_signed(float v, int32_t page) { + if (page < 0 || !std::isfinite(v)) return 0u; + uint32_t u = 0; + if (v != 0.0f) std::memcpy(&u, &v, 4); + return (u & 0x80000000u) ? ~u : (u ^ 0x80000000u); +} + enum Form { kSingle, kWide, kAuto }; const char* const kFormName[] = { "single", "wide", "auto" }; @@ -140,7 +156,11 @@ std::map g_paths; void note_paths(const Fix& f, int m, Form form, bool split) { const int s = f.seq_of(m), n = f.n_of(m), topk = f.topk; std::vector k((size_t)std::max(n, 0)); - for (int b = 0; b < n; ++b) k[(size_t)b] = keyof(f.sc[(size_t)m * f.s_ld + b], f.bt[(size_t)s * f.t_ld + b]); + for (int b = 0; b < n; ++b) { + const float v = f.sc[(size_t)m * f.s_ld + b]; + const int32_t pg = f.bt[(size_t)s * f.t_ld + b]; + k[(size_t)b] = f.sgn ? keyof_signed(v, pg) : keyof(v, pg); + } std::vector live; for (uint32_t x : k) if (x) live.push_back(x); std::sort(live.begin(), live.end(), std::greater()); @@ -155,6 +175,7 @@ void note_paths(const Fix& f, int m, Form form, bool split) { int above = 0, eq = 0; for (uint32_t x : live) { above += x > T; eq += x == T; } if (eq > topk - above) hit("a threshold whose ties are cut short"); + if (f.sgn && T < 0x80000000u) hit("signed: a negative threshold"); } if (split) { const int nch = Path::par_chunks(f.nb()), chunk = (f.nb() + nch - 1) / nch; @@ -200,9 +221,10 @@ void note_paths(const Fix& f, int m, Form form, bool split) { hit("wide: a sample that fell back"); } if (L <= topk) return; - const uint32_t B = live[(size_t)topk - 1] >> Path::kWideShift; + const int shift = Path::wide_shift(f.sgn); + const uint32_t B = live[(size_t)topk - 1] >> shift; int in = 0; - for (uint32_t x : live) in += (x >> Path::kWideShift) == B; + for (uint32_t x : live) in += (x >> shift) == B; hit(in <= Path::kMergeCand && topk <= Path::kMergeAbove ? "wide: merged lists" : in <= Path::kWideCand ? "wide: the threshold's bin in LDS" : "wide: the threshold's bin over global memory"); } @@ -227,10 +249,10 @@ int run(Fix& f, Form form) { tens(f.cu.data(), RAD_I32, {f.S + 1}), tens(se.data(), RAD_I32, {M, W}, f.o_ld), tens(ns.data(), RAD_I32, {M}), tens(su.data(), RAD_I32, {M}), }; - RadParam p[5]{}; + RadParam p[6]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"blocks", RAD_P_INT, f.nb()}; p[2] = {"topk", RAD_P_INT, f.topk}; - p[3] = {"ratio", RAD_P_INT, f.ratio}; p[4] = {"seqs", RAD_P_INT, f.S}; - RadArgs a{}; a.t = t; a.n_t = 8; a.p = p; a.n_p = 5; + p[3] = {"ratio", RAD_P_INT, f.ratio}; p[4] = {"seqs", RAD_P_INT, f.S}; p[5] = {"signed", RAD_P_INT, 1}; + RadArgs a{}; a.t = t; a.n_t = 8; a.p = p; a.n_p = f.sgn ? 6 : 5; const int64_t need = r4d_rad_qsa_select_scratch(&a); std::vector scratch((size_t)(need / 4 + 1), 0xA5A5A5A5u); if (form == kAuto) { a.scratch = scratch.data(); a.scratch_bytes = need; } @@ -245,7 +267,9 @@ int run(Fix& f, Form form) { : "qsa_select_kernel"; const char* fn = kFormName[form]; if (rc != RAD_OK) { std::printf("FAIL %-48s %-6s launch returned %d\n", f.name.c_str(), fn, rc); return 1; } - if (std::strcmp(emu_last_kernel, expect) != 0 || grids != (split ? 2 : 1)) { + /* The launch site names the template, `kernel`: the name is what precedes it. */ + const std::string ran(emu_last_kernel, std::strcspn(emu_last_kernel, "<")); + if (ran != expect || grids != (split ? 2 : 1)) { std::printf("FAIL %-48s %-6s ran %s in %d grid(s), expected %s in %d\n", f.name.c_str(), fn, emu_last_kernel, grids, expect, split ? 2 : 1); return 1; @@ -324,8 +348,11 @@ Fix fix_prefill() { * score distributions. Over 4096 blocks at six rows, the automatic choice is the split path. */ Fix fix_wide(int dist) { static const char* const kDist[] = { "continuous", "coarse, heavy ties", "an eighth in one first-digit bin", - "all in one first-digit bin", "fine ties at the threshold" }; + "all in one first-digit bin", "fine ties at the threshold", + "signed, heavy ties", "signed, all negative, heavy ties", + "signed, continuous across zero" }; Fix f; f.name = std::string("wide: ") + kDist[dist]; + f.sgn = dist >= 5; const int S = 2, nb = 9000, topk = 512, ratio = 4, pages = 1 << 20; f.shape(S, 6, nb, nb, topk, ratio); f.cu = { 0, 4, 6 }; @@ -341,6 +368,9 @@ Fix fix_wide(int dist) { case 1: v = (float)(u % 23) * 0.25f; break; case 2: v = u % 8 == 0 ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break; case 3: v = 1.0f + (float)(u % 60000) * 1e-6f; break; + case 5: v = (float)(u % 23) * 0.25f - 3.0f; break; + case 6: v = -(float)(u % 23) * 0.25f - 1.0f; break; + case 7: v = (float)(u % 1000003) / 1000.0f - 500.0f; break; default: v = (float)(u % 4999) * 0.01f; break; } } @@ -551,6 +581,22 @@ Fix fix_random(int it) { return f; } +/* A fixture under the signed order, its finite scores negated on odd rows when `flip` and moved + * by `shift`, so live scores straddle zero or fall below it. */ +Fix as_signed(Fix f, float shift, bool flip = false) { + f.sgn = true; + f.name = "signed " + f.name; + if (shift == 0.0f && !flip) return f; /* as built: keeps -0 apart from +0 */ + for (int m = 0; m < f.M; ++m) + for (int b = 0; b < f.nb_s; ++b) { + float& v = f.score(m, b); + if (!std::isfinite(v)) continue; + if (flip && m % 2) v = -v; + v += shift; + } + return f; +} + } // namespace /* No argument: the fixtures above and the branch check. `sweep N`: N fix_random fixtures, about @@ -562,12 +608,20 @@ int main(int argc, char** argv) { if (sweep) { const int n = argc > 2 ? std::atoi(argv[2]) : 100; for (int i = 0; i < n; ++i) fixtures.push_back([i] { return fix_random(i); }); + for (int i = 0; i < n; ++i) fixtures.push_back([i] { return as_signed(fix_random(i), -1.0f, true); }); } else { fixtures = { fix_decode, fix_prefill, fix_few_live, fix_wide_launch, [] { return fix_split(1, 4); }, [] { return fix_split(2, 4); }, fix_split_sparse, fix_big_topk, [] { return fix_no_split(true); }, [] { return fix_no_split(false); } }; for (int d = 0; d < 5; ++d) fixtures.push_back([d] { return fix_wide(d); }); for (int i = 0; i < 150; ++i) fixtures.push_back([i] { return fix_sweep(i); }); + fixtures.push_back([] { return as_signed(fix_decode(), -5.0f); }); + fixtures.push_back([] { return as_signed(fix_decode(), -20.0f); }); + fixtures.push_back([] { return as_signed(fix_few_live(), 0.0f); }); + fixtures.push_back([] { return as_signed(fix_split(2, 4), -6.0f); }); + fixtures.push_back([] { return as_signed(fix_wide_launch(), -1.0f, true); }); + for (int d = 5; d < 8; ++d) fixtures.push_back([d] { return fix_wide(d); }); + for (int i = 0; i < 150; ++i) fixtures.push_back([i] { return as_signed(fix_sweep(i), 0.0f); }); } int fails = 0, launches = 0; for (auto& make : fixtures) { @@ -592,6 +646,7 @@ int main(int argc, char** argv) { "wide: the threshold's bin in LDS", "wide: the threshold's bin over global memory", "split: topk or fewer live, every one taken", "split: no chunk over topk, more than topk live", "split: a chunk over topk", "split: exactly topk candidates, from a chunk over topk", + "signed: a negative threshold", }; int missing = 0; for (const char* p : kRequired) From da77f863324eb77603b766ae947fcba651f8c1d7 Mon Sep 17 00:00:00 2001 From: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:06:35 +0200 Subject: [PATCH 059/152] libref, libavx: GLM-5.3's ops -- mHC, clamped SwiGLU, f32 routing, KDA, the DSA indexer, MLA The reference and CPU forms of the ops GLM-5.3-Flash's graph needs, with their schemas and shape hooks: mhc_pre / mhc_post / mhc_contract and the column-split pair mhc_pre_partial / mhc_pre_finish; swiglu_clamped; gemm_nt_f32 (bf16 activation, f32 weight and result) for the router logits and the indexer's head gates; router_sigmoid_topk (correction-bias top-k); kda_update with per-channel decay and both state forms; dsa_pool, dsa_query and dsa_score; and mla_attn and mla_project for absorbed latent attention. moe_gather takes f32 expert weights beside bf16, and fp8a8f32 joins the dtype list. docs/OPS.md states each op. ref_test checks every op against hand-computed cases, avx_check_hand the CPU forms against libref, build_test the indexer cache's page size. Co-Authored-By: Nunze --- docs/OPS.md | 167 ++++++++- libavx/CMakeLists.txt | 3 + libavx/avx_cases.cpp | 46 ++- libavx/avx_check_hand.cpp | 183 ++++++++++ libavx/avx_dsa.cpp | 201 +++++++++++ libavx/avx_glm.cpp | 507 +++++++++++++++++++++++++++ libavx/avx_isa.h | 10 + libavx/avx_mla.cpp | 113 +++++++ libavx/avx_moe.cpp | 4 +- libavx/avx_registry.cpp | 82 +++++ libref/ref_dsa.cpp | 206 +++++++++++ libref/ref_glm.cpp | 90 +++++ libref/ref_kda.cpp | 199 +++++++++++ libref/ref_mhc.cpp | 250 ++++++++++++++ libref/ref_mla.cpp | 105 ++++++ libref/ref_moe.cpp | 3 +- libref/ref_ops.h | 28 ++ libref/ref_registry.cpp | 106 ++++++ libref/ref_shapes.cpp | 210 +++++++++++- tests/build_test.cpp | 28 ++ tests/ref_test.cpp | 695 +++++++++++++++++++++++++++++++++++++- 21 files changed, 3217 insertions(+), 19 deletions(-) create mode 100644 libavx/avx_dsa.cpp create mode 100644 libavx/avx_glm.cpp create mode 100644 libavx/avx_mla.cpp create mode 100644 libref/ref_dsa.cpp create mode 100644 libref/ref_glm.cpp create mode 100644 libref/ref_kda.cpp create mode 100644 libref/ref_mhc.cpp create mode 100644 libref/ref_mla.cpp diff --git a/docs/OPS.md b/docs/OPS.md index 98a3ef56..650a27c9 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -40,9 +40,9 @@ here is such a choice. otherwise; strides are the kernel's business, not the schema's. - Where an op takes `dtype`, it is a string naming the operand combination, so a weight format and an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`, `u8`, `fp8_e4m3`, - `fp8a8`, `fp8a16`, `i8a8`, `i8a8h`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`, - `w8a16`, `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`, and the codebook - expert forms `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` (`docs/MOE-W4.md`). + `fp8a8`, `fp8a8f32`, `fp8a16`, `i8a8`, `i8a8h`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, + `w4a16`, `w8a16`, `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`, and the + codebook expert forms `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` (`docs/MOE-W4.md`). - `w4a8h` is `w4a8` with a `group`-wide Walsh–Hadamard along K baked into the stored weight (`docs/MOE-W4.md`). - `i8a8` is an i8 weight with a bf16 scale per (row, 128 of K) against an int8 activation on @@ -50,6 +50,7 @@ here is such a choice. carrying the 1/128 (libquant's `transform=fwht128`), met by `had_quant_act_i8g`. - `w4a8_asym` is the unsigned-nibble-minus-zero-point grid instead of the symmetric one. - `fp8a8` and `fp8a16` say whether a block-scaled E4M3 weight meets an fp8 or a bf16 activation. + - `fp8a8f32` is `fp8a8` with f32 weight scales on the 128x128 block grid. - `w5a16` and `w4a16_asym` are ParoQuant's int5 and z-lab's int4 (u5 / u4 codes, an f16 scale and a u8 zero point per 128 of K) against an f16 activation; `w5a8i8` and `w4a8i8_asym` are the same weights against an int8 activation with an f32 scale per (row, 128 of K). @@ -191,6 +192,11 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `rmsnorm_p` | `M`(range) `n` `eps`:f64 `dtype` | `x` → `y` | | `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` | | `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` | +| `mhc_pre` | `M`(range) `n` `hc` `iterations` `eps`:f64 `hc_eps`:f64 `dtype` | `h`, `fn`w, `scale`w, `base`w → `x`, `post`, `comb` | +| `mhc_pre_partial` | `M`(range) `n` `hc` `chunk` `first` `chunks` `dtype` | `h`, `fn`w → `part` | +| `mhc_pre_finish` | `M`(range) `n` `hc` `iterations` `eps`:f64 `hc_eps`:f64 `chunk` `dtype` | `part`, `h`, `scale`w, `base`w → `x`, `post`, `comb` | +| `mhc_post` | `M`(range) `n` `hc` `dtype` | `x`, `h`, `post`, `comb` → `out` | +| `mhc_contract` | `M`(range) `n` `hc` `dtype` | `h` → `x` | | `hc_read` | `M`(range) `n` `hc` `lowrank` `eps`:f64 `dtype` `wadd`:f64/opt `inject`/opt `group`/opt `rotate`/opt `mix`/opt | `h`, `w`w, `mix_down`w, `mix_up`w, `inject_w`w? → `x`, `inj`?, `q`?, `scale`?, `rq`?, `rscale`? | | `hc_write` | `M`(range) `n` `hc` `dtype` | `y`, `inj`, `h`:inout | | `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` | @@ -199,6 +205,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `add` | `M`(range) `n` `dtype` `div`:f64/opt | `a`, `b` → `y` | | `mul` | `M`(range) `n` `dtype` | `a`, `b` → `y` | | `silu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gate·up) | +| `swiglu_clamped` | `M`(range) `n` `limit`:f64 `dtype` | `gate_up` → `y` | | `mul_weight` | `M`(range) `n` `dtype` `scalar`/opt | `x`, `w`w → `y` (w one element or one row) | | `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) | | `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) | @@ -239,6 +246,11 @@ does it. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.m `gelu_pytorch_tanh`, while the unary `gelu` is the exact erf form. Both split the fused `gate_up` with the gate in the first half. +`swiglu_clamped` splits `[M, 2n]` as gate then up, as `silu_mul` does, and computes +`silu(min(gate, limit)) * clamp(up, -limit, limit)` in f32, rounded once to `y`'s dtype. `limit` +is positive and finite (GLM-5.3's is 10). The clip precedes the SiLU, and the gate has no lower +clip. + **`add` and `mul`** broadcast a `b` of exactly `n` elements along the rows of a taller output (a bias add). Nothing else broadcasts, in these or any other elementwise op. `add`'s `div` divides the sum after its rounding, `y = rd(rd(a + b) / div)` with `rd` `y`'s dtype (absent, 1: the plain @@ -319,6 +331,34 @@ is easy to miss. and an f32 scale plane (a group of 128 for `mix_down`, a quarter row for `mix_up`), which a host kernel reads joined (Weights of several planes). +**mHC** (manifold-constrained hyper-connections) keeps `hc` residual streams in one `[M, hc*n]` +row and is a separate family from `hc_read`/`hc_write`. `mhc_pre` projects the whole row with the +f32 matrix `fn` `[hc*(hc+2), hc*n]` and multiplies each projection by +`1 / sqrt(sum(h^2) / (hc*n) + eps)`, giving coefficients `c`. `scale` holds three f32 scalars and +`base` `hc*(hc+2)` f32 biases: the pre gates are `sigmoid(c[j]*scale[0] + base[j]) + hc_eps` and +the post gates `2*sigmoid(c[hc+j]*scale[1] + base[hc+j])` for `j < hc`, and the remaining `hc*hc` +coefficients, times `scale[2]` plus their bias, are the mixing logits indexed +`[source, destination]`. The first Sinkhorn pass is a row softmax plus `hc_eps`, then column +normalization; every later pass normalizes the rows, then the columns; each normalization divides +by the sum plus `hc_eps`. `iterations` counts the passes, the first included. `x` is the sum of the +streams weighted by the pre gates, rounded once to `dtype`; `post` `[M, hc]` and `comb` +`[M, hc*hc]` stay f32. Transposing `comb` leaves every shape valid and changes the model. +`mhc_post` writes `out[dst, i] = post[dst]*x[i] + sum_src comb[src, dst]*h[src, i]` into a +separate buffer (`out` must not alias `h`), with no normalization of the stream. `mhc_contract` is +the mean over the streams, rounded once. + +`mhc_pre_partial` and `mhc_pre_finish` are `mhc_pre` split by residual columns, so +tensor-parallel ranks share its projection instead of each computing it whole. Chunk `c` covers +columns `[c*chunk, (c+1)*chunk)` of the `hc*n` row (`chunk` divides it). `mhc_pre_partial` +computes chunks `[first, first+chunks)`: `part[m, (c-first)*S + j]` is the chunk's sum of +`h*fn[j]` for `j < hc*(hc+2)` and of `h*h` for `j = hc*(hc+2)`, with `S = hc*(hc+2)+1` rounded up +to a multiple of four and the slots past the last zero, so a gathered payload is defined. A +row-interleaved `all_gather` with `row = chunks*S` joins the ranks' matrices into +`[M, (hc*n/chunk)*S]`, which `mhc_pre_finish` reads: each coefficient and the sum of squares is +the sum of its chunks' partials, then `mhc_pre`'s gates, Sinkhorn mixing and collapse. The order +of that sum is the implementation's, so the pair matches `mhc_pre` to rounding, and bit for bit +only where an implementation says so. + ### Gemma 4's audio tower - **`relu`** is `max(x, 0)` at each operand's own row pitch. @@ -449,6 +489,11 @@ a weight layout the stored WMMA fragment order does not provide, so it is not us quantises the activation for an integer weight it is int8: `quant_act_i8` for `w4a8`, `w8a8` and `w2a8`, `quant_act_i8g` for `i8a8`. +`fp8a8f32` is `fp8a8`'s E4M3 activation against an E4M3 weight whose 128x128 block scales are +f32, read as the checkpoint stores them. A scale that bf16 cannot represent exactly keeps its +value, which `fp8a8`'s bf16 scale plane would round. It applies to `gemm_nt_q` and `moe_gemm_q` +with `group` 128. + **`group` has different meanings in this table.** A kernel that reads it the other way is wrong, not slow. `libref/ref_quant.cpp` is the definition. @@ -587,6 +632,7 @@ may not have arrived. | op | params | operands | |---|---|---| | `gemm_nt` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` | +| `gemm_nt_f32` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` | | `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` | | `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | | `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` | @@ -636,6 +682,11 @@ what a separate tensor would hold, so the fused form equals the unfused chain bi may be `y` itself, the residual stream updated in place (the encoder towers' layers do this), so an implementation reads `res` before it stores the product over it. +`gemm_nt_f32` is `y[M, N] = a[M, K] @ b[N, K]^T` with a bf16 activation, an f32 weight, f32 +accumulation and an f32 `y`; `dtype` (`bf16`) names the activation. It exists for the projections +whose weights and results must not narrow to bf16: GLM's router logits and its indexer's signed +head gates. + ### Runtime LoRA: `lora_shrink` and `lora_expand` | op | params | operands | @@ -1356,6 +1407,7 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t | `router_topk_scatter` | `M`(range) `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `logits` → `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count` | | `router_gemm_topk_scatter` | `M`(range) `K` `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `a`, `b`w, `gate_b`w? → `logits`, `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`? | | `moe_gemm` | `M`(range) `N` `K` `n_expert` `top_k` `a_order` `dtype` | `a`, `w`wt, `sorted_tok`, `expert_offset` → `y` | +| `router_sigmoid_topk` | `M`(range) `n_expert` `top_k` `norm` `route_scale`:f64 `dtype` | `logits`, `bias`w → `ids`, `weights` | | `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` | | `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? | | `row_topk_merge` | `M` `R` `world_size` `dtype` | `gathered` → `idx`, `val` | @@ -1447,6 +1499,9 @@ product before the sum, so carrying either in f32 moves the last bit. `act` is ` runs on one rank, so the op this replaces is a dispatch every other rank waits out inside the block's all-reduce. +With bf16 expert outputs, `expert_w` may be bf16 or f32. f32 mixture weights stay f32 through +the sum; only the gathered result narrows to bf16, as with bf16 weights. + ### Quantised experts and the row gate | op | params | operands | @@ -1468,6 +1523,20 @@ gate/up); the output is `max(N, N_odd)` wide, and a narrower class fills the lea output part and writes zeros after them, so the gated quantiser behind it reads one layout for every row. The weight list is the even class's codes, its scales, then the odd class's codes and scales. +**`router_sigmoid_topk`** is single-group correction-bias routing, all in f32. The scores are +`p = sigmoid(logits)`; the selection takes the `top_k` largest `p + bias`, ties to the lower +expert, and the weights are the selected `p`, never the biased ranks. With `norm` 1 a weight is +`p * (route_scale / (sum + 1e-20))` over the row's selected `p`, with `norm` 0 `p * route_scale`; +`route_scale` is positive and finite. A rank that is NaN or `-inf` is never selected, and a row +with fewer than `top_k` selectable experts has no defined selection (libref refuses it). +Grouped selection (`n_group > 1`) is not this op. GLM-5.3 routes 8 of 288 experts in one group +with `route_scale` 2.5. + +At `dtype=mxfp4a8`, `w` and `w_odd` are OCP e2m1 codes and `w_scale` and `w_odd_scale` hold one +E8M0 exponent per (row, 32 of K), typed `e8m0` or raw `u8`; either way a byte is an exponent, not +an integer multiplier. `a` and `a_scale` are `quant_act_fp8`'s pair, and `group` is that +activation's scale group, independent of the weight's 32-wide grid. + **`moe_gemm_q_mod4`** is the same GEMM over four classes by the expert's number mod 4. `w`/`w_scale` hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting to `N`, `K`); expert `e` is entry `e / 4` of class `e % 4`, so class `q` holds `ceil((n_expert - q) / 4)` of them. @@ -1538,6 +1607,7 @@ wrong. | op | params | operands | |---|---|---| +| `kda_update` | `M`(range) `heads` `head_k` `head_v` `lower_bound`:f64 `scale`:f64 `l2_eps`:f64 `mode` `dtype` `state_form`/opt | `q`, `k`, `v`, `a`, `b`, `A_log`w, `dt_bias`w, `state`:inout, `state_idx`, `cu`, `num_accepted`?, `has_init`? → `o` | | `gdn_conv_prep` | `M`(range) `head_k` `head_v` `chunk`/der `conv_width` `l2_eps`:f64/opt `softplus_thr`:f64/opt | `x`, `w`w, `b`w?, `A_log`w, `dt_bias`w, `conv_state`:inout, `cu`, `a`?, `b_gate`?, `cache_idx`?, `has_init`? → `q`,`k`,`v`,`g`,`beta` | | `gdn_conv_update` | `q_len`(range) `head_k` `head_v` `conv_width` `max_query_len`/opt | `x`, `w`w, `b`w?, `conv_state`:inout, `state_idx`, `num_accepted`, `cu` → `q`,`k`,`v` | | `gdn_kkt_solve` | `M`(range) `head_k` `chunk`/der | `k`, `beta`, `g`, `cu` → `A` | @@ -1546,6 +1616,32 @@ wrong. | `gdn_conv_recurrent_update` | `q_len`(range) `head_k` `head_v` `conv_width` `n_head_v`/opt `scale`:f64/opt `eps`:f64/opt `l2_eps`:f64/opt `softplus_thr`:f64/opt `act`:str/opt `state_fp16`/opt `state_form`:str/opt | `x`, `conv_w`w, `conv_b`w?, `conv_state`:inout, `conv_idx`, `a`,`b`,`A_log`w,`dt_bias`w,`state`:inout,`state_idx`,`num_accepted`,`cu`,`z`,`norm_w`w → `o`,`o_q`?,`o_scale`? | | `gdn_gated_rmsnorm` | `M`(range) `channels` `eps`:f64 `act`:str | `x`, `z`, `w`w → `o` | +**`kda_update` is Kimi delta attention with per-channel decay.** Per token and head it +L2-normalizes `q` and `k` with `l2_eps`, scales `q` by `scale`, and forms the decay +`exp(lower_bound * sigmoid(exp(A_log[h]) * (a[d] + dt_bias[h, d])))` per K channel `d` +(`lower_bound` negative and finite) and `beta = sigmoid(b[h])`. For each value row `e` of the +state it decays the row by channel, computes `delta = beta * (v[e] - dot(S[e], k))`, adds +`delta * k`, and writes `o[e] = dot(S[e], q)`. `state` is f32 `[slots, heads, head_v, head_k]`; +`q`, `k`, `v` and `a` may be `[M, heads, width]` or flattened `[M, heads*width]`, and `b` is one +value per (token, head). `o` excludes the model's gated RMS norm. `cu` holds absolute token +offsets, so a call can cover a slice of a mixed batch. `mode=verify` reads column +`num_accepted - 1` of the sequence's `state_idx` row (`num_accepted` absent is 1) and writes the +state after token `t` of the window to column `t`; `mode=prefill` reads column zero and writes only +the final state there. `has_init` 0 starts from a zero state, a negative read slot gives zero +output, and a negative write slot is skipped. + +`state_form` is `gdn_recurrent_update`'s (below): `per_candidate` when absent, and with `anchor` +one committed state and one scratch slot per sequence. Under `anchor`, column zero of `state_idx` +is the committed state and column `width/2` the scratch; the two must differ, and both forms need +`head_k = head_v = 128`. The scratch holds, per head, one f32 replay count and then one record of +385 f32 per token: the normalized key, the raw value, the per-channel decay and beta, 32 records +at most, which fits one 128 x 128 head block. `mode=verify` first replays the previous window's +accepted prefix (`num_accepted` records, at most the stored count) onto the committed state and +stores it back, then runs the window from it, writing each token's record and the window length +as the new count; the committed state does not advance past the accepted prefix, and a window has +at most 32 tokens. `mode=prefill` commits its final state and sets the count to zero. A zeroed +scratch slot replays nothing. + **Speculative rollback is part of the schema** (`spec.md` §10). The recurrent state and the conv window have already absorbed rejected tokens, so the state cache is a rolling window of `conv_width-1 + n_spec` entries read at the slot the last accepted token left, and a rejection is a @@ -2037,6 +2133,11 @@ order, not a slow one. | op | params | operands | |---|---|---| | `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `k`, `w`w, `page`?, `pos`? → `out` | +| `dsa_pool` | `M`(range) `n` `ratio` `dtype` `block_size`/opt | `kg`, `ape`w → `q`, `scale`; `page`?, `cache`:inout? | +| `dsa_query` | `M`(range) `n` `dtype` | `x` → `q`, `scale` | +| `dsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `q_scale`, `gate`, `k`, `k_scale`?, `bt`, `cu`, `nc` → `score` | +| `mla_attn` | `M`(range) `latent_dim` `heads` `blocks` `block_size` `scale`:f64 `dtype` | `q`, `kv`, `bt`, `length` → `out` | +| `mla_project` | `M`(range) `heads` `head_dim` `latent_dim` `mode` `dtype` | `a`, `b`w → `y` | | `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` | | `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` `signed`/opt | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` | | `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` | @@ -2231,6 +2332,66 @@ block-key kernel with two sources, a per-key source selector and a tail layout. selection both need and this op computes on the way. It is not the number of blocks that completed this step; the two agree only for a sequence that starts at zero. +### GLM-5.3's indexer and latent attention + +GLM's sparse attention keeps QSA's selection (`qsa_select` with `signed` 1) and replaces the +block keys, the queries and the score. Its indexer applies no RoPE, and the layer norm of the raw +keys precedes `dsa_pool`. + +`dsa_pool` compresses `ratio` key rows into one. `kg` is `[M*ratio, 2n]` bf16, each row a +normalized key followed by its channel-wise gate logits. The learned f32 `ape` `[ratio, n]` is +added to the gate logits, which are softmaxed over the `ratio` axis per channel; the keys are +pooled with those probabilities and rounded to bf16, then rotated by the ascending-stride +Walsh-Hadamard transform, multiplied by `1/sqrt(n)` and rounded to bf16 again. Each row is +quantised to E4M3 with `scale = 2^ceil(log2(max(amax, 1e-4) / 448))`, codes rounded to nearest +even: `q` `[M, n]`, `scale` `[M, 1]` f32. `n` is a power of two up to 256, `ratio` 2 to 16. + +`page` and `cache`, both or neither, also store the result into the indexer's paged key cache, at +`n` 128 and `ratio` 4 only. `page[M]` names each row's destination page, which must be unique +within the call; a negative or out-of-range id is skipped. `cache` is u8 `[pages, 1, 4, 34]` with +contiguous inner rows and a four-byte-aligned page pitch of at least 136 bytes: a page holds the +128 codes, then the f32 scale at byte 128, and its last four bytes and any pitch padding are left +untouched. That is one block-size-4 group of the indexer's KV, with no separate scale allocation. +`block_size`, when given, is 4 and names the consuming layout to the cache planner. + +`dsa_query` rotates each bf16 query head by the same normalized Walsh-Hadamard transform, rounds +to bf16, and quantises to E4M3 with the same power-of-two scale: `x` `[M, n]`, `q` `[M, n]`, +`scale` `[M, 1]`, token and head flattened into `M`. There is no RoPE and no RMS norm. Unlike +`had_quant_act_fp8`, both the normalization of the rotation and the power-of-two scale are part of +the op. `n` is a power of two up to 256. + +`dsa_score` takes E4M3 queries `[M, heads, n]` with f32 scales and signed f32 gates `[M, heads]`, +E4M3 pooled keys `[pages, n]` with f32 scales `[pages]`. `bt[seqs, blocks]` names key pages, +`cu[seqs+1]` holds absolute query offsets and `nc[seqs]` bounds the live blocks. The score of block +`b` is `k_scale * sum_h(gate_h * q_scale_h * relu(dot(q_h, k))) / sqrt(heads*n)`: the ReLU comes +before the head weighting, so a negative gate can make a block's score negative. A block past +`nc`, a negative page id or one past the key rows scores `-inf`. `score` is f32 `[M, blocks]` and +may have fewer columns than `bt` with its own row pitch, so an architecture can bound it by the +current history. `qsa_select` applies each query's causal bound, so scoring a chunk's shared +history makes no future block eligible. + +`k` may instead be the packed u8 cache `dsa_pool` writes, with `k_scale` absent: the codes and the +embedded scale are read in place. `q` may be flattened `[M*heads, n]` with `q_scale` +`[M*heads, 1]`, each with its own row pitch, which is `dsa_query`'s output as written. + +`mla_attn` is absorbed latent attention: one latent vector per token is both key and value. +`q` and `out` are `[M, heads, latent_dim]`, `kv` is `[pages, 1, block_size, latent_dim]`, and +`bt[M, blocks]` is each query's own page table, the selected complete pages followed by its tail. +`length[M]` counts the table's visible tokens (every selected complete page and the visible part of +the tail) and is the causal bound: no slot at or past it is read. A missing or out-of-range page +contributes nothing, and a row with no visible key outputs zero. The softmax is f32 and `out` is +rounded once. `scale` is positive and finite and comes from the original query/key head width, +not the latent width (GLM: `1/sqrt(256)` against a latent of 512). + +`mla_project` moves a query into the latent and a latent result out of it, through the bf16 +weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows. +`mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored, +`[head_dim, latent_dim]`, giving `[M, heads, latent_dim]`; `mode=expand` multiplies +`a` `[M, heads, latent_dim]` by the transposed value block, giving `[M, heads, head_dim]`. Both +accumulate in f32 and round once to bf16. The KV cache stays latent; only this weight carries the +per-head width. Its rows are head-major, so a tensor-parallel slice of whole heads is a row range. +`a` and `y` may also be `[M, heads*width]`, heads contiguous, with their own token pitch. + ## Draft heads A drafter is an ordinary graph over ordinary ops except at its two ends: what proposes the diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index 0f3b8d22..10e80c3a 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -37,6 +37,9 @@ set(AVX_KERNEL_SRC avx_elementwise.cpp avx_norm.cpp avx_hc.cpp + avx_glm.cpp + avx_dsa.cpp + avx_mla.cpp avx_quant.cpp avx_gemm.cpp avx_gemm_tile.cpp diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 3e77b68e..39f51551 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -113,6 +113,39 @@ std::vector build_cases() { * on is the trunk case, off the final mixer; they differ in the operand list. */ for (const char* dt : { "f32", "bf16" }) { add("hc_enter", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) }); + add("swiglu_clamped", { HI("M", 5), HI("n", 259), HF("limit", 0.5), HS("dtype", dt) }); + if (!std::strcmp(dt, "bf16")) + add("dsa_pool", { HI("M", 7), HI("n", 128), HI("ratio", 4), HS("dtype", "bf16") }); + if (!std::strcmp(dt, "bf16")) + add("dsa_query", { HI("M", 7), HI("n", 128), HS("dtype", "bf16") }); + if (!std::strcmp(dt, "bf16")) + add("gemm_nt_f32", { HI("M", 4), HI("N", 32), HI("K", 129), HS("dtype", "bf16") }); + if (!std::strcmp(dt, "bf16")) + for (const char* mode : { "absorb", "expand" }) + add("mla_project", { HI("M", 3), HI("heads", 2), HI("head_dim", 17), + HI("latent_dim", 31), HS("mode", mode), HS("dtype", "bf16") }); + if (!std::strcmp(dt, "bf16")) + add("dsa_score", { HI("M", 3), HI("n", 128), HI("heads", 32), HI("blocks", 17), + HI("seqs", 2), HS("dtype", "fp8_e4m3") }); + for (int norm : { 0, 1 }) + add("router_sigmoid_topk", + { HI("M", 5), HI("n_expert", 288), HI("top_k", 8), HI("norm", norm), + HF("route_scale", 2.5), HS("dtype", dt) }); + add("mhc_pre", { HI("M", 3), HI("n", 129), HI("hc", 4), HI("iterations", 20), + HF("eps", 1e-5), HF("hc_eps", 1e-6), HS("dtype", dt) }); + add("mhc_pre_partial", { HI("M", 3), HI("n", 129), HI("hc", 4), HI("chunk", 129), + HI("first", 1), HI("chunks", 2), HS("dtype", dt) }); + add("mhc_pre_finish", + { HI("M", 3), HI("n", 129), HI("hc", 4), HI("iterations", 20), HF("eps", 1e-5), + HF("hc_eps", 1e-6), HI("chunk", 129), HS("dtype", dt) }); + add("mhc_post", { HI("M", 3), HI("n", 129), HI("hc", 4), HS("dtype", dt) }); + add("mhc_contract", { HI("M", 3), HI("n", 129), HI("hc", 4), HS("dtype", dt) }); + add("mla_attn", { HI("M", 3), HI("latent_dim", 32), HI("heads", 2), HI("blocks", 7), + HI("block_size", 4), HF("scale", 0.125), HS("dtype", dt) }); + for (const char* mode : { "prefill", "verify" }) + add("kda_update", { HI("M", 3), HI("heads", 2), HI("head_k", 32), HI("head_v", 32), + HF("lower_bound", -5), HF("scale", 0.1767766952966369), + HF("l2_eps", 1e-6), HS("mode", mode), HS("dtype", dt) }); add("hc_write", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) }); add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8), HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 1), HI("inject", 1), @@ -134,6 +167,10 @@ std::vector build_cases() { } add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) }); + for (const char* order : { "token", "sorted" }) + add("moe_gemm_q", + { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8), HI("top_k", 2), + HI("group", 128), HS("a_order", order), HS("dtype", "mxfp4a8") }); /* One scale per column over the rows: no group. */ add("quant_cols_fp8", { HI("M", 5), HI("n", 256), HS("dtype", "bf16") }, EB(5, 256, 2, 1.5)); add("quant_cols_fp8", { HI("M", 7), HI("n", 96), HS("dtype", "f32") }, EB(7, 96, 4, 1.25)); @@ -214,7 +251,7 @@ std::vector build_cases() { /* The formats libref describes (ref_shapes.cpp): block fp8, and the int4 and int8 weights * against quant_act_i8's step-ordered codes. The bias form needs `a_scale`, which fp8a16 (a * bf16 activation) does not have, so libref declines it there. */ - for (const char* dt : { "fp8a8", "fp8a16", "w4a8", "w8a8" }) + for (const char* dt : { "fp8a8", "fp8a8f32", "fp8a16", "w4a8", "w8a8" }) for (int M : { 1, 65 }) { const double fl = 2.0 * M * 96 * 256; add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128), @@ -439,6 +476,10 @@ std::vector build_cases() { HI("seqs", 3) }); add("qsa_select", { HI("M", 2), HI("blocks", 1), HI("topk", 1), HI("ratio", 3), HI("seqs", 1) }); + add("qsa_select", { HI("M", 4), HI("blocks", 300), HI("topk", 32), HI("ratio", 4), + HI("seqs", 1), HI("signed", 1) }); + add("qsa_select", { HI("M", 7), HI("blocks", 129), HI("topk", 16), HI("ratio", 4), + HI("seqs", 3), HI("signed", 1) }); add("qsa_tail_store", { HI("M", 3), HI("n", 37), HI("ratio", 2), HI("ring", 2), HI("seqs", 3), HS("dtype", "f32") }); add("qsa_work", { HI("M", 3), HI("n", 40), HI("ratio", 2), HI("ring", 3), HI("seqs", 3), @@ -523,6 +564,9 @@ std::vector build_cases() { add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8), HI("top_k", 2), HI("group", 128), HS("a_order", order), HS("dtype", "fp8a8") }); + add("moe_gemm_q", + { HI("M", 9), HI("N", 128), HI("K", 256), HI("n_expert", 8), HI("top_k", 2), + HI("group", 128), HS("a_order", order), HS("dtype", "fp8a8f32") }); } /* Two classes at different widths: a gate/up pair whose odd experts are half as wide * (the output's second part begins past the odd class's zeros), and a down projection diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index e1fa8986..2898a0c0 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -526,6 +526,126 @@ void shape_cases(std::vector& hs) { .pi("M", BAND).pi("heads", 4).pi("ngram", 3).pi("eos", 5); hs.push_back(std::move(n)); } + /* GLM's two-copy speculative state, including a nonempty previous replay window. */ + for (const char* mode : { "prefill", "verify" }) + for (int accepted : { 1, 2, 3 }) + for (int cold : { 0, 1 }) { + constexpr int64_t D = 128; + Hand h("KDA anchor accepted-prefix replay", "kda_update", 0.01); + h.dense(RAD_BF16, { 2, 1, D }, hfill(201, 0.25f)) + .dense(RAD_BF16, { 2, 1, D }, hfill(202, 0.25f)) + .dense(RAD_BF16, { 2, 1, D }, hfill(203, 0.25f)) + .dense(RAD_BF16, { 2, 1, D }, hfill(204, 0.25f)) + .dense(RAD_BF16, { 2, 1 }, hfill(205, 0.25f)) + .dense(RAD_F32, { 1 }, [](int64_t) { return 0.0f; }) + .dense(RAD_F32, { D }, [](int64_t) { return -1.0f; }) + .dense( + RAD_F32, { 2, 1, D, D }, + [](int64_t i) { + if (i < D * D) return 0.125f; + i -= D * D; + if (!i) return 3.0f; + if (i > 3 * 385) return 0.0f; + const int at = (int)((i - 1) % 385); + return at < 128 ? 0.01f : at < 256 ? 0.125f : at < 384 ? 0.75f : 0.5f; + }, + true) + .dense(RAD_I32, { 1, 6 }, [](int64_t i) { return i < 3 ? 0.0f : 1.0f; }) + .idx({ 0, 2 }) + .idx({ accepted }) + .idx({ cold ? 0 : 1 }) + .dense(RAD_BF16, { 2, 1, D }, hfill(206), true) + .pi("M", 2) + .pi("heads", 1) + .pi("head_k", D) + .pi("head_v", D) + .pf("lower_bound", -5) + .pf("scale", 1.0 / std::sqrt(128.0)) + .pf("l2_eps", 1e-6) + .ps("mode", mode) + .ps("dtype", "bf16") + .ps("state_form", "anchor"); + hs.push_back(std::move(h)); + } + for (const char* mode : { "absorb", "expand" }) { + const bool absorb = !std::strcmp(mode, "absorb"); + const int64_t in = absorb ? 17 : 31, out = absorb ? 31 : 17; + Hand h("MLA flattened linear inputs and outputs", "mla_project", 0.01); + h.view(RAD_BF16, { 3, 2 * in }, { 2 * in + 7, 1 }, 3 * (2 * in + 7), hfill(215, 0.25f)) + .dense(RAD_BF16, { 68, 31 }, hfill(216, 0.25f)) + .view(RAD_BF16, { 3, 2 * out }, { 2 * out + 9, 1 }, 3 * (2 * out + 9), hfill(217), true) + .pi("M", 3) + .pi("heads", 2) + .pi("head_dim", 17) + .pi("latent_dim", 31) + .ps("mode", mode) + .ps("dtype", "bf16"); + hs.push_back(std::move(h)); + } + { + Hand h("MoE preserves F32 probabilities with BF16 experts", "moe_gather", 1e-5); + h.dense(RAD_BF16, { 2, 1 }, [](int64_t i) { return i ? -1024.0f : 1024.0f; }) + .dense(RAD_F32, { 1, 2 }, [](int64_t i) { return i ? 1.0f : 1.0f + 1.0f / 8192; }) + .idx({ 0, 1 }) + .none() + .none() + .dense( + RAD_BF16, { 1, 1 }, [](int64_t) { return 0.0f; }, true) + .pi("M", 1) + .pi("n", 1) + .pi("top_k", 2) + .ps("dtype", "bf16"); + hs.push_back(std::move(h)); + } + /* Packed index pages share code and scale storage, including pitched cache pages. */ + { + Hand h("DSA pool writes pitched managed pages", "dsa_pool", 0.001); + h.dense(RAD_BF16, { 28, 256 }, hfill(211, 0.25f)) + .dense(RAD_F32, { 4, 128 }, hfill(212, 0.125f)) + .dense( + RAD_F8E4M3, { 7, 128 }, [](int64_t) { return 0.0f; }, true) + .dense( + RAD_F32, { 7, 1 }, [](int64_t) { return 0.0f; }, true) + .idx({ 4, -1, 2, 99, 1, 0, 3 }) + .view( + RAD_U8, { 5, 1, 4, 34 }, { 160, 136, 34, 1 }, 5 * 160, + [](int64_t) { return 165.0f; }, true) + .pi("M", 7) + .pi("n", 128) + .pi("ratio", 4) + .ps("dtype", "bf16"); + hs.push_back(std::move(h)); + Hand s("DSA scorer reads embedded scales", "dsa_score", 1e-5); + s.dense(RAD_F8E4M3, { 64, 128 }, hfill(213, 0.25f)) + .dense(RAD_F32, { 64, 1 }, [](int64_t) { return 0.5f; }) + .dense(RAD_F32, { 2, 32 }, hfill(214)) + .view(RAD_U8, { 5, 1, 4, 34 }, { 160, 136, 34, 1 }, 5 * 160, + [](int64_t i) { + const int d = (int)(i % 160); + if (d < 128) return (float)(48 + i % 9); + // Little-endian F32 scale 0.5; all padding stays poisoned. + return d == 128 || d == 129 ? 0.0f + : d == 130 ? 0.0f + : d == 131 ? 63.0f + : 165.0f; + }) + .none() + .dense(RAD_I32, { 1, 4 }, + [](int64_t i) { + return (float)(i == 1 ? -1 : i == 3 ? 99 : i); + }) + .idx({ 0, 2 }) + .idx({ 4 }) + .dense( + RAD_F32, { 2, 4 }, [](int64_t) { return 0.0f; }, true) + .pi("M", 2) + .pi("n", 128) + .pi("heads", 32) + .pi("blocks", 4) + .pi("seqs", 1) + .ps("dtype", "fp8_e4m3"); + hs.push_back(std::move(s)); + } /* ---- packed weight codes at odd element offsets ------------------------------------------ */ { const int64_t M = 2, N = 4, K = 33; @@ -2729,6 +2849,69 @@ void qsa_cases(std::vector& hs) { .pi("M", M).pi("blocks", nb).pi("topk", topk).pi("ratio", ratio).pi("seqs", 1); hs.push_back(std::move(h)); } + { + /* The signed order, against the rule: row 0 ranks 2 over the tie of -0 and +0 (NaN dead, + * -1e31 live), row 1 is all negative with -inf dead and -1e30 live. Under the unsigned + * order both rows would rank as zeros. */ + static const float v[2][8] = { + { -3.0f, -1.0f, -0.0f, 2.0f, -1.0f, 0.0f, NAN, -1e31f }, + { -5.0f, -2e30f, -7.0f, -6.0f, -INFINITY, -9.0f, -1e30f, -8.0f } }; + Hand h("signed: negative scores, -0 tying +0, NaN and -inf dead", "qsa_select", 0.0); + h.dense(RAD_F32, { 2, 8 }, [](int64_t i) { return v[i / 8][i % 8]; }) + .dense(RAD_I32, { 2, 8 }, [](int64_t i) { return (float)(100 + 10 * (i / 8) + i % 8); }) + .idx({ 8, 8 }) + .idx({ 31, 31 }) + .idx({ 0, 1, 2 }) + .dense(RAD_I32, { 2, 4 }, sent, true) + .dense(RAD_I32, { 2 }, sent, true) + .dense(RAD_I32, { 2 }, sent, true) + .pi("M", 2).pi("blocks", 8).pi("topk", 3).pi("ratio", 4).pi("seqs", 2).pi("signed", 1) + .expect(5, { 103, 102, 105, -1, 110, 113, 112, -1 }); + hs.push_back(std::move(h)); + } + { + /* The column-slice case's scores, shifted to straddle zero, under the signed order. */ + const int64_t S = 2, M = 6, live = 40, pitch = 56, W = 48, topk = 8, ratio = 4; + Hand h("signed: cu from 1, unheld rows, a column slice, ties across zero", "qsa_select", + 0.0); + h.view(RAD_F32, { M, live }, { pitch, 1 }, M * pitch, [=](int64_t i) { + switch ((i % pitch + i / pitch) % 9) { + case 0: case 1: case 7: return -1.0f; + case 2: return NAN; + case 3: return INFINITY; + case 4: return -0.0f; + case 5: return -INFINITY; + case 6: return -1.5f; + default: return 0.25f * (float)(i % 5) - 0.5f; + } + }) + .dense(RAD_I32, { S, W }, [](int64_t i) { + return i % 11 == 4 ? -1.0f : (float)((i * 13 + 3) % 500); + }) + .idx({ 40, 25 }) + .idx({ 160, 98, 99, 161, 40, 7 }) + .idx({ 1, 3, 5 }) + .dense(RAD_I32, { M, topk + 1 }, sent, true) + .dense(RAD_I32, { M }, sent, true) + .dense(RAD_I32, { M }, sent, true) + .pi("M", M).pi("blocks", W).pi("topk", topk).pi("ratio", ratio).pi("seqs", S) + .pi("signed", 1); + hs.push_back(std::move(h)); + } + { + Hand h("a `signed` other than 0 or 1 is refused before any write", "qsa_select", 0.0); + h.dense(RAD_F32, { 1, 4 }, hfill(208)) + .dense(RAD_I32, { 1, 4 }, [](int64_t i) { return (float)i; }) + .idx({ 4 }) + .idx({ 15 }) + .idx({ 0, 1 }) + .dense(RAD_I32, { 1, 3 }, sent, true) + .dense(RAD_I32, { 1 }, sent, true) + .dense(RAD_I32, { 1 }, sent, true) + .pi("M", 1).pi("blocks", 4).pi("topk", 2).pi("ratio", 4).pi("seqs", 1).pi("signed", 2) + .refuses(RAD_E_INVAL); + hs.push_back(std::move(h)); + } { Hand h("a negative block count is refused before any write", "qsa_select", 0.0); h.dense(RAD_F32, { 1, 4 }, hfill(207)) diff --git a/libavx/avx_dsa.cpp b/libavx/avx_dsa.cpp new file mode 100644 index 00000000..08f25015 --- /dev/null +++ b/libavx/avx_dsa.cpp @@ -0,0 +1,201 @@ +#include "avx_vec.h" +#include "avx_common.h" +#include +#include +using namespace avx; + +AVX_KERNEL(dsa_query) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const auto &x = a->t[0], &q = a->t[1], &s = a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n < 1 || n > 256 || (n & (n - 1)) || x.rank != 2 || q.rank != 2 || s.rank != 2 || + x.shape[0] < 1 || q.shape[0] != x.shape[0] || x.shape[1] != n || q.shape[1] != n || + s.shape[0] != x.shape[0] || s.shape[1] != 1) + return RAD_E_SHAPE; + if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE; + if (!x.data || !q.data || !s.data) return RAD_E_INVAL; + AVX_PARALLEL_FOR_IF(x.shape[0] * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < x.shape[0]; ++r) { + float v[256]; + for (int64_t d = 0; d < n; ++d) v[d] = ldt(&x, r * x.stride[0] + d * x.stride[1]); + for (int64_t h = 1; h < n; h *= 2) + for (int64_t i = 0; i < n; i += 2 * h) + for (int64_t j = 0; j < h; ++j) { + const float lo = v[i + j], hi = v[i + j + h]; + v[i + j] = lo + hi; + v[i + j + h] = lo - hi; + } + float am = 1e-4f; + const float norm = 1.0f / std::sqrt((float)n); + for (int64_t d = 0; d < n; ++d) { + v[d] = rad_bf16_to_f32(rad_f32_to_bf16(v[d] * norm)); + am = std::max(am, std::fabs(v[d])); + } + int exponent = 0; + const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent); + const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f)); + stt(&s, r * s.stride[0], sc); + for (int64_t d = 0; d < n; ++d) + stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(v[d] / sc, -448.0f, 448.0f)); + } + return RAD_OK; +} + +AVX_KERNEL(dsa_score) { + if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL; + RadTensor q = a->t[0], qs = a->t[1]; + const auto& g = a->t[2]; + RadTensor k = a->t[3], ks = a->t[4]; + const bool packed = k.dtype == RAD_U8; + if (packed) { + if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 || + k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 || + ((uintptr_t)k.data & 3)) + return RAD_E_SHAPE; + ks = {}; + ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr; + ks.dtype = RAD_F32; + ks.rank = 1; + ks.shape[0] = k.shape[0]; + ks.stride[0] = k.stride[0] / 4; + k.dtype = RAD_F8E4M3; + k.rank = 2; + k.shape[1] = 128; + k.stride[1] = 1; + } + const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &out = a->t[8]; + const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0); + if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && + q.shape[0] == out.shape[0] * h && qs.shape[0] == q.shape[0]) { + q.rank = 3; + q.shape[0] = out.shape[0]; + q.shape[2] = q.shape[1]; + q.shape[1] = h; + q.stride[2] = q.stride[1]; + q.stride[1] = q.stride[0]; + q.stride[0] *= h; + qs.shape[0] = out.shape[0]; + qs.shape[1] = h; + qs.stride[1] = qs.stride[0]; + qs.stride[0] *= h; + } + if (n < 1 || h < 1 || h > 64 || q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || + q.shape[2] != n || qs.rank != 2 || g.rank != 2 || qs.shape[0] != q.shape[0] || + g.shape[0] != q.shape[0] || qs.shape[1] != h || g.shape[1] != h || k.rank != 2 || + k.shape[1] != n || ks.rank != 1 || ks.shape[0] != k.shape[0] || bt.rank != 2 || + cu.rank != 1 || nc.rank != 1 || cu.shape[0] != bt.shape[0] + 1 || + nc.shape[0] != bt.shape[0] || out.rank != 2 || out.shape[0] != q.shape[0] || + out.shape[1] > bt.shape[1]) + return RAD_E_SHAPE; + if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 || + ks.dtype != RAD_F32 || g.dtype != RAD_F32 || bt.dtype != RAD_I32 || cu.dtype != RAD_I32 || + nc.dtype != RAD_I32 || out.dtype != RAD_F32) + return RAD_E_DTYPE; + for (int i = 0; i < 9; ++i) + if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL; + const float norm = 1.0f / std::sqrt((float)(h * n)); + AVX_PARALLEL_FOR_IF(q.shape[0] * out.shape[1] * h * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < q.shape[0]; ++r) { + int64_t seq = -1; + for (int64_t s = 0; s < bt.shape[0]; ++s) + if (r >= ld_int_dt(cu.dtype, cu.data, s * cu.stride[0]) && + r < ld_int_dt(cu.dtype, cu.data, (s + 1) * cu.stride[0])) { + seq = s; + break; + } + const int64_t live = seq >= 0 ? ld_int_dt(nc.dtype, nc.data, seq * nc.stride[0]) : 0; + for (int64_t b = 0; b < out.shape[1]; ++b) { + const int64_t page = + seq >= 0 && b < live + ? ld_int_dt(bt.dtype, bt.data, seq * bt.stride[0] + b * bt.stride[1]) + : -1; + float result = -INFINITY; + if (page >= 0 && page < k.shape[0]) { + result = 0; + for (int64_t head = 0; head < h; ++head) { + float dot = 0; + for (int64_t d = 0; d < n; ++d) + dot += ldt(&q, r * q.stride[0] + head * q.stride[1] + d * q.stride[2]) * + ldt(&k, page * k.stride[0] + d * k.stride[1]); + result += std::max(dot, 0.0f) * + ldt(&qs, r * qs.stride[0] + head * qs.stride[1]) * + ldt(&g, r * g.stride[0] + head * g.stride[1]); + } + result *= ldt(&ks, page * ks.stride[0]) * norm; + } + stt(&out, r * out.stride[0] + b * out.stride[1], result); + } + } + return RAD_OK; +} + +AVX_KERNEL(dsa_pool) { + if (p_int(a, "block_size", 4) != 4) return RAD_E_SHAPE; + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3]; + const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0); + const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5); + if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL; + if (cache && + (n != 128 || ratio != 4 || page->dtype != RAD_I32 || page->rank != 1 || + page->shape[0] != q.shape[0] || page->stride[0] < 1 || cache->dtype != RAD_U8 || + cache->rank != 4 || cache->shape[0] < 1 || cache->shape[1] != 1 || cache->shape[2] != 4 || + cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 || + cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3))) + return RAD_E_SHAPE; + if (n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16 || kg.rank != 2 || + ape.rank != 2 || q.rank != 2 || s.rank != 2 || q.shape[0] < 1 || !kg.data || !ape.data || + !q.data || !s.data || kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 || + q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32 || kg.shape[0] != q.shape[0] * ratio || + kg.shape[1] != 2 * n || ape.shape[0] != ratio || ape.shape[1] != n || q.shape[1] != n || + s.shape[0] != q.shape[0] || s.shape[1] != 1) + return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(q.shape[0] * n * ratio >= AVX_PAR_MIN) + for (int64_t r = 0; r < q.shape[0]; ++r) { + float x[256]; + for (int64_t d = 0; d < n; ++d) { + float g[16], mx = -INFINITY; + for (int64_t j = 0; j < ratio; ++j) { + g[j] = ldt(&kg, (r * ratio + j) * kg.stride[0] + (n + d) * kg.stride[1]) + + ldt(&ape, j * ape.stride[0] + d * ape.stride[1]); + mx = std::max(mx, g[j]); + } + float z = 0, den = 0; + for (int64_t j = 0; j < ratio; ++j) { + const float p = std::exp(g[j] - mx); + z += p * ldt(&kg, (r * ratio + j) * kg.stride[0] + d * kg.stride[1]); + den += p; + } + x[d] = rad_bf16_to_f32(rad_f32_to_bf16(z / den)); + } + for (int64_t step = 1; step < n; step *= 2) + for (int64_t base = 0; base < n; base += 2 * step) + for (int64_t j = 0; j < step; ++j) { + const float lo = x[base + j], hi = x[base + j + step]; + x[base + j] = lo + hi; + x[base + j + step] = lo - hi; + } + float am = 1e-4f; + const float norm = 1.0f / std::sqrt((float)n); + for (int64_t d = 0; d < n; ++d) { + x[d] = rad_bf16_to_f32(rad_f32_to_bf16(x[d] * norm)); + am = std::max(am, std::fabs(x[d])); + } + int exponent = 0; + const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent); + const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f)); + stt(&s, r * s.stride[0], sc); + for (int64_t d = 0; d < n; ++d) + stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(x[d] / sc, -448.0f, 448.0f)); + if (cache) { + const int64_t p = ldi(page, r * page->stride[0]); + if (p >= 0 && p < cache->shape[0]) { + auto* dst = (uint8_t*)cache->data + p * cache->stride[0]; + for (int d = 0; d < 128; ++d) + dst[d] = ((uint8_t*)q.data)[r * q.stride[0] + d * q.stride[1]]; + std::memcpy(dst + 128, &sc, sizeof(sc)); + } + } + } + return RAD_OK; +} diff --git a/libavx/avx_glm.cpp b/libavx/avx_glm.cpp new file mode 100644 index 00000000..5c7d9b5f --- /dev/null +++ b/libavx/avx_glm.cpp @@ -0,0 +1,507 @@ +/* Host mHC and bounded KDA. Widen each activation row once, then reduce the + * projections and state products with this ISA level's vector operations. */ +#include "avx_vec.h" +#include "avx_common.h" +#include + +using namespace avx; + +namespace { +bool matrix(const RadTensor& t, int64_t r, int64_t c) { + return t.data && t.rank == 2 && t.shape[0] == r && t.shape[1] == c; +} +float dot(const float* x, const float* y, int64_t n) { + vf acc = vf_zero(); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) acc = vf_fma(vf_loadu(x + i), vf_loadu(y + i), acc); + float s = vf_hsum(acc); + for (; i < n; ++i) s += x[i] * y[i]; + return s; +} +void sinkhorn(float* c, int h, int repeats, float eps) { + for (int r = 0; r < h; ++r) { + float max = -INFINITY; + for (int k = 0; k < h; ++k) max = std::max(max, c[r * h + k]); + float total = 0; + for (int k = 0; k < h; ++k) { + c[r * h + k] = std::exp(c[r * h + k] - max); + total += c[r * h + k]; + } + for (int k = 0; k < h; ++k) c[r * h + k] = c[r * h + k] / total + eps; + } + for (int it = 0; it < repeats; ++it) { + if (it) + for (int r = 0; r < h; ++r) { + float total = 0; + for (int k = 0; k < h; ++k) total += c[r * h + k]; + for (int k = 0; k < h; ++k) c[r * h + k] /= total + eps; + } + for (int k = 0; k < h; ++k) { + float total = 0; + for (int r = 0; r < h; ++r) total += c[r * h + k]; + for (int r = 0; r < h; ++r) c[r * h + k] /= total + eps; + } + } +} +bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t dim) { + return t.data && t.shape[0] == tokens && + ((t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim) || + (t.rank == 2 && t.shape[1] == heads * dim)); +} +int64_t at(const RadTensor& t, int64_t token, int64_t h, int64_t d, int64_t width) { + return token * t.stride[0] + h * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) + + d * laststride(&t); +} +} + +AVX_KERNEL(gemm_nt_f32) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const auto &x = a->t[0], &w = a->t[1], &y = a->t[2]; + const int64_t n = p_int(a, "N", 0), k = p_int(a, "K", 0); + if (n < 1 || k < 1 || x.rank != 2 || w.rank != 2 || y.rank != 2 || x.shape[0] < 1 || + x.shape[1] != k || w.shape[0] != n || w.shape[1] != k || y.shape[0] != x.shape[0] || + y.shape[1] != n) + return RAD_E_SHAPE; + if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE; + if (!x.data || !w.data || !y.data) return RAD_E_INVAL; + AVX_PARALLEL_FOR_IF(x.shape[0] * n * k >= AVX_PAR_MIN) + for (int64_t r = 0; r < x.shape[0]; ++r) { + float* query = scratch_f32((size_t)k); + for (int64_t j = 0; j < k; ++j) query[j] = ldt(&x, r * x.stride[0] + j * x.stride[1]); + for (int64_t col = 0; col < n; ++col) { + float sum = 0; + if (w.stride[1] == 1) + sum = dot(query, (const float*)w.data + col * w.stride[0], k); + else + for (int64_t j = 0; j < k; ++j) + sum += query[j] * ldt(&w, col * w.stride[0] + j * w.stride[1]); + stt(&y, r * y.stride[0] + col * y.stride[1], sum); + } + } + return RAD_OK; +} + +AVX_KERNEL(router_sigmoid_topk) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3]; + const int64_t ne = p_int(a, "n_expert", 0), k = p_int(a, "top_k", 0); + const float factor = p_f32(a, "route_scale", 0); + if (ne < 1 || ne > 512 || k < 1 || k > ne || !std::isfinite(factor) || factor <= 0 || + lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 || + bias.shape[0] != ne || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || + !matrix(ids, lg.shape[0], k) || !matrix(w, lg.shape[0], k) || !lg.data || !bias.data) + return RAD_E_SHAPE; + for (int64_t r = 0; r < lg.shape[0]; ++r) { + float prob[512], ranked[512], chosen[512]; + int index[512]; + for (int64_t e = 0; e < ne; ++e) { + prob[e] = 1.0f / (1.0f + std::exp(-ldt(&lg, rowoff(&lg, r, ne) + e * laststride(&lg)))); + ranked[e] = prob[e] + ldt(&bias, e * laststride(&bias)); + } + float total = 0; + for (int64_t j = 0; j < k; ++j) { + int winner = -1; + for (int64_t e = 0; e < ne; ++e) + if (ranked[e] > -INFINITY && (winner < 0 || ranked[e] > ranked[winner])) + winner = (int)e; + if (winner < 0) return RAD_E_SHAPE; + index[j] = winner; + chosen[j] = prob[winner]; + total += chosen[j]; + ranked[winner] = -INFINITY; + } + const float mult = p_int(a, "norm", 0) ? factor / (total + 1e-20f) : factor; + for (int64_t j = 0; j < k; ++j) { + st_int_dt(ids.dtype, ids.data, rowoff(&ids, r, k) + j * laststride(&ids), index[j]); + stt(&w, rowoff(&w, r, k) + j * laststride(&w), chosen[j] * mult); + } + } + return RAD_OK; +} + +AVX_KERNEL(swiglu_clamped) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const auto &gu = a->t[0], &y = a->t[1]; + const int64_t n = p_int(a, "n", 0); + const float limit = p_f32(a, "limit", 0); + if (n < 1 || !std::isfinite(limit) || limit <= 0 || gu.rank != 2 || y.rank != 2 || !gu.data || + !y.data || y.shape[0] < 1 || gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n || + y.shape[1] != n) + return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(y.shape[0] * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < y.shape[0]; ++r) { + for (int64_t i = 0; i < n; ++i) { + const int64_t b = rowoff(&gu, r, 2 * n), s = laststride(&gu); + const float g = std::min(ldt(&gu, b + i * s), limit); + const float u = std::clamp(ldt(&gu, b + (n + i) * s), -limit, limit); + stt(&y, rowoff(&y, r, n) + i * laststride(&y), (g / (1.0f + std::exp(-g))) * u); + } + } + return RAD_OK; +} + +namespace { +int64_t part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; } +bool pre_params(const RadArgs* a, int64_t* n, int64_t* hc, int64_t* iters, float* eps, + float* heps) { + *n = p_int(a, "n", 0); + *hc = p_int(a, "hc", 0); + *iters = p_int(a, "iterations", 0); + *eps = p_f32(a, "eps", 0); + *heps = p_f32(a, "hc_eps", 0); + return *n >= 1 && *hc >= 2 && *hc <= 8 && *iters >= 1 && *iters <= 256 && std::isfinite(*eps) && + *eps > 0 && std::isfinite(*heps) && *heps >= 0; +} +bool pre_outputs(const RadTensor& h, const RadTensor& scale, const RadTensor& base, + const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t rows, + int64_t n, int64_t hc) { + const int64_t mix = hc * (hc + 2); + return matrix(h, rows, hc * n) && scale.rank == 1 && scale.dtype == RAD_F32 && + numel(&scale) == 3 && base.rank == 1 && base.dtype == RAD_F32 && numel(&base) == mix && + matrix(x, rows, n) && matrix(post, rows, hc) && matrix(comb, rows, hc * hc) && + post.dtype == RAD_F32 && comb.dtype == RAD_F32; +} +/* Row r from its RMS-scaled coefficients and the widened residual row hv. */ +void finish_row(const float* coeff, const float* hv, const RadTensor& scale, const RadTensor& base, + const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t r, + int64_t n, int64_t hc, int64_t iters, float heps) { + float pre[8], c[64]; + for (int64_t j = 0; j < hc; ++j) { + pre[j] = + 1.0f / (1.0f + + std::exp(-(coeff[j] * ldt(&scale, 0) + ldt(&base, j * laststride(&base))))) + + heps; + const float z = coeff[hc + j] * ldt(&scale, laststride(&scale)) + + ldt(&base, (hc + j) * laststride(&base)); + stt(&post, rowoff(&post, r, hc) + j * laststride(&post), 2.0f / (1.0f + std::exp(-z))); + } + for (int64_t j = 0; j < hc * hc; ++j) + c[j] = coeff[2 * hc + j] * ldt(&scale, 2 * laststride(&scale)) + + ldt(&base, (2 * hc + j) * laststride(&base)); + sinkhorn(c, (int)hc, (int)iters, heps); + for (int64_t j = 0; j < hc * hc; ++j) + stt(&comb, rowoff(&comb, r, hc * hc) + j * laststride(&comb), c[j]); + for (int64_t i = 0; i < n; ++i) { + float v = 0; + for (int64_t j = 0; j < hc; ++j) v += pre[j] * hv[j * n + i]; + stt(&x, rowoff(&x, r, n) + i * laststride(&x), v); + } +} +/* fn row j over columns [lo, lo+len), contiguous or through the scratch fw. */ +float fn_dot(const float* hv, const RadTensor& fn, int64_t j, int64_t width, int64_t lo, + int64_t len, float* fw) { + const int64_t fb = rowoff(&fn, j, width); + if (laststride(&fn) == 1) return dot(hv + lo, (const float*)fn.data + fb + lo, len); + for (int64_t i = 0; i < len; ++i) fw[i] = ldt(&fn, fb + (lo + i) * laststride(&fn)); + return dot(hv + lo, fw, len); +} +void widen(const RadTensor& h, int64_t r, int64_t width, float* hv) { + for (int64_t i = 0; i < width; ++i) hv[i] = ldt(&h, rowoff(&h, r, width) + i * laststride(&h)); +} +} + +AVX_KERNEL(mhc_pre) { + if (!rad_args_have(a, 7)) return RAD_E_INVAL; + int64_t n, hc, iters; + float eps, heps; + if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE; + const auto &h = a->t[0], &fn = a->t[1], &scale = a->t[2], &base = a->t[3]; + const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6]; + if (h.rank != 2) return RAD_E_SHAPE; + const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2); + if (rows < 1 || !matrix(fn, mix, width) || fn.dtype != RAD_F32 || + !pre_outputs(h, scale, base, x, post, comb, rows, n, hc)) + return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(rows * width * mix >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* scratch = scratch_f32((size_t)(2 * width)); + float* hv = scratch; + float* fw = hv + width; + widen(h, r, width, hv); + const float norm = 1.0f / std::sqrt(dot(hv, hv, width) / (float)width + eps); + float coeff[80]; + for (int64_t j = 0; j < mix; ++j) coeff[j] = fn_dot(hv, fn, j, width, 0, width, fw) * norm; + finish_row(coeff, hv, scale, base, x, post, comb, r, n, hc, iters, heps); + } + return RAD_OK; +} + +AVX_KERNEL(mhc_pre_partial) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0), chunk = p_int(a, "chunk", 0); + const int64_t first = p_int(a, "first", -1), count = p_int(a, "chunks", 0); + if (n < 1 || hc < 2 || hc > 8 || chunk < 1 || (hc * n) % chunk || first < 0 || count < 1 || + first + count > hc * n / chunk) + return RAD_E_SHAPE; + const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2]; + if (h.rank != 2) return RAD_E_SHAPE; + const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2), S = part_stride(hc); + if (rows < 1 || !matrix(h, rows, width) || !matrix(fn, mix, width) || fn.dtype != RAD_F32 || + !matrix(part, rows, count * S) || part.dtype != RAD_F32) + return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(rows * count * chunk * mix >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* scratch = scratch_f32((size_t)(width + chunk)); + float* hv = scratch; + float* fw = hv + width; + widen(h, r, width, hv); + const int64_t pb = rowoff(&part, r, count * S), ps = laststride(&part); + for (int64_t c = 0; c < count; ++c) { + const int64_t lo = (first + c) * chunk; + for (int64_t j = 0; j < S; ++j) { + const float v = j < mix ? fn_dot(hv, fn, j, width, lo, chunk, fw) + : j == mix ? dot(hv + lo, hv + lo, chunk) + : 0.0f; + stt(&part, pb + (c * S + j) * ps, v); + } + } + } + return RAD_OK; +} + +AVX_KERNEL(mhc_pre_finish) { + if (!rad_args_have(a, 7)) return RAD_E_INVAL; + int64_t n, hc, iters; + float eps, heps; + if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE; + const int64_t chunk = p_int(a, "chunk", 0); + if (chunk < 1 || (hc * n) % chunk) return RAD_E_SHAPE; + const auto &part = a->t[0], &h = a->t[1], &scale = a->t[2], &base = a->t[3]; + const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6]; + if (h.rank != 2) return RAD_E_SHAPE; + const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2), S = part_stride(hc), + chunks = width / chunk; + if (rows < 1 || !matrix(part, rows, chunks * S) || part.dtype != RAD_F32 || + !pre_outputs(h, scale, base, x, post, comb, rows, n, hc)) + return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(rows * width >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* hv = scratch_f32((size_t)width); + widen(h, r, width, hv); + const int64_t pb = rowoff(&part, r, chunks * S), ps = laststride(&part); + float sq = 0; + for (int64_t c = 0; c < chunks; ++c) sq += ldt(&part, pb + (c * S + mix) * ps); + const float norm = 1.0f / std::sqrt(sq / (float)width + eps); + float coeff[80]; + for (int64_t j = 0; j < mix; ++j) { + float d = 0; + for (int64_t c = 0; c < chunks; ++c) d += ldt(&part, pb + (c * S + j) * ps); + coeff[j] = d * norm; + } + finish_row(coeff, hv, scale, base, x, post, comb, r, n, hc, iters, heps); + } + return RAD_OK; +} + +AVX_KERNEL(mhc_post) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0); + if (n < 1 || hc < 2 || hc > 8) return RAD_E_SHAPE; + const auto &x = a->t[0], &h = a->t[1], &p = a->t[2], &c = a->t[3], &o = a->t[4]; + if (x.rank != 2) return RAD_E_SHAPE; + const int64_t rows = x.shape[0]; + if (rows < 1 || !matrix(x, rows, n) || !matrix(h, rows, hc * n) || !matrix(p, rows, hc) || + !matrix(c, rows, hc * hc) || !matrix(o, rows, hc * n) || o.data == h.data || + p.dtype != RAD_F32 || c.dtype != RAD_F32) + return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(rows * n * hc >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + for (int64_t dst = 0; dst < hc; ++dst) + for (int64_t i = 0; i < n; ++i) { + float v = 0; + for (int64_t src = 0; src < hc; ++src) + v += ldt(&c, rowoff(&c, r, hc * hc) + (src * hc + dst) * laststride(&c)) * + ldt(&h, rowoff(&h, r, hc * n) + (src * n + i) * laststride(&h)); + v += ldt(&p, rowoff(&p, r, hc) + dst * laststride(&p)) * + ldt(&x, rowoff(&x, r, n) + i * laststride(&x)); + stt(&o, rowoff(&o, r, hc * n) + (dst * n + i) * laststride(&o), v); + } + } + return RAD_OK; +} + +AVX_KERNEL(mhc_contract) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0); + if (n < 1 || hc < 2 || hc > 8) return RAD_E_SHAPE; + const auto &h = a->t[0], &x = a->t[1]; + if (h.rank != 2 || h.shape[0] < 1 || !matrix(h, h.shape[0], hc * n) || + !matrix(x, h.shape[0], n)) + return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(h.shape[0] * n * hc >= AVX_PAR_MIN) + for (int64_t r = 0; r < h.shape[0]; ++r) + for (int64_t i = 0; i < n; ++i) { + float v = 0; + for (int64_t j = 0; j < hc; ++j) + v += ldt(&h, rowoff(&h, r, hc * n) + (j * n + i) * laststride(&h)); + stt(&x, rowoff(&x, r, n) + i * laststride(&x), v / (float)hc); + } + return RAD_OK; +} + +AVX_KERNEL(kda_update) { + if (!a || a->n_t < 13) return RAD_E_INVAL; + for (int i = 0; i < 10; ++i) + if (!rad_arg_in(a, i)) return RAD_E_INVAL; + if (!rad_arg_in(a, 12)) return RAD_E_INVAL; + const int64_t H = p_int(a, "heads", 0), K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0); + const float lower = p_f32(a, "lower_bound", 0), eps = p_f32(a, "l2_eps", 1e-6f), + scale = p_f32(a, "scale", 1); + const char* mode = p_str(a, "mode", ""); + const bool verify = !std::strcmp(mode, "verify"); + const char* form = p_str(a, "state_form", "per_candidate"); + const bool anchor = !std::strcmp(form, "anchor"); + if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL; + if (anchor && (K != 128 || V != 128)) return RAD_E_UNSUPPORTED; + if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL; + if (H < 1 || K < 1 || K > 128 || V < 1 || V > 128 || !std::isfinite(lower) || lower >= 0 || + !std::isfinite(eps) || eps <= 0 || !std::isfinite(scale)) + return RAD_E_SHAPE; + const auto &q = a->t[0], &k = a->t[1], &v = a->t[2], &g = a->t[3], &b = a->t[4]; + const auto &al = a->t[5], &bias = a->t[6], &s = a->t[7], &idx = a->t[8], &cu = a->t[9], + &out = a->t[12]; + const auto* accepted = rad_arg_in(a, 10); + const auto* init = rad_arg_in(a, 11); + if (q.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE; + const int64_t T = q.shape[0], N = cu.shape[0] - 1, slots = s.shape[0]; + if (T < 1) return RAD_E_SHAPE; + if (!headed(q, T, H, K) || !headed(k, T, H, K) || !headed(v, T, H, V) || !headed(g, T, H, K) || + !headed(b, T, H, 1) || !headed(out, T, H, V) || numel(&al) != H || numel(&bias) != H * K || + s.rank != 4 || s.dtype != RAD_F32 || s.shape[1] != H || s.shape[2] != V || + s.shape[3] != K || idx.rank != 2 || idx.dtype != RAD_I32 || idx.shape[0] < N || + idx.shape[1] < 1 || (accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) || + (init && (init->dtype != RAD_I32 || numel(init) < N))) + return RAD_E_SHAPE; + const int64_t width = idx.shape[1]; + for (int64_t seq = 0; seq < N; ++seq) { + const int64_t begin = ldi(&cu, seq * cu.stride[0]); + const int64_t end = ldi(&cu, (seq + 1) * cu.stride[0]); + const int64_t na = accepted ? ldi(accepted, offlin(accepted, seq)) : 1; + if (begin < 0 || end < begin || end > T || na < 1 || na > (anchor ? 32 : width) || + (verify && end - begin > (anchor ? 32 : width)) || (anchor && width < 2)) + return RAD_E_SHAPE; + for (int64_t j = 0; j < width; ++j) + if (ldi(&idx, seq * idx.stride[0] + j * idx.stride[1]) >= slots) return RAD_E_SHAPE; + if (anchor) { + const int64_t read = ldi(&idx, seq * idx.stride[0]); + const int64_t scratch = ldi(&idx, seq * idx.stride[0] + (width / 2) * idx.stride[1]); + if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE; + if (verify && read >= 0 && (!init || ldi(init, offlin(init, seq)))) + for (int64_t h = 0; h < H; ++h) { + const float count = ldt(&s, scratch * s.stride[0] + h * s.stride[1]); + if (!std::isfinite(count) || count < 0 || count > 32 || + count != std::floor(count) || (count > 0 && na > count)) + return RAD_E_SHAPE; + } + } + } + AVX_PARALLEL_FOR_IF(N * H * V * K >= AVX_PAR_MIN) + for (int64_t sh = 0; sh < N * H; ++sh) { + const int64_t seq = sh / H, head = sh % H; + const int64_t begin = ldi(&cu, seq * cu.stride[0]); + const int64_t end = ldi(&cu, (seq + 1) * cu.stride[0]); + const int64_t na = accepted ? ldi(accepted, offlin(accepted, seq)) : 1; + const int64_t read = + ldi(&idx, seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]); + if (read < 0) { + for (int64_t t = begin; t < end; ++t) + for (int64_t e = 0; e < V; ++e) stt(&out, at(out, t, head, e, V), 0); + continue; + } + float* S = scratch_f32((size_t)(V * K + 3 * K)); + float* qn = S + V * K; + float* kn = qn + K; + float* decay = kn + K; + const bool warm = !init || ldi(init, offlin(init, seq)) != 0; + for (int64_t e = 0; e < V; ++e) + for (int64_t d = 0; d < K; ++d) + S[e * K + d] = warm ? ldt(&s, read * s.stride[0] + head * s.stride[1] + + e * s.stride[2] + d * s.stride[3]) + : 0; + const int64_t scratch = + anchor ? ldi(&idx, seq * idx.stride[0] + (width / 2) * idx.stride[1]) : 0; + auto factor_at = [&](int64_t i) { + return scratch * s.stride[0] + head * s.stride[1] + (i / K) * s.stride[2] + + (i % K) * s.stride[3]; + }; + constexpr int factors = 385; + if (anchor && verify) { + const int replay = warm ? (int)ldt(&s, factor_at(0)) : 0; + for (int t = 0; t < (replay ? na : 0); ++t) { + const int f = 1 + t * factors; + for (int d = 0; d < 128; ++d) { + kn[d] = ldt(&s, factor_at(f + d)); + decay[d] = ldt(&s, factor_at(f + 256 + d)); + } + const float bt = ldt(&s, factor_at(f + 384)); + for (int e = 0; e < 128; ++e) { + float* row = S + e * K; + for (int d = 0; d < 128; d += VF_N) + vf_storeu(row + d, vf_mul(vf_loadu(row + d), vf_loadu(decay + d))); + const float delta = bt * (ldt(&s, factor_at(f + 128 + e)) - dot(row, kn, K)); + for (int d = 0; d < 128; d += VF_N) + vf_storeu(row + d, + vf_fma(vf_set1(delta), vf_loadu(kn + d), vf_loadu(row + d))); + } + } + for (int e = 0; e < 128; ++e) + for (int d = 0; d < 128; ++d) + stt(&s, + read * s.stride[0] + head * s.stride[1] + e * s.stride[2] + d * s.stride[3], + S[e * K + d]); + } + const float gain = std::exp(ldt(&al, head * laststride(&al))); + for (int64_t t = begin; t < end; ++t) { + for (int64_t d = 0; d < K; ++d) { + qn[d] = ldt(&q, at(q, t, head, d, K)); + kn[d] = ldt(&k, at(k, t, head, d, K)); + } + const float qi = scale / std::sqrt(dot(qn, qn, K) + eps), + ki = 1 / std::sqrt(dot(kn, kn, K) + eps); + for (int64_t d = 0; d < K; ++d) { + qn[d] *= qi; + kn[d] *= ki; + const float z = gain * (ldt(&g, at(g, t, head, d, K)) + + ldt(&bias, (head * K + d) * laststride(&bias))); + decay[d] = std::exp(lower / (1 + std::exp(-z))); + } + const float beta = 1 / (1 + std::exp(-ldt(&b, at(b, t, head, 0, 1)))); + if (anchor && verify) { + const int f = 1 + (int)(t - begin) * factors; + for (int d = 0; d < 128; ++d) { + stt(&s, factor_at(f + d), kn[d]); + stt(&s, factor_at(f + 256 + d), decay[d]); + } + for (int e = 0; e < 128; ++e) + stt(&s, factor_at(f + 128 + e), ldt(&v, at(v, t, head, e, V))); + stt(&s, factor_at(f + 384), beta); + } + for (int64_t e = 0; e < V; ++e) { + float* row = S + e * K; + int64_t d = 0; + for (; d + VF_N <= K; d += VF_N) + vf_storeu(row + d, vf_mul(vf_loadu(row + d), vf_loadu(decay + d))); + for (; d < K; ++d) row[d] *= decay[d]; + const float delta = beta * (ldt(&v, at(v, t, head, e, V)) - dot(row, kn, K)); + d = 0; + for (; d + VF_N <= K; d += VF_N) + vf_storeu(row + d, vf_fma(vf_set1(delta), vf_loadu(kn + d), vf_loadu(row + d))); + for (; d < K; ++d) row[d] += delta * kn[d]; + stt(&out, at(out, t, head, e, V), dot(row, qn, K)); + } + if ((!anchor && verify) || (!verify && t + 1 == end)) { + const int64_t write = + ldi(&idx, seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]); + if (write >= 0) + for (int64_t e = 0; e < V; ++e) + for (int64_t d = 0; d < K; ++d) + stt(&s, + write * s.stride[0] + head * s.stride[1] + e * s.stride[2] + + d * s.stride[3], + S[e * K + d]); + } + } + if (anchor) stt(&s, factor_at(0), verify ? (float)(end - begin) : 0.0f); + } + return RAD_OK; +} diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index ac0f9ed9..2081c01c 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -71,6 +71,16 @@ int avx_par_force(int threads); /* ---- elementwise and norms */ \ X(rmsnorm) X(rmsnorm_p) X(rmsnorm_add) X(hc_enter) \ X(hc_read) X(hc_write) X(mtp_enter) X(layernorm) \ + X(mhc_pre) X(mhc_post) X(mhc_contract) X(kda_update) \ + X(mhc_pre_partial) X(mhc_pre_finish) \ + X(swiglu_clamped) \ + X(router_sigmoid_topk) \ + X(dsa_pool) \ + X(dsa_query) \ + X(gemm_nt_f32) \ + X(mla_project) \ + X(dsa_score) \ + X(mla_attn) \ X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \ X(mul) X(silu_mul) X(gelu_mul) X(gelu) \ X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \ diff --git a/libavx/avx_mla.cpp b/libavx/avx_mla.cpp new file mode 100644 index 00000000..94c82558 --- /dev/null +++ b/libavx/avx_mla.cpp @@ -0,0 +1,113 @@ +#include "avx_vec.h" +#include "avx_common.h" +#include +#include +using namespace avx; + +AVX_KERNEL(mla_project) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + RadTensor x = a->t[0], y = a->t[2]; + const auto& w = a->t[1]; + const int64_t h = p_int(a, "heads", 0), d = p_int(a, "head_dim", 0), + l = p_int(a, "latent_dim", 0); + const char* mode = p_str(a, "mode", ""); + const bool absorb = !std::strcmp(mode, "absorb"), expand = !std::strcmp(mode, "expand"); + auto heads_view = [&](RadTensor& t, int64_t width) { + if (h > 0 && width > 0 && t.rank == 2 && t.shape[1] == h * width) { + t.rank = 3; + t.shape[1] = h; + t.shape[2] = width; + t.stride[2] = t.stride[1]; + t.stride[1] *= width; + } + }; + heads_view(x, absorb ? d : l); + heads_view(y, absorb ? l : d); + if ((!absorb && !expand) || h < 1 || d < 1 || l < 1 || x.rank != 3 || w.rank != 2 || + y.rank != 3 || x.shape[0] < 1 || x.shape[1] != h || x.shape[2] != (absorb ? d : l) || + w.shape[0] != h * 2 * d || w.shape[1] != l || y.shape[0] != x.shape[0] || y.shape[1] != h || + y.shape[2] != (absorb ? l : d)) + return RAD_E_SHAPE; + if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE; + if (!x.data || !w.data || !y.data) return RAD_E_INVAL; + AVX_PARALLEL_FOR_IF(x.shape[0] * h * d * l >= AVX_PAR_MIN) + for (int64_t job = 0; job < x.shape[0] * h; ++job) { + const int64_t r = job / h, head = job % h; + float* tmp = scratch_f32((size_t)(2 * (d + l))); + float *query = tmp, *weights = tmp + d + l; + for (int64_t j = 0; j < (absorb ? d : l); ++j) + query[j] = ldt(&x, r * x.stride[0] + head * x.stride[1] + j * x.stride[2]); + for (int64_t col = 0; col < (absorb ? l : d); ++col) { + const int64_t nk = absorb ? d : l; + for (int64_t j = 0; j < nk; ++j) { + const int64_t wr = head * 2 * d + (absorb ? j : d + col), wc = absorb ? col : j; + weights[j] = ldt(&w, wr * w.stride[0] + wc * w.stride[1]); + } + vf acc = vf_zero(); + int64_t j = 0; + for (; j + VF_N <= nk; j += VF_N) + acc = vf_fma(vf_loadu(query + j), vf_loadu(weights + j), acc); + float sum = vf_hsum(acc); + for (; j < nk; ++j) sum += query[j] * weights[j]; + stt(&y, r * y.stride[0] + head * y.stride[1] + col * y.stride[2], sum); + } + } + return RAD_OK; +} + +AVX_KERNEL(mla_attn) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &out = a->t[4]; + const int64_t d = p_int(a, "latent_dim", 0), h = p_int(a, "heads", 0), + bs = p_int(a, "block_size", 0); + const float scale = p_f32(a, "scale", 0); + if (d < 1 || d > 2048 || h < 1 || bs < 1 || !std::isfinite(scale) || scale <= 0 || + q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != d || kv.rank != 4 || + kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != d || bt.rank != 2 || + bt.shape[0] != q.shape[0] || len.rank != 1 || len.shape[0] != q.shape[0] || out.rank != 3 || + out.shape[0] != q.shape[0] || out.shape[1] != h || out.shape[2] != d || + bt.dtype != RAD_I32 || len.dtype != RAD_I32) + return RAD_E_SHAPE; + for (int i = 0; i < 5; ++i) + if (!a->t[i].data) return RAD_E_INVAL; + AVX_PARALLEL_FOR_IF(q.shape[0] * h * d * bt.shape[1] * bs >= AVX_PAR_MIN) + for (int64_t job = 0; job < q.shape[0] * h; ++job) { + const int64_t r = job / h, head = job % h; + const int64_t live = std::clamp(ld_int_dt(len.dtype, len.data, r * len.stride[0]), + (int64_t)0, bt.shape[1] * bs); + float *tmp = scratch_f32((size_t)(3 * d)), *query = tmp, *key = tmp + d, + *value = tmp + 2 * d; + for (int64_t c = 0; c < d; ++c) { + query[c] = ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]); + value[c] = 0; + } + float max = -INFINITY, den = 0; + for (int64_t j = 0; j < live; ++j) { + const int64_t page = + ld_int_dt(bt.dtype, bt.data, r * bt.stride[0] + (j / bs) * bt.stride[1]); + if (page < 0 || page >= kv.shape[0]) continue; + const int64_t base = page * kv.stride[0] + (j % bs) * kv.stride[2]; + for (int64_t c = 0; c < d; ++c) key[c] = ldt(&kv, base + c * kv.stride[3]); + vf acc = vf_zero(); + int64_t c = 0; + for (; c + VF_N <= d; c += VF_N) + acc = vf_fma(vf_loadu(query + c), vf_loadu(key + c), acc); + float score = vf_hsum(acc); + for (; c < d; ++c) score += query[c] * key[c]; + score *= scale; + const float next = std::max(max, score), old = std::exp(max - next), + w = std::exp(score - next); + den = den * old + w; + max = next; + const vf a = vf_set1(old), b = vf_set1(w); + c = 0; + for (; c + VF_N <= d; c += VF_N) + vf_storeu(value + c, vf_fma(vf_loadu(key + c), b, vf_mul(vf_loadu(value + c), a))); + for (; c < d; ++c) value[c] = value[c] * old + key[c] * w; + } + for (int64_t c = 0; c < d; ++c) + stt(&out, r * out.stride[0] + head * out.stride[1] + c * out.stride[2], + den > 0 ? value[c] / den : 0); + } + return RAD_OK; +} diff --git a/libavx/avx_moe.cpp b/libavx/avx_moe.cpp index 1650698d..fea717a5 100644 --- a/libavx/avx_moe.cpp +++ b/libavx/avx_moe.cpp @@ -1098,7 +1098,7 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { if (jc > 0 || (ts && cb_joined(wse[e]))) return RAD_E_DTYPE; } mw[e] = as_mat(&we[e], k); - SW[e] = make_scales(quant && ts ? &wse[e] : nullptr, n, k, false); + SW[e] = make_scales(quant && ts ? &wse[e] : nullptr, n, k, we[e].dtype == RAD_FP4E2M1); /* An activation scale grid finer than an expert's cannot be hoisted out of the group. No * supported format has one, but libref answers it by scaling each element, so the panel * below is scaled as it is packed and the dot reads no activation scale (`SAg`). */ @@ -1218,7 +1218,7 @@ AVX_KERNEL(moe_gemm_q_mod4) { return moe_gemm_impl(a, true, 4); } /* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)], summed in * ascending slot j (see the file header). The inverse permutation is built once per batch. */ AVX_KERNEL(moe_gather) { - if (!rad_args_have(a, 6)) return RAD_E_INVAL; + if (!a || !a->t || a->n_t < 6 || !rad_args_have(a, 3) || !rad_arg_in(a, 5)) return RAD_E_INVAL; const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5]; /* Optional shared-expert fold: y = narrow(shared * act(gate)) + narrow(gathered). Both * operands or neither, as in libref. */ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 3c1e9a76..3d70387a 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -67,6 +67,26 @@ static const RadOperandSpec oHcRead[] = { OPD("h"), WGT("w"), WGT("mix_down"), WGT_O("inject_w"), OUT("x"), OUT_O("inj"), OUT_O("q"), OUT_O("scale"), OUT_O("rq"), OUT_O("rscale") }; +static const RadParamSpec pMhcPre[] = { P_INT("M"), P_INT("n"), P_INT("hc"), + P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_STR("dtype") }; +static const RadOperandSpec oMhcPre[] = { OPD("h"), WGT("fn"), WGT("scale"), WGT("base"), + OUT("x"), OUT("post"), OUT("comb") }; +static const RadParamSpec pMhcPrePartial[] = { P_INT("M"), P_INT("n"), P_INT("hc"), + P_INT("chunk"), P_INT("first"), P_INT("chunks"), P_STR("dtype") }; +static const RadOperandSpec oMhcPrePartial[] = { OPD("h"), WGT("fn"), OUT("part") }; +static const RadParamSpec pMhcPreFinish[] = { P_INT("M"), P_INT("n"), P_INT("hc"), + P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype") }; +static const RadOperandSpec oMhcPreFinish[] = { OPD("part"), OPD("h"), WGT("scale"), WGT("base"), + OUT("x"), OUT("post"), OUT("comb") }; +static const RadOperandSpec oMhcPost[] = { OPD("x"), OPD("h"), OPD("post"), OPD("comb"), OUT("out") }; +static const RadOperandSpec oMhcContract[] = { OPD("h"), OUT("x") }; +static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_k"), + P_INT("head_v"), P_F64("lower_bound"), P_F64("scale"), P_F64("l2_eps"), + P_STR("mode"), P_STR("dtype"), P_STRO("state_form") }; +static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"), + WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"), + OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") }; + static const RadParamSpec pNgramIds[] = { P_INT("M"), P_INT("heads"), P_INT("ngram"), P_INT("eos") }; static const RadOperandSpec oNgramIds[] = { OPD("tok"), INOUT("state"), OPD("cu"), WGT("mult"), @@ -110,6 +130,22 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") }; static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") }; +static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), P_STR("dtype") }; +static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), P_INTO("block_size") }; +static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"), + P_INT("blocks"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") }; +static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"), + P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") }; +static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") }; +static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), + P_INT("blocks"), P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"), + OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") }; +static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT("scale"), + OPD_O("page"), INOUT_O("cache") }; +static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; +static const RadOperandSpec oRouterSigmoid[] = { OPD("logits"), WGT("bias"), OUT("ids"), OUT("weights") }; static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; /* `add`'s `div` divides the rounded sum (libref's pAdd). */ static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") }; @@ -697,6 +733,14 @@ static const RadOpSchema kSchemas[] = { "f32 sum, the multiply from residual_out after narrowing, as libref." }, { "hc_enter", ARR(pHcWrite), ARR(oHcEnter), "h[s] = x for each of the hc streams -- the wide residual stream's first value." }, +{ "mhc_pre", ARR(pMhcPre), ARR(oMhcPre), "Whole-residual RMS projection, sigmoid gates and Sinkhorn mixing." }, +{ "mhc_pre_partial", ARR(pMhcPrePartial), ARR(oMhcPrePartial), + "mhc_pre's projection over chunks [first, first+chunks) of `chunk` columns, zero-padded per chunk." }, +{ "mhc_pre_finish", ARR(pMhcPreFinish), ARR(oMhcPreFinish), + "mhc_pre from every chunk's partials: chunk sums, gates, Sinkhorn mixing, collapse." }, +{ "mhc_post", ARR(pHcWrite), ARR(oMhcPost), "Source-to-destination manifold residual update." }, +{ "mhc_contract", ARR(pHcWrite), ARR(oMhcContract), "Mean over manifold residual streams." }, +{ "kda_update", ARR(pKdaUpdate), ARR(oKdaUpdate), "Bounded per-channel KDA with candidate-state rollback." }, { "hc_read", ARR(pHcRead), ARR(oHcRead), "The read half of a gated residual: grouped norm, low-rank gate, stream mix, and optionally the " "block-scaled fp8 form of x and its Hadamard-rotated twin. See docs/OPS.md for the three facts " @@ -737,6 +781,20 @@ static const RadOpSchema kSchemas[] = { "local attention with a relative-position term and a softcap (Gemma 4's audio)." }, { "pool_rows", ARR(pPoolRows), ARR(oUnary), "y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." }, +{ "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn), + "Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." }, +{ "mla_project", ARR(pMlaProject), ARR(oGemm), + "Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix." }, +{ "dsa_score", ARR(pDsaScore), ARR(oDsaScore), + "Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf." }, +{ "gemm_nt_f32", ARR(pGemm), ARR(oGemm), + "BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision." }, +{ "dsa_query", ARR(pMnD), ARR(oQuantFp8), + "Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head." }, +{ "dsa_pool", ARR(pDsaPool), ARR(oDsaPool), + "Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8." }, +{ "swiglu_clamped", ARR(pSwigluClamped), ARR(oGateUp), + "silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half." }, { "silu_mul", ARR(pMnD), ARR(oGateUp), "silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." }, { "gelu_mul", ARR(pMnD), ARR(oGateUp), @@ -848,6 +906,8 @@ static const RadOpSchema kSchemas[] = { { "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." }, { "scale_rows", ARR(pScaleRows), ARR(oScaleRows), "one scalar per row, optionally through an activation, broadcast across the row." }, +{ "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid), + "Single-group sigmoid routing; correction bias selects experts, original scores weight them." }, { "router_topk", ARR(pRouter), ARR(oRouter), "softmax then exact top-k routing." }, { "moe_scatter", ARR(pScatter), ARR(oScatter), "stable counting sort of routing slots by expert." }, @@ -1160,6 +1220,12 @@ SIMPLE("avx_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D L(rmsnorm_add)), SIMPLE("avx_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT, L(hc_enter)), +SIMPLE("avx_mhc_pre", "mhc_pre", "norm", "manifold gates and Sinkhorn mixing", DT_FLOAT, L(mhc_pre)), +SIMPLE("avx_mhc_pre_partial", "mhc_pre_partial", "norm", "manifold projection partials", DT_FLOAT, L(mhc_pre_partial)), +SIMPLE("avx_mhc_pre_finish", "mhc_pre_finish", "norm", "manifold gates from projection partials", DT_FLOAT, L(mhc_pre_finish)), +SIMPLE("avx_mhc_post", "mhc_post", "norm", "manifold residual update", DT_FLOAT, L(mhc_post)), +SIMPLE("avx_mhc_contract", "mhc_contract", "norm", "mean of residual streams", DT_FLOAT, L(mhc_contract)), +SIMPLE("avx_kda_update", "kda_update", "gdn", "bounded KDA and candidate-state rollback", DT_FLOAT, L(kda_update)), ROWL("avx_hc_read", "hc_read", "norm", "gated residual read: grouped norm, low-rank gate, stream mix", DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", L(hc_read), @@ -1203,6 +1269,20 @@ SIMPLE("avx_seg_sinusoid", "seg_sinusoid", "elem", SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn", "local attention with a relative-position term and a softcap", DT_FLOAT, L(attn_local_rel)), +SIMPLE("avx_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT, + L(mla_attn)), +SIMPLE("avx_dsa_score", "dsa_score", "attn", "weighted FP8 index scoring", DT_FLOAT, + L(dsa_score)), +SIMPLE("avx_dsa_pool", "dsa_pool", "attn", "learned compressed FP8 index keys", DT_FLOAT, + L(dsa_pool)), +SIMPLE("avx_dsa_query", "dsa_query", "attn", "normalized FP8 index queries", DT_FLOAT, + L(dsa_query)), +SIMPLE("avx_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FLOAT, + L(gemm_nt_f32)), +SIMPLE("avx_mla_project", "mla_project", "attn", "absorbed MLA projections", DT_FLOAT, + L(mla_project)), +SIMPLE("avx_swiglu_clamped", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", DT_FLOAT, + L(swiglu_clamped)), SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT, L(silu_mul)), SIMPLE("avx_gelu_mul", "gelu_mul", "elem", "gelu_tanh-gated product over a fused gate_up", DT_FLOAT, @@ -1325,6 +1405,8 @@ SIMPLE("avx_qsa_work", "qsa_work", "attn", SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT, L(router_topk)), +SIMPLE("avx_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT, + L(router_sigmoid_topk)), SIMPLE("avx_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert", "i32 indices", L(moe_scatter)), SIMPLE("avx_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT, diff --git a/libref/ref_dsa.cpp b/libref/ref_dsa.cpp new file mode 100644 index 00000000..8ce2a790 --- /dev/null +++ b/libref/ref_dsa.cpp @@ -0,0 +1,206 @@ +/* GLM's compressed index keys: channel-wise learned pooling, then a normalized + * Hadamard and power-of-two E4M3 quantization. Pooling the raw keys by a mean, + * or omitting either BF16 boundary, changes sparse selection. */ +#include "ref_common.h" +#include "ref_ops.h" +#include +#include +using namespace ref; + +int ref_dsa_query(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const auto &x = a->t[0], &q = a->t[1], &s = a->t[2]; + const int64_t n = p_int(a, "n", 0); + if (n < 1 || n > 256 || (n & (n - 1)) || x.rank != 2 || q.rank != 2 || s.rank != 2 || + x.shape[0] < 1 || q.shape[0] != x.shape[0] || x.shape[1] != n || q.shape[1] != n || + s.shape[0] != x.shape[0] || s.shape[1] != 1) + return RAD_E_SHAPE; + if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE; + if (!x.data || !q.data || !s.data) return RAD_E_INVAL; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < x.shape[0]; ++r) { + float v[256]; + for (int64_t d = 0; d < n; ++d) v[d] = ldt(&x, r * x.stride[0] + d * x.stride[1]); + for (int64_t h = 1; h < n; h *= 2) + for (int64_t i = 0; i < n; i += 2 * h) + for (int64_t j = 0; j < h; ++j) { + const float lo = v[i + j], hi = v[i + j + h]; + v[i + j] = lo + hi; + v[i + j + h] = lo - hi; + } + float am = 1e-4f; + const float norm = 1.0f / std::sqrt((float)n); + for (int64_t d = 0; d < n; ++d) { + v[d] = bf16_to_f32(f32_to_bf16(v[d] * norm)); + am = std::max(am, std::fabs(v[d])); + } + int exponent = 0; + const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent); + const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f)); + stt(&s, r * s.stride[0], sc); + for (int64_t d = 0; d < n; ++d) + stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(v[d] / sc, -448.0f, 448.0f)); + } + return RAD_OK; +} + +int ref_dsa_score(const RadArgs* a, RadStream) { + if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL; + RadTensor q = a->t[0], qs = a->t[1]; + const auto& gate = a->t[2]; + RadTensor k = a->t[3], ks = a->t[4]; + const bool packed = k.dtype == RAD_U8; + if (packed) { + if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 || + k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 || + ((uintptr_t)k.data & 3)) + return RAD_E_SHAPE; + ks = {}; + ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr; + ks.dtype = RAD_F32; + ks.rank = 1; + ks.shape[0] = k.shape[0]; + ks.stride[0] = k.stride[0] / 4; + k.dtype = RAD_F8E4M3; + k.rank = 2; + k.shape[1] = 128; + k.stride[1] = 1; + } + const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &out = a->t[8]; + const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0); + if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && + q.shape[0] == out.shape[0] * h && qs.shape[0] == q.shape[0]) { + q.rank = 3; + q.shape[0] = out.shape[0]; + q.shape[2] = q.shape[1]; + q.shape[1] = h; + q.stride[2] = q.stride[1]; + q.stride[1] = q.stride[0]; + q.stride[0] *= h; + qs.shape[0] = out.shape[0]; + qs.shape[1] = h; + qs.stride[1] = qs.stride[0]; + qs.stride[0] *= h; + } + if (n < 1 || h < 1 || h > 64 || q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || + q.shape[2] != n || qs.rank != 2 || gate.rank != 2 || qs.shape[0] != q.shape[0] || + gate.shape[0] != q.shape[0] || qs.shape[1] != h || gate.shape[1] != h || k.rank != 2 || + k.shape[1] != n || ks.rank != 1 || ks.shape[0] != k.shape[0] || bt.rank != 2 || + cu.rank != 1 || nc.rank != 1 || cu.shape[0] != bt.shape[0] + 1 || + nc.shape[0] != bt.shape[0] || out.rank != 2 || out.shape[0] != q.shape[0] || + out.shape[1] > bt.shape[1]) + return RAD_E_SHAPE; + if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 || + ks.dtype != RAD_F32 || gate.dtype != RAD_F32 || bt.dtype != RAD_I32 || + cu.dtype != RAD_I32 || nc.dtype != RAD_I32 || out.dtype != RAD_F32) + return RAD_E_DTYPE; + for (int i = 0; i < 9; ++i) + if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL; + const float norm = 1.0f / std::sqrt((float)(h * n)); +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < q.shape[0]; ++r) { + int64_t seq = -1; + for (int64_t s = 0; s < bt.shape[0]; ++s) + if (r >= ld_int(cu.dtype, cu.data, s * cu.stride[0]) && + r < ld_int(cu.dtype, cu.data, (s + 1) * cu.stride[0])) { + seq = s; + break; + } + const int64_t live = seq >= 0 ? ld_int(nc.dtype, nc.data, seq * nc.stride[0]) : 0; + for (int64_t b = 0; b < out.shape[1]; ++b) { + const int64_t page = + seq >= 0 && b < live + ? ld_int(bt.dtype, bt.data, seq * bt.stride[0] + b * bt.stride[1]) + : -1; + float result = -INFINITY; + if (page >= 0 && page < k.shape[0]) { + result = 0; + for (int64_t head = 0; head < h; ++head) { + float dot = 0; + for (int64_t d = 0; d < n; ++d) + dot += ldt(&q, r * q.stride[0] + head * q.stride[1] + d * q.stride[2]) * + ldt(&k, page * k.stride[0] + d * k.stride[1]); + result += std::max(dot, 0.0f) * + ldt(&qs, r * qs.stride[0] + head * qs.stride[1]) * + ldt(&gate, r * gate.stride[0] + head * gate.stride[1]); + } + result *= ldt(&ks, page * ks.stride[0]) * norm; + } + stt(&out, r * out.stride[0] + b * out.stride[1], result); + } + } + return RAD_OK; +} + +int ref_dsa_pool(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3]; + const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0); + if (p_int(a, "block_size", 4) != 4) return RAD_E_SHAPE; + const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5); + if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL; + if (cache && + (n != 128 || ratio != 4 || page->dtype != RAD_I32 || page->rank != 1 || + page->shape[0] != q.shape[0] || page->stride[0] < 1 || cache->dtype != RAD_U8 || + cache->rank != 4 || cache->shape[0] < 1 || cache->shape[1] != 1 || cache->shape[2] != 4 || + cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 || + cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3))) + return RAD_E_SHAPE; + if (n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16 || kg.rank != 2 || + ape.rank != 2 || q.rank != 2 || s.rank != 2 || q.shape[0] < 1 || !kg.data || !ape.data || + !q.data || !s.data || kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 || + q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32 || kg.shape[0] != q.shape[0] * ratio || + kg.shape[1] != 2 * n || ape.shape[0] != ratio || ape.shape[1] != n || q.shape[1] != n || + s.shape[0] != q.shape[0] || s.shape[1] != 1) + return RAD_E_SHAPE; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < q.shape[0]; ++r) { + float v[256]; + for (int64_t d = 0; d < n; ++d) { + float gate[16], mx = -INFINITY; + for (int64_t j = 0; j < ratio; ++j) { + gate[j] = ldt(&kg, rowoff(&kg, r * ratio + j, 2 * n) + (n + d) * laststride(&kg)) + + ldt(&ape, rowoff(&ape, j, n) + d * laststride(&ape)); + mx = std::max(mx, gate[j]); + } + float num = 0, den = 0; + for (int64_t j = 0; j < ratio; ++j) { + const float p = std::exp(gate[j] - mx); + num += p * ldt(&kg, rowoff(&kg, r * ratio + j, 2 * n) + d * laststride(&kg)); + den += p; + } + v[d] = bf16_to_f32(f32_to_bf16(num / den)); + } + for (int64_t h = 1; h < n; h *= 2) + for (int64_t i = 0; i < n; i += 2 * h) + for (int64_t j = 0; j < h; ++j) { + const float x = v[i + j], y = v[i + j + h]; + v[i + j] = x + y; + v[i + j + h] = x - y; + } + float am = 1e-4f; + const float norm = 1.0f / std::sqrt((float)n); + for (int64_t d = 0; d < n; ++d) { + v[d] = bf16_to_f32(f32_to_bf16(v[d] * norm)); + am = std::max(am, std::fabs(v[d])); + } + const float target = am * (1.0f / 448.0f); + int exp = 0; + const float frac = std::frexp(target, &exp); + const float scale = std::ldexp(1.0f, exp - (frac == 0.5f)); + stt(&s, rowoff(&s, r, 1), scale); + for (int64_t d = 0; d < n; ++d) + stt(&q, rowoff(&q, r, n) + d * laststride(&q), + std::clamp(v[d] / scale, -448.0f, 448.0f)); + if (cache) { + const int64_t p = ld_int(page->dtype, page->data, r * page->stride[0]); + if (p >= 0 && p < cache->shape[0]) { + auto* dst = (uint8_t*)cache->data + p * cache->stride[0]; + for (int d = 0; d < 128; ++d) + dst[d] = ((uint8_t*)q.data)[r * q.stride[0] + d * q.stride[1]]; + std::memcpy(dst + 128, &scale, sizeof(scale)); + } + } + } + return RAD_OK; +} diff --git a/libref/ref_glm.cpp b/libref/ref_glm.cpp new file mode 100644 index 00000000..1c1c7c8c --- /dev/null +++ b/libref/ref_glm.cpp @@ -0,0 +1,90 @@ +#include "ref_common.h" +#include "ref_ops.h" +#include +#include +using namespace ref; + +/* Routing and index head gates are F32 projections in GLM, even with BF16 hidden states. */ +int ref_gemm_nt_f32(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const auto &x = a->t[0], &w = a->t[1], &y = a->t[2]; + const int64_t n = p_int(a, "N", 0), k = p_int(a, "K", 0); + if (n < 1 || k < 1 || x.rank != 2 || w.rank != 2 || y.rank != 2 || x.shape[0] < 1 || + x.shape[1] != k || w.shape[0] != n || w.shape[1] != k || y.shape[0] != x.shape[0] || + y.shape[1] != n) + return RAD_E_SHAPE; + if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE; + if (!x.data || !w.data || !y.data) return RAD_E_INVAL; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < x.shape[0]; ++r) + for (int64_t col = 0; col < n; ++col) { + float sum = 0; + for (int64_t j = 0; j < k; ++j) + sum += ldt(&x, r * x.stride[0] + j * x.stride[1]) * + ldt(&w, col * w.stride[0] + j * w.stride[1]); + stt(&y, r * y.stride[0] + col * y.stride[1], sum); + } + return RAD_OK; +} + +/* Single-group noaux_tc routing: correction changes selection, never the mixture weights. */ +int ref_router_sigmoid_topk(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &weights = a->t[3]; + const int64_t ne = p_int(a, "n_expert", 0), k = p_int(a, "top_k", 0); + const float scale = p_f32(a, "route_scale", 0); + const bool norm = p_int(a, "norm", 0) != 0; + if (ne < 1 || ne > 512 || k < 1 || k > ne || !std::isfinite(scale) || scale <= 0 || + lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 || + bias.shape[0] != ne || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || ids.rank != 2 || + weights.rank != 2 || ids.shape[0] != lg.shape[0] || weights.shape[0] != lg.shape[0] || + ids.shape[1] != k || weights.shape[1] != k || !lg.data || !bias.data || !ids.data || + !weights.data) + return RAD_E_SHAPE; + for (int64_t r = 0; r < lg.shape[0]; ++r) { + float scores[512], select[512], chosen[512]; + int index[512]; + for (int64_t e = 0; e < ne; ++e) { + scores[e] = act_sigmoid(ldt(&lg, rowoff(&lg, r, ne) + e * laststride(&lg))); + select[e] = scores[e] + ldt(&bias, e * laststride(&bias)); + } + float sum = 0; + for (int64_t j = 0; j < k; ++j) { + int best = -1; + for (int64_t e = 0; e < ne; ++e) + if (select[e] > -INFINITY && (best < 0 || select[e] > select[best])) best = (int)e; + if (best < 0) return RAD_E_SHAPE; + index[j] = best; + chosen[j] = scores[best]; + sum += chosen[j]; + select[best] = -INFINITY; + } + for (int64_t j = 0; j < k; ++j) { + st_int(ids.dtype, ids.data, rowoff(&ids, r, k) + j * laststride(&ids), index[j]); + stt(&weights, rowoff(&weights, r, k) + j * laststride(&weights), + chosen[j] * (norm ? scale / (sum + 1e-20f) : scale)); + } + } + return RAD_OK; +} + +/* GLM clamps the gate only above, but clamps the up branch on both sides. */ +int ref_swiglu_clamped(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const auto &gu = a->t[0], &y = a->t[1]; + const int64_t n = p_int(a, "n", 0); + const float limit = p_f32(a, "limit", 0); + if (n < 1 || !std::isfinite(limit) || limit <= 0 || gu.rank != 2 || y.rank != 2 || !gu.data || + !y.data || y.shape[0] < 1 || gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n || + y.shape[1] != n) + return RAD_E_SHAPE; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < y.shape[0]; ++r) + for (int64_t i = 0; i < n; ++i) { + const int64_t b = rowoff(&gu, r, 2 * n), s = laststride(&gu); + const float g = std::min(ldt(&gu, b + i * s), limit); + const float u = std::clamp(ldt(&gu, b + (n + i) * s), -limit, limit); + stt(&y, rowoff(&y, r, n) + i * laststride(&y), act_silu(g) * u); + } + return RAD_OK; +} diff --git a/libref/ref_kda.cpp b/libref/ref_kda.cpp new file mode 100644 index 00000000..a3b4ec7a --- /dev/null +++ b/libref/ref_kda.cpp @@ -0,0 +1,199 @@ +/* Bounded per-channel Kimi Delta Attention. Cache rows are complete candidate states, + * so the accepted-prefix index restores the recurrence without trying to invert a delta. + * Prefill commits only its final state; verify preserves every candidate for rejection. */ +#include "ref_common.h" +#include "ref_ops.h" +#include +#include + +using namespace ref; + +namespace { +bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t dim) { + return t.data && t.shape[0] == tokens && + ((t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim) || + (t.rank == 2 && t.shape[1] == heads * dim)); +} +int64_t off(const RadTensor& t, int64_t token, int64_t head, int64_t d, int64_t width) { + return token * t.stride[0] + head * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) + + d * laststride(&t); +} +} + +int ref_kda_update(const RadArgs* a, RadStream) { + if (!a || a->n_t < 13) return RAD_E_INVAL; + for (int i = 0; i < 10; ++i) + if (!rad_arg_in(a, i)) return RAD_E_INVAL; + if (!rad_arg_in(a, 12)) return RAD_E_INVAL; + const int64_t H = p_int(a, "heads", 0), K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0); + const float lower = p_f32(a, "lower_bound", 0), eps = p_f32(a, "l2_eps", 1e-6f); + const float scale = p_f32(a, "scale", 1.0f); + const char* mode = p_str(a, "mode", ""); + const bool verify = !std::strcmp(mode, "verify"); + const char* form = p_str(a, "state_form", "per_candidate"); + const bool anchor = !std::strcmp(form, "anchor"); + if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL; + if (anchor && (K != 128 || V != 128)) return RAD_E_UNSUPPORTED; + if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL; + if (H <= 0 || K <= 0 || K > 128 || V <= 0 || V > 128 || !std::isfinite(lower) || lower >= 0 || + !std::isfinite(eps) || eps <= 0 || !std::isfinite(scale)) + return RAD_E_SHAPE; + const auto &q = a->t[0], &k = a->t[1], &v = a->t[2], &g = a->t[3], &beta = a->t[4]; + const auto &alog = a->t[5], &bias = a->t[6], &state = a->t[7], &idx = a->t[8], &cu = a->t[9]; + const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11); + const auto& out = a->t[12]; + if (q.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE; + const int64_t T = q.shape[0], N = cu.shape[0] - 1; + if (T < 1) return RAD_E_SHAPE; + if (!headed(q, T, H, K) || !headed(k, T, H, K) || !headed(v, T, H, V) || !headed(g, T, H, K) || + !headed(beta, T, H, 1) || !headed(out, T, H, V) || numel(&alog) != H || + numel(&bias) != H * K || state.rank != 4 || state.dtype != RAD_F32 || state.shape[1] != H || + state.shape[2] != V || state.shape[3] != K || idx.dtype != RAD_I32 || idx.rank != 2 || + idx.shape[0] < N || idx.shape[1] < 1 || + (accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) || + (init && (init->dtype != RAD_I32 || numel(init) < N))) + return RAD_E_SHAPE; + const int64_t width = idx.shape[1], slots = state.shape[0]; + /* Check every address before writing any state, so a malformed batch cannot leave a + * partially committed prefix when the host reference reports an error. */ + for (int64_t seq = 0; seq < N; ++seq) { + const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]); + const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]); + const int64_t na = + accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1; + if (begin < 0 || end < begin || end > T || na < 1 || na > (anchor ? 32 : width) || + (verify && end - begin > (anchor ? 32 : width)) || (anchor && width < 2)) + return RAD_E_SHAPE; + for (int64_t j = 0; j < width; ++j) + if (ld_int(idx.dtype, idx.data, seq * idx.stride[0] + j * idx.stride[1]) >= slots) + return RAD_E_SHAPE; + if (anchor) { + const int64_t read = ld_int(idx.dtype, idx.data, seq * idx.stride[0]); + const int64_t scratch = + ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1]); + if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE; + if (verify && read >= 0 && + (!init || ld_int(init->dtype, init->data, offlin(init, seq)))) + for (int64_t h = 0; h < H; ++h) { + const float count = + ldt(&state, scratch * state.stride[0] + h * state.stride[1]); + if (!std::isfinite(count) || count < 0 || count > 32 || + count != std::floor(count) || (count > 0 && na > count)) + return RAD_E_SHAPE; + } + } + } +#pragma omp parallel for schedule(static) + for (int64_t sh = 0; sh < N * H; ++sh) { + const int64_t seq = sh / H, head = sh % H; + const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]); + const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]); + if (begin == end) continue; + const int64_t na = + accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1; + const int64_t read = + ld_int(idx.dtype, idx.data, + seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]); + if (read < 0) { + for (int64_t t = begin; t < end; ++t) + for (int64_t e = 0; e < V; ++e) stt(&out, off(out, t, head, e, V), 0); + continue; + } + float S[128 * 128], qn[128], kn[128], decay[128]; + const bool initialized = !init || ld_int(init->dtype, init->data, offlin(init, seq)) != 0; + const int64_t sb = read * state.stride[0] + head * state.stride[1]; + for (int64_t e = 0; e < V; ++e) + for (int64_t d = 0; d < K; ++d) + S[e * K + d] = + initialized ? ldt(&state, sb + e * state.stride[2] + d * state.stride[3]) : 0; + const int64_t scratch = + anchor ? ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1]) + : 0; + auto factor_at = [&](int64_t i) { + return scratch * state.stride[0] + head * state.stride[1] + (i / K) * state.stride[2] + + (i % K) * state.stride[3]; + }; + constexpr int factors = 385; + if (anchor && verify) { + const int replay = initialized ? (int)ldt(&state, factor_at(0)) : 0; + for (int t = 0; t < (replay ? na : 0); ++t) { + const int f = 1 + t * factors; + for (int d = 0; d < 128; ++d) { + kn[d] = ldt(&state, factor_at(f + d)); + decay[d] = ldt(&state, factor_at(f + 256 + d)); + } + const float bt = ldt(&state, factor_at(f + 384)); + for (int e = 0; e < 128; ++e) { + float prediction = 0; + for (int d = 0; d < 128; ++d) { + S[e * K + d] *= decay[d]; + prediction += S[e * K + d] * kn[d]; + } + const float delta = bt * (ldt(&state, factor_at(f + 128 + e)) - prediction); + for (int d = 0; d < 128; ++d) S[e * K + d] += delta * kn[d]; + } + } + // Publish only the accepted prefix. Current candidates remain in registers. + for (int e = 0; e < 128; ++e) + for (int d = 0; d < 128; ++d) + stt(&state, sb + e * state.stride[2] + d * state.stride[3], S[e * K + d]); + } + const float gain = std::exp(ldt(&alog, head * laststride(&alog))); + for (int64_t t = begin; t < end; ++t) { + float qs = 0, ks = 0; + for (int64_t d = 0; d < K; ++d) { + qn[d] = ldt(&q, off(q, t, head, d, K)); + kn[d] = ldt(&k, off(k, t, head, d, K)); + qs += qn[d] * qn[d]; + ks += kn[d] * kn[d]; + } + const float qi = scale / std::sqrt(qs + eps), ki = 1.0f / std::sqrt(ks + eps); + for (int64_t d = 0; d < K; ++d) { + qn[d] *= qi; + kn[d] *= ki; + const float z = gain * (ldt(&g, off(g, t, head, d, K)) + + ldt(&bias, (head * K + d) * laststride(&bias))); + decay[d] = std::exp(lower / (1.0f + std::exp(-z))); + } + const float bt = 1.0f / (1.0f + std::exp(-ldt(&beta, off(beta, t, head, 0, 1)))); + if (anchor && verify) { + const int f = 1 + (int)(t - begin) * factors; + for (int d = 0; d < 128; ++d) { + stt(&state, factor_at(f + d), kn[d]); + stt(&state, factor_at(f + 256 + d), decay[d]); + } + for (int e = 0; e < 128; ++e) + stt(&state, factor_at(f + 128 + e), ldt(&v, off(v, t, head, e, V))); + stt(&state, factor_at(f + 384), bt); + } + for (int64_t e = 0; e < V; ++e) { + float predicted = 0; + for (int64_t d = 0; d < K; ++d) { + S[e * K + d] *= decay[d]; + predicted += S[e * K + d] * kn[d]; + } + const float delta = bt * (ldt(&v, off(v, t, head, e, V)) - predicted); + float result = 0; + for (int64_t d = 0; d < K; ++d) { + S[e * K + d] += delta * kn[d]; + result += S[e * K + d] * qn[d]; + } + stt(&out, off(out, t, head, e, V), result); + } + if ((!anchor && verify) || (!verify && t + 1 == end)) { + const int64_t write = + ld_int(idx.dtype, idx.data, + seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]); + if (write >= 0) + for (int64_t e = 0; e < V; ++e) + for (int64_t d = 0; d < K; ++d) + stt(&state, + write * state.stride[0] + head * state.stride[1] + + e * state.stride[2] + d * state.stride[3], + S[e * K + d]); + } + } + if (anchor) stt(&state, factor_at(0), verify ? (float)(end - begin) : 0.0f); + } + return RAD_OK; +} diff --git a/libref/ref_mhc.cpp b/libref/ref_mhc.cpp new file mode 100644 index 00000000..954e69b9 --- /dev/null +++ b/libref/ref_mhc.cpp @@ -0,0 +1,250 @@ +/* Manifold-constrained hyper-connections. The residual mixing matrix is indexed + * [source, destination]; transposing it leaves every shape valid and changes the model. + * The first Sinkhorn pass is softmax + eps, then column normalization. Later passes + * add eps to both denominators. These are separate operations from Qwen's hc_read/write. */ +#include "ref_common.h" +#include "ref_ops.h" + +#include +#include + +using namespace ref; + +namespace { +bool matrix(const RadTensor& t, int64_t rows, int64_t cols) { + return t.data && t.rank == 2 && t.shape[0] == rows && t.shape[1] == cols; +} +} + +namespace { +int64_t part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; } + +bool pre_params(const RadArgs* a, int64_t* n, int64_t* hc, int64_t* iters, float* eps, + float* heps) { + *n = p_int(a, "n", 0); + *hc = p_int(a, "hc", 0); + *iters = p_int(a, "iterations", 0); + *eps = p_f32(a, "eps", 0); + *heps = p_f32(a, "hc_eps", 0); + return *n > 0 && *hc >= 2 && *hc <= 8 && *iters >= 1 && *iters <= 256 && std::isfinite(*eps) && + std::isfinite(*heps) && *eps > 0 && *heps >= 0; +} + +/* The outputs' shapes, shared by mhc_pre and mhc_pre_finish. */ +bool pre_outputs(const RadTensor& h, const RadTensor& scale, const RadTensor& base, + const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t rows, + int64_t n, int64_t hc) { + const int64_t mix = hc * (hc + 2); + return matrix(h, rows, hc * n) && scale.rank == 1 && scale.dtype == RAD_F32 && + numel(&scale) == 3 && base.rank == 1 && base.dtype == RAD_F32 && numel(&base) == mix && + matrix(x, rows, n) && matrix(post, rows, hc) && matrix(comb, rows, hc * hc) && + post.dtype == RAD_F32 && comb.dtype == RAD_F32; +} + +/* Row r from its RMS-scaled coefficients: gates, Sinkhorn mixing and the collapse of h. */ +void finish_row(const float* coeff, const RadTensor& h, const RadTensor& scale, + const RadTensor& base, const RadTensor& x, const RadTensor& post, + const RadTensor& comb, int64_t r, int64_t n, int64_t hc, int64_t iters, + float heps) { + float pre[8], c[64]; + const int64_t hb = rowoff(&h, r, hc * n), hs = laststride(&h); + for (int64_t j = 0; j < hc; ++j) { + pre[j] = + 1.0f / (1.0f + + std::exp(-(coeff[j] * ldt(&scale, 0) + ldt(&base, j * laststride(&base))))) + + heps; + const float z = coeff[hc + j] * ldt(&scale, laststride(&scale)) + + ldt(&base, (hc + j) * laststride(&base)); + stt(&post, rowoff(&post, r, hc) + j * laststride(&post), 2.0f / (1.0f + std::exp(-z))); + } + for (int64_t j = 0; j < hc; ++j) { + float mx = -INFINITY; + for (int64_t k = 0; k < hc; ++k) { + const int64_t q = 2 * hc + j * hc + k; + c[j * hc + k] = + coeff[q] * ldt(&scale, 2 * laststride(&scale)) + ldt(&base, q * laststride(&base)); + mx = std::max(mx, c[j * hc + k]); + } + float sum = 0; + for (int64_t k = 0; k < hc; ++k) { + c[j * hc + k] = std::exp(c[j * hc + k] - mx); + sum += c[j * hc + k]; + } + for (int64_t k = 0; k < hc; ++k) c[j * hc + k] = c[j * hc + k] / sum + heps; + } + for (int64_t it = 0; it < iters; ++it) { + if (it) + for (int64_t j = 0; j < hc; ++j) { + float sum = 0; + for (int64_t k = 0; k < hc; ++k) sum += c[j * hc + k]; + for (int64_t k = 0; k < hc; ++k) c[j * hc + k] /= sum + heps; + } + for (int64_t k = 0; k < hc; ++k) { + float sum = 0; + for (int64_t j = 0; j < hc; ++j) sum += c[j * hc + k]; + for (int64_t j = 0; j < hc; ++j) c[j * hc + k] /= sum + heps; + } + } + const int64_t cb = rowoff(&comb, r, hc * hc), cs = laststride(&comb); + for (int64_t j = 0; j < hc * hc; ++j) stt(&comb, cb + j * cs, c[j]); + const int64_t xb = rowoff(&x, r, n), xs = laststride(&x); + for (int64_t i = 0; i < n; ++i) { + float v = 0; + for (int64_t j = 0; j < hc; ++j) v += pre[j] * ldt(&h, hb + (j * n + i) * hs); + stt(&x, xb + i * xs, v); + } +} +} + +int ref_mhc_pre(const RadArgs* a, RadStream) { + if (!have(a, 7)) return RAD_E_INVAL; + int64_t n, hc, iters; + float eps, heps; + if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE; + const auto &h = a->t[0], &fn = a->t[1], &scale = a->t[2], &base = a->t[3]; + const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6]; + const int64_t width = hc * n, mix = hc * (hc + 2); + if (h.rank != 2) return RAD_E_SHAPE; + const int64_t rows = h.shape[0]; + if (rows < 1 || !matrix(fn, mix, width) || fn.dtype != RAD_F32 || + !pre_outputs(h, scale, base, x, post, comb, rows, n, hc)) + return RAD_E_SHAPE; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + float coeff[80]; + const int64_t hb = rowoff(&h, r, width), hs = laststride(&h); + float sq = 0; + for (int64_t i = 0; i < width; ++i) { + const float v = ldt(&h, hb + i * hs); + sq += v * v; + } + const float inv = 1.0f / std::sqrt(sq / (float)width + eps); + for (int64_t j = 0; j < mix; ++j) { + float dot = 0; + const int64_t fb = rowoff(&fn, j, width), fs = laststride(&fn); + for (int64_t i = 0; i < width; ++i) dot += ldt(&h, hb + i * hs) * ldt(&fn, fb + i * fs); + coeff[j] = dot * inv; + } + finish_row(coeff, h, scale, base, x, post, comb, r, n, hc, iters, heps); + } + return RAD_OK; +} + +int ref_mhc_pre_partial(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0), chunk = p_int(a, "chunk", 0); + const int64_t first = p_int(a, "first", -1), count = p_int(a, "chunks", 0); + if (n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk || first < 0 || count < 1 || + first + count > hc * n / chunk) + return RAD_E_SHAPE; + const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2]; + const int64_t width = hc * n, mix = hc * (hc + 2), S = part_stride(hc); + if (h.rank != 2) return RAD_E_SHAPE; + const int64_t rows = h.shape[0]; + if (rows < 1 || !matrix(h, rows, width) || !matrix(fn, mix, width) || fn.dtype != RAD_F32 || + !matrix(part, rows, count * S) || part.dtype != RAD_F32) + return RAD_E_SHAPE; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t hb = rowoff(&h, r, width), hs = laststride(&h); + const int64_t pb = rowoff(&part, r, count * S), ps = laststride(&part); + for (int64_t c = 0; c < count; ++c) { + const int64_t lo = (first + c) * chunk; + for (int64_t j = 0; j < S; ++j) { + float sum = 0; + if (j < mix) { + const int64_t fb = rowoff(&fn, j, width), fs = laststride(&fn); + for (int64_t i = lo; i < lo + chunk; ++i) + sum += ldt(&h, hb + i * hs) * ldt(&fn, fb + i * fs); + } else if (j == mix) { + for (int64_t i = lo; i < lo + chunk; ++i) { + const float v = ldt(&h, hb + i * hs); + sum += v * v; + } + } + stt(&part, pb + (c * S + j) * ps, sum); + } + } + } + return RAD_OK; +} + +int ref_mhc_pre_finish(const RadArgs* a, RadStream) { + if (!have(a, 7)) return RAD_E_INVAL; + int64_t n, hc, iters; + float eps, heps; + if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE; + const int64_t chunk = p_int(a, "chunk", 0); + if (chunk <= 0 || (hc * n) % chunk) return RAD_E_SHAPE; + const auto &part = a->t[0], &h = a->t[1], &scale = a->t[2], &base = a->t[3]; + const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6]; + const int64_t width = hc * n, mix = hc * (hc + 2), S = part_stride(hc), chunks = width / chunk; + if (h.rank != 2) return RAD_E_SHAPE; + const int64_t rows = h.shape[0]; + if (rows < 1 || !matrix(part, rows, chunks * S) || part.dtype != RAD_F32 || + !pre_outputs(h, scale, base, x, post, comb, rows, n, hc)) + return RAD_E_SHAPE; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + float coeff[80]; + const int64_t pb = rowoff(&part, r, chunks * S), ps = laststride(&part); + float sq = 0; + for (int64_t c = 0; c < chunks; ++c) sq += ldt(&part, pb + (c * S + mix) * ps); + const float inv = 1.0f / std::sqrt(sq / (float)width + eps); + for (int64_t j = 0; j < mix; ++j) { + float dot = 0; + for (int64_t c = 0; c < chunks; ++c) dot += ldt(&part, pb + (c * S + j) * ps); + coeff[j] = dot * inv; + } + finish_row(coeff, h, scale, base, x, post, comb, r, n, hc, iters, heps); + } + return RAD_OK; +} + +int ref_mhc_post(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0); + if (n <= 0 || hc < 2 || hc > 8) return RAD_E_SHAPE; + const auto &x = a->t[0], &h = a->t[1], &post = a->t[2], &comb = a->t[3], &out = a->t[4]; + if (x.rank != 2) return RAD_E_SHAPE; + const int64_t rows = x.shape[0]; + if (rows < 1 || !matrix(x, rows, n) || !matrix(h, rows, hc * n) || !matrix(post, rows, hc) || + !matrix(comb, rows, hc * hc) || !matrix(out, rows, hc * n) || out.data == h.data || + post.dtype != RAD_F32 || comb.dtype != RAD_F32) + return RAD_E_SHAPE; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t hb = rowoff(&h, r, hc * n), cb = rowoff(&comb, r, hc * hc); + const int64_t pb = rowoff(&post, r, hc), xb = rowoff(&x, r, n); + const int64_t ob = rowoff(&out, r, hc * n); + for (int64_t k = 0; k < hc; ++k) + for (int64_t i = 0; i < n; ++i) { + float v = 0; + for (int64_t j = 0; j < hc; ++j) + v += ldt(&comb, cb + (j * hc + k) * laststride(&comb)) * + ldt(&h, hb + (j * n + i) * laststride(&h)); + v += ldt(&post, pb + k * laststride(&post)) * ldt(&x, xb + i * laststride(&x)); + stt(&out, ob + (k * n + i) * laststride(&out), v); + } + } + return RAD_OK; +} + +int ref_mhc_contract(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0); + if (n <= 0 || hc < 2 || hc > 8) return RAD_E_SHAPE; + const auto &h = a->t[0], &x = a->t[1]; + if (h.rank != 2 || h.shape[0] < 1 || !matrix(h, h.shape[0], hc * n) || + !matrix(x, h.shape[0], n)) + return RAD_E_SHAPE; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < h.shape[0]; ++r) + for (int64_t i = 0; i < n; ++i) { + float v = 0; + for (int64_t j = 0; j < hc; ++j) + v += ldt(&h, rowoff(&h, r, hc * n) + (j * n + i) * laststride(&h)); + stt(&x, rowoff(&x, r, n) + i * laststride(&x), v / (float)hc); + } + return RAD_OK; +} diff --git a/libref/ref_mla.cpp b/libref/ref_mla.cpp new file mode 100644 index 00000000..85515da0 --- /dev/null +++ b/libref/ref_mla.cpp @@ -0,0 +1,105 @@ +/* Absorbed MLA: one latent vector is both the attention key and value. The + * per-query table already contains the selected complete pages plus its tail. + * `scale` comes from the original query/key head width, NOT the latent width. */ +#include "ref_common.h" +#include "ref_ops.h" +#include +#include +using namespace ref; + +/* Both projections share the checkpoint's [head,(K|V),latent] matrix. + * Absorb: q @ Wk. Expand: attention_latent @ Wv^T. No per-head KV cache. */ +int ref_mla_project(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + RadTensor x = a->t[0], y = a->t[2]; + const auto& w = a->t[1]; + const int64_t h = p_int(a, "heads", 0), d = p_int(a, "head_dim", 0), + l = p_int(a, "latent_dim", 0); + const char* mode = p_str(a, "mode", ""); + const bool absorb = !std::strcmp(mode, "absorb"), expand = !std::strcmp(mode, "expand"); + auto heads_view = [&](RadTensor& t, int64_t width) { + if (h > 0 && width > 0 && t.rank == 2 && t.shape[1] == h * width) { + t.rank = 3; + t.shape[1] = h; + t.shape[2] = width; + t.stride[2] = t.stride[1]; + t.stride[1] *= width; + } + }; + heads_view(x, absorb ? d : l); + heads_view(y, absorb ? l : d); + if ((!absorb && !expand) || h < 1 || d < 1 || l < 1 || x.rank != 3 || w.rank != 2 || + y.rank != 3 || x.shape[0] < 1 || x.shape[1] != h || x.shape[2] != (absorb ? d : l) || + w.shape[0] != h * 2 * d || w.shape[1] != l || y.shape[0] != x.shape[0] || y.shape[1] != h || + y.shape[2] != (absorb ? l : d)) + return RAD_E_SHAPE; + if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE; + if (!x.data || !w.data || !y.data) return RAD_E_INVAL; +#pragma omp parallel for schedule(static) + for (int64_t r = 0; r < x.shape[0]; ++r) + for (int64_t head = 0; head < h; ++head) + for (int64_t col = 0; col < (absorb ? l : d); ++col) { + float sum = 0; + for (int64_t j = 0; j < (absorb ? d : l); ++j) { + const int64_t wr = head * 2 * d + (absorb ? j : d + col), wc = absorb ? col : j; + sum += ldt(&x, r * x.stride[0] + head * x.stride[1] + j * x.stride[2]) * + ldt(&w, wr * w.stride[0] + wc * w.stride[1]); + } + stt(&y, r * y.stride[0] + head * y.stride[1] + col * y.stride[2], sum); + } + return RAD_OK; +} + +int ref_mla_attn(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &out = a->t[4]; + const int64_t d = p_int(a, "latent_dim", 0), h = p_int(a, "heads", 0), + bs = p_int(a, "block_size", 0); + const float scale = p_f32(a, "scale", 0); + if (d < 1 || d > 2048 || h < 1 || bs < 1 || !std::isfinite(scale) || scale <= 0 || + q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != d || kv.rank != 4 || + kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != d || bt.rank != 2 || + bt.shape[0] != q.shape[0] || len.rank != 1 || len.shape[0] != q.shape[0] || out.rank != 3 || + out.shape[0] != q.shape[0] || out.shape[1] != h || out.shape[2] != d || + bt.dtype != RAD_I32 || len.dtype != RAD_I32) + return RAD_E_SHAPE; + for (int i = 0; i < 5; ++i) + if (!a->t[i].data) return RAD_E_INVAL; +#pragma omp parallel for schedule(static) + for (int64_t job = 0; job < q.shape[0] * h; ++job) { + const int64_t r = job / h, head = job % h; + const int64_t live = std::clamp(ld_int(len.dtype, len.data, r * len.stride[0]), (int64_t)0, + bt.shape[1] * bs); + auto key_offset = [&](int64_t token) -> int64_t { + const int64_t page = + ld_int(bt.dtype, bt.data, r * bt.stride[0] + (token / bs) * bt.stride[1]); + return page < 0 || page >= kv.shape[0] + ? -1 + : page * kv.stride[0] + (token % bs) * kv.stride[2]; + }; + auto dot = [&](int64_t base) -> float { + float v = 0; + for (int64_t c = 0; c < d; ++c) + v += ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]) * + ldt(&kv, base + c * kv.stride[3]); + return v * scale; + }; + float max = -INFINITY; + for (int64_t j = 0; j < live; ++j) { + const auto base = key_offset(j); + if (base >= 0) max = std::max(max, dot(base)); + } + float val[2048] = {}, den = 0; + for (int64_t j = 0; j < live; ++j) { + const auto base = key_offset(j); + if (base < 0) continue; + const float w = std::exp(dot(base) - max); + den += w; + for (int64_t c = 0; c < d; ++c) val[c] += w * ldt(&kv, base + c * kv.stride[3]); + } + for (int64_t c = 0; c < d; ++c) + stt(&out, r * out.stride[0] + head * out.stride[1] + c * out.stride[2], + den > 0 ? val[c] / den : 0); + } + return RAD_OK; +} diff --git a/libref/ref_moe.cpp b/libref/ref_moe.cpp index 0192d22c..6a771405 100644 --- a/libref/ref_moe.cpp +++ b/libref/ref_moe.cpp @@ -492,7 +492,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) { if (ts && cb_joined(wse[(size_t)e])) return RAD_E_DTYPE; } mw[(size_t)e] = as_mat(&we[(size_t)e], k); - SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k, false); + SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k, + we[(size_t)e].dtype == RAD_FP4E2M1); } const int64_t fy = N / parts; diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 2d9b6a86..16c6e76c 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -59,6 +59,12 @@ int ref_rmsnorm (const RadArgs*, RadStream); int ref_rmsnorm_p (const RadArgs*, RadStream); int ref_rmsnorm_add (const RadArgs*, RadStream); int ref_hc_enter (const RadArgs*, RadStream); +int ref_mhc_pre (const RadArgs*, RadStream); +int ref_mhc_pre_partial (const RadArgs*, RadStream); +int ref_mhc_pre_finish (const RadArgs*, RadStream); +int ref_mhc_post (const RadArgs*, RadStream); +int ref_mhc_contract (const RadArgs*, RadStream); +int ref_kda_update (const RadArgs*, RadStream); int ref_hc_read (const RadArgs*, RadStream); int ref_hc_write (const RadArgs*, RadStream); int ref_mtp_enter (const RadArgs*, RadStream); @@ -68,6 +74,14 @@ int ref_grid_embed_aa (const RadArgs*, RadStream); int ref_add (const RadArgs*, RadStream); int ref_mul (const RadArgs*, RadStream); int ref_silu_mul (const RadArgs*, RadStream); +int ref_swiglu_clamped (const RadArgs*, RadStream); +int ref_router_sigmoid_topk(const RadArgs*, RadStream); +int ref_dsa_pool(const RadArgs*, RadStream); +int ref_dsa_query(const RadArgs*, RadStream); +int ref_gemm_nt_f32(const RadArgs*, RadStream); +int ref_mla_project(const RadArgs*, RadStream); +int ref_dsa_score(const RadArgs*, RadStream); +int ref_mla_attn(const RadArgs*, RadStream); int ref_gelu_mul (const RadArgs*, RadStream); int ref_act_mul (const RadArgs*, RadStream); int ref_mul_weight (const RadArgs*, RadStream); @@ -267,6 +281,12 @@ REF_SHAPE_FN(ref_rmsnorm); REF_SHAPE_FN(ref_rmsnorm_p); REF_SHAPE_FN(ref_rmsnorm_add); REF_SHAPE_FN(ref_hc_enter); +REF_SHAPE_FN(ref_mhc_pre); +REF_SHAPE_FN(ref_mhc_pre_partial); +REF_SHAPE_FN(ref_mhc_pre_finish); +REF_SHAPE_FN(ref_mhc_post); +REF_SHAPE_FN(ref_mhc_contract); +REF_SHAPE_FN(ref_kda_update); REF_SHAPE_FN(ref_hc_read); REF_SHAPE_FN(ref_hc_write); REF_SHAPE_FN(ref_mtp_enter); @@ -276,6 +296,14 @@ REF_SHAPE_FN(ref_grid_embed_aa); REF_SHAPE_FN(ref_add); REF_SHAPE_FN(ref_mul); REF_SHAPE_FN(ref_silu_mul); +REF_SHAPE_FN(ref_swiglu_clamped); +REF_SHAPE_FN(ref_router_sigmoid_topk); +REF_SHAPE_FN(ref_dsa_pool); +REF_SHAPE_FN(ref_dsa_query); +REF_SHAPE_FN(ref_gemm_nt_f32); +REF_SHAPE_FN(ref_mla_project); +REF_SHAPE_FN(ref_dsa_score); +REF_SHAPE_FN(ref_mla_attn); REF_SHAPE_FN(ref_gelu_mul); REF_SHAPE_FN(ref_act_mul); REF_SHAPE_FN(ref_mul_weight); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 8cdecc32..abcf91fa 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -120,6 +120,25 @@ static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_st static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") }; static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") }; static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") }; +static const RadParamSpec pMhcPre[] = { P_INT("M"), P_INT("n"), P_INT("hc"), + P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_STR("dtype") }; +static const RadOperandSpec oMhcPre[] = { OPD("h"), WGT("fn"), WGT("scale"), WGT("base"), + OUT("x"), OUT("post"), OUT("comb") }; +static const RadParamSpec pMhcPrePartial[] = { P_INT("M"), P_INT("n"), P_INT("hc"), + P_INT("chunk"), P_INT("first"), P_INT("chunks"), P_STR("dtype") }; +static const RadOperandSpec oMhcPrePartial[] = { OPD("h"), WGT("fn"), OUT("part") }; +static const RadParamSpec pMhcPreFinish[] = { P_INT("M"), P_INT("n"), P_INT("hc"), + P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype") }; +static const RadOperandSpec oMhcPreFinish[] = { OPD("part"), OPD("h"), WGT("scale"), WGT("base"), + OUT("x"), OUT("post"), OUT("comb") }; +static const RadOperandSpec oMhcPost[] = { OPD("x"), OPD("h"), OPD("post"), OPD("comb"), OUT("out") }; +static const RadOperandSpec oMhcContract[] = { OPD("h"), OUT("x") }; +static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_k"), + P_INT("head_v"), P_F64("lower_bound"), P_F64("scale"), P_F64("l2_eps"), + P_STR("mode"), P_STR("dtype"), P_STRO("state_form") }; +static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"), + WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"), + OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") }; /* The MTP head's entry for a wide residual stream. `ngroup` is hc for a grouped norm over the * sub-streams, 1 for a flat one over the whole row (see ref_hc.cpp). */ static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"), @@ -137,6 +156,22 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") }; static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") }; +static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), P_STR("dtype") }; +static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), P_INTO("block_size") }; +static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"), + P_INT("blocks"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") }; +static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"), + P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") }; +static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") }; +static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), + P_INT("blocks"), P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"), + OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") }; +static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT("scale"), + OPD_O("page"), INOUT_O("cache") }; +static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; +static const RadOperandSpec oRouterSigmoid[] = { OPD("logits"), WGT("bias"), OUT("ids"), OUT("weights") }; static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; /* `div` divides the rounded sum, rounded again (default 1, the plain sum): a mean of branches * summed pairwise, as a vocoder averages its residual blocks. */ @@ -850,6 +885,33 @@ static const RadOpSchema kSchemas[] = { "is what every fused implementation does." }, { "hc_enter", ARR(pHcWrite), ARR(oHcEnter), "h[s] = x for each of the hc streams -- the wide residual stream's first value. Shares `hc_write`'s parameter list." }, +{ "mhc_pre", ARR(pMhcPre), ARR(oMhcPre), + "Manifold hyper-connection read: RMS-scaled projection of the whole hc*n residual, sigmoid " + "pre/post gates and Sinkhorn mixing. x has dtype, post and comb are f32. comb is indexed " + "[source,destination]. First pass is row softmax + hc_eps then column normalization; later " + "passes add hc_eps to both normalization denominators. hc is 2..8; iterations is 1..256." }, +{ "mhc_pre_partial", ARR(pMhcPrePartial), ARR(oMhcPrePartial), + "mhc_pre's projection split by residual columns. Chunk c covers columns [c*chunk, (c+1)*chunk) " + "of the hc*n row; for chunks [first, first+chunks) part[m, (c-first)*S + j] is the sum over the " + "chunk of h*fn[j] for j < hc*(hc+2) and of h*h for j = hc*(hc+2), with S = hc*(hc+2)+1 rounded " + "up to a multiple of 4 and the slots past the last zero. chunk divides hc*n. Tensor-parallel " + "ranks each compute their chunks and an all_gather (row = chunks*S) joins them." }, +{ "mhc_pre_finish", ARR(pMhcPreFinish), ARR(oMhcPreFinish), + "mhc_pre from mhc_pre_partial's matrix over all hc*n/chunk chunks: each coefficient and the sum " + "of squares is the sum of its chunks' partials (the order is the implementation's), then " + "mhc_pre's gates, Sinkhorn mixing and collapse of h. part and mhc_pre_partial over every chunk " + "together are mhc_pre." }, +{ "mhc_post", ARR(pHcWrite), ARR(oMhcPost), + "out[dst,i] = post[dst]*x[i] + sum_src comb[src,dst]*h[src,i]. post and comb are f32; " + "out must not alias h. No normalization of the residual stream." }, +{ "mhc_contract", ARR(pHcWrite), ARR(oMhcContract), + "x[i] = mean over hc streams h[stream,i], rounded once to dtype." }, +{ "kda_update", ARR(pKdaUpdate), ARR(oKdaUpdate), + "L2-normalized KDA: per-channel decay exp(lower_bound*sigmoid(exp(A_log)*(a+dt_bias))), " + "beta=sigmoid(b), S*=decay; S+=beta*(v-S*k)*k; o=scale*S*q. State is f32 [slot,heads,V,K]. " + "verify reads state_idx[seq,num_accepted-1] and writes each candidate state_idx[seq,t]; " + "prefill reads/writes column zero, committing only the final state. cu offsets are absolute; " + "has_init=0 starts from zero and a negative initial slot emits zero output. No output norm." }, { "hc_read", ARR(pHcRead), ARR(oHcRead), "The read half of a gated residual. N = grouped_rmsnorm(h) -- one rsqrt per `n`-wide stream, " "one gain of hc*n over all of them, `w + wadd`; g = sigmoid(mix_up @ silu(mix_down @ N / hc)); " @@ -929,6 +991,18 @@ static const RadOpSchema kSchemas[] = { "keys j with 0 <= i - j <= left (`right` 0). qf = q * head_dim^-0.5/ln2 * softplus(pds); logit " "= qf.k * ln(1+e)/ln2 + qf.relk[i-j]; softcap * tanh(logit / softcap); softmax; .v. f32, one " "rounding." }, +{ "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn), + "Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." }, +{ "mla_project", ARR(pMlaProject), ARR(oGemm), + "Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix." }, +{ "dsa_score", ARR(pDsaScore), ARR(oDsaScore), + "Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf." }, +{ "dsa_query", ARR(pMnD), ARR(oQuantFp8), + "Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head." }, +{ "dsa_pool", ARR(pDsaPool), ARR(oDsaPool), + "Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8." }, +{ "swiglu_clamped", ARR(pSwigluClamped), ARR(oGateUp), + "silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half." }, { "silu_mul", ARR(pMnD), ARR(oGateUp), "y[i] = silu(gate_up[i]) * gate_up[n + i]. The GATE IS THE FIRST HALF, which is the order " "rad-convert fuses gate and up into one weight in." }, @@ -1095,6 +1169,8 @@ static const RadOpSchema kSchemas[] = { "y = q * scale, the inverse of quant_act_i8g. It does NOT undo a rotation." }, { "gemm_nt", ARR(pGemm), ARR(oGemm), "y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate." }, +{ "gemm_nt_f32", ARR(pGemm), ARR(oGemm), + "BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision." }, { "gemm_nt_bias", ARR(pGemmBias), ARR(oGemmBias), "gemm_nt with a per-column bias added in f32, rounded to y's dtype; then, optionally, `act` of " "that (\"gelu\" exact, \"gelu_tanh\" the tanh approximation, \"none\"), rounded; then `res` " @@ -1184,6 +1260,8 @@ static const RadOpSchema kSchemas[] = { "when rows == n. `act` is \"sigmoid\" or \"none\", and it applies to the SCALAR. With `add` " "present the form is y = bf16(x * act(s)) + add -- the product NARROWED before the sum, which " "is what makes the fused form bit-identical to the pair it replaces." }, +{ "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid), + "Single-group sigmoid routing; correction bias selects experts, original scores weight them." }, { "router_topk", ARR(pRouter), ARR(oRouter), "Softmax over ALL n_expert logits, then the top_k by probability with ties to the lower expert " "id, then -- if `norm` -- renormalise the kept weights to sum to one." }, @@ -1691,6 +1769,18 @@ SIMPLE("ref_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D ref_rmsnorm_add), SIMPLE("ref_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT, ref_hc_enter), +SIMPLE("ref_mhc_pre", "mhc_pre", "norm", "manifold residual gates and Sinkhorn mixing", DT_FLOAT, + ref_mhc_pre), +SIMPLE("ref_mhc_pre_partial", "mhc_pre_partial", "norm", "manifold residual projection partials", DT_FLOAT, + ref_mhc_pre_partial), +SIMPLE("ref_mhc_pre_finish", "mhc_pre_finish", "norm", "manifold residual gates from projection partials", DT_FLOAT, + ref_mhc_pre_finish), +SIMPLE("ref_mhc_post", "mhc_post", "norm", "manifold residual source-to-destination update", DT_FLOAT, + ref_mhc_post), +SIMPLE("ref_mhc_contract", "mhc_contract", "norm", "mean of manifold residual streams", DT_FLOAT, + ref_mhc_contract), +SIMPLE("ref_kda_update", "kda_update", "gdn", "bounded per-channel delta recurrence and candidate rollback", DT_FLOAT, + ref_kda_update), ROWL("ref_hc_read", "hc_read", "norm", "gated residual read: grouped norm, low-rank gate, stream mix", DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", @@ -1710,6 +1800,20 @@ SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem", ref_grid_embed_aa), SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add), SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul), +SIMPLE("ref_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT, + ref_mla_attn), +SIMPLE("ref_dsa_score", "dsa_score", "attn", "weighted FP8 index scoring", DT_FLOAT, + ref_dsa_score), +SIMPLE("ref_dsa_pool", "dsa_pool", "attn", "learned compressed FP8 index keys", DT_FLOAT, + ref_dsa_pool), +SIMPLE("ref_dsa_query", "dsa_query", "attn", "normalized FP8 index queries", DT_FLOAT, + ref_dsa_query), +SIMPLE("ref_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FLOAT, + ref_gemm_nt_f32), +SIMPLE("ref_mla_project", "mla_project", "attn", "absorbed MLA projections", DT_FLOAT, + ref_mla_project), +SIMPLE("ref_swiglu_clamped", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", DT_FLOAT, + ref_swiglu_clamped), SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT, ref_silu_mul), SIMPLE("ref_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, ref_act_mul), @@ -1847,6 +1951,8 @@ SIMPLE("ref_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary SIMPLE("ref_scale_rows", "scale_rows", "elem", "one scalar per row, broadcast across the row", DT_FLOAT, ref_scale_rows), +SIMPLE("ref_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT, + ref_router_sigmoid_topk), SIMPLE("ref_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT, ref_router_topk), SIMPLE("ref_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index b3dc8a6e..30dbf06e 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -336,6 +336,95 @@ int ref_hc_enter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("hc_enter", operand, out); } +int ref_kda_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const char* form = gs(p, n_p, "state_form"); + // Replay records and aliased engine index columns require a hand-built fixture. + if (form && !std::strcmp(form,"anchor")) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), H = gi(p, n_p, "heads", 0); + const int64_t K = gi(p, n_p, "head_k", 0), V = gi(p, n_p, "head_v", 0); + if (M < 1 || H < 1 || K < 1 || K > 128 || V < 1 || V > 128) return RAD_E_UNSUPPORTED; + const char* mode = gs(p, n_p, "mode"); + const int64_t history = mode && !std::strcmp(mode, "verify") ? M : 1; + Opd o; + o.t(D, {M, H, K}); o.t(D, {M, H, K}); o.t(D, {M, H, V}); + o.t(D, {M, H, K}); o.t(D, {M, H}); + o.t((uint32_t)RAD_F32, {H}); o.t((uint32_t)RAD_F32, {H * K}); + o.t((uint32_t)RAD_F32, {history + 1, H, V, K}); + o.t_idx({1, history}, history + 1, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); + o.t_idx({2}, M, -1, (uint32_t)RAD_OPD_F_IDX_CU); + o.t_idx({1}, 0, 1, 0); o.t_idx({1}, 0, 1, 0); + o.t(D, {M, H, V}); + return o.finish("kda_update", operand, out); +} + +int ref_mhc_pre_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0); + if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, {M, hc * n}); + o.t((uint32_t)RAD_F32, {hc * (hc + 2), hc * n}); + o.t((uint32_t)RAD_F32, {3}); + o.t((uint32_t)RAD_F32, {hc * (hc + 2)}); + o.t(D, {M, n}); + o.t((uint32_t)RAD_F32, {M, hc}); + o.t((uint32_t)RAD_F32, {M, hc * hc}); + return o.finish("mhc_pre", operand, out); +} + +static int64_t mhc_part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; } + +int ref_mhc_pre_partial_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0); + const int64_t chunk = gi(p, n_p, "chunk", 0), chunks = gi(p, n_p, "chunks", 0); + if (M <= 0 || n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk || chunks <= 0) + return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, {M, hc * n}); + o.t((uint32_t)RAD_F32, {hc * (hc + 2), hc * n}); + o.t((uint32_t)RAD_F32, {M, chunks * mhc_part_stride(hc)}); + return o.finish("mhc_pre_partial", operand, out); +} + +int ref_mhc_pre_finish_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0); + const int64_t chunk = gi(p, n_p, "chunk", 0); + if (M <= 0 || n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk) + return RAD_E_UNSUPPORTED; + Opd o; + o.t((uint32_t)RAD_F32, {M, hc * n / chunk * mhc_part_stride(hc)}); + o.t(D, {M, hc * n}); + o.t((uint32_t)RAD_F32, {3}); + o.t((uint32_t)RAD_F32, {hc * (hc + 2)}); + o.t(D, {M, n}); + o.t((uint32_t)RAD_F32, {M, hc}); + o.t((uint32_t)RAD_F32, {M, hc * hc}); + return o.finish("mhc_pre_finish", operand, out); +} + +int ref_mhc_post_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0); + if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, {M, n}); o.t(D, {M, hc * n}); + o.t((uint32_t)RAD_F32, {M, hc}); o.t((uint32_t)RAD_F32, {M, hc * hc}); + o.t(D, {M, hc * n}); + return o.finish("mhc_post", operand, out); +} + +int ref_mhc_contract_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0); + if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, {M, hc * n}); o.t(D, {M, n}); + return o.finish("mhc_contract", operand, out); +} + int ref_hc_write_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -573,6 +662,87 @@ int ref_attn_local_rel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc return o.finish("attn_local_rel", operand, out); } +int ref_swiglu_clamped_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return ref_silu_mul_shape(p, n_p, operand, out); +} +int ref_router_sigmoid_topk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), ne = gi(p, n_p, "n_expert", 0), + k = gi(p, n_p, "top_k", 0); + if (M < 1 || ne < 1 || ne > 512 || k < 1 || k > ne) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, ne }); + o.t(RAD_F32, { ne }); + o.t_idx({ M, k }, ne, -1, 0); + o.t(D, { M, k }); + return o.finish("router_sigmoid_topk", operand, out); +} +int ref_mla_project_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), h = gi(p, n_p, "heads", 0), d = gi(p, n_p, "head_dim", 0), + l = gi(p, n_p, "latent_dim", 0); + const char* mode = gs(p, n_p, "mode"); + const bool absorb = mode && !std::strcmp(mode, "absorb"), + expand = mode && !std::strcmp(mode, "expand"); + if (M < 1 || h < 1 || d < 1 || l < 1 || (!absorb && !expand)) return RAD_E_UNSUPPORTED; + Opd o; + o.t(RAD_BF16, { M, h, absorb ? d : l }); + o.t(RAD_BF16, { h * 2 * d, l }); + o.t(RAD_BF16, { M, h, absorb ? l : d }); + return o.finish("mla_project", operand, out); +} +int ref_dsa_query_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M < 1 || n < 1 || n > 256 || (n & (n - 1))) return RAD_E_UNSUPPORTED; + Opd o; + o.t(RAD_BF16, { M, n }); + o.t(RAD_F8E4M3, { M, n }); + o.t(RAD_F32, { M, 1 }); + return o.finish("dsa_query", operand, out); +} +int ref_dsa_pool_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), ratio = gi(p, n_p, "ratio", 0); + if (M < 1 || n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16) + return RAD_E_UNSUPPORTED; + Opd o; + o.t(RAD_BF16, { M * ratio, 2 * n }); + o.t(RAD_F32, { ratio, n }); + o.t(RAD_F8E4M3, { M, n }); + o.t(RAD_F32, { M, 1 }); + o.skip(); + o.skip(); // Optional paged cache writes use a hand-built unique page list. + return o.finish("dsa_pool", operand, out); +} +int ref_dsa_score_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), H = gi(p, n_p, "heads", 0); + const int64_t B = gi(p, n_p, "blocks", 0), S = gi(p, n_p, "seqs", 0), pages = S * B; + if (M < 1 || n < 1 || H < 1 || H > 64 || B < 1 || S < 1 || S > M) return RAD_E_UNSUPPORTED; + Opd o; + o.t(RAD_F8E4M3, { M, H, n }); + o.t_fill(RAD_F32, { M, H }, RAD_FILL_SIGMOID, 0); + o.t(RAD_F32, { M, H }); + o.t(RAD_F8E4M3, { pages, n }); + o.t_fill(RAD_F32, { pages }, RAD_FILL_SIGMOID, 0); + o.t_idx({ S, B }, pages, -1, 0); + o.t_idx({ S + 1 }, M, -1, RAD_OPD_F_IDX_CU); + o.t_idx({ S }, 0, B, 0); + o.t(RAD_F32, { M, B }); + return o.finish("dsa_score", operand, out); +} +int ref_mla_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "latent_dim", 0), + H = gi(p, n_p, "heads", 0); + const int64_t B = gi(p, n_p, "blocks", 0), bs = gi(p, n_p, "block_size", 0), + pages = std::max((int64_t)2, B * M); + if (M < 1 || D < 1 || D > 2048 || H < 1 || B < 1 || bs < 1) return RAD_E_UNSUPPORTED; + const uint32_t dtype = act_dt(p, n_p); + Opd o; + o.t(dtype, { M, H, D }); + o.t(dtype, { pages, 1, bs, D }); + o.t_idx({ M, B }, pages, -1, 0); + o.t_idx({ M }, 0, B * bs, 0); + o.t(dtype, { M, H, D }); + return o.finish("mla_attn", operand, out); +} int ref_silu_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -931,6 +1101,15 @@ int ref_dequant_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) /* ================================================================== gemm */ +int ref_gemm_nt_f32_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); + if (M < 1 || N < 1 || K < 1) return RAD_E_UNSUPPORTED; + Opd o; + o.t(RAD_BF16, { M, K }); + o.t(RAD_F32, { N, K }); + o.t(RAD_F32, { M, N }); + return o.finish("gemm_nt_f32", operand, out); +} int ref_gemm_nt_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); @@ -971,7 +1150,8 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO const int64_t group = gi(p, n_p, "group", 0); const char* q = gs(p, n_p, "dtype"); auto is = [&](const char* s) { return q && std::strcmp(q, s) == 0; }; - const bool a8 = is("fp8a8"), a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8"); + const bool f32s = is("fp8a8f32"); + const bool a8 = is("fp8a8") || f32s, a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8"); /* i8a8h is i8a8's operands; its rotation is in the values. */ const bool i8 = is("i8a8") || is("i8a8h"), mx = is("mxfp4a8"); if ((!a8 && !a16 && !w4 && !w8 && !i8 && !mx) || N <= 0 || K <= 0 || group <= 0) @@ -1015,7 +1195,8 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO o.skip(); /* a_scale */ } o.t((uint32_t)RAD_F8E4M3, { N, K }); /* b -- the checkpoint's own bytes */ - o.t((uint32_t)RAD_BF16, { nb, kb }); /* b_scale -- weight_scale_inv, per 128x128 */ + /* b_scale -- weight_scale_inv, per 128x128; f32 at fp8a8f32 */ + o.t(f32s ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16, { nb, kb }); } if (bias) { o.t((uint32_t)RAD_BF16, { N }); /* bias */ @@ -1460,7 +1641,8 @@ struct MoeScaleGrid { int64_t rows, k; }; static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) { const char* d = gs(p, n_p, "dtype"); auto is = [&](const char* s) { return d && std::strcmp(d, s) == 0; }; - if (is("fp8a8")) return { g, g }; + if (is("fp8a8") || is("fp8a8f32")) return { g, g }; + if (is("mxfp4a8")) return { 1, 32 }; if (is("w4a8") || is("w4a8h") || is("w4nla8h")) return { 1, g }; if (is("w4nl64a8h") || is("w5nl64a8h")) return { 1, g / 2 }; if (is("w4nl32a8h")) return { 1, g / 4 }; @@ -1490,14 +1672,21 @@ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou const uint32_t D = act_dt(p, n_p); Opd o; const int64_t AR = sorted_a_order(p, n_p) ? M * k : M; + const char* kind = gs(p, n_p, "dtype"); + const bool mx = kind && !std::strcmp(kind, "mxfp4a8"); + const auto SD = kind && !std::strcmp(kind, "fp8a8f32") ? (uint32_t)RAD_F32 : D; o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */ o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */ - o.t((uint32_t)RAD_F8E4M3, { ne0, N0, K0 }); /* w -- the even experts */ - o.t(D, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k }); /* w_scale */ + /* w -- the even experts; mxfp4a8 carries e2m1 codes with an E8M0 byte per (row, 32 of K) */ + o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { ne0, N0, K0 }); + if (mx) o.t_idx_dt(RAD_U8, { ne0, N0, (K0 + 31) / 32 }, 0, 127, 0); /* w_scale */ + else o.t(SD, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k }); o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */ o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */ - o.t((uint32_t)RAD_F8E4M3, { ne1, N1, K1 }); /* w_odd -- the odd experts */ - o.t(D, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k }); /* w_odd_scale */ + /* w_odd -- the odd experts */ + o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { ne1, N1, K1 }); + if (mx) o.t_idx_dt(RAD_U8, { ne1, N1, (K1 + 31) / 32 }, 0, 127, 0); /* w_odd_scale */ + else o.t(SD, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k }); o.t(D, { M * k, N }); /* y -- in sorted order */ return o.finish("moe_gemm_q", operand, out); } @@ -1525,10 +1714,13 @@ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDes const uint32_t D = act_dt(p, n_p); Opd o; const int64_t AR = sorted_a_order(p, n_p) ? M * k : M; + const char* kind = gs(p, n_p, "dtype"); + const bool mx = kind && !std::strcmp(kind, "mxfp4a8"); auto cls = [&](int q) { const int64_t nq = (ne + 3 - q) / 4; - o.t((uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] }); - o.t(D, { nq, (Nq[q] + sg.rows - 1) / sg.rows, (Kq[q] + sg.k - 1) / sg.k }); + o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] }); + if (mx) o.t_idx_dt(RAD_U8, {nq, Nq[q], (Kq[q] + 31) / 32}, 0, 127, 0); + else o.t(D, { nq, (Nq[q] + sg.rows - 1) / sg.rows, (Kq[q] + sg.k - 1) / sg.k }); }; o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */ o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */ diff --git a/tests/build_test.cpp b/tests/build_test.cpp index 39a12e3f..3f4d2242 100644 --- a/tests/build_test.cpp +++ b/tests/build_test.cpp @@ -751,6 +751,34 @@ TEST(kv_block_size_comes_off_the_kernel) { CHECK_EQ((int)gi.layers.size(), 2); } +TEST(glm_index_cache_pages_are_sized_by_the_real_pool_consumer) { + Registry reg; + REQUIRE_EQ(reg.load_dir(home() + "/kernels", { "libref" }), RAD_OK); + Builder b(reg, make_meta(), make_ctx()); + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_U8; + kd.n_head_kv = 1; + kd.head_dim = 17; + const auto group = b.decl_kv_group("glm_index", &kd); + RadWeightDecl wd{}; + wd.dtype = RAD_F32; + wd.rank = 2; + wd.shape[0] = 4; + wd.shape[1] = 128; + wd.access = RAD_ACCESS_PER_TOKEN; + wd.shard = RAD_SHARD_NONE; + const auto ape = b.decl_weight("pool_ape", &wd); + const RadParam params[] = { RAD_RANGE("M", 1, 12), RAD_INT("n", 128), RAD_INT("ratio", 4), + RAD_STR("dtype", "bf16"), RAD_INT("block_size", 4) }; + REQUIRE(b.decl_op("dsa_pool", params, 5, &ape, 1)); + CHECK_EQ(b.kv_block_size(group), 4); + CHECK_OK(b.bind_layer_kv(0, group)); + CHECK_OK(b.bind_layer_kv(1, group)); + REQUIRE_EQ(b.finish(), RAD_OK); + CHECK_EQ(b.program().kv_groups[group].bytes_per_block, (int64_t)(2 * 136)); +} + TEST(a_kv_group_with_no_layers_is_an_error) { NEED_PLUGIN(reg) Builder b(reg, make_meta(), make_ctx()); diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index e81fafd7..03e63ce7 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -229,6 +229,669 @@ int run(const char* op, A& args, int rank = 0, int world = 1) { } /* namespace */ +TEST(manifold_read_uses_whole_stream_rms_and_unaveraged_pre_mix) { + T h(RAD_F32, {1, 2}); h.f({1, 3}); + T fn(RAD_F32, {8, 2}); + fn.f({3.0f * std::log(3.0f), 0}); + T scale(RAD_F32, {3}); scale.f({1, 1, 1}); + T base(RAD_F32, {8}); base.f({0, 0, std::log(3.0f), 0, 0, 0, 0, 0}); + T x(RAD_F32, {1, 1}), post(RAD_F32, {1, 2}), comb(RAD_F32, {1, 4}); + A a; a.t(h).t(fn).t(scale).t(base).t(x).t(post).t(comb) + .i("M", 1).i("n", 1).i("hc", 2).i("iterations", 20) + .d("eps", 4).d("hc_eps", 0).s("dtype", "f32"); + REQUIRE_EQ(run("mhc_pre", a), RAD_OK); + /* RMS inverse = 1/3, pre = [3/4,1/2], post = [3/2,1]. */ + CHECK_NEAR(x.at(0), 2.25f, 1e-6); + CHECK_NEAR(post.at(0), 1.5f, 1e-6); + CHECK_EQ(post.at(1), 1.0f); + for (int i = 0; i < 4; ++i) CHECK_EQ(comb.at(i), 0.5f); + a.ps[3].ival = 0; + CHECK_EQ(run("mhc_pre", a), RAD_E_SHAPE); +} + +/* Two ranks each project half of the chunks; their partials, joined row by row as the + * row-interleaved all_gather lays them out, finish to mhc_pre. Quarter-step inputs keep every + * product and sum exact, so the split is compared bit for bit. */ +TEST(manifold_read_split_by_chunks_finishes_to_the_whole_read) { + const int64_t M = 3, n = 8, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28; + T h(RAD_F32, {M, W}), fn(RAD_F32, {mix, W}), scale(RAD_F32, {3}), base(RAD_F32, {mix}); + std::vector hv((size_t)(M * W)), fv((size_t)(mix * W)), bv((size_t)mix); + for (size_t i = 0; i < hv.size(); ++i) hv[i] = (float)((int)((i * 7) % 9) - 4) * 0.25f; + for (size_t i = 0; i < fv.size(); ++i) fv[i] = (float)((int)((i * 5) % 7) - 3) * 0.125f; + for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)((int)(i % 5) - 2) * 0.5f; + h.f(hv); fn.f(fv); scale.f({0.5f, 0.25f, 1.0f}); base.f(bv); + T x(RAD_F32, {M, n}), post(RAD_F32, {M, hc}), comb(RAD_F32, {M, hc * hc}); + A whole; whole.t(h).t(fn).t(scale).t(base).t(x).t(post).t(comb) + .i("M", M).i("n", n).i("hc", hc).i("iterations", 20) + .d("eps", 1e-5).d("hc_eps", 1e-6).s("dtype", "f32"); + REQUIRE_EQ(run("mhc_pre", whole), RAD_OK); + T gathered(RAD_F32, {M, 4 * S}); + for (int rank = 0; rank < 2; ++rank) { + T part(RAD_F32, {M, 2 * S}); + part.f(std::vector((size_t)(M * 2 * S), 9.0f)); + A pa; pa.t(h).t(fn).t(part).i("M", M).i("n", n).i("hc", hc).i("chunk", 8) + .i("first", 2 * rank).i("chunks", 2).s("dtype", "f32"); + REQUIRE_EQ(run("mhc_pre_partial", pa), RAD_OK); + for (int64_t r = 0; r < M; ++r) for (int64_t c = 0; c < 2; ++c) + for (int64_t j = mix + 1; j < S; ++j) CHECK_EQ(part.at(r * 2 * S + c * S + j), 0.0f); + for (int64_t r = 0; r < M; ++r) for (int64_t i = 0; i < 2 * S; ++i) + st_dt(RAD_F32, gathered.t.data, r * 4 * S + rank * 2 * S + i, part.at(r * 2 * S + i)); + } + T x2(RAD_F32, {M, n}), post2(RAD_F32, {M, hc}), comb2(RAD_F32, {M, hc * hc}); + A fa; fa.t(gathered).t(h).t(scale).t(base).t(x2).t(post2).t(comb2) + .i("M", M).i("n", n).i("hc", hc).i("iterations", 20) + .d("eps", 1e-5).d("hc_eps", 1e-6).i("chunk", 8).s("dtype", "f32"); + REQUIRE_EQ(run("mhc_pre_finish", fa), RAD_OK); + for (int64_t i = 0; i < M * n; ++i) CHECK_EQ(x2.at(i), x.at(i)); + for (int64_t i = 0; i < M * hc; ++i) CHECK_EQ(post2.at(i), post.at(i)); + for (int64_t i = 0; i < M * hc * hc; ++i) CHECK_EQ(comb2.at(i), comb.at(i)); + /* A chunk that does not divide the residual, or a range past its end, is refused. */ + T part(RAD_F32, {M, 2 * S}); + A bad; bad.t(h).t(fn).t(part).i("M", M).i("n", n).i("hc", hc).i("chunk", 8) + .i("first", 3).i("chunks", 2).s("dtype", "f32"); + CHECK_EQ(run("mhc_pre_partial", bad), RAD_E_SHAPE); + fa.ps[6].ival = 7; + CHECK_EQ(run("mhc_pre_finish", fa), RAD_E_SHAPE); +} + +TEST(manifold_post_mixes_sources_into_destinations_and_contracts_by_mean) { + T h(RAD_F32, {1, 6}); h.f({10, 20, 30, 40, 50, 60}); + T x(RAD_F32, {1, 2}); x.f({2, 4}); + T post(RAD_F32, {1, 3}); post.f({1, 2, 3}); + T comb(RAD_F32, {1, 9}); comb.f({0, 1, 0, 0, 0, 1, 1, 0, 0}); + T out(RAD_F32, {1, 6}); + A a; a.t(x).t(h).t(post).t(comb).t(out).i("M", 1).i("n", 2).i("hc", 3).s("dtype", "f32"); + REQUIRE_EQ(run("mhc_post", a), RAD_OK); + const float expected[] = {52, 64, 14, 28, 36, 52}; + for (int i = 0; i < 6; ++i) CHECK_EQ(out.at(i), expected[i]); + /* The input remains the unnormalized residual. */ + CHECK_EQ(h.at(0), 10.0f); + a.ts[4] = h.t; + CHECK_EQ(run("mhc_post", a), RAD_E_SHAPE); + T contracted(RAD_F32, {1, 2}); + A c; c.t(h).t(contracted).i("M", 1).i("n", 2).i("hc", 3).s("dtype", "f32"); + REQUIRE_EQ(run("mhc_contract", c), RAD_OK); + CHECK_EQ(contracted.at(0), 30.0f); + CHECK_EQ(contracted.at(1), 40.0f); +} + +TEST(manifold_sinkhorn_first_pass_and_epsilon_are_distinct) { + T h(RAD_F32, {1, 2}); h.f({1, 3}); + T fn(RAD_F32, {8, 2}), scale(RAD_F32, {3}); scale.f({1, 1, 1}); + T base(RAD_F32, {8}); base.f({0, 0, 0, 0, std::log(3.0f), 0, 0, 0}); + T x(RAD_F32, {1, 1}), post(RAD_F32, {1, 2}), comb(RAD_F32, {1, 4}); + A a; a.t(h).t(fn).t(scale).t(base).t(x).t(post).t(comb) + .i("M", 1).i("n", 1).i("hc", 2).i("iterations", 1) + .d("eps", 1e-5).d("hc_eps", 0).s("dtype", "f32"); + REQUIRE_EQ(run("mhc_pre", a), RAD_OK); + const float first[] = {0.6f, 1.0f / 3, 0.4f, 2.0f / 3}; + for (int i = 0; i < 4; ++i) CHECK_NEAR(comb.at(i), first[i], 1e-6); + a.ps[3].ival = 20; + REQUIRE_EQ(run("mhc_pre", a), RAD_OK); + CHECK_NEAR(comb.at(0), 0.633974596f, 1e-6); + CHECK_NEAR(comb.at(1), 0.366025404f, 1e-6); + /* Uniform logits: first pass is (.5 + .25) / (1.5 + .25) = 3/7. */ + base.f({0, 0, 0, 0, 0, 0, 0, 0}); + a.ps[3].ival = 1; + a.ps[5].dval = 0.25; + REQUIRE_EQ(run("mhc_pre", a), RAD_OK); + CHECK_EQ(x.at(0), 3.0f); + for (int i = 0; i < 4; ++i) CHECK_NEAR(comb.at(i), 3.0f / 7, 1e-6); +} + +TEST(kda_candidate_states_restore_the_accepted_prefix) { + T q(RAD_F32, {2, 1, 2}); q.f({1, 0, 1, 0}); + T k(RAD_F32, {2, 1, 2}); k.f({1, 0, 1, 0}); + T v(RAD_F32, {2, 1, 1}); v.f({2, 2}); + T g(RAD_F32, {2, 1, 2}); g.f({0, std::log(3.0f), 0, std::log(3.0f)}); + T b(RAD_F32, {2, 1}), alog(RAD_F32, {1}), bias(RAD_F32, {2}); + T state(RAD_F32, {3, 1, 1, 2}); state.f({4, 8, 0, 0, 123, 456}); + T idx(RAD_I32, {1, 2}); idx.n({0, 1}); + T cu(RAD_I32, {2}); cu.n({0, 2}); + T accepted(RAD_I32, {1}); accepted.n({1}); + T out(RAD_F32, {2, 1, 1}); + A a; a.t(q).t(k).t(v).t(g).t(b).t(alog).t(bias).t(state).t(idx).t(cu).t(accepted).tnull().t(out) + .i("M", 2).i("heads", 1).i("head_k", 2).i("head_v", 1) + .d("lower_bound", -std::log(16.0)).d("scale", 1).d("l2_eps", 1e-6) + .s("mode", "verify").s("dtype", "f32"); + REQUIRE_EQ(run("kda_update", a), RAD_OK); + /* Decays [1/4,1/8] distinguish the per-channel gate from a scalar gate. */ + CHECK_NEAR(out.at(0), 1.5f, 3e-6); + CHECK_NEAR(out.at(1), 1.1875f, 3e-6); + CHECK_NEAR(state.at(0), 1.5f, 3e-6); + CHECK_NEAR(state.at(1), 1.0f, 3e-6); + CHECK_NEAR(state.at(2), 1.1875f, 3e-6); + CHECK_NEAR(state.at(3), 0.125f, 3e-6); + CHECK_EQ(state.at(4), 123.0f); + CHECK_EQ(state.at(5), 456.0f); + /* The next step rejects candidate 1 and reads candidate 0, then writes candidate 0's slot. */ + cu.n({0, 1}); + REQUIRE_EQ(run("kda_update", a), RAD_OK); + CHECK_NEAR(out.at(0), 1.1875f, 3e-6); + /* Accepting both candidates instead starts from slot 1. */ + accepted.n({2}); + REQUIRE_EQ(run("kda_update", a), RAD_OK); + CHECK_NEAR(out.at(0), 1.1484375f, 3e-6); + accepted.n({3}); + CHECK_EQ(run("kda_update", a), RAD_E_SHAPE); +} + +TEST(kda_prefill_commits_final_state_and_uses_absolute_cu_offsets) { + T q(RAD_F32, {3, 1, 2}); q.f({1000, 1000, 1, 0, 1, 0}); + T k(RAD_F32, {3, 1, 2}); k.f({1000, 1000, 1, 0, 1, 0}); + T v(RAD_F32, {3, 1, 1}); v.f({1000, 2, 2}); + T g(RAD_F32, {3, 1, 2}); g.f({0, 0, 0, std::log(3.0f), 0, std::log(3.0f)}); + T b(RAD_F32, {3, 1}), alog(RAD_F32, {1}), bias(RAD_F32, {2}); + T state(RAD_F32, {2, 1, 1, 2}); state.f({4, 8, 123, 456}); + T idx(RAD_I32, {1, 1}); idx.n({0}); + T cu(RAD_I32, {2}); cu.n({1, 3}); + T init(RAD_I32, {1}); init.n({1}); + T out(RAD_F32, {3, 1, 1}); out.f({77, 77, 77}); + A a; a.t(q).t(k).t(v).t(g).t(b).t(alog).t(bias).t(state).t(idx).t(cu).tnull().t(init).t(out) + .i("M", 3).i("heads", 1).i("head_k", 2).i("head_v", 1) + .d("lower_bound", -std::log(16.0)).d("scale", 1).d("l2_eps", 1e-6) + .s("mode", "prefill").s("dtype", "f32"); + REQUIRE_EQ(run("kda_update", a), RAD_OK); + CHECK_EQ(out.at(0), 77.0f); + CHECK_NEAR(out.at(1), 1.5f, 3e-6); + CHECK_NEAR(out.at(2), 1.1875f, 3e-6); + CHECK_NEAR(state.at(0), 1.1875f, 3e-6); + CHECK_NEAR(state.at(1), 0.125f, 3e-6); + CHECK_EQ(state.at(2), 123.0f); + init.n({0}); + REQUIRE_EQ(run("kda_update", a), RAD_OK); + CHECK_NEAR(out.at(1), 1.0f, 3e-6); + CHECK_NEAR(out.at(2), 1.125f, 3e-6); + idx.n({-1}); + REQUIRE_EQ(run("kda_update", a), RAD_OK); + CHECK_EQ(out.at(1), 0.0f); + CHECK_EQ(out.at(2), 0.0f); +} + +TEST(mla_attention_reads_one_latent_and_masks_the_last_selected_page) { + T q(RAD_F32, { 1, 1, 2 }), kv(RAD_F32, { 2, 1, 2, 2 }), bt(RAD_I32, { 1, 2 }); + T len(RAD_I32, { 1 }), out(RAD_F32, { 1, 1, 2 }); + q.f({ 0, 0 }); + kv.f({ 3, 5, 1000, -1000, 1, 0, 0, 1 }); + bt.n({ 1, 0 }); + len.n({ 3 }); + A a; + a.t(q) + .t(kv) + .t(bt) + .t(len) + .t(out) + .i("M", 7) + .i("latent_dim", 2) + .i("heads", 1) + .i("blocks", 2) + .i("block_size", 2) + .d("scale", 1) + .s("dtype", "f32"); + REQUIRE_EQ(run("mla_attn", a), RAD_OK); + CHECK_NEAR(out.at(0), 4.0 / 3, 1e-6); + CHECK_EQ(out.at(1), 2); + q.f({ std::log(3.0f), 0 }); + kv.f({ 0, 0, 1000, -1000, 1, 0, 0, 0 }); + len.n({ 2 }); + REQUIRE_EQ(run("mla_attn", a), RAD_OK); + CHECK_NEAR(out.at(0), 0.75, 1e-6); + CHECK_EQ(out.at(1), 0); + len.n({ 0 }); + REQUIRE_EQ(run("mla_attn", a), RAD_OK); + CHECK_EQ(out.at(0), 0); + CHECK_EQ(out.at(1), 0); + len.n({ 3 }); + bt.n({ -1, 99 }); + REQUIRE_EQ(run("mla_attn", a), RAD_OK); + CHECK_EQ(out.at(0), 0); + CHECK_EQ(out.at(1), 0); +} + +TEST(dsa_score_relu_is_per_head_before_signed_weights_and_masks_invalid_history) { + T q(RAD_F8E4M3, { 2, 2, 2 }), qs(RAD_F32, { 2, 2 }), gate(RAD_F32, { 2, 2 }); + T k(RAD_F8E4M3, { 3, 2 }), ks(RAD_F32, { 3 }), bt(RAD_I32, { 2, 3 }); + T cu(RAD_I32, { 3 }), nc(RAD_I32, { 2 }), out(RAD_F32, { 2, 3 }); + q.f({ 1, 0, 0, 1, -1, 0, 0, -1 }); + qs.f({ 2, 0.5, 1, 1 }); + gate.f({ -1, 4, 2, -1 }); + k.f({ 1, -1, 2, 3, -2, -4 }); + ks.f({ 0.25, 0.5, 1 }); + bt.n({ 0, 1, -1, 2, 0, 1 }); + cu.n({ 0, 1, 2 }); + nc.n({ 2, 1 }); + A a; + a.t(q) + .t(qs) + .t(gate) + .t(k) + .t(ks) + .t(bt) + .t(cu) + .t(nc) + .t(out) + .i("M", 9) + .i("n", 2) + .i("heads", 2) + .i("blocks", 3) + .i("seqs", 2) + .s("dtype", "fp8_e4m3"); + REQUIRE_EQ(run("dsa_score", a), RAD_OK); + CHECK_EQ(out.at(0), -0.25f); + CHECK_EQ(out.at(1), 0.5f); + CHECK_EQ(out.at(3), 0); + for (int i : { 2, 4, 5 }) CHECK_EQ(out.at(i), -INFINITY); + bt.n({ 99, 1, -1, 2, 0, 1 }); + REQUIRE_EQ(run("dsa_score", a), RAD_OK); + CHECK_EQ(out.at(0), -INFINITY); +} + +TEST(kda_anchor_replays_only_the_accepted_prefix_of_the_previous_window) { + constexpr int D = 128; + for (int accepted : { 1, 2, 3 }) { + T q(RAD_BF16, { 3, 1, D }), k(RAD_BF16, { 3, 1, D }), v(RAD_BF16, { 3, 1, D }), + g(RAD_BF16, { 3, 1, D }); + T beta(RAD_BF16, { 3, 1 }), al(RAD_F32, { 1 }), bias(RAD_F32, { D }); + T anchor(RAD_F32, { 2, 1, D, D }), candidate(RAD_F32, { 3, 1, D, D }); + T ai(RAD_I32, { 1, 6 }), ci(RAD_I32, { 1, 3 }), cu(RAD_I32, { 2 }), na(RAD_I32, { 1 }), + init(RAD_I32, { 1 }); + T ao(RAD_BF16, { 3, 1, D }), co(RAD_BF16, { 3, 1, D }); + std::vector values(3 * D); + for (int j = 0; j < 3 * D; ++j) values[j] = (float)(j % 17 - 8) * 0.125f; + q.f(values); + v.f(values); + for (int j = 0; j < 3 * D; ++j) values[j] = (float)(j % 11 - 5) * 0.25f; + k.f(values); + g.f(std::vector(3 * D, 0)); + beta.f({ 0, 0.5f, -0.5f }); + al.f({ 0 }); + bias.f(std::vector(D, -1)); + anchor.f(std::vector(2 * D * D, 0)); + candidate.f(std::vector(3 * D * D, 0)); + ai.n({ 0, 0, 0, 1, 1, 1 }); + ci.n({ 0, 1, 2 }); + cu.n({ 0, 3 }); + na.n({ 1 }); + init.n({ 1 }); + A a; + a.t(q) + .t(k) + .t(v) + .t(g) + .t(beta) + .t(al) + .t(bias) + .t(anchor) + .t(ai) + .t(cu) + .t(na) + .t(init) + .t(ao) + .i("M", 3) + .i("heads", 1) + .i("head_k", D) + .i("head_v", D) + .d("lower_bound", -5) + .d("scale", 1.0 / std::sqrt(128.0)) + .d("l2_eps", 1e-6) + .s("mode", "verify") + .s("dtype", "bf16") + .s("state_form", "anchor"); + A c; + c.t(q) + .t(k) + .t(v) + .t(g) + .t(beta) + .t(al) + .t(bias) + .t(candidate) + .t(ci) + .t(cu) + .t(na) + .t(init) + .t(co) + .i("M", 3) + .i("heads", 1) + .i("head_k", D) + .i("head_v", D) + .d("lower_bound", -5) + .d("scale", 1.0 / std::sqrt(128.0)) + .d("l2_eps", 1e-6) + .s("mode", "verify") + .s("dtype", "bf16"); + REQUIRE_EQ(run("kda_update", a), RAD_OK); + REQUIRE_EQ(run("kda_update", c), RAD_OK); + for (int j = 0; j < 3 * D; ++j) CHECK_EQ(ao.at(j), co.at(j)); + for (int j = 0; j < D * D; ++j) CHECK_EQ(anchor.at(j), 0); + std::vector committed(D * D); + for (int j = 0; j < D * D; ++j) committed[j] = candidate.at((accepted - 1) * D * D + j); + na.n({ accepted }); + REQUIRE_EQ(run("kda_update", a), RAD_OK); + REQUIRE_EQ(run("kda_update", c), RAD_OK); + for (int j = 0; j < 3 * D; ++j) CHECK_EQ(ao.at(j), co.at(j)); + for (int j = 0; j < D * D; ++j) CHECK_EQ(anchor.at(j), committed[j]); + const auto saved = anchor.mem; + na.n({ 4 }); + CHECK_EQ(run("kda_update", a), RAD_E_SHAPE); + CHECK(anchor.mem == saved); + } +} + +TEST(mla_projects_the_key_and_value_halves_with_opposite_orientations) { + T q(RAD_BF16, { 1, 2, 2 }), w(RAD_BF16, { 8, 3 }), latent(RAD_BF16, { 1, 2, 3 }), + out(RAD_BF16, { 1, 2, 2 }); + q.f({ 2, -1, 3, 1 }); + w.f({ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1, 0, 1, 2, 0, -2, 2, 3, 4, 5, 6, 7 }); + A a; + a.t(q) + .t(w) + .t(latent) + .i("M", 7) + .i("heads", 2) + .i("head_dim", 2) + .i("latent_dim", 3) + .s("mode", "absorb") + .s("dtype", "bf16"); + REQUIRE_EQ(run("mla_project", a), RAD_OK); + CHECK_EQ(latent.at(0), -2); + CHECK_EQ(latent.at(1), -1); + CHECK_EQ(latent.at(2), 0); + CHECK_EQ(latent.at(3), -1); + CHECK_EQ(latent.at(4), 0); + CHECK_EQ(latent.at(5), 1); + A b; + b.t(latent) + .t(w) + .t(out) + .i("M", 7) + .i("heads", 2) + .i("head_dim", 2) + .i("latent_dim", 3) + .s("mode", "expand") + .s("dtype", "bf16"); + REQUIRE_EQ(run("mla_project", b), RAD_OK); + CHECK_EQ(out.at(0), -22); + CHECK_EQ(out.at(1), -31); + CHECK_EQ(out.at(2), 2); + CHECK_EQ(out.at(3), 2); + auto flatten = [](RadTensor& t) { + t.rank = 2; + t.shape[1] *= t.shape[2]; + t.stride[1] = t.stride[2]; + }; + flatten(a.ts[0]); + flatten(a.ts[2]); + REQUIRE_EQ(run("mla_project", a), RAD_OK); + flatten(b.ts[0]); + flatten(b.ts[2]); + REQUIRE_EQ(run("mla_project", b), RAD_OK); + CHECK_EQ(out.at(0), -22); + CHECK_EQ(out.at(1), -31); + CHECK_EQ(out.at(2), 2); + CHECK_EQ(out.at(3), 2); +} + +TEST(moe_gather_preserves_f32_mixture_weights_between_bf16_expert_outputs) { + T experts(RAD_BF16, { 2, 1 }), weights(RAD_F32, { 1, 2 }), sorted(RAD_I32, { 2 }), + out(RAD_BF16, { 1, 1 }); + experts.f({ 1024, -1024 }); + weights.f({ 1.0f + 1.0f / 8192, 1 }); + sorted.n({ 0, 1 }); + A a; + a.t(experts) + .t(weights) + .t(sorted) + .tnull() + .tnull() + .t(out) + .i("M", 1) + .i("n", 1) + .i("top_k", 2) + .s("dtype", "bf16"); + REQUIRE_EQ(run("moe_gather", a), RAD_OK); + CHECK_EQ(out.at(0), 0.125f); +} + +TEST(dsa_query_normalizes_the_rotation_and_rounds_power_of_two_scales) { + T x(RAD_BF16, { 1, 4 }), q(RAD_F8E4M3, { 1, 4 }), scale(RAD_F32, { 1, 1 }); + A a; + a.t(x).t(q).t(scale).i("M", 7).i("n", 4).s("dtype", "bf16"); + x.f({ 3, 4, 7, 7 }); + REQUIRE_EQ(run("dsa_query", a), RAD_OK); + CHECK_EQ(scale.at(0), 1.0f / 32); + CHECK_EQ(q.at(0), 320); + CHECK_EQ(q.at(1), -16); + CHECK_EQ(q.at(2), -112); + CHECK_EQ(q.at(3), -16); + for (float v : { 0.0f, 224.0f, 225.0f }) { + x.f({ v, v, v, v }); + REQUIRE_EQ(run("dsa_query", a), RAD_OK); + CHECK_EQ(scale.at(0), v == 0 ? std::ldexp(1.0f, -22) : v == 224 ? 1.0f : 2.0f); + CHECK_EQ(q.at(0), v == 0 ? 0 : v == 224 ? 448 : 224); + for (int d = 1; d < 4; ++d) CHECK_EQ(q.at(d), 0); + } +} + +TEST(f32_projection_preserves_small_weight_differences_and_output_bits) { + T x(RAD_BF16, { 1, 2 }), w(RAD_F32, { 2, 2 }), y(RAD_F32, { 1, 2 }); + x.f({ 1, -1 }); + w.f({ 1.0001f, 1.0f, 2.0002f, 2.0f }); + A a; + a.t(x).t(w).t(y).i("M", 7).i("N", 2).i("K", 2).s("dtype", "bf16"); + REQUIRE_EQ(run("gemm_nt_f32", a), RAD_OK); + CHECK_EQ(y.at(0), 1.0001f - 1.0f); + CHECK_EQ(y.at(1), 2.0002f - 2.0f); +} + +TEST(dsa_pool_writes_paged_codes_and_scales_and_the_scorer_reads_them) { + T kg(RAD_BF16, { 12, 256 }), ape(RAD_F32, { 4, 128 }), q(RAD_F8E4M3, { 3, 128 }), + scales(RAD_F32, { 3, 1 }); + T pages(RAD_I32, { 3 }), cache(RAD_U8, { 4, 1, 4, 34 }); + std::vector input(12 * 256, 0); + for (int r = 0; r < 12; ++r) + for (int d = 0; d < 128; ++d) input[r * 256 + d] = 1; + kg.f(input); + ape.f(std::vector(512, 0)); + pages.n({ 2, -1, 9 }); + std::fill(cache.mem.begin(), cache.mem.end(), 0xa5); + A pool; + pool.t(kg) + .t(ape) + .t(q) + .t(scales) + .t(pages) + .t(cache) + .i("M", 3) + .i("n", 128) + .i("ratio", 4) + .s("dtype", "bf16"); + REQUIRE_EQ(run("dsa_pool", pool), RAD_OK); + for (int i = 0; i < 4 * 136; ++i) + if (i >= 2 * 136 && i < 2 * 136 + 128) + CHECK_EQ(cache.mem[i], q.mem[i - 2 * 136]); + else if (i < 2 * 136 + 128 || i >= 2 * 136 + 132) + CHECK_EQ(cache.mem[i], 0xa5); + float stored = 0; + std::memcpy(&stored, cache.mem.data() + 2 * 136 + 128, sizeof(stored)); + CHECK_EQ(stored, scales.at(0)); + T query(RAD_F8E4M3, { 1, 32, 128 }), qs(RAD_F32, { 1, 32 }), gate(RAD_F32, { 1, 32 }); + query.f(std::vector(32 * 128, 1)); + qs.f(std::vector(32, 1)); + gate.f(std::vector(32, 1)); + T bt(RAD_I32, { 1, 3 }), cu(RAD_I32, { 2 }), nc(RAD_I32, { 1 }), out(RAD_F32, { 1, 3 }); + bt.n({ 2, -1, 9 }); + cu.n({ 0, 1 }); + nc.n({ 3 }); + A score; + score.t(query) + .t(qs) + .t(gate) + .t(cache) + .tnull() + .t(bt) + .t(cu) + .t(nc) + .t(out) + .i("M", 1) + .i("n", 128) + .i("heads", 32) + .i("blocks", 3) + .i("seqs", 1) + .s("dtype", "fp8_e4m3"); + REQUIRE_EQ(run("dsa_score", score), RAD_OK); + CHECK_EQ(out.at(0), 5.5f); + CHECK(std::isinf(out.at(1)) && out.at(1) < 0); + CHECK(std::isinf(out.at(2)) && out.at(2) < 0); +} + +TEST(dsa_pool_uses_channel_gates_bf16_boundaries_and_power_of_two_scales) { + T kg(RAD_BF16, { 2, 8 }), ape(RAD_F32, { 2, 4 }), q(RAD_F8E4M3, { 1, 4 }), + scale(RAD_F32, { 1, 1 }); + kg.f({ 0, 2, 4, 6, 0, 0, 0, 0, 4, 6, 8, 10, 0, 0, 0, 0 }); + ape.f({ 0, 0, 0, 0, std::log(3.0f), 0, std::log(3.0f), -std::log(3.0f) }); + A a; + a.t(kg).t(ape).t(q).t(scale).i("M", 7).i("n", 4).i("ratio", 2).s("dtype", "bf16"); + REQUIRE_EQ(run("dsa_pool", a), RAD_OK); + // Pooled [3,4,7,7]; H4/sqrt(4) = [10.5,-.5,-3.5,-.5]. + // 10.5*32=336 is the FP8 midpoint 320/352, rounded to even 320. + CHECK_EQ(scale.at(0), 1.0f / 32); + CHECK_EQ(q.at(0), 320); + CHECK_EQ(q.at(1), -16); + CHECK_EQ(q.at(2), -112); + CHECK_EQ(q.at(3), -16); + ape.f(std::vector(8, 0)); + for (float key : { 0.0f, 224.0f, 225.0f }) { + kg.f({ key, key, key, key, 0, 0, 0, 0, key, key, key, key, 0, 0, 0, 0 }); + REQUIRE_EQ(run("dsa_pool", a), RAD_OK); + CHECK_EQ(scale.at(0), key == 0 ? std::ldexp(1.0f, -22) : key == 224 ? 1.0f : 2.0f); + CHECK_EQ(q.at(0), key == 0 ? 0 : key == 224 ? 448 : 224); + for (int i = 1; i < 4; ++i) CHECK_EQ(q.at(i), 0); + } +} + +TEST(swiglu_clamping_is_asymmetric_and_precedes_the_activation) { + T gu(RAD_F32, { 1, 12 }), y(RAD_F32, { 1, 6 }); + gu.f({ -20, -2, 0, 2, 10, 20, -20, 20, 20, -20, 20, 20 }); + A a; + a.t(gu).t(y).i("M", 9).i("n", 6).d("limit", 10).s("dtype", "f32"); + REQUIRE_EQ(run("swiglu_clamped", a), RAD_OK); + const float gate[] = { -20, -2, 0, 2, 10, 10 }, up[] = { -10, 10, 10, -10, 10, 10 }; + for (int i = 0; i < 6; ++i) + CHECK_NEAR(y.at(i), (gate[i] / (1 + std::exp(-gate[i]))) * up[i], 1e-5); + CHECK(y.at(0) > 0 && y.at(0) < 1e-5); // a negative gate must not clamp to -10 + CHECK_EQ(y.at(4), y.at(5)); + A bad; + bad.t(gu).t(y).i("M", 1).i("n", 6).d("limit", 0).s("dtype", "f32"); + CHECK_EQ(run("swiglu_clamped", bad), RAD_E_SHAPE); +} + +TEST(sigmoid_router_uses_correction_only_for_selection_and_stable_ties) { + T lg(RAD_F32, { 1, 4 }), bias(RAD_F32, { 4 }), ids(RAD_I32, { 1, 2 }), w(RAD_F32, { 1, 2 }); + lg.f({ -std::log(3.0f), std::log(3.0f), 0, 0 }); + bias.f({ 1, -1, 0, 0 }); + for (int norm : { 0, 1 }) { + A a; + a.t(lg) + .t(bias) + .t(ids) + .t(w) + .i("M", 9) + .i("n_expert", 4) + .i("top_k", 2) + .i("norm", norm) + .d("route_scale", 2.5) + .s("dtype", "f32"); + REQUIRE_EQ(run("router_sigmoid_topk", a), RAD_OK); + CHECK_EQ(ids.at(0), 0); + CHECK_EQ(ids.at(1), 2); + CHECK_NEAR(w.at(0), norm ? 2.5 / 3 : 0.625, 1e-6); + CHECK_NEAR(w.at(1), norm ? 5.0 / 3 : 1.25, 1e-6); + } + lg.f({ 0, 0, 0, 0 }); + bias.f({ 0, 0, 0, 0 }); + A tie; + tie.t(lg) + .t(bias) + .t(ids) + .t(w) + .i("M", 1) + .i("n_expert", 4) + .i("top_k", 2) + .i("norm", 1) + .d("route_scale", 2.5) + .s("dtype", "f32"); + REQUIRE_EQ(run("router_sigmoid_topk", tie), RAD_OK); + CHECK_EQ(ids.at(0), 0); + CHECK_EQ(ids.at(1), 1); + CHECK_EQ(w.at(0), 1.25f); + CHECK_EQ(w.at(1), 1.25f); +} + +TEST(grouped_mxfp4_preserves_e2m1_codes_and_e8m0_scales) { + T input(RAD_F8E4M3, { 2, 64 }); + std::vector values(128, 1.0f); + for (int i = 64; i < 128; ++i) values[(size_t)i] = 2; + input.f(values); + T as(RAD_F32, { 2, 1 }); + as.f({ 0.5f, 0.5f }); + T even(RAD_FP4E2M1, { 1, 1, 64 }); + even.raw(std::vector(32, 0x22)); + T odd(RAD_FP4E2M1, { 1, 1, 64 }); + odd.raw(std::vector(32, 0x33)); + T es(RAD_U8, { 1, 1, 2 }); + es.raw({ 127, 128 }); + T os(RAD_U8, { 1, 1, 2 }); + os.raw({ 126, 127 }); + T sorted(RAD_I32, { 2 }); + sorted.n({ 1, 0 }); + T offsets(RAD_I32, { 3 }); + offsets.n({ 0, 1, 2 }); + T out(RAD_BF16, { 2, 1 }); + A a; + a.t(input) + .t(as) + .t(even) + .t(es) + .t(sorted) + .t(offsets) + .t(odd) + .t(os) + .t(out) + .i("M", 2) + .i("N", 1) + .i("K", 64) + .i("n_expert", 2) + .i("top_k", 1) + .i("group", 64) + .s("a_order", "token") + .s("dtype", "mxfp4a8"); + REQUIRE_EQ(run("moe_gemm_q", a), RAD_OK); + /* E2M1 0x2=1, 0x3=1.5. The second half of each row has its own power-of-two scale. */ + CHECK_EQ(out.at(0), 96.0f); + CHECK_EQ(out.at(1), 36.0f); + a.strs.emplace_back("sorted"); + a.ps[6].sval = a.strs.back().c_str(); + REQUIRE_EQ(run("moe_gemm_q", a), RAD_OK); + CHECK_EQ(out.at(0), 48.0f); + CHECK_EQ(out.at(1), 72.0f); + /* Each expert may have a separate address, including host-resident weights. */ + void* wp0[] = { even.t.data }; + void* wp1[] = { odd.t.data }; + void* sp0[] = { es.t.data }; + void* sp1[] = { os.t.data }; + const int operands[] = { 2, 3, 6, 7 }; + void* tables[] = { wp0, sp0, wp1, sp1 }; + for (int i = 0; i < 4; ++i) { + a.ts[(size_t)operands[i]].data = tables[i]; + a.ts[(size_t)operands[i]].stride[0] = 0; + } + a.ts[3].dtype = a.ts[7].dtype = RAD_E8M0; + REQUIRE_EQ(run("moe_gemm_q", a), RAD_OK); + CHECK_EQ(out.at(0), 48.0f); + CHECK_EQ(out.at(1), 72.0f); +} + /* ================================================================== the plugin surface */ TEST(plugin_surface) { CHECK(api().abi_version != nullptr); @@ -255,6 +918,8 @@ TEST(plugin_surface) { TEST(op_vocabulary) { static const char* kOps[] = { "rmsnorm", "rmsnorm_p", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter", + "mhc_pre", "mhc_pre_partial", "mhc_pre_finish", "mhc_post", "mhc_contract", "swiglu_clamped", "router_sigmoid_topk", "dsa_pool", "dsa_query", "dsa_score", "mla_attn", "mla_project", "gemm_nt_f32", + "kda_update", "layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean", "pool_rows", "relu", "clamp", "conv2d", "conv2d_unfold", "conv1d_dw", "rel_sinusoid", "seg_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "logit_softcap", "scale", @@ -3316,7 +3981,7 @@ TEST(op_moe_gemm_q_scale_grid_by_dtype) { /* N 256, K 512, group 128; the last class at N 128, K 256. */ const Want wants[] = { { "fp8a8", 2, 4 }, { "w4a8", 256, 4 }, { "w4a8h", 256, 4 }, { "w4nla8h", 256, 4 }, { "w4nl64a8h", 256, 8 }, { "w5nl64a8h", 256, 8 }, - { "w4nl32a8h", 256, 16 } }; + { "w4nl32a8h", 256, 16 }, { "mxfp4a8", 256, 16 } }; for (const char* op : { "moe_gemm_q", "moe_gemm_q_mod4" }) { const RadKernelInfo* k = kern(op); REQUIRE(k != nullptr && k->opd_shape != nullptr); @@ -3332,7 +3997,7 @@ TEST(op_moe_gemm_q_scale_grid_by_dtype) { RadOpdDesc d{}, dl{}; REQUIRE_EQ(k->opd_shape(r->p, r->n_p, 3, &d), RAD_OK); REQUIRE_EQ(k->opd_shape(r->p, r->n_p, last, &dl), RAD_OK); - CHECK_EQ(d.dtype, (uint32_t)RAD_BF16); + CHECK_EQ(d.dtype, !std::strcmp(w.dt, "mxfp4a8") ? (uint32_t)RAD_U8 : (uint32_t)RAD_BF16); CHECK_EQ(d.rank, 3u); CHECK_EQ(d.shape[0], four ? 2LL : 4LL); if (d.shape[1] != w.rows || d.shape[2] != w.cols) @@ -3402,7 +4067,7 @@ TEST(op_moe_gemm_q_scale_grid_by_dtype) { for (const char* op : { "moe_gemm_q", "moe_gemm_q_mod4" }) { const RadKernelInfo* k = kern(op); REQUIRE(k != nullptr && k->opd_shape != nullptr); - for (const char* dt : { "w8a8", "mxfp4a8", "" }) { + for (const char* dt : { "w8a8", "invalid", "" }) { A a; a.i("M", 2).i("N", 256).i("K", 512).i("n_expert", 8).i("top_k", 2).i("group", 128) .s("a_order", "token"); @@ -7038,6 +7703,30 @@ std::vector geometries() { G("attn_prefix_self", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2) .i("block_size", 4).i("causal", 1).s("q_dtype", "bf16") .s("kv_dtype", "bf16").i("n_head", 4).i("ctx", 5)), + G("mhc_pre", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).i("iterations", 20).d("eps", 1e-5) + .d("hc_eps", 1e-6).s("dtype", "f32")), + G("mhc_pre_partial", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).i("chunk", 8).i("first", 1) + .i("chunks", 2).s("dtype", "f32")), + G("mhc_pre_finish", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).i("iterations", 20) + .d("eps", 1e-5).d("hc_eps", 1e-6).i("chunk", 8) + .s("dtype", "f32")), + G("mhc_post", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).s("dtype", "f32")), + G("mhc_contract", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).s("dtype", "f32")), + G("kda_update", "M", 3, a.i("M", R).i("heads", 2).i("head_k", 8).i("head_v", 8) + .d("lower_bound", -5.0).d("scale", 0.35).d("l2_eps", 1e-6) + .s("mode", "prefill").s("dtype", "f32")), + G("mla_attn", "M", 3, a.i("M", R).i("latent_dim", 8).i("heads", 2).i("blocks", 2) + .i("block_size", 4).d("scale", 0.125).s("dtype", "f32")), + G("mla_project", "M", 3, a.i("M", R).i("heads", 2).i("head_dim", 4).i("latent_dim", 6) + .s("mode", "absorb").s("dtype", "bf16")), + G("dsa_score", "M", 4, a.i("M", R).i("n", 8).i("heads", 2).i("blocks", 3).i("seqs", 2) + .s("dtype", "fp8_e4m3")), + G("dsa_pool", "M", 3, a.i("M", R).i("n", 8).i("ratio", 4).s("dtype", "bf16")), + G("dsa_query", "M", 3, a.i("M", R).i("n", 8).s("dtype", "bf16")), + G("gemm_nt_f32", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "bf16")), + G("swiglu_clamped", "M", 3, a.i("M", R).i("n", 8).d("limit", 0.5).s("dtype", "f32")), + G("router_sigmoid_topk", "M", 3, a.i("M", R).i("n_expert", 6).i("top_k", 2).i("norm", 1) + .d("route_scale", 2.5).s("dtype", "f32")), G("conv1d", "M", 8, a.i("M", R).i("cin", 2).i("cout", 3).i("k", 3).i("dil", 1) .s("dtype", "f32")), G("conv_t1d", "M", 8, a.i("M", R).i("cin", 2).i("cout", 3).i("stride", 2).s("dtype", "f32")), From 78c58841bf8228733436e78d1261d733afda891c Mon Sep 17 00:00:00 2001 From: Nunze Date: Mon, 19 Oct 2026 17:08:48 +0200 Subject: [PATCH 060/152] libr4d: GLM-5.3's kernels -- mHC, KDA, the DSA indexer, MLA, f32-scaled FP8, MXFP4 experts The device rows for GLM-5.3-Flash's ops, at its geometry and at TP4 and TP8 slices: - mhc_pre / mhc_post / mhc_contract, and mhc_pre_partial / mhc_pre_finish, which run mhc_pre's own projection and finishing kernels with its chunk-sum order, so the pair is byte-identical to mhc_pre at n 4096, hc 4, chunk 2048. - kda_update_k128_v128_bf16, one, two or four value rows a wave, both state forms. - dsa_pool_fp8, dsa_query_fp8 and dsa_score_fp8 (fp8 WMMA, 32 heads of 128). - mla_attn: a matrix row whose WMMA tile holds a query's heads, or pairs eight heads of two neighbouring queries over the union of their page tables, above the wave row; mla_project with up to eight rows a thread or wave. - gemm_nt_f32 and router_sigmoid_topk in tiled and one-wave-a-row forms; gemm_fp8a8_f32scale and moe_gemm_fp8a8_f32scale read f32 block scales in place; moe_gemm_mxfp4a8 decodes e2m1 into exact E4M3 bytes for fp8 WMMA, with an expert-major decode form and a wide prefill form. - swiglu_clamped, and the device-only fusions of GLM's MoE block: swiglu_clamped_quant_fp8, router_sigmoid_topk_scatter, and moe_scatter_inv / moe_gather_inv, which pass the gather's slot table from the sort instead of rebuilding it. moe_gather takes f32 routing weights in its column-per-thread kernel. The sort and the gather kernels move from r4d_moe.hip into r4d_moe_sort.h and r4d_moe_gather.h, so the fused router and gather instantiate the same code. Every form that replaces another gives its bytes: tests/r4d_emu runs the kernels on the host (test_f32, test_fp8f32, test_kda, test_mhc, test_mla, test_moefuse, test_moemx), r4d_selftest compares them on a card against libref and against each other, and plugin_test pins the mla_attn band. docs/OPS.md states what libr4d serves. Co-Authored-By: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> --- docs/OPS.md | 123 + libr4d/CMakeLists.txt | 7 + libr4d/r4d.h | 4 + libr4d/r4d_dsa.hip | 298 ++ libr4d/r4d_fp8_f32scale.hip | 642 +++++ libr4d/r4d_fuse.cpp | 88 +- libr4d/r4d_glm.hip | 471 +++ libr4d/r4d_kda.hip | 491 ++++ libr4d/r4d_layout.cpp | 17 + libr4d/r4d_mhc.hip | 731 +++++ libr4d/r4d_mla.hip | 700 +++++ libr4d/r4d_moe.hip | 344 +-- libr4d/r4d_moe_gather.h | 92 + libr4d/r4d_moe_mxfp4.hip | 1156 ++++++++ libr4d/r4d_moe_sort.h | 198 ++ libr4d/r4d_mxfp4.h | 9 + libr4d/r4d_plugin.h | 47 + libr4d/r4d_rows.cpp | 381 +++ libr4d/r4d_selftest.cpp | 4160 ++++++++++++++++++++++++++- libr4d/r4d_shapes.cpp | 191 ++ tests/CMakeLists.txt | 33 +- tests/plugin_test.cpp | 19 + tests/r4d_emu/emu/emu.cpp | 39 +- tests/r4d_emu/emu/hip/hip_runtime.h | 88 + tests/r4d_emu/test_f32.cpp | 260 ++ tests/r4d_emu/test_fp8f32.cpp | 110 + tests/r4d_emu/test_kda.cpp | 187 ++ tests/r4d_emu/test_mhc.cpp | 283 ++ tests/r4d_emu/test_mla.cpp | 408 +++ tests/r4d_emu/test_moefuse.cpp | 614 ++++ tests/r4d_emu/test_moemx.cpp | 482 ++++ 31 files changed, 12371 insertions(+), 302 deletions(-) create mode 100644 libr4d/r4d_dsa.hip create mode 100644 libr4d/r4d_fp8_f32scale.hip create mode 100644 libr4d/r4d_glm.hip create mode 100644 libr4d/r4d_kda.hip create mode 100644 libr4d/r4d_mhc.hip create mode 100644 libr4d/r4d_mla.hip create mode 100644 libr4d/r4d_moe_gather.h create mode 100644 libr4d/r4d_moe_mxfp4.hip create mode 100644 libr4d/r4d_moe_sort.h create mode 100644 tests/r4d_emu/test_f32.cpp create mode 100644 tests/r4d_emu/test_fp8f32.cpp create mode 100644 tests/r4d_emu/test_kda.cpp create mode 100644 tests/r4d_emu/test_mhc.cpp create mode 100644 tests/r4d_emu/test_mla.cpp create mode 100644 tests/r4d_emu/test_moefuse.cpp create mode 100644 tests/r4d_emu/test_moemx.cpp diff --git a/docs/OPS.md b/docs/OPS.md index 650a27c9..2fe30b51 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -251,6 +251,9 @@ with the gate in the first half. is positive and finite (GLM-5.3's is 10). The clip precedes the SiLU, and the gate has no lower clip. +libr4d's `swiglu_clamped_bf16` serves bf16 in and out at any width, pitched rows, `M` up to +65535. + **`add` and `mul`** broadcast a `b` of exactly `n` elements along the rows of a taller output (a bias add). Nothing else broadcasts, in these or any other elementwise op. `add`'s `div` divides the sum after its rounding, `y = rd(rd(a + b) / div)` with `rd` `y`'s dtype (absent, 1: the plain @@ -359,6 +362,19 @@ the sum of its chunks' partials, then `mhc_pre`'s gates, Sinkhorn mixing and col of that sum is the implementation's, so the pair matches `mhc_pre` to rounding, and bit for bit only where an implementation says so. +libr4d serves `mhc_pre`, `mhc_post` and `mhc_contract` at `hc` 2 to 8, `n` up to 16384 and +`M` up to 65535 (`iterations` 1 to 256), bf16 activations with f32 `fn`, `scale`, `base`, +`post` and `comb`. At GLM's geometry (`n` 4096, `hc` 4) `mhc_pre` runs as eight 2048-column chunk +partials held in `x`'s rows, then a finishing kernel; other geometries project and finish in one +workgroup per row. `mhc_pre_partial` and `mhc_pre_finish` serve that geometry only (`n` 4096, +`hc` 4, `chunk` 2048, a 28-float chunk stride) and run `mhc_pre`'s own projection and finishing +kernels with its chunk-sum order, so the pair is byte-identical to `mhc_pre` (`r4d_selftest`, +`tests/r4d_emu/test_mhc.cpp`). The projection takes a four-slot form from two rows, one row a wave +and two from 32, where the weight rows are 16-byte and the residual rows 8-byte aligned; the +finish forms the 4x4 mixing on one wave and collapses the row over the workgroup; `mhc_post` at +`hc` 4 writes eight columns of every stream a thread on 16-byte rows. Every form gives the bytes +of the scalar kernels it replaces. + ### Gemma 4's audio tower - **`relu`** is `max(x, 0)` at each operand's own row pitch. @@ -494,6 +510,16 @@ f32, read as the checkpoint stores them. A scale that bf16 cannot represent exac value, which `fp8a8`'s bf16 scale plane would round. It applies to `gemm_nt_q` and `moe_gemm_q` with `group` 128. +libr4d reads both canonical planes in place, with no relayout: `gemm_fp8a8_f32scale` for +`gemm_nt_q` and `moe_gemm_fp8a8_f32scale` for `moe_gemm_q`, `N` and `K` multiples of 128, E4M3 +WMMA with the f32 scale product folded per 128 of K, bf16 out. The dense row picks a decode form +(row tiles sharing each weight fragment, several waves on consecutive K blocks) or a row-tile +form by `M`, `N` and `K`; on rows that are not 16-byte aligned it takes the 16x64 tile. The forms +are byte-identical (`tests/r4d_emu/test_fp8f32.cpp`). The grouped row takes equal-width parity +tables (`N_odd = N`, `K_odd = K`), token or sorted activations, and stacked planes or pointer +tables, and runs expert-major: a block per (column span, expert) takes every row of its expert, +each element keeping the row-tile form's sequence. + **`group` has different meanings in this table.** A kernel that reads it the other way is wrong, not slow. `libref/ref_quant.cpp` is the definition. @@ -545,6 +571,7 @@ and is optional. | `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` | | `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | +| `swiglu_clamped_quant_fp8` | `M`(range) `n` `limit`:f64 `group` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | `quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows, @@ -559,6 +586,12 @@ it does not produce that op's `y`. `act` is required here, unlike on the quantis implementation may compile one gate only, and an optional parameter would let it resolve for another. +`swiglu_clamped_quant_fp8` (device-only) is `swiglu_clamped` then `quant_act_fp8` over its +product in one pass. The product is rounded to bf16 before the quantiser reads it, as the pair +reads it from its bf16 tensor, so the codes, scales and `out_bf16` are the pair's bytes, NaN and +infinite inputs included (`r4d_selftest`). `n` is a multiple of 4, `group` 128, `M` up to 65535, +rows pitched. + `out_bf16` is part of the function, not an optimisation: the unfused pair leaves a bf16 tensor behind and takes the codes over it, so a layer with a bf16 consumer of the post-norm value must ask for it. `residual` present is the `fused_add_rms_norm` form. @@ -687,6 +720,12 @@ accumulation and an f32 `y`; `dtype` (`bf16`) names the activation. It exists fo whose weights and results must not narrow to bf16: GLM's router logits and its indexer's signed head gates. +libr4d's `gemm_nt_f32_bf16` takes `N` up to 512, `K` up to 16384, `M` up to 65535 and pitched +rows. A wave computes a tile of rows by columns, chosen by `M` and `N` (a single column per wave +at one row, eight rows by four columns from 64 rows, four rows by one column at `N <= 8`); each +output keeps one order (lane `l` sums `k = l, l+32, ...` with fused multiply-add, then a fixed +butterfly), so every tile is byte-identical (`tests/r4d_emu/test_f32.cpp`). + ### Runtime LoRA: `lora_shrink` and `lora_expand` | op | params | operands | @@ -1408,6 +1447,9 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t | `router_gemm_topk_scatter` | `M`(range) `K` `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `a`, `b`w, `gate_b`w? → `logits`, `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`? | | `moe_gemm` | `M`(range) `N` `K` `n_expert` `top_k` `a_order` `dtype` | `a`, `w`wt, `sorted_tok`, `expert_offset` → `y` | | `router_sigmoid_topk` | `M`(range) `n_expert` `top_k` `norm` `route_scale`:f64 `dtype` | `logits`, `bias`w → `ids`, `weights` | +| `router_sigmoid_topk_scatter` | `M`(range) `n_expert` `n_local`/opt `top_k` `norm` `route_scale`:f64 `dtype` `expert_base`/opt `protect`:str/opt | `logits`, `bias`w → `ids`, `weights`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`?, `inverse`? | +| `moe_scatter_inv` | `M`(range) `n_expert` `top_k` `expert_base`/opt `protect`:str/opt | `expert_ids` → `sorted_tok`, `expert_offset`, `expert_count`, `inverse` | +| `moe_gather_inv` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `inverse`, `shared`?, `shared_gate`? → `y` | | `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` | | `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? | | `row_topk_merge` | `M` `R` `world_size` `dtype` | `gathered` → `idx`, `val` | @@ -1502,6 +1544,11 @@ block's all-reduce. With bf16 expert outputs, `expert_w` may be bf16 or f32. f32 mixture weights stay f32 through the sum; only the gathered result narrows to bf16, as with bf16 weights. +libr4d's `moe_gather_bf16` takes f32 weights in its column-per-thread kernel, with the self-scan +up to 512 slots (and `top_k` up to 64) and the two prepass launches above. The wave-per-token +form past 512 slots reads bf16 weights only, so f32 weights stay on the column-per-thread kernel +at every size. + ### Quantised experts and the row gate | op | params | operands | @@ -1532,11 +1579,51 @@ with fewer than `top_k` selectable experts has no defined selection (libref refu Grouped selection (`n_group > 1`) is not this op. GLM-5.3 routes 8 of 288 experts in one group with `route_scale` 2.5. +libr4d's `router_sigmoid_topk_f32` takes up to 512 experts and `top_k` up to 32, f32 logits, bias +and weights, i32 ids, pitched rows, `M` up to 65535. It selects in one wave per row: each lane +holds its experts as order-preserving keys (`-0` as `+0`, ties to the lower expert), and round `j` +takes the largest key below round `j-1`'s winner. A row without NaN ranks gives the bytes of the +serial scan. A NaN rank is never selected, and a row with fewer than `top_k` other ranks names +expert 0 in its empty slots, weighted by expert 0's `p`. + +**`router_sigmoid_topk_scatter`** (device-only) is `router_sigmoid_topk` and `moe_scatter` over its +`ids` in one launch, and with `gate` `[M, 1]` also the `fill` of an ungated shared arm's gate with +1 (GLM-5.3's shared expert has no gate, and the gather reads one). `n_expert`, `n_local`, +`expert_base` and `protect` are as in `router_topk_scatter`. Every output is the bytes the +separate launches write, including a row with fewer than `top_k` non-NaN ranks (NaN logits), +whose empty slots carry expert 0 into the sort as `ids` does (`r4d_selftest`). Bounded like +`router_topk_scatter` (`M * top_k <= 1024`, one workgroup) and refused past it. With `inverse` the +sort is `moe_scatter_inv`'s. + +**`moe_scatter_inv`** and **`moe_gather_inv`** (device-only) are `moe_scatter` and `moe_gather` +with the gather's slot table passed between them. `inverse` `[M * top_k]` holds, for slot +`token * top_k + slot`, its row in `sorted_tok`, or -1 when the slot was dropped; `moe_gather` +builds exactly that table from `sorted_tok` before it sums (a scan of the sort per token up to 512 +slots, two prepass launches above), and `moe_gather_inv` reads it instead. They are ops of their +own because `moe_scatter`'s and `moe_gather`'s operand lists are the shared vocabulary's. +`moe_scatter_inv` is the same sort (one launch up to 1024 slots, three above, `n_expert` up to +512), and `moe_gather_inv` runs the kernel `moe_gather` picks at the same size, bf16 or f32 +weights; both are byte-identical to the pair they replace, at GLM's shape with f32 routing weights +and the shared arm folded in (`r4d_selftest`). + At `dtype=mxfp4a8`, `w` and `w_odd` are OCP e2m1 codes and `w_scale` and `w_odd_scale` hold one E8M0 exponent per (row, 32 of K), typed `e8m0` or raw `u8`; either way a byte is an exponent, not an integer multiplier. `a` and `a_scale` are `quant_act_fp8`'s pair, and `group` is that activation's scale group, independent of the weight's 32-wide grid. +libr4d's `moe_gemm_mxfp4a8` keeps the canonical bytes, including pointer tables of device or +device-mapped host addresses: a wave decodes the packed e2m1 words into exact E4M3 bytes and runs +fp8 WMMA, folding each 32-wide E8M0 exponent into the f32 accumulator. Per 128 of K, each 32-wide +group is a fresh WMMA pair, folded as raw * activation scale * E8M0 scale. It serves `group` 128, +`K` a multiple of 128, 2 to 512 experts, `top_k` up to 32, token or sorted activations, `parts`, +and an odd class narrower in `N` or `K`, with `M` up to 32767; there is no `moe_gemm_q_mod4` row +at this dtype. The form follows the routed rows. The expert-major form, a block per (column block, +expert) that reads each expert slice once, takes up to 511 rows, and at GLM's TP8 slices (288 +experts, top 8) gate_up up to 768 and down up to 6143. At those slices the wide prefill form (P64: +jobs of 32 or 64 rows of one expert) takes gate_up from 769 rows and down from 5760, ahead of the +expert-major band. Elsewhere the row-group forms serve. Every form gives the bytes of the +arithmetic-decode row-group form (`tests/r4d_emu/test_moemx.cpp`). + **`moe_gemm_q_mod4`** is the same GEMM over four classes by the expert's number mod 4. `w`/`w_scale` hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting to `N`, `K`); expert `e` is entry `e / 4` of class `e % 4`, so class `q` holds `ceil((n_expert - q) / 4)` of them. @@ -1642,6 +1729,14 @@ as the new count; the committed state does not advance past the accepted prefix, at most 32 tokens. `mode=prefill` commits its final state and sets the count to zero. A zeroed scratch slot replays nothing. +libr4d's `kda_update_k128_v128_bf16` takes `head_k = head_v = 128`, 1 to 65535 heads, bf16 +activations, f32 `A_log`, `dt_bias` and state, both modes and both state forms. A wave holds one, +two or four value rows of a head (four by default, the next token's operands loaded while the +current one reduces) and runs the sequence's tokens in order; every form gives the bytes of the +one-row kernel (`tests/r4d_emu/test_kda.cpp`). Under `anchor`, `verify` replays the accepted prefix +in a separate dispatch before the window, so no value row overwrites factors another is still +reading. A sequence whose window or slots are out of bounds is skipped on the device, not refused. + **Speculative rollback is part of the schema** (`spec.md` §10). The recurrent state and the conv window have already absorbed rejected tokens, so the state cache is a rolling window of `conv_width-1 + n_spec` entries read at the slot the last accepted token left, and a rejection is a @@ -2354,12 +2449,17 @@ contiguous inner rows and a four-byte-aligned page pitch of at least 136 bytes: untouched. That is one block-size-4 group of the indexer's KV, with no separate scale allocation. `block_size`, when given, is 4 and names the consuming layout to the cache planner. +libr4d's `dsa_pool_fp8` serves `n` 128 and `ratio` 4, the cache form included: one wave per pooled +row, the softmax channels and the Hadamard in registers, pitched rows. + `dsa_query` rotates each bf16 query head by the same normalized Walsh-Hadamard transform, rounds to bf16, and quantises to E4M3 with the same power-of-two scale: `x` `[M, n]`, `q` `[M, n]`, `scale` `[M, 1]`, token and head flattened into `M`. There is no RoPE and no RMS norm. Unlike `had_quant_act_fp8`, both the normalization of the rotation and the power-of-two scale are part of the op. `n` is a power of two up to 256. +libr4d's `dsa_query_fp8` serves `n` 128, one wave per query head, pitched rows. + `dsa_score` takes E4M3 queries `[M, heads, n]` with f32 scales and signed f32 gates `[M, heads]`, E4M3 pooled keys `[pages, n]` with f32 scales `[pages]`. `bt[seqs, blocks]` names key pages, `cu[seqs+1]` holds absolute query offsets and `nc[seqs]` bounds the live blocks. The score of block @@ -2374,6 +2474,11 @@ history makes no future block eligible. embedded scale are read in place. `q` may be flattened `[M*heads, n]` with `q_scale` `[M*heads, 1]`, each with its own row pitch, which is `dsa_query`'s output as written. +libr4d's `dsa_score_fp8` serves `n` 128 and 32 heads, `M` up to 65535, both key forms and both +query forms. A block of two waves covers the 32 heads of one query row against one or two 16-key +tiles (two past 32 blocks); the dot products run on fp8 WMMA, and scales and gates fold only after +each head's ReLU. + `mla_attn` is absorbed latent attention: one latent vector per token is both key and value. `q` and `out` are `[M, heads, latent_dim]`, `kv` is `[pages, 1, block_size, latent_dim]`, and `bt[M, blocks]` is each query's own page table, the selected complete pages followed by its tail. @@ -2383,6 +2488,19 @@ contributes nothing, and a row with no visible key outputs zero. The softmax is rounded once. `scale` is positive and finite and comes from the original query/key head width, not the latent width (GLM: `1/sqrt(256)` against a latent of 512). +libr4d has two `mla_attn` rows, both at `latent_dim` 512, `block_size` 4 and up to 64 heads. The +matrix row, `mla_attn_matrix_bf16`, ranks above the wave row and takes heads in multiples of 8: the +heads are the WMMA tile's rows, so all of them share each latent load, and the probabilities enter +it as bf16 high and low parts with f32 accumulation. At a multiple of 16 a tile holds 16 heads of +one query; otherwise it pairs eight heads of two neighbouring queries, loading a key once where +both tables name the page, so GLM-5.3's 8 heads a rank fill the tile. The pairing walks the union +of the two tables, so each chunk runs once, for tables of up to 520 entries; past that it pairs +by table position, with a second pass where the two differ. +`RADIANCE_MLA_MATRIX_MAX_M` lowers the matrix row's `M` bound (65535 by default); past it the +wave row, `mla_attn_bf16`, serves: a wave per head with an online softmax. Both split a short +batch's history across workgroups and merge the f32 partials before narrowing, into the fixed +scratch their hooks reserve; without scratch they compute unsplit. + `mla_project` moves a query into the latent and a latent result out of it, through the bf16 weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows. `mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored, @@ -2392,6 +2510,11 @@ accumulate in f32 and round once to bf16. The KV cache stays latent; only this w per-head width. Its rows are head-major, so a tensor-parallel slice of whole heads is a row range. `a` and `y` may also be `[M, heads*width]`, heads contiguous, with their own token pitch. +libr4d's `mla_project_bf16` serves `head_dim` 256 and `latent_dim` 512, up to 64 heads, pitched +tensors. It takes up to eight rows a thread (`absorb`) or a wave (`expand`), loading each weight +element once for them, with every row's sum in the one-row kernels' order, so all forms give the +same bytes. + ## Draft heads A drafter is an ordinary graph over ordinary ops except at its two ends: what proposes the diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index a8944e37..351dca26 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -103,6 +103,13 @@ set(R4D_UNITS # launches behind one entry point: the mix depends on every column of the low-rank waist, so it # needs a grid-wide barrier. "r4d_hc_bf16|" + "r4d_mhc|" + "r4d_glm|" + "r4d_dsa|" + "r4d_mla|" + "r4d_kda|" + "r4d_moe_mxfp4|" + "r4d_fp8_f32scale|" "r4d_ngram_ids|" "r4d_ple_gate_bf16|" "r4d_ple_conv_bf16|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 9308639e..141b1b85 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -643,6 +643,10 @@ void r4d_moe_gemm_pin_down_dec(int pin); // (refused likewise, and below 512 rows, whose scratch is not sized for their weight planes). // All bit-identical; r4d_selftest compares their bytes. void r4d_hc_read_pin_prefill(int form); +// Test hook: pins the MLA matrix row's key load. 0 is the launcher's rule (sixteen-byte vectors +// wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to. +// Bit-identical; r4d_selftest compares them and --perfmla times both. +void r4d_mla_matrix_pin_form(int form); // Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the // next call, and returns how many launches the previous recording saw (which may exceed its cap). // Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel diff --git a/libr4d/r4d_dsa.hip b/libr4d/r4d_dsa.hip new file mode 100644 index 00000000..839a2f8e --- /dev/null +++ b/libr4d/r4d_dsa.hip @@ -0,0 +1,298 @@ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_fwht.h" +#include "r4d_q8.h" +#include "r4d_fp8_wmma.h" +#include + +namespace { +__global__ void dsa_query_kernel(const uint16_t* x, uint8_t* q, float* scale, long xp, long qp, + long sp, int rows) { + const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5); + if (r >= rows) return; + float v[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) v[d] = bf16_to_f32(x[(long)r * xp + lane * 4 + d]); + r4d_fwht_wave<128>(v, lane); + float am = 1e-4f; +#pragma unroll + for (int d = 0; d < 4; ++d) { + v[d] = bf16_to_f32(f32_to_bf16(v[d] * 0.08838834764831845f)); + am = fmaxf(am, fabsf(v[d])); + } +#pragma unroll + for (int mask = 16; mask; mask >>= 1) am = fmaxf(am, __shfl_xor(am, mask, 32)); + const uint32_t bits = __float_as_uint(am * (1.0f / 448.0f)); + const float sc = __uint_as_float((bits & 0x7f800000u) + ((bits & 0x7fffffu) ? 0x800000u : 0)); + if (!lane) scale[(long)r * sp] = sc; + const uint32_t packed = q8_pack4(v[0], v[1], v[2], v[3], 1.0f / sc); + uint8_t* dst = q + (long)r * qp + lane * 4; + if (((uintptr_t)dst & 3) == 0) + *(uint32_t*)dst = packed; + else { +#pragma unroll + for (int d = 0; d < 4; ++d) dst[d] = (uint8_t)(packed >> (8 * d)); + } +} +int query_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const auto &x = a->t[0], &q = a->t[1], &s = a->t[2]; + if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE; + if (!x.data || !q.data || !s.data) return RAD_E_INVAL; + if (r4d_geti_or(a, "n", 0) != 128 || x.rank != 2 || q.rank != 2 || s.rank != 2 || + x.shape[0] < 1 || x.shape[0] > INT_MAX - 3 || x.shape[1] != 128 || + q.shape[0] != x.shape[0] || q.shape[1] != 128 || s.shape[0] != x.shape[0] || + s.shape[1] != 1 || x.stride[1] != 1 || q.stride[1] != 1 || s.stride[1] != 1 || + x.stride[0] < 128 || q.stride[0] < 128 || s.stride[0] < 1) + return RAD_E_SHAPE; + return R4D_EMIT(stream, dsa_query_kernel, dim3((x.shape[0] + 3) / 4), dim3(128), 0, + (const uint16_t*)x.data, (uint8_t*)q.data, (float*)s.data, x.stride[0], + q.stride[0], s.stride[0], (int)x.shape[0]); +} +struct ScoreMeta { + long qr, qh, qsr, qsc, gr, gc, kr, ksr, btr, btc, cur, ncr, op; + int rows, blocks, seqs, pages; +}; +__device__ uint32_t bytes4(const uint8_t* p) { + if (!((uintptr_t)p & 3)) return *(const uint32_t*)p; + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} +/* Two waves cover all 32 heads and reuse the query across `kScoreTiles` 16-key tiles, one up to 32 + * blocks and two past them. FP8 dot products stay on WMMA; scales and the signed per-head gates + * fold only after the per-head ReLU. */ +template +__global__ void dsa_score_kernel(const uint8_t* q, const float* qs, const float* gate, + const uint8_t* k, const float* ks, const int* bt, const int* cu, + const int* nc, float* out, ScoreMeta m) { + constexpr int kScoreKeys = 16 * kScoreTiles; + __shared__ __align__(16) uint8_t qa[32 * 136], kb[kScoreKeys * 136]; + __shared__ int seq, pages[kScoreKeys]; + __shared__ float scales[kScoreKeys], coefficients[32], partial[2][kScoreKeys]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int r = blockIdx.y, b0 = blockIdx.x * kScoreKeys; + if (!tid) { + seq = -1; + for (int s = 0; s < m.seqs; ++s) + if (r >= cu[(long)s * m.cur] && r < cu[(long)(s + 1) * m.cur]) { + seq = s; + break; + } + } + __syncthreads(); + const int live = seq >= 0 ? min(nc[(long)seq * m.ncr], m.blocks) : 0; + if (b0 >= live) { + for (int i = tid; i < kScoreKeys; i += 64) + if (b0 + i < m.blocks) out[(long)r * m.op + b0 + i] = -INFINITY; + return; + } + for (int i = tid; i < kScoreKeys; i += 64) { + const int b = b0 + i; + int p = seq >= 0 && b < m.blocks && b < nc[(long)seq * m.ncr] + ? bt[(long)seq * m.btr + b * m.btc] + : -1; + if (p >= m.pages) p = -1; + pages[i] = p; + scales[i] = p >= 0 ? ks[(long)p * m.ksr] : 0; + } + if (tid < 32) + coefficients[tid] = qs[(long)r * m.qsr + tid * m.qsc] * gate[(long)r * m.gr + tid * m.gc]; + for (int j = tid; j < 32 * 32; j += 64) { + const int h = j / 32, d = (j % 32) * 4; + *(uint32_t*)(qa + h * 136 + d) = bytes4(q + (long)r * m.qr + (long)h * m.qh + d); + } + __syncthreads(); + for (int j = tid; j < kScoreKeys * 32; j += 64) { + const int b = j / 32, d = (j % 32) * 4, p = pages[b]; + *(uint32_t*)(kb + b * 136 + d) = p >= 0 ? bytes4(k + (long)p * m.kr + d) : 0; + } + __syncthreads(); + r4d_fp8::f8v acc[kScoreTiles]; +#pragma unroll + for (int tile = 0; tile < kScoreTiles; ++tile) acc[tile] = r4d_fp8::acc_zero(); +#pragma unroll + for (int d = 0; d < 128; d += 16) { + const auto a = r4d_fp8::frag<128>(qa, wave * 16, d, lane); +#pragma unroll + for (int tile = 0; tile < kScoreTiles; ++tile) + acc[tile] = r4d_fp8::mma(a, r4d_fp8::frag<128>(kb, tile * 16, d, lane), acc[tile]); + } +#pragma unroll + for (int tile = 0; tile < kScoreTiles; ++tile) { + float value = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) + value += fmaxf(acc[tile][j], 0.0f) * coefficients[wave * 16 + (lane >> 4) * 8 + j]; + value += __shfl_xor(value, 16, 32); + if (lane < 16) partial[wave][tile * 16 + lane] = value; + } + __syncthreads(); + for (int i = tid; i < kScoreKeys; i += 64) + if (b0 + i < m.blocks) + out[(long)r * m.op + b0 + i] = + pages[i] >= 0 ? (partial[0][i] + partial[1][i]) * scales[i] * 0.015625f : -INFINITY; +} +int score_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 9) return RAD_E_INVAL; + RadTensor q = a->t[0], qs = a->t[1]; + const auto& g = a->t[2]; + RadTensor k = a->t[3], ks = a->t[4]; + const bool packed = k.dtype == RAD_U8; + if (packed) { + if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 || + k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 || + ((uintptr_t)k.data & 3)) + return RAD_E_SHAPE; + ks = {}; + ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr; + ks.dtype = RAD_F32; + ks.rank = 1; + ks.shape[0] = k.shape[0]; + ks.stride[0] = k.stride[0] / 4; + k.dtype = RAD_F8E4M3; + k.rank = 2; + k.shape[1] = 128; + k.stride[1] = 1; + } + const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &o = a->t[8]; + if (q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && q.shape[0] == o.shape[0] * 32 && + qs.shape[0] == q.shape[0]) { + q.rank = 3; + q.shape[0] = o.shape[0]; + q.shape[2] = q.shape[1]; + q.shape[1] = 32; + q.stride[2] = q.stride[1]; + q.stride[1] = q.stride[0]; + q.stride[0] *= 32; + qs.shape[0] = o.shape[0]; + qs.shape[1] = 32; + qs.stride[1] = qs.stride[0]; + qs.stride[0] *= 32; + } + if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 || + g.dtype != RAD_F32 || ks.dtype != RAD_F32 || o.dtype != RAD_F32 || bt.dtype != RAD_I32 || + cu.dtype != RAD_I32 || nc.dtype != RAD_I32) + return RAD_E_DTYPE; + for (int i = 0; i < 9; ++i) + if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL; + if (r4d_geti_or(a, "n", 0) != 128 || r4d_geti_or(a, "heads", 0) != 32 || q.rank != 3 || + q.shape[0] < 1 || q.shape[0] > 65535 || q.shape[1] != 32 || q.shape[2] != 128 || + q.stride[2] != 1 || q.stride[1] < 128 || q.stride[0] < 32 * q.stride[1] || qs.rank != 2 || + g.rank != 2 || qs.shape[0] != q.shape[0] || g.shape[0] != q.shape[0] || qs.shape[1] != 32 || + g.shape[1] != 32 || qs.stride[1] < 1 || g.stride[1] < 1 || + qs.stride[0] < 32 * qs.stride[1] || g.stride[0] < 32 * g.stride[1] || k.rank != 2 || + k.shape[0] < 1 || k.shape[0] > INT_MAX || k.shape[1] != 128 || k.stride[1] != 1 || + k.stride[0] < 128 || ks.rank != 1 || ks.shape[0] != k.shape[0] || ks.stride[0] < 1 || + bt.rank != 2 || bt.shape[0] < 1 || bt.shape[0] > INT_MAX || bt.stride[1] < 1 || + cu.rank != 1 || cu.shape[0] != bt.shape[0] + 1 || nc.rank != 1 || + nc.shape[0] != bt.shape[0] || cu.stride[0] < 1 || nc.stride[0] < 1 || o.rank != 2 || + o.shape[0] != q.shape[0] || o.shape[1] < 1 || o.shape[1] > INT_MAX - 15 || + o.shape[1] > bt.shape[1] || o.stride[1] != 1 || o.stride[0] < o.shape[1] || + bt.stride[0] < bt.shape[1] * bt.stride[1]) + return RAD_E_SHAPE; + ScoreMeta m{ q.stride[0], q.stride[1], qs.stride[0], qs.stride[1], g.stride[0], + g.stride[1], k.stride[0], ks.stride[0], bt.stride[0], bt.stride[1], + cu.stride[0], nc.stride[0], o.stride[0], (int)q.shape[0], (int)o.shape[1], + (int)bt.shape[0], (int)k.shape[0] }; +#define SCORE(NT) \ + R4D_EMIT(stream, (dsa_score_kernel), dim3((m.blocks + 16 * NT - 1) / (16 * NT), m.rows), \ + dim3(64), 0, (const uint8_t*)q.data, (const float*)qs.data, (const float*)g.data, \ + (const uint8_t*)k.data, (const float*)ks.data, (const int*)bt.data, \ + (const int*)cu.data, (const int*)nc.data, (float*)o.data, m) + if (m.blocks <= 32) return SCORE(1); + return SCORE(2); +#undef SCORE +} +/* One wave per pool: all softmax channels and the full Hadamard stay in registers. */ +__global__ void dsa_pool_kernel(const uint16_t* kg, const float* ape, uint8_t* q, float* scale, + const int* page, uint8_t* cache, long kp, long ap, long qp, long sp, + long pp, long cp, int rows, int pages) { + const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5); + if (r >= rows) return; + float v[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int col = lane * 4 + d; + float g[4], mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + g[j] = bf16_to_f32(kg[((long)r * 4 + j) * kp + 128 + col]) + ape[(long)j * ap + col]; + mx = fmaxf(mx, g[j]); + } + float num = 0, den = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float p = expf(g[j] - mx); + num += p * bf16_to_f32(kg[((long)r * 4 + j) * kp + col]); + den += p; + } + v[d] = bf16_to_f32(f32_to_bf16(num / den)); + } + r4d_fwht_wave<128>(v, lane); + float am = 1e-4f; +#pragma unroll + for (int d = 0; d < 4; ++d) { + v[d] = bf16_to_f32(f32_to_bf16(v[d] * 0.08838834764831845f)); + am = fmaxf(am, fabsf(v[d])); + } +#pragma unroll + for (int mask = 16; mask; mask >>= 1) am = fmaxf(am, __shfl_xor(am, mask, 32)); + const uint32_t bits = __float_as_uint(am * (1.0f / 448.0f)); + const float sc = __uint_as_float((bits & 0x7f800000u) + ((bits & 0x7fffffu) ? 0x800000u : 0)); + if (!lane) scale[(long)r * sp] = sc; + const uint32_t packed = q8_pack4(v[0], v[1], v[2], v[3], 1.0f / sc); + uint8_t* dst = q + (long)r * qp + lane * 4; + if (((uintptr_t)dst & 3) == 0) + *(uint32_t*)dst = packed; + else { +#pragma unroll + for (int d = 0; d < 4; ++d) dst[d] = (uint8_t)(packed >> (8 * d)); + } + if (cache) { + const int p = page[(long)r * pp]; + if (p >= 0 && p < pages) { + uint8_t* out = cache + (long)p * cp; + *(uint32_t*)(out + lane * 4) = packed; + if (!lane) *(float*)(out + 128) = sc; + } + } +} +int pool_body(const RadArgs* a, RadStream stream) { + if (r4d_geti_or(a, "block_size", 4) != 4) return RAD_E_SHAPE; + if (!a || a->n_t < 4) return RAD_E_INVAL; + const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3]; + const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5); + if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL; + if (cache && + (page->dtype != RAD_I32 || page->rank != 1 || page->shape[0] != q.shape[0] || + page->stride[0] < 1 || cache->dtype != RAD_U8 || cache->rank != 4 || cache->shape[0] < 1 || + cache->shape[0] > INT_MAX || cache->shape[1] != 1 || cache->shape[2] != 4 || + cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 || + cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3))) + return RAD_E_SHAPE; + if (kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) + return RAD_E_DTYPE; + if (r4d_geti_or(a, "n", 0) != 128 || r4d_geti_or(a, "ratio", 0) != 4 || kg.rank != 2 || + ape.rank != 2 || q.rank != 2 || s.rank != 2 || !kg.data || !ape.data || !q.data || + !s.data || q.shape[0] < 1 || q.shape[0] > INT_MAX / 4 || kg.shape[0] != q.shape[0] * 4 || + kg.shape[1] != 256 || ape.shape[0] != 4 || ape.shape[1] != 128 || q.shape[1] != 128 || + s.shape[0] != q.shape[0] || s.shape[1] != 1 || kg.stride[1] != 1 || ape.stride[1] != 1 || + q.stride[1] != 1 || s.stride[1] != 1 || kg.stride[0] < 256 || ape.stride[0] < 128 || + q.stride[0] < 128 || s.stride[0] < 1) + return RAD_E_SHAPE; + return R4D_EMIT( + stream, dsa_pool_kernel, dim3((q.shape[0] + 3) / 4), dim3(128), 0, (const uint16_t*)kg.data, + (const float*)ape.data, (uint8_t*)q.data, (float*)s.data, + page ? (const int*)page->data : nullptr, cache ? (uint8_t*)cache->data : nullptr, + kg.stride[0], ape.stride[0], q.stride[0], s.stride[0], page ? page->stride[0] : 0, + cache ? cache->stride[0] : 0, (int)q.shape[0], cache ? (int)cache->shape[0] : 0); +} +} +extern "C" int r4d_rad_dsa_pool(const RadArgs* a, RadStream stream) { return pool_body(a, stream); } +extern "C" int r4d_rad_dsa_query(const RadArgs* a, RadStream stream) { + return query_body(a, stream); +} +extern "C" int r4d_rad_dsa_score(const RadArgs* a, RadStream stream) { + return score_body(a, stream); +} diff --git a/libr4d/r4d_fp8_f32scale.hip b/libr4d/r4d_fp8_f32scale.hip new file mode 100644 index 00000000..fe947940 --- /dev/null +++ b/libr4d/r4d_fp8_f32scale.hip @@ -0,0 +1,642 @@ +/* Canonical E4M3 weights with exact F32 block scales: native FP8 WMMA and F32 scale folding, no + * checkpoint scale narrowing. The grouped form and the legacy dense form compute one 16x64 output + * tile a block; the dense decode and prefill forms below them produce the same bytes faster. */ +#include +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_common.h" +#include "r4d_fp8_wmma.h" +#include "r4d_launch.h" +#include +#include +#include +#include +#include + +namespace { +struct Meta { + long ar, asr, yr, wr, sr, wstep[2], sstep[2]; + int T, N, K, experts, topk, sorted_a, tile; +}; +__device__ const uint8_t* entry(const void* p, long step, int e) { + return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e]; +} +template +__global__ void fp8_f32scale(const uint8_t* a, const float* as, const void* w0, const void* s0, + const void* w1, const void* s1, const int* sorted, const int* offsets, + uint16_t* y, Meta m) { + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, n0 = blockIdx.x * 64; + __shared__ uint8_t qa[16 * 136], wb[64 * 136]; + __shared__ int source[16]; + int first = (int)blockIdx.y * (Grouped ? m.tile : 16); + const int limit = min(first + (Grouped ? m.tile : 16), m.T); + while (first < limit) { + int expert = 0, end = limit; + if constexpr (Grouped) { + // Tile sorted rows rather than launching every expert, most of which are empty + // during native MTP decode. Split a tile at each expert boundary. + if (sorted[first] < 0 || offsets[m.experts] <= first) { + for (int c = tid; c < 64; c += 128) + if (n0 + c < m.N) y[(long)first * m.yr + n0 + c] = 0; + ++first; + continue; + } + int lo = 0, hi = m.experts; + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offsets[mid] <= first) + lo = mid; + else + hi = mid; + } + expert = lo; + end = min(limit, offsets[expert + 1]); + if (end <= first) return; + } + const int parity = Grouped ? expert & 1 : 0, e = Grouped ? expert / 2 : 0; + const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e); + const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e); + if (tid < 16) { + const int r = first + tid; + const int flat = Grouped && r < end ? sorted[r] : r; + source[tid] = r < end && flat >= 0 ? (Grouped && !m.sorted_a ? flat / m.topk : r) : -1; + } + __syncthreads(); + auto acc = r4d_fp8::acc_zero(); + for (int k0 = 0; k0 < m.K; k0 += 128) { + for (int j = tid; j < 16 * 32; j += 128) { + const int r = j / 32, c = (j % 32) * 4, src = source[r]; + uint32_t v = 0; + if (src >= 0) { + const auto* p = a + (long)src * m.ar + k0 + c; + v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | + ((uint32_t)p[3] << 24); + } + *(uint32_t*)(qa + r * 136 + c) = v; + } + for (int j = tid; j < 64 * 32; j += 128) { + const int r = j / 32, c = (j % 32) * 4; + const auto* p = w + (long)(n0 + r) * m.wr + k0 + c; + *(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | + ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + } + __syncthreads(); + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = 0; k < 128; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane), + r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw); + const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int src = source[(lane >> 4) * 8 + j]; + const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0; + acc[j] += raw[j] * scale; + } + __syncthreads(); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15); + if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]); + } + __syncthreads(); + first = end; + } +} +/* The grouped form expert-major: a block per (column span, expert) takes every row of its + * expert in 16-row tiles, so an expert slice is read from memory once however its rows fall in + * the sorted order (the row tiles above re-read it once per tile its run spans). Each element + * keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as raw * + * (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K in + * stages of StageK, as one stage sequence with the next stage loaded into registers while the + * current one computes from LDS. Block row `experts` zeroes the dropped rows past + * offsets[experts]. */ +typedef unsigned f8_u4 __attribute__((ext_vector_type(4))); +template +struct F8Stage { + static constexpr int KB = StageK / 128; + f8_u4 a[StageK / 128], w[StageK / 32]; + float wsc[KB], sa; +}; +template +__global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, const float* as, + const void* w0, const void* s0, + const void* w1, const void* s1, + const int* sorted, const int* offsets, + uint16_t* y, Meta m) { + using St = F8Stage; + constexpr int KB = St::KB, P = StageK + 8; + __shared__ __align__(16) uint8_t qa[16 * P], wb[64 * P]; + __shared__ float sa[16 * KB]; + __shared__ int source[16]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, e = blockIdx.y, + colb = blockIdx.x * 64 * ColTiles; + if (e == m.experts) { + const int r0 = offsets[m.experts]; + for (long i = tid; i < (long)(m.T - r0) * 64 * ColTiles; i += 128) { + const int c = colb + (int)(i % (64 * ColTiles)); + if (c < m.N) y[(long)(r0 + i / (64 * ColTiles)) * m.yr + c] = 0; + } + return; + } + const int lo = offsets[e], hi = offsets[e + 1]; + if (lo >= hi) return; + const int parity = e & 1; + const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e / 2); + const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e / 2); + const int ksn = (m.K + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + 63) / 64), + S = tiles * ksn; + const int rowbase = (lane >> 4) * 8; + for (int r0 = lo; r0 < hi; r0 += 16) { + __syncthreads(); + if (tid < 16) { + const int r = r0 + tid, flat = r < hi ? sorted[r] : -1; + source[tid] = r < hi && flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1; + } + __syncthreads(); + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = source[rowbase + j] >= 0; + auto load = [&](int s, St& R) { + const int col0 = colb + (s / ksn) * 64, k0 = (s % ksn) * StageK; +#pragma unroll + for (int i = 0; i < StageK / 128; ++i) { + const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16, + src = source[r]; + R.a[i] = f8_u4{ 0, 0, 0, 0 }; + if (src >= 0 && k0 + c < m.K) + __builtin_memcpy(&R.a[i], a + (long)src * m.ar + k0 + c, 16); + } +#pragma unroll + for (int i = 0; i < StageK / 32; ++i) { + const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + R.w[i] = f8_u4{ 0, 0, 0, 0 }; + if (k0 + c < m.K) + __builtin_memcpy(&R.w[i], w + (long)(col0 + r) * m.wr + k0 + c, 16); + } +#pragma unroll + for (int kb = 0; kb < KB; ++kb) + R.wsc[kb] = + k0 + kb * 128 < m.K ? ws[(long)(col0 / 128) * m.sr + (k0 + kb * 128) / 128] : 0; + if (tid < 16 * KB) { + const int src = source[tid / KB], kb = k0 + (tid % KB) * 128; + R.sa = src >= 0 && kb < m.K ? as[(long)src * m.asr + kb / 128] : 0; + } + }; + auto store = [&](const St& R) { +#pragma unroll + for (int i = 0; i < StageK / 128; ++i) { + const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + *reinterpret_cast(qa + r * P + c) = R.a[i]; + } +#pragma unroll + for (int i = 0; i < StageK / 32; ++i) { + const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + *reinterpret_cast(wb + r * P + c) = R.w[i]; + } + if (tid < 16 * KB) sa[tid] = R.sa; + }; + auto acc = r4d_fp8::acc_zero(); + St R; + load(0, R); + for (int s = 0; s < S; ++s) { + store(R); + float wsc[KB]; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) wsc[kb] = R.wsc[kb]; + __syncthreads(); + if (s + 1 < S) load(s + 1, R); + const int k0 = (s % ksn) * StageK; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= m.K) break; + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = kb * 128; k < (kb + 1) * 128; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag(qa, 0, k, lane), + r4d_fp8::frag(wb, wave * 16, k, lane), raw); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float scale = rv[j] ? sa[(rowbase + j) * KB + kb] * wsc[kb] : 0; + acc[j] += raw[j] * scale; + } + } + if (s % ksn == ksn - 1) { + const int c = colb + (s / ksn) * 64 + wave * 16 + (lane & 15); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = r0 + rowbase + j; + if (r < hi) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]); + } + acc = r4d_fp8::acc_zero(); + } + __syncthreads(); + } + } +} +// Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same +// eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's +// row segment, which the old kernel copied through LDS unchanged), then acc += raw * (a_scale * +// w_scale) in ascending block order. A WMMA output depends only on its own A row, B column and +// C, so which rows and columns share a tile does not change it. + +// Decode: one wave C adjacent 16-column tiles, S waves of a block on S consecutive K blocks at +// once, the fragments loaded straight from global memory; R row tiles share each weight fragment +// and C column tiles each activation fragment. Each wave scales its own partial products (the +// a_scale x w_scale product and the multiply are the old fold's own two roundings) into LDS; then +// every wave folds a share of the outputs, adding the round's products in block order to the +// output's running sum, which lives in LDS between rounds. The block's activation scales are +// staged in LDS when they fit (`stage`). +template +__global__ void fp8_f32scale_decode(const uint8_t* a, const float* as, const uint8_t* w, + const float* ws, uint16_t* y, Meta m, int stage) { + constexpr int SL = R * C * 8; + R4D_DYN_LDS(float, lds); + const int lane = threadIdx.x & 31, s = threadIdx.x >> 5, S = blockDim.x >> 5, h = lane >> 4; + const int c0 = blockIdx.x * 16 * C, first = (int)blockIdx.y * R * 16, KB = m.K / 128; + float* part = lds; + float* sums = part + S * SL * 32; + float* scales = sums + SL * 32; + if (stage) + for (int i = threadIdx.x; i < R * 16 * KB; i += blockDim.x) { + const int r = first + i / KB; + scales[i] = r < m.T ? as[(long)r * m.asr + i % KB] : 0; + } + for (int i = threadIdx.x; i < SL * 32; i += blockDim.x) sums[i] = 0; + const uint8_t* arow[R]; + bool alive[R]; +#pragma unroll + for (int t = 0; t < R; ++t) { + const int r = first + t * 16 + (lane & 15); + alive[t] = r < m.T; + arow[t] = a + (long)(alive[t] ? r : 0) * m.ar + h * 8; + } + __syncthreads(); + for (int k0 = 0; k0 < KB; k0 += S) { + const int kb = k0 + s; + if (kb < KB) { + r4d_fp8::i2v b[C][8]; + float weight_scale[C]; +#pragma unroll + for (int c = 0; c < C; ++c) { + const uint8_t* wrow = + w + (long)(c0 + c * 16 + (lane & 15)) * m.wr + h * 8 + (long)kb * 128; +#pragma unroll + for (int q = 0; q < 8; ++q) { + const uint2 v = *(const uint2*)(wrow + q * 16); + b[c][q][0] = (int)v.x; + b[c][q][1] = (int)v.y; + } + weight_scale[c] = ws[(long)((c0 + c * 16) / 128) * m.sr + kb]; + } +#pragma unroll + for (int t = 0; t < R; ++t) { + r4d_fp8::i2v f[8]; +#pragma unroll + for (int q = 0; q < 8; ++q) { + uint2 v = make_uint2(0, 0); + if (alive[t]) v = *(const uint2*)(arow[t] + (long)kb * 128 + q * 16); + f[q][0] = (int)v.x; + f[q][1] = (int)v.y; + } + float act[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int rr = t * 16 + h * 8 + j, r = first + rr; + act[j] = + stage ? scales[rr * KB + kb] : (r < m.T ? as[(long)r * m.asr + kb] : 0); + } +#pragma unroll + for (int c = 0; c < C; ++c) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int q = 0; q < 8; ++q) raw = r4d_fp8::mma(f[q], b[c][q], raw); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + t * 16 + h * 8 + j; + const float scale = r < m.T ? act[j] * weight_scale[c] : 0; + part[((long)s * SL + (t * C + c) * 8 + j) * 32 + lane] = raw[j] * scale; + } + } + } + } + __syncthreads(); + for (int slot = s; slot < SL; slot += S) { + float acc = sums[slot * 32 + lane]; + for (int q = 0; q < S && k0 + q < KB; ++q) + acc += part[((long)q * SL + slot) * 32 + lane]; + sums[slot * 32 + lane] = acc; + } + __syncthreads(); + } + for (int slot = s; slot < SL; slot += S) { + const int t = slot / (C * 8), c = slot / 8 % C, j = slot % 8, + r = first + t * 16 + h * 8 + j; + if (r < m.T) + y[(long)r * m.yr + c0 + c * 16 + (lane & 15)] = f32_to_bf16(sums[slot * 32 + lane]); + } +} + +// Prefill: the old kernel's 64-column block and LDS layout over R row tiles, so a staged weight +// block serves R*16 rows instead of 16, staged with 16-byte loads and the next K block loaded +// into registers while the current one is multiplied. +template +__global__ void __launch_bounds__(128) + fp8_f32scale_rows(const uint8_t* a, const float* as, const uint8_t* w, const float* ws, + uint16_t* y, Meta m) { + constexpr int P = 136, AV = R * 16 * 8 / 128, WV = 64 * 8 / 128; + __shared__ uint8_t qa[R * 16 * P], wb[64 * P]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, h = lane >> 4, + n0 = blockIdx.x * 64; + const int first = (int)blockIdx.y * R * 16, KB = m.K / 128; + uint4 av[AV], wv[WV]; + auto load = [&](int kb) { +#pragma unroll + for (int i = 0; i < AV; ++i) { + const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16; + av[i] = first + r < m.T + ? *(const uint4*)(a + (long)(first + r) * m.ar + (long)kb * 128 + c) + : make_uint4(0, 0, 0, 0); + } +#pragma unroll + for (int i = 0; i < WV; ++i) { + const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16; + wv[i] = *(const uint4*)(w + (long)(n0 + r) * m.wr + (long)kb * 128 + c); + } + }; + r4d_fp8::f8v acc[R]; +#pragma unroll + for (int t = 0; t < R; ++t) acc[t] = r4d_fp8::acc_zero(); + load(0); + for (int kb = 0; kb < KB; ++kb) { + // The 136-byte pitch keeps 8-byte alignment only, so each 16 bytes go in as two halves. + auto put = [](uint8_t* p, const uint4& v) { + ((uint2*)p)[0] = make_uint2(v.x, v.y); + ((uint2*)p)[1] = make_uint2(v.z, v.w); + }; +#pragma unroll + for (int i = 0; i < AV; ++i) { + const int j = tid + i * 128; + put(qa + (j / 8) * P + (j % 8) * 16, av[i]); + } +#pragma unroll + for (int i = 0; i < WV; ++i) { + const int j = tid + i * 128; + put(wb + (j / 8) * P + (j % 8) * 16, wv[i]); + } + __syncthreads(); + if (kb + 1 < KB) load(kb + 1); + const float weight_scale = ws[(long)(n0 / 128) * m.sr + kb]; +#pragma unroll + for (int t = 0; t < R; ++t) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = 0; k < 128; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, t * 16, k, lane), + r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + t * 16 + h * 8 + j; + const float scale = r < m.T ? as[(long)r * m.asr + kb] * weight_scale : 0; + acc[t][j] += raw[j] * scale; + } + } + __syncthreads(); + } +#pragma unroll + for (int t = 0; t < R; ++t) +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + t * 16 + h * 8 + j, c = n0 + wave * 16 + (lane & 15); + if (r < m.T) y[(long)r * m.yr + c] = f32_to_bf16(acc[t][j]); + } +} + +// The dense form. RADIANCE_FP8F32_FORM names "legacy", "rows1"/"rows2"/"rows4" (row tiles a +// block) or "decode", optionally "decodeRxS" or "decodeRxSxC" (R row tiles, S waves a block, C +// column tiles a wave); otherwise the rule at the end of dense_form. The forms are byte-identical; +// the choice is speed only. +struct Form { + int kind = 0, r = 0, s = 0, c = 1; +}; // kind 0 legacy, 1 decode, 2 rows +constexpr int kLdsCap = 64 * 1024; +long decode_lds(int R, int S, int C, long KB, bool stage) { + return ((long)S * R * C * 8 * 32 + (long)R * C * 8 * 32 + (stage ? (long)R * 16 * KB : 0)) * 4; +} +// Row tiles a decode block shares a weight fragment over (at most three: four need 192 registers +// and spill), then waves a block: doubled while the grid stays under 1024 waves, the K blocks last +// and the exchange fits the LDS. +Form decode_plan(long N, long K, long T) { + Form f; + f.kind = 1; + const long tiles = (T + 15) / 16, kb = K / 128; + f.r = (int)(tiles >= 3 ? 3 : tiles); + const long blocks = (N / 16) * ((tiles + f.r - 1) / f.r); + f.s = 1; + while (f.s < 32 && f.s * 2 <= kb && blocks * f.s < 1024 && + decode_lds(f.r, f.s * 2, 1, kb, false) <= kLdsCap) + f.s *= 2; + return f; +} +Form dense_form(long N, long K, long T) { + if (const char* e = std::getenv("RADIANCE_FP8F32_FORM")) { + if (!std::strcmp(e, "legacy")) return Form{}; + if (!std::strncmp(e, "rows", 4)) { + Form f; + f.kind = 2; + f.r = e[4] == '1' ? 1 : e[4] == '2' ? 2 : 4; + return f; + } + if (!std::strncmp(e, "decode", 6)) { + Form f = decode_plan(N, K, T); + int r = 0, s = 0, c = 1; + const int n = std::sscanf(e + 6, "%dx%dx%d", &r, &s, &c); + if (n >= 2 && r >= 1 && r <= 3 && s >= 1 && s <= 32 && (s & (s - 1)) == 0 && + (c == 1 || c == 2 || c == 4) && !(r == 3 && c == 4)) { + f.r = r; + f.s = s; + f.c = c; + } + return f; + } + } + // Measured on gfx1201 (r4d_selftest --perfq, cold) at GLM's six shapes: decode1x8 up to 16 + // rows; from 17 to 64 two column tiles a wave (decode1x8x2) lead by 5 to 15 %, except at N 512 + // (too few column tiles, 1x8 stays) and N 4096 over K 1536, where the 16-row tile wins; from 65 + // to 128 rows decode1x8 holds at K 4096 and the row tiles win at K 2048 and below. Among the + // row tiles (and past 128 rows) the 16-row tile beats the 64-row tile by a quarter; the 32-row + // tile wins at N 4096. + const long kb = K / 128; + Form f; + const bool rows = + T > 128 || (T > 64 && K <= 2048) || (T > 16 && T <= 64 && K <= 1536 && N >= 4096); + if (!rows) { + f.kind = 1; + f.r = 1; + f.c = T > 16 && T <= 64 && N > 512 ? 2 : 1; + f.s = 8; + while (f.s > 1 && f.s > kb) f.s /= 2; + return f; + } + f.kind = 2; + f.r = T > 64 && N >= 4096 ? 2 : 1; + return f; +} +template +int emit_rows(RadStream stream, const uint8_t* xa, const float* xsa, const uint8_t* wa, + const float* wsa, uint16_t* ya, const Meta& m) { + return R4D_EMIT(stream, fp8_f32scale_rows, + dim3(m.N / 64, (unsigned)((m.T + R * 16 - 1) / (R * 16))), dim3(128), 0, xa, + xsa, wa, wsa, ya, m); +} +int dense_fast(RadStream stream, const RadTensor& x, const RadTensor& xs, const RadTensor& w, + const RadTensor& ws, const RadTensor& y, const Meta& m, bool* done) { + *done = false; + const Form f = dense_form(m.N, m.K, m.T); + if (!f.kind || m.wr % 16 || m.ar % 16 || + (reinterpret_cast(x.data) | reinterpret_cast(w.data)) % 16) + return RAD_OK; + const uint8_t *xa = (const uint8_t*)x.data, *wa = (const uint8_t*)w.data; + const float *xsa = (const float*)xs.data, *wsa = (const float*)ws.data; + uint16_t* ya = (uint16_t*)y.data; + if (f.kind == 1) { + const long kb = m.K / 128; + const int stage = decode_lds(f.r, f.s, f.c, kb, true) <= kLdsCap; + const long lds = decode_lds(f.r, f.s, f.c, kb, stage); + if (lds > kLdsCap || m.N % (16 * f.c)) return RAD_OK; + *done = true; + const dim3 grid(m.N / (16 * f.c), (unsigned)(((m.T + 15) / 16 + f.r - 1) / f.r)), + block(32 * f.s); +#define F32S_DECODE(R_, C_) \ + if (f.r == R_ && f.c == C_) \ + return R4D_EMIT(stream, (fp8_f32scale_decode), grid, block, (uint32_t)lds, xa, \ + xsa, wa, wsa, ya, m, stage); + F32S_DECODE(1, 1) + F32S_DECODE(2, 1) F32S_DECODE(3, 1) F32S_DECODE(1, 2) F32S_DECODE(2, 2) F32S_DECODE(3, 2) + F32S_DECODE(1, 4) F32S_DECODE(2, 4) +#undef F32S_DECODE + * done = false; + return RAD_OK; + } + *done = true; + if (f.r == 1) return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m); + if (f.r == 2) return emit_rows<2>(stream, xa, xsa, wa, wsa, ya, m); + return emit_rows<4>(stream, xa, xsa, wa, wsa, ya, m); +} +int body(const RadArgs* a, RadStream stream, bool grouped) { + if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL; + const auto &x = a->t[0], &xs = a->t[1], &w = a->t[2], &ws = a->t[3], &y = a->t[grouped ? 8 : 4]; + const int64_t N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0); + if (N < 128 || N % 128 || K < 128 || K % 128 || N > INT_MAX || K > INT_MAX || + r4d_geti_or(a, "group", 0) != 128 || r4d_geti_or(a, "pb1", 0) > 0) + return RAD_E_SHAPE; + if (x.dtype != RAD_F8E4M3 || xs.dtype != RAD_F32 || w.dtype != RAD_F8E4M3 || + ws.dtype != RAD_F32 || y.dtype != RAD_BF16) + return RAD_E_DTYPE; + if (!x.data || !xs.data || !w.data || !ws.data || !y.data || x.rank != 2 || xs.rank != 2 || + y.rank != 2 || x.shape[1] != K || xs.shape[0] != x.shape[0] || xs.shape[1] != K / 128 || + y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 || + y.shape[0] < 1 || y.shape[0] > INT_MAX) + return RAD_E_SHAPE; + const int rank = grouped ? 3 : 2; + if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K || + ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 || + ws.stride[rank - 1] != 1) + return RAD_E_SHAPE; + Meta m{}; + m.ar = x.stride[0]; + m.asr = xs.stride[0]; + m.yr = y.stride[0]; + m.wr = w.stride[rank - 2]; + m.sr = ws.stride[rank - 2]; + m.T = (int)y.shape[0]; + m.N = N; + m.K = K; + const void *w1 = nullptr, *s1 = nullptr; + const int *sorted = nullptr, *offsets = nullptr; + if (grouped) { + m.experts = r4d_geti_or(a, "n_expert", 0); + m.topk = r4d_geti_or(a, "top_k", 0); + const char* order = r4d_gets(a, "a_order"); + m.sorted_a = order && !std::strcmp(order, "sorted"); + const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5]; + if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N || + r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 || + wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K || + so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr || + so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 || + off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 || + off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data || + !so.data || !st.data || !off.data) + return RAD_E_SHAPE; + m.wstep[0] = w.stride[0]; + m.wstep[1] = wo.stride[0]; + m.sstep[0] = ws.stride[0] * 4; + m.sstep[1] = so.stride[0] * 4; + if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE; + w1 = wo.data; + s1 = so.data; + sorted = (const int*)st.data; + offsets = (const int*)off.data; + } else { + if (x.shape[0] != m.T) return RAD_E_SHAPE; + m.wstep[0] = N * m.wr; + m.sstep[0] = (N / 128) * m.sr * 4; + bool done = false; + const int rc = dense_fast(stream, x, xs, w, ws, y, m, &done); + if (done || rc < 0) return rc; + } + m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16; + if (grouped) { + /* The expert-major form at every routed-row count unless the environment bounds or + * refuses it (RADIANCE_FP8F32_DECODE_EXPERTS 0 or 1, ..._MAX_T). Measured at GLM's TP8 + * slices: a long K (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and + * under 128 routed rows four tiles a block on top; at down's K of 256 every variant + * reads within a few percent of the bandwidth, so it keeps 128 over four tiles. Stage + * and tiles can be pinned, for the microbenchmark. */ + auto env_long = [](const char* name, long dflt) { + const char* v = std::getenv(name); + return v && *v ? std::strtol(v, nullptr, 10) : dflt; + }; + const char* force = std::getenv("RADIANCE_FP8F32_DECODE_EXPERTS"); + const long max_t = env_long("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1); + if (force ? force[0] == '1' : max_t < 0 || m.T <= max_t) { + const long stage = env_long("RADIANCE_FP8F32_EXPERTS_STAGE_K", K <= 256 ? 128 : 256); + const long tiles = + env_long("RADIANCE_FP8F32_EXPERTS_COLTILES", K <= 256 || m.T < 128 ? 4 : 1); +#define F8_EXPERTS(SK, C) \ + R4D_EMIT(stream, (fp8_f32scale_experts), \ + dim3((N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), 0, \ + (const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, \ + offsets, (uint16_t*)y.data, m) + if (stage == 256) return tiles == 4 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1); + return tiles == 4 ? F8_EXPERTS(128, 4) : F8_EXPERTS(128, 1); +#undef F8_EXPERTS + } + } + if (grouped) + return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + m.tile - 1) / m.tile), + dim3(128), 0, (const uint8_t*)x.data, (const float*)xs.data, w.data, + ws.data, w1, s1, sorted, offsets, (uint16_t*)y.data, m); + return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0, + (const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, + offsets, (uint16_t*)y.data, m); +} +int dense(const RadArgs* a, RadStream stream) { return body(a, stream, false); } +int grouped(const RadArgs* a, RadStream stream) { return body(a, stream, true); } +} +extern "C" int r4d_rad_fp8_f32scale(const RadArgs* a, RadStream stream) { return dense(a, stream); } +extern "C" int r4d_rad_moe_fp8_f32scale(const RadArgs* a, RadStream stream) { + return grouped(a, stream); +} +extern "C" int r4d_layout_fp8_f32scale(const RadParam*, int, int operand, const RadEncoding* e, + const int* sel, const RadTensor*, int n, RadLayout*) { + if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED; + if (!e || !sel || n != 1 || !rad_enc_is(e, "affine") || e->n_planes != 2 || + e->plane[0].dtype != RAD_F8E4M3 || e->plane[1].dtype != RAD_F32 || + e->plane[1].block[0] != 128 || e->plane[1].block[1] != 128 || + sel[0] != (operand == 3 || operand == 7 ? 1 : 0)) + return RAD_E_DTYPE; + return RAD_E_UNSUPPORTED; // Both canonical planes are read without a relayout. +} diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 668ef541..bc176795 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -1,7 +1,7 @@ /* r4d_fuse.cpp -- the chain of unfused ops each fused kernel computes in one launch. * * `RadKernelInfo::replaces` (rad_abi.h) makes a fused row's claim to be byte-identical to the ops - * it replaces executable. Eleven of libr4d's fusions have no libref kernel, so this is their only + * it replaces executable. Most of libr4d's fusions have no libref kernel, so this is their only * oracle: a caller runs the fused row against its chain built from this plugin's own unfused rows, * and expects identical bytes, not a tolerance. * @@ -149,6 +149,16 @@ struct Step { return *this; } + Step& pf64(const char* key, double v) { + if (s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; } + RadParam q{}; + q.key = key; + q.kind = RAD_P_F64; + q.dval = v; + s->p[s->n_p++] = q; + return *this; + } + Step& pstr(const char* key, const char* v) { if (!v || s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; } RadParam q{}; @@ -306,6 +316,82 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre } } +/* ========================================================================================== + * swiglu_clamped_quant_fp8 -- GLM's clipped SwiGLU and the fp8 quantiser in one pass. + * (kernel: libr4d/r4d_glm.hip, swiglu_clamped_quant_kernel) + * + * Operands: [0] gate_up [1] q [2] scale [3] out_bf16? + * + * Each element is `swiglu_clamped_bf16`'s expression, rounded to bf16 once, and the codes are + * quant_act_fp8's over that rounded value, so the chain is the two rows with the product between. + */ +extern "C" int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam* p, int n_p, uint64_t present, + int step, RadFuseStep* out) { + + if (!out) return RAD_E_INVAL; + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); + if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED; + const int16_t mid = RAD_FUSE_HAS(present, 3) ? (int16_t)3 : RAD_FUSE_TMP(0); + + switch (step) { + case 0: { + Step s(out, "swiglu_clamped"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "limit").mirror(p, n_p, "dtype"); + return s.wire({ 0, mid }); /* gate_up, y */ + } + case 1: { + Step s(out, "quant_act_fp8"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype"); + return s.wire({ mid, 1, 2 }); /* x, q, scale */ + } + default: + return RAD_E_NOTFOUND; + } +} + +/* ========================================================================================== + * router_sigmoid_topk_scatter -- GLM's selection, the sort over its ids and the shared gate's fill. + * (kernel: libr4d/r4d_glm.hip, router_sigmoid_scatter_kernel) + * + * Operands: [0] logits [1] bias [2] ids [3] weights [4] sorted_tok [5] expert_offset + * [6] expert_count [7] gate? [8] inverse? + * + * The sort runs over this rank's slice, so `moe_scatter`'s `n_expert` is the fused op's `n_local`; + * with the inverse it is `moe_scatter_inv`. The fill steps in only with the gate. + */ +extern "C" int r4d_fuse_router_sigmoid_topk_scatter(const RadParam* p, int n_p, uint64_t present, + int step, RadFuseStep* out) { + + if (!out) return RAD_E_INVAL; + const int64_t ne = pi(p, n_p, "n_expert"), nl = pi(p, n_p, "n_local", ne); + if (ne <= 0 || nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED; + + switch (step) { + case 0: { + Step s(out, "router_sigmoid_topk"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n_expert").mirror(p, n_p, "top_k") + .mirror(p, n_p, "norm").mirror(p, n_p, "route_scale").mirror(p, n_p, "dtype"); + return s.wire({ 0, 1, 2, 3 }); /* logits, bias, ids, weights */ + } + case 1: { + const bool inv = RAD_FUSE_HAS(present, 8) != 0; + Step s(out, inv ? "moe_scatter_inv" : "moe_scatter"); + s.mirror(p, n_p, "M").pint("n_expert", nl).mirror(p, n_p, "top_k") + .mirror_opt(p, n_p, "expert_base").mirror_opt(p, n_p, "protect"); + if (inv) return s.wire({ 2, 4, 5, 6, 8 }); /* expert_ids, sorted_tok, offset, count, inverse */ + return s.wire({ 2, 4, 5, 6 }); /* expert_ids, sorted_tok, offset, count */ + } + case 2: { + if (!RAD_FUSE_HAS(present, 7)) return RAD_E_NOTFOUND; + Step s(out, "fill"); + s.mirror(p, n_p, "M").pint("n", 1).pstr("dtype", "bf16").pf64("value", 1.0); + return s.wire({ 7 }); /* y */ + } + default: + return RAD_E_NOTFOUND; + } +} + /* ========================================================================================== * gate_quant_fp8 -- the same epilogue with the gate in its own operand. * (kernel: libr4d/r4d_fused_quant_fp8.hip, gate_quant_fp8_kernel) diff --git a/libr4d/r4d_glm.hip b/libr4d/r4d_glm.hip new file mode 100644 index 00000000..b8324b27 --- /dev/null +++ b/libr4d/r4d_glm.hip @@ -0,0 +1,471 @@ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_moe_sort.h" +#include +#include +#include +#include +#include + +namespace { +__global__ void gemm_nt_f32_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, + long yp, int n, int k) { + const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), r = blockIdx.y; + if (col >= n) return; + float sum = 0; + for (int j = lane; j < k; j += 32) + sum = fmaf(bf16_to_f32(x[(long)r * xp + j]), w[(long)col * wp + j], sum); +#pragma unroll + for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + if (!lane) y[(long)r * yp + col] = sum; +} + +// One wave computes R rows by C columns, so each loaded weight serves R rows and each input +// C columns. Every output keeps gemm_nt_f32_kernel's arithmetic: lane l accumulates +// k = l, l+32, ... in ascending order with fmaf, then the same xor butterfly. Tail rows and +// columns read a clamped valid address and are never stored. +template +__global__ void __launch_bounds__(128) + gemm_nt_f32_tile_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, long yp, + int m, int n, int k) { + const int lane = threadIdx.x & 31, c0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * C, + r0 = blockIdx.y * R; + if (c0 >= n) return; + const uint16_t* xr[R]; + const float* wc[C]; +#pragma unroll + for (int q = 0; q < R; ++q) xr[q] = x + (long)(r0 + q < m ? r0 + q : m - 1) * xp; +#pragma unroll + for (int c = 0; c < C; ++c) wc[c] = w + (long)(c0 + c < n ? c0 + c : n - 1) * wp; + float sum[R][C]; +#pragma unroll + for (int q = 0; q < R; ++q) +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = 0; + for (int j = lane; j < k; j += 32) { + float weight[C]; +#pragma unroll + for (int c = 0; c < C; ++c) weight[c] = wc[c][j]; +#pragma unroll + for (int q = 0; q < R; ++q) { + const float v = bf16_to_f32(xr[q][j]); +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, weight[c], sum[q][c]); + } + } +#pragma unroll + for (int q = 0; q < R; ++q) +#pragma unroll + for (int c = 0; c < C; ++c) { +#pragma unroll + for (int mask = 16; mask; mask >>= 1) sum[q][c] += __shfl_xor(sum[q][c], mask, 32); + } + if (lane) return; +#pragma unroll + for (int q = 0; q < R; ++q) + if (r0 + q < m) +#pragma unroll + for (int c = 0; c < C; ++c) + if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c]; +} + +// The tile forms, by rows x columns per wave. RADIANCE_F32_GEMM_TILE names one ("8x4") or +// "legacy"; unset or unknown picks by M. All forms are byte-identical, so the choice is speed only. +struct F32Tile { + int r, c; +}; +constexpr F32Tile kF32Tiles[] = { { 1, 1 }, { 2, 1 }, { 4, 1 }, { 8, 1 }, { 4, 2 }, + { 8, 2 }, { 4, 4 }, { 8, 4 }, { 16, 2 }, { 16, 4 } }; +F32Tile f32_tile(long rows, long n) { + if (const char* e = std::getenv("RADIANCE_F32_GEMM_TILE")) { + if (!std::strcmp(e, "legacy")) return { 0, 0 }; + int r = 0, c = 0; + if (std::sscanf(e, "%dx%d", &r, &c) == 2) + for (const F32Tile& t : kF32Tiles) + if (t.r == r && t.c == c) return t; + } + // Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096. 16x4 gains + // 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every width. A + // projection of a few columns has too few waves for wide tiles at any M. + if (n <= 8) return { 4, 1 }; + if (rows <= 1) return { 0, 0 }; + if (rows <= 2) return { 2, 1 }; + if (rows < 16) return { 4, 1 }; + if (rows < 64) return { 4, 4 }; + return { 8, 4 }; +} +template +int gemm_f32_tile(RadStream stream, const RadTensor& x, const RadTensor& w, const RadTensor& y, + long n, long k) { + const long m = x.shape[0]; + return R4D_EMIT(stream, (gemm_nt_f32_tile_kernel), + dim3((unsigned)((n + 4 * C - 1) / (4 * C)), (unsigned)((m + R - 1) / R)), + dim3(128), 0, (const uint16_t*)x.data, (const float*)w.data, (float*)y.data, + x.stride[0], w.stride[0], y.stride[0], (int)m, (int)n, (int)k); +} +int gemm_f32_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const auto &x = a->t[0], &w = a->t[1], &y = a->t[2]; + const long n = r4d_geti_or(a, "N", 0), k = r4d_geti_or(a, "K", 0); + if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE; + if (!x.data || !w.data || !y.data) return RAD_E_INVAL; + if (n < 1 || n > 512 || k < 1 || k > 16384 || x.rank != 2 || w.rank != 2 || y.rank != 2 || + x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != k || w.shape[0] != n || + w.shape[1] != k || y.shape[0] != x.shape[0] || y.shape[1] != n || x.stride[1] != 1 || + w.stride[1] != 1 || y.stride[1] != 1 || x.stride[0] < k || w.stride[0] < k || + y.stride[0] < n) + return RAD_E_SHAPE; + const F32Tile t = f32_tile(x.shape[0], n); +#define R4D_F32_TILE(R, C) \ + if (t.r == R && t.c == C) return gemm_f32_tile(stream, x, w, y, n, k); + R4D_F32_TILE(1, 1) + R4D_F32_TILE(2, 1) R4D_F32_TILE(4, 1) R4D_F32_TILE(8, 1) R4D_F32_TILE(4, 2) R4D_F32_TILE(8, 2) + R4D_F32_TILE(4, 4) R4D_F32_TILE(8, 4) R4D_F32_TILE(16, 2) R4D_F32_TILE(16, 4) +#undef R4D_F32_TILE + return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0, + (const uint16_t*)x.data, (const float*)w.data, (float*)y.data, + x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k); +} +__global__ void router_sigmoid_kernel(const float* logits, const float* bias, int* ids, + float* weights, long lp, long bp, long ip, long wp, int ne, + int k, int norm, float factor) { + __shared__ float probabilities[512], ranking[512]; + const int r = blockIdx.x; + for (int e = threadIdx.x; e < ne; e += 256) { + const float p = 1.0f / (1.0f + expf(-logits[(long)r * lp + e])); + probabilities[e] = p; + ranking[e] = p + bias[(long)e * bp]; + } + __syncthreads(); + if (threadIdx.x) return; + int index[32]; + float chosen[32], total = 0; + for (int j = 0; j < k; ++j) { + int best = 0; + for (int e = 1; e < ne; ++e) + if (ranking[e] > ranking[best]) best = e; + index[j] = best; + chosen[j] = probabilities[best]; + total += chosen[j]; + ranking[best] = -INFINITY; + } + const float mult = norm ? factor / (total + 1e-20f) : factor; + for (int j = 0; j < k; ++j) { + ids[(long)r * ip + j] = index[j]; + weights[(long)r * wp + j] = chosen[j] * mult; + } +} +// The scan above in one wave per row. Lane l holds experts l, l+32, ... as 64-bit keys: the +// rank's order-preserving bits (-0 folded to +0) over ~e, so equal ranks order as the scan's strict +// `>` does, to the lower expert. Round j takes the largest key below round j-1's winner and parks +// it on lane j (top_k <= 32). Probabilities, `total` in round order, `mult` and the weights are +// the scan's expressions, so a finite row gives the same bytes. A NaN rank is never selected here, +// while the scan takes expert 0 first when its rank is NaN. +// OWN is a template bound because the keys are registers; a lane-derived trip count would index +// them divergently, which gfx12 lowers to a v_movrels loop. +__device__ __forceinline__ unsigned long long router_rank_key(float rank, int e) { + uint32_t u = __float_as_uint(rank); + if (u == 0x80000000u) u = 0; + const uint32_t k = (u & 0x80000000u) ? ~u : (u | 0x80000000u); + return rank == rank ? ((unsigned long long)k << 32) | (uint32_t)~e : 0ull; +} +__device__ __forceinline__ unsigned long long router_wave_max(unsigned long long b) { + unsigned long long o; + o = r4d_xor_lane_u64<16>(b); + b = b > o ? b : o; + o = r4d_xor_lane_u64<8>(b); + b = b > o ? b : o; + o = r4d_xor_lane_u64<4>(b); + b = b > o ? b : o; + o = r4d_xor_lane_u64<2>(b); + b = b > o ? b : o; + o = r4d_xor_lane_u64<1>(b); + b = b > o ? b : o; + return b; +} +// One row in one wave, from any grid: the standalone select and the fused one below run this. A +// lane below `k` returns its slot's expert as written to `ids`. +template +__device__ __forceinline__ int router_sigmoid_row(const float* logits, const float* bias, int* ids, + float* weights, long lp, long bp, long ip, + long wp, int r, int ne, int k, int norm, + float factor, int lane) { + float p[OWN]; + unsigned long long key[OWN]; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const int e = lane + 32 * i, s = e < ne ? e : 0; + p[i] = 1.0f / (1.0f + expf(-logits[(long)r * lp + s])); + key[i] = e < ne ? router_rank_key(p[i] + bias[(long)s * bp], e) : 0ull; + } + unsigned long long below = ~0ull, mine = 0; + for (int j = 0; j < k; ++j) { + unsigned long long best = 0; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const unsigned long long c = key[i] < below ? key[i] : 0ull; + best = c > best ? c : best; + } + best = router_wave_max(best); + if (lane == j) mine = best; + below = best; + } + const int e = mine ? (int)~(uint32_t)mine : 0; + float chosen = 0; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const float v = __shfl(p[i], e & 31, 32); + if ((e >> 5) == i) chosen = v; + } + float total = 0; + for (int j = 0; j < k; ++j) + total += __int_as_float(__builtin_amdgcn_readlane(__float_as_int(chosen), j)); + const float mult = norm ? factor / (total + 1e-20f) : factor; + if (lane < k) { + ids[(long)r * ip + lane] = e; + weights[(long)r * wp + lane] = chosen * mult; + } + return e; +} +template +__global__ void __launch_bounds__(128) + router_sigmoid_wave_kernel(const float* logits, const float* bias, int* ids, float* weights, + long lp, long bp, long ip, long wp, int m, int ne, int k, int norm, + float factor) { + const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5); + if (r >= m) return; + (void)router_sigmoid_row(logits, bias, ids, weights, lp, bp, ip, wp, r, ne, k, norm, + factor, lane); +} +// router_sigmoid_topk, then moe_scatter over its ids, then the `fill` of an ungated shared arm's +// gate with 1, in one workgroup. Rows wrap over the NW waves; each leaves its slots in the sort's +// LDS list instead of re-reading `ids`. A slot carries the expert its row wrote, including the +// expert 0 of a row with fewer finite ranks than top_k, so every output equals the three launches'. +// INV also writes the inverse, as moe_scatter_inv does. +template +__global__ void __launch_bounds__(NW * 32) + router_sigmoid_scatter_kernel(const float* logits, const float* bias, int* ids, float* weights, + int32_t* sorted, int32_t* off, int32_t* cnt, uint16_t* gate, + int32_t* inv, long lp, long bp, long ip, long wp, long gp, int m, + int ne, int n_local, int k, int norm, float factor, int base, + r4d_moesort::Protect prot) { + __shared__ r4d_moesort::ScatterLds sl; + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + for (int e = threadIdx.x; e < n_local; e += (int)(NW * 32)) sl.cnt[e] = 0; + for (int r = wave; r < m; r += (int)NW) { + const int e = router_sigmoid_row(logits, bias, ids, weights, lp, bp, ip, wp, r, ne, k, + norm, factor, lane) - + base; + if (lane < k) + sl.e[r * k + lane] = + e >= 0 && e < n_local ? r4d_moesort::sort_place(e, (uint32_t)n_local, prot) : -1; + if (gate && !lane) gate[(long)r * gp] = f32_to_bf16(1.0f); + } + lds_barrier(); + r4d_moesort::scatter_small_place(sorted, off, cnt, (uint32_t)(m * k), + (uint32_t)n_local, sl, inv); +} +int router_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 4) return RAD_E_INVAL; + const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3]; + const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0); + const float factor = (float)r4d_getf(a, "route_scale", 0); + if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || w.dtype != RAD_F32) + return RAD_E_DTYPE; + if (ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne || !std::isfinite(factor) || factor <= 0 || + !lg.data || !bias.data || !ids.data || !w.data || lg.rank != 2 || lg.shape[0] < 1 || + lg.shape[0] > 65535 || lg.shape[1] != ne || bias.rank != 1 || bias.shape[0] != ne || + ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] || w.shape[0] != lg.shape[0] || + ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 || ids.stride[1] != 1 || + w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k || w.stride[0] < k || + bias.stride[0] < 1) + return RAD_E_SHAPE; + const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0); + const char* select = std::getenv("RADIANCE_ROUTER_SELECT"); + if (select && !std::strcmp(select, "old")) + return R4D_EMIT(stream, router_sigmoid_kernel, dim3(lg.shape[0]), dim3(256), 0, + (const float*)lg.data, (const float*)bias.data, (int*)ids.data, + (float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], + (int)ne, (int)k, norm, factor); + const dim3 grid((unsigned)((lg.shape[0] + 3) / 4)); + if (ne <= 9 * 32) + return R4D_EMIT(stream, router_sigmoid_wave_kernel<9>, grid, dim3(128), 0, + (const float*)lg.data, (const float*)bias.data, (int*)ids.data, + (float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], + (int)lg.shape[0], (int)ne, (int)k, norm, factor); + return R4D_EMIT(stream, router_sigmoid_wave_kernel<16>, grid, dim3(128), 0, + (const float*)lg.data, (const float*)bias.data, (int*)ids.data, (float*)w.data, + lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], (int)lg.shape[0], + (int)ne, (int)k, norm, factor); +} +/* Operands: router_sigmoid_topk's four, moe_scatter's three outputs, then the optional gate and the + * optional inverse. The sort is the single-workgroup form, so M * top_k must fit it; a larger pass + * is refused rather than served at another cost. */ +int router_scatter_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3]; + const RadTensor *sorted = &a->t[4], *off = &a->t[5], *cnt = &a->t[6]; + const RadTensor* gate = a->n_t > 7 ? r4d_opt(a, 7) : nullptr; + const RadTensor* inv = a->n_t > 8 ? r4d_opt(a, 8) : nullptr; + const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0); + const long nl = r4d_geti_or(a, "n_local", ne), base = r4d_geti_or(a, "expert_base", 0); + const float factor = (float)r4d_getf(a, "route_scale", 0); + if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || + w.dtype != RAD_F32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 || + cnt->dtype != RAD_I32 || (gate && gate->dtype != RAD_BF16) || + (inv && inv->dtype != RAD_I32)) + return RAD_E_DTYPE; + if (ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne || !std::isfinite(factor) || factor <= 0 || + !lg.data || !bias.data || !ids.data || !w.data || !sorted->data || !off->data || + !cnt->data || lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 || + bias.shape[0] != ne || ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] || + w.shape[0] != lg.shape[0] || ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 || + ids.stride[1] != 1 || w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k || + w.stride[0] < k || bias.stride[0] < 1) + return RAD_E_SHAPE; + const long m = lg.shape[0], T = m * k; + if (T > (long)r4d_moesort::kScatterSmall || nl < 1 || nl > ne || base < 0 || base + nl > ne || + !r4d_contig(sorted) || !r4d_contig(off) || !r4d_contig(cnt) || r4d_numel(sorted) < T || + r4d_numel(off) < nl + 1 || r4d_numel(cnt) < nl || + (inv && (!r4d_contig(inv) || r4d_numel(inv) < T))) + return RAD_E_SHAPE; + long long grows = 0; + const long long gp = gate ? r4d_rows_pitch(gate, 1, &grows) : 0; + if (gate && (gp < 1 || grows < m)) return RAD_E_SHAPE; + r4d_moesort::Protect prot; + const int prc = r4d_moesort::protect_of(a, nl, &prot); + if (prc != RAD_OK) return prc; + const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0); + // A wave a row up to 32 rows, as router_topk_scatter: the rows a wave serves run back to back. + const int nw = m <= 8 ? 8 : m <= 16 ? 16 : 32; +#define R4D_RSS_I(OWN, NW, INV) \ + return R4D_EMIT(stream, (router_sigmoid_scatter_kernel), dim3(1), \ + dim3((NW) * 32), 0, (const float*)lg.data, (const float*)bias.data, \ + (int*)ids.data, (float*)w.data, (int32_t*)sorted->data, (int32_t*)off->data, \ + (int32_t*)cnt->data, gate ? (uint16_t*)gate->data : (uint16_t*)nullptr, \ + inv ? (int32_t*)inv->data : (int32_t*)nullptr, lg.stride[0], bias.stride[0], \ + ids.stride[0], w.stride[0], (long)gp, (int)m, (int)ne, (int)nl, (int)k, norm, \ + factor, (int)base, prot) +#define R4D_RSS(OWN, NW) \ + do { \ + if (inv) R4D_RSS_I(OWN, NW, true); \ + R4D_RSS_I(OWN, NW, false); \ + } while (0) + if (ne <= 9 * 32) { + if (nw == 8) R4D_RSS(9, 8u); + if (nw == 16) R4D_RSS(9, 16u); + R4D_RSS(9, 32u); + } + if (nw == 8) R4D_RSS(16, 8u); + if (nw == 16) R4D_RSS(16, 16u); + R4D_RSS(16, 32u); +#undef R4D_RSS +#undef R4D_RSS_I +} +__global__ void swiglu_clamped_kernel(const uint16_t* gu, uint16_t* y, long gp, long yp, int n, + float limit) { + const long r = blockIdx.x; + const int i = blockIdx.y * 256 + threadIdx.x; + if (i >= n) return; + const float g = fminf(bf16_to_f32(gu[r * gp + i]), limit); + const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + i]), -limit), limit); + y[r * yp + i] = f32_to_bf16((g / (1.0f + expf(-g))) * u); +} +int clamped_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 2) return RAD_E_INVAL; + const auto &gu = a->t[0], &y = a->t[1]; + const long n = r4d_geti_or(a, "n", 0); + const float limit = (float)r4d_getf(a, "limit", 0); + if (gu.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE; + if (n < 1 || n > INT_MAX / 2 || !std::isfinite(limit) || limit <= 0 || !gu.data || !y.data || + gu.rank != 2 || y.rank != 2 || y.shape[0] < 1 || y.shape[0] > 65535 || + gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n || y.shape[1] != n || gu.stride[1] != 1 || + y.stride[1] != 1 || gu.stride[0] < 2 * n || y.stride[0] < n) + return RAD_E_SHAPE; + return R4D_EMIT(stream, swiglu_clamped_kernel, dim3(y.shape[0], (n + 255) / 256), dim3(256), 0, + (const uint16_t*)gu.data, (uint16_t*)y.data, gu.stride[0], y.stride[0], (int)n, + limit); +} +// swiglu_clamped, then quant_act_fp8 over its product, in one pass: a wave per (row, 128 columns), +// four columns a lane, as the quantiser maps them. Each element is swiglu_clamped_kernel's +// expression and each group quant_act_fp8_kernel's. The product is rounded to bf16 and read back +// before the absmax because the separate quantiser reads the stored bf16 bytes. +__global__ void __launch_bounds__(256) + swiglu_clamped_quant_kernel(const uint16_t* gu, uint16_t* y, uint8_t* q, float* s, long gp, + long yp, long qp, long sp, int n, int nkb, float limit) { + const long r = blockIdx.x; + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + for (int kb = wave; kb < nkb; kb += (int)(blockDim.x >> 5)) { + const int c0 = kb * 128 + lane * 4; + float v[4], m = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int c = c0 + j; + v[j] = 0.0f; + if (c < n) { + const float g = fminf(bf16_to_f32(gu[r * gp + c]), limit); + const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + c]), -limit), limit); + const uint16_t h = f32_to_bf16((g / (1.0f + expf(-g))) * u); + if (y) y[r * yp + c] = h; + v[j] = bf16_to_f32(h); + } + } +#pragma unroll + for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); + m = r4d_wave_max(m); + const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f; + if (!lane) s[r * sp + kb] = sc; + const float inv = 1.0f / sc; + int pk = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f), + fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f), + fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true); + if (c0 < n) *(uint32_t*)(q + r * qp + c0) = (uint32_t)pk; + } +} +/* Operands: gate_up [M, 2n], q [M, n] E4M3, scale [M, ceil(n/128)] f32, out_bf16 [M, n] optional. + * n a multiple of 4 and group 128, as quant_act_fp8 requires. */ +int clamped_quant_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const auto &gu = a->t[0], &q = a->t[1], &sc = a->t[2]; + const RadTensor* y = a->n_t > 3 ? r4d_opt(a, 3) : nullptr; + const long n = r4d_geti_or(a, "n", 0), nkb = (n + 127) / 128; + const float limit = (float)r4d_getf(a, "limit", 0); + if (gu.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || sc.dtype != RAD_F32 || + (y && y->dtype != RAD_BF16)) + return RAD_E_DTYPE; + if (r4d_geti_or(a, "group", 128) != 128 || n < 4 || n % 4 || n > INT_MAX / 2 || + !std::isfinite(limit) || limit <= 0 || !gu.data || !q.data || !sc.data || gu.rank != 2 || + q.rank != 2 || sc.rank != 2 || gu.shape[0] < 1 || gu.shape[0] > 65535 || + gu.shape[1] != 2 * n || q.shape[0] != gu.shape[0] || q.shape[1] != n || + sc.shape[0] != gu.shape[0] || sc.shape[1] != nkb || gu.stride[1] != 1 || q.stride[1] != 1 || + sc.stride[1] != 1 || gu.stride[0] < 2 * n || q.stride[0] < n || sc.stride[0] < nkb || + (y && (y->rank != 2 || y->shape[0] != gu.shape[0] || y->shape[1] != n || + y->stride[1] != 1 || y->stride[0] < n))) + return RAD_E_SHAPE; + // A wave a group, at most eight: a row of GLM's TP8 expert width is two groups. + const unsigned thr = (unsigned)(nkb < 8 ? nkb : 8) * 32u; + return R4D_EMIT(stream, swiglu_clamped_quant_kernel, dim3((unsigned)gu.shape[0]), dim3(thr), 0, + (const uint16_t*)gu.data, y ? (uint16_t*)y->data : (uint16_t*)nullptr, + (uint8_t*)q.data, (float*)sc.data, gu.stride[0], y ? (long)y->stride[0] : 0L, + q.stride[0], sc.stride[0], (int)n, (int)nkb, limit); +} +} +extern "C" int r4d_rad_swiglu_clamped(const RadArgs* a, RadStream stream) { + return clamped_body(a, stream); +} +extern "C" int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs* a, RadStream stream) { + return clamped_quant_body(a, stream); +} +extern "C" int r4d_rad_gemm_nt_f32(const RadArgs* a, RadStream stream) { + return gemm_f32_body(a, stream); +} +extern "C" int r4d_rad_router_sigmoid_topk(const RadArgs* a, RadStream stream) { + return router_body(a, stream); +} +extern "C" int r4d_rad_router_sigmoid_topk_scatter(const RadArgs* a, RadStream stream) { + return router_scatter_body(a, stream); +} diff --git a/libr4d/r4d_kda.hip b/libr4d/r4d_kda.hip new file mode 100644 index 00000000..fdbcd799 --- /dev/null +++ b/libr4d/r4d_kda.hip @@ -0,0 +1,491 @@ +/* Exact recurrent baseline for GLM KDA, including speculative candidate snapshots. + * One wave owns one, two or four value rows and keeps each row's 128-wide state in four + * registers per lane. + * Prefill uses the same recurrence and commits only its final state. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include +#include +#include + +namespace { +struct KdaMeta { + int row[5], head[5]; + long os0, os1, ss0, ss1, ss2; + long is0, is1, cs0, as0, hs0; + int tokens, slots, width, verify, anchor; + float lower, eps, scale; +}; +struct KdaJob : KdaMeta { + const uint16_t* input[5]; + const float *alog, *bias; + float* state; + uint16_t* out; + const int *idx, *cu, *accepted, *init; +}; + +__device__ float sum(float v) { + for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32); + return __shfl(v, 0, 32); +} +/* r4d_wave_sum adds the same partners in the same order as sum() does for lane 0, and every + * other lane forms the same additions with the operands swapped, so all lanes hold lane 0's bits + * without the broadcast. */ +template +__device__ __forceinline__ float wave_total(float v) { + if constexpr (Dpp) + return r4d_wave_sum(v); + else + return sum(v); +} +__device__ long factor_offset(long base, int logical, long pitch) { + return base + (logical / 128) * pitch + (logical % 128); +} +/* Separate dispatch: all old factor reads finish before the next window overwrites them. */ +template +__global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, const int* accepted, + const int* init, KdaMeta m) { + const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, + seq = blockIdx.z; + const int anchor = idx[(long)seq * m.is0], + scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1]; + if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch) + return; + const long fb = (long)scratch * m.ss0 + (long)head * m.ss1; + const long sb = (long)anchor * m.ss0 + (long)head * m.ss1 + (long)e * m.ss2; + if (init && !init[(long)seq * m.hs0]) { +#pragma unroll + for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = 0; + return; + } + const float count = state[fb]; + const int na = accepted ? accepted[(long)seq * m.as0] : 1; + if (!(count >= 0 && count <= 32) || count != floorf(count) || na < 1 || na > 32 || + (count > 0 && na > count)) + return; + float s[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) s[d] = state[sb + lane + d * 32]; + for (int t = 0; t < (count > 0 ? na : 0); ++t) { + const int f = 1 + t * 385; + float k[4], prediction = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int c = lane + d * 32; + k[d] = state[factor_offset(fb, f + c, m.ss2)]; + s[d] *= state[factor_offset(fb, f + 256 + c, m.ss2)]; + prediction += s[d] * k[d]; + } + const float delta = + state[factor_offset(fb, f + 384, m.ss2)] * + (state[factor_offset(fb, f + 128 + e, m.ss2)] - wave_total(prediction)); +#pragma unroll + for (int d = 0; d < 4; ++d) s[d] += delta * k[d]; + } +#pragma unroll + for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d]; +} +__global__ void kda_update_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v, + const uint16_t* g, const uint16_t* beta, const float* alog, + const float* bias, float* state_ptr, uint16_t* out, + const int* idx, const int* cu, const int* accepted_ptr, + const int* init, KdaMeta meta) { + KdaJob j{}; + static_cast(j) = meta; + j.input[0] = q; + j.input[1] = k; + j.input[2] = v; + j.input[3] = g; + j.input[4] = beta; + j.alog = alog; + j.bias = bias; + j.state = state_ptr; + j.out = out; + j.idx = idx; + j.cu = cu; + j.accepted = accepted_ptr; + j.init = init; + const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5); + const int head = blockIdx.y, seq = blockIdx.z; + const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0]; + const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1; + if (begin < 0 || end < begin || end > j.tokens || accepted < 1 || + accepted > (j.anchor ? 32 : j.width) || + (j.verify && end - begin > (j.anchor ? 32 : j.width))) + return; + const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1]; + if (read >= j.slots) return; + if (read < 0) { + if (!lane) + for (int t = begin; t < end; ++t) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = 0; + return; + } + const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0; + const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0; + if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return; + const long fb = (long)scratch * j.ss0 + (long)head * j.ss1; + const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2; + float state[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) state[d] = initialized ? j.state[initial + lane + 32 * d] : 0; + const float gain = expf(j.alog[head]); + for (int t = begin; t < end; ++t) { + float q[4], k[4], decay[4], sq = 0, sk = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int channel = lane + d * 32; + q[d] = bf16_to_f32(j.input[0][(long)t * j.row[0] + (long)head * j.head[0] + channel]); + k[d] = bf16_to_f32(j.input[1][(long)t * j.row[1] + (long)head * j.head[1] + channel]); + sq += q[d] * q[d]; + sk += k[d] * k[d]; + const float raw = + bf16_to_f32(j.input[3][(long)t * j.row[3] + (long)head * j.head[3] + channel]); + decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + j.bias[head * 128 + channel])))); + } + const float qi = j.scale * rsqrtf(sum(sq) + j.eps), ki = rsqrtf(sum(sk) + j.eps); + const float beta = + 1.0f / + (1.0f + expf(-bf16_to_f32(j.input[4][(long)t * j.row[4] + (long)head * j.head[4]]))); + float predicted = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + q[d] *= qi; + k[d] *= ki; + state[d] *= decay[d]; + predicted += state[d] * k[d]; + } + predicted = sum(predicted); + const float value = + bf16_to_f32(j.input[2][(long)t * j.row[2] + (long)head * j.head[2] + e]); + if (j.anchor && j.verify) { + const int f = 1 + (t - begin) * 385; + if (e == 0) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int c = lane + 32 * d; + j.state[factor_offset(fb, f + c, j.ss2)] = k[d]; + j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d]; + } + if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = beta; + } + if (!lane) j.state[factor_offset(fb, f + 128 + e, j.ss2)] = value; + } + const float delta = beta * (value - predicted); + float result = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + state[d] += delta * k[d]; + result += state[d] * q[d]; + } + result = sum(result); + if (!lane) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = f32_to_bf16(result); + if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) { + const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1]; + if (write >= 0 && write < j.slots) { + const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2; +#pragma unroll + for (int d = 0; d < 4; ++d) j.state[target + lane + 32 * d] = state[d]; + } + } + } + if (j.anchor && e == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f; +} +/* kda_update_kernel with R value rows a wave: the loads, norms and decay exponentials, which do + * not depend on the state, are formed once for R rows, and the rows' reductions interleave. Each + * row's arithmetic is kda_update_kernel's in its order, so the bytes match (selftest --perfkda). + * With Prefetch the next token's operands are loaded while this one is reduced. */ +template +__global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v, + const uint16_t* g, const uint16_t* beta, const float* alog, + const float* bias, float* state_ptr, uint16_t* out, const int* idx, + const int* cu, const int* accepted_ptr, const int* init, + KdaMeta meta) { + static_assert(32 % R == 0, "the 128 value rows split evenly over the waves"); + KdaJob j{}; + static_cast(j) = meta; + j.input[0] = q; + j.input[1] = k; + j.input[2] = v; + j.input[3] = g; + j.input[4] = beta; + j.alog = alog; + j.bias = bias; + j.state = state_ptr; + j.out = out; + j.idx = idx; + j.cu = cu; + j.accepted = accepted_ptr; + j.init = init; + const int lane = threadIdx.x & 31, e0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * R; + const int head = blockIdx.y, seq = blockIdx.z; + const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0]; + const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1; + if (begin < 0 || end < begin || end > j.tokens || accepted < 1 || + accepted > (j.anchor ? 32 : j.width) || + (j.verify && end - begin > (j.anchor ? 32 : j.width))) + return; + const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1]; + if (read >= j.slots) return; + uint16_t* const out_row = j.out + (long)head * j.os1 + e0; + if (read < 0) { + if (lane < R) + for (int t = begin; t < end; ++t) out_row[(long)t * j.os0 + lane] = 0; + return; + } + const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0; + const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0; + if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return; + const long fb = (long)scratch * j.ss0 + (long)head * j.ss1; + const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2; + float state[R][4]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int d = 0; d < 4; ++d) + state[r][d] = initialized ? j.state[initial + r * j.ss2 + lane + 32 * d] : 0; + const float gain = expf(j.alog[head]); + float shift[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) shift[d] = j.bias[head * 128 + lane + 32 * d]; + const uint16_t* const qb = j.input[0] + (long)head * j.head[0] + lane; + const uint16_t* const kb = j.input[1] + (long)head * j.head[1] + lane; + const uint16_t* const vb = j.input[2] + (long)head * j.head[2] + e0; + const uint16_t* const gb = j.input[3] + (long)head * j.head[3] + lane; + const uint16_t* const bb = j.input[4] + (long)head * j.head[4]; + struct Token { + uint32_t q[4], k[4], g[4], beta, value[R]; + }; + auto fetch = [&](int t, Token& o) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + o.q[d] = ldg_u16(qb + (long)t * j.row[0] + 32 * d); + o.k[d] = ldg_u16(kb + (long)t * j.row[1] + 32 * d); + o.g[d] = ldg_u16(gb + (long)t * j.row[3] + 32 * d); + } + o.beta = ldg_u16(bb + (long)t * j.row[4]); +#pragma unroll + for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r); + }; + Token cur; + if (Prefetch && begin < end) fetch(begin, cur); + for (int t = begin; t < end; ++t) { + [[maybe_unused]] Token next; + /* The last token loads itself again rather than a row past `end`. */ + if constexpr (Prefetch) + fetch(t + 1 < end ? t + 1 : t, next); + else + fetch(t, cur); + float qv[4], kv[4], decay[4], sq = 0, sk = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + qv[d] = bf16w_lo(cur.q[d]); + kv[d] = bf16w_lo(cur.k[d]); + sq += qv[d] * qv[d]; + sk += kv[d] * kv[d]; + const float raw = bf16w_lo(cur.g[d]); + decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + shift[d])))); + } + const float qi = j.scale * rsqrtf(r4d_wave_sum(sq) + j.eps), + ki = rsqrtf(r4d_wave_sum(sk) + j.eps); + const float b = 1.0f / (1.0f + expf(-bf16w_lo(cur.beta))); + float predicted[R]; +#pragma unroll + for (int r = 0; r < R; ++r) predicted[r] = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + qv[d] *= qi; + kv[d] *= ki; +#pragma unroll + for (int r = 0; r < R; ++r) { + state[r][d] *= decay[d]; + predicted[r] += state[r][d] * kv[d]; + } + } + float value[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + predicted[r] = r4d_wave_sum(predicted[r]); + value[r] = bf16w_lo(cur.value[r]); + } + if (j.anchor && j.verify) { + const int f = 1 + (t - begin) * 385; + if (e0 == 0) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int c = lane + 32 * d; + j.state[factor_offset(fb, f + c, j.ss2)] = kv[d]; + j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d]; + } + if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = b; + } + if (!lane) { +#pragma unroll + for (int r = 0; r < R; ++r) + j.state[factor_offset(fb, f + 128 + e0 + r, j.ss2)] = value[r]; + } + } + float result[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const float delta = b * (value[r] - predicted[r]); + result[r] = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + state[r][d] += delta * kv[d]; + result[r] += state[r][d] * qv[d]; + } + } + float mine = 0; +#pragma unroll + for (int r = 0; r < R; ++r) { + result[r] = r4d_wave_sum(result[r]); + if (lane == r) mine = result[r]; + } + if (lane < R) out_row[(long)t * j.os0 + lane] = f32_to_bf16(mine); + if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) { + const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1]; + if (write >= 0 && write < j.slots) { + const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int d = 0; d < 4; ++d) + j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d]; + } + } + if constexpr (Prefetch) cur = next; + } + if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f; +} + +template +bool headed(const RadTensor& t, long tokens, long heads, long dim, Pitch* row, Pitch* head) { + if (!t.data || t.dtype != RAD_BF16 || t.shape[0] != tokens || t.stride[0] > INT_MAX || + (t.rank == 3 && t.stride[1] > INT_MAX)) + return false; + if (t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim && t.stride[2] == 1 && + t.stride[1] >= dim && t.stride[0] >= heads * t.stride[1]) { + *row = t.stride[0]; + *head = t.stride[1]; + return true; + } + if (t.rank == 2 && t.shape[1] == heads * dim && t.stride[1] == 1 && + t.stride[0] >= heads * dim) { + *row = t.stride[0]; + *head = dim; + return true; + } + return false; +} +bool vector(const RadTensor& t, uint32_t dt, long n) { + return t.data && t.dtype == dt && t.rank == 1 && t.shape[0] >= n && t.stride[0] == 1; +} +int body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 13) return RAD_E_INVAL; + const long H = r4d_geti_or(a, "heads", 0); + if (H < 1 || H > 65535 || r4d_geti_or(a, "head_k", 0) != 128 || + r4d_geti_or(a, "head_v", 0) != 128) + return RAD_E_SHAPE; + KdaJob j{}; + const auto &state = a->t[7], &idx = a->t[8], &cu = a->t[9]; + const long tokens = a->t[0].shape[0]; + if (tokens < 1 || tokens > INT_MAX || state.rank != 4 || state.dtype != RAD_F32 || + !state.data || state.shape[0] < 1 || state.shape[0] > INT_MAX || state.shape[1] != H || + state.shape[2] != 128 || state.shape[3] != 128 || state.stride[3] != 1 || + state.stride[2] < 128 || state.stride[1] < 128 * state.stride[2] || + state.stride[0] < H * state.stride[1] || cu.rank != 1 || cu.dtype != RAD_I32 || !cu.data || + cu.shape[0] < 2 || cu.shape[0] > 65536 || cu.stride[0] < 1 || idx.rank != 2 || + idx.dtype != RAD_I32 || !idx.data || idx.shape[0] < cu.shape[0] - 1 || idx.shape[1] < 1 || + idx.shape[1] > INT_MAX || idx.stride[1] < 1 || idx.stride[0] < idx.shape[1] * idx.stride[1]) + return RAD_E_SHAPE; + for (int i = 0; i < 5; ++i) { + if (!headed(a->t[i], tokens, H, i == 4 ? 1 : 128, &j.row[i], &j.head[i])) + return RAD_E_SHAPE; + j.input[i] = (const uint16_t*)a->t[i].data; + } + if (!headed(a->t[12], tokens, H, 128, &j.os0, &j.os1) || !vector(a->t[5], RAD_F32, H) || + !vector(a->t[6], RAD_F32, H * 128)) + return RAD_E_SHAPE; + const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11); + if ((accepted && !vector(*accepted, RAD_I32, cu.shape[0] - 1)) || + (init && !vector(*init, RAD_I32, cu.shape[0] - 1))) + return RAD_E_SHAPE; + const char* mode = r4d_gets(a, "mode"); + if (!mode || (std::strcmp(mode, "verify") && std::strcmp(mode, "prefill"))) return RAD_E_INVAL; + j.verify = !std::strcmp(mode, "verify"); + const char* form = r4d_gets(a, "state_form"); + j.anchor = form && !std::strcmp(form, "anchor"); + if (form && !j.anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL; + if (j.anchor && idx.shape[1] < 2) return RAD_E_SHAPE; + j.lower = (float)r4d_getf(a, "lower_bound", 0); + j.eps = (float)r4d_getf(a, "l2_eps", 0); + j.scale = (float)r4d_getf(a, "scale", 1); + if (!std::isfinite(j.lower) || j.lower >= 0 || !std::isfinite(j.eps) || j.eps <= 0 || + !std::isfinite(j.scale)) + return RAD_E_SHAPE; + j.tokens = (int)tokens; + j.slots = (int)state.shape[0]; + j.width = (int)idx.shape[1]; + j.alog = (const float*)a->t[5].data; + j.bias = (const float*)a->t[6].data; + j.state = (float*)state.data; + j.out = (uint16_t*)a->t[12].data; + j.ss0 = state.stride[0]; + j.ss1 = state.stride[1]; + j.ss2 = state.stride[2]; + j.idx = (const int*)idx.data; + j.is0 = idx.stride[0]; + j.is1 = idx.stride[1]; + j.cu = (const int*)cu.data; + j.cs0 = cu.stride[0]; + if (accepted) { + j.accepted = (const int*)accepted->data; + j.as0 = accepted->stride[0]; + } + if (init) { + j.init = (const int*)init->data; + j.hs0 = init->stride[0]; + } + /* RADIANCE_KDA_FORM=old is the one-row kernel on shuffle sums, the reference the selftest + * holds every form to byte for byte; RADIANCE_KDA_ROWS (1, 2 or 4 value rows a wave) and + * RADIANCE_KDA_PREFETCH=0 pin the other form's variants for the microbenchmark. */ + const char* kform = std::getenv("RADIANCE_KDA_FORM"); + const bool old = kform && !std::strcmp(kform, "old"); + const unsigned seqs = (unsigned)(cu.shape[0] - 1); + if (j.anchor && j.verify) { + const int rc = + old ? R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), + 0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast(j)) + : R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), + 0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast(j)); + if (rc != RAD_OK) return rc; + } + if (old) + return R4D_EMIT(stream, kda_update_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0, + j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], j.alog, j.bias, + j.state, j.out, j.idx, j.cu, j.accepted, j.init, static_cast(j)); + const char* rows_env = std::getenv("RADIANCE_KDA_ROWS"); + const long rows = rows_env && *rows_env ? std::strtol(rows_env, nullptr, 10) : 4; + const char* prefetch_env = std::getenv("RADIANCE_KDA_PREFETCH"); + const bool prefetch = !prefetch_env || prefetch_env[0] != '0'; +#define KDA_ROWS(RR, PF) \ + return R4D_EMIT(stream, (kda_rows_kernel), dim3(32 / RR, (unsigned)H, seqs), \ + dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], \ + j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init, \ + static_cast(j)) + if (rows == 1) { + if (prefetch) KDA_ROWS(1, true); + KDA_ROWS(1, false); + } + if (rows == 2) { + if (prefetch) KDA_ROWS(2, true); + KDA_ROWS(2, false); + } + if (prefetch) KDA_ROWS(4, true); + KDA_ROWS(4, false); +#undef KDA_ROWS +} +} +extern "C" int r4d_rad_kda_update(const RadArgs* a, RadStream stream) { return body(a, stream); } diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 88b34adb..6ef46f6f 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -1197,6 +1197,23 @@ extern "C" int r4d_rad_unrelayout_moe_w4_mod4(const RadParam* p, int n_p, int op return moew4_unrelayout_by(moe_view_mod4, p, n_p, operand, enc, sel, src, src_bytes, pl, n); } +extern "C" int r4d_rad_layout_moe_mxfp4(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout*) { + if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED; + if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, 32)) return RAD_E_DTYPE; + MoeView v; + const int rc = moe_view(p, n_p, operand, &v); + if (rc != RAD_OK) return rc; + const long long N = r4d_pgeti_or(v.p, v.n, "N", 0), K = r4d_pgeti_or(v.p, v.n, "K", 0); + const bool scale = operand == 3 || operand == 7; + if (n != 1 || !pl || !sel || !selects(enc, sel, n, scale ? "scale" : "codes") || + !dims(pl[0], N, scale ? K / 32 : K) || K % 128) return RAD_E_SHAPE; + /* The exact selected canonical plane, not a relayout: it remains readable in place + * from the container or a mapped host pool. Unsupported is the ABI spelling for that. */ + return RAD_E_UNSUPPORTED; +} + extern "C" int r4d_rad_layout_moe_fp8(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out) { diff --git a/libr4d/r4d_mhc.hip b/libr4d/r4d_mhc.hip new file mode 100644 index 00000000..53a2b8ea --- /dev/null +++ b/libr4d/r4d_mhc.hip @@ -0,0 +1,731 @@ +/* GLM's mHC, kept separate from the Qwen gated-residual kernels. The GLM shape + * projects in parallel before one workgroup per token forms the Sinkhorn matrix. + * Mixing weights are declared f32; activations are bf16, coefficients stay f32. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include +#include +#include +#include + +namespace { +__device__ float warp_sum(float v) { + for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32); + return v; +} + +// The final collapsed output is large enough to hold the projection partials +// until the finishing kernel has read them. Align within each pitched row. +__device__ float* partials(uint16_t* x, long row, long pitch) { + return reinterpret_cast((reinterpret_cast(x + row * pitch) + 3) & + ~uintptr_t(3)); +} +// Where projection partial (row, coefficient j, chunk) lives: inside the collapsed output's rows +// (mhc_pre), or a separate [rows][chunk][stride] matrix (mhc_pre_partial writes this rank's chunks +// from `first`, mhc_pre_finish reads every rank's after the gather). Kernels differ in address only. +// `pad` clears a Dense chunk's slots past the last partial, so the gathered payload is defined. +struct InX { + uint16_t* x; + long xp; + int chunks; + __device__ float* at(long row, int j, int chunk) const { + return partials(x, row, xp) + j * chunks + chunk; + } + __device__ void pad(long, int, int) const {} +}; +struct Dense { + float* p; + long pp; + int stride, first; + __device__ float* at(long row, int j, int chunk) const { + return p + row * pp + (long)(chunk - first) * stride + j; + } + __device__ void pad(long row, int last, int chunk) const { + for (int j = last + 1; j < stride; ++j) *at(row, j, chunk) = 0; + } +}; +template +__global__ void mhc_partial_kernel(const uint16_t* h, const float* fn, Out out, int width, int mix, + int chunk0, long hp, long fp) { + __shared__ float sums[4]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int j = blockIdx.y, chunk = chunk0 + blockIdx.x; + const long row = blockIdx.z; + float sum = 0; + for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) { + const float v = bf16_to_f32(h[row * hp + i]); + sum += v * (j == mix ? v : fn[(long)j * fp + i]); + } + sum = warp_sum(sum); + if (!lane) sums[wave] = sum; + __syncthreads(); + if (!tid) { + *out.at(row, j, chunk) = sums[0] + sums[1] + sums[2] + sums[3]; + if (j == mix) out.pad(row, mix, chunk); + } +} + +// Prefill reuses each F32 mixing weight across four BF16 token rows. +// Each row keeps the same accumulation and reduction order as the scalar-row path. +template +__global__ void mhc_partial_rows4_kernel(const uint16_t* h, const float* fn, Out out, int width, + int mix, int chunk0, long hp, long fp, long rows) { + __shared__ float sums[4][4]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int j = blockIdx.y, chunk = chunk0 + blockIdx.x; + const long first = (long)blockIdx.z * 4; + float sum[4] = { 0, 0, 0, 0 }; + for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) { + const float weight = j == mix ? 0 : fn[(long)j * fp + i]; +#pragma unroll + for (int r = 0; r < 4; ++r) + if (first + r < rows) { + const float v = bf16_to_f32(h[(first + r) * hp + i]); + sum[r] += v * (j == mix ? v : weight); + } + } +#pragma unroll + for (int r = 0; r < 4; ++r) { + sum[r] = warp_sum(sum[r]); + if (!lane) sums[r][wave] = sum[r]; + } + __syncthreads(); + if (!tid) + for (int r = 0; r < 4; ++r) + if (first + r < rows) { + *out.at(first + r, j, chunk) = sums[r][0] + sums[r][1] + sums[r][2] + sums[r][3]; + if (j == mix) out.pad(first + r, mix, chunk); + } +} + +// Reuse each input across four coefficients and each weight across four rows. +// All per-output K accumulation and reduction orders match the rows4 path. +template +__global__ void mhc_partial_rows4_coeff4_kernel(const uint16_t* h, const float* fn, Out out, + int width, int mix, int chunk0, long hp, long fp, + long rows) { + __shared__ float sums[4][4][4]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int first_j = blockIdx.y * 4, chunk = chunk0 + blockIdx.x; + const long first = (long)blockIdx.z * 4; + float sum[4][4]{}; + for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) { + float weight[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) + weight[q] = first_j + q < mix ? fn[(long)(first_j + q) * fp + i] : 0; +#pragma unroll + for (int r = 0; r < 4; ++r) + if (first + r < rows) { + const float v = bf16_to_f32(h[(first + r) * hp + i]); +#pragma unroll + for (int q = 0; q < 4; ++q) + if (first_j + q <= mix) sum[q][r] += v * (first_j + q == mix ? v : weight[q]); + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) + if (first_j + q <= mix) { +#pragma unroll + for (int r = 0; r < 4; ++r) { + sum[q][r] = warp_sum(sum[q][r]); + if (!lane) sums[q][r][wave] = sum[q][r]; + } + } + __syncthreads(); + if (tid < 16) { + const int q = tid / 4, r = tid % 4; + if (first_j + q <= mix && first + r < rows) { + *out.at(first + r, first_j + q, chunk) = + sums[q][r][0] + sums[q][r][1] + sums[q][r][2] + sums[q][r][3]; + if (first_j + q == mix) out.pad(first + r, mix, chunk); + } + } +} + +// The collapsed read x[i] = sum_j pre[j] * h[j*n + i] eight columns a thread, in 16-byte loads +// and stores. Each element keeps the scalar loop's order (from zero, j ascending), so its bits +// are the same; false when the rows are not 16-byte aligned, and the caller runs its own loop. +__device__ __forceinline__ bool mix_rows_vec(const uint16_t* hr, uint16_t* xr, const float* pre, + int n, int hc, int tid, int nt) { + if ((((uintptr_t)hr | (uintptr_t)xr) & 15) || (n & 7)) return false; + for (int i = tid * 8; i < n; i += nt * 8) { + float v[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + for (int j = 0; j < hc; ++j) { + const uint4 q = *reinterpret_cast(hr + (long)j * n + i); + const uint32_t w[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int e = 0; e < 8; ++e) + v[e] += pre[j] * bf16_to_f32((uint16_t)(w[e >> 1] >> (16 * (e & 1)))); + } + uint32_t o[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) + o[e] = (uint32_t)f32_to_bf16(v[2 * e]) | ((uint32_t)f32_to_bf16(v[2 * e + 1]) << 16); + *reinterpret_cast(xr + i) = uint4{ o[0], o[1], o[2], o[3] }; + } + return true; +} + +// The projection partials four slots a lane. The kernels above give each of 128 threads one slot +// s, the sum over the chunk's columns s, s+128, ... in order; here lane L holds slots 4L..4L+3, +// so a row is read 8 bytes and a weight 16 bytes a load, and one wave does a whole block's work. +// Their reduction is replayed exactly: warp_sum pairs slot l with l+16, l+8, l+4, l+2 and l+1, +// here lanes +4, +2, +1 and then the lane's own slots, and the four waves' sums, at lanes 0, 8, +// 16 and 24, are added in order. R rows and four coefficients a wave, four independent waves a +// block, no barrier. +template +__global__ __launch_bounds__(128) void mhc_partial_vec_kernel(const uint16_t* h, const float* fn, + Out out, int mix, int chunk0, + int count, long hp, long fp, + long rows, long items) { + const int lane = threadIdx.x & 31; + const long item = (long)blockIdx.x * 4 + (threadIdx.x >> 5); + if (item >= items) return; + const int groups = (mix + 4) / 4; + const int chunk = chunk0 + (int)(item % count); + const int first_j = (int)((item / count) % groups) * 4; + const long first = item / count / groups * R; + float acc[4][R][4]{}; + for (int t = 0; t < 16; ++t) { + const int col = chunk * 2048 + t * 128 + lane * 4; + float w[4][4]; +#pragma unroll + for (int q = 0; q < 4; ++q) { + const float4 v = + first_j + q < mix + ? *reinterpret_cast(fn + (long)(first_j + q) * fp + col) + : float4{ 0, 0, 0, 0 }; + w[q][0] = v.x; + w[q][1] = v.y; + w[q][2] = v.z; + w[q][3] = v.w; + } +#pragma unroll + for (int r = 0; r < R; ++r) + if (first + r < rows) { + const uint2 hv = *reinterpret_cast(h + (first + r) * hp + col); + const float v[4] = { bf16_to_f32((uint16_t)hv.x), + bf16_to_f32((uint16_t)(hv.x >> 16)), + bf16_to_f32((uint16_t)hv.y), + bf16_to_f32((uint16_t)(hv.y >> 16)) }; +#pragma unroll + for (int q = 0; q < 4; ++q) + if (first_j + q <= mix) { +#pragma unroll + for (int u = 0; u < 4; ++u) + acc[q][r][u] += v[u] * (first_j + q == mix ? v[u] : w[q][u]); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) + if (first_j + q <= mix) { +#pragma unroll + for (int r = 0; r < R; ++r) + if (first + r < rows) { + float c[4]; +#pragma unroll + for (int u = 0; u < 4; ++u) { + float a = acc[q][r][u]; + a += __shfl_down(a, 4, 32); + a += __shfl_down(a, 2, 32); + a += __shfl_down(a, 1, 32); + c[u] = a; + } + const float e0 = c[0] + c[2], e1 = c[1] + c[3], f = e0 + e1; + const float s1 = __shfl(f, 8, 32), s2 = __shfl(f, 16, 32), + s3 = __shfl(f, 24, 32); + if (!lane) { + *out.at(first + r, first_j + q, chunk) = f + s1 + s2 + s3; + if (first_j + q == mix) out.pad(first + r, mix, chunk); + } + } + } +} + +template +__global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* scale, + const float* base, uint16_t* x, float* post, float* comb, int n, + int hc, int iterations, float eps, float heps, long hp, long fp, + long xp, long pp, long cp, int chunks, In in) { + __shared__ float sums[8], inverse, coefficients[80], pre[8], c[64]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const long r = blockIdx.x; + const int width = hc * n, mix = hc * (hc + 2); + float ss = 0; + for (int i = tid; !chunks && i < width; i += 256) { + const float v = bf16_to_f32(h[r * hp + i]); + ss += v * v; + } + ss = warp_sum(ss); + if (!lane) sums[wave] = ss; + __syncthreads(); + if (!tid) { + float s = 0; + if (chunks) + for (int i = 0; i < chunks; ++i) s += *in.at(r, mix, i); + else + for (int i = 0; i < 8; ++i) s += sums[i]; + inverse = rsqrtf(s / (float)width + eps); + } + __syncthreads(); + for (int j = wave; j < mix; j += 8) { + float dot = 0; + if (chunks) + for (int i = lane; i < chunks; i += 32) dot += *in.at(r, j, i); + else + for (int i = lane; i < width; i += 32) + dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i]; + dot = warp_sum(dot); + if (!lane) coefficients[j] = dot * inverse; + } + __syncthreads(); + if (!tid) { + for (int j = 0; j < hc; ++j) { + pre[j] = 1.0f / (1.0f + expf(-(coefficients[j] * scale[0] + base[j]))) + heps; + post[r * pp + j] = + 2.0f / (1.0f + expf(-(coefficients[hc + j] * scale[1] + base[hc + j]))); + } + for (int j = 0; j < hc; ++j) { + float mx = -INFINITY; + for (int k = 0; k < hc; ++k) { + const int q = 2 * hc + j * hc + k; + c[j * hc + k] = coefficients[q] * scale[2] + base[q]; + mx = fmaxf(mx, c[j * hc + k]); + } + float sum = 0; + for (int k = 0; k < hc; ++k) { + c[j * hc + k] = expf(c[j * hc + k] - mx); + sum += c[j * hc + k]; + } + for (int k = 0; k < hc; ++k) c[j * hc + k] = c[j * hc + k] / sum + heps; + } + for (int it = 0; it < iterations; ++it) { + if (it) + for (int j = 0; j < hc; ++j) { + float sum = 0; + for (int k = 0; k < hc; ++k) sum += c[j * hc + k]; + for (int k = 0; k < hc; ++k) c[j * hc + k] /= sum + heps; + } + for (int k = 0; k < hc; ++k) { + float sum = 0; + for (int j = 0; j < hc; ++j) sum += c[j * hc + k]; + for (int j = 0; j < hc; ++j) c[j * hc + k] /= sum + heps; + } + } + for (int j = 0; j < hc * hc; ++j) comb[r * cp + j] = c[j]; + } + __syncthreads(); + if (VecX && mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return; + for (int i = tid; i < n; i += 256) { + float v = 0; + for (int j = 0; j < hc; ++j) v += pre[j] * bf16_to_f32(h[r * hp + j * n + i]); + x[r * xp + i] = f32_to_bf16(v); + } +} + +// One wave handles GLM's 4x4 Sinkhorn matrix. Keep row/column sums in the +// scalar reference order; the other rows never participate in these shuffles. +// Writes post and comb; returns pre[lane] in lanes 0..3. +template +__device__ __forceinline__ float glm_warp_mix(int lane, long row, const float* scale, + const float* base, float* post, float* comb, + int iterations, float eps, float heps, long pp, + long cp, const In& in) { + float inverse = 0; + if (!lane) { + float ss = 0; + for (int i = 0; i < 8; ++i) ss += *in.at(row, 24, i); + inverse = rsqrtf(ss / 16384.0f + eps); + } + inverse = __shfl(inverse, 0, 32); + float dot = 0; + if (lane < 24) { + float v[8]; + for (int i = 0; i < 8; ++i) v[i] = *in.at(row, lane, i); + // The existing eight-chunk warp reduction pairs 0/4, 2/6, 1/5, 3/7. + dot = ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7])); + } + const float coefficient = dot * inverse; + const float post_coefficient = __shfl(coefficient, (lane + 4) & 31, 32); + const float matrix_coefficient = __shfl(coefficient, (lane + 8) & 31, 32); + float pre = 0; + if (lane < 4) { + pre = 1.0f / (1.0f + expf(-(coefficient * scale[0] + base[lane]))) + heps; + post[row * pp + lane] = + 2.0f / (1.0f + expf(-(post_coefficient * scale[1] + base[4 + lane]))); + } + float value = lane < 16 ? matrix_coefficient * scale[2] + base[8 + lane] : 0; + const int row_base = lane & ~3, col = lane & 3; + float mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) mx = fmaxf(mx, __shfl(value, row_base + j, 32)); + value = expf(value - mx); + float sum = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) sum += __shfl(value, row_base + j, 32); + value = value / sum + heps; + for (int it = 0; it < iterations; ++it) { + if (it) { + sum = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) sum += __shfl(value, row_base + j, 32); + value /= sum + heps; + } + sum = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) sum += __shfl(value, col + 4 * j, 32); + value /= sum + heps; + } + if (lane < 16) comb[row * cp + lane] = value; + return pre; +} +template +__global__ void mhc_pre_glm_warp_kernel(const uint16_t* h, const float* scale, const float* base, + uint16_t* x, float* post, float* comb, int iterations, + float eps, float heps, long hp, long xp, long pp, long cp, + In in) { + const int lane = threadIdx.x; + const long row = blockIdx.x; + const float pre = + glm_warp_mix(lane, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in); + const float p0 = __shfl(pre, 0, 32), p1 = __shfl(pre, 1, 32), p2 = __shfl(pre, 2, 32), + p3 = __shfl(pre, 3, 32); + for (int i = lane; i < 4096; i += 32) { + float v = 0; + v += p0 * bf16_to_f32(h[row * hp + i]); + v += p1 * bf16_to_f32(h[row * hp + 4096 + i]); + v += p2 * bf16_to_f32(h[row * hp + 8192 + i]); + v += p3 * bf16_to_f32(h[row * hp + 12288 + i]); + x[row * xp + i] = f32_to_bf16(v); + } +} + +// The warp kernel's mix on wave 0, then the collapsed read over the whole block: one wave writing +// 4096 columns a row was most of a decode step's mhc_pre. +template +__global__ __launch_bounds__(256) void mhc_pre_glm_wide_kernel( + const uint16_t* h, const float* scale, const float* base, uint16_t* x, float* post, float* comb, + int iterations, float eps, float heps, long hp, long xp, long pp, long cp, In in) { + __shared__ float spre[4]; + const int tid = threadIdx.x; + const long row = blockIdx.x; + if (tid < 32) { + const float pre = + glm_warp_mix(tid, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in); + if (tid < 4) spre[tid] = pre; + } + __syncthreads(); + const float pre[4] = { spre[0], spre[1], spre[2], spre[3] }; + if (mix_rows_vec(h + row * hp, x + row * xp, pre, 4096, 4, tid, 256)) return; + for (int i = tid; i < 4096; i += 256) { + float v = 0; + v += pre[0] * bf16_to_f32(h[row * hp + i]); + v += pre[1] * bf16_to_f32(h[row * hp + 4096 + i]); + v += pre[2] * bf16_to_f32(h[row * hp + 8192 + i]); + v += pre[3] * bf16_to_f32(h[row * hp + 12288 + i]); + x[row * xp + i] = f32_to_bf16(v); + } +} + +__global__ void mhc_post_kernel(const uint16_t* x, const uint16_t* h, const float* post, + const float* comb, uint16_t* out, int n, int hc, long xp, long hp, + long pp, long cp, long op) { + const long r = blockIdx.y; + const int q = blockIdx.x * blockDim.x + threadIdx.x; + if (q >= n * hc) return; + const int k = q / n, i = q % n; + float v = 0; + for (int j = 0; j < hc; ++j) + v += comb[r * cp + j * hc + k] * bf16_to_f32(h[r * hp + j * n + i]); + v += post[r * pp + k] * bf16_to_f32(x[r * xp + i]); + out[r * op + q] = f32_to_bf16(v); +} + +// mhc_post at four streams, eight columns of every output stream a thread: each input word is +// loaded once instead of once per output stream. Every output keeps mhc_post_kernel's order. +__global__ void mhc_post_vec_kernel(const uint16_t* x, const uint16_t* h, const float* post, + const float* comb, uint16_t* out, int n, long xp, long hp, + long pp, long cp, long op) { + const long r = blockIdx.y; + const int i = (blockIdx.x * blockDim.x + threadIdx.x) * 8; + if (i >= n) return; + float hv[4][8], xv[8]; + auto unpack = [](const uint16_t* p, float* v) { + const uint4 q = *reinterpret_cast(p); + const uint32_t w[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int e = 0; e < 8; ++e) v[e] = bf16_to_f32((uint16_t)(w[e >> 1] >> (16 * (e & 1)))); + }; +#pragma unroll + for (int j = 0; j < 4; ++j) unpack(h + r * hp + (long)j * n + i, hv[j]); + unpack(x + r * xp + i, xv); +#pragma unroll + for (int k = 0; k < 4; ++k) { + float c[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) c[j] = comb[r * cp + j * 4 + k]; + const float pk = post[r * pp + k]; + uint32_t o[4]; +#pragma unroll + for (int e = 0; e < 8; e += 2) { + float v0 = 0, v1 = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + v0 += c[j] * hv[j][e]; + v1 += c[j] * hv[j][e + 1]; + } + v0 += pk * xv[e]; + v1 += pk * xv[e + 1]; + o[e >> 1] = (uint32_t)f32_to_bf16(v0) | ((uint32_t)f32_to_bf16(v1) << 16); + } + *reinterpret_cast(out + r * op + (long)k * n + i) = uint4{ o[0], o[1], o[2], o[3] }; + } +} + +__global__ void mhc_contract_kernel(const uint16_t* h, uint16_t* x, int n, int hc, long hp, + long xp) { + const long r = blockIdx.y; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float v = 0; + for (int j = 0; j < hc; ++j) v += bf16_to_f32(h[r * hp + j * n + i]); + x[r * xp + i] = f32_to_bf16(v / (float)hc); +} + +bool matrix(const RadTensor& t, uint32_t dt, long rows, long cols) { + return t.data && t.dtype == dt && t.rank == 2 && t.shape[0] == rows && t.shape[1] == cols && + t.stride[1] == 1 && t.stride[0] >= cols; +} +bool vector(const RadTensor& t, long n) { + return t.data && t.dtype == RAD_F32 && t.rank == 1 && t.shape[0] == n && t.stride[0] == 1; +} +bool geometry(const RadArgs* a, int* n, int* hc) { + const long nn = r4d_geti_or(a, "n", 0), hh = r4d_geti_or(a, "hc", 0); + if (nn < 1 || nn > 16384 || hh < 2 || hh > 8) return false; + *n = (int)nn; + *hc = (int)hh; + return true; +} +// GLM's split projection: eight 2048-column chunks of the 16384-wide residual, 24 coefficients +// and the sum of squares each. A Dense chunk holds those 25 partials in kPartStride slots. +constexpr int kChunkCols = 2048, kPartStride = 28; +template +int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out out, int n, int hc, + int chunk0, int count, long rows) { + const char* rows4 = std::getenv("RADIANCE_MHC_PREFILL_ROWS4"); + const char* coeff4 = std::getenv("RADIANCE_MHC_PREFILL_COEFF4"); + /* From 2 rows the four-slot form (RADIANCE_MHC_PARTIAL_VEC 0 off, 1 at every row count; + * RADIANCE_MHC_PARTIAL_ROWS 1, 2 or 4 pins its rows a wave), on 16-byte weight and 8-byte + * residual rows; GLM's 2048-column chunks only. Measured cold on gfx1201 at GLM's shape: + * one row a wave leads up to 16 rows (13 us against the old 20 to 36), two rows from 48 + * (20 against 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave + * trail two at every count. */ + const char* vec = std::getenv("RADIANCE_MHC_PARTIAL_VEC"); + const bool vec_aligned = ((uintptr_t)fn.data & 15) == 0 && fn.stride[0] % 4 == 0 && + ((uintptr_t)h.data & 7) == 0 && h.stride[0] % 4 == 0 && + hc * n % kChunkCols == 0; + if (vec_aligned && (vec ? vec[0] == '1' : rows >= 2)) { + const char* pin_rows = std::getenv("RADIANCE_MHC_PARTIAL_ROWS"); + const long R = pin_rows && *pin_rows ? std::strtol(pin_rows, nullptr, 10) + : rows >= 32 ? 2 + : 1; + const int mix = hc * (hc + 2), groups = (mix + 4) / 4; +#define MHC_VEC(RR) \ + do { \ + const long items = (long)count * groups * ((rows + RR - 1) / RR); \ + return R4D_EMIT(stream, (mhc_partial_vec_kernel), \ + dim3((unsigned)((items + 3) / 4)), dim3(128), 0, (const uint16_t*)h.data, \ + (const float*)fn.data, out, mix, chunk0, count, (long)h.stride[0], \ + (long)fn.stride[0], rows, items); \ + } while (0) + if (R == 4) MHC_VEC(4); + if (R == 2) MHC_VEC(2); + MHC_VEC(1); +#undef MHC_VEC + } + const char* rows4_min = std::getenv("RADIANCE_MHC_ROWS4_MIN"); + const bool use_rows4 = + (!rows4 || rows4[0] == '1') && + rows >= (rows4_min && *rows4_min ? std::strtol(rows4_min, nullptr, 10) : 32); + if (use_rows4 && (!coeff4 || coeff4[0] == '1')) + return R4D_EMIT(stream, (mhc_partial_rows4_coeff4_kernel), + dim3(count, (hc * (hc + 2) + 4) / 4, (unsigned)((rows + 3) / 4)), dim3(128), + 0, (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, + hc * (hc + 2), chunk0, (long)h.stride[0], (long)fn.stride[0], rows); + if (use_rows4) + return R4D_EMIT(stream, (mhc_partial_rows4_kernel), + dim3(count, hc * (hc + 2) + 1, (unsigned)((rows + 3) / 4)), dim3(128), 0, + (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2), + chunk0, (long)h.stride[0], (long)fn.stride[0], rows); + return R4D_EMIT(stream, (mhc_partial_kernel), + dim3(count, hc * (hc + 2) + 1, (unsigned)rows), dim3(128), 0, + (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2), + chunk0, (long)h.stride[0], (long)fn.stride[0]); +} +// The finishing dispatch. `split` says the partials exist (in `in`); without them +// mhc_pre_kernel projects the residual itself from `fn`. +template +int emit_finish(RadStream stream, const RadTensor& h, const float* fn, long fp, const RadTensor& s, + const RadTensor& b, const RadTensor& x, const RadTensor& p, const RadTensor& c, + int n, int hc, int iters, float eps, float heps, long rows, int chunks, bool split, + In in) { + const char* warp = std::getenv("RADIANCE_MHC_PREFILL_WARP"); + /* The warp mix at every row count: byte-identical to the scalar one and a quarter of its time + * at one to six rows. RADIANCE_MHC_FINISH, for the microbenchmark: `old` the one-wave finish + * from 32 rows and the scalar mix and read below, `scalar` that mix with the wide read. */ + const char* form = std::getenv("RADIANCE_MHC_FINISH"); + const bool old = form && !std::strcmp(form, "old"); + const bool warp_mix = split && (warp ? warp[0] == '1' : true) && + (old ? rows >= 32 : !(form && !std::strcmp(form, "scalar"))); + if (warp_mix && old) + return R4D_EMIT(stream, (mhc_pre_glm_warp_kernel), dim3((unsigned)rows), dim3(32), 0, + (const uint16_t*)h.data, (const float*)s.data, (const float*)b.data, + (uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps, + (long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], + in); + if (warp_mix) + return R4D_EMIT(stream, (mhc_pre_glm_wide_kernel), dim3((unsigned)rows), dim3(256), 0, + (const uint16_t*)h.data, (const float*)s.data, (const float*)b.data, + (uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps, + (long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], + in); + if (old) + return R4D_EMIT(stream, (mhc_pre_kernel), dim3((unsigned)rows), dim3(256), 0, + (const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data, + (uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps, + (long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], + (long)c.stride[0], split ? chunks : 0, in); + return R4D_EMIT(stream, (mhc_pre_kernel), dim3((unsigned)rows), dim3(256), 0, + (const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data, + (uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps, + (long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], + split ? chunks : 0, in); +} +bool coefficients(const RadArgs* a, long* iters, float* eps, float* heps) { + *iters = r4d_geti_or(a, "iterations", 0); + *eps = (float)r4d_getf(a, "eps", 0); + *heps = (float)r4d_getf(a, "hc_eps", 0); + return *iters >= 1 && *iters <= 256 && std::isfinite(*eps) && std::isfinite(*heps) && + *eps > 0 && *heps >= 0; +} +// mhc_pre_partial and mhc_pre_finish serve GLM's split geometry only. +bool glm_chunks(const RadArgs* a, int n, int hc) { + return n == 4096 && hc == 4 && r4d_geti_or(a, "chunk", 0) == kChunkCols; +} +int pre_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc)) return RAD_E_SHAPE; + long iters; + float eps, heps; + if (!coefficients(a, &iters, &eps, &heps)) return RAD_E_SHAPE; + const auto &h = a->t[0], &fn = a->t[1], &s = a->t[2], &b = a->t[3]; + const auto &x = a->t[4], &p = a->t[5], &c = a->t[6]; + if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > INT_MAX) return RAD_E_SHAPE; + const long rows = h.shape[0]; + if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(fn, RAD_F32, hc * (hc + 2), hc * n) || + !vector(s, 3) || !vector(b, hc * (hc + 2)) || !matrix(x, RAD_BF16, rows, n) || + !matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc)) + return RAD_E_SHAPE; + const int chunks = (hc * n + kChunkCols - 1) / kChunkCols; + const bool split = + n == 4096 && hc == 4 && rows <= 65535 && (hc * (hc + 2) + 1) * chunks * 4 + 2 <= n * 2; + const InX in{ (uint16_t*)x.data, (long)x.stride[0], chunks }; + if (split) { + const int rc = emit_partials(stream, h, fn, in, n, hc, 0, chunks, rows); + if (rc < 0) return rc; + } + return emit_finish(stream, h, (const float*)fn.data, (long)fn.stride[0], s, b, x, p, c, n, hc, + (int)iters, eps, heps, rows, chunks, split, in); +} +int partial_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc) || !glm_chunks(a, n, hc)) return RAD_E_SHAPE; + const int total = hc * n / kChunkCols; + const long first = r4d_geti_or(a, "first", -1), count = r4d_geti_or(a, "chunks", 0); + if (first < 0 || count < 1 || first + count > total) return RAD_E_SHAPE; + const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2]; + if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE; + const long rows = h.shape[0]; + if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(fn, RAD_F32, hc * (hc + 2), hc * n) || + !matrix(part, RAD_F32, rows, count * kPartStride)) + return RAD_E_SHAPE; + const Dense out{ (float*)part.data, (long)part.stride[0], kPartStride, (int)first }; + return emit_partials(stream, h, fn, out, n, hc, (int)first, (int)count, rows); +} +int finish_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc) || !glm_chunks(a, n, hc)) return RAD_E_SHAPE; + long iters; + float eps, heps; + if (!coefficients(a, &iters, &eps, &heps)) return RAD_E_SHAPE; + const int chunks = hc * n / kChunkCols; + const auto &part = a->t[0], &h = a->t[1], &s = a->t[2], &b = a->t[3]; + const auto &x = a->t[4], &p = a->t[5], &c = a->t[6]; + if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE; + const long rows = h.shape[0]; + if (!matrix(part, RAD_F32, rows, chunks * kPartStride) || !matrix(h, RAD_BF16, rows, hc * n) || + !vector(s, 3) || !vector(b, hc * (hc + 2)) || !matrix(x, RAD_BF16, rows, n) || + !matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc)) + return RAD_E_SHAPE; + const Dense in{ (float*)part.data, (long)part.stride[0], kPartStride, 0 }; + return emit_finish(stream, h, nullptr, 0, s, b, x, p, c, n, hc, (int)iters, eps, heps, rows, + chunks, true, in); +} +int post_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc)) return RAD_E_SHAPE; + const auto &x = a->t[0], &h = a->t[1], &p = a->t[2], &c = a->t[3], &o = a->t[4]; + if (x.rank != 2 || x.shape[0] < 1 || x.shape[0] > 65535) return RAD_E_SHAPE; + const long rows = x.shape[0]; + if (!matrix(x, RAD_BF16, rows, n) || !matrix(h, RAD_BF16, rows, hc * n) || + !matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc) || + !matrix(o, RAD_BF16, rows, hc * n) || o.data == h.data) + return RAD_E_SHAPE; + /* RADIANCE_MHC_POST_VEC=0 keeps the per-output kernel, for the microbenchmark. */ + const char* vec = std::getenv("RADIANCE_MHC_POST_VEC"); + const auto aligned = [](const RadTensor& t) { + return ((uintptr_t)t.data & 15) == 0 && t.stride[0] % 8 == 0; + }; + if ((!vec || vec[0] == '1') && hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o)) + return R4D_EMIT(stream, mhc_post_vec_kernel, dim3((n / 8 + 255) / 256, (unsigned)rows), + dim3(256), 0, (const uint16_t*)x.data, (const uint16_t*)h.data, + (const float*)p.data, (const float*)c.data, (uint16_t*)o.data, n, + (long)x.stride[0], (long)h.stride[0], (long)p.stride[0], (long)c.stride[0], + (long)o.stride[0]); + return R4D_EMIT(stream, mhc_post_kernel, dim3((n * hc + 255) / 256, (unsigned)rows), dim3(256), + 0, (const uint16_t*)x.data, (const uint16_t*)h.data, (const float*)p.data, + (const float*)c.data, (uint16_t*)o.data, n, hc, (long)x.stride[0], + (long)h.stride[0], (long)p.stride[0], (long)c.stride[0], (long)o.stride[0]); +} +int contract_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 2) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc)) return RAD_E_SHAPE; + const auto &h = a->t[0], &x = a->t[1]; + if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE; + const long rows = h.shape[0]; + if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(x, RAD_BF16, rows, n)) return RAD_E_SHAPE; + return R4D_EMIT(stream, mhc_contract_kernel, dim3((n + 255) / 256, (unsigned)rows), dim3(256), + 0, (const uint16_t*)h.data, (uint16_t*)x.data, n, hc, (long)h.stride[0], + (long)x.stride[0]); +} +} +extern "C" int r4d_rad_mhc_pre(const RadArgs* a, RadStream stream) { return pre_body(a, stream); } +extern "C" int r4d_rad_mhc_pre_partial(const RadArgs* a, RadStream stream) { + return partial_body(a, stream); +} +extern "C" int r4d_rad_mhc_pre_finish(const RadArgs* a, RadStream stream) { + return finish_body(a, stream); +} +extern "C" int r4d_rad_mhc_post(const RadArgs* a, RadStream stream) { return post_body(a, stream); } +extern "C" int r4d_rad_mhc_contract(const RadArgs* a, RadStream stream) { + return contract_body(a, stream); +} diff --git a/libr4d/r4d_mla.hip b/libr4d/r4d_mla.hip new file mode 100644 index 00000000..710c1a35 --- /dev/null +++ b/libr4d/r4d_mla.hip @@ -0,0 +1,700 @@ +/* Absorbed MLA keeps a single 512-wide latent per token. Decode splits the + * selected history across waves, then merges FP32 softmax statistics. It never + * materializes per-head K/V in the growing cache. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_gdn_wmma.h" +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct ProjectMeta { + long xr, xh, wp, yr, yh; + int rows, heads; +}; +/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. */ +__global__ void project_absorb(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { + const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r = blockIdx.z; + if (col >= 512) return; + float sum = 0; + for (int j = 0; j < 256; ++j) + sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]), + bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]), sum); + y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum); +} +__global__ void project_expand(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { + const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, + r = blockIdx.z; + float sum = 0; + for (int j = lane; j < 512; j += 32) + sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]), + bf16_to_f32(w[((long)head * 512 + 256 + col) * m.wp + j]), sum); +#pragma unroll + for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + if (!lane) y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum); +} +/* project_absorb and project_expand with R rows a thread (absorb) or a wave (expand): each weight + * element is loaded once for R rows. Every row's sum runs over j in the same order, and + * r4d_xor_sum<32> exchanges as the shuffle loop does, so the bytes match the one-row kernels. + * A tail group past the last row reads that row again and stores nothing for it. */ +template +__global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16_t* y, + ProjectMeta m) { + const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r0 = blockIdx.z * R; + if (col >= 512) return; + const uint16_t* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh; + float sum[R]; +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = 0; + for (int j = 0; j < 256; ++j) { + const float wv = bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]); +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]); + } +#pragma unroll + for (int r = 0; r < R; ++r) + if (r0 + r < m.rows) y[(long)(r0 + r) * m.yr + head * m.yh + col] = f32_to_bf16(sum[r]); +} +template +__global__ void project_expand_rows(const uint16_t* x, const uint16_t* w, uint16_t* y, + ProjectMeta m) { + const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, + r0 = blockIdx.z * R; + const uint16_t* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh; + const uint16_t* const wr = w + ((long)head * 512 + 256 + col) * m.wp; + float sum[R]; +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = 0; + for (int j = lane; j < 512; j += 32) { + const float wv = bf16_to_f32(wr[j]); +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]); + } + float mine = 0; +#pragma unroll + for (int r = 0; r < R; ++r) { + sum[r] = r4d_xor_sum<32>(sum[r]); + if (lane == r) mine = sum[r]; + } + if (lane < R && r0 + lane < m.rows) + y[(long)(r0 + lane) * m.yr + head * m.yh + col] = f32_to_bf16(mine); +} +int project_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + RadTensor x = a->t[0], y = a->t[2]; + const auto& w = a->t[1]; + const char* mode = r4d_gets(a, "mode"); + const bool absorb = mode && !std::strcmp(mode, "absorb"), + expand = mode && !std::strcmp(mode, "expand"); + const long h = r4d_geti_or(a, "heads", 0); + auto heads_view = [&](RadTensor& t, long width) { + if (h > 0 && t.rank == 2 && t.shape[1] == h * width) { + t.rank = 3; + t.shape[1] = h; + t.shape[2] = width; + t.stride[2] = t.stride[1]; + t.stride[1] *= width; + } + }; + heads_view(x, absorb ? 256 : 512); + heads_view(y, absorb ? 512 : 256); + if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE; + if (!x.data || !w.data || !y.data) return RAD_E_INVAL; + if ((!absorb && !expand) || h < 1 || h > 64 || r4d_geti_or(a, "head_dim", 0) != 256 || + r4d_geti_or(a, "latent_dim", 0) != 512 || x.rank != 3 || w.rank != 2 || y.rank != 3 || + x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != h || + x.shape[2] != (absorb ? 256 : 512) || w.shape[0] != h * 512 || w.shape[1] != 512 || + y.shape[0] != x.shape[0] || y.shape[1] != h || y.shape[2] != (absorb ? 512 : 256) || + x.stride[2] != 1 || w.stride[1] != 1 || y.stride[2] != 1 || x.stride[1] < x.shape[2] || + x.stride[0] < h * x.stride[1] || w.stride[0] < 512 || y.stride[1] < y.shape[2] || + y.stride[0] < h * y.stride[1]) + return RAD_E_SHAPE; + const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0], + y.stride[1], (int)x.shape[0], (int)h }; + /* RADIANCE_MLA_PROJECT: `old` the one-row kernels on shuffle sums, the reference the selftest + * holds the row forms to byte for byte; 1, 2, 4 or 8 pins the rows a thread (absorb) or a + * wave (expand). */ + const char* form = std::getenv("RADIANCE_MLA_PROJECT"); + const auto* xp = (const uint16_t*)x.data; + const auto* wp = (const uint16_t*)w.data; + auto* yp = (uint16_t*)y.data; + if (form && !std::strcmp(form, "old")) { + if (absorb) + return R4D_EMIT(stream, project_absorb, dim3(4, h, m.rows), dim3(128), 0, xp, wp, yp, + m); + return R4D_EMIT(stream, project_expand, dim3(64, h, m.rows), dim3(128), 0, xp, wp, yp, m); + } + const long R = form && *form ? std::strtol(form, nullptr, 10) + : m.rows >= 8 ? 8 + : m.rows >= 4 ? 4 + : m.rows >= 2 ? 2 + : 1; +#define MLA_PROJECT_ROWS(RR) \ + do { \ + const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \ + if (absorb) \ + return R4D_EMIT(stream, (project_absorb_rows), dim3(4, h, groups), dim3(128), 0, \ + xp, wp, yp, m); \ + return R4D_EMIT(stream, (project_expand_rows), dim3(64, h, groups), dim3(128), 0, xp, \ + wp, yp, m); \ + } while (0) + if (R == 8) MLA_PROJECT_ROWS(8); + if (R == 4) MLA_PROJECT_ROWS(4); + if (R == 2) MLA_PROJECT_ROWS(2); + MLA_PROJECT_ROWS(1); +#undef MLA_PROJECT_ROWS +} +constexpr int D = 512, PART = D + 2; +constexpr int64_t scratch_bytes = 512ll * PART * 4; +constexpr int64_t matrix_scratch_bytes = 2048ll * PART * 4; +/* r4d_mla_matrix_pin_form: 0 is the launcher's rule (vector key loads where the cache is + * aligned), 1 the element-wise key load. */ +int g_mla_matrix_form = 0; +struct Meta { + long qr, qh, kp, kt, bp, bc, lp, orr, oh; + int rows, heads, blocks, bs, pages, splits; + float scale; +}; +/* RADIANCE_MLA_CONFLICT_STATS: per device, the 16-token passes the matrix row ran, how many of them + * were a pair's second pass, and the chunks of the max(length) raster a pass-free pairing would + * run. Read back by r4d_mla_matrix_stats, and printed every 1024th counted launch. */ +__device__ unsigned long long g_mla_stats[3]; +__device__ void load_latent(const uint16_t* p, float (&v)[16]) { + if (!((uintptr_t)p & 15)) { + const uint4 a = *(const uint4*)p, b = *(const uint4*)(p + 8); + const uint32_t packed[8] = { a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w }; +#pragma unroll + for (int j = 0; j < 16; ++j) + v[j] = bf16_to_f32((uint16_t)(packed[j / 2] >> (16 * (j & 1)))); + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) v[j] = bf16_to_f32(p[j]); + } +} +__global__ __launch_bounds__(128) void attend(const uint16_t* q, const uint16_t* kv, const int* bt, + const int* len, uint16_t* out, float* scratch, + Meta m) { + const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x, + split = blockIdx.z; + if (head >= m.heads) return; + const int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs); + const int begin = (int)((long)live * split / m.splits), + end = (int)((long)live * (split + 1) / m.splits); + float query[16], value[16] = {}; + load_latent(q + (long)r * m.qr + (long)head * m.qh + lane * 16, query); + float max_score = -INFINITY, den = 0; + for (int token = begin; token < end; ++token) { + const int page = bt[(long)r * m.bp + (token / m.bs) * m.bc]; + if (page < 0 || page >= m.pages) continue; + float key[16]; + load_latent(kv + (long)page * m.kp + (token % m.bs) * m.kt + lane * 16, key); + float score = 0; +#pragma unroll + for (int j = 0; j < 16; ++j) score += query[j] * key[j]; + score = r4d_wave_sum(score) * m.scale; + const bool higher = score > max_score; + const float weight = expf(higher ? max_score - score : score - max_score); + if (higher) { +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] = value[j] * weight + key[j]; + den = den * weight + 1; + max_score = score; + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] += key[j] * weight; + den += weight; + } + } + if (m.splits == 1) { +#pragma unroll + for (int j = 0; j < 16; ++j) + out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] = + f32_to_bf16(den > 0 ? value[j] / den : 0); + } else { + float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART; +#pragma unroll + for (int j = 0; j < 16; ++j) dst[lane * 16 + j] = value[j]; + if (!lane) { + dst[D] = max_score; + dst[D + 1] = den; + } + } +} +__global__ __launch_bounds__(128) void merge(const float* scratch, uint16_t* out, Meta m) { + const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x; + if (head >= m.heads) return; + const float* src = scratch + ((long)r * m.heads + head) * m.splits * PART; + float max_score = -INFINITY; + for (int s = 0; s < m.splits; ++s) + if (src[s * PART + D + 1] > 0) max_score = fmaxf(max_score, src[s * PART + D]); + float value[16] = {}, den = 0; + for (int s = 0; s < m.splits; ++s) { + const float part_den = src[s * PART + D + 1]; + if (!(part_den > 0)) continue; + const float w = expf(src[s * PART + D] - max_score); + den += part_den * w; +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] += src[s * PART + lane * 16 + j] * w; + } +#pragma unroll + for (int j = 0; j < 16; ++j) + out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] = + f32_to_bf16(den > 0 ? value[j] / den : 0); +} +/* Heads are the matrix rows, so all sixteen share each latent load even when + * each query selected different pages. Splitting P into BF16 high/low parts + * preserves FP32 softmax precision without a materialized per-head KV cache. + * + * PAIR fills the sixteen rows with eight heads of two neighbouring requests + * (rows 0-7 request r, rows 8-15 request r+1). A key is loaded once when both + * requests address the same cache row at that table position, as consecutive + * queries of one sequence do; each half masks columns that are not its own, + * which carries the causal edge. Where the two tables name different rows the + * chunk runs a second pass with the second request's keys. + * + * UNION pairs by page instead of by position: past the DSA budget each request + * selects its own blocks, neighbours share most of them at shifted positions, + * and the positional pairing would run nearly every chunk twice. The walk is + * request r's table in its own order (so r sums exactly as it does unpaired at + * one split), each entry carrying where r+1's table names the same page, then + * the pages only r+1 names, in r+1's order. Every chunk runs once. */ +constexpr int kUnionBlocks = 520, kUnionSlots = 1024; +__device__ __forceinline__ unsigned union_slot(int page) { + return ((unsigned)page * 2654435761u) >> 22; +} +/* STATS is its own instance: counting inside the loop costs the paired tile spilled VGPRs. */ +template +__global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const uint16_t* kv, + const int* bt, const int* len, uint16_t* out, + float* scratch, Meta m) { + static_assert(PAIR || !UNION, "the union pairs two requests"); + static_assert(16 * 520 * sizeof(uint16_t) >= (2 * kUnionSlots + 2 * kUnionBlocks) * sizeof(int), + "the union's hash lives in the key tile"); + __shared__ __align__(16) uint16_t query[16 * 520], keys[16 * 520], prob_hi[16 * 24], + prob_lo[16 * 24]; + __shared__ float score[16 * 16], maximum[16], denominator[16], alpha[16]; + __shared__ long source[16]; + __shared__ long own[PAIR ? 32 : 1]; + __shared__ short pair_of[UNION ? kUnionBlocks : 1], only_b[UNION ? kUnionBlocks : 1]; + __shared__ int union_count[UNION ? 4 : 1], union_end; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int r = PAIR ? blockIdx.x * 2 : blockIdx.x, h0 = blockIdx.y * (PAIR ? 8 : 16), + split = blockIdx.z; + int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs), live_pair[2] = { live, 0 }; + if constexpr (PAIR) { + if (r + 1 < m.rows) live_pair[1] = min(max(len[(long)(r + 1) * m.lp], 0), m.blocks * m.bs); + live = max(live_pair[0], live_pair[1]); + } + for (int j = tid; j < 16 * 512; j += 128) { + if constexpr (PAIR) { + const int row = j / 512, request = r + row / 8; + query[row * 520 + j % 512] = + request < m.rows ? q[(long)request * m.qr + (long)(h0 + row % 8) * m.qh + j % 512] + : 0; + } else + query[(j / 512) * 520 + j % 512] = + q[(long)r * m.qr + (long)(h0 + j / 512) * m.qh + j % 512]; + } + if (tid < 16) { + maximum[tid] = -INFINITY; + denominator[tid] = 0; + } + v8f value[8]; +#pragma unroll + for (int nt = 0; nt < 8; ++nt) value[nt] = (v8f){ 0 }; + const int* const bt_a = bt + (long)r * m.bp; + const int* const bt_b = bt + (long)(r + 1) * m.bp; + int blocks_a = 0; + if constexpr (UNION) { + /* The key tile is free until the first chunk: an open-addressed page -> lowest r entry + * hash, the lowest r+1 entry naming each r entry's page, and each r+1 entry's match. */ + int* const slot_page = (int*)keys; + int* const slot_first = slot_page + kUnionSlots; + int* const first_b = slot_first + kUnionSlots; + int* const match = first_b + kUnionBlocks; + blocks_a = (live_pair[0] + m.bs - 1) / m.bs; + const int blocks_b = (live_pair[1] + m.bs - 1) / m.bs; + for (int i = tid; i < kUnionSlots; i += 128) { + slot_page[i] = -1; + slot_first[i] = INT_MAX; + } + for (int i = tid; i < blocks_a; i += 128) first_b[i] = INT_MAX; + if (!tid) union_end = live_pair[0]; + __syncthreads(); + for (int i = tid; i < blocks_a; i += 128) { + const int page = bt_a[(long)i * m.bc]; + if (page < 0 || page >= m.pages) continue; + for (unsigned at = union_slot(page);; at = (at + 1) & (kUnionSlots - 1)) { + const int seen = atomicCAS(&slot_page[at], -1, page); + if (seen == -1 || seen == page) { + atomicMin(&slot_first[at], i); + break; + } + } + } + __syncthreads(); + for (int j = tid; j < blocks_b; j += 128) { + const int page = bt_b[(long)j * m.bc]; + int found = -1; + if (page >= 0 && page < m.pages) + for (unsigned at = union_slot(page); slot_page[at] != -1; + at = (at + 1) & (kUnionSlots - 1)) + if (slot_page[at] == page) { + found = slot_first[at]; + break; + } + match[j] = found; + if (found >= 0) atomicMin(&first_b[found], j); + } + __syncthreads(); + for (int i = tid; i < blocks_a; i += 128) + pair_of[i] = (short)(first_b[i] == INT_MAX ? -1 : first_b[i]); + /* r+1's own pages in its table order: slots from a ballot prefix, not an atomic, so the + * walk (and the summation order) is the same on every run. */ + int appended = 0; + for (int j0 = 0; j0 < blocks_b; j0 += 128) { + const int j = j0 + tid; + bool only = false; + if (j < blocks_b) { + const int page = bt_b[(long)j * m.bc]; + only = page >= 0 && page < m.pages && (match[j] < 0 || first_b[match[j]] != j); + } + const unsigned long long ballot = __ballot(only); + if (!lane) union_count[wave] = (int)__popcll(ballot); + __syncthreads(); + int before = appended, total = appended; +#pragma unroll + for (int w = 0; w < 4; ++w) { + before += w < wave ? union_count[w] : 0; + total += union_count[w]; + } + if (only) { + const int at = before + (int)__popcll(ballot & ((1ull << lane) - 1ull)); + only_b[at] = (short)j; + const int seen = min(m.bs, live_pair[1] - j * m.bs); + atomicMax(&union_end, (blocks_a + at) * m.bs + seen); + } else if (j < blocks_b && match[j] >= 0 && first_b[match[j]] == j) + atomicMax(&union_end, match[j] * m.bs + min(m.bs, live_pair[1] - j * m.bs)); + appended = total; + __syncthreads(); + } + live = union_end; + } + const int begin = (int)((long)live * split / m.splits), + end = (int)((long)live * (split + 1) / m.splits); + __syncthreads(); + for (int start = begin; start < end; start += 16) { + bool second = false; + if constexpr (UNION) { + if (tid < 16) { + const int token = start + tid, entry = token / m.bs, offset = token % m.bs; + long row[2] = { -1, -1 }; + if (token < end) { + const int at_a = entry < blocks_a ? entry : -1; + const int at_b = entry < blocks_a ? pair_of[entry] : only_b[entry - blocks_a]; + const int page = at_a >= 0 ? bt_a[(long)at_a * m.bc] : bt_b[(long)at_b * m.bc]; + if (page >= 0 && page < m.pages) { + const long at = (long)page * m.kp + offset * m.kt; + if (at_a >= 0 && at_a * m.bs + offset < live_pair[0]) row[0] = at; + if (at_b >= 0 && at_b * m.bs + offset < live_pair[1]) row[1] = at; + } + } + own[tid] = row[0]; + own[16 + tid] = row[1]; + source[tid] = row[0] >= 0 ? row[0] : row[1]; + } + __syncthreads(); + } else if constexpr (PAIR) { + bool conflict = false; + if (tid < 16) { + const int token = start + tid; + long row[2]; +#pragma unroll + for (int k = 0; k < 2; ++k) { + const int page = token < end && token < live_pair[k] + ? bt[(long)(r + k) * m.bp + (token / m.bs) * m.bc] + : -1; + row[k] = page >= 0 && page < m.pages ? (long)page * m.kp + (token % m.bs) * m.kt + : -1; + own[k * 16 + tid] = row[k]; + } + source[tid] = row[0] >= 0 ? row[0] : row[1]; + conflict = row[0] >= 0 && row[1] >= 0 && row[0] != row[1]; + } + second = __syncthreads_or(conflict); + if (STATS && second && !tid) { + atomicAdd(&g_mla_stats[0], 1ull); + atomicAdd(&g_mla_stats[1], 1ull); + } + } else { + if (tid < 16) { + const int token = start + tid; + const int page = token < end ? bt[(long)r * m.bp + (token / m.bs) * m.bc] : -1; + source[tid] = + page >= 0 && page < m.pages ? (long)page * m.kp + (token % m.bs) * m.kt : -1; + } + __syncthreads(); + } + for (int pass = 0; pass < (second ? 2 : 1); ++pass) { + if constexpr (PAIR) + if (pass) { + if (tid < 16) { + const long first = own[tid], other = own[16 + tid]; + source[tid] = first >= 0 && other >= 0 && first != other ? other : -1; + } + __syncthreads(); + } + if constexpr (WIDE) { + /* Unconditional loads (an absent row reads row 0 and is zeroed after) so all + * eight are in flight before the first wait. */ + uint4 part[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int flat = tid + j * 128; + const long at = source[flat >> 6]; + part[j] = *(const uint4*)(kv + (at >= 0 ? at : 0) + (flat & 63) * 8); + if (at < 0) part[j] = make_uint4(0, 0, 0, 0); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int flat = tid + j * 128; + *(uint4*)(keys + (flat >> 6) * 520 + (flat & 63) * 8) = part[j]; + } + } else { + for (int j = tid; j < 16 * 512; j += 128) { + const int token = j / 512, col = j % 512; + keys[token * 520 + col] = source[token] >= 0 ? kv[source[token] + col] : 0; + } + } + __syncthreads(); + if (!wave) { + v8f dot = { 0 }; +#pragma unroll + for (int d = 0; d < 512; d += 16) + dot = mma(frag(query, 520, 0, d, lane), frag(keys, 520, 0, d, lane), dot); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int head = (lane >> 4) * 8 + j, col = lane & 15; + bool visible = source[col] >= 0; + if constexpr (PAIR) + visible = visible && own[(lane >> 4) * 16 + col] == source[col]; + score[head * 16 + col] = visible ? dot[j] * m.scale : -INFINITY; + } + } + __syncthreads(); + if (tid < 16) { + float mx = maximum[tid]; + for (int j = 0; j < 16; ++j) mx = fmaxf(mx, score[tid * 16 + j]); + const float a = isfinite(mx) ? expf(maximum[tid] - mx) : 1; + float den = denominator[tid] * a; + for (int j = 0; j < 16; ++j) { + const float p = + isfinite(score[tid * 16 + j]) ? expf(score[tid * 16 + j] - mx) : 0; + const uint16_t hi = f32_to_bf16(p); + prob_hi[tid * 24 + j] = hi; + prob_lo[tid * 24 + j] = f32_to_bf16(p - bf16_to_f32(hi)); + den += p; + } + maximum[tid] = mx; + denominator[tid] = den; + alpha[tid] = a; + } + // Read before the in-place transpose overwrites keys. Query remains resident. + uint16_t held[64]; +#pragma unroll + for (int j = 0; j < 64; ++j) { + const int flat = tid + j * 128; + held[j] = keys[(flat / 512) * 520 + flat % 512]; + } + __syncthreads(); +#pragma unroll + for (int j = 0; j < 64; ++j) { + const int flat = tid + j * 128; + keys[(flat % 512) * 16 + flat / 512] = held[j]; + } + __syncthreads(); + const auto hi = frag(prob_hi, 24, 0, 0, lane), lo = frag(prob_lo, 24, 0, 0, lane); +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { +#pragma unroll + for (int j = 0; j < 8; ++j) value[nt][j] *= alpha[(lane >> 4) * 8 + j]; + const auto v = frag(keys, 16, wave * 128 + nt * 16, 0, lane); + value[nt] = mma(hi, v, value[nt]); + value[nt] = mma(lo, v, value[nt]); + } + __syncthreads(); + } + } +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { + const int col = wave * 128 + nt * 16 + (lane & 15); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int row = (lane >> 4) * 8 + j, request = PAIR ? r + (lane >> 4) : r, + head = PAIR ? h0 + j : h0 + row; + if (PAIR && request >= m.rows) continue; + if (m.splits == 1) { + const float den = denominator[row]; + out[(long)request * m.orr + (long)head * m.oh + col] = + f32_to_bf16(den > 0 ? value[nt][j] / den : 0); + } else + scratch[(((long)request * m.heads + head) * m.splits + split) * PART + col] = + value[nt][j]; + } + } + if (m.splits > 1 && tid < 16) { + const int request = PAIR ? r + tid / 8 : r, head = PAIR ? h0 + tid % 8 : h0 + tid; + if (!PAIR || request < m.rows) { + float* dst = scratch + (((long)request * m.heads + head) * m.splits + split) * PART; + dst[D] = maximum[tid]; + dst[D + 1] = denominator[tid]; + } + } + if (STATS && !tid) { + const int whole = max(live_pair[0], live_pair[1]); + const int raster = + (int)((long)whole * (split + 1) / m.splits) - (int)((long)whole * split / m.splits); + const unsigned long long chunks = (unsigned long long)(end - begin + 15) / 16; + atomicAdd(&g_mla_stats[0], chunks); + atomicAdd(&g_mla_stats[2], (unsigned long long)(raster + 15) / 16); + } +} +bool env_on(const char* name) { + const char* e = std::getenv(name); + return e && *e && *e != '0'; +} +void read_stats(unsigned long long (&v)[3], bool reset) { + v[0] = v[1] = v[2] = 0; + if (hipMemcpyFromSymbol(v, HIP_SYMBOL(g_mla_stats), sizeof v, 0, hipMemcpyDeviceToHost) != + hipSuccess) + return; + const unsigned long long zero[3] = {}; + if (reset) + (void)hipMemcpyToSymbol(HIP_SYMBOL(g_mla_stats), zero, sizeof zero, 0, + hipMemcpyHostToDevice); +} +/* A server has no point at which to read the counters: running totals every 1024th counted launch. + * Not at exit, where a HIP call meets a runtime that is tearing down; not inside a graph capture, + * which a blocking copy would break. */ +void report_stats(RadStream stream) { + static std::atomic launches{ 0 }; + if (++launches % 1024) return; + hipStreamCaptureStatus capture = hipStreamCaptureStatusNone; + if (hipStreamIsCapturing((hipStream_t)stream, &capture) != hipSuccess || + capture != hipStreamCaptureStatusNone) + return; + int device = 0; + if (hipGetDevice(&device) != hipSuccess) return; + unsigned long long v[3]; + read_stats(v, false); + if (!v[2]) return; + std::fprintf(stderr, + "r4d mla_attn_matrix device %d: %llu passes over %llu raster chunks, " + "%llu second passes (%.3fx)\n", + device, v[0], v[2], v[1], (double)v[0] / (double)v[2]); +} +template +int body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &o = a->t[4]; + if (q.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 || + len.dtype != RAD_I32) + return RAD_E_DTYPE; + for (int i = 0; i < 5; ++i) + if (!a->t[i].data) return RAD_E_INVAL; + const long heads = r4d_geti_or(a, "heads", 0), bs = r4d_geti_or(a, "block_size", 0); + const float scale = (float)r4d_getf(a, "scale", 0); + if (r4d_geti_or(a, "latent_dim", 0) != D || heads < 1 || heads > 64 || bs < 1 || bs > 256 || + !std::isfinite(scale) || scale <= 0 || q.rank != 3 || q.shape[0] < 1 || + q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || q.stride[2] != 1 || + q.stride[1] < D || q.stride[0] < heads * q.stride[1] || kv.rank != 4 || kv.shape[0] < 1 || + kv.shape[0] > INT_MAX || kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != D || + kv.stride[3] != 1 || kv.stride[2] < D || kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 || + bt.shape[0] != q.shape[0] || bt.shape[1] < 1 || bt.shape[1] > INT_MAX / bs || + bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || len.rank != 1 || + len.shape[0] != q.shape[0] || len.stride[0] < 1 || o.rank != 3 || + o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 || + o.stride[1] < D || o.stride[0] < heads * o.stride[1]) + return RAD_E_SHAPE; + if (MATRIX && heads % 8) return RAD_E_UNSUPPORTED; + const bool pair = MATRIX && heads % 16; + const long jobs = MATRIX ? (pair ? (q.shape[0] + 1) / 2 * (heads / 8) : q.shape[0] * heads / 16) + : q.shape[0] * heads; + int splits = (int)std::min(MATRIX ? 64l : 16l, ((MATRIX ? 64 : 256) + jobs - 1) / jobs); + const long minimum = MATRIX ? 16 : 64; + splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + minimum - 1) / minimum)); + if (!a->scratch || a->scratch_bytes < (MATRIX ? matrix_scratch_bytes : scratch_bytes)) + splits = 1; + // Vectors need every cache row on a sixteen-byte boundary. + const bool wide = g_mla_matrix_form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) && + !(kv.stride[2] % 8); + /* RADIANCE_MLA_PAIR=pos keeps the positional pairing, for comparison; the union's LDS lists + * hold a table of at most kUnionBlocks entries. */ + const char* pairing = std::getenv("RADIANCE_MLA_PAIR"); + const bool by_page = !(pairing && !std::strcmp(pairing, "pos")) && bt.shape[1] <= kUnionBlocks; + const bool stats = MATRIX && env_on("RADIANCE_MLA_CONFLICT_STATS"); + Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2], + bt.stride[0], bt.stride[1], len.stride[0], o.stride[0], + o.stride[1], (int)q.shape[0], (int)heads, (int)bt.shape[1], + (int)bs, (int)kv.shape[0], splits, scale }; + int rc; + if constexpr (MATRIX) { +#define MATRIX_EMIT(P, W, U, S, X, Y) \ + R4D_EMIT(stream, (attend_matrix), dim3(X, Y, m.splits), dim3(128), 0, \ + (const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data, \ + (const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m) +#define MATRIX_LAUNCH(P, W, U, X, Y) \ + (stats ? MATRIX_EMIT(P, W, U, true, X, Y) : MATRIX_EMIT(P, W, U, false, X, Y)) + if (pair && by_page) + rc = wide ? MATRIX_LAUNCH(true, true, true, (m.rows + 1) / 2, m.heads / 8) + : MATRIX_LAUNCH(true, false, true, (m.rows + 1) / 2, m.heads / 8); + else if (pair) + rc = wide ? MATRIX_LAUNCH(true, true, false, (m.rows + 1) / 2, m.heads / 8) + : MATRIX_LAUNCH(true, false, false, (m.rows + 1) / 2, m.heads / 8); + else + rc = wide ? MATRIX_LAUNCH(false, true, false, m.rows, m.heads / 16) + : MATRIX_LAUNCH(false, false, false, m.rows, m.heads / 16); +#undef MATRIX_LAUNCH +#undef MATRIX_EMIT + } else + rc = R4D_EMIT(stream, attend, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128), 0, + (const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data, + (const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m); + if (rc == RAD_OK && splits > 1) + rc = R4D_EMIT(stream, merge, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0, + (const float*)a->scratch, (uint16_t*)o.data, m); + if (rc == RAD_OK && stats) report_stats(stream); + return rc; +} +} +extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) { + return body(a, stream); +} +extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) { + return body(a, stream); +} +extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) { + return project_body(a, stream); +} +extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; } +extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; } +extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; } +/* Test hook: the current device's RADIANCE_MLA_CONFLICT_STATS counters since the last call (passes, + * second passes, raster chunks), then zeroed. */ +extern "C" void r4d_mla_matrix_stats(unsigned long long* out) { + unsigned long long v[3]; + (void)hipDeviceSynchronize(); + read_stats(v, true); + if (out) std::memcpy(out, v, sizeof v); +} diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index f23e0819..75528e13 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -43,6 +43,8 @@ #include "r4d_plugin.h" #include "r4d_emit.h" #include "r4d_gemm_args.h" +#include "r4d_moe_sort.h" +#include "r4d_moe_gather.h" #include @@ -57,11 +59,20 @@ namespace { constexpr uint32_t kWave = 32; -/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in - * registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers - * Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router - * instantiation. */ -constexpr uint32_t kMaxExpert = 512; +using r4d_moesort::kMaxExpert; +using r4d_moesort::kMaxProtect; +using r4d_moesort::Protect; +using r4d_moesort::sort_place; +using r4d_moesort::protect_of; +using r4d_moesort::kScatterSmall; +using r4d_moesort::ScatterLds; +using r4d_moesort::wave_incl_scan_i32; +using r4d_moesort::scatter_small_place; +using r4d_moesort::kScatWaves; +using r4d_moesort::scatter_small_kernel; +using r4d_moegather::kGatherSlots; +using r4d_moegather::kGatherSelfT; +using r4d_moegather::gather_kernel; constexpr uint32_t kBlock = 128; // the fp8 scale block, along K and along N /* Run-map entry that owns no expert: rows above `off[n_expert]` are dropped slots whose output must * be zeroed. Declared here because the GEMM reads it; the map is built further down. */ @@ -152,27 +163,6 @@ __device__ __forceinline__ uint32_t wave_min_u32(uint32_t b) { * `router_topk_scatter_kernel` run this same code from a different grid, byte-identically. */ /* In the fused kernel a row also hands its slots to the sort through `e`: each slot's expert * relative to the slice, or -1 for another rank's. The standalone selection passes a null `e`. */ -/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output - * dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort - * places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and - * [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an - * expert's place is itself. */ -constexpr uint32_t kMaxProtect = 8; -struct Protect { - uint32_t n; - uint16_t e[kMaxProtect]; -}; - -/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */ -__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) { - int32_t below = 0; - for (uint32_t j = 0; j < p.n; ++j) { - if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j); - below += (int32_t)p.e[j] < e; - } - return e - below; -} - struct SlotSink { int32_t* e; int32_t base; @@ -292,123 +282,8 @@ __global__ __launch_bounds__(NW * kWave) void router_topk_kernel( /* ================================================================== moe_scatter * - * The small form: one workgroup does the whole sort, for T <= kScatterSmall, which covers every - * decode and verify step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch - * instead of three. Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert - * counts, and each slot placed by its rank inside its expert's run. - * - * On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work: - * - * - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one - * barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts). - * - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its - * expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's - * place is the number of the run's slots with a lower index. That count is as long as the run - * (a row picks an expert at most once), far shorter than counting all earlier slots. - * - * Stable and byte-identical: a slot's place is its position among the same expert's slots in - * ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so - * none waits on or invalidates the vector memory path. */ -constexpr uint32_t kScatterSmall = 1024; -constexpr uint32_t kScatWaves = 8; /* the standalone sort: 256 threads */ - -/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the - * workgroup's wave count, which sizes the scan's exchange. */ -template -struct ScatterLds { - static constexpr uint32_t kTiles = (kMaxExpert + NW * kWave - 1) / (NW * kWave); - int32_t e[kScatterSmall]; /* the slot list: expert in the slice, or -1 */ - int32_t tk[kScatterSmall]; /* the slot's ticket inside its expert's run */ - int32_t run[kScatterSmall]; /* slots grouped by expert, tickets' order */ - int32_t cnt[kMaxExpert + 1]; - int32_t off[kMaxExpert + 1]; - int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */ -}; - -/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then - * the upper row adds the lower row's total. Lanes shifted in from outside the row read zero - * (bound_ctrl). */ -__device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) { - x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */ - x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */ - x += __builtin_amdgcn_update_dpp(0, x, 0x114, 0xF, 0xF, true); /* row_shr:4 */ - x += __builtin_amdgcn_update_dpp(0, x, 0x118, 0xF, 0xF, true); /* row_shr:8 */ - const int32_t lo = __builtin_amdgcn_readlane(x, 15); - return lane >= 16u ? x + lo : x; -} - -/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has - * written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the - * standalone sort and the fused kernel. The workgroup is exactly NW waves. */ -template -__device__ __forceinline__ void scatter_small_place( - int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt, - uint32_t T, uint32_t n_expert, ScatterLds& sl) { - const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave; - - for (uint32_t i = tid; i < T; i += blockDim.x) { - const int32_t e = sl.e[i]; - if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1); - } - lds_barrier(); - - /* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same - * in every thread. */ - int32_t carry = 0; - for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kWave, ++t) { - const uint32_t e = b + tid; - const int32_t v = (e < n_expert) ? sl.cnt[e] : 0; - const int32_t x = wave_incl_scan_i32(v, lane); - if (lane == kWave - 1) sl.wt[t][wave] = x; - lds_barrier(); - int32_t below = 0, tot = 0; -#pragma unroll - for (uint32_t k = 0; k < NW; ++k) { - const int32_t c = sl.wt[t][k]; - below += (k < wave) ? c : 0; - tot += c; - } - if (e < n_expert) { - const int32_t o = carry + below + x - v; /* inclusive -> exclusive */ - sl.off[e] = o; - off[e] = o; - cnt[e] = v; - } - carry += tot; - } - if (tid == 0) off[n_expert] = carry; - lds_barrier(); - - for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1; - for (uint32_t i = tid; i < T; i += blockDim.x) { - const int32_t e = sl.e[i]; - if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i; - } - lds_barrier(); - for (uint32_t i = tid; i < T; i += blockDim.x) { - const int32_t e = sl.e[i]; - if (e < 0) continue; - const int32_t o = sl.off[e], n = sl.cnt[e]; - int32_t rank = 0; - for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i; - sorted[o + rank] = (int32_t)i; - } -} - -__global__ __launch_bounds__(kScatWaves * kWave) void scatter_small_kernel( - const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off, - int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot) { - __shared__ ScatterLds sl; - const uint32_t tid = threadIdx.x; - for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0; - for (uint32_t i = tid; i < T; i += blockDim.x) { - const int32_t e = ids[i] - base; - sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1; - } - lds_barrier(); - scatter_small_place(sorted, off, cnt, T, n_expert, sl); -} - + * The small form is one workgroup and the sort of r4d_moe_sort.h; the general form below takes + * three passes. */ /* ================================================================== router_topk + moe_scatter * * One launch for the pair: at decode each half is a single 256-thread workgroup moving about a @@ -520,11 +395,12 @@ __global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel( /* Placement and tail. Each routed slot goes to its expert's offset plus the expert's count in * earlier tiles plus its rank in this tile. Sorted rows past the live count are -1; no placement * lands there (all placed slots are below `off[n_expert]`), so each thread writes its own index - * without races. */ + * without races. INV also writes each slot's row, -1 when dropped (scatter_small_place). */ +template __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel( const int32_t* __restrict__ ids, const int32_t* __restrict__ bcnt, const int32_t* __restrict__ off, int32_t* __restrict__ sorted, - uint32_t T, uint32_t n_expert, int32_t base, Protect prot) { + uint32_t T, uint32_t n_expert, int32_t base, Protect prot, int32_t* __restrict__ inv) { __shared__ int32_t s_id[kScatterTile]; const uint32_t tid = threadIdx.x, b = blockIdx.x; const uint32_t i = b * kScatterTile + tid; @@ -536,12 +412,15 @@ __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel( const uint32_t live = (uint32_t)off[n_expert]; if (i >= live && i < T) sorted[i] = -1; __syncthreads(); + if constexpr (INV) if (i < T && e < 0) inv[i] = -1; if (i >= T || e < 0) return; /* Rank within the tile: earlier slots of this tile with the same expert. A serial scan of at * most 256 LDS words per thread, the price of stability. */ int32_t rank = 0; for (uint32_t j = 0; j < tid; ++j) rank += (s_id[j] == e); - sorted[off[e] + bcnt[(size_t)b * n_expert + e] + rank] = (int32_t)i; + const int32_t at = off[e] + bcnt[(size_t)b * n_expert + e] + rank; + sorted[at] = (int32_t)i; + if constexpr (INV) inv[i] = at; } /* ================================================================== the 4-bit expert weight @@ -2155,78 +2034,6 @@ __global__ void gather_scatter_kernel(const int32_t* __restrict__ sorted, if (f >= 0 && f < (int32_t)T) inv[f] = (int32_t)i; } -/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the - * column, and read inside the column loop each `inv` load would serialise the `ye` load behind it - * (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline. - * - * The column range is also split over blocks, since decode has one token. Neither change touches - * the sum: each column's slots are still summed in ascending order within one block. */ -constexpr uint32_t kGatherSlots = 64; -/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not - * launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k), - * giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it - * (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches - * (~2.1 us each) of single-block kernels. - * - * `sorted == nullptr` selects the prepass path, used at prefill. */ -constexpr uint32_t kGatherSelfT = 512; - -template -__global__ __launch_bounds__(NTHR) void gather_kernel( - const uint16_t* __restrict__ ye, const uint16_t* __restrict__ ew, - const int32_t* __restrict__ inv, uint16_t* __restrict__ y, - uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld, - const int32_t* __restrict__ sorted, uint32_t T, - const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg, - uint32_t sh_ld, uint32_t sg_ld, int sig) { - __shared__ int32_t s_i[kGatherSlots]; - __shared__ float s_w[kGatherSlots]; - const uint32_t t = blockIdx.x; - if (t >= M) return; - const bool cached = top_k <= kGatherSlots; - /* The shared arm's scalar, read once per block as scale_rows reads it once per row. */ - float gate = 0.0f; - if (sh) { - const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]); - gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0; - } - if (sorted) { - /* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the - * prepass is two kernels). */ - for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1; - __syncthreads(); - const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k; - for (uint32_t i = threadIdx.x; i < T; i += NTHR) { - const int32_t f = sorted[i]; - if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i; - } - for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) - s_w[j] = bf16_to_f32(ew[(size_t)t * ew_ld + j]); - __syncthreads(); - } else if (cached) { - for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) { - s_i[j] = inv[t * top_k + j]; - s_w[j] = bf16_to_f32(ew[(size_t)t * ew_ld + j]); - } - __syncthreads(); - } - for (uint32_t c = blockIdx.y * NTHR + threadIdx.x; c < n; c += NTHR * gridDim.y) { - float acc = 0.0f; - for (uint32_t j = 0; j < top_k; ++j) { - const int32_t i = cached ? s_i[j] : inv[t * top_k + j]; - if (i < 0) continue; - const float wj = cached ? s_w[j] : bf16_to_f32(ew[(size_t)t * ew_ld + j]); - acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]); - } - const uint16_t g = f32_to_bf16(acc); - if (!sh) { y[(size_t)t * y_ld + c] = g; continue; } - /* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather - * as bf16 and narrows its own product before adding. */ - const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate); - y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g)); - } -} - /* ---- prefill gather: a wave per token, eight columns per lane --------------------------------- * * At prefill this op reads `ye` (105 MB per layer at a 2048 chunk of Qwen3.8-Flash-Next on four @@ -2397,27 +2204,6 @@ extern "C" int r4d_rad_router_topk(const RadArgs* a, RadStream s) { return RAD_OK; } -/* `protect`, a comma list of local expert indices: strictly ascending, inside the slice, at most - * kMaxProtect. Absent or empty is none. */ -static int protect_of(const RadArgs* a, long long n_local, Protect* p) { - *p = Protect{}; - const char* s = r4d_gets(a, "protect"); - if (!s) return RAD_OK; - long long prev = -1; - while (*s) { - char* end = nullptr; - const long long v = std::strtoll(s, &end, 10); - if (end == s || v <= prev || v >= n_local || p->n >= kMaxProtect) - return R4D_NO(RAD_E_SHAPE); - p->e[p->n++] = (uint16_t)v; - prev = v; - s = end; - if (*s == ',') ++s; - else if (*s) return R4D_NO(RAD_E_SHAPE); - } - return RAD_OK; -} - /* The pair in one launch. Operands are the two ops' own, selection first: logits -> expert_ids, * expert_w, sorted_tok, expert_offset, expert_count. The checks are the two shims' checks. * @@ -2518,7 +2304,8 @@ extern "C" int64_t r4d_rad_moe_scatter_scratch(const RadArgs* a) { return n_tile * n_expert * (long long)sizeof(int32_t); } -extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { +/* moe_scatter, and with `inv` (moe_scatter_inv's fifth operand) the inverse beside it. */ +static int moe_scatter_body(const RadArgs* a, RadStream s, const RadTensor* inv) { const RadTensor* ids = r4d_opt(a, 0); const RadTensor* sorted = r4d_opt(a, 1); const RadTensor* off = r4d_opt(a, 2); @@ -2543,15 +2330,24 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { const int prc = protect_of(a, n_expert, &prot); if (prc != RAD_OK) return prc; + if (inv && (inv->dtype != RAD_I32 || !r4d_contig(inv) || r4d_numel(inv) < T)) + return R4D_NO(RAD_E_SHAPE); + const int32_t* idp = (const int32_t*)ids->data; int32_t* sp = (int32_t*)sorted->data; int32_t* op = (int32_t*)off->data; int32_t* cp = (int32_t*)cnt->data; + int32_t* ip = inv ? (int32_t*)inv->data : nullptr; if (T <= (long long)kScatterSmall) { - hipLaunchKernelGGL(scatter_small_kernel, dim3(1), dim3(256), 0, (hipStream_t)s, - idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, - prot); + if (ip) + hipLaunchKernelGGL(scatter_small_kernel, dim3(1), dim3(kScatWaves * kWave), 0, + (hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); + else + hipLaunchKernelGGL(scatter_small_kernel, dim3(1), dim3(kScatWaves * kWave), 0, + (hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); R4D_MOE_CHK(); return RAD_OK; } @@ -2568,13 +2364,30 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { hipLaunchKernelGGL(scatter_scan_kernel, dim3(1), dim3(kMaxExpert), 0, (hipStream_t)s, bcnt, op, cp, (uint32_t)n_tile, (uint32_t)n_expert); R4D_MOE_CHK(); - hipLaunchKernelGGL(scatter_place_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), 0, - (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert, - (int32_t)base, prot); + if (ip) + hipLaunchKernelGGL(scatter_place_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), + 0, (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); + else + hipLaunchKernelGGL(scatter_place_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), + 0, (hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); R4D_MOE_CHK(); return RAD_OK; } +extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { + return moe_scatter_body(a, s, nullptr); +} + +/* moe_scatter that also writes, for every slot, its row in `sorted_tok` (-1 when dropped): the + * table moe_gather_inv reads instead of rebuilding it from `sorted_tok`. Same sort, same scratch. */ +extern "C" int r4d_rad_moe_scatter_inv(const RadArgs* a, RadStream s) { + const RadTensor* inv = r4d_opt(a, 4); + if (!inv) return R4D_NO(RAD_E_INVAL); + return moe_scatter_body(a, s, inv); +} + /* The weight-table operand from the core's tensor. A zero leading stride marks a pointer array * (abi/rad_runtime.h, RAD_WTAB); otherwise it is a stacked plane with the stride in elements of the * weight's dtype (bytes for E4M3). */ @@ -3220,7 +3033,9 @@ extern "C" int64_t r4d_rad_moe_gather_scratch(const RadArgs* a) { return M * top_k * (long long)sizeof(int32_t); } -extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { +/* moe_gather, or with `given` moe_gather_inv, whose third operand is the inverse moe_scatter_inv + * wrote: no prepass and no self-scan, and the same kernel at the same T, so the same sums. */ +static int moe_gather_body(const RadArgs* a, RadStream s, bool given) { const RadTensor* ye = r4d_opt(a, 0); const RadTensor* ew = r4d_opt(a, 1); const RadTensor* sorted = r4d_opt(a, 2); @@ -3232,7 +3047,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { const long long n = r4d_geti_or(a, "n", 0); const long long top_k = r4d_geti_or(a, "top_k", 0); if (n <= 0 || top_k <= 0) return R4D_NO(RAD_E_SHAPE); - if (ye->dtype != RAD_BF16 || ew->dtype != RAD_BF16 || Y->dtype != RAD_BF16) + if (ye->dtype != RAD_BF16 || (ew->dtype != RAD_BF16 && ew->dtype != RAD_F32) || Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (sorted->dtype != RAD_I32 || !r4d_contig(sorted)) return R4D_NO(RAD_E_STRIDE); /* The shared arm is a pair: the plane and its per-row gate, or neither. */ @@ -3253,12 +3068,14 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { /* SELF: small enough for the gather to build its own slot table, skipping the two prepass * kernels (see gather_kernel). Bounded on T because each of the M*gy blocks repeats the scan; - * at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. */ - const bool self = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots; + * at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. A given + * table replaces both, and `small` keeps the kernel choice the self-scan would make. */ + const bool small = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots; + const bool self = small && !given; - const int64_t need = self ? 0 : T * (long long)sizeof(int32_t); - int32_t* inv = nullptr; - if (!self) { + const int64_t need = self || given ? 0 : T * (long long)sizeof(int32_t); + int32_t* inv = given ? (int32_t*)sorted->data : nullptr; + if (!self && !given) { if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); inv = (int32_t*)a->scratch; const unsigned blocks = (unsigned)((T + 255) / 256); @@ -3288,7 +3105,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { auto al16 = [](const void* p, long long ld) { return ((uintptr_t)p % 16) == 0 && ld % (long long)kGatherWideCols == 0; }; - const bool wide_ok = !self && top_k <= (long long)kGatherWideSlots && + const bool wide_ok = ew->dtype == RAD_BF16 && !small && top_k <= (long long)kGatherWideSlots && n % (long long)kGatherWideCols == 0 && al16(ye->data, ye_ld) && al16(Y->data, y_ld) && (!sh || al16(sh->data, sh_ld)); const int gpin = g_moe_gather_pin; @@ -3310,6 +3127,17 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { } const unsigned gy = (unsigned)((n + 255) / 256); + if (ew->dtype == RAD_F32) { + hipLaunchKernelGGL( + (gather_kernel<256, true>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s, + (const uint16_t*)ye->data, ew->data, inv, (uint16_t*)Y->data, (uint32_t)M, (uint32_t)n, + (uint32_t)top_k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, + self ? (const int32_t*)sorted->data : nullptr, (uint32_t)T, + sh ? (const uint16_t*)sh->data : nullptr, sh ? (const uint16_t*)sg->data : nullptr, + (uint32_t)sh_ld, (uint32_t)sg_ld, sig); + R4D_MOE_CHK(); + return RAD_OK; + } hipLaunchKernelGGL((gather_kernel<256>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s, (const uint16_t*)ye->data, (const uint16_t*)ew->data, inv, (uint16_t*)Y->data, (uint32_t)M, (uint32_t)n, (uint32_t)top_k, @@ -3322,6 +3150,14 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { return RAD_OK; } +extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { + return moe_gather_body(a, s, false); +} + +extern "C" int r4d_rad_moe_gather_inv(const RadArgs* a, RadStream s) { + return moe_gather_body(a, s, true); +} + extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) { const RadTensor* x = r4d_opt(a, 0); const RadTensor* sc = r4d_opt(a, 1); diff --git a/libr4d/r4d_moe_gather.h b/libr4d/r4d_moe_gather.h new file mode 100644 index 00000000..8eabec4f --- /dev/null +++ b/libr4d/r4d_moe_gather.h @@ -0,0 +1,92 @@ +// r4d_moe_gather.h -- moe_gather's kernel for decode and short passes, beside its launcher in +// r4d_moe.hip; tests/r4d_emu runs it from here against the inverse the sort writes. +#pragma once +#include +#include + +#include "r4d_common.h" + +// Internal linkage, as the unit's own definition had. +namespace r4d_moegather { +namespace { + +/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the + * column, and read inside the column loop each `inv` load would serialise the `ye` load behind it + * (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline. + * + * The column range is also split over blocks, since decode has one token. Neither change touches + * the sum: each column's slots are still summed in ascending order within one block. */ +constexpr uint32_t kGatherSlots = 64; +/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not + * launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k), + * giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it + * (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches + * (~2.1 us each) of single-block kernels. + * + * `sorted == nullptr` selects the prepass path, used at prefill. */ +constexpr uint32_t kGatherSelfT = 512; + +template +__device__ float gather_weight(const void* ew, size_t i) { + if constexpr (F32) return ((const float*)ew)[i]; + else return bf16_to_f32(((const uint16_t*)ew)[i]); +} +template +__global__ __launch_bounds__(NTHR) void gather_kernel( + const uint16_t* __restrict__ ye, const void* __restrict__ ew, + const int32_t* __restrict__ inv, uint16_t* __restrict__ y, + uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld, + const int32_t* __restrict__ sorted, uint32_t T, + const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg, + uint32_t sh_ld, uint32_t sg_ld, int sig) { + __shared__ int32_t s_i[kGatherSlots]; + __shared__ float s_w[kGatherSlots]; + const uint32_t t = blockIdx.x; + if (t >= M) return; + const bool cached = top_k <= kGatherSlots; + /* The shared arm's scalar, read once per block as scale_rows reads it once per row. */ + float gate = 0.0f; + if (sh) { + const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]); + gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0; + } + if (sorted) { + /* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the + * prepass is two kernels). */ + for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1; + __syncthreads(); + const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k; + for (uint32_t i = threadIdx.x; i < T; i += NTHR) { + const int32_t f = sorted[i]; + if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i; + } + for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) + s_w[j] = gather_weight(ew, (size_t)t * ew_ld + j); + __syncthreads(); + } else if (cached) { + for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) { + s_i[j] = inv[t * top_k + j]; + s_w[j] = gather_weight(ew, (size_t)t * ew_ld + j); + } + __syncthreads(); + } + for (uint32_t c = blockIdx.y * NTHR + threadIdx.x; c < n; c += NTHR * gridDim.y) { + float acc = 0.0f; + for (uint32_t j = 0; j < top_k; ++j) { + const int32_t i = cached ? s_i[j] : inv[t * top_k + j]; + if (i < 0) continue; + const float wj = cached ? s_w[j] : gather_weight(ew, (size_t)t * ew_ld + j); + if constexpr (F32) acc = fmaf(wj, bf16_to_f32(ye[(size_t)i * ye_ld + c]), acc); + else acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]); + } + const uint16_t g = f32_to_bf16(acc); + if (!sh) { y[(size_t)t * y_ld + c] = g; continue; } + /* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather + * as bf16 and narrows its own product before adding. */ + const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate); + y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g)); + } +} + +} // namespace +} // namespace r4d_moegather diff --git a/libr4d/r4d_moe_mxfp4.hip b/libr4d/r4d_moe_mxfp4.hip new file mode 100644 index 00000000..ad22b3b5 --- /dev/null +++ b/libr4d/r4d_moe_mxfp4.hip @@ -0,0 +1,1156 @@ +/* Canonical MXFP4 experts: packed E2M1 codes and E8M0 bytes remain in their + * source layout, including mapped host expert tables. A wave decodes packed + * words into exact E4M3 staging bytes for FP8 WMMA. Activation then weight + * scales fold in F32 per 32 values, matching the reference grouping. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_fp8_wmma.h" +#include "r4d_mxfp4.h" +#include +#include +#include + +namespace { +struct MxMeta { + long wstep[2], sstep[2]; + int wrow[2], srow[2], n[2], k[2]; + long ar, asr, yr; + int T, Arows, N, K, experts, topk, sorted_a, tile, parts, aligned_jobs; + int stage_out, out16; +}; +__device__ const uint8_t* entry(const void* base, long step, int e) { + return step ? (const uint8_t*)base + (long)e * step : ((const uint8_t* const*)base)[e]; +} +/* E2M1 values are exactly representable in E4M3. Stage those codes directly, + * use FP8 WMMA, and fold each 32-wide E8M0 scale into the F32 accumulator. + * No persistent expansion or checkpoint relayout is needed. */ +// Four independent bytes: magnitudes >=2 map to (m+12)*4; 0/1 map to 0/48. +// Expand each magnitude-test bit into a byte mask without cross-byte carries. +__device__ __forceinline__ uint32_t fp4x4(uint32_t n) { + const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u; + const uint32_t mask = (flag << 5) - (flag >> 3); + return ((((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) | + ((n & 0x08080808u) << 4)); +} +/* Eight codes of a packed word to their E4M3 bytes in k order. The table form (r4d_mxfp4.h, v_perm + * on the magnitude) gives the same bytes in about a third of the instructions; the arithmetic form + * stays reachable (RADIANCE_MXFP4_LUT=0) as the bytewise reference. */ +template +__device__ __forceinline__ uint2 mx_codes8(uint32_t packed) { + if constexpr (Lut) { + uint32_t lo, hi; + r4d_mxfp4_unpack8_exact(packed, &lo, &hi); + return uint2{ lo, hi }; + } else { + const uint32_t low = fp4x4(packed & 0x0f0f0f0fu), high = fp4x4((packed >> 4) & 0x0f0f0f0fu); + return uint2{ __byte_perm(low, high, 0x5140), __byte_perm(low, high, 0x7362) }; + } +} +template +__global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const void* w0, + const void* s0, const void* w1, const void* s1, + const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + __shared__ __align__(16) uint8_t aa[16 * RowTiles * 136], bb[16 * ColTiles * 136]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, + col0 = blockIdx.x * (16 * ColTiles); + constexpr int JobRows = 16 * RowTiles, Threads = 32 * ColTiles * RowTiles; + const int wave_col = ColTiles == 1 ? 0 : wave % ColTiles, + wave_row = RowTiles == 1 ? 0 : wave / ColTiles; + int first = blockIdx.y * m.tile; + int group_end = min((int)(blockIdx.y + 1) * m.tile, m.T), job_expert = 0; + if (m.aligned_jobs) { + // Expert e begins at job floor(offset[e]/JobRows)+e. The extra job per expert + // bounds padding without a prefix-sum pass; every live job owns one row tile + // of one expert, so hot experts still spread across independent CTAs. + const int job = blockIdx.y, tail = offset[m.experts] / JobRows + m.experts; + if (job >= tail) { + const int r0 = offset[m.experts] + (job - tail) * JobRows; + for (int r = r0; r < min(r0 + JobRows, m.T); ++r) + if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)r * m.yr + col0 + tid] = 0; + return; + } + int lo = 0, hi = m.experts; + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offset[mid] / JobRows + mid <= job) + lo = mid; + else + hi = mid; + } + job_expert = lo; + first = offset[lo] + (job - (offset[lo] / JobRows + lo)) * JobRows; + group_end = min(first + JobRows, offset[lo + 1]); + } + for (int start = first; start < group_end;) { + if (sorted[start] < 0 || offset[m.experts] <= start) { + if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)start * m.yr + col0 + tid] = 0; + ++start; + continue; + } + int lo = m.aligned_jobs ? job_expert : 0, hi = m.experts; + if (!m.aligned_jobs) + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offset[mid] <= start) + lo = mid; + else + hi = mid; + } + const int cls = lo & 1, end = min(group_end, offset[lo + 1]); + if (end <= start) return; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2); + auto total = r4d_fp8::acc_zero(); + // Routing is invariant across K; each activation scale covers all four groups. + int sources[8]; + if constexpr (CachedRows) { +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = start + wave_row * 16 + (lane >> 4) * 8 + row; + const int flat = r < end ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + sources[row] = ar >= 0 && ar < m.Arows ? ar : -1; + } + } + for (int kb = 0; kb < m.k[cls]; kb += 128) { + for (int j = tid; j < 16 * RowTiles * 16; j += Threads) { + const int r = j / 16, d = (j % 16) * 8; + const int ar = start + r < end && sorted[start + r] >= 0 + ? (m.sorted_a ? start + r : sorted[start + r] / m.topk) + : -1; + uint2 av{}; + if (ar >= 0 && ar < m.Arows) __builtin_memcpy(&av, a + (long)ar * m.ar + kb + d, 8); + *reinterpret_cast(aa + r * 136 + d) = av; + } + for (int j = tid; j < 16 * ColTiles * 16; j += Threads) { + const int r = j / 16, d = (j % 16) * 8; + const int n = col0 + r, part = n / (m.N / m.parts), within = n % (m.N / m.parts); + const int wn = part * (m.n[cls] / m.parts) + within; + uint32_t packed = 0; + if (n < m.N && within < m.n[cls] / m.parts) + __builtin_memcpy(&packed, w + (long)wn * m.wrow[cls] + (kb + d) / 2, 4); + *reinterpret_cast(bb + r * 136 + d) = mx_codes8(packed); + } + __syncthreads(); + if (start + wave_row * 16 < end) { + const int n = col0 + wave_col * 16 + (lane & 15), part = n / (m.N / m.parts), + within = n % (m.N / m.parts); + const int wn = part * (m.n[cls] / m.parts) + within; + const bool valid = n < m.N && within < m.n[cls] / m.parts; + float activation[8]; + if constexpr (CachedRows) { +#pragma unroll + for (int row = 0; row < 8; ++row) + activation[row] = + sources[row] >= 0 ? as[(long)sources[row] * m.asr + kb / 128] : 0; + } +#pragma unroll + for (int group = 0; group < 4; ++group) { + const int exp = valid ? ws[(long)wn * m.srow[cls] + kb / 32 + group] : 127; + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = group * 32; k < (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, wave_row * 16, k, lane), + r4d_fp8::frag<128>(bb, wave_col * 16, k, lane), raw); + // E8M0 maps directly to the F32 exponent field; code zero is 2^-127, + // a representable subnormal, and code 255 is NaN. + const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? ((uint32_t)exp << 23) + : 0x00400000u); +#pragma unroll + for (int row = 0; row < 8; ++row) { + if constexpr (CachedRows) { + if (sources[row] >= 0) total[row] += raw[row] * activation[row] * scale; + } else { + const int r = start + wave_row * 16 + (lane >> 4) * 8 + row; + if (r < end) { + const int ar = sorted[r] < 0 ? -1 + : m.sorted_a ? r + : sorted[r] / m.topk; + if (ar >= 0 && ar < m.Arows) + total[row] += + raw[row] * as[(long)ar * m.asr + kb / 128] * scale; + } + } + } + } + } + __syncthreads(); + } +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = start + wave_row * 16 + (lane >> 4) * 8 + row, + n = col0 + wave_col * 16 + (lane & 15); + if (r < end && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]); + } + start = end; + } +} + +/* An expert's weight and exponent rows reached through entry() are generic pointers, so their loads + * compile to flat loads, which every LDS wait (s_wait_dscnt) also waits for: a barrier then stalls + * on the prefetch. The tables hold device or device-mapped host addresses, so a global load reads + * the same bytes. Byte-aligned, as a stacked plane's row pitch may be odd. */ +typedef r4d_u32x4 mx_g16 __attribute__((aligned(1))); +typedef uint32_t mx_g4 __attribute__((aligned(1))); +__device__ __forceinline__ r4d_u32x4 mx_ldg16(const uint8_t* p) { + return *(const __attribute__((address_space(1))) mx_g16*)p; +} +__device__ __forceinline__ uint32_t mx_ldg4(const uint8_t* p) { + return *(const __attribute__((address_space(1))) mx_g4*)p; +} +/* The TP8 prefill form (M32N64, aligned jobs, cached rows) with its loads a stage ahead. A job's + * row table resolves into LDS once; the next 128 of K (activation bytes, weight codes, an exponent + * dword a column, the activation scales) is loaded into registers while the current stage computes + * from LDS. The form above waits on three dependent latencies a stage: the routing entry, the + * activation row it names, and the exponent bytes it reads after the barrier. A job begins at its + * first row even when that slot is dropped; rows are independent, so the bytes are the same. + * The exponents are decoded once, at staging; the fold carries no row predicate, the epilogue + * writes a dropped row's zero instead. + * One stage ahead only: a deeper prefetch measured slower on the expert-major forms. The barriers + * order LDS only (lds_barrier), so the prefetch stays in flight across them and L0 keeps the + * activation rows the next column block reads. */ +template +__global__ __launch_bounds__(256) + R4D_WAVES(16) void moe_mxfp4_prefill_kernel(const uint8_t* a, const float* as, const void* w0, + const void* s0, const void* w1, const void* s1, + const int* sorted, const int* offset, uint16_t* y, + MxMeta m) { + constexpr int BN = 64, BM = 32, Threads = 256, P = 136; + static_assert(BM * 128 / 16 == Threads && BN * 64 / 16 == Threads, + "one 16-byte chunk a thread and operand"); + __shared__ __align__(16) uint8_t aa[BM * P], bb[BN * P]; + __shared__ __align__(16) float ss[4 * BN]; + __shared__ float sa[BM]; + __shared__ int src[BM]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, col0 = blockIdx.x * BN; + const int wave_col = wave & 3, wave_row = wave >> 2; + const int job = blockIdx.y, tail = offset[m.experts] / BM + m.experts; + if (job >= tail) { + const int r0 = offset[m.experts] + (job - tail) * BM; + for (int r = r0; r < min(r0 + BM, m.T); ++r) + if (tid < BN && col0 + tid < m.N) y[(long)r * m.yr + col0 + tid] = 0; + return; + } + int lo = 0, hi = m.experts; + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offset[mid] / BM + mid <= job) + lo = mid; + else + hi = mid; + } + const int first = offset[lo] + (job - (offset[lo] / BM + lo)) * BM, + end = min(first + BM, offset[lo + 1]); + if (first >= end) return; + const int cls = lo & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2); + if (tid < BM) { + const int r = first + tid, flat = r < end ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + // The block's columns are fixed, so each thread's weight row and exponent row are too. + const int wcol = tid >> 2, wd = (tid & 3) * 16, wn_c = col0 + wcol, wn_w = wn_c % pw; + const bool wvalid = wn_c < m.N && wn_w < cw; + const uint8_t* wp = w + (long)((wn_c / pw) * cw + wn_w) * m.wrow[cls] + wd; + const int en_c = col0 + tid, en_w = en_c % pw; + const bool evalid = tid < BN && en_c < m.N && en_w < cw; + const uint8_t* ep = ws + (long)((en_c / pw) * cw + en_w) * m.srow[cls]; + lds_barrier(); + const int arow = tid >> 3, ad = (tid & 7) * 16, a_src = src[arow]; + const uint8_t* ap = a + (long)max(a_src, 0) * m.ar + ad; + const int sa_row = tid - BN, sa_src = sa_row >= 0 && sa_row < BM ? src[sa_row] : -1; + const float* asp = as + (long)max(sa_src, 0) * m.asr; + const int rowbase = wave_row * 16 + (lane >> 4) * 8, mycol = wave_col * 16 + (lane & 15); + const bool live = first + wave_row * 16 < end; + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = src[rowbase + j] >= 0; + r4d_u32x4 ra, rw; + uint32_t rs = 0x7f7f7f7fu; + float rsa = 0; + auto load = [&](int k0) { + ra = r4d_u32x4{ 0, 0, 0, 0 }; + if (a_src >= 0) __builtin_memcpy(&ra, ap + k0, 16); + rw = r4d_u32x4{ 0, 0, 0, 0 }; + if (wvalid) rw = mx_ldg16(wp + k0 / 2); + if (evalid) rs = mx_ldg4(ep + k0 / 32); + if (sa_src >= 0) rsa = asp[k0 / 128]; + }; + auto store = [&]() { + *reinterpret_cast(aa + arow * P + ad) = ra; +#pragma unroll + for (int t = 0; t < 4; ++t) + *reinterpret_cast(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8(rw[t]); + if (tid < BN) { + // E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable + // subnormal, and code 255 is NaN. + float sc[4]; +#pragma unroll + for (int g = 0; g < 4; ++g) { + const uint32_t exp = (rs >> (8 * g)) & 0xffu; + sc[g] = __uint_as_float(exp == 255 ? 0x7fc00000u : exp ? (exp << 23) : 0x00400000u); + } + *reinterpret_cast(ss + 4 * tid) = make_float4(sc[0], sc[1], sc[2], sc[3]); + } + if (sa_row >= 0 && sa_row < BM) sa[sa_row] = rsa; + }; + auto total = r4d_fp8::acc_zero(); + load(0); + for (int k0 = 0; k0 < kc; k0 += 128) { + store(); + lds_barrier(); + if (k0 + 128 < kc) load(k0 + 128); + if (live) { + const float4 sc4 = *reinterpret_cast(ss + 4 * mycol); + const float scales[4] = { sc4.x, sc4.y, sc4.z, sc4.w }; + float activation[8]; +#pragma unroll + for (int row = 0; row < 8; ++row) activation[row] = sa[rowbase + row]; +#pragma unroll + for (int group = 0; group < 4; ++group) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = group * 32; k < (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, wave_row * 16, k, lane), + r4d_fp8::frag<128>(bb, wave_col * 16, k, lane), raw); +// A dropped row folds zeros (or NaN under a code-255 scale) and is written as 0. +#pragma unroll + for (int row = 0; row < 8; ++row) + total[row] += raw[row] * activation[row] * scales[group]; + // Two groups' WMMA chains at a time: with all four in flight the kernel takes 104 + // VGPRs, 12 waves a SIMD at gfx1201's 24-register granule instead of 16. + if (group == 1) sched_barrier(); + } + } + lds_barrier(); + } +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = first + rowbase + row, n = col0 + mycol; + if (r < end && n < m.N) y[(long)r * m.yr + n] = rv[row] ? f32_to_bf16(total[row]) : 0; + } +} + +/* The wide prefill form (P64): jobs of BM rows of one expert, blocks of BN columns, eight waves + * as BM/16 row waves times 8/(BM/16) column waves, so a wave holds BN/(16*column waves) tiles of + * 16x16 and reuses each A fragment across them. M32N64 reads every expert slice once per 32 rows + * and a fragment pair per WMMA pair; at 57 rows an expert (2048 tokens) BM 64 halves the slice + * reads, and a row wave past the run's end skips its compute, so the taller job costs no WMMA. + * + * Resident (K <= 256, down): the job's whole A tile sits in LDS for the block's CT column tiles, + * walked as one stage sequence whose next stage (weight codes, exponents) is loaded while the + * current one computes, across tile boundaries; A is read once per CT tiles instead of once per + * column block. Otherwise (gate_up) A streams with the weights, a stage ahead. + * + * Each element keeps the row-group form's sequence: per 128 of K in order, per 32-wide group a + * fresh WMMA pair from zero, folded as (raw * activation scale) * E8M0 scale and added, two + * roundings and an add (the unit is built -ffp-contract=off). The tiles of a wave are separate + * accumulators, so no element sees another order. `stage_out` writes the output through LDS in + * 16-byte rows instead of a lane's 2-byte column stores. + * + * DB (streamed A only): two LDS stages, one barrier a stage. The next stage is stored into the + * other buffer after the current one computes, which every wave last read before the previous + * barrier; the single-buffer order needs a second barrier before it may overwrite the stage it + * computes from. Same bytes in LDS, same per-element sequence. */ +template +struct MxP64 { + static constexpr int Threads = 256, WR = BM / 16, WC = 8 / WR, TC = BN / (16 * WC), + KB = StageK / 128; + static constexpr int KR = 256, AK = Resident ? KR : StageK, PA = AK + 8, PB = StageK + 8, + PO = 2 * BN + 16; + static constexpr int TPA = Threads / BM, ACh = StageK / 16 / TPA, RCh = KR / 16 / TPA; + static constexpr int TPW = Threads / BN, WCh = StageK / 32 / TPW, + SAK = Resident ? KR / 128 : KB; + static constexpr int NB = DB ? 2 : 1, BB = NB * BN * PB > BM *PO ? NB * BN * PB : BM * PO; + static constexpr int Lds = NB * (BM * PA + 16 * KB * BN + 4 * SAK * BM) + BB + 4 * BM; + // The waves a SIMD the LDS admits (128 KiB a WGP, a block's eight waves over four SIMDs): + // stating it keeps the compiler from trading the stage registers for waves it cannot get. + static constexpr int Waves = 2 * (131072 / Lds > 8 ? 8 : 131072 / Lds); +}; +template +__global__ __launch_bounds__(256) + R4D_WAVES((MxP64::Waves)) void moe_mxfp4_p64_kernel( + const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, + const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + using G = MxP64; + constexpr int Threads = G::Threads, WC = G::WC, TC = G::TC, KB = G::KB, AK = G::AK, PA = G::PA, + PB = G::PB; + constexpr int PO = G::PO, TPA = G::TPA, TPW = G::TPW, SAK = G::SAK; + static_assert(BM % 16 == 0 && 8 % G::WR == 0 && TC >= 1 && TC * 16 * WC == BN && + (Resident || CT == 1) && G::ACh >= 1 && G::WCh >= 1 && BN * KB <= Threads && + BM * SAK <= Threads && !(DB && Resident) && G::Lds <= 65536, + "stage chunks must divide evenly over the block, in 64 KiB of LDS"); + constexpr int NB = G::NB; + __shared__ __align__(16) uint8_t aa[NB * BM * PA], bb[G::BB]; + __shared__ __align__(16) float ss[NB * 4 * KB * BN], sa[NB * SAK * BM]; + __shared__ int src[BM]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, wave_row = wave / WC, + wave_col = wave % WC; + const int colb = blockIdx.x * (BN * CT), job = blockIdx.y, + tail = offset[m.experts] / BM + m.experts; + if (job >= tail) { + const int r0 = offset[m.experts] + (job - tail) * BM, rows = min(r0 + BM, m.T) - r0; + for (int i = tid; i < rows * BN * CT; i += Threads) { + const int n = colb + i % (BN * CT); + if (n < m.N) y[(long)(r0 + i / (BN * CT)) * m.yr + n] = 0; + } + return; + } + int lo = 0, hi = m.experts; + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offset[mid] / BM + mid <= job) + lo = mid; + else + hi = mid; + } + const int first = offset[lo] + (job - (offset[lo] / BM + lo)) * BM, + end = min(first + BM, offset[lo + 1]); + if (first >= end) return; + const int cls = lo & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2); + if (tid < BM) { + const int r = first + tid, flat = r < end ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + lds_barrier(); + // A thread's A chunks share one row and its weight chunks one column, so each keeps a single + // row pointer; neighbouring threads cover neighbouring 16 bytes, as one coalesced row. + const int arow = tid / TPA, a0 = tid % TPA, a_src = src[arow]; + const uint8_t* ap = a + (long)max(a_src, 0) * m.ar + a0 * 16; + const int wcol = tid / TPW, w0c = tid % TPW, ecol = tid / KB, ekb = tid % KB, skb = tid / BM; + const int sa_src = tid < BM * SAK ? src[tid % BM] : -1; + const float* asp = as + (long)max(sa_src, 0) * m.asr; + const int rowbase = wave_row * 16 + (lane >> 4) * 8, colw = wave_col * 16 * TC; + const bool live = first + wave_row * 16 < end; + const uint8_t *wp = w, *ep = ws; + bool wvalid = false, evalid = false; + auto columns = [&](int col0) { + const int wn = col0 + wcol, wi = wn % pw, en = col0 + ecol, ei = en % pw; + wvalid = wn < m.N && wi < cw; + wp = w + (long)((wn / pw) * cw + wi) * m.wrow[cls] + w0c * 16; + evalid = tid < BN * KB && en < m.N && ei < cw; + ep = ws + (long)((en / pw) * cw + ei) * m.srow[cls]; + }; + if constexpr (Resident) { +#pragma unroll + for (int i = 0; i < G::RCh; ++i) { + const int d = (a0 + i * TPA) * 16; + r4d_u32x4 v{ 0, 0, 0, 0 }; + if (a_src >= 0 && d < kc) __builtin_memcpy(&v, ap + i * TPA * 16, 16); + *reinterpret_cast(aa + arow * PA + d) = v; + } + if (tid < BM * SAK) sa[tid] = sa_src >= 0 && skb * 128 < kc ? asp[skb] : 0; + } + const int ksn = (kc + StageK - 1) / StageK, + tiles = Resident ? min(CT, (m.N - colb + BN - 1) / BN) : 1, S = tiles * ksn; + r4d_u32x4 ra[Resident ? 1 : G::ACh], rw[G::WCh]; + uint32_t re = 0x7f7f7f7fu; + float rsa = 0; + int cur = -1; + auto load = [&](int s) { + const int tile = s / ksn, k0 = (s - tile * ksn) * StageK; + if (tile != cur) { + cur = tile; + columns(colb + tile * BN); + } + if constexpr (!Resident) { +#pragma unroll + for (int i = 0; i < G::ACh; ++i) { + ra[i] = r4d_u32x4{ 0, 0, 0, 0 }; + if (a_src >= 0 && k0 + (a0 + i * TPA) * 16 < kc) + __builtin_memcpy(&ra[i], ap + k0 + i * TPA * 16, 16); + } + if (tid < BM * KB) rsa = sa_src >= 0 && k0 + skb * 128 < kc ? asp[k0 / 128 + skb] : 0; + } +#pragma unroll + for (int i = 0; i < G::WCh; ++i) { + rw[i] = r4d_u32x4{ 0, 0, 0, 0 }; + if (wvalid && k0 + (w0c + i * TPW) * 32 < kc) + rw[i] = mx_ldg16(wp + k0 / 2 + i * TPW * 16); + } + re = 0x7f7f7f7fu; + if (evalid && k0 + ekb * 128 < kc) re = mx_ldg4(ep + (k0 + ekb * 128) / 32); + }; + auto store = [&](int b) { + if constexpr (!Resident) { +#pragma unroll + for (int i = 0; i < G::ACh; ++i) + *reinterpret_cast(aa + b * BM * PA + arow * PA + (a0 + i * TPA) * 16) = + ra[i]; + if (tid < BM * KB) sa[b * SAK * BM + tid] = rsa; + } +#pragma unroll + for (int i = 0; i < G::WCh; ++i) { +#pragma unroll + for (int t = 0; t < 4; ++t) + *reinterpret_cast(bb + b * BN * PB + wcol * PB + (w0c + i * TPW) * 32 + + 8 * t) = mx_codes8(rw[i][t]); + } + if (tid < BN * KB) { +// E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable +// subnormal, and code 255 is NaN. +#pragma unroll + for (int g = 0; g < 4; ++g) { + const uint32_t exp = (re >> (8 * g)) & 0xffu; + ss[b * 4 * KB * BN + (ekb * 4 + g) * BN + ecol] = + __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? (exp << 23) + : 0x00400000u); + } + } + }; + r4d_fp8::f8v total[TC]; +#pragma unroll + for (int t = 0; t < TC; ++t) total[t] = r4d_fp8::acc_zero(); + auto compute = [&](int s, int b) { + const int k0 = (s % ksn) * StageK; + const uint8_t *ab = aa + b * BM * PA, *bp = bb + b * BN * PB; + const float* sp = ss + b * 4 * KB * BN; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= kc) break; + const float* sar = sa + b * SAK * BM + (Resident ? k0 / 128 + kb : kb) * BM + rowbase; + float activation[8]; +#pragma unroll + for (int row = 0; row < 8; ++row) activation[row] = sar[row]; + const int ka = (Resident ? k0 : 0) + kb * 128; +#pragma unroll + for (int group = 0; group < 4; ++group) { + const auto fa0 = r4d_fp8::frag(ab, wave_row * 16, ka + group * 32, lane); + const auto fa1 = r4d_fp8::frag(ab, wave_row * 16, ka + group * 32 + 16, lane); +#pragma unroll + for (int t = 0; t < TC; ++t) { + auto raw = r4d_fp8::mma( + fa0, r4d_fp8::frag(bp, colw + t * 16, kb * 128 + group * 32, lane), + r4d_fp8::acc_zero()); + raw = r4d_fp8::mma( + fa1, + r4d_fp8::frag(bp, colw + t * 16, kb * 128 + group * 32 + 16, lane), + raw); + const float scale = sp[(kb * 4 + group) * BN + colw + t * 16 + (lane & 15)]; +// A dropped row folds zeros (or NaN under a code-255 scale) and is written as 0. +#pragma unroll + for (int row = 0; row < 8; ++row) + total[t][row] += raw[row] * activation[row] * scale; + } + // One group's TC chains at a time: they already give the WMMA pipe independent + // work, and a second group in flight would double the raw registers. + sched_barrier(); + } + } + }; + auto epilogue = [&](int col0) { + if (m.stage_out) { + if (live) { +#pragma unroll + for (int t = 0; t < TC; ++t) { +#pragma unroll + for (int row = 0; row < 8; ++row) + *reinterpret_cast(bb + (rowbase + row) * PO + + 2 * (colw + t * 16 + (lane & 15))) = + src[rowbase + row] >= 0 ? f32_to_bf16(total[t][row]) : 0; + } + } + lds_barrier(); + for (int j = tid; j < BM * BN / 8; j += Threads) { + const int r = j / (BN / 8), c = (j % (BN / 8)) * 8, n = col0 + c; + if (first + r >= end || n >= m.N) continue; + const r4d_u32x4 v = *reinterpret_cast(bb + r * PO + 2 * c); + uint16_t* dst = y + (long)(first + r) * m.yr + n; + if (m.out16 && n + 8 <= m.N) + *reinterpret_cast(dst) = v; + else + for (int q = 0; q < 8 && n + q < m.N; ++q) + dst[q] = (uint16_t)(v[q / 2] >> (16 * (q & 1))); + } + lds_barrier(); + } else if (live) { +#pragma unroll + for (int t = 0; t < TC; ++t) { +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = first + rowbase + row, n = col0 + colw + t * 16 + (lane & 15); + if (r < end && n < m.N) + y[(long)r * m.yr + n] = + src[rowbase + row] >= 0 ? f32_to_bf16(total[t][row]) : 0; + } + } + } + }; + load(0); + if constexpr (DB) { + store(0); + lds_barrier(); + } + for (int s = 0; s < S; ++s) { + if constexpr (DB) { + if (s + 1 < S) load(s + 1); + if (live) compute(s, s & 1); + if (s + 1 < S) store((s + 1) & 1); + } else { + store(0); + lds_barrier(); + if (s + 1 < S) load(s + 1); + if (live) compute(s, 0); + } + lds_barrier(); + if (s % ksn == ksn - 1) { + epilogue(colb + (s / ksn) * BN); +#pragma unroll + for (int t = 0; t < TC; ++t) total[t] = r4d_fp8::acc_zero(); + } + } +} + +/* The decode form, expert-major: a block per (column block, expert) takes every row of its expert + * in 16-row tiles, so an expert slice is read from memory once however its rows fall in the + * sorted order (row groups re-read it once per group its run spans). Parallelism is column + * blocks times touched experts. Split-K would sum partials in another order than the row-group + * form and lose its bits, so each element keeps that form's sequence: per 128 of K in order, per + * 32-wide group a fresh WMMA pair, folded as raw * activation scale * E8M0 scale. + * + * A stage of StageK of K is loaded into registers while the previous one computes from LDS; at + * gate_up's K of 4096 the 256 stage measured fastest. Block row `experts` zeroes the dropped rows + * past offset[experts]. */ +template +__global__ __launch_bounds__(32 * Waves) void moe_mxfp4_expert_kernel( + const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, + const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + constexpr int BN = 16 * Waves, Threads = 32 * Waves, KB = StageK / 128, P = StageK + 8; + constexpr int AChunks = StageK / Threads, WChunks = BN * StageK / 32 / Threads; + constexpr int SChunks = (BN * KB + Threads - 1) / Threads; + static_assert(StageK % Threads == 0 && (BN * StageK / 32) % Threads == 0 && 16 * KB <= Threads, + "stage chunks must divide evenly over the block"); + __shared__ __align__(16) uint8_t aa[16 * P], bb[BN * P]; + __shared__ uint32_t ss[BN * KB]; + __shared__ float sa[16 * KB]; + __shared__ int src[16]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, col0 = blockIdx.x * BN, + e = blockIdx.y; + if (e == m.experts) { + const int r0 = offset[m.experts]; + for (long i = tid; i < (long)(m.T - r0) * BN; i += Threads) { + const int n = col0 + (int)(i % BN); + if (n < m.N) y[(long)(r0 + i / BN) * m.yr + n] = 0; + } + return; + } + const int lo = offset[e], hi = offset[e + 1]; + if (lo >= hi) return; + const int cls = e & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], e / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], e / 2); + const int rowbase = (lane >> 4) * 8, mycol = wave * 16 + (lane & 15); + auto wrow = [&](int c, bool& valid) { + const int n = col0 + c, within = n % pw; + valid = n < m.N && within < cw; + return (n / pw) * cw + within; + }; + for (int r0 = lo; r0 < hi; r0 += 16) { + __syncthreads(); + if (tid < 16) { + const int r = r0 + tid, flat = r < hi ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + __syncthreads(); + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = src[rowbase + j] >= 0; + uint4 ra[AChunks], rw[WChunks]; + uint32_t rs[SChunks]; + float rsa = 0; + auto load = [&](int k0) { +#pragma unroll + for (int i = 0; i < AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16, ar = src[r]; + ra[i] = uint4{ 0, 0, 0, 0 }; + if (ar >= 0 && k0 + d < kc) + __builtin_memcpy(&ra[i], a + (long)ar * m.ar + k0 + d, 16); + } +#pragma unroll + for (int i = 0; i < WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; + bool valid; + const int wn = wrow(c, valid); + rw[i] = uint4{ 0, 0, 0, 0 }; + if (valid && k0 + 2 * d < kc) + __builtin_memcpy(&rw[i], w + (long)wn * m.wrow[cls] + k0 / 2 + d, 16); + } +#pragma unroll + for (int i = 0; i < SChunks; ++i) { + const int j = tid + i * Threads, c = j / KB, kb = k0 + (j % KB) * 128; + bool valid; + const int wn = wrow(c, valid); + rs[i] = 0x7f7f7f7fu; + if (j < BN * KB && valid && kb < kc) + __builtin_memcpy(&rs[i], ws + (long)wn * m.srow[cls] + kb / 32, 4); + } + if (tid < 16 * KB) { + const int ar = src[tid / KB], kb = k0 + (tid % KB) * 128; + rsa = ar >= 0 && kb < kc ? as[(long)ar * m.asr + kb / 128] : 0; + } + }; + auto store = [&]() { +#pragma unroll + for (int i = 0; i < AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16; + *reinterpret_cast(aa + r * P + d) = ra[i]; + } +#pragma unroll + for (int i = 0; i < WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; + const uint32_t q[4] = { rw[i].x, rw[i].y, rw[i].z, rw[i].w }; +#pragma unroll + for (int t = 0; t < 4; ++t) + *reinterpret_cast(bb + c * P + 2 * d + 8 * t) = mx_codes8(q[t]); + } +#pragma unroll + for (int i = 0; i < SChunks; ++i) { + const int j = tid + i * Threads; + if (j < BN * KB) ss[j] = rs[i]; + } + if (tid < 16 * KB) sa[tid] = rsa; + }; + auto total = r4d_fp8::acc_zero(); + load(0); + for (int k0 = 0; k0 < kc; k0 += StageK) { + store(); + __syncthreads(); + if (k0 + StageK < kc) load(k0 + StageK); +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= kc) break; + const uint32_t exps = ss[mycol * KB + kb]; +#pragma unroll + for (int group = 0; group < 4; ++group) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = kb * 128 + group * 32; k < kb * 128 + (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag(aa, 0, k, lane), + r4d_fp8::frag(bb, wave * 16, k, lane), raw); + const uint32_t exp = (exps >> (8 * group)) & 0xffu; + const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? (exp << 23) + : 0x00400000u); +#pragma unroll + for (int row = 0; row < 8; ++row) + if (rv[row]) total[row] += raw[row] * sa[(rowbase + row) * KB + kb] * scale; + } + } + __syncthreads(); + } +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = r0 + rowbase + row, n = col0 + mycol; + if (r < hi && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]); + } + } +} + +/* The expert-major form for a short K, same per-element sequence as the one above: a block walks + * ColTiles column tiles of 64, each over K in stages of StageK, as one stage sequence with the + * next stage loaded into registers while the current one computes. At down's K of 256 a single + * stage leaves a block nothing to overlap; 128 stages over four tiles give it eight, and halve + * LDS and registers a block, so twice the blocks are resident. Measured fastest for down at + * every routed-row count up to 16384, prefill forms included. A deeper prefetch, two-wave + * blocks and non-temporal weight loads measured slower. */ +typedef unsigned mx_u4 __attribute__((ext_vector_type(4))); +template +struct MxStage { + static constexpr int Threads = 128, BN = 64, KB = StageK / 128; + static constexpr int AChunks = StageK / Threads, WChunks = BN * StageK / 32 / Threads; + static constexpr int SChunks = (BN * KB + Threads - 1) / Threads; + mx_u4 a[AChunks], w[WChunks]; + uint32_t s[SChunks]; + float sa; +}; +template +__global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel( + const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, + const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + using St = MxStage; + constexpr int BN = St::BN, Threads = St::Threads, KB = St::KB, P = StageK + 8; + static_assert(StageK % Threads == 0 && (BN * StageK / 32) % Threads == 0 && 16 * KB <= Threads, + "stage chunks must divide evenly over the block"); + __shared__ __align__(16) uint8_t aa[16 * P], bb[BN * P]; + __shared__ uint32_t ss[BN * KB]; + __shared__ float sa[16 * KB]; + __shared__ int src[16]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, e = blockIdx.y; + const int colb = blockIdx.x * (BN * ColTiles); + if (e == m.experts) { + const int r0 = offset[m.experts]; + for (long i = tid; i < (long)(m.T - r0) * BN * ColTiles; i += Threads) { + const int n = colb + (int)(i % (BN * ColTiles)); + if (n < m.N) y[(long)(r0 + i / (BN * ColTiles)) * m.yr + n] = 0; + } + return; + } + const int lo = offset[e], hi = offset[e + 1]; + if (lo >= hi) return; + const int cls = e & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], e / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], e / 2); + const int ksn = (kc + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + BN - 1) / BN), + S = tiles * ksn; + const int rowbase = (lane >> 4) * 8, mycol = wave * 16 + (lane & 15); + auto wrow = [&](int n, bool& valid) { + const int within = n % pw; + valid = n < m.N && within < cw; + return (n / pw) * cw + within; + }; + for (int r0 = lo; r0 < hi; r0 += 16) { + __syncthreads(); + if (tid < 16) { + const int r = r0 + tid, flat = r < hi ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + __syncthreads(); + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = src[rowbase + j] >= 0; + auto load = [&](int s, St& R) { + const int col0 = colb + (s / ksn) * BN, k0 = (s % ksn) * StageK; +#pragma unroll + for (int i = 0; i < St::AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16, ar = src[r]; + R.a[i] = mx_u4{ 0, 0, 0, 0 }; + if (ar >= 0 && k0 + d < kc) + __builtin_memcpy(&R.a[i], a + (long)ar * m.ar + k0 + d, 16); + } +#pragma unroll + for (int i = 0; i < St::WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; + bool valid; + const int wn = wrow(col0 + c, valid); + R.w[i] = mx_u4{ 0, 0, 0, 0 }; + if (valid && k0 + 2 * d < kc) + __builtin_memcpy(&R.w[i], w + (long)wn * m.wrow[cls] + k0 / 2 + d, 16); + } +#pragma unroll + for (int i = 0; i < St::SChunks; ++i) { + const int j = tid + i * Threads, c = j / KB, kb = k0 + (j % KB) * 128; + bool valid; + const int wn = wrow(col0 + c, valid); + R.s[i] = 0x7f7f7f7fu; + if (j < BN * KB && valid && kb < kc) + __builtin_memcpy(&R.s[i], ws + (long)wn * m.srow[cls] + kb / 32, 4); + } + if (tid < 16 * KB) { + const int ar = src[tid / KB], kb = k0 + (tid % KB) * 128; + R.sa = ar >= 0 && kb < kc ? as[(long)ar * m.asr + kb / 128] : 0; + } + }; + auto store = [&](const St& R) { +#pragma unroll + for (int i = 0; i < St::AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16; + *reinterpret_cast(aa + r * P + d) = R.a[i]; + } +#pragma unroll + for (int i = 0; i < St::WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; +#pragma unroll + for (int t = 0; t < 4; ++t) + *reinterpret_cast(bb + c * P + 2 * d + 8 * t) = + mx_codes8(R.w[i][t]); + } +#pragma unroll + for (int i = 0; i < St::SChunks; ++i) { + const int j = tid + i * Threads; + if (j < BN * KB) ss[j] = R.s[i]; + } + if (tid < 16 * KB) sa[tid] = R.sa; + }; + auto total = r4d_fp8::acc_zero(); + auto compute = [&](int s) { + const int k0 = (s % ksn) * StageK; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= kc) break; + const uint32_t exps = ss[mycol * KB + kb]; +#pragma unroll + for (int group = 0; group < 4; ++group) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = kb * 128 + group * 32; k < kb * 128 + (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag(aa, 0, k, lane), + r4d_fp8::frag(bb, wave * 16, k, lane), raw); + const uint32_t exp = (exps >> (8 * group)) & 0xffu; + const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? (exp << 23) + : 0x00400000u); +#pragma unroll + for (int row = 0; row < 8; ++row) + if (rv[row]) total[row] += raw[row] * sa[(rowbase + row) * KB + kb] * scale; + } + } + if (s % ksn == ksn - 1) { + const int n = colb + (s / ksn) * BN + mycol; +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = r0 + rowbase + row; + if (r < hi && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]); + } + total = r4d_fp8::acc_zero(); + } + }; + St R; + load(0, R); + for (int s = 0; s < S; ++s) { + store(R); + __syncthreads(); + if (s + 1 < S) load(s + 1, R); + compute(s); + __syncthreads(); + } + } +} + +int table(const RadTensor* t, uint32_t dtype, int bits, long experts, long n, long k, long* step, + int* row) { + if (!t || !t->data || t->rank != 3 || t->dtype != dtype || t->shape[0] < experts || + t->shape[1] != n || t->shape[2] != k || t->stride[2] != 1 || t->stride[1] < k || + (t->stride[1] * bits) % 8 || t->stride[1] * bits / 8 > INT_MAX) + return RAD_E_SHAPE; + if (t->stride[0] && (t->stride[0] < n * t->stride[1] || (t->stride[0] * bits) % 8)) + return RAD_E_STRIDE; + *step = t->stride[0] * bits / 8; + *row = (int)(t->stride[1] * bits / 8); + return RAD_OK; +} +int body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 9) return RAD_E_INVAL; + const auto *aq = rad_arg_in(a, 0), *as = rad_arg_in(a, 1), *sorted = rad_arg_in(a, 4), + *off = rad_arg_in(a, 5); + const auto* y = rad_arg_in(a, 8); + if (!aq || !as || !sorted || !off || !y) return RAD_E_INVAL; + MxMeta m{}; + const long n0 = r4d_geti_or(a, "N", 0), k0 = r4d_geti_or(a, "K", 0); + const long nn[2] = { n0, r4d_geti_or(a, "N_odd", n0) }, + kk[2] = { k0, r4d_geti_or(a, "K_odd", k0) }; + const long ne = r4d_geti_or(a, "n_expert", 0), top = r4d_geti_or(a, "top_k", 0), + parts = r4d_geti_or(a, "parts", 1); + if (ne < 2 || ne > 512 || top < 1 || top > ne || parts < 1 || parts > INT_MAX || + r4d_geti_or(a, "group", 0) != 128) + return RAD_E_SHAPE; + const RadTensor* w[2] = { rad_arg_in(a, 2), rad_arg_in(a, 6) }; + const RadTensor* s[2] = { rad_arg_in(a, 3), rad_arg_in(a, 7) }; + for (int q = 0; q < 2; ++q) { + if (nn[q] < 1 || nn[q] > INT_MAX - 16 || kk[q] < 128 || kk[q] > INT_MAX || kk[q] % 128 || + nn[q] % parts) + return RAD_E_SHAPE; + m.n[q] = (int)nn[q]; + m.k[q] = (int)kk[q]; + int rc = + table(w[q], RAD_FP4E2M1, 4, (ne + 1 - q) / 2, nn[q], kk[q], &m.wstep[q], &m.wrow[q]); + if (rc < 0) return rc; + const uint32_t dt = s[q] ? s[q]->dtype : 0; + if (dt != RAD_U8 && dt != RAD_E8M0) return RAD_E_DTYPE; + rc = table(s[q], dt, 8, (ne + 1 - q) / 2, nn[q], kk[q] / 32, &m.sstep[q], &m.srow[q]); + if (rc < 0) return rc; + } + m.N = (int)std::max(nn[0], nn[1]); + m.K = (int)std::max(kk[0], kk[1]); + if (aq->dtype != RAD_F8E4M3 || as->dtype != RAD_F32 || y->dtype != RAD_BF16 || + sorted->dtype != RAD_I32 || off->dtype != RAD_I32) + return RAD_E_DTYPE; + if (aq->rank != 2 || aq->shape[0] > INT_MAX || aq->shape[1] != m.K || aq->stride[1] != 1 || + aq->stride[0] < m.K || as->rank != 2 || as->shape[0] != aq->shape[0] || + as->shape[1] != m.K / 128 || as->stride[1] != 1 || as->stride[0] < m.K / 128 || + y->rank != 2 || y->shape[0] < 1 || y->shape[0] > INT_MAX || y->shape[1] != m.N || + y->stride[1] != 1 || y->stride[0] < m.N || sorted->rank != 1 || sorted->stride[0] != 1 || + sorted->shape[0] < y->shape[0] || off->rank != 1 || off->stride[0] != 1 || + off->shape[0] < ne + 1) + return RAD_E_SHAPE; + const char* ord = r4d_gets(a, "a_order"); + if (!ord || (std::strcmp(ord, "token") && std::strcmp(ord, "sorted"))) return RAD_E_INVAL; + m.sorted_a = !std::strcmp(ord, "sorted"); + m.T = (int)y->shape[0]; + m.Arows = (int)aq->shape[0]; + if (m.T % top || m.Arows < (m.sorted_a ? m.T : m.T / top)) return RAD_E_SHAPE; + m.experts = (int)ne; + m.topk = (int)top; + m.parts = (int)parts; + m.ar = aq->stride[0]; + m.asr = as->stride[0]; + m.yr = y->stride[0]; + m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16; + // Validated GLM projections at TP4 and TP8: retain the small/decode path and other models. + const bool glm_prefill = ne == 288 && top == 8 && nn[0] == nn[1] && kk[0] == kk[1] && + ((parts == 2 && (nn[0] == 1024 || nn[0] == 512) && kk[0] == 4096) || + (parts == 1 && nn[0] == 4096 && (kk[0] == 512 || kk[0] == 256))); + auto enabled = [&](const char* name) { + const char* v = std::getenv(name); + return v ? v[0] == '1' : glm_prefill; + }; + /* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted + * rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form + * overtakes it, down up to 6143 rows (at 8192 the pipelined prefill form reads the slice + * 2.2 times less often and wins by a quarter). Other shapes keep the decode band. The environment + * moves the bounds, forces either side (RADIANCE_MXFP4_DECODE_EXPERTS 0 or 1) and pins stage + * and tiles, for the microbenchmark. */ + const char* lut_env = std::getenv("RADIANCE_MXFP4_LUT"); + const bool lut = lut_env ? lut_env[0] == '1' : true; + auto env_long = [](const char* name, long dflt) { + const char* v = std::getenv(name); + return v && *v ? std::strtol(v, nullptr, 10) : dflt; + }; + const long max_t = + env_long(m.sorted_a ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN" + : "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP", + glm_prefill && (nn[0] == 512 || kk[0] == 256) ? (m.sorted_a ? 6143 : 768) : 511); + const char* experts_env = std::getenv("RADIANCE_MXFP4_DECODE_EXPERTS"); + /* The P64 form from a routed-row bound per projection, ahead of the expert-major band (its + * down bound overlaps it): gate_up from 769 rows, where the prefill forms begin, down from + * 20 rows an expert at GLM's 288. Default at GLM's TP8 slices only, the measured ones + * (RADIANCE_MXFP4_PREFILL_P64=0 keeps the TP8 prefill form of stage 1, which also takes a grid + * P64 cannot address). The + * tile follows the rows an expert, measured at the TP8 slices (perfmx, cold): down BM32 BN64 + * K128 over four column tiles up to 3072 tokens (2048: 647 against 831 us), above BM64 BN128 + * K128 x4 with the LDS output (4096: 1101 against 1607); gate_up BM32 BN64 K256 up to 1536 + * tokens (768: 563 against 660), BM64 BN64 K256 up to 3072 (2048: 941 against 995), above + * BM64 BN128 K128 with the LDS output (4096: 1715 against 1915). BM, BN, stage, column tiles, + * the LDS output, the double buffer and the three row bounds move with the environment, and a + * forced expert-major form (DECODE_EXPERTS=1) keeps precedence. */ + const char* p64_env = std::getenv("RADIANCE_MXFP4_PREFILL_P64"); + const bool resident = m.K <= 256; + long dbm = 32, dbn = 64, dsk = 128, dout = 0; + if (resident) { + if (m.T >= env_long("RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", 24576)) { + dbm = 64; + dbn = 128; + dout = 1; + } + } else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BM64", 12288)) + dsk = 256; + else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BN128", 24576)) { + dbm = 64; + dsk = 256; + } else { + dbm = 64; + dbn = 128; + dout = 1; + } + const long bm = env_long("RADIANCE_MXFP4_PREFILL_P64_BM", dbm) == 32 ? 32 : 64; + const bool tp8 = glm_prefill && (nn[0] == 512 || kk[0] == 256); + if ((p64_env ? p64_env[0] == '1' : tp8) && !(experts_env && experts_env[0] == '1') && + m.T >= env_long(m.sorted_a ? "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN" + : "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + m.sorted_a ? 5760 : 769) && + (m.T + bm - 1) / bm + m.experts <= 65535) { + const long bn = env_long("RADIANCE_MXFP4_PREFILL_P64_BN", dbn) == 64 ? 64 : 128; + const long sk = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", dsk) == 256 ? 256 : 128; + const long ct = resident && env_long("RADIANCE_MXFP4_PREFILL_P64_COLTILES", 4) != 1 ? 4 : 1; + m.stage_out = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", dout) == 1; + // The double buffer exists where two stages fit in 64 KiB of LDS: every 128 stage, and + // the 256 stage at BM32 BN64. + const bool db = !resident && env_long("RADIANCE_MXFP4_PREFILL_P64_DB", 0) == 1 && + (sk == 128 || (bm == 32 && bn == 64)); + m.out16 = (reinterpret_cast(y->data) & 15) == 0 && m.yr % 8 == 0; + const long jobs = (m.T + bm - 1) / bm + m.experts; +#define MX_P64(BM, BN, SK, CT, R) \ + R4D_EMIT(stream, (moe_mxfp4_p64_kernel), \ + dim3(((long)m.N + BN * CT - 1) / (BN * CT), jobs), dim3(256), 0, \ + (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \ + s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) +#define MX_P64D(BM, BN, SK) \ + R4D_EMIT(stream, (moe_mxfp4_p64_kernel), \ + dim3(((long)m.N + BN - 1) / BN, jobs), dim3(256), 0, (const uint8_t*)aq->data, \ + (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, s[1]->data, \ + (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) + if (db) { + if (sk == 256) return MX_P64D(32, 64, 256); + if (bm == 32) return bn == 64 ? MX_P64D(32, 64, 128) : MX_P64D(32, 128, 128); + return bn == 64 ? MX_P64D(64, 64, 128) : MX_P64D(64, 128, 128); + } +#undef MX_P64D +#define MX_P64_SK(BM, BN, CT, R) \ + return sk == 256 ? MX_P64(BM, BN, 256, CT, R) : MX_P64(BM, BN, 128, CT, R); +#define MX_P64_BN(BM, CT, R) \ + if (bn == 64) { MX_P64_SK(BM, 64, CT, R) } \ + MX_P64_SK(BM, 128, CT, R) +#define MX_P64_BM(CT, R) \ + if (bm == 32) { MX_P64_BN(32, CT, R) } \ + MX_P64_BN(64, CT, R) + if (!resident) { MX_P64_BM(1, false) } + if (ct == 1) { MX_P64_BM(1, true) } + MX_P64_BM(4, true) +#undef MX_P64_BM +#undef MX_P64_BN +#undef MX_P64_SK +#undef MX_P64 + } + if (experts_env ? experts_env[0] == '1' : max_t < 0 || m.T <= max_t) { + const long stage = env_long("RADIANCE_MXFP4_EXPERTS_STAGE_K", m.K <= 256 ? 128 : 256); + const long tiles = env_long("RADIANCE_MXFP4_EXPERTS_COLTILES", m.K <= 256 ? 4 : 1); +#define MX_EXPERTS(KERNEL, C) \ + R4D_EMIT(stream, KERNEL, dim3(((long)m.N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), \ + 0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \ + w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \ + (uint16_t*)y->data, m) +#define MX_EXPERTS_LUT(L) \ + if (stage == 128) \ + return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 4, L>), 4) \ + : MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 1, L>), 1); \ + return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<256, 4, L>), 4) \ + : MX_EXPERTS((moe_mxfp4_expert_kernel<4, 256, L>), 1); + if (lut) { MX_EXPERTS_LUT(true) } + MX_EXPERTS_LUT(false) +#undef MX_EXPERTS_LUT +#undef MX_EXPERTS + } + m.aligned_jobs = enabled("RADIANCE_MXFP4_ALIGNED_JOBS") && m.T >= 512; + const bool wide = enabled("RADIANCE_MXFP4_PREFILL_N32") && m.T >= 512; + const bool tall = wide && m.aligned_jobs && enabled("RADIANCE_MXFP4_PREFILL_M32"); + const int job_rows = tall ? 32 : 16; + const int jobs = + m.aligned_jobs ? (m.T + job_rows - 1) / job_rows + m.experts : (m.T + m.tile - 1) / m.tile; + if (jobs > 65535) return RAD_E_SHAPE; +#define MX_EMIT(CT, RT, CACHE, L) \ + R4D_EMIT(stream, (moe_mxfp4_fp8_kernel), \ + dim3(((long)m.N + 16 * CT - 1) / (16 * CT), jobs), dim3(32 * CT * RT), 0, \ + (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \ + s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) +#define MX_PIPE(L) \ + R4D_EMIT(stream, (moe_mxfp4_prefill_kernel), dim3(((long)m.N + 63) / 64, jobs), dim3(256), \ + 0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \ + w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \ + (uint16_t*)y->data, m) + const char* cached = std::getenv("RADIANCE_MXFP4_PREFILL_CACHE_ROWS"); + const bool pipe = enabled("RADIANCE_MXFP4_PREFILL_PIPE"); +#define MX_EMIT_LUT(L) \ + if (tall && enabled("RADIANCE_MXFP4_PREFILL_N64")) { \ + if (cached ? cached[0] == '1' : glm_prefill) \ + return pipe ? MX_PIPE(L) : MX_EMIT(4, 2, true, L); \ + return MX_EMIT(4, 2, false, L); \ + } \ + if (tall) return MX_EMIT(2, 2, false, L); \ + if (wide) return MX_EMIT(2, 1, false, L); \ + return MX_EMIT(1, 1, false, L); + if (lut) { MX_EMIT_LUT(true) } + MX_EMIT_LUT(false) +#undef MX_EMIT_LUT +#undef MX_PIPE +#undef MX_EMIT +} +} +extern "C" int r4d_rad_moe_mxfp4(const RadArgs* a, RadStream stream) { return body(a, stream); } diff --git a/libr4d/r4d_moe_sort.h b/libr4d/r4d_moe_sort.h new file mode 100644 index 00000000..12ccba6a --- /dev/null +++ b/libr4d/r4d_moe_sort.h @@ -0,0 +1,198 @@ +// r4d_moe_sort.h -- the routed slots' stable counting sort in one workgroup, shared by every +// kernel that ends in it: moe_scatter's small form and router_topk_scatter (r4d_moe.hip), and +// GLM's router_sigmoid_topk_scatter (r4d_glm.hip). One definition, so a fused selection and the +// standalone sort place every slot alike; tests/r4d_emu runs it from here. +#pragma once +#include +#include +#include + +#include "r4d_args.h" +#include "r4d_common.h" + +// Internal linkage, as each unit's own definitions had: the same code generation in every kernel +// that takes the sort. +namespace r4d_moesort { +namespace { + +constexpr uint32_t kSortWave = 32; +/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in + * registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers + * Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router + * instantiation. */ +constexpr uint32_t kMaxExpert = 512; + +/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output + * dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort + * places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and + * [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an + * expert's place is itself. */ +constexpr uint32_t kMaxProtect = 8; +struct Protect { + uint32_t n; + uint16_t e[kMaxProtect]; +}; + +/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */ +__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) { + int32_t below = 0; + for (uint32_t j = 0; j < p.n; ++j) { + if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j); + below += (int32_t)p.e[j] < e; + } + return e - below; +} + +/* `protect`, a comma list of local expert indices: strictly ascending, inside the slice, at most + * kMaxProtect. Absent or empty is none. */ +inline int protect_of(const RadArgs* a, long long n_local, Protect* p) { + *p = Protect{}; + const char* s = r4d_gets(a, "protect"); + if (!s) return RAD_OK; + long long prev = -1; + while (*s) { + char* end = nullptr; + const long long v = std::strtoll(s, &end, 10); + if (end == s || v <= prev || v >= n_local || p->n >= kMaxProtect) + return R4D_NO(RAD_E_SHAPE); + p->e[p->n++] = (uint16_t)v; + prev = v; + s = end; + if (*s == ',') ++s; + else if (*s) return R4D_NO(RAD_E_SHAPE); + } + return RAD_OK; +} + +/* ================================================================== the small sort + * + * One workgroup does the whole sort, for T <= kScatterSmall, which covers every decode and verify + * step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch instead of three. + * Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert counts, and each slot + * placed by its rank inside its expert's run. + * + * On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work: + * + * - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one + * barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts). + * - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its + * expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's + * place is the number of the run's slots with a lower index. That count is as long as the run + * (a row picks an expert at most once), far shorter than counting all earlier slots. + * + * Stable and byte-identical: a slot's place is its position among the same expert's slots in + * ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so + * none waits on or invalidates the vector memory path. */ +constexpr uint32_t kScatterSmall = 1024; + +/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the + * workgroup's wave count, which sizes the scan's exchange. */ +template +struct ScatterLds { + static constexpr uint32_t kTiles = (kMaxExpert + NW * kSortWave - 1) / (NW * kSortWave); + int32_t e[kScatterSmall]; /* the slot list: expert in the slice, or -1 */ + int32_t tk[kScatterSmall]; /* the slot's ticket inside its expert's run */ + int32_t run[kScatterSmall]; /* slots grouped by expert, tickets' order */ + int32_t cnt[kMaxExpert + 1]; + int32_t off[kMaxExpert + 1]; + int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */ +}; + +/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then + * the upper row adds the lower row's total. Lanes shifted in from outside the row read zero + * (bound_ctrl). */ +__device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) { + x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */ + x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */ + x += __builtin_amdgcn_update_dpp(0, x, 0x114, 0xF, 0xF, true); /* row_shr:4 */ + x += __builtin_amdgcn_update_dpp(0, x, 0x118, 0xF, 0xF, true); /* row_shr:8 */ + const int32_t lo = __builtin_amdgcn_readlane(x, 15); + return lane >= 16u ? x + lo : x; +} + +/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has + * written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the + * standalone sort and the fused kernels. The workgroup is exactly NW waves. + * + * INV also writes the inverse: `inv[i]` is slot i's row in `sorted`, -1 for a dropped slot, the + * table moe_gather would otherwise build from `sorted`. */ +template +__device__ __forceinline__ void scatter_small_place( + int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt, + uint32_t T, uint32_t n_expert, ScatterLds& sl, int32_t* __restrict__ inv = nullptr) { + const uint32_t tid = threadIdx.x, lane = tid % kSortWave, wave = tid / kSortWave; + + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1); + } + lds_barrier(); + + /* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same + * in every thread. */ + int32_t carry = 0; + for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kSortWave, ++t) { + const uint32_t e = b + tid; + const int32_t v = (e < n_expert) ? sl.cnt[e] : 0; + const int32_t x = wave_incl_scan_i32(v, lane); + if (lane == kSortWave - 1) sl.wt[t][wave] = x; + lds_barrier(); + int32_t below = 0, tot = 0; +#pragma unroll + for (uint32_t k = 0; k < NW; ++k) { + const int32_t c = sl.wt[t][k]; + below += (k < wave) ? c : 0; + tot += c; + } + if (e < n_expert) { + const int32_t o = carry + below + x - v; /* inclusive -> exclusive */ + sl.off[e] = o; + off[e] = o; + cnt[e] = v; + } + carry += tot; + } + if (tid == 0) off[n_expert] = carry; + lds_barrier(); + + for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1; + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i; + } + lds_barrier(); + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e < 0) { + if constexpr (INV) inv[i] = -1; + continue; + } + const int32_t o = sl.off[e], n = sl.cnt[e]; + int32_t rank = 0; + for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i; + sorted[o + rank] = (int32_t)i; + if constexpr (INV) inv[i] = o + rank; + } +} + +/* moe_scatter's small form: the slot list from `ids`, then the sort. A template only so a unit that + * includes this header and does not launch it compiles no kernel. */ +constexpr uint32_t kScatWaves = 8; /* 256 threads */ +template +__global__ __launch_bounds__(kScatWaves * kSortWave) void scatter_small_kernel( + const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off, + int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot, + int32_t* __restrict__ inv) { + __shared__ ScatterLds sl; + const uint32_t tid = threadIdx.x; + for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0; + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = ids[i] - base; + sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1; + } + lds_barrier(); + scatter_small_place(sorted, off, cnt, T, n_expert, sl, inv); +} + +} // namespace +} // namespace r4d_moesort diff --git a/libr4d/r4d_mxfp4.h b/libr4d/r4d_mxfp4.h index b0d15200..7bb8a002 100644 --- a/libr4d/r4d_mxfp4.h +++ b/libr4d/r4d_mxfp4.h @@ -56,6 +56,15 @@ static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d, unsigned int* lo, unsigned int* hi) { r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi); } +// Row d = 0 as immediates, for kernels that fold the E8M0 scale in F32 and need the exact e2m1 +// values: no table load, v_perm_b32 takes the two words as literals. tests/r4d_emu/test_moemx +// holds them to row 0 of the table. +#define R4D_MXFP4_MAG0_LO 0x3c383000u +#define R4D_MXFP4_MAG0_HI 0x4c484440u +static __device__ __forceinline__ void r4d_mxfp4_unpack8_exact(unsigned int wv, unsigned int* lo, + unsigned int* hi) { + r4d_mxfp4_unpack8_t(wv, R4D_MXFP4_MAG0_LO, R4D_MXFP4_MAG0_HI, lo, hi); +} // The activation scale a row's accumulator is carried in, for the per-(row, 128 of K) grid: the // last non-zero entry of `row` at or before block `kb`, or 1 if none. A zero-scale block has zero diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 52e747c4..7db0f3a9 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -296,6 +296,15 @@ int r4d_rad_dflash_select (const RadArgs*, RadStream); /* -- the gated residual (r4d_hc_bf16.hip) -- */ int r4d_rad_hc_enter (const RadArgs*, RadStream); +int r4d_rad_mhc_pre(const RadArgs*, RadStream); +int r4d_rad_mhc_pre_partial(const RadArgs*, RadStream); +int r4d_rad_mhc_pre_finish(const RadArgs*, RadStream); +int r4d_rad_kda_update(const RadArgs*, RadStream); +int r4d_rad_moe_mxfp4(const RadArgs*, RadStream); +int r4d_rad_layout_moe_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_mhc_post(const RadArgs*, RadStream); +int r4d_rad_mhc_contract(const RadArgs*, RadStream); int r4d_rad_mtp_enter (const RadArgs*, RadStream); int64_t r4d_rad_mtp_enter_scratch(const RadArgs*); int r4d_rad_hc_read (const RadArgs*, RadStream); @@ -604,6 +613,35 @@ int r4d_rad_fill (const RadArgs*, RadStream); int r4d_rad_logit_softcap (const RadArgs*, RadStream); int r4d_rad_scale (const RadArgs*, RadStream); int r4d_rad_silu_mul (const RadArgs*, RadStream); +int r4d_rad_swiglu_clamped(const RadArgs*, RadStream); +int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs*, RadStream); +int r4d_rad_dsa_pool(const RadArgs*, RadStream); +int r4d_shape_dsa_pool(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_dsa_query(const RadArgs*, RadStream); +int r4d_rad_fp8_f32scale(const RadArgs*, RadStream); +int r4d_rad_moe_fp8_f32scale(const RadArgs*, RadStream); +int r4d_layout_fp8_f32scale(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_shape_dsa_query(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_gemm_nt_f32(const RadArgs*, RadStream); +int r4d_shape_gemm_nt_f32(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_mla_project(const RadArgs*, RadStream); +int r4d_shape_mla_project(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_dsa_score(const RadArgs*, RadStream); +int r4d_shape_dsa_score(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_mla_attn(const RadArgs*, RadStream); +int64_t r4d_rad_mla_attn_scratch(const RadArgs*); +int r4d_rad_mla_attn_matrix(const RadArgs*, RadStream); +int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*); +int r4d_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream); +int r4d_shape_router_sigmoid_topk(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_router_sigmoid_topk_scatter(const RadArgs*, RadStream); +int r4d_rad_moe_scatter_inv(const RadArgs*, RadStream); +int r4d_shape_moe_scatter_inv(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_moe_gather_inv(const RadArgs*, RadStream); +int r4d_shape_moe_gather_inv(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_router_sigmoid_topk_scatter(const RadParam*, int, int, RadOpdDesc*); int r4d_rad_gelu_mul (const RadArgs*, RadStream); int r4d_rad_rope (const RadArgs*, RadStream); /* -- the vision tower's ops (r4d_vit_bf16.hip) -- */ @@ -656,6 +694,13 @@ int r4d_shape_scatter_rows_u8(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_cast (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_enter (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_mhc_pre(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_mhc_pre_partial(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_mhc_pre_finish(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_kda_update(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_moe_mxfp4(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_mhc_post(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_mhc_contract(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_read (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_write (const RadParam*, int, int operand, RadOpdDesc*); @@ -750,6 +795,8 @@ int r4d_shape_dflash_select (const RadParam*, int, int operand, RadOpdDesc*); * Pure host code, like r4d_rows.cpp, r4d_layout.cpp and r4d_shapes.cpp. */ int r4d_fuse_rmsnorm_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gated_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index c72dd76b..a4d7038a 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -469,6 +469,50 @@ static const RadParamSpec pHcPlain[] = { static const RadOperandSpec oHcEnter[] = { { "x", RAD_OPD_IN, 0 }, { "h", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pMhcPre[] = { + P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("iterations"), P_F64("eps"), + P_F64("hc_eps"), P_STR("dtype"), +}; +static const RadOperandSpec oMhcPre[] = { + {"h", RAD_OPD_IN, 0}, {"fn", RAD_OPD_WEIGHT, 0}, {"scale", RAD_OPD_WEIGHT, 0}, + {"base", RAD_OPD_WEIGHT, 0}, {"x", RAD_OPD_OUT, 0}, {"post", RAD_OPD_OUT, 0}, + {"comb", RAD_OPD_OUT, 0}, +}; +static const RadParamSpec pMhcPrePartial[] = { + P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("chunk"), P_INT("first"), P_INT("chunks"), + P_STR("dtype"), +}; +static const RadOperandSpec oMhcPrePartial[] = { + {"h", RAD_OPD_IN, 0}, {"fn", RAD_OPD_WEIGHT, 0}, {"part", RAD_OPD_OUT, 0}, +}; +static const RadParamSpec pMhcPreFinish[] = { + P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("iterations"), P_F64("eps"), + P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype"), +}; +static const RadOperandSpec oMhcPreFinish[] = { + {"part", RAD_OPD_IN, 0}, {"h", RAD_OPD_IN, 0}, {"scale", RAD_OPD_WEIGHT, 0}, + {"base", RAD_OPD_WEIGHT, 0}, {"x", RAD_OPD_OUT, 0}, {"post", RAD_OPD_OUT, 0}, + {"comb", RAD_OPD_OUT, 0}, +}; +static const RadOperandSpec oMhcPost[] = { + {"x", RAD_OPD_IN, 0}, {"h", RAD_OPD_IN, 0}, {"post", RAD_OPD_IN, 0}, + {"comb", RAD_OPD_IN, 0}, {"out", RAD_OPD_OUT, 0}, +}; +static const RadOperandSpec oMhcContract[] = { + {"h", RAD_OPD_IN, 0}, {"x", RAD_OPD_OUT, 0}, +}; +static const RadParamSpec pKdaUpdate[] = { + P_INT("M"), P_INT("heads"), P_INT("head_k"), P_INT("head_v"), P_F64("lower_bound"), + P_F64("scale"), P_F64("l2_eps"), P_STR("mode"), P_STR("dtype"), + P_STRO("state_form"), +}; +static const RadOperandSpec oKdaUpdate[] = { + {"q", RAD_OPD_IN, 0}, {"k", RAD_OPD_IN, 0}, {"v", RAD_OPD_IN, 0}, + {"a", RAD_OPD_IN, 0}, {"b", RAD_OPD_IN, 0}, {"A_log", RAD_OPD_WEIGHT, 0}, + {"dt_bias", RAD_OPD_WEIGHT, 0}, {"state", RAD_OPD_INOUT, 0}, {"state_idx", RAD_OPD_IN, 0}, + {"cu", RAD_OPD_IN, 0}, {"num_accepted", RAD_OPD_IN, 1}, {"has_init", RAD_OPD_IN, 1}, + {"o", RAD_OPD_OUT, 0}, +}; static const RadOperandSpec oHcWrite[] = { { "y", RAD_OPD_IN, 0 }, { "inj", RAD_OPD_IN, 0 }, { "h", RAD_OPD_INOUT, 0 }, }; @@ -816,6 +860,16 @@ static const RadOperandSpec oMoeScatter[] = { { "expert_offset", RAD_OPD_OUT, 0 }, { "expert_count", RAD_OPD_OUT, 0 }, }; +/* moe_scatter with each slot's row in `sorted_tok` beside it: moe_gather_inv reads that table + * instead of rebuilding it. Ops of their own, since the shared vocabulary fixes moe_scatter's and + * moe_gather's operands. */ +static const RadOperandSpec oMoeScatterInv[] = { + { "expert_ids", RAD_OPD_IN, 0 }, + { "sorted_tok", RAD_OPD_OUT, 0 }, + { "expert_offset", RAD_OPD_OUT, 0 }, + { "expert_count", RAD_OPD_OUT, 0 }, + { "inverse", RAD_OPD_OUT, 0 }, +}; /* `a_order` ("token" or "sorted") says which rows the activation has: one per token, gathered * through sorted_tok, or one per (token, slot) already in scatter order. A routed block's two * grouped GEMMs differ (gate_up reads the block input, down reads gate_up's output), and the row @@ -902,6 +956,14 @@ static const RadOperandSpec oMoeGather[] = { { "shared_gate", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, }; +static const RadOperandSpec oMoeGatherInv[] = { + { "y_expert", RAD_OPD_IN, 0 }, + { "expert_w", RAD_OPD_IN, 0 }, + { "inverse", RAD_OPD_IN, 0 }, + { "shared", RAD_OPD_IN, 1 }, + { "shared_gate", RAD_OPD_IN, 1 }, + { "y", RAD_OPD_OUT, 0 }, +}; /* `vocab_off` and `pairs` are the vocab-parallel form, both absent on a single-rank graph (which * keeps it byte-identical to the unsplit form). With them, `x` is one rank's slice, `idx` carries @@ -1566,6 +1628,51 @@ static const RadParamSpec pMnDtype[] = { { "n", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; +static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), + P_STR("dtype") }; +static const RadParamSpec pSwigluClampedQuant[] = { P_INT("M"), P_INT("n"), P_F64("limit"), + P_INT("group"), P_STR("dtype") }; +static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), + P_INTO("block_size") }; +static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"), + P_INT("blocks"), P_INT("block_size"), P_F64("scale"), + P_STR("dtype") }; +static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"), + P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") }; +static const RadOperandSpec oMlaAttn[] = { { "q", RAD_OPD_IN, 0 }, + { "kv", RAD_OPD_IN, 0 }, + { "bt", RAD_OPD_IN, 0 }, + { "length", RAD_OPD_IN, 0 }, + { "out", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), + P_INT("blocks"), P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oDsaScore[] = { + { "q", RAD_OPD_IN, 0 }, { "q_scale", RAD_OPD_IN, 0 }, { "gate", RAD_OPD_IN, 0 }, + { "k", RAD_OPD_IN, 0 }, { "k_scale", RAD_OPD_IN, 1 }, { "bt", RAD_OPD_IN, 0 }, + { "cu", RAD_OPD_IN, 0 }, { "nc", RAD_OPD_IN, 0 }, { "score", RAD_OPD_OUT, 0 } +}; +static const RadOperandSpec oDsaPool[] = { + { "kg", RAD_OPD_IN, 0 }, { "ape", RAD_OPD_WEIGHT, 0 }, { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, { "page", RAD_OPD_IN, 1 }, { "cache", RAD_OPD_INOUT, 1 } +}; +static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; +static const RadOperandSpec oRouterSigmoid[] = { + { "logits", RAD_OPD_IN, 0 }, { "bias", RAD_OPD_WEIGHT, 0 }, + { "ids", RAD_OPD_OUT, 0 }, { "weights", RAD_OPD_OUT, 0 } +}; +/* router_sigmoid_topk and moe_scatter as one op, with `ids` named once, and the `fill` of an + * ungated shared arm's gate with 1 as an optional output. */ +static const RadParamSpec pRouterSigmoidScatter[] = { P_INT("M"), P_INT("n_expert"), + P_INTO("n_local"), P_INT("top_k"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype"), + P_INTO("expert_base"), P_STRO("protect") }; +static const RadOperandSpec oRouterSigmoidScatter[] = { + { "logits", RAD_OPD_IN, 0 }, { "bias", RAD_OPD_WEIGHT, 0 }, + { "ids", RAD_OPD_OUT, 0 }, { "weights", RAD_OPD_OUT, 0 }, + { "sorted_tok", RAD_OPD_OUT, 0 }, { "expert_offset", RAD_OPD_OUT, 0 }, + { "expert_count", RAD_OPD_OUT, 0 }, { "gate", RAD_OPD_OUT, 1 }, + { "inverse", RAD_OPD_OUT, 1 } +}; /* `logit_softcap`'s, matching ref's `pMnCap` (spec §2.3). `cap` must be > 0; the op refuses a * non-positive cap (a division by zero in every lane). */ static const RadParamSpec pMnCap[] = { @@ -2432,6 +2539,23 @@ static const RadOpSchema kSchemas[] = { SCHEMA("mul_weight", pMulWeight, oMulWeight, "y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row " "(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."), + SCHEMA("mla_attn", pMlaAttn, oMlaAttn, + "Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths."), + SCHEMA("mla_project", pMlaProject, oGemmNt, + "Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix."), + SCHEMA("dsa_score", pDsaScore, oDsaScore, + "Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf."), + SCHEMA("dsa_pool", pDsaPool, oDsaPool, + "Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8."), + SCHEMA("dsa_query", pMnDtype, oQuantActFp8, + "Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head."), + SCHEMA("gemm_nt_f32", pGemmNt, oGemmNt, + "BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision."), + SCHEMA("swiglu_clamped", pSwigluClamped, oGateUp, + "silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half."), + SCHEMA("swiglu_clamped_quant_fp8", pSwigluClampedQuant, oGatedQuantFp8, + "`swiglu_clamped` then `quant_act_fp8` over its product, in one pass: the codes are " + "taken over the BF16-ROUNDED product, which `out_bf16` receives when present."), SCHEMA("silu_mul", pMnDtype, oGateUp, "y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The GATE IS THE FIRST HALF, " "which is the order rad-convert fuses gate_proj and up_proj in."), @@ -2673,6 +2797,22 @@ static const RadOpSchema kSchemas[] = { "the two ops it replaces."), SCHEMA("hc_enter", pHcPlain, oHcEnter, "h[s] = x for each of the hc streams -- the wide residual stream's first value."), + SCHEMA("mhc_pre", pMhcPre, oMhcPre, + "Whole-residual RMS-scaled projection, sigmoid gates and Sinkhorn mixing; coefficients f32."), + SCHEMA("mhc_pre_partial", pMhcPrePartial, oMhcPrePartial, + "mhc_pre's projection over chunks [first, first+chunks) of `chunk` residual columns: " + "per chunk the hc*(hc+2) coefficient partials and the sum of squares, zero-padded to " + "a multiple of four floats; tensor-parallel ranks each take their chunks."), + SCHEMA("mhc_pre_finish", pMhcPreFinish, oMhcPreFinish, + "mhc_pre from every chunk's partials: chunk sums, gates, Sinkhorn mixing and the " + "collapse of h; the pair is mhc_pre."), + SCHEMA("mhc_post", pHcPlain, oMhcPost, + "out[dst,i] = post[dst]*x[i] + sum_src comb[src,dst]*h[src,i]; separate output."), + SCHEMA("mhc_contract", pHcPlain, oMhcContract, + "Mean over the hc residual streams, rounded once to dtype."), + SCHEMA("kda_update", pKdaUpdate, oKdaUpdate, + "Bounded per-channel KDA recurrence. verify stores candidate states; prefill commits final state. " + "Absolute cu offsets, accepted-prefix read slot, optional cold initialization, no output norm."), SCHEMA("hc_read", pHcRead, oHcRead, "the read half of a gated residual: a grouped rmsnorm, a low-rank sigmoid gate, and " "the mean of the gated streams -- plus the per-branch write gains and, optionally, " @@ -2722,6 +2862,14 @@ static const RadOpSchema kSchemas[] = { "With `add` present the form is y = bf16(x * act(s)) + add: the product is NARROWED " "before the sum, which is what makes the fused form bit-identical to the two ops it " "stands in for rather than merely close to them."), + SCHEMA("router_sigmoid_topk", pRouterSigmoid, oRouterSigmoid, + "Single-group sigmoid routing; correction bias selects experts, original scores weight them."), + SCHEMA("router_sigmoid_topk_scatter", pRouterSigmoidScatter, oRouterSigmoidScatter, + "`router_sigmoid_topk` then `moe_scatter` over its ids, in one launch, and with `gate` " + "present the ungated shared arm's `fill` of its gate with 1; with `inverse` the sort is " + "`moe_scatter_inv`. Every output is the bytes the separate launches write, including a " + "row with fewer finite ranks than top_k. Bounded by the sort's single-workgroup form: " + "M * top_k <= 1024, refused above."), SCHEMA("router_topk", pRouterTopk, oRouterTopk, "softmax over ALL n_expert logits, then the top_k of them by value with ties to the " "lower expert id, then -- if `norm` -- the kept weights renormalised to sum to one. The " @@ -2755,6 +2903,13 @@ static const RadOpSchema kSchemas[] = { "does not depend on the scheduler. `protect` lists local experts sorted LAST, in that " "order, the rest closed up: `expert_offset` and `expert_count` are then in sort order, " "and a layer's protected experts are one trailing run a second grouped GEMM serves."), + SCHEMA("moe_scatter_inv", pMoeScatter, oMoeScatterInv, + "`moe_scatter`, also writing `inverse`: for every slot token*top_k + slot its row in " + "`sorted_tok`, -1 for a dropped slot. That is the table `moe_gather` builds from " + "`sorted_tok` before it sums, so `moe_gather_inv` reads it instead."), + SCHEMA("moe_gather_inv", pMoeGather, oMoeGatherInv, + "`moe_gather` reading the slot table `moe_scatter_inv` wrote instead of rebuilding it " + "from `sorted_tok`: the same sums in ascending slot order, the same bytes."), SCHEMA("moe_gemm", pMoeGemm, oMoeGemm, "y[i] = a[row(i)] @ w[e]^T in SORTED order, e being the expert whose offset range " "contains i, both operands unquantised and one accumulator over K. `a_order` picks " @@ -3662,6 +3817,77 @@ static const RadConstraint cHcReadE4m3[] = { static const RadConstraint cHcPlain[] = { C_GE("M", 1), C_GE("n", 1), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), }; +static const RadConstraint cMhcPlain[] = { + C_GE("M", 1), C_LE("M", 65535), C_GE("n", 1), C_LE("n", 16384), + C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), +}; +/* GLM's split projection only: eight 2048-column chunks of a 4 x 4096 residual. */ +static const RadConstraint cMhcPrePartial[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 4096), C_EQ("hc", 4), C_EQ("chunk", 2048), + C_GE("first", 0), C_LE("first", 7), C_GE("chunks", 1), C_LE("chunks", 8), C_IN("dtype", "bf16"), +}; +static const RadConstraint cMhcPreFinish[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 4096), C_EQ("hc", 4), + C_EQ("chunk", 2048), C_IN("dtype", "bf16"), C_GE("iterations", 1), C_LE("iterations", 256), +}; +static const RadConstraint cKdaUpdate[] = { + C_GE("M", 1), C_GE("heads", 1), C_LE("heads", 65535), + C_EQ("head_k", 128), C_EQ("head_v", 128), C_IN("mode", "prefill verify"), + C_IN("dtype", "bf16"), +}; +static const RadConstraint cMhcPre[] = { + C_GE("M", 1), C_LE("M", 65535), C_GE("n", 1), + C_LE("n", 16384), C_GE("hc", 2), C_LE("hc", 8), + C_IN("dtype", "bf16"), C_GE("iterations", 1), C_LE("iterations", 256), +}; +static const RadConstraint cDsaPool[] = { C_GE("M", 1), C_EQ("n", 128), C_EQ("ratio", 4), + C_IN("dtype", "bf16") }; +static const RadConstraint cDsaQuery[] = { C_GE("M", 1), C_LE("M", 2147483644), C_EQ("n", 128), + C_IN("dtype", "bf16") }; +static const RadConstraint cFp8F32Scale[] = { + C_GE("M", 1), C_GE("N", 128), C_DIV("N", 128), C_GE("K", 128), + C_DIV("K", 128), C_EQ("group", 128), C_IN("dtype", "fp8a8f32") +}; +static const RadConstraint cGemmNtF32[] = { C_GE("M", 1), C_LE("M", 65535), + C_GE("N", 1), C_LE("N", 512), + C_GE("K", 1), C_LE("K", 16384), + C_IN("dtype", "bf16") }; +static const RadConstraint cDsaScore[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 128), C_EQ("heads", 32), + C_GE("blocks", 1), C_GE("seqs", 1), C_IN("dtype", "fp8_e4m3") +}; +static const RadConstraint cMlaAttn[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("latent_dim", 512), C_GE("heads", 1), + C_LE("heads", 64), C_GE("blocks", 1), C_EQ("block_size", 4), C_IN("dtype", "bf16") +}; +static const RadConstraint cMlaProject[] = { C_GE("M", 1), + C_LE("M", 65535), + C_GE("heads", 1), + C_LE("heads", 64), + C_EQ("head_dim", 256), + C_EQ("latent_dim", 512), + C_IN("mode", "absorb expand"), + C_IN("dtype", "bf16") }; +/* The matrix row outranks the wave row (mla_attn_bf16) at every M, the pairing walking the union + * of both rows' pages: measured cold on gfx1201 (r4d_selftest --perfmla), a 2048-row chunk + * with DSA tables (fill topk:16) takes 7.1 ms against 12.4 ms on the wave row and 13.0 ms on the + * positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms. + * RADIANCE_MLA_MATRIX_MAX_M lowers the bound, read once as the table loads; 0 is never. */ +static long long mla_matrix_max_m() { + const char* e = std::getenv("RADIANCE_MLA_MATRIX_MAX_M"); + char* end = nullptr; + const long long v = e && *e ? std::strtoll(e, &end, 10) : -1; + return end && !*end && v >= 0 ? (v < 65535 ? v : 65535) : 65535; +} +static const RadConstraint cMlaMatrix[] = { C_GE("M", 1), + C_LE("M", mla_matrix_max_m()), + C_EQ("latent_dim", 512), + C_GE("heads", 8), + C_LE("heads", 64), + C_DIV("heads", 8), + C_GE("blocks", 1), + C_EQ("block_size", 4), + C_IN("dtype", "bf16") }; /* `n` is bounded by LDS: nh (hc*n) and ne (n) are both bf16 and live through the second phase; * 28672 elements is that budget at hc 4. */ static const RadConstraint cMtpEnter[] = { @@ -3681,6 +3907,15 @@ static const RadConstraint cRouterTopK[] = { C_GE("M", 1), C_GE("n_expert", 1), C_LE("n_expert", 512), C_GE("top_k", 1), C_LE("top_k", 32), C_IN("dtype", "bf16"), }; +static const RadConstraint cRouterSigmoid[] = { C_GE("M", 1), C_LE("M", 65535), + C_GE("n_expert", 1), C_LE("n_expert", 512), + C_GE("top_k", 1), C_LE("top_k", 32), + C_IN("dtype", "f32") }; +/* The sort's single-workgroup form bounds M * top_k at 1024, which the shim checks. */ +static const RadConstraint cRouterSigmoidScatter[] = { C_GE("M", 1), C_LE("M", 1024), + C_GE("n_expert", 1), C_LE("n_expert", 512), + C_GE("top_k", 1), C_LE("top_k", 32), + C_IN("dtype", "f32") }; /* The selection's bounds and the skinny GEMM's decode band: four 16-row tiles. */ static const RadConstraint cRouterGemmTopkScatter[] = { C_GE("M", 1), C_LE("M", 64), C_DIV("K", 16), C_GE("n_expert", 1), C_LE("n_expert", 512), @@ -3693,6 +3928,11 @@ static const RadConstraint cMoeGemmQ[] = { C_GE("M", 1), C_DIV("N", 64), C_DIV("K", 128), C_GE("n_expert", 1), C_LE("n_expert", 65536), C_GE("top_k", 1), C_EQ("group", 128), C_IN("dtype", "fp8a8"), }; +static const RadConstraint cMoeMx[] = { + C_GE("M", 1), C_LE("M", 32767), C_GE("N", 1), C_DIV("K", 128), + C_GE("n_expert", 2), C_LE("n_expert", 512), C_GE("top_k", 1), C_LE("top_k", 32), + C_EQ("group", 128), C_IN("dtype", "mxfp4a8"), +}; /* The same op at a four-bit expert weight: same band and operands, only the stored weight plane * and scale grid differ, so the dtype string alone separates the rows. * @@ -3916,6 +4156,10 @@ static const RadConstraint cArGatherHcWrite4[] = { static const RadConstraint cGatedQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; +static const RadConstraint cSwigluClampedQuant[] = { + C_GE("M", 1), C_LE("M", 65535), C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), + C_IN("dtype", "bf16"), +}; /* n divisible by the group, as in cHadQuantActFp8. */ static const RadConstraint cGatedHadQuantFp8[] = { C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), @@ -4805,6 +5049,70 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr, r4d_shape_scale }, +{ "mla_attn_matrix_bf16", "mla_attn", "attn", "head-tiled WMMA latent attention with FP32 softmax", + "latent_dim=512, heads a multiple of 8 (heads%16==8 pairs two requests a tile), block_size=4", + "bf16 operands; FP32 probabilities via high/low BF16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 1, ROW(cMlaMatrix), NOTUNE, + nullptr, nullptr, r4d_rad_mla_attn_matrix, r4d_rad_mla_attn_matrix_scratch, nullptr, nullptr, + r4d_shape_mla_attn }, +{ "mla_attn_bf16", "mla_attn", "attn", "absorbed MLA with a shared latent cache and split history", + "latent_dim=512, heads<=64, block_size=4", "bf16 Q/cache/output, f32 softmax and partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaAttn), NOTUNE, + nullptr, nullptr, r4d_rad_mla_attn, r4d_rad_mla_attn_scratch, nullptr, nullptr, + r4d_shape_mla_attn }, +{ "gemm_fp8a8_f32scale", "gemm_nt_q", "gemm", "FP8 WMMA with canonical F32 block scales", + "N and K multiples of 128; pitched activations and row-major weights", "E4M3 codes, F32 scales, BF16 output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cFp8F32Scale), NOTUNE, + nullptr, nullptr, r4d_rad_fp8_f32scale, nullptr, r4d_layout_fp8_f32scale, nullptr, + nullptr }, +{ "moe_gemm_fp8a8_f32scale", "moe_gemm_q", "moe", "grouped FP8 WMMA with canonical F32 block scales", + "equal parity widths; token/sorted activations; canonical pointer tables", "E4M3 codes, F32 scales, BF16 output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cFp8F32Scale), NOTUNE, + nullptr, nullptr, r4d_rad_moe_fp8_f32scale, nullptr, r4d_layout_fp8_f32scale, nullptr, + nullptr }, +{ "dsa_score_fp8", "dsa_score", "attn", "32-head FP8 WMMA index scoring over paged keys", + "n=128, heads=32; ragged sequences and pitched tensors", "E4M3 codes, f32 scales and gates", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaScore), NOTUNE, + nullptr, nullptr, r4d_rad_dsa_score, nullptr, nullptr, nullptr, + r4d_shape_dsa_score }, +{ "mla_project_bf16", "mla_project", "attn", "per-head absorbed MLA projections", + "head_dim=256, latent_dim=512; pitched tensors", "bf16 input, weights and output; fp32 arithmetic", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaProject), NOTUNE, + nullptr, nullptr, r4d_rad_mla_project, nullptr, nullptr, nullptr, + r4d_shape_mla_project }, +{ "dsa_query_fp8", "dsa_query", "attn", "normalized index queries in wave-local registers", + "n=128; flattened heads and pitched rows", "bf16 input, E4M3 codes and power-of-two f32 scale", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaQuery), NOTUNE, + nullptr, nullptr, r4d_rad_dsa_query, nullptr, nullptr, nullptr, + r4d_shape_dsa_query }, +{ "gemm_nt_f32_bf16", "gemm_nt_f32", "gemm", "F32 routing and index gate projection", + "N<=512, K<=16384; pitched rows", "bf16 input, f32 weights and output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGemmNtF32), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_nt_f32, nullptr, nullptr, nullptr, + r4d_shape_gemm_nt_f32 }, +{ "dsa_pool_fp8", "dsa_pool", "attn", "learned compressed index keys in wave-local registers", + "n=128, ratio=4; pitched rows", "bf16 keys/gates, f32 position bias; FP8 codes and f32 scale", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaPool), NOTUNE, + nullptr, nullptr, r4d_rad_dsa_pool, nullptr, nullptr, nullptr, + r4d_shape_dsa_pool }, +{ "swiglu_clamped_bf16", "swiglu_clamped", "elem", + "asymmetrically clipped SwiGLU", "positive finite limit; pitched rows", + "bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_swiglu_clamped, nullptr, nullptr, nullptr, + r4d_shape_silu_mul }, +{ "swiglu_clamped_quant_fp8", "swiglu_clamped_quant_fp8", "quant", + "asymmetrically clipped SwiGLU and the fp8 activation quantiser in one pass", + "positive finite limit; n a multiple of 4; the gated operand is [M][2n], gate then up; " + "group 128; pitched rows", + "bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes " + "are taken over the BF16-ROUNDED product", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cSwigluClampedQuant), NOTUNE, + nullptr, nullptr, r4d_rad_swiglu_clamped_quant_fp8, nullptr, nullptr, nullptr, + r4d_shape_gated_quant_fp8, nullptr, + /* `swiglu_clamped` + `quant_act_fp8` (r4d_fuse.cpp). */ + r4d_fuse_swiglu_clamped_quant_fp8 }, { "silu_mul_bf16", "silu_mul", "elem", "silu-gated product over a fused [M, 2n] gate_up", "any n; the gate is the first half", @@ -5663,6 +5971,37 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gdn_conv_recurrent_update, nullptr, nullptr, nullptr, nullptr, nullptr, r4d_fuse_gdn_conv_recurrent_update }, +{ "kda_update_k128_v128_bf16", "kda_update", "gdn", "per-channel KDA recurrence and candidate rollback", + "heads 1..65535, K=V=128, prefill and verify", "bf16 activations, f32 gates and state", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cKdaUpdate), NOTUNE, + nullptr, nullptr, r4d_rad_kda_update, nullptr, nullptr, nullptr, + r4d_shape_kda_update }, +{ "mhc_pre_bf16", "mhc_pre", "norm", "manifold residual gates and Sinkhorn mixing", + "M 1..65535, n 1..16384, hc 2..8, iterations 1..256", "bf16 activation, f32 weights and coefficients", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPre), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_pre, nullptr, nullptr, nullptr, + r4d_shape_mhc_pre }, +{ "mhc_pre_partial_bf16", "mhc_pre_partial", "norm", "mHC projection partials of a chunk range", + "n 4096, hc 4, chunk 2048 (GLM)", "bf16 activation, f32 weights and partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPrePartial), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_pre_partial, nullptr, nullptr, nullptr, + r4d_shape_mhc_pre_partial }, +{ "mhc_pre_finish_bf16", "mhc_pre_finish", "norm", "mHC gates and Sinkhorn mixing from gathered partials", + "n 4096, hc 4, chunk 2048 (GLM), iterations 1..256", "bf16 activation, f32 partials and coefficients", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPreFinish), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_pre_finish, nullptr, nullptr, nullptr, + r4d_shape_mhc_pre_finish }, +{ "mhc_post_bf16", "mhc_post", "norm", "source-to-destination manifold residual update", + "M 1..65535, n 1..16384, hc 2..8", "bf16 activation, f32 coefficients", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPlain), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_post, nullptr, nullptr, nullptr, + r4d_shape_mhc_post }, +{ "mhc_contract_bf16", "mhc_contract", "norm", "mean over manifold residual streams", + "M 1..65535, n 1..16384, hc 2..8", "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPlain), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_contract, nullptr, nullptr, nullptr, + r4d_shape_mhc_contract }, + /* ---------------------------------------------------------------- the gated residual -------- * r4d_hc_bf16.hip. Three rows; the read is two launches behind one entry point, because `x` * depends on every column of the low-rank waist and the kernel boundary is the grid-wide @@ -6275,6 +6614,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_scale_rows, nullptr, nullptr, nullptr, r4d_shape_scale_rows }, +{ "router_sigmoid_topk_f32", "router_sigmoid_topk", "moe", + "sigmoid correction-bias routing", "single group, experts <=512, top_k<=32", + "f32 logits, bias and weights; i32 ids", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRouterSigmoid), NOTUNE, + nullptr, nullptr, r4d_rad_router_sigmoid_topk, nullptr, nullptr, nullptr, + r4d_shape_router_sigmoid_topk }, +{ "router_sigmoid_topk_scatter_f32", "router_sigmoid_topk_scatter", "moe", + "sigmoid correction-bias routing, the stable counting sort and the ungated shared gate in one " + "launch", "single group, experts <=512, top_k<=32, M*top_k<=1024", + "f32 logits, bias and weights; i32 ids, sorted slots, offsets and counts; bf16 gate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRouterSigmoidScatter), NOTUNE, + nullptr, nullptr, r4d_rad_router_sigmoid_topk_scatter, nullptr, nullptr, nullptr, + r4d_shape_router_sigmoid_topk_scatter, nullptr, + /* `router_sigmoid_topk` + `moe_scatter` (+ `fill` with the gate) (r4d_fuse.cpp). */ + r4d_fuse_router_sigmoid_topk_scatter }, { "router_topk_bf16", "router_topk", "moe", "softmax over a row of expert logits and the exact top-k of it, one wave a row", "n_expert <= 512, top_k <= min(n_expert, 32); bf16 logits and weights, i32 ids", @@ -6317,6 +6672,23 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_moe_scatter, r4d_rad_moe_scatter_scratch, nullptr, nullptr, r4d_shape_moe_scatter }, +{ "moe_scatter_inv_i32", "moe_scatter_inv", "moe", + "moe_scatter's stable counting sort, also writing every slot's row in the sort", + "n_expert <= 512; one launch at M*top_k <= 1024 and three above it", + "i32 throughout", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cMoeScatter), NOTUNE, + nullptr, nullptr, r4d_rad_moe_scatter_inv, r4d_rad_moe_scatter_scratch, nullptr, nullptr, + r4d_shape_moe_scatter_inv }, + +{ "moe_gemm_mxfp4a8", "moe_gemm_q", "moe", + "canonical MXFP4 experts decoded in packed words into exact FP8 WMMA tiles, scales folded per 32 values", + "K multiple 128, parity tables, token and sorted order, parts and narrower odd experts", + "E2M1 and E8M0 weights, E4M3 activations and f32 scales, bf16 output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMoeMx), NOTUNE, + nullptr, nullptr, r4d_rad_moe_mxfp4, nullptr, r4d_rad_layout_moe_mxfp4, nullptr, + r4d_shape_moe_mxfp4 }, + { "moe_gemm_fp8a8", "moe_gemm_q", "moe", "the grouped block-scaled fp8 GEMM: one contiguous range of expert-sorted rows a block, looping " "over the experts that range covers", @@ -6407,6 +6779,15 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_moe_gather, r4d_rad_moe_gather_scratch, nullptr, nullptr, r4d_shape_moe_gather }, +{ "moe_gather_inv_bf16", "moe_gather_inv", "moe", + "moe_gather over the slot table moe_scatter_inv wrote: no prepass and no scan of the sort", + "any M and n; the decode kernel up to 512 slots, the prefill forms above, as moe_gather", + "bf16 in and out, f32 or bf16 routing weights", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cMoeGather), NOTUNE, + nullptr, nullptr, r4d_rad_moe_gather_inv, nullptr, nullptr, nullptr, + r4d_shape_moe_gather_inv }, + { "rowtopk_bf16", "row_topk", "select", "exact per-row top-R of a bf16 matrix, descending, ties to the lower column", "any M, N a multiple of 8, R <= 32; two launches, caller-sized partial buffer", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index e9c4748d..3844acbd 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -59,6 +59,7 @@ #include #include #include +#include #include #include #include @@ -78,6 +79,10 @@ static int g_skip = 0; /* The row this process was asked to run, or null for the parent. Set from --case. */ static const char* g_case = nullptr; +/* The plugin under test's path, set in the child. Cases that compare against libref open the + * libref.so beside it. */ +static const char* g_plugin = nullptr; + /* Whether any case block claimed g_case; a row no case mentions is reported as a coverage hole. */ static bool g_matched = false; @@ -137,6 +142,8 @@ struct Plugin { void (*pin_ddec)(int) = nullptr; void (*pin_hc)(int) = nullptr; void (*pin_qsel)(int) = nullptr; + void (*pin_mla)(int) = nullptr; + void (*mla_stats)(unsigned long long*) = nullptr; int (*record)(const void**, int) = nullptr; }; @@ -172,6 +179,8 @@ static bool load(Plugin* pl, const char* path) { okall &= sym(pl->h, "r4d_moe_gemm_pin_down_dec", &pl->pin_ddec); okall &= sym(pl->h, "r4d_hc_read_pin_prefill", &pl->pin_hc); okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel); + okall &= sym(pl->h, "r4d_mla_matrix_pin_form", &pl->pin_mla); + okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats); okall &= sym(pl->h, "r4d_record_dispatches", &pl->record); return okall; } @@ -2373,7 +2382,8 @@ static void scatter_protect_at(const RadKernelInfo* rs, int64_t M, int64_t nl, i * `wide` says whether the shape takes the wide form. */ struct MoeGatherShape { int64_t M, n, k; const char* act; bool wide; }; -static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGatherShape& sh) { +static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGatherShape& sh, + bool f32 = false) { const int64_t M = sh.M, n = sh.n, k = sh.k, NS = M * k; const bool shared = sh.act != nullptr; const std::string at = " (M=" + std::to_string(M) + ", n=" + std::to_string(n) + ", top " + @@ -2398,14 +2408,17 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat std::vector ye((size_t)(NS * n)), ew((size_t)(M * k)), shv, sgv; for (auto& v : ye) v = h_to_bf16((float)((int64_t)(rnd() % 4001) - 2000) / 512.0f); for (auto& v : ew) v = h_to_bf16((float)(rnd() % 1000 + 1) / 1024.0f); + std::vector ewf(ew.size()); + for (size_t i = 0; i < ew.size(); ++i) ewf[i] = h_bf16(ew[i]) + 0.0001f * (float)(i % 7 + 1); if (shared) { shv.resize((size_t)(M * n)); sgv.resize((size_t)M); for (auto& v : shv) v = h_to_bf16((float)((int64_t)(rnd() % 4001) - 2000) / 256.0f); for (auto& v : sgv) v = h_to_bf16((float)((int64_t)(rnd() % 801) - 400) / 100.0f); + if (f32) std::fill(sgv.begin(), sgv.end(), h_to_bf16(1.0f)); } void* d_ye = dalloc(ye.size() * 2); - void* d_ew = dalloc(ew.size() * 2); + void* d_ew = dalloc(ew.size() * (f32?4:2)); void* d_so = dalloc(sorted.size() * 4); void* d_sh = shared ? dalloc(shv.size() * 2) : nullptr; void* d_sg = shared ? dalloc(sgv.size() * 2) : nullptr; @@ -2415,13 +2428,13 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat return; } st_memcpy(d_ye, ye.data(), ye.size() * 2, hipMemcpyHostToDevice); - st_memcpy(d_ew, ew.data(), ew.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_ew, f32?(const void*)ewf.data():(const void*)ew.data(), ew.size() * (f32?4:2), hipMemcpyHostToDevice); st_memcpy(d_so, sorted.data(), sorted.size() * 4, hipMemcpyHostToDevice); if (shared) { st_memcpy(d_sh, shv.data(), shv.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_sg, sgv.data(), sgv.size() * 2, hipMemcpyHostToDevice); } - std::vector ts = { T(d_ye, RAD_BF16, { NS, n }), T(d_ew, RAD_BF16, { M, k }), + std::vector ts = { T(d_ye, RAD_BF16, { NS, n }), T(d_ew, f32?RAD_F32:RAD_BF16, { M, k }), T(d_so, RAD_I32, { NS }), T(d_sh, RAD_BF16, { M, n }), T(d_sg, RAD_BF16, { M, 1 }), T(d_y, RAD_BF16, { M, n }) }; @@ -2454,6 +2467,24 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat ok(("moe_gather, a column a thread" + at).c_str(), false, "rc=" + std::to_string(rc)); return; } + if (f32) { + std::vector inverse((size_t)NS, -1); + for (int64_t i = 0; i < NS; ++i) + if (sorted[i] >= 0) inverse[sorted[i]] = i; + bool exact = true; + for (int64_t t = 0; t < M; ++t) + for (int64_t c = 0; c < n; ++c) { + float sum = 0; + for (int64_t j = 0; j < k; ++j) { + const int64_t i = inverse[t * k + j]; + if (i >= 0) sum = std::fma(ewf[t * k + j], h_bf16(ye[i * n + c]), sum); + } + uint16_t want = h_to_bf16(sum); + if (shared) want = h_to_bf16(h_bf16(want) + h_bf16(shv[t * n + c])); + exact = exact && base[t * n + c] == want; + } + ok(("GLM gather preserves F32 mixture weights" + at).c_str(), exact); + } struct Var { int form; const char* name; bool wide; }; static const Var kVar[] = { { 0, "the rule", false }, @@ -2462,7 +2493,7 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat for (const Var& v : kVar) { const std::string label = "moe_gather, " + std::string(v.name) + at; const int rc = run(v.form, got); - if (v.wide && !sh.wide) { + if (v.wide && (!sh.wide || f32)) { /* A shape the wide form cannot take refuses the pin rather than run another form. */ ok((label + " is refused").c_str(), rc == RAD_E_UNSUPPORTED, "rc=" + std::to_string(rc)); continue; @@ -2482,7 +2513,7 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat " differ from a column a thread" + first); } - if (M >= 2048 && sh.wide) { + if (M >= 2048 && sh.wide && !f32) { hipEvent_t e0, e1; st_ev_create(&e0); st_ev_create(&e1); @@ -2524,6 +2555,9 @@ static void moe_gather_case(const Plugin& pl) { { 2048, 2560, 10, "sigmoid", true }, /* Qwen3.8-Flash-Next's chunk, timed */ }; for (const MoeGatherShape& sh : kSh) moe_gather_at(pl, r, sh); + for (int64_t m : { 1, 4, 65 }) + for (bool shared : { false, true }) + moe_gather_at(pl, r, { m, 4096, 8, shared ? "none" : nullptr, false }, true); } /* ------------------------------------------------------- the vocab-parallel top-R, end to end @@ -2898,17 +2932,19 @@ static void kv_store_v4_case(const Plugin& pl, bool k6 = false) { bad ? first : fmt("every live row decodes exactly; %d bytes of other rows touched", touched)); } -static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dtype) { +static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dtype, + bool latent = false) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); if (!r) { ok(name, false, "row absent"); return; } const bool fp8 = std::strcmp(kv_dtype, "bf16") != 0; - const int64_t head_dim = 256, kv_heads = 2, block_size = 16, n_blocks = 4; + const int64_t head_dim = 256, kv_heads = latent?1:2, block_size = latent?4:16, n_blocks = 4; const int64_t lane = kv_heads * head_dim; const int64_t cache_elts = n_blocks * kv_heads * block_size * 2 * head_dim; /* Slot 0 is real; -1 is the pad; the last is past the end of the four blocks. */ - const std::vector slots = { 0, 17, 63, -1, (int32_t)(n_blocks * block_size), 33 }; + const std::vector slots = { 0, (int32_t)(block_size+1), + (int32_t)(n_blocks*block_size-1), -1, (int32_t)(n_blocks * block_size), (int32_t)(2*block_size+1) }; const int64_t T_tok = (int64_t)slots.size(); /* Exact in E4M3 and bf16. Sign separates K from V, the magnitude encodes head and column, so @@ -2946,6 +2982,22 @@ static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dty T(d_sm, RAD_I32, { T_tok }), T(d_c, fp8 ? RAD_F8E4M3 : RAD_BF16, { n_blocks, kv_heads, block_size, 2 * head_dim }), }; + if (latent) { + std::vector joined((size_t)T_tok * 512); + for (int64_t t = 0; t < T_tok; ++t) { + std::memcpy(joined.data() + t * 512, hk.data() + t * 256, 512); + std::memcpy(joined.data() + t * 512 + 256, hv.data() + t * 256, 512); + } + void* data = dalloc(joined.size() * 2); + if (!data) { + ok("MLA latent cache store", false, "allocation failed"); + return; + } + st_memcpy(data, joined.data(), joined.size() * 2, hipMemcpyHostToDevice); + ts[0].data = data; + ts[1].data = (uint16_t*)data + 256; + ts[0].stride[0] = ts[1].stride[0] = 512; + } std::vector ps = { PI("M", T_tok), PI("head_dim", head_dim), PI("n_head_kv", kv_heads), PI("block_size", block_size), PS("kv_dtype", kv_dtype), @@ -10985,6 +11037,2505 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, * sizes `u` for its weight planes; below it the pin to PF2 is refused. */ static constexpr int64_t kHcPf2MinRows = 512; +/* Independent host oracle, with pitched rows, narrowed runtime extents, and poisoned + * row padding and allocation margins. All three rows run at GLM's actual hidden width. */ +static void mhc_check(const Plugin& pl, const char* name, int64_t rows, int64_t n, int64_t hc, + bool paged = false) { + const RadKernelInfo* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row or plugin path absent"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "reference plugin unavailable"); + return; + } + auto count = (int (*)(void))dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (std::strcmp(at(i)->op, row->op) == 0) { + oracle = at(i); + break; + } + if (!oracle) { + ok(name, false, "reference operation unavailable"); + dlclose(ref); + return; + } + const bool clipped = !std::strcmp(row->op, "swiglu_clamped"); + const bool routed = !std::strcmp(row->op, "router_sigmoid_topk"); + const bool pooled = !std::strcmp(row->op, "dsa_pool"); + const bool query = !std::strcmp(row->op, "dsa_query"); + const bool projection = !std::strcmp(row->op, "gemm_nt_f32"); + std::vector ps = { PI("M", rows + 7), PS("dtype", routed ? "f32" : "bf16") }; + if (routed) { + ps.push_back(PI("n_expert", n)); + ps.push_back(PI("top_k", 8)); + ps.push_back(PI("norm", hc)); + ps.push_back(PF("route_scale", 2.5)); + } else if (projection) { + ps.push_back(PI("N", n)); + ps.push_back(PI("K", hc)); + } else + ps.push_back(PI("n", n)); + if (clipped) + ps.push_back(PF("limit", 10)); + else if (pooled) + ps.push_back(PI("ratio", 4)); + else if (query || projection) { /* hc selects input pattern or projection width */ + } else if (routed) { /* hc is the normalization choice in this test */ + } else + ps.push_back(PI("hc", hc)); + if (!std::strcmp(row->op, "mhc_pre")) { + ps.push_back(PI("iterations", 20)); + ps.push_back(PF("eps", 1e-5)); + ps.push_back(PF("hc_eps", 1e-6)); + } + const bool is_pre = !std::strcmp(row->op, "mhc_pre"); + const bool is_post = !std::strcmp(row->op, "mhc_post"); + const int operands = paged ? 6 + : (query || projection) ? 3 + : (routed || pooled) ? 4 + : is_pre ? 7 + : is_post ? 5 + : 2; + const int output_first = projection ? 2 + : query ? 1 + : (routed || pooled) ? 2 + : is_pre ? 4 + : is_post ? 4 + : 1; + std::vector host, device; + std::vector> bytes((size_t)operands); + std::vector allocations; + for (int i = 0; i < operands; ++i) { + RadOpdDesc desc{}; + int rc = RAD_OK; + if (paged && i == 4) { + desc.dtype = RAD_I32; + desc.rank = 1; + desc.shape[0] = rows; + } else if (paged && i == 5) { + desc.dtype = RAD_U8; + desc.rank = 4; + desc.shape[0] = rows + 3; + desc.shape[1] = 1; + desc.shape[2] = 4; + desc.shape[3] = 34; + } else + rc = oracle->opd_shape(ps.data(), (int)ps.size(), i, &desc); + if (rc != RAD_OK) { + ok(name, false, "oracle shape refused"); + dlclose(ref); + return; + } + std::vector shape(desc.shape, desc.shape + desc.rank); + if (paged && i >= 4) { /* cache capacity and page list are not token outputs */ + } else if (pooled) { + if (i == 0) + shape[0] = rows * 4; + else if (i != 1) + shape[0] = rows; + } else if (desc.rank == 2 && !(is_pre && i == 1) && !(projection && i == 1)) + shape[0] = rows; + RadTensor ht = T(nullptr, desc.dtype, shape); + if (ht.rank == 2) ht.stride[0] += 5; + if (paged && i == 4) ht.stride[0] = 2; + if (paged && i == 5) ht.stride[0] = 160; + const int64_t elements = ht.shape[0] * ht.stride[0]; + bytes[(size_t)i].assign((size_t)elements * esz(ht.dtype) + 256, 0xa5); + ht.data = bytes[(size_t)i].data() + 128; + if (paged && i == 4) + for (int64_t r = 0; r < rows; ++r) + ((int*)ht.data)[r * ht.stride[0]] = r == 1 ? -1 + : r == 2 ? (int)rows + 9 + : (int)(rows - r); + if (i < output_first) { + const int64_t nr = ht.rank == 2 ? ht.shape[0] : 1; + const int64_t nc = ht.rank == 2 ? ht.shape[1] : ht.shape[0]; + for (int64_t r = 0; r < nr; ++r) + for (int64_t c = 0; c < nc; ++c) { + const int64_t off = ht.rank == 2 ? r * ht.stride[0] + c : c; + float v = + (float)((int)(st_mix32((uint32_t)(r * nc + c + i * 271)) % 2001) - 1000) / + 1000; + if (is_pre && i == 1) v *= 0.01f; + if (clipped) v *= 40; + if (routed) v = i == 1 ? (float)(c % 5 - 2) * 0.125f : r == 0 ? 0 : v * 5; + if (pooled) { + if (hc == 1) + v = 0; + else if (hc == 2) + v = i == 0 && c < 128 ? 224 : 0; + else if (hc == 3) + v = i == 0 && c >= 128 ? (float)(r % 4) * 100 : v * 3; + } + if (query && hc == 1) v = 0; + if (query && hc == 2) v = 224; + if (query && hc == 3) v = c == 0 ? 0.5f : 0; + if (projection) v *= 0.125f; + if (ht.dtype == RAD_F32) + ((float*)ht.data)[off] = v; + else + ((uint16_t*)ht.data)[off] = h_to_bf16(v); + } + } + void* d = dalloc(bytes[(size_t)i].size()); + if (!d) { + ok(name, false, "allocation failed"); + dlclose(ref); + return; + } + allocations.push_back(d); + st_memcpy(d, bytes[(size_t)i].data(), bytes[(size_t)i].size(), hipMemcpyHostToDevice); + RadTensor dt = ht; + dt.data = (char*)d + 128; + host.push_back(ht); + device.push_back(dt); + } + RadArgs args{}; + args.t = host.data(); + args.n_t = operands; + args.p = ps.data(); + args.n_p = (int)ps.size(); + args.world_size = 1; + const int rr = oracle->launch(&args, nullptr); + ok(fmt("%s host oracle", name).c_str(), rr == RAD_OK); + if (rr == RAD_OK) run_case(row, device, ps); + bool matches = rr == RAD_OK, guards = true; + int mismatches = 0; + double pool_error2 = 0, pool_energy2 = 0; + for (int i = output_first; i < (paged ? 4 : operands) && rr == RAD_OK; ++i) { + const auto& ht = host[(size_t)i]; + std::vector got(bytes[(size_t)i].size()); + st_memcpy(got.data(), allocations[(size_t)i], got.size(), hipMemcpyDeviceToHost); + for (size_t j = 0; j < 128; ++j) + guards = guards && got[j] == 0xa5 && got[got.size() - 128 + j] == 0xa5; + for (int64_t r = 0; r < rows; ++r) { + for (int64_t c = 0; c < ht.shape[1]; ++c) { + const int64_t off = r * ht.stride[0] + c; + float expected, actual; + if (ht.dtype == RAD_F8E4M3) { + expected = rad_fp8e4m3_to_f32(((const uint8_t*)ht.data)[off]); + actual = rad_fp8e4m3_to_f32(got[128 + (size_t)off]); + } else if (ht.dtype == RAD_I32) { + expected = (float)((const int32_t*)ht.data)[off]; + actual = (float)((const int32_t*)(got.data() + 128))[off]; + } else if (ht.dtype == RAD_F32) { + expected = ((const float*)ht.data)[off]; + actual = ((const float*)(got.data() + 128))[off]; + } else { + expected = h_bf16(((const uint16_t*)ht.data)[off]); + actual = h_bf16(((const uint16_t*)(got.data() + 128))[off]); + } + // libm/OCML softmax can straddle a BF16 midpoint by one FP32 ulp. + // Only random pooling admits sparse quantization-boundary differences; + // fixed patterns and every power-of-two scale still compare exactly. + const float tol = query ? 0 + : pooled ? (hc == 0 && ht.dtype == RAD_F8E4M3 + ? std::max(0.125f, 0.125f * std::fabs(expected)) + : 0) + : ht.dtype == RAD_I32 ? 0 + : ht.dtype == RAD_F32 ? 3e-4f + : 0.016f + 0.008f * std::fabs(expected); + matches = matches && std::isfinite(actual) && std::fabs(actual - expected) <= tol; + if (pooled && ht.dtype == RAD_F8E4M3) { + mismatches += actual != expected; + pool_error2 += (double)(actual - expected) * (actual - expected); + pool_energy2 += (double)expected * expected; + } + } + for (int64_t c = ht.shape[1] * (int64_t)esz(ht.dtype); + c < ht.stride[0] * (int64_t)esz(ht.dtype); ++c) + guards = guards && + got[128 + (size_t)r * ht.stride[0] * esz(ht.dtype) + (size_t)c] == 0xa5; + } + } + if (pooled) { + const double nrmse = std::sqrt(pool_error2 / std::max(pool_energy2, 1e-30)); + matches = matches && mismatches <= std::max((int64_t)1, rows * n / 1000) && nrmse <= 0.001; + std::printf(" pool codes differ %d/%lld, normalized RMS error %.7g; scales exact\n", + mismatches, (long long)(rows * n), nrmse); + } + if (paged && rr == RAD_OK) { + std::vector got(bytes[5].size()); + st_memcpy(got.data(), allocations[5], got.size(), hipMemcpyDeviceToHost); + ok("DSA paged cache codes/scales, unused pages, padding and red zones", got == bytes[5]); + } + ok(fmt("%s oracle at M=%lld n=%lld hc=%lld", name, (long long)rows, (long long)n, (long long)hc) + .c_str(), + matches); + ok(fmt("%s red zones and row padding", name).c_str(), guards); + dlclose(ref); +} + +static void fp8_f32scale_check(const Plugin& pl, bool grouped, int64_t rows, bool sorted_a = false, + bool tables = false, int64_t experts = 6, int64_t N = 128, + int64_t K = 256) { + const char* name = grouped ? "moe_gemm_fp8a8_f32scale" : "gemm_fp8a8_f32scale"; + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "oracle missing"); + return; + } + const auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + const auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + for (int i = 0; count && at && i < count(); ++i) + if (!std::strcmp(at(i)->op, grouped ? "moe_gemm_q" : "gemm_nt_q")) oracle = at(i); + if (!oracle) { + ok(name, false, "oracle row missing"); + dlclose(ref); + return; + } + constexpr int64_t top = 4; + const int64_t E = experts; + std::vector ps = { PI("M", rows), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "fp8a8f32") }; + if (grouped) { + ps.push_back(PI("n_expert", E)); + ps.push_back(PI("top_k", top)); + ps.push_back(PS("a_order", sorted_a ? "sorted" : "token")); + ps.push_back(PI("N_odd", N)); + ps.push_back(PI("K_odd", K)); + } + const int operands = grouped ? 9 : 7, out = grouped ? 8 : 4; + std::vector host, device; + std::vector> bytes(operands); + std::vector alloc(operands, nullptr); + for (int i = 0; i < operands; ++i) { + RadOpdDesc d{}; + if (oracle->opd_shape(ps.data(), (int)ps.size(), i, &d) != RAD_OK) { + ok(name, false, "oracle shape refused"); + dlclose(ref); + return; + } + if (!d.rank) { + host.push_back({}); + device.push_back({}); + continue; + } + auto t = T(nullptr, d.dtype, std::vector(d.shape, d.shape + d.rank)); + const int64_t nel = t.shape[0] * t.stride[0]; + bytes[i].assign((size_t)nel * esz(t.dtype) + 256, 0xa5); + t.data = bytes[i].data() + 128; + if (i != out) + for (int64_t j = 0; j < nel; ++j) { + const float v = + (float)((int)(st_mix32((uint32_t)(j + i * 371)) % 2001) - 1000) / 256; + if (t.dtype == RAD_F8E4M3) + ((uint8_t*)t.data)[j] = rad_f32_to_fp8e4m3(v); + else if (t.dtype == RAD_F32) + ((float*)t.data)[j] = 0.003456789f + (float)(j % 11) * 0.0001234567f; + else + ((int*)t.data)[j] = 0; + } + if (grouped && i == 4) + for (int64_t j = 0; j < nel; ++j) + ((int*)t.data)[j] = j < rows * top * 3 / 4 ? (int)(rows * top - 1 - j) : -1; + if (grouped && i == 5) + for (int64_t j = 0; j < nel; ++j) + ((int*)t.data)[j] = (int)((rows * top * 3 / 4) * j / E); + alloc[i] = dalloc(bytes[i].size()); + if (!alloc[i]) { + ok(name, false, "allocation failed"); + dlclose(ref); + return; + } + st_memcpy(alloc[i], bytes[i].data(), bytes[i].size(), hipMemcpyHostToDevice); + host.push_back(t); + t.data = (char*)alloc[i] + 128; + device.push_back(t); + } + if (tables && grouped) + for (int i : { 2, 3, 6, 7 }) { + auto& t = device[i]; + std::vector ptrs((size_t)t.shape[0]); + for (int64_t e = 0; e < t.shape[0]; ++e) + ptrs[e] = (uint8_t*)t.data + e * t.stride[0] * esz(t.dtype); + void* table = dalloc(ptrs.size() * sizeof(void*)); + st_memcpy(table, ptrs.data(), ptrs.size() * sizeof(void*), hipMemcpyHostToDevice); + t.data = table; + t.stride[0] = 0; + } + RadArgs args{}; + args.t = host.data(); + args.n_t = operands; + args.p = ps.data(); + args.n_p = (int)ps.size(); + const int rc = oracle->launch(&args, nullptr); + ok("FP8 F32-scale host oracle", rc == RAD_OK); + if (rc == RAD_OK) run_case(row, device, ps); + std::vector got(bytes[out].size()); + st_memcpy(got.data(), alloc[out], got.size(), hipMemcpyDeviceToHost); + const int64_t count_y = host[out].shape[0] * N; + bool matches = rc == RAD_OK, guards = true; + float worst = 0; + for (int64_t i = 0; i < count_y; ++i) { + const float want = h_bf16(((const uint16_t*)host[out].data)[i]), + actual = h_bf16(((const uint16_t*)(got.data() + 128))[i]); + worst = std::max(worst, std::fabs(actual - want)); + matches = matches && std::isfinite(actual) && + std::fabs(actual - want) <= 1e-6f + 0.008f * std::fabs(want); + } + for (int i = 0; i < 128; ++i) + guards = guards && got[i] == 0xa5 && got[got.size() - 1 - i] == 0xa5; + ok(fmt("%s M=%lld N=%lld K=%lld sorted=%d tables=%d, max error %.8g", name, (long long)rows, + (long long)N, (long long)K, sorted_a, tables, worst) + .c_str(), + matches); + ok("FP8 F32-scale output guards", guards); + dlclose(ref); +} + +static void glm_index_layout_check(const Plugin& pl) { + const auto* row = find(pl, "cast_bf16_bf16"); + if (!row) { + ok("GLM index layout", false, "BF16 copy row missing"); + return; + } + for (int64_t tokens : { 1, 4, 33 }) + for (bool gate : { false, true }) { + const int64_t width = gate ? 128 : 4096, src_pitch = gate ? 256 : 4096; + const int64_t dst_pitch = gate ? 256 : 128, heads = gate ? 1 : 32; + std::vector input((size_t)tokens * src_pitch), + want((size_t)tokens * src_pitch, 0x7fff); + for (size_t i = 0; i < input.size(); ++i) + input[i] = h_to_bf16((float)((int)(i % 71) - 35) * 0.125f); + if (gate) + for (int64_t t = 0; t < tokens; ++t) + std::memcpy(want.data() + t * 256 + 128, input.data() + t * 256 + 128, 256); + else + want = input; + void* x = dalloc(input.size() * 2); + void* y = dalloc(want.size() * 2); + if (!x || !y) { + ok("GLM index layout", false, "allocation failed"); + return; + } + st_memcpy(x, input.data(), input.size() * 2, hipMemcpyHostToDevice); + st_memset(y, 0x7f, want.size() * 2); + // memset's BF16 poison is 0x7f7f, including the untouched normalized-key half. + if (gate) + for (int64_t t = 0; t < tokens; ++t) + for (int d = 0; d < 128; ++d) want[t * 256 + d] = 0x7f7f; + auto xt = T(gate ? (uint16_t*)x + 128 : x, RAD_BF16, { tokens, gate ? 128 : width }); + xt.stride[0] = src_pitch; + auto yt = T(gate ? (uint16_t*)y + 128 : y, RAD_BF16, { tokens * heads, 128 }); + yt.stride[0] = dst_pitch; + std::vector ts = { xt, yt }; + std::vector ps = { PI("M", tokens * heads), PI("n", 128), PS("from", "bf16"), + PS("to", "bf16") }; + run_case(row, ts, ps); + std::vector got(want.size()); + st_memcpy(got.data(), y, got.size() * 2, hipMemcpyDeviceToHost); + ok(gate ? "GLM pool gate column copy preserves key columns" + : "GLM query head flatten copy", + got == want); + } +} + +static void dsa_score_check(const Plugin& pl, int64_t rows, int64_t blocks, bool packed = false) { + const auto* row = find(pl, "dsa_score_fp8"); + if (!row || !g_plugin) { + ok("DSA scorer", false, "row or plugin missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok("DSA scorer", false, "oracle missing"); + return; + } + auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "dsa_score")) oracle = at(i); + if (!oracle) { + ok("DSA scorer", false, "oracle row missing"); + dlclose(ref); + return; + } + const int64_t seqs = rows > 1 ? 2 : 1; + std::vector ps = { PI("M", rows), PI("n", 128), PI("heads", 32), + PI("blocks", blocks), PI("seqs", seqs), PS("dtype", "fp8_e4m3") }; + std::vector host, device; + std::vector> bytes(9); + std::vector allocations; + for (int i = 0; i < 9; ++i) { + RadOpdDesc desc{}; + if (oracle->opd_shape(ps.data(), (int)ps.size(), i, &desc) != RAD_OK) { + ok("DSA scorer", false, "oracle shape refused"); + dlclose(ref); + return; + } + RadTensor t = + T(nullptr, desc.dtype, std::vector(desc.shape, desc.shape + desc.rank)); + if (t.rank == 3) { + t.stride[1] += 5; + t.stride[0] = t.shape[1] * t.stride[1] + (packed ? 0 : 7); + } else if (t.rank == 2) { + if (!(packed && i == 1)) t.stride[0] += 7; + } else + t.stride[0] = 2; + const int64_t elements = t.shape[0] * t.stride[0]; + bytes[i].assign((size_t)elements * esz(t.dtype) + 256, 0xa5); + t.data = bytes[i].data() + 128; + if (i < 8) { + const int64_t heads = t.rank == 3 ? t.shape[1] : 1; + const int64_t cols = t.rank >= 2 ? t.shape[t.rank - 1] : 1; + for (int64_t r = 0; r < t.shape[0]; ++r) + for (int64_t h = 0; h < heads; ++h) + for (int64_t c = 0; c < cols; ++c) { + const int64_t off = + r * t.stride[0] + (t.rank == 3 ? h * t.stride[1] + c : c); + const float v = (float)((int)(st_mix32((uint32_t)(r * heads * cols + + h * cols + c + i * 271)) % + 2001) - + 1000) / + 1000; + if (t.dtype == RAD_F8E4M3) + ((uint8_t*)t.data)[off] = rad_f32_to_fp8e4m3(v * 16); + else if (t.dtype == RAD_F32) + ((float*)t.data)[off] = i == 1 ? std::ldexp(1.0f, -6 - (r + h) % 3) + : i == 4 ? std::ldexp(1.0f, -5 - r % 3) + : v; + else { + int val = 0; + if (i == 5) + val = c % 11 == 3 ? -1 + : c % 17 == 5 ? (int)(seqs * blocks + 3) + : (int)((c * 7 + r * 11) % (seqs * blocks)); + else if (i == 6) + val = r == 0 ? (rows > 2 ? 1 : 0) + : r == seqs ? (int)rows + : (int)(rows / 2); + else + val = (int)(r == 0 ? blocks : blocks / 2); + ((int32_t*)t.data)[off] = val; + } + } + } + void* d = dalloc(bytes[i].size()); + if (!d) { + ok("DSA scorer", false, "allocation failed"); + dlclose(ref); + return; + } + st_memcpy(d, bytes[i].data(), bytes[i].size(), hipMemcpyHostToDevice); + allocations.push_back(d); + host.push_back(t); + t.data = (char*)d + 128; + device.push_back(t); + } + std::vector packed_bytes; + void* packed_device = nullptr; + if (packed) { + const int64_t pages = host[3].shape[0]; + packed_bytes.assign((size_t)pages * 160 + 256, 0xa5); + RadTensor cache = T(packed_bytes.data() + 128, RAD_U8, { pages, 1, 4, 34 }); + cache.stride[0] = 160; + for (int64_t p = 0; p < pages; ++p) { + std::memcpy((uint8_t*)cache.data + p * 160, + (uint8_t*)host[3].data + p * host[3].stride[0], 128); + const float scale = ((float*)host[4].data)[p * host[4].stride[0]]; + std::memcpy((uint8_t*)cache.data + p * 160 + 128, &scale, sizeof(scale)); + } + packed_device = dalloc(packed_bytes.size()); + if (!packed_device) { + ok("DSA packed cache", false, "allocation failed"); + dlclose(ref); + return; + } + st_memcpy(packed_device, packed_bytes.data(), packed_bytes.size(), hipMemcpyHostToDevice); + host[3] = cache; + host[4] = {}; + cache.data = (char*)packed_device + 128; + device[3] = cache; + device[4] = {}; + for (auto* ts : { &host, &device }) { + auto& q = (*ts)[0]; + q.rank = 2; + q.shape[0] = rows * 32; + q.shape[1] = 128; + q.stride[0] = q.stride[1]; + q.stride[1] = 1; + auto& qs = (*ts)[1]; + qs.shape[0] = rows * 32; + qs.shape[1] = 1; + qs.stride[0] = qs.stride[1]; + } + } + ps[0] = PI("M", rows + 7); // tensors narrow a declared bucket + RadArgs args{}; + args.t = host.data(); + args.n_t = 9; + args.p = ps.data(); + args.n_p = (int)ps.size(); + const int rc = oracle->launch(&args, nullptr); + ok("DSA scorer host oracle", rc == RAD_OK); + run_case(row, device, ps); + std::vector got(bytes[8].size()); + st_memcpy(got.data(), allocations[8], got.size(), hipMemcpyDeviceToHost); + const auto& out = host[8]; + bool matches = rc == RAD_OK, guards = true; + float max_error = 0; + for (int64_t r = 0; r < rows; ++r) + for (int64_t b = 0; b < blocks; ++b) { + const long off = r * out.stride[0] + b; + const float want = ((float*)out.data)[off], actual = ((float*)(got.data() + 128))[off]; + const float error = std::fabs(actual - want); + matches = matches && (actual == want || (std::isfinite(actual) && std::isfinite(want) && + error <= 1e-5f + 1e-5f * std::fabs(want))); + if (std::isfinite(error)) max_error = std::max(max_error, error); + } + for (size_t j = 0; j < 128; ++j) + guards = guards && got[j] == 0xa5 && got[got.size() - 128 + j] == 0xa5; + for (int64_t r = 0; r < rows; ++r) + for (int64_t b = blocks * 4; b < out.stride[0] * 4; ++b) + guards = guards && got[128 + (size_t)r * out.stride[0] * 4 + b] == 0xa5; + ok(fmt("DSA FP8 WMMA M=%lld blocks=%lld, signed gates, ragged cu, max error %.8g", + (long long)rows, (long long)blocks, max_error) + .c_str(), + matches); + ok("DSA scorer guards and pitched output", guards); + if (packed) { + std::vector after(packed_bytes.size()); + st_memcpy(after.data(), packed_device, after.size(), hipMemcpyDeviceToHost); + ok("DSA packed cache and its guards remain unchanged", after == packed_bytes); + } + if (matches && guards) { + args.t = device.data(); + for (int i = 0; i < 4; ++i) row->launch(&args, nullptr); + const double us = st_time_us([&](int) { row->launch(&args, nullptr); }, 30, nullptr); + std::printf(" DSA score M=%lld blocks=%lld: %.3f us (component timing)\n", + (long long)rows, (long long)blocks, us); + } + dlclose(ref); +} + +static void mla_project_check(const Plugin& pl, int64_t rows, int64_t heads, const char* mode, + bool flat = false) { + const auto* row = find(pl, "mla_project_bf16"); + if (!row || !g_plugin) { + ok("MLA projection", false, "kernel missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok("MLA projection", false, "oracle missing"); + return; + } + auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "mla_project")) oracle = at(i); + if (!oracle) { + ok("MLA projection", false, "oracle row missing"); + dlclose(ref); + return; + } + std::vector ps = { PI("M", rows + 7), PI("heads", heads), PI("head_dim", 256), + PI("latent_dim", 512), PS("mode", mode), PS("dtype", "bf16") }; + std::vector host, device; + std::vector> bytes(3); + std::vector allocations; + bool allocated = true; + for (int i = 0; i < 3; ++i) { + RadOpdDesc desc{}; + if (oracle->opd_shape(ps.data(), (int)ps.size(), i, &desc) != RAD_OK) { + allocated = false; + break; + } + std::vector shape(desc.shape, desc.shape + desc.rank); + if (i != 1) shape[0] = rows; + RadTensor t = T(nullptr, desc.dtype, shape); + if (t.rank == 3) { + t.stride[1] += flat ? 0 : 5; + t.stride[0] = heads * t.stride[1] + 7; + } else + t.stride[0] += 7; + bytes[i].assign((size_t)(t.shape[0] * t.stride[0]) * 2 + 256, 0xa5); + t.data = bytes[i].data() + 128; + if (i < 2) + for (int64_t r = 0; r < t.shape[0]; ++r) + for (int64_t h = 0; h < (t.rank == 3 ? heads : 1); ++h) + for (int64_t d = 0; d < t.shape[t.rank - 1]; ++d) { + const long off = r * t.stride[0] + (t.rank == 3 ? h * t.stride[1] : 0) + d; + const float v = + (float)((int)(st_mix32((uint32_t)(r * 7919 + h * 1031 + d + i * 271)) % + 2001) - + 1000) / + 8000; + ((uint16_t*)t.data)[off] = h_to_bf16(v); + } + void* ptr = dalloc(bytes[i].size()); + if (!ptr) { + allocated = false; + break; + } + allocations.push_back(ptr); + st_memcpy(ptr, bytes[i].data(), bytes[i].size(), hipMemcpyHostToDevice); + host.push_back(t); + t.data = (char*)ptr + 128; + device.push_back(t); + } + if (allocated) { + auto hargs = host, dargs = device; + if (flat) + for (auto* ts : { &hargs, &dargs }) + for (int i : { 0, 2 }) { + auto& t = (*ts)[i]; + t.rank = 2; + t.shape[1] = t.shape[1] * t.shape[2]; + t.stride[1] = 1; + } + RadArgs args{}; + args.t = hargs.data(); + args.n_t = 3; + args.p = ps.data(); + args.n_p = (int)ps.size(); + const int rc = oracle->launch(&args, nullptr); + ok("MLA projection host oracle", rc == RAD_OK); + if (rc == RAD_OK) { + run_case(row, dargs, ps); + std::vector got(bytes[2].size()); + st_memcpy(got.data(), allocations[2], got.size(), hipMemcpyDeviceToHost); + std::vector written(got.size(), false); + bool matches = true, guards = true; + float max_error = 0; + const auto& t = host[2]; + for (int64_t r = 0; r < rows; ++r) + for (int64_t h = 0; h < heads; ++h) + for (int64_t d = 0; d < t.shape[2]; ++d) { + const long off = r * t.stride[0] + h * t.stride[1] + d; + const float want = h_bf16(((uint16_t*)t.data)[off]), + actual = h_bf16(((uint16_t*)(got.data() + 128))[off]); + const float error = std::fabs(actual - want); + max_error = std::max(max_error, error); + matches = matches && std::isfinite(actual) && + error <= 0.0001f + 0.008f * std::fabs(want); + written[128 + off * 2] = written[129 + off * 2] = true; + } + for (size_t j = 0; j < got.size(); ++j) + if (!written[j]) guards = guards && got[j] == 0xa5; + ok(fmt("MLA %s M=%lld H=%lld max error %.8g", mode, (long long)rows, (long long)heads, + max_error) + .c_str(), + matches); + ok("MLA projection pitched tensors and guards", guards); + } + } else + ok("MLA projection", false, "allocation or shape failed"); + dlclose(ref); +} + +/* An environment variable set (or, with a null value, cleared) for one scope and restored after + * it: the MLA launcher and the eight-rank two-shot read their settings at every call. */ +struct ScopedEnv { + const char* name; + bool had; + std::string kept; + ScopedEnv(const char* n, const char* v) : name(n) { + const char* was = std::getenv(n); + had = was != nullptr; + if (was) kept = was; + if (v) + setenv(n, v, 1); + else + unsetenv(n); + } + ~ScopedEnv() { + if (had) + setenv(name, kept.c_str(), 1); + else + unsetenv(name); + } + ScopedEnv(const ScopedEnv&) = delete; + ScopedEnv& operator=(const ScopedEnv&) = delete; +}; + +/* Tables as qsa_select emits them past its budget: for the queries at positions context-rows .. + * context-1 of one sequence, each row the top blocks-1 of its complete blocks, the strictly higher + * ones in block order and a short tie run after them, then the partial page. Row r's choice is row + * r-1's with `swaps` members exchanged for non-members, so neighbours share most blocks but rarely + * a table position once a swap shifts the order. Pages are a fixed shuffle of the sequence's + * blocks, context/4+1 of them. */ +static void mla_topk_tables(int64_t rows, int64_t blocks, int64_t context, int64_t swaps, + std::vector& bt, std::vector& len) { + const int64_t topk = blocks - 1, universe = context / 4 + 1, ties = std::min(4, topk); + uint32_t draw = 0x6d2b79f5u; + auto rnd = [&](int64_t n) { return (int64_t)(st_mix32(draw++) % (uint32_t)n); }; + std::vector page((size_t)universe); + for (int64_t i = 0; i < universe; ++i) page[(size_t)i] = (int32_t)i; + for (int64_t i = universe - 1; i > 0; --i) std::swap(page[(size_t)i], page[(size_t)rnd(i + 1)]); + std::vector in((size_t)universe, 0); + std::vector members; + auto tie_rank = [](int64_t b) { return st_mix32((uint32_t)b ^ 0x9e3779b9u); }; + bt.assign((size_t)(rows * blocks), -1); + len.assign((size_t)rows, 0); + for (int64_t r = 0; r < rows; ++r) { + const int64_t p = context - rows + r, n = (p + 1) / 4; + if (n <= topk) { + for (int64_t b = 0; b < n; ++b) + if (!in[(size_t)b]) { + in[(size_t)b] = 1; + members.push_back(b); + } + } else { + while ((int64_t)members.size() < topk) { + const int64_t b = rnd(n); + if (!in[(size_t)b]) { + in[(size_t)b] = 1; + members.push_back(b); + } + } + for (int64_t k = 0; k < swaps; ++k) { + int64_t add; + do add = rnd(n); + while (in[(size_t)add]); + const size_t drop = (size_t)rnd((int64_t)members.size()); + in[(size_t)members[drop]] = 0; + members[drop] = add; + in[(size_t)add] = 1; + } + } + std::vector order(members); + std::sort(order.begin(), order.end()); + if (n > topk) { + std::vector tied(order); + std::sort(tied.begin(), tied.end(), + [&](int64_t a, int64_t b) { return tie_rank(a) < tie_rank(b); }); + tied.resize((size_t)ties); + std::sort(tied.begin(), tied.end()); + order.erase(std::remove_if(order.begin(), order.end(), + [&](int64_t b) { + return std::binary_search(tied.begin(), tied.end(), b); + }), + order.end()); + order.insert(order.end(), tied.begin(), tied.end()); + } + int64_t out = 0; + for (int64_t b : order) bt[(size_t)(r * blocks + out++)] = page[(size_t)b]; + if ((p + 1) % 4) bt[(size_t)(r * blocks + out++)] = page[(size_t)n]; + len[(size_t)r] = (int32_t)(out ? (out - 1) * 4 + p % 4 + 1 : 0); + } +} + +/* ragged: every request its own scattered table with holes; full: every request its own fully + * populated pages; prefill: requests are consecutive queries of two sequences that share a table + * and grow by one token a row (the second sequence starts at an odd row, so a pair of rows can + * straddle it), with an occasional row whose table differs in one position; topk: one sequence + * past the DSA budget (mla_topk_tables), `swaps` blocks exchanged between neighbouring rows. */ +enum class MlaFill { ragged, full, prefill, topk }; +static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blocks, + const char* name = "mla_attn_bf16", MlaFill fill = MlaFill::ragged, + const char* versus = nullptr, int form = 0, int64_t swaps = 0) { + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok("MLA attention", false, "row or plugin missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok("MLA attention", false, "oracle missing"); + return; + } + auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "mla_attn")) oracle = at(i); + if (!oracle) { + ok("MLA attention", false, "oracle row missing"); + dlclose(ref); + return; + } + std::vector ps = { PI("M", rows), PI("latent_dim", 512), PI("heads", heads), + PI("blocks", blocks), PI("block_size", 4), PF("scale", 0.0625), + PS("dtype", "bf16") }; + std::vector host, device; + std::vector> bytes(5); + std::vector allocations; + /* The oracle's cache has rows*blocks pages: three budgets of context where that allows. */ + std::vector topk_bt, topk_len; + if (fill == MlaFill::topk) + mla_topk_tables(rows, blocks, 4 * std::min(rows * blocks - 1, 3 * (blocks - 1)), + swaps, topk_bt, topk_len); + for (int i = 0; i < 5; ++i) { + RadOpdDesc desc{}; + if (oracle->opd_shape(ps.data(), (int)ps.size(), i, &desc) != RAD_OK) { + ok("MLA attention", false, "oracle shape refused"); + dlclose(ref); + return; + } + RadTensor t = + T(nullptr, desc.dtype, std::vector(desc.shape, desc.shape + desc.rank)); + if (t.rank == 4) { + t.stride[2] += 8; + t.stride[1] = t.shape[2] * t.stride[2] + 8; + t.stride[0] = t.stride[1] + 8; + } else if (t.rank == 3) { + t.stride[1] += 5; + t.stride[0] = t.shape[1] * t.stride[1] + 7; + } else if (t.rank == 2) + t.stride[0] += 7; + else + t.stride[0] = 2; + const int64_t elements = t.shape[0] * t.stride[0]; + bytes[i].assign((size_t)elements * esz(t.dtype) + 256, 0xa5); + t.data = bytes[i].data() + 128; + if (i < 4) { + const int64_t n1 = t.rank > 1 ? t.shape[1] : 1; + const int64_t n2 = t.rank > 2 ? t.shape[2] : 1; + const int64_t n3 = t.rank > 3 ? t.shape[3] : 1; + for (int64_t r = 0; r < t.shape[0]; ++r) + for (int64_t a1 = 0; a1 < n1; ++a1) + for (int64_t a2 = 0; a2 < n2; ++a2) + for (int64_t a3 = 0; a3 < n3; ++a3) { + const long off = r * t.stride[0] + a1 * t.stride[1] + a2 * t.stride[2] + + a3 * t.stride[3]; + const float v = + (float)((int)(st_mix32((uint32_t)(((r * n1 + a1) * n2 + a2) * n3 + + a3 + i * 271)) % + 2001) - + 1000) / + 1000; + if (t.dtype == RAD_BF16) + ((uint16_t*)t.data)[off] = h_to_bf16(i == 0 ? v * 0.25f : v); + else if (fill == MlaFill::full) + ((int32_t*)t.data)[off] = + i == 2 ? (int)(r * blocks + a1) : (int)(blocks * 4); + else if (fill == MlaFill::topk) + ((int32_t*)t.data)[off] = i == 2 + ? topk_bt[(size_t)(r * blocks + a1)] + : topk_len[(size_t)r]; + else if (fill == MlaFill::prefill) { + const int64_t boundary = rows > 2 ? (rows / 2) | 1 : rows, + seq = r >= boundary; + const int64_t index = seq ? r - boundary : r, + count = seq ? rows - boundary : boundary; + ((int32_t*)t.data)[off] = + i == 2 + ? (a1 % 11 == 7 ? -1 + : r % 4 == 2 && a1 == 5 ? (int)(rows * blocks - 1 - a1) + : (int)(seq * blocks + a1)) + : (int)(blocks * 4 - count + index + 1); + } else + ((int32_t*)t.data)[off] = + i == 2 ? (a1 % 17 == 3 ? -1 + : a1 % 19 == 5 + ? (int)(rows * blocks + 3) + : (int)((a1 * 7 + r * 11) % (rows * blocks))) + : r % 5 == 4 ? 0 + : (int)(blocks * 4 - 1 - r % 7); + } + } + void* d = dalloc(bytes[i].size()); + if (!d) { + ok("MLA attention", false, "allocation failed"); + dlclose(ref); + return; + } + st_memcpy(d, bytes[i].data(), bytes[i].size(), hipMemcpyHostToDevice); + allocations.push_back(d); + host.push_back(t); + t.data = (char*)d + 128; + device.push_back(t); + } + ps[0] = PI("M", rows + 7); + RadArgs args{}; + args.t = host.data(); + args.n_t = 5; + args.p = ps.data(); + args.n_p = (int)ps.size(); + const int rc = oracle->launch(&args, nullptr); + ok("MLA host oracle", rc == RAD_OK); + args.t = device.data(); + /* The head-tiled row serves tiles of 16 heads or of 8 heads from two requests (cMlaMatrix); + * other head counts must be refused rather than computed. */ + if (std::strstr(name, "matrix") && heads % 8) { + args.scratch = nullptr; + args.scratch_bytes = 0; + const int grc = row->launch(&args, nullptr); + st_stream_sync(nullptr); + ok(fmt("MLA %s refuses heads=%lld (not a multiple of 8) with RAD_E_UNSUPPORTED, no launch", + name, (long long)heads) + .c_str(), + grc == RAD_E_UNSUPPORTED); + dlclose(ref); + return; + } + if (form && pl.pin_mla) pl.pin_mla(form); + const int64_t need = row->scratch ? row->scratch(&args) : 0; + void* scratch = need > 0 ? dalloc((size_t)need + 256) : nullptr; + if (need <= 0 || !scratch) { + if (form && pl.pin_mla) pl.pin_mla(0); + ok("MLA scratch allocation", false); + dlclose(ref); + return; + } + bool matches = rc == RAD_OK, guards = true; + float max_error = 0; + const auto& out = host[4]; + for (int pass = 0; pass < 2; ++pass) { + st_memset(allocations[4], 0xa5, bytes[4].size()); + st_memset(scratch, 0xa5, (size_t)need + 256); + args.scratch = pass ? (char*)scratch + 128 : nullptr; + args.scratch_bytes = pass ? need : 0; + const int grc = row->launch(&args, nullptr); + const auto he = st_stream_sync(nullptr); + matches = matches && grc == RAD_OK && he == hipSuccess; + std::vector got(bytes[4].size()); + st_memcpy(got.data(), allocations[4], got.size(), hipMemcpyDeviceToHost); + std::vector written(got.size(), false); + for (int64_t r = 0; r < rows; ++r) + for (int64_t h = 0; h < heads; ++h) + for (int64_t d = 0; d < 512; ++d) { + const long off = r * out.stride[0] + h * out.stride[1] + d; + const float want = h_bf16(((uint16_t*)out.data)[off]), + actual = h_bf16(((uint16_t*)(got.data() + 128))[off]); + const float error = std::fabs(actual - want); + max_error = std::max(max_error, error); + matches = matches && std::isfinite(actual) && + error <= 1e-5f + 0.008f * std::fabs(want); + written[128 + off * 2] = written[129 + off * 2] = true; + } + for (size_t i = 0; i < got.size(); ++i) + if (!written[i]) guards = guards && got[i] == 0xa5; + uint8_t left[128], right[128]; + st_memcpy(left, scratch, 128, hipMemcpyDeviceToHost); + st_memcpy(right, (char*)scratch + 128 + need, 128, hipMemcpyDeviceToHost); + for (int i = 0; i < 128; ++i) guards = guards && left[i] == 0xa5 && right[i] == 0xa5; + } + const char* pairing = std::getenv("RADIANCE_MLA_PAIR"); + ok(fmt("MLA M=%lld heads=%lld blocks=%lld%s%s%s split/unsplit, max error %.8g", (long long)rows, + (long long)heads, (long long)blocks, + fill == MlaFill::topk ? fmt(" topk:%lld", (long long)swaps).c_str() : "", + form ? fmt(" pinned form %d", form).c_str() : "", + pairing && std::strstr(name, "matrix") ? fmt(" pairing %s", pairing).c_str() : "", + max_error) + .c_str(), + matches); + ok("MLA pitched rows, heads, cache, padding and scratch red zones", guards); + if (matches && guards) { + const char* shape = fill == MlaFill::full ? "fully populated" + : fill == MlaFill::prefill ? "prefill" + : fill == MlaFill::topk ? "topk" + : "ragged"; + const double us = st_time_us([&](int) { row->launch(&args, nullptr); }, 30, nullptr); + std::printf( + " %s M=%lld heads=%lld capacity=%lld tokens: %.3f us (%s component timing)\n", + name, (long long)rows, (long long)heads, (long long)(blocks * 4), us, shape); + if (const auto* other = versus ? find(pl, versus) : nullptr) { + const int64_t other_need = other->scratch ? other->scratch(&args) : 0; + void* other_scratch = other_need > need ? dalloc((size_t)other_need) : nullptr; + args.scratch = other_scratch ? other_scratch : (char*)scratch + 128; + args.scratch_bytes = other_scratch ? other_need : need; + const double base = + st_time_us([&](int) { other->launch(&args, nullptr); }, 30, nullptr); + std::printf(" %s same case: %.3f us, %s %.2fx faster (%s component timing)\n", + versus, base, name, base / us, shape); + } + } + if (form && pl.pin_mla) pl.pin_mla(0); + dlclose(ref); +} + +/* ------------------------------------------------------------- MLA attention, timed at length + * + * mla_check's operands without the oracle, so a prefill chunk of 2048 rows at 2k or 8k of context + * fits: one block table a sequence and a pool of pages a sequence instead of M*blocks. fill + * "prefill" is mla_check's two sequences, "fresh" one sequence whose rows are the last M positions + * of the capacity (a new prompt's chunk), "ragged" scattered per-row tables with holes, and "SxR" + * (e.g. 8x6) a decode step: S sequences of R rows each (the token and its drafts), one table and + * one context between 1024 positions and the capacity a sequence; M is then S*R. "topk:d[:context]" + * is one sequence past the DSA budget (mla_topk_tables): the pairing of the matrix row shares a key + * load only where both rows name the same page at the same table position, which the other fills + * always or never give. The matrix row is timed at both key loads (paired tiles at heads%16 == 8) + * against the wave row on the same operands, with its second passes counted on one more launch; + * differences are against the wave row's output. */ +static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, int iters, + const char* fill) { + if (iters <= 0) iters = 20; + const bool ragged = !std::strcmp(fill, "ragged"), fresh = !std::strcmp(fill, "fresh"); + long long seqs = 0, rows_per = 0, swaps = -1, context = 0; + char tail = 0; + const bool decode = + std::sscanf(fill, "%lldx%lld%c", &seqs, &rows_per, &tail) == 2 && seqs > 0 && rows_per > 0; + const int topk_fields = std::sscanf(fill, "topk:%lld:%lld%c", &swaps, &context, &tail); + const bool topk = (topk_fields == 1 || topk_fields == 2) && swaps >= 0; + if (topk && topk_fields == 1) context = 16 * (blocks - 1); + if (!ragged && !fresh && !decode && !topk && std::strcmp(fill, "prefill")) { + std::printf("--perfmla: fill prefill|fresh|ragged|SxR|topk:d[:context]\n"); + return; + } + if (decode) { + if (M != seqs * rows_per) + std::printf("--perfmla: decode %s sets M=%lld\n", fill, seqs * rows_per); + M = seqs * rows_per; + } + if (M < 1 || M > 65535 || blocks < 1 || heads < 1 || heads > 64 || + (topk && (blocks < 2 || context < M))) { + std::printf("--perfmla: shape out of range\n"); + return; + } + const int64_t D = 512, bs = 4, cap = blocks * bs; + const int64_t pages = + topk ? context / bs + 1 : std::max(2, decode ? seqs : 2) * blocks; + std::vector qh((size_t)(M * heads * D)), kvh((size_t)(pages * bs * D)); + for (size_t i = 0; i < qh.size(); ++i) + qh[i] = h_to_bf16(0.25f * (float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) / 1000); + for (size_t i = 0; i < kvh.size(); ++i) + kvh[i] = + h_to_bf16((float)((int)(st_mix32((uint32_t)i + 0x9e3779b9u) % 2001) - 1000) / 1000); + std::vector bth((size_t)(M * blocks)), lh((size_t)M); + const int64_t boundary = fresh ? M : M > 2 ? (M / 2) | 1 : M; + double visible = 0; + if (topk) { + std::vector tl; + mla_topk_tables(M, blocks, context, swaps, bth, tl); + for (int64_t r = 0; r < M; ++r) lh[(size_t)r] = tl[(size_t)r]; + } + for (int64_t r = 0; r < M && topk; ++r) + for (int64_t t = 0; t < lh[(size_t)r]; ++t) + if (bth[(size_t)(r * blocks + t / bs)] >= 0) visible += 1; + for (int64_t r = 0; r < M && !topk; ++r) { + int64_t seq, l; + if (decode) { + seq = r / rows_per; + const int64_t context = cap > 1024 ? 1024 + (seq * 7919) % (cap - 1023) : cap; + l = std::max(1, context - (rows_per - 1 - r % rows_per)); + } else { + seq = r >= boundary; + const int64_t index = seq ? r - boundary : r, count = seq ? M - boundary : boundary; + l = ragged ? (r % 5 == 4 ? 0 : cap - 1 - r % 7) + : std::max(1, cap - count + index + 1); + } + for (int64_t b = 0; b < blocks; ++b) + bth[(size_t)(r * blocks + b)] = + ragged ? (b % 17 == 3 ? -1 : (int32_t)((b * 7 + r * 11) % pages)) + : (int32_t)(seq * blocks + b); + lh[(size_t)r] = (int32_t)l; + for (int64_t t = 0; t < l; ++t) + if (bth[(size_t)(r * blocks + t / bs)] >= 0) visible += 1; + } + const double flops = visible * (double)D * (double)heads * 4; + std::printf( + "mla_attn M=%lld blocks=%lld (capacity %lld) heads=%lld fill=%s: %.0f visible positions, " + "%.3f GFLOP, %d launches%s\n", + (long long)M, (long long)blocks, (long long)cap, (long long)heads, fill, visible, + flops * 1e-9, iters, g_cold > 0 ? " (cold)" : ""); + void* dq = dalloc(qh.size() * 2); + void* dkv = dalloc(kvh.size() * 2); + void* dbt = dalloc(bth.size() * 4); + void* dl = dalloc(lh.size() * 4); + void* dout = dalloc(qh.size() * 2); + if (!dq || !dkv || !dbt || !dl || !dout) { + std::printf(" alloc failed\n"); + return; + } + st_memcpy(dq, qh.data(), qh.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dkv, kvh.data(), kvh.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dbt, bth.data(), bth.size() * 4, hipMemcpyHostToDevice); + st_memcpy(dl, lh.data(), lh.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { T(dq, RAD_BF16, { M, heads, D }), + T(dkv, RAD_BF16, { pages, 1, bs, D }), + T(dbt, RAD_I32, { M, blocks }), T(dl, RAD_I32, { M }), + T(dout, RAD_BF16, { M, heads, D }) }; + std::vector ps = { PI("M", M), PI("latent_dim", D), PI("heads", heads), + PI("blocks", blocks), PI("block_size", bs), PF("scale", 0.0625), + PS("dtype", "bf16") }; + std::vector base, rule; + auto run = [&](const char* name, int form, const char* label, bool positional = false) { + ScopedEnv pairing("RADIANCE_MLA_PAIR", positional ? "pos" : nullptr); + const RadKernelInfo* r = find(pl, name); + if (!r) { + std::printf(" %-34s row absent\n", label); + return; + } + if (form >= 0) { + if (!pl.pin_mla) { + std::printf(" %-34s no pin hook\n", label); + return; + } + pl.pin_mla(form); + } + 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(); + const int64_t need = r->scratch ? r->scratch(&a) : 0; + if (need > 0) { + a.scratch = dalloc((size_t)need); + a.scratch_bytes = need; + } + st_memset(dout, 0xff, qh.size() * 2); + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { + std::printf(" %-34s rc=%d (shape not served)\n", label, rc); + if (form >= 0) pl.pin_mla(0); + return; + } + std::vector got(qh.size()); + st_memcpy(got.data(), dout, got.size() * 2, hipMemcpyDeviceToHost); + { /* Clocks to deployment speed first, as qsa_perf does. */ + hipEvent_t w0, w1; + st_ev_create(&w0); + st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0; + for (int guard = 0; guard < 100000 && wms < 500.0f; ++guard) { + for (int i = 0; i < 8; ++i) r->launch(&a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); + st_ev_destroy(w1); + } + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + if (form >= 0) pl.pin_mla(0); + char diff[192] = "reference"; + if (base.empty()) + base = got; + else { + /* bf16 as an ordered integer, so the distance counts representable steps. */ + auto ord = [](uint16_t h) { return (h & 0x8000) ? -(int)(h & 0x7fff) : (int)h; }; + int ulp = 0; + float abs_err = 0; + bool finite = true; + for (size_t i = 0; i < got.size(); ++i) { + const float x = h_bf16(got[i]), y = h_bf16(base[i]); + finite = finite && std::isfinite(x); + ulp = std::max(ulp, std::abs(ord(got[i]) - ord(base[i]))); + abs_err = std::max(abs_err, std::fabs(x - y)); + } + /* The two key loads stage the same values: their outputs must agree to the bit. The + * pairings walk request r of a pair in the same order (equal at one split) and r+1 in + * another. */ + std::string same = + form == 1 && !rule.empty() + ? (rule == got ? ", bit-identical to form 0" : ", DIFFERS from form 0") + : ""; + if (positional && !rule.empty()) { + size_t differ[2] = { 0, 0 }; + float apart = 0; + for (size_t i = 0; i < got.size(); ++i) + if (got[i] != rule[i]) { + ++differ[(i / (size_t)(heads * D)) % 2]; + apart = std::max(apart, std::fabs(h_bf16(got[i]) - h_bf16(rule[i]))); + } + same = fmt(", vs union %zu/%zu values differ (r/r+1), max abs %.3g", differ[0], + differ[1], apart); + } + std::snprintf(diff, sizeof diff, "%smax %d ulp, max abs %.3g%s", + finite ? "" : "NONFINITE ", ulp, abs_err, same.c_str()); + } + if (form == 0 && !positional) rule = got; + std::printf(" %-34s %10.2f us %7.2f TFLOP/s %s\n", label, us, flops / (us * 1e6), diff); + if (form >= 0 && pl.mla_stats) { + /* One more launch with the conflict counters on, outside the timing. */ + ScopedEnv counting("RADIANCE_MLA_CONFLICT_STATS", "1"); + unsigned long long v[3]; + pl.mla_stats(v); + pl.pin_mla(form); + r->launch(&a, nullptr); + pl.pin_mla(0); + pl.mla_stats(v); + std::printf(" %-34s %llu passes over %llu raster chunks, %llu second passes (%.3fx)\n", + "", v[0], v[2], v[1], v[2] ? (double)v[0] / (double)v[2] : 0.0); + } + }; + run("mla_attn_bf16", -1, "mla_attn_bf16 (wave)"); + if (heads % 8) { + std::printf(" mla_attn_matrix_bf16 serves heads a multiple of 8 only\n"); + return; + } + if (heads % 16) { + run("mla_attn_matrix_bf16", 0, "matrix paired, union, vector load"); + run("mla_attn_matrix_bf16", 1, "matrix paired, union, element load"); + run("mla_attn_matrix_bf16", 0, "matrix paired, positional, vector", true); + } else { + run("mla_attn_matrix_bf16", 0, "matrix 16 heads, vector load"); + run("mla_attn_matrix_bf16", 1, "matrix 16 heads, element load"); + } +} + +static void kda_check(const Plugin& pl, const char* mode, bool cold, int accepted_count, + bool anchor = false) { + const char* name = "kda_update_k128_v128_bf16"; + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row or plugin path absent"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "reference plugin unavailable"); + return; + } + auto count = (int (*)(void))dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "kda_update")) { + oracle = at(i); + break; + } + if (!oracle) { + ok(name, false, "reference operation unavailable"); + dlclose(ref); + return; + } + const int H = 2, T0 = 6, D = 128; + const std::vector> shapes = { + { T0, H, D }, { T0, H, D }, { T0, H, D }, { T0, H, D }, { T0, H }, + { H }, { H * D }, { 8, H, D, D }, { 2, anchor ? 6 : 3 }, { 3 }, + { 2 }, { 2 }, { T0, H, D }, + }; + std::vector> bytes(13), visible(13); + std::vector host, device; + std::vector allocations; + auto offset = [](const RadTensor& t, int64_t logical) { + int64_t physical = 0; + for (int d = (int)t.rank - 1; d >= 0; --d) { + physical += (logical % t.shape[d]) * t.stride[d]; + logical /= t.shape[d]; + } + return physical; + }; + for (int i = 0; i < 13; ++i) { + const uint32_t dt = i >= 8 && i <= 11 ? (uint32_t)RAD_I32 + : i >= 5 && i <= 7 ? (uint32_t)RAD_F32 + : (uint32_t)RAD_BF16; + auto ht = T(nullptr, dt, shapes[(size_t)i]); + if (ht.rank >= 2) { + int64_t pitch = ht.shape[ht.rank - 1] + 4; + for (int d = (int)ht.rank - 2; d >= 0; --d) { + ht.stride[d] = pitch; + pitch = ht.shape[d] * pitch + 8; + } + } + const size_t size = (size_t)(ht.shape[0] * ht.stride[0]) * esz(dt) + 256; + bytes[(size_t)i].assign(size, 0xa5); + visible[(size_t)i].assign(size, 0); + ht.data = bytes[(size_t)i].data() + 128; + int64_t count0 = 1; + for (uint32_t d = 0; d < ht.rank; ++d) count0 *= ht.shape[d]; + for (int64_t j = 0; j < count0; ++j) { + const int64_t off0 = offset(ht, j); + const float value = + (float)((int)(st_mix32((uint32_t)(i * 173 + j)) % 2001) - 1000) / 2000; + if (dt == RAD_F32) + ((float*)ht.data)[off0] = value; + else if (dt == RAD_BF16) + ((uint16_t*)ht.data)[off0] = h_to_bf16(value); + else + ((int*)ht.data)[off0] = 0; + for (size_t b0 = 0; b0 < esz(dt); ++b0) + visible[(size_t)i][128 + (size_t)off0 * esz(dt) + b0] = 1; + } + host.push_back(ht); + } + auto integers = [&](int i, std::initializer_list values) { + int64_t j = 0; + for (int v : values) ((int*)host[(size_t)i].data)[offset(host[(size_t)i], j++)] = v; + }; + if (anchor) { + integers(8, { 2, 2, 2, 0, 0, 0, 5, 5, 5, 6, 6, 6 }); + integers(9, { 0, 3, 6 }); + for (int slot : { 0, 6 }) + for (int h = 0; h < H; ++h) + ((float*)host[7].data)[slot * host[7].stride[0] + h * host[7].stride[1]] = 0; + } else { + integers(8, { 2, 0, 3, 5, 6, 7 }); + integers(9, { 1, 3, 6 }); + } + integers(10, { accepted_count, 1 }); + integers(11, { cold ? 0 : 1, 1 }); + for (int i = 0; i < 13; ++i) { + void* d = dalloc(bytes[(size_t)i].size()); + if (!d) { + ok(name, false, "allocation failed"); + dlclose(ref); + return; + } + allocations.push_back(d); + st_memcpy(d, bytes[(size_t)i].data(), bytes[(size_t)i].size(), hipMemcpyHostToDevice); + auto dt = host[(size_t)i]; + dt.data = (char*)d + 128; + device.push_back(dt); + } + std::vector ps = { + PI("M", T0 + 7), PI("heads", H), + PI("head_k", D), PI("head_v", D), + PF("lower_bound", -5), PF("scale", 1.0 / std::sqrt(128.0)), + PF("l2_eps", 1e-6), PS("mode", mode), + PS("dtype", "bf16"), PS("state_form", anchor ? "anchor" : "per_candidate") + }; + RadArgs args{}; + args.t = host.data(); + args.n_t = 13; + args.p = ps.data(); + args.n_p = (int)ps.size(); + args.world_size = 1; + const int rc = oracle->launch(&args, nullptr); + ok("KDA host oracle", rc == RAD_OK); + if (rc == RAD_OK) run_case(row, device, ps); + if (rc == RAD_OK && anchor && !std::strcmp(mode, "verify")) { + // A second window must replay only the accepted prefix of the first window. + integers(11, { 1, 1 }); + st_memcpy(allocations[11], bytes[11].data(), bytes[11].size(), hipMemcpyHostToDevice); + args.t = host.data(); + ok("KDA anchor second-window host replay", oracle->launch(&args, nullptr) == RAD_OK); + run_case(row, device, ps); + } + bool matches = rc == RAD_OK, guards = true; + for (int i : { 7, 12 }) + if (rc == RAD_OK) { + std::vector got(bytes[(size_t)i].size()); + st_memcpy(got.data(), allocations[(size_t)i], got.size(), hipMemcpyDeviceToHost); + for (size_t j = 0; j < got.size(); ++j) + if (!visible[(size_t)i][j]) guards = guards && got[j] == 0xa5; + const auto& ht = host[(size_t)i]; + int64_t count0 = 1; + for (uint32_t d = 0; d < ht.rank; ++d) count0 *= ht.shape[d]; + for (int64_t j = 0; j < count0; ++j) { + const auto off0 = offset(ht, j); + const float expected = ht.dtype == RAD_F32 + ? ((const float*)ht.data)[off0] + : h_bf16(((const uint16_t*)ht.data)[off0]); + const float actual = ht.dtype == RAD_F32 + ? ((const float*)(got.data() + 128))[off0] + : h_bf16(((const uint16_t*)(got.data() + 128))[off0]); + const float tol = + ht.dtype == RAD_F32 ? 2e-5f : 0.008f + 0.008f * std::fabs(expected); + matches = matches && std::isfinite(actual) && std::fabs(actual - expected) <= tol; + } + } + ok(fmt("KDA %s %s cold=%d accepted=%d: output, state, untouched slots", + anchor ? "anchor" : "candidate", mode, cold, accepted_count) + .c_str(), + matches); + ok("KDA pitched rows and state red zones", guards); + dlclose(ref); +} + +/* Saves the given switches on construction and restores them on destruction; pin() sets each + * to its value or, for nullptr, back to what the caller had. */ +struct EnvPins { + std::vector names; + std::vector saved; + std::vector had; + explicit EnvPins(std::initializer_list n) : names(n) { + for (const char* k : names) { + const char* v = std::getenv(k); + had.push_back(v != nullptr); + saved.push_back(v ? v : ""); + } + } + void pin(std::initializer_list values) { + size_t i = 0; + for (const char* v : values) { + if (v) + setenv(names[i], v, 1); + else if (had[i]) + setenv(names[i], saved[i].c_str(), 1); + else + unsetenv(names[i]); + ++i; + } + } + ~EnvPins() { + for (size_t i = 0; i < names.size(); ++i) { + if (had[i]) + setenv(names[i], saved[i].c_str(), 1); + else + unsetenv(names[i]); + } + } +}; + +/* One launch, then a 200 ms warm-up and `iters` timed launches (st_time_us: --cold gives the + * median of flushed launches). -1 when the row refuses the arguments. */ +static double form_us(const RadKernelInfo* r, RadArgs* a, int iters) { + if (r->launch(a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return -1.0; + hipEvent_t w0, w1; + st_ev_create(&w0); + st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0.0f; + for (int guard = 0; guard < 100000 && wms < 200.0f; ++guard) { + for (int i = 0; i < 8; ++i) r->launch(a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); + st_ev_destroy(w1); + return st_time_us([&](int) { r->launch(a, nullptr); }, iters, nullptr); +} + +static std::vector fetch_bytes(const void* d, size_t bytes) { + std::vector v(bytes); + st_memcpy(v.data(), d, bytes, hipMemcpyDeviceToHost); + return v; +} + +/* kda_update at GLM's TP8 shape (eight heads, 128 x 128 state per head), every form held byte for + * byte to the one-row kernel on shuffle sums (RADIANCE_KDA_FORM=old) over the output and the + * whole state buffer, the slots no sequence names included: prefill of M tokens as one sequence + * per candidate and as three anchored sequences (one cold, one unseated), and the verify step of + * eight sequences with up to six candidates, per candidate and anchored, the anchored one after a + * replay of the accepted prefix. `iters` below zero compares only, as a case. */ +static void kda_forms(const Plugin& pl, int64_t M, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 50; + if (M < 1 || M > 65535) { + std::printf("--perfkda: 1 <= M <= 65535\n"); + return; + } + const RadKernelInfo* row = find(pl, "kda_update_k128_v128_bf16"); + if (!row) { + std::printf("--perfkda: row kda_update_k128_v128_bf16 absent\n"); + return; + } + const int64_t H = 8, D = 128, slots = 64, tokens = std::max(M, 48); + const size_t state_floats = (size_t)(slots * H * D * D); + std::vector state0(state_floats), alog((size_t)H), bias((size_t)(H * D)); + auto uni = [](uint32_t i, float span) { + return (float)((int)(st_mix32(i) % 2001) - 1000) / 1000 * span; + }; + for (size_t i = 0; i < state0.size(); ++i) state0[i] = uni((uint32_t)i * 7u + 1u, 1.0f); + for (size_t i = 0; i < alog.size(); ++i) alog[i] = uni((uint32_t)i + 91u, 0.75f) - 0.25f; + for (size_t i = 0; i < bias.size(); ++i) bias[i] = uni((uint32_t)i * 3u + 17u, 1.0f); + std::vector in[5]; + for (int i = 0; i < 5; ++i) { + in[i].resize((size_t)(tokens * H * (i == 4 ? 1 : D))); + for (size_t j = 0; j < in[i].size(); ++j) + in[i][j] = + h_to_bf16(uni((uint32_t)(j * 5 + (size_t)i * 1000003u), i >= 3 ? 2.0f : 1.0f)); + } + void* d_in[5]; + for (int i = 0; i < 5; ++i) { + d_in[i] = dalloc(in[i].size() * 2); + if (!d_in[i]) { + std::printf("--perfkda: alloc failed\n"); + return; + } + st_memcpy(d_in[i], in[i].data(), in[i].size() * 2, hipMemcpyHostToDevice); + } + void* d_alog = dalloc(alog.size() * 4); + void* d_bias = dalloc(bias.size() * 4); + void* d_state = dalloc(state_floats * 4); + void* d_out = dalloc((size_t)(tokens * H * D * 2)); + if (!d_alog || !d_bias || !d_state || !d_out) { + std::printf("--perfkda: alloc failed\n"); + return; + } + st_memcpy(d_alog, alog.data(), alog.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_bias, bias.data(), bias.size() * 4, hipMemcpyHostToDevice); + + struct Case { + std::string what; + const char* mode; + bool anchor; + int64_t width; + std::vector cu, idx, accepted, init; + std::vector> counts; /* scratch slots' window counts */ + }; + std::vector cases; + { + Case c{ fmt("prefill M=%lld, one sequence, per candidate", (long long)M), + "prefill", + false, + 1, + { 0, (int)M }, + { 5 }, + { 1 }, + { 1 }, + {} }; + cases.push_back(c); + } + { + const int a = (int)(M / 2), b = (int)(M - M / 4); + Case c{ fmt("prefill M=%lld, three sequences, anchored", (long long)M), + "prefill", + true, + 2, + { 0, a, b, (int)M }, + { 7, 8, 9, 10, -1, 11 }, + { 1, 1, 1 }, + { 0, 1, 1 }, + {} }; + cases.push_back(c); + } + { + Case c{ "verify 8x6, per candidate", "verify", false, 6, {}, {}, {}, {}, {} }; + int t = 0; + for (int s = 0; s < 8; ++s) { + c.cu.push_back(t); + t += s == 3 ? 5 : 6; + for (int k = 0; k < 6; ++k) c.idx.push_back(12 + s * 6 + k); + c.accepted.push_back(1 + s % 6); + c.init.push_back(s == 5 ? 0 : 1); + } + c.cu.push_back(t); + cases.push_back(c); + } + { + Case c{ "verify 8x6, anchored (replay first)", "verify", true, 6, {}, {}, {}, {}, {} }; + int t = 0; + for (int s = 0; s < 8; ++s) { + c.cu.push_back(t); + t += s == 2 ? 4 : 6; + const int anchor_slot = 1 + s, scratch = 20 + s; + for (int k = 0; k < 6; ++k) + c.idx.push_back(k == 0 ? anchor_slot : k == 3 ? scratch : 40 + s); + c.accepted.push_back(1 + (s * 5) % 6); + c.init.push_back(s == 6 ? 0 : 1); + c.counts.push_back({ scratch, s == 4 ? 0.0f : 6.0f }); + } + c.cu.push_back(t); + cases.push_back(c); + } + + EnvPins env({ "RADIANCE_KDA_FORM", "RADIANCE_KDA_ROWS", "RADIANCE_KDA_PREFETCH" }); + struct Form { + const char* what; + const char* form; + const char* rows; + const char* prefetch; + }; + const Form forms[] = { { "rule", nullptr, nullptr, nullptr }, + { "1 row a wave", "new", "1", "1" }, + { "2 rows a wave", "new", "2", "1" }, + { "4 rows a wave", "new", "4", "1" }, + { "1 row a wave, no prefetch", "new", "1", "0" }, + { "2 rows a wave, no prefetch", "new", "2", "0" }, + { "4 rows a wave, no prefetch", "new", "4", "0" } }; + if (!check) + std::printf("kda_update at GLM's TP8 shape (8 heads, 128 x 128), %s, %d launches\n", + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", + iters); + const size_t out_bytes = (size_t)(tokens * H * D * 2), state_bytes = state_floats * 4; + for (Case& c : cases) { + const int64_t seqs = (int64_t)c.cu.size() - 1; + std::vector start = state0; + for (const auto& sc : c.counts) + for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second; + void* d_idx = dalloc(c.idx.size() * 4); + void* d_cu = dalloc(c.cu.size() * 4); + void* d_acc = dalloc(c.accepted.size() * 4); + void* d_init = dalloc(c.init.size() * 4); + if (!d_idx || !d_cu || !d_acc || !d_init) { + std::printf("--perfkda: alloc failed\n"); + return; + } + st_memcpy(d_idx, c.idx.data(), c.idx.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_cu, c.cu.data(), c.cu.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_acc, c.accepted.data(), c.accepted.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_init, c.init.data(), c.init.size() * 4, hipMemcpyHostToDevice); + std::vector t = { T(d_in[0], RAD_BF16, { tokens, H, D }), + T(d_in[1], RAD_BF16, { tokens, H, D }), + T(d_in[2], RAD_BF16, { tokens, H, D }), + T(d_in[3], RAD_BF16, { tokens, H, D }), + T(d_in[4], RAD_BF16, { tokens, H }), + T(d_alog, RAD_F32, { H }), + T(d_bias, RAD_F32, { H * D }), + T(d_state, RAD_F32, { slots, H, D, D }), + T(d_idx, RAD_I32, { seqs, c.width }), + T(d_cu, RAD_I32, { seqs + 1 }), + T(d_acc, RAD_I32, { seqs }), + T(d_init, RAD_I32, { seqs }), + T(d_out, RAD_BF16, { tokens, H, D }) }; + std::vector ps = { + PI("M", tokens), PI("heads", H), + PI("head_k", D), PI("head_v", D), + PF("lower_bound", -5), PF("scale", 1.0 / std::sqrt(128.0)), + PF("l2_eps", 1e-6), PS("mode", c.mode), + PS("dtype", "bf16"), PS("state_form", c.anchor ? "anchor" : "per_candidate") + }; + RadArgs a{}; + a.t = t.data(); + a.n_t = (int)t.size(); + a.p = ps.data(); + a.n_p = (int)ps.size(); + a.world_size = 1; + auto run = [&]() { + st_memcpy(d_state, start.data(), state_bytes, hipMemcpyHostToDevice); + st_memset(d_out, 0xff, out_bytes); + if (row->launch(&a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) + return false; + return true; + }; + auto outputs = [&]() { + std::vector o = fetch_bytes(d_out, out_bytes); + const std::vector s = fetch_bytes(d_state, state_bytes); + o.insert(o.end(), s.begin(), s.end()); + return o; + }; + env.pin({ "old", nullptr, nullptr }); + const bool ref_ok = run(); + const std::vector ref = outputs(); + if (check) + ok(fmt("KDA %s: old form served", c.what.c_str()).c_str(), ref_ok); + else + std::printf(" %s\n %-34s %8.1f us\n", c.what.c_str(), "old", + ref_ok ? form_us(row, &a, iters) : -1.0); + for (const Form& f : forms) { + env.pin({ f.form, f.rows, f.prefetch }); + const bool served = run(); + const bool same = served && outputs() == ref; + if (check) { + ok(fmt("KDA %s, %s: byte-identical to the old form", c.what.c_str(), f.what) + .c_str(), + ref_ok && same, served ? "" : "not served"); + continue; + } + const double us = served ? form_us(row, &a, iters) : -1.0; + if (us < 0) + std::printf(" %-34s not served\n", f.what); + else + std::printf(" %-34s %8.1f us%s\n", f.what, us, + same ? " = old" : " DIFFERS from old"); + } + } +} + +/* mla_project at GLM's TP8 shape (eight heads, head_dim 256, latent 512) in both modes, every row + * form held byte for byte to the one-row kernels on shuffle sums (RADIANCE_MLA_PROJECT=old) over + * the whole pitched output, so a store past a row or into the pitch shows. M not a multiple of the + * rows a group checks the tail. `iters` below zero compares only, as a case. */ +static void project_forms(const Plugin& pl, int64_t M, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 100; + if (M < 1 || M > 65535) { + std::printf("--perfproject: 1 <= M <= 65535\n"); + return; + } + const RadKernelInfo* row = find(pl, "mla_project_bf16"); + if (!row) { + std::printf("--perfproject: row mla_project_bf16 absent\n"); + return; + } + const int64_t H = 8, wp = 512 + 8; + std::vector w((size_t)(H * 512 * wp)); + for (size_t i = 0; i < w.size(); ++i) + w[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 3u + 5u) % 2001) - 1000) / 8000); + void* d_w = dalloc(w.size() * 2); + if (!d_w) { + std::printf("--perfproject: alloc failed\n"); + return; + } + st_memcpy(d_w, w.data(), w.size() * 2, hipMemcpyHostToDevice); + EnvPins env({ "RADIANCE_MLA_PROJECT" }); + if (!check) + std::printf( + "mla_project at GLM's TP8 shape (8 heads, 256 <-> 512), M=%lld, %s, %d launches\n", + (long long)M, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", + iters); + for (const char* mode : { "absorb", "expand" }) { + const bool absorb = !std::strcmp(mode, "absorb"); + const int64_t xd = absorb ? 256 : 512, yd = absorb ? 512 : 256; + const int64_t xh = xd + 3, xr = H * xh + 5, yh = yd + 4, yr = H * yh + 6; + std::vector x((size_t)(M * xr)); + for (size_t i = 0; i < x.size(); ++i) + x[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 7u + 13u) % 2001) - 1000) / 1000); + void* d_x = dalloc(x.size() * 2); + void* d_y = dalloc((size_t)(M * yr * 2)); + if (!d_x || !d_y) { + std::printf("--perfproject: alloc failed\n"); + return; + } + st_memcpy(d_x, x.data(), x.size() * 2, hipMemcpyHostToDevice); + RadTensor tx = T(d_x, RAD_BF16, { M, H, xd }), tw = T(d_w, RAD_BF16, { H * 512, 512 }), + ty = T(d_y, RAD_BF16, { M, H, yd }); + tx.stride[1] = xh; + tx.stride[0] = xr; + tw.stride[0] = wp; + ty.stride[1] = yh; + ty.stride[0] = yr; + std::vector t = { tx, tw, ty }; + std::vector ps = { PI("M", M), PI("heads", H), + PI("head_dim", 256), PI("latent_dim", 512), + PS("mode", mode), PS("dtype", "bf16") }; + RadArgs a{}; + a.t = t.data(); + a.n_t = 3; + a.p = ps.data(); + a.n_p = (int)ps.size(); + a.world_size = 1; + const size_t y_bytes = (size_t)(M * yr * 2); + auto run = [&]() { + st_memset(d_y, 0xa5, y_bytes); + return row->launch(&a, nullptr) == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + }; + env.pin({ "old" }); + const bool ref_ok = run(); + const std::vector ref = fetch_bytes(d_y, y_bytes); + if (check) + ok(fmt("MLA project %s M=%lld: old form served", mode, (long long)M).c_str(), ref_ok); + else + std::printf(" %s\n %-20s %8.1f us\n", mode, "old", + ref_ok ? form_us(row, &a, iters) : -1.0); + for (const char* f : { (const char*)nullptr, "1", "2", "4", "8" }) { + env.pin({ f }); + const bool served = run(); + const bool same = served && fetch_bytes(d_y, y_bytes) == ref; + const std::string what = f ? fmt("%s rows a group", f) : std::string("rule"); + if (check) { + ok(fmt("MLA project %s M=%lld, %s: byte-identical to the old form", mode, + (long long)M, what.c_str()) + .c_str(), + ref_ok && same, served ? "" : "not served"); + continue; + } + const double us = served ? form_us(row, &a, iters) : -1.0; + if (us < 0) + std::printf(" %-20s not served\n", what.c_str()); + else + std::printf(" %-20s %8.1f us%s\n", what.c_str(), us, + same ? " = old" : " DIFFERS from old"); + } + } +} + +static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, const char* order, + int model_shape = 0, bool exceptional = false, int NE = 3, int top = 2, + bool holes = false) { + const char* name = "moe_gemm_mxfp4a8"; + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row or plugin path absent"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "reference plugin unavailable"); + return; + } + auto count = (int (*)(void))dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "moe_gemm_q")) { + oracle = at(i); + break; + } + if (!oracle) { + ok(name, false, "reference operation unavailable"); + dlclose(ref); + return; + } + // Model shapes: 1/2 are GLM's gate_up/down slices at TP4, 3/4 the same at TP8. + static const int MN[5] = { 0, 1024, 4096, 512, 4096 }, MK[5] = { 0, 4096, 512, 4096, 256 }; + const int N[2] = { model_shape ? MN[model_shape] : 64, model_shape ? MN[model_shape] + : parts == 2 ? 32 + : 64 }; + const int K[2] = { model_shape ? MK[model_shape] : 128, model_shape ? MK[model_shape] + : parts == 2 ? 256 + : 128 }; + const int OUT = std::max(N[0], N[1]); + const int NK = std::max(K[0], K[1]), T0 = M * top, AR = !std::strcmp(order, "sorted") ? T0 : M; + const int ap = NK + 8, asp = NK / 128 + 3, yp = OUT + 5; + std::vector av((size_t)AR * ap, 0x7f); + std::vector asc((size_t)AR * asp, 0); + for (int r = 0; r < AR; ++r) { + for (int k = 0; k < NK; ++k) + av[(size_t)r * ap + k] = + rad_f32_to_fp8e4m3((float)((int)(st_mix32(r * NK + k) % 33) - 16) / 4); + for (int g = 0; g < NK / 128; ++g) asc[(size_t)r * asp + g] = 0.003f * (1 + (r + g) % 5); + } + std::vector sorted((size_t)T0, -1), offsets(NE + 1, 0); + std::vector> by(NE); + for (int i = 0; i < T0 - (T0 > 2 ? 2 : 0); ++i) + by[(size_t)((i * 17 + i / 2) % NE)].push_back(i); + int next = 0; + // `holes` drops about every seventh slot inside the runs, a run's first rows included. + for (int e = 0; e < NE; ++e) { + offsets[(size_t)e] = next; + for (size_t j = 0; j < by[(size_t)e].size(); ++j) + sorted[(size_t)next++] = holes && (j + (size_t)e) % 7 == 3 ? -1 : by[(size_t)e][j]; + } + offsets[NE] = next; + std::vector> weights(NE), scales(NE); + std::vector hw[2], hs[2], dw[2], ds[2], pinned; + bool memory_ok = true; + for (int e = 0; e < NE; ++e) { + const int q = e & 1; + weights[(size_t)e].resize((size_t)N[q] * K[q] / 2); + scales[(size_t)e].resize((size_t)N[q] * K[q] / 32); + for (size_t i = 0; i < weights[(size_t)e].size(); ++i) + weights[(size_t)e][i] = (uint8_t)st_mix32((uint32_t)(i + e * 1879)); + for (size_t i = 0; i < scales[(size_t)e].size(); ++i) + scales[(size_t)e][i] = (uint8_t)(122 + st_mix32((uint32_t)(i + e * 271)) % 8); + if (exceptional) { + const uint8_t exponents[] = { 0, 1, 2, 252, 253, 254, 255 }; + for (size_t i = 0; i < scales[(size_t)e].size(); ++i) + scales[(size_t)e][i] = exponents[i % 7]; + } + hw[q].push_back(weights[(size_t)e].data()); + hs[q].push_back(scales[(size_t)e].data()); + auto upload = [&](std::vector& source) -> void* { + if (pooled && e == 0) { + void *h = nullptr, *d = nullptr; + if (hipHostMalloc(&h, source.size(), hipHostMallocMapped) != hipSuccess) { + memory_ok = false; + return nullptr; + } + pinned.push_back(h); + std::memcpy(h, source.data(), source.size()); + if (hipHostGetDevicePointer(&d, h, 0) != hipSuccess) { + memory_ok = false; + return nullptr; + } + return d; + } + void* d = dalloc(source.size()); + if (!d) { + memory_ok = false; + return nullptr; + } + st_memcpy(d, source.data(), source.size(), hipMemcpyHostToDevice); + return d; + }; + dw[q].push_back(upload(weights[(size_t)e])); + ds[q].push_back(upload(scales[(size_t)e])); + } + ok("MXFP4 expert storage allocation", memory_ok); + if (!memory_ok) { + for (void* p : pinned) hipHostFree(p); + dlclose(ref); + return; + } + std::vector expected((size_t)T0 * yp, h_to_bf16(-4)); + std::vector ht = { T(av.data(), RAD_F8E4M3, { AR, NK }), + T(asc.data(), RAD_F32, { AR, NK / 128 }), + T(hw[0].data(), RAD_FP4E2M1, { (NE + 1) / 2, N[0], K[0] }), + T(hs[0].data(), RAD_E8M0, { (NE + 1) / 2, N[0], K[0] / 32 }), + T(sorted.data(), RAD_I32, { T0 }), + T(offsets.data(), RAD_I32, { NE + 1 }), + T(hw[1].data(), RAD_FP4E2M1, { NE / 2, N[1], K[1] }), + T(hs[1].data(), RAD_E8M0, { NE / 2, N[1], K[1] / 32 }), + T(expected.data(), RAD_BF16, { T0, OUT }) }; + ht[0].stride[0] = ap; + ht[1].stride[0] = asp; + ht[8].stride[0] = yp; + for (int i : { 2, 3, 6, 7 }) ht[(size_t)i].stride[0] = 0; + std::vector dt = ht; + auto upload_plain = [&](int i, const void* source, size_t bytes) { + void* d = dalloc(bytes); + st_memcpy(d, source, bytes, hipMemcpyHostToDevice); + dt[(size_t)i].data = d; + }; + upload_plain(0, av.data(), av.size()); + upload_plain(1, asc.data(), asc.size() * 4); + upload_plain(2, dw[0].data(), dw[0].size() * sizeof(void*)); + upload_plain(3, ds[0].data(), ds[0].size() * sizeof(void*)); + upload_plain(6, dw[1].data(), dw[1].size() * sizeof(void*)); + upload_plain(7, ds[1].data(), ds[1].size() * sizeof(void*)); + upload_plain(4, sorted.data(), sorted.size() * 4); + upload_plain(5, offsets.data(), offsets.size() * 4); + const size_t ybytes = expected.size() * 2; + void* dy = dalloc(ybytes + 256); + st_memset(dy, 0xa5, ybytes + 256); + dt[8].data = (char*)dy + 128; + st_memcpy(dt[8].data, expected.data(), ybytes, hipMemcpyHostToDevice); + std::vector ps = { PI("M", M), PI("N", N[0]), PI("K", K[0]), + PI("N_odd", N[1]), PI("K_odd", K[1]), PI("n_expert", NE), + PI("top_k", top), PI("parts", parts), PI("group", 128), + PS("a_order", order), PS("dtype", "mxfp4a8") }; + RadArgs args{}; + args.t = ht.data(); + args.n_t = 9; + args.p = ps.data(); + args.n_p = (int)ps.size(); + args.world_size = 1; + const int rc = oracle->launch(&args, nullptr); + ok("MXFP4 grouped host oracle", rc == RAD_OK); + if (rc == RAD_OK) run_case(row, dt, ps); + std::vector got(ybytes + 256); + st_memcpy(got.data(), dy, got.size(), hipMemcpyDeviceToHost); + bool match = rc == RAD_OK, guards = true; + for (size_t i = 0; i < 128; ++i) + guards = guards && got[i] == 0xa5 && got[got.size() - 128 + i] == 0xa5; + const auto* values = (const uint16_t*)(got.data() + 128); + for (int r = 0; r < T0; ++r) + for (int c = 0; c < yp; ++c) { + if (c >= OUT) + guards = guards && values[r * yp + c] == h_to_bf16(-4); + else { + const float want = h_bf16(expected[(size_t)r * yp + c]), + value = h_bf16(values[r * yp + c]); + match = match && (std::isnan(want) ? std::isnan(value) + : std::isinf(want) ? value == want + : std::isfinite(value) && + std::fabs(value - want) <= + 0.004f + 0.008f * std::fabs(want)); + } + } + const char* lut = std::getenv("RADIANCE_MXFP4_LUT"); + const char* pipe = std::getenv("RADIANCE_MXFP4_PREFILL_PIPE"); + auto env_or = [](const char* n, const char* d) { + const char* v = std::getenv(n); + return v ? v : d; + }; + const char* p64 = std::getenv("RADIANCE_MXFP4_PREFILL_P64"); + const std::string p64s = + !p64 ? std::string("rule") + : p64[0] == '1' + ? fmt("BM%s BN%s K%s x%s out%s db%s", env_or("RADIANCE_MXFP4_PREFILL_P64_BM", "rule"), + env_or("RADIANCE_MXFP4_PREFILL_P64_BN", "rule"), + env_or("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", "rule"), + env_or("RADIANCE_MXFP4_PREFILL_P64_COLTILES", "4"), + env_or("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", "rule"), + env_or("RADIANCE_MXFP4_PREFILL_P64_DB", "0")) + : std::string("off"); + ok(fmt("MXFP4 M=%d N=%d K=%d parts=%d pooled=%d %s exceptional=%d holes=%d lut=%s pipe=%s " + "p64=%s, pointer tables and dropped slots", + M, OUT, NK, parts, pooled, order, exceptional, holes, lut ? lut : "rule", + pipe ? pipe : "rule", p64s.c_str()) + .c_str(), + match); + ok("MXFP4 grouped output red zones and pitch", guards); + RadEncoding enc{}; + rad_enc_copy_str(enc.scheme, "affine"); + rad_enc_add_plane(&enc, "codes", RAD_FP4E2M1, 1, 1); + rad_enc_add_plane(&enc, "scale", RAD_E8M0, 1, 32); + int selection = 0; + RadLayout layout{}; + RadTensor plane = T(nullptr, RAD_FP4E2M1, { N[0], K[0] }); + ok("MXFP4 layout keeps canonical bytes", + row->layout(ps.data(), (int)ps.size(), 2, &enc, &selection, &plane, 1, &layout) == + RAD_E_UNSUPPORTED); + enc.plane[1].block[1] = 64; + ok("MXFP4 layout rejects a different scale group", + row->layout(ps.data(), (int)ps.size(), 2, &enc, &selection, &plane, 1, &layout) == + RAD_E_DTYPE); + for (void* p : pinned) hipHostFree(p); + dlclose(ref); +} + +/* The MXFP4 expert GEMM at GLM's TP8 slices (mx_experts_check's model shapes 3 and 4): gate_up + * 512 x 4096 over token rows (parts 2), down 4096 x 256 over sorted rows, over an M-token chunk. + * + * Routing is uniform with top_k distinct experts a token, as a trained router spreads load at + * decode, or skewed (`skew`): a Gamma load per expert with the given coefficient of variation + * ("g1.0" or "1.0"), or Zipf ("z1.1") over a shuffled rank, each token drawing its top_k distinct + * experts by that load. The fill of tall row tiles hangs on that skew, and the real router's is not + * measured. Every expert has its own bytes behind a pointer table, as the engine passes them, so + * the touched experts are the real traffic. Warm, a touched set under 64 MiB is cache-resident + * after the first launch; --cold is the engine's case. + * + * Forms are chosen by the RADIANCE_MXFP4_* environment, read at every launch. Their rule is + * mirrored here only to name the form and count the expert slices it streams: a (job, expert) + * pair reads the whole slice across the column blocks, so row groups re-read an expert once per + * group its run spans, and the expert-major decode form once per 16 of its rows. Every form must + * match the bytes of a pinned reference ("old": the TP8 prefill form with its stage prefetch from + * 512 routed rows, below that the rule), since each keeps one accumulation order per element. */ +static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_t top_k, + bool f8 = false, const char* skew = nullptr) { + if (iters <= 0) iters = 100; + if (Mtok < 1 || E < 2 || E > 512 || top_k < 1 || top_k > E) { + std::printf("--perfmx: M >= 1, 2 <= experts <= 512 and 1 <= top_k <= experts\n"); + return; + } + const char* const rname = f8 ? "moe_gemm_fp8a8_f32scale" : "moe_gemm_mxfp4a8"; + const RadKernelInfo* r = find(pl, rname); + if (!r) { + std::printf("--perfmx: row %s absent\n", rname); + return; + } + const int64_t Tr = Mtok * top_k; + + uint64_t rs = 0x9E3779B97F4A7C15ull; + auto rnd = [&]() { + rs ^= rs << 13; + rs ^= rs >> 7; + rs ^= rs << 17; + return rs; + }; + /* An expert's load: none (uniform), Gamma(1/cv^2) or 1/rank^s. */ + char kind = 'u'; + double sk = 0.0; + if (skew && *skew) { + kind = std::isalpha((unsigned char)skew[0]) ? (char)skew[0] : 'g'; + sk = std::strtod(std::isalpha((unsigned char)skew[0]) ? skew + 1 : skew, nullptr); + if ((kind != 'g' && kind != 'z') || !(sk >= 0.0)) { + std::printf("--perfmx: skew is a Gamma CV (\"g1.0\" or \"1.0\") or a Zipf exponent " + "(\"z1.1\")\n"); + return; + } + if (sk == 0.0) kind = 'u'; + } + std::vector load((size_t)E, 1.0); + if (kind == 'g') { + std::mt19937_64 gen(0x5EEDull); + std::gamma_distribution gam(1.0 / (sk * sk), 1.0); + for (double& v : load) v = std::max(gam(gen), 1e-12); + } else if (kind == 'z') { + std::vector rank((size_t)E); + for (int64_t e = 0; e < E; ++e) rank[(size_t)e] = e; + for (int64_t e = E - 1; e > 0; --e) + std::swap(rank[(size_t)e], rank[(size_t)(rnd() % (uint64_t)(e + 1))]); + for (int64_t e = 0; e < E; ++e) + load[(size_t)e] = std::pow((double)(rank[(size_t)e] + 1), -sk); + } + std::vector perm((size_t)E); + for (int64_t e = 0; e < E; ++e) perm[(size_t)e] = (int32_t)e; + std::vector> by_e((size_t)E); + std::vector left((size_t)E); + for (int64_t t = 0; t < Mtok; ++t) { + if (kind == 'u') { + for (int64_t j = 0; j < top_k; ++j) { + std::swap(perm[(size_t)j], + perm[(size_t)(j + (int64_t)(rnd() % (uint64_t)(E - j)))]); + by_e[(size_t)perm[(size_t)j]].push_back((int32_t)(t * top_k + j)); + } + continue; + } + left = load; + double sum = 0.0; + for (double v : left) sum += v; + for (int64_t j = 0; j < top_k; ++j) { + double u = (double)(rnd() >> 11) * (1.0 / 9007199254740992.0) * sum; + int64_t e = 0; + while (e + 1 < E && (left[(size_t)e] == 0.0 || u >= left[(size_t)e])) { + u -= left[(size_t)e]; + ++e; + } + while (left[(size_t)e] == 0.0) e = (e + 1) % E; + sum -= left[(size_t)e]; + left[(size_t)e] = 0.0; + by_e[(size_t)e].push_back((int32_t)(t * top_k + j)); + } + } + std::vector off((size_t)(E + 1), 0), sorted, owner; + sorted.reserve((size_t)Tr); + owner.reserve((size_t)Tr); + int64_t touched = 0, rmax = 0, under16 = 0; + double sq = 0.0; + for (int64_t e = 0; e < E; ++e) { + const int64_t n = (int64_t)by_e[(size_t)e].size(); + off[(size_t)(e + 1)] = off[(size_t)e] + (int32_t)n; + sorted.insert(sorted.end(), by_e[(size_t)e].begin(), by_e[(size_t)e].end()); + owner.insert(owner.end(), (size_t)n, (int32_t)e); + touched += n > 0; + rmax = std::max(rmax, n); + under16 += n < 16; + sq += (double)n * (double)n; + } + const double mean = (double)Tr / (double)E; + const double cv = + mean > 0 ? std::sqrt(std::max(sq / (double)E - mean * mean, 0.0)) / mean : 0.0; + const std::string routing = kind == 'u' + ? std::string("uniform") + : fmt("%s %.2f", kind == 'g' ? "Gamma CV" : "Zipf s", sk); + std::printf( + "%s at GLM's TP8 slices, a %lld-token chunk: Tr=%lld routed rows, " + "top %lld of %lld experts (%s), %lld touched, a run 1..%lld rows, %.1f mean, CV %.2f, " + "%lld under 16; %s, %d launches\n", + rname, (long long)Mtok, (long long)Tr, (long long)top_k, (long long)E, routing.c_str(), + (long long)touched, (long long)rmax, mean, cv, (long long)under16, + g_cold > 0 + ? fmt("cold (%lld MiB read before each, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", + iters); + + constexpr int kEnvs = 22; + static const char* const kEnvMx[kEnvs] = { "RADIANCE_MXFP4_DECODE_EXPERTS", + "RADIANCE_MXFP4_ALIGNED_JOBS", + "RADIANCE_MXFP4_PREFILL_N32", + "RADIANCE_MXFP4_PREFILL_M32", + "RADIANCE_MXFP4_PREFILL_N64", + "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", + "RADIANCE_MXFP4_EXPERTS_STAGE_K", + "RADIANCE_MXFP4_EXPERTS_COLTILES", + "RADIANCE_MXFP4_LUT", + "RADIANCE_MXFP4_PREFILL_PIPE", + "RADIANCE_MXFP4_PREFILL_P64", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", + "RADIANCE_MXFP4_PREFILL_P64_BM", + "RADIANCE_MXFP4_PREFILL_P64_BN", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", + "RADIANCE_MXFP4_PREFILL_P64_COLTILES", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", + "RADIANCE_MXFP4_PREFILL_P64_T_BM64", + "RADIANCE_MXFP4_PREFILL_P64_T_BN128", + "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", + "RADIANCE_MXFP4_PREFILL_P64_DB" }; + /* The F32-scale row has no prefill forms; its slots 1..5 and 8..21 name the MXFP4 switches, + * which it does not read. */ + static const char* const kEnvF8[kEnvs] = { "RADIANCE_FP8F32_DECODE_EXPERTS", + "RADIANCE_MXFP4_ALIGNED_JOBS", + "RADIANCE_MXFP4_PREFILL_N32", + "RADIANCE_MXFP4_PREFILL_M32", + "RADIANCE_MXFP4_PREFILL_N64", + "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", + "RADIANCE_FP8F32_EXPERTS_STAGE_K", + "RADIANCE_FP8F32_EXPERTS_COLTILES", + "RADIANCE_MXFP4_LUT", + "RADIANCE_MXFP4_PREFILL_PIPE", + "RADIANCE_MXFP4_PREFILL_P64", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", + "RADIANCE_MXFP4_PREFILL_P64_BM", + "RADIANCE_MXFP4_PREFILL_P64_BN", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", + "RADIANCE_MXFP4_PREFILL_P64_COLTILES", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", + "RADIANCE_MXFP4_PREFILL_P64_T_BM64", + "RADIANCE_MXFP4_PREFILL_P64_T_BN128", + "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", + "RADIANCE_MXFP4_PREFILL_P64_DB" }; + const char* const* const kEnv = f8 ? kEnvF8 : kEnvMx; + std::string saved[kEnvs]; + bool had[kEnvs]; + for (int i = 0; i < kEnvs; ++i) { + const char* v = std::getenv(kEnv[i]); + had[i] = v != nullptr; + if (v) saved[i] = v; + } + auto restore = [&]() { + for (int i = 0; i < kEnvs; ++i) { + if (had[i]) + setenv(kEnv[i], saved[i].c_str(), 1); + else + unsetenv(kEnv[i]); + } + }; + auto on = [](const char* n, bool dflt) { + const char* v = std::getenv(n); + return v ? v[0] == '1' : dflt; + }; + /* body()'s glm_prefill: the default of the prefill switches at GLM's projections. */ + const bool glm = !f8 && E == 288 && top_k == 8; + auto num = [](const char* n, long dflt) { + const char* v = std::getenv(n); + return v && *v ? std::strtol(v, nullptr, 10) : dflt; + }; + /* env nullptr: the environment as given. Expert-major forms pin stage and column tiles; the + * prefill forms exist only from 512 routed rows. `lut` 0 or 1 pins the weight decode, `pipe` + * the TP8 prefill form's stage prefetch (-1: as given); the arithmetic decode without the + * prefetch is the bytewise reference of the others. `bm` > 0 pins the P64 form below its row + * bound at BM, BN, stage, column tiles (down only), LDS output and double buffer (gate_up + * only); every other pinned form pins P64 off. */ + struct Form { + const char* env; + int stage, tiles, lut, pipe = -1, bm = 0, bn = 0, sk = 0, ct = 0, out = 0, db = 0; + }; + std::vector
forms = { { nullptr, 0, 0, -1 }, { "100000", 256, 1, -1 }, + { "100000", 256, 4, -1 }, { "100000", 128, 1, -1 }, + { "100000", 128, 4, -1 }, { "000000", 0, 0, -1 } }; + if (!f8) + for (int lut : { 0, 1 }) { + forms.push_back({ "100000", 256, 1, lut }); + forms.push_back({ "100000", 128, 4, lut }); + } + if (Tr >= 512 && !f8) { + for (const char* f : { "010000", "001000", "011000", "011100", "011110", "011111" }) + forms.push_back({ f, 0, 0, -1 }); + for (int pipe : { 0, 1 }) + for (int lut : { 0, 1 }) forms.push_back({ "011111", 0, 0, lut, pipe }); + } + const Form old = Tr >= 512 && !f8 ? Form{ "011111", 0, 0, 1, 1 } : Form{ nullptr, 0, 0, -1 }; + auto apply = [&](const Form& F) { + restore(); + if (!F.env) return; + for (int i = 0; i < 6; ++i) setenv(kEnv[i], F.env[i] == '1' ? "1" : "0", 1); + const int pinned[2] = { F.stage, F.tiles }; + for (int i = 0; i < 2; ++i) { + if (F.stage) + setenv(kEnv[6 + i], std::to_string(pinned[i]).c_str(), 1); + else + unsetenv(kEnv[6 + i]); + } + const int pinned2[2] = { F.lut, F.pipe }; + for (int i = 8; i < 10; ++i) + if (pinned2[i - 8] >= 0) setenv(kEnv[i], pinned2[i - 8] ? "1" : "0", 1); + setenv(kEnv[10], F.bm ? "1" : "0", 1); + if (F.bm) { + const int v[7] = { 0, 0, F.bm, F.bn, F.sk, F.ct, F.out }; + for (int i = 0; i < 7; ++i) setenv(kEnv[11 + i], std::to_string(v[i]).c_str(), 1); + setenv(kEnv[21], F.db ? "1" : "0", 1); + } + }; + + struct Proj { + const char* name; + int64_t N, K, parts; + bool srt; + }; + const Proj projs[2] = { { "gate_up", 512, 4096, 2, false }, { "down", 4096, 256, 1, true } }; + double rule_us = 0.0, rule_bytes = 0.0; + for (const Proj& P : projs) { + const int64_t N = P.N, K = P.K, Ma = P.srt ? Tr : Mtok; + /* Per expert: E2M1 codes and an E8M0 byte per 32, or E4M3 codes and an f32 per 128 x 128. */ + const int64_t cb = f8 ? N * K : N * K / 2, sb = f8 ? N / 128 * (K / 128) * 4 : N * K / 32; + const int64_t nec[2] = { (E + 1) / 2, E / 2 }; + const double slice = (double)(cb + sb); + std::printf(" %-7s %lld x %lld (parts %lld, %s rows): %.3f MiB an expert slice, %.1f MiB " + "touched of %.1f MiB\n", + P.name, (long long)N, (long long)K, (long long)P.parts, + P.srt ? "sorted" : "token", slice / 1048576.0, touched * slice / 1048576.0, + E * slice / 1048576.0); + /* P64 over BM x BN x stage; at down's K (A resident) also over column tiles, and the LDS + * output at the default. */ + std::vector pf = forms; + if (Tr >= 512 && !f8) { + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + for (int sk2 : { 128, 256 }) + for (int ct : { 1, 4 }) { + if (ct == 1 && K > 256) continue; + pf.push_back({ "000000", 0, 0, -1, -1, bm, bn, sk2, ct, 0 }); + } + pf.push_back({ "000000", 0, 0, -1, -1, 64, 128, 128, 4, 1 }); + /* The double buffer where two stages fit in LDS (streamed A, gate_up). */ + if (K > 256) { + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + pf.push_back({ "000000", 0, 0, -1, -1, bm, bn, 128, 4, 0, 1 }); + pf.push_back({ "000000", 0, 0, -1, -1, 32, 64, 256, 4, 0, 1 }); + pf.push_back({ "000000", 0, 0, -1, -1, 64, 128, 128, 4, 1, 1 }); + } + } + + std::vector av((size_t)(Ma * K)); + for (size_t i = 0; i < av.size(); ++i) + av[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i) % 33) - 16) / 4); + std::vector asc((size_t)(Ma * (K / 128))); + for (size_t i = 0; i < asc.size(); ++i) asc[i] = 0.003f * (float)(1 + i % 5); + void* d_a = dalloc(av.size()); + void* d_as = dalloc(asc.size() * 4); + void* d_s = dalloc((size_t)Tr * 4); + void* d_o = dalloc((size_t)(E + 1) * 4); + void* d_y = dalloc((size_t)(Tr * N) * 2); + void *d_w[2], *d_sc[2], *d_tw[2], *d_ts[2]; + bool alloc_ok = d_a && d_as && d_s && d_o && d_y; + for (int c = 0; c < 2 && alloc_ok; ++c) { + d_w[c] = dalloc((size_t)(nec[c] * cb)); + d_sc[c] = dalloc((size_t)(nec[c] * sb)); + d_tw[c] = dalloc((size_t)nec[c] * sizeof(void*)); + d_ts[c] = dalloc((size_t)nec[c] * sizeof(void*)); + alloc_ok = d_w[c] && d_sc[c] && d_tw[c] && d_ts[c]; + if (!alloc_ok) break; + /* E4M3 codes with the top exponent bit clear: finite, under 2 in magnitude. */ + std::vector hw((size_t)(nec[c] * cb + 7) / 8); + for (uint64_t& v : hw) v = f8 ? rnd() & 0xF7F7F7F7F7F7F7F7ull : rnd(); + st_memcpy(d_w[c], hw.data(), (size_t)(nec[c] * cb), hipMemcpyHostToDevice); + /* E8M0 2^-5..2^2 or f32 near 0.01: finite products, no exceptional codes on the timed + * path. */ + std::vector hs((size_t)(nec[c] * sb)); + if (f8) + for (size_t i = 0; i < hs.size(); i += 4) { + const float v = 0.01f * (float)(1 + rnd() % 7); + std::memcpy(&hs[i], &v, 4); + } + else + for (uint8_t& v : hs) v = (uint8_t)(122 + rnd() % 8); + st_memcpy(d_sc[c], hs.data(), hs.size(), hipMemcpyHostToDevice); + std::vector tw((size_t)nec[c]), tsc((size_t)nec[c]); + for (int64_t x = 0; x < nec[c]; ++x) { + tw[(size_t)x] = (const char*)d_w[c] + x * cb; + tsc[(size_t)x] = (const char*)d_sc[c] + x * sb; + } + st_memcpy(d_tw[c], tw.data(), tw.size() * sizeof(void*), hipMemcpyHostToDevice); + st_memcpy(d_ts[c], tsc.data(), tsc.size() * sizeof(void*), hipMemcpyHostToDevice); + } + if (!alloc_ok) { + std::printf(" %s: alloc failed\n", P.name); + dfree_all(); + break; + } + st_memcpy(d_a, av.data(), av.size(), hipMemcpyHostToDevice); + st_memcpy(d_as, asc.data(), asc.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, sorted.data(), (size_t)Tr * 4, hipMemcpyHostToDevice); + st_memcpy(d_o, off.data(), (size_t)(E + 1) * 4, hipMemcpyHostToDevice); + + std::vector ts = { + T(d_a, RAD_F8E4M3, { Ma, K }), + T(d_as, RAD_F32, { Ma, K / 128 }), + f8 ? T(d_tw[0], RAD_F8E4M3, { nec[0], N, K }) + : T(d_tw[0], RAD_FP4E2M1, { nec[0], N, K }), + f8 ? T(d_ts[0], RAD_F32, { nec[0], N / 128, K / 128 }) + : T(d_ts[0], RAD_E8M0, { nec[0], N, K / 32 }), + T(d_s, RAD_I32, { Tr }), + T(d_o, RAD_I32, { E + 1 }), + f8 ? T(d_tw[1], RAD_F8E4M3, { nec[1], N, K }) + : T(d_tw[1], RAD_FP4E2M1, { nec[1], N, K }), + f8 ? T(d_ts[1], RAD_F32, { nec[1], N / 128, K / 128 }) + : T(d_ts[1], RAD_E8M0, { nec[1], N, K / 32 }), + T(d_y, RAD_BF16, { Tr, N }), + }; + /* A pointer table is told from a stacked plane by a leading stride of zero. */ + for (int i : { 2, 3, 6, 7 }) ts[(size_t)i].stride[0] = 0; + std::vector ps = { + PI("M", Mtok), + PI("N", N), + PI("K", K), + PI("N_odd", N), + PI("K_odd", K), + PI("n_expert", E), + PI("top_k", top_k), + PI("parts", P.parts), + PI("group", 128), + PS("a_order", P.srt ? "sorted" : "token"), + PS("dtype", f8 ? "fp8a8f32" : "mxfp4a8"), + }; + 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; + const double flop = 2.0 * (double)Tr * (double)N * (double)K; + const size_t ybytes = (size_t)(Tr * N) * 2; + std::vector reference(ybytes), got(ybytes); + apply(old); + st_memset(d_y, 0xff, ybytes); + bool have_old = r->launch(&a, nullptr) == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + if (have_old) st_memcpy(reference.data(), d_y, ybytes, hipMemcpyDeviceToHost); + std::printf(" old: %s\n", + !have_old ? "not served, no byte comparison" + : old.env ? "TP8 prefill form, stage prefetch and table decode pinned" + : "the rule"); + for (size_t f = 0; f < pf.size(); ++f) { + apply(pf[f]); + const long max_t = f8 ? num("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1) + : num(P.srt ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN" + : "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP", + glm ? (P.srt ? 6143 : 768) : 511); + const char* forced = std::getenv(kEnv[0]); + const bool pwide = K > 256 ? Tr >= num(kEnv[19], 24576) : Tr >= num(kEnv[20], 24576); + const long dbm = pwide || (K > 256 && Tr >= num(kEnv[18], 12288)) ? 64 : 32; + const long dbn = pwide ? 128 : 64; + const long dsk = K > 256 && !pwide ? 256 : 128; + const long pbm = num(kEnv[13], dbm) == 32 ? 32 : 64, + pbn = num(kEnv[14], dbn) == 64 ? 64 : 128; + const long psk = num(kEnv[15], dsk) == 256 ? 256 : 128; + const bool p64 = !f8 && on(kEnv[10], glm) && !(forced && forced[0] == '1') && + Tr >= num(P.srt ? kEnv[12] : kEnv[11], P.srt ? 5760 : 769) && + (Tr + pbm - 1) / pbm + E <= 65535; + const bool expert = !p64 && on(kEnv[0], max_t < 0 || Tr <= max_t); + const long esk = num(kEnv[6], K <= 256 ? 128 : 256) == 128 ? 128 : 256; + const long et = num(kEnv[7], K <= 256 || (f8 && Tr < 128) ? 4 : 1) == 4 ? 4 : 1; + const bool aligned = !p64 && !expert && !f8 && on(kEnv[1], glm) && Tr >= 512; + const bool wide = !p64 && !expert && !f8 && on(kEnv[2], glm) && Tr >= 512; + const bool tall = wide && aligned && on(kEnv[3], glm), n64 = tall && on(kEnv[4], glm); + const bool cached = n64 && on(kEnv[5], glm), lut = f8 || p64 || on(kEnv[8], true); + const bool pipe = cached && on(kEnv[9], glm); + const long pct = K <= 256 && num(kEnv[16], 4) != 1 ? 4 : 1; + const bool pout = num(kEnv[17], pwide ? 1 : 0) == 1; + const bool pdb = + K > 256 && num(kEnv[21], 0) == 1 && (psk == 128 || (pbm == 32 && pbn == 64)); + const int64_t jr = p64 ? pbm : tall ? 32 : 16, tile = Tr < 32 ? 1 : Tr < 128 ? 4 : 16; + int64_t streams = 0; + if (p64 || aligned || expert) + for (int64_t e = 0; e < E; ++e) + streams += (off[(size_t)(e + 1)] - off[(size_t)e] + jr - 1) / jr; + else + for (int64_t i = 0; i < Tr; ++i) + streams += i % tile == 0 || owner[(size_t)i] != owner[(size_t)(i - 1)]; + const std::string label = + std::string(pf[f].env ? "" : "rule: ") + + (p64 ? fmt("P64 BM%ld BN%ld K%ld", pbm, pbn, psk) + + (K <= 256 ? fmt(" x%ld, A resident", pct) : "") + + (pout ? ", LDS out" : "") + (pdb ? ", double buffer" : "") + : expert ? fmt("expert-major K%ld x%ld tiles", esk, et) + : std::string(n64 ? "M32N64" + : tall ? "M32N32" + : wide ? "M16N32" + : f8 ? "M16N64" + : "M16N16") + + (aligned ? " aligned jobs" + : fmt(" row groups of %lld", (long long)tile)) + + (cached ? ", cached rows" : "") + (pipe ? ", pipe" : "")) + + (lut ? "" : ", fp4x4"); + st_memset(d_y, 0xff, ybytes); + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { + std::printf(" %-46s rc=%d (not served)\n", label.c_str(), rc); + continue; + } + st_memcpy(got.data(), d_y, ybytes, hipMemcpyDeviceToHost); + { + hipEvent_t w0, w1; + st_ev_create(&w0); + st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0.0f; + for (int guard = 0; guard < 100000 && wms < 500.0f; ++guard) { + for (int i = 0; i < 4; ++i) r->launch(&a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); + st_ev_destroy(w1); + } + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + if (f == 0) { + rule_us += us; + rule_bytes += touched * slice; + } + std::string same; + if (have_old) { + int64_t diff = 0; + for (size_t i = 0; i < ybytes; i += 2) + diff += std::memcmp(&got[i], &reference[i], 2) != 0; + same = diff ? fmt(" %lld elements differ from old", (long long)diff) : " = old"; + } + std::printf( + " %-46s %9.1f us %7.1f GB/s touched %5.2fx streamed %6.1f TFLOP/s%s\n", + label.c_str(), us, touched * slice / (us * 1e3), + touched ? (double)streams / (double)touched : 0.0, flop / (us * 1e6), same.c_str()); + } + restore(); + dfree_all(); + } + if (rule_us > 0) + std::printf(" the rule's forms, gate_up + down: %.1f us a layer, %.1f GB/s touched\n", + rule_us, rule_bytes / (rule_us * 1e3)); +} + /* The gated residual's read at int8 codes. The same inputs run with the codes plane as E4M3 and * as I8: the bf16 block input and the rotated E4M3 twin must be byte-identical, and the int8 codes * must equal quant_act_i8g's over the bf16 input (per (row, 128) at amax / 127). Row counts reach @@ -11278,6 +13829,995 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool (void)hipStreamDestroy(hs); } +/* mHC's chunk-split read, as tensor parallelism issues it: every rank's mhc_pre_partial over its + * chunks, the partials joined row by row as the row-interleaved all_gather lays them out (here on + * the host), then mhc_pre_finish. The result must be byte-identical to mhc_pre on the same inputs, + * under each of mhc_pre's kernel switches, since both run the same projection and finishing + * kernels; the partial matrix's padding slots must be zero. */ +static void mhc_split_check(const Plugin& pl, int64_t rows, int world, const char* env, + const char* value) { + const RadKernelInfo* pre = find(pl, "mhc_pre_bf16"); + const RadKernelInfo* part_row = find(pl, "mhc_pre_partial_bf16"); + const RadKernelInfo* fin = find(pl, "mhc_pre_finish_bf16"); + const char* nm = "mhc_pre_partial_bf16 + mhc_pre_finish_bf16"; + if (!pre || !part_row || !fin) { ok(nm, false, "row absent"); return; } + const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; + const int64_t mine = total / world, hp = W + 6, xp = n + 2; + const char* saved = env ? std::getenv(env) : nullptr; + const std::string keep = saved ? saved : ""; + if (env) setenv(env, value, 1); + + std::vector hv((size_t)(rows * hp)); + for (size_t i = 0; i < hv.size(); ++i) + hv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 3u + 11u) % 2001) - 1000) / 1000); + std::vector fv((size_t)(mix * W)), sv = { 0.7f, 0.9f, 1.1f }, bv((size_t)mix); + for (size_t i = 0; i < fv.size(); ++i) + fv[i] = (float)((int)(st_mix32((uint32_t)i + 77u) % 2001) - 1000) / 100000; + for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)((int)(i % 7) - 3) * 0.25f; + void* d_h = dalloc(hv.size() * 2); + void* d_f = dalloc(fv.size() * 4); + void* d_s = dalloc(12); + void* d_b = dalloc(bv.size() * 4); + st_memcpy(d_h, hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_f, fv.data(), fv.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, sv.data(), 12, hipMemcpyHostToDevice); + st_memcpy(d_b, bv.data(), bv.size() * 4, hipMemcpyHostToDevice); + RadTensor th = T(d_h, RAD_BF16, { rows, W }); th.stride[0] = hp; + const RadTensor tf = T(d_f, RAD_F32, { mix, W }), ts = T(d_s, RAD_F32, { 3 }), + tb = T(d_b, RAD_F32, { mix }); + struct Out { std::vector x, p, c; }; + auto outputs = [&](void** dx, void** dp, void** dc, std::vector* t) { + *dx = dalloc((size_t)(rows * xp * 2)); *dp = dalloc((size_t)(rows * hc * 4)); + *dc = dalloc((size_t)(rows * hc * hc * 4)); + RadTensor tx = T(*dx, RAD_BF16, { rows, n }); tx.stride[0] = xp; + t->push_back(tx); + t->push_back(T(*dp, RAD_F32, { rows, hc })); + t->push_back(T(*dc, RAD_F32, { rows, hc * hc })); + }; + auto fetch = [&](void* dx, void* dp, void* dc) { + Out o; + o.x.resize((size_t)(rows * xp * 2)); o.p.resize((size_t)(rows * hc * 4)); + o.c.resize((size_t)(rows * hc * hc * 4)); + st_memcpy(o.x.data(), dx, o.x.size(), hipMemcpyDeviceToHost); + st_memcpy(o.p.data(), dp, o.p.size(), hipMemcpyDeviceToHost); + st_memcpy(o.c.data(), dc, o.c.size(), hipMemcpyDeviceToHost); + return o; + }; + auto launch = [&](const RadKernelInfo* r, std::vector& t, std::vector& p) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); + a.world_size = 1; + const int rc = r->launch(&a, nullptr); + return rc == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + }; + std::vector coef = { PI("M", rows), PI("n", n), PI("hc", hc), PI("iterations", 20), + PF("eps", 1e-5), PF("hc_eps", 1e-6) }; + + void *wx, *wp, *wc; + std::vector whole = { th, tf, ts, tb }; + outputs(&wx, &wp, &wc, &whole); + std::vector pp = coef; pp.push_back(PS("dtype", "bf16")); + bool good = launch(pre, whole, pp); + const Out want = fetch(wx, wp, wc); + + std::vector gathered((size_t)(rows * total * S)); + bool padded = true; + for (int rank = 0; rank < world && good; ++rank) { + void* d_p = dalloc((size_t)(rows * mine * S * 4)); + std::vector t = { th, tf, T(d_p, RAD_F32, { rows, mine * S }) }; + std::vector p = { PI("M", rows), PI("n", n), PI("hc", hc), PI("chunk", 2048), + PI("first", rank * mine), PI("chunks", mine), + PS("dtype", "bf16") }; + std::vector fill((size_t)(rows * mine * S), 7.0f); + st_memcpy(d_p, fill.data(), fill.size() * 4, hipMemcpyHostToDevice); + good = launch(part_row, t, p); + st_memcpy(fill.data(), d_p, fill.size() * 4, hipMemcpyDeviceToHost); + for (int64_t r = 0; r < rows; ++r) { + for (int64_t c = 0; c < mine; ++c) + for (int64_t j = mix + 1; j < S; ++j) + padded = padded && fill[(size_t)(r * mine * S + c * S + j)] == 0.0f; + std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)], + &fill[(size_t)(r * mine * S)], (size_t)(mine * S * 4)); + } + } + void* d_g = dalloc(gathered.size() * 4); + st_memcpy(d_g, gathered.data(), gathered.size() * 4, hipMemcpyHostToDevice); + void *sx, *sp, *sc; + std::vector split = { T(d_g, RAD_F32, { rows, total * S }), th, ts, tb }; + outputs(&sx, &sp, &sc, &split); + std::vector fp = coef; fp.push_back(PI("chunk", 2048)); fp.push_back(PS("dtype", "bf16")); + good = good && launch(fin, split, fp); + const Out got = fetch(sx, sp, sc); + const bool same = good && got.x == want.x && got.p == want.p && got.c == want.c; + ok(fmt("%s at M=%lld over %d ranks%s%s%s: byte-identical to mhc_pre", nm, (long long)rows, + world, env ? ", " : "", env ? env : "", env ? (std::string("=") + value).c_str() : "") + .c_str(), same, good ? (got.x != want.x ? "x differs" : got.p != want.p ? "post differs" + : got.c != want.c ? "comb differs" : "") + : "launch failed"); + ok(fmt("%s at M=%lld over %d ranks: zero padding", nm, (long long)rows, world).c_str(), padded); + if (env) { if (saved) setenv(env, keep.c_str(), 1); else unsetenv(env); } +} + +/* mhc_pre and mhc_post at GLM's shape (n 4096, four streams, 2048-column chunks, 20 Sinkhorn + * rounds), every form timed and compared byte for byte with the old dispatch + * (RADIANCE_MHC_FINISH=old, RADIANCE_MHC_PARTIAL_VEC=0, the per-output mhc_post). + * The whole op, its partials alone (all eight chunks, and the one chunk a rank computes at TP8) + * and its finish alone over those partials. GB/s counts h and x (and mhc_post's output); the + * mixing weights (1.5 MiB) stay in L2. `iters` below zero runs each form once and reports only + * the comparisons, as a case. */ +static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + if (rows < 1 || rows > 65535) { std::printf("--perfmhcpre: 1 <= M <= 65535\n"); return; } + const RadKernelInfo* pre = find(pl, "mhc_pre_bf16"); + const RadKernelInfo* part = find(pl, "mhc_pre_partial_bf16"); + const RadKernelInfo* fin = find(pl, "mhc_pre_finish_bf16"); + const RadKernelInfo* post = find(pl, "mhc_post_bf16"); + if (!pre || !part || !fin || !post) { std::printf("--perfmhcpre: an mhc row is absent\n"); return; } + const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; + static const char* const kEnv[5] = { "RADIANCE_MHC_FINISH", "RADIANCE_MHC_ROWS4_MIN", + "RADIANCE_MHC_POST_VEC", "RADIANCE_MHC_PARTIAL_VEC", + "RADIANCE_MHC_PARTIAL_ROWS" }; + std::string saved[5]; + bool had[5]; + for (int i = 0; i < 5; ++i) { + const char* v = std::getenv(kEnv[i]); + had[i] = v != nullptr; + if (v) saved[i] = v; + } + auto pin = [&](const char* finish, const char* rows4, const char* vec, + const char* pvec = nullptr, const char* prows = nullptr) { + const char* v[5] = { finish, rows4, vec, pvec, prows }; + for (int i = 0; i < 5; ++i) { + if (v[i]) setenv(kEnv[i], v[i], 1); + else if (had[i]) setenv(kEnv[i], saved[i].c_str(), 1); + else unsetenv(kEnv[i]); + } + }; + + std::vector hv((size_t)(rows * W)), yv((size_t)(rows * n)); + for (size_t i = 0; i < hv.size(); ++i) + hv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 3u + 11u) % 2001) - 1000) / 1000); + for (size_t i = 0; i < yv.size(); ++i) + yv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 5u + 3u) % 2001) - 1000) / 500); + std::vector fv((size_t)(mix * W)), sv = { 0.7f, 0.9f, 1.1f }, bv((size_t)mix); + for (size_t i = 0; i < fv.size(); ++i) + fv[i] = (float)((int)(st_mix32((uint32_t)i + 77u) % 2001) - 1000) / 100000; + for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)((int)(i % 7) - 3) * 0.25f; + void* d_h = dalloc(hv.size() * 2); + void* d_y = dalloc(yv.size() * 2); + void* d_f = dalloc(fv.size() * 4); + void* d_s = dalloc(12); + void* d_b = dalloc(bv.size() * 4); + void* d_x = dalloc((size_t)(rows * n * 2)); + void* d_p = dalloc((size_t)(rows * hc * 4)); + void* d_c = dalloc((size_t)(rows * hc * hc * 4)); + void* d_part = dalloc((size_t)(rows * total * S * 4)); + void* d_part1 = dalloc((size_t)(rows * S * 4)); + void* d_out = dalloc((size_t)(rows * W * 2)); + if (!d_h || !d_y || !d_f || !d_s || !d_b || !d_x || !d_p || !d_c || !d_part || !d_part1 || !d_out) { + std::printf("--perfmhcpre: alloc failed\n"); + return; + } + st_memcpy(d_h, hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_y, yv.data(), yv.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_f, fv.data(), fv.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, sv.data(), 12, hipMemcpyHostToDevice); + st_memcpy(d_b, bv.data(), bv.size() * 4, hipMemcpyHostToDevice); + const RadTensor th = T(d_h, RAD_BF16, { rows, W }), tf = T(d_f, RAD_F32, { mix, W }), + ts = T(d_s, RAD_F32, { 3 }), tb = T(d_b, RAD_F32, { mix }), + tx = T(d_x, RAD_BF16, { rows, n }), tp = T(d_p, RAD_F32, { rows, hc }), + tc = T(d_c, RAD_F32, { rows, hc * hc }); + std::vector coef = { PI("M", rows), PI("n", n), PI("hc", hc), PI("iterations", 20), + PF("eps", 1e-6), PF("hc_eps", 1e-6), PI("chunk", 2048), + PS("dtype", "bf16") }; + std::vector p_all = { PI("M", rows), PI("n", n), PI("hc", hc), PI("chunk", 2048), + PI("first", 0), PI("chunks", total), PS("dtype", "bf16") }; + std::vector p_one = p_all; + p_one[5] = PI("chunks", 1); + std::vector a_pre = { th, tf, ts, tb, tx, tp, tc }; + std::vector a_all = { th, tf, T(d_part, RAD_F32, { rows, total * S }) }; + std::vector a_one = { th, tf, T(d_part1, RAD_F32, { rows, S }) }; + std::vector a_fin = { T(d_part, RAD_F32, { rows, total * S }), th, ts, tb, tx, tp, tc }; + std::vector a_post = { T(d_y, RAD_BF16, { rows, n }), th, tp, tc, + T(d_out, RAD_BF16, { rows, W }) }; + auto args = [](std::vector& t, std::vector& p) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); + a.world_size = 1; + return a; + }; + RadArgs A_pre = args(a_pre, coef), A_all = args(a_all, p_all), A_one = args(a_one, p_one), + A_fin = args(a_fin, coef), A_post = args(a_post, coef); + auto timed = [&](const RadKernelInfo* r, RadArgs* a) { + if (r->launch(a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return -1.0; + if (check) return 0.0; + hipEvent_t w0, w1; + st_ev_create(&w0); st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0.0f; + for (int guard = 0; guard < 100000 && wms < 200.0f; ++guard) { + for (int i = 0; i < 8; ++i) r->launch(a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); st_ev_destroy(w1); + return st_time_us([&](int) { r->launch(a, nullptr); }, iters, nullptr); + }; + auto fetch = [&](void* d, size_t bytes) { + std::vector v(bytes); + st_memcpy(v.data(), d, bytes, hipMemcpyDeviceToHost); + return v; + }; + auto outputs = [&]() { + std::vector o = fetch(d_x, (size_t)(rows * n * 2)); + for (auto* d : { d_p, d_c }) { + const std::vector q = fetch(d, d == d_p ? (size_t)(rows * hc * 4) + : (size_t)(rows * hc * hc * 4)); + o.insert(o.end(), q.begin(), q.end()); + } + return o; + }; + const double hx = (double)rows * (W + n) * 2; + if (!check) + std::printf("mhc at GLM's shape, M=%lld (n 4096, hc 4, 20 rounds), %s, %d launches\n", + (long long)rows, g_cold > 0 ? fmt("cold (%lld MiB, median)", + (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", iters); + auto line = [&](const char* what, double us, double bytes, const std::string& same) { + if (check) { + ok(fmt("%s at M=%lld%s", what, (long long)rows, + same.empty() ? " is served" : ": byte-identical to the old dispatch").c_str(), + us >= 0 && same.find("DIFFERS") == std::string::npos, us < 0 ? "not served" : ""); + return; + } + if (us < 0) { std::printf(" %-44s not served\n", what); return; } + std::printf(" %-44s %8.1f us %7.1f GB/s%s\n", what, us, bytes / (us * 1e3), same.c_str()); + }; + auto cmp = [](const std::vector& a, const std::vector& b) { + return a == b ? std::string(" = old") : std::string(" DIFFERS from old"); + }; + + pin("old", nullptr, "0", "0"); + const double us_old = timed(pre, &A_pre); + const std::vector ref = outputs(); + line("mhc_pre, old dispatch", us_old, hx, ""); + struct Pv { const char* what; const char* finish; const char* rows4; const char* pvec; + const char* prows; }; + for (const Pv& v : { Pv{ "mhc_pre, rule", nullptr, nullptr, nullptr, nullptr }, + Pv{ "mhc_pre, finish: scalar mix, wide read", "scalar", nullptr, nullptr, nullptr }, + Pv{ "mhc_pre, old partials (rows4 from 32)", nullptr, nullptr, "0", nullptr }, + Pv{ "mhc_pre, four-slot partials, 1 row a wave", nullptr, nullptr, "1", "1" }, + Pv{ "mhc_pre, four-slot partials, 2 rows a wave", nullptr, nullptr, "1", "2" }, + Pv{ "mhc_pre, four-slot partials, 4 rows a wave", nullptr, nullptr, "1", "4" } }) { + pin(v.finish, v.rows4, nullptr, v.pvec, v.prows); + st_memset(d_x, 0xff, (size_t)(rows * n * 2)); + const double us = timed(pre, &A_pre); + line(v.what, us, hx, us < 0 ? "" : cmp(outputs(), ref)); + } + pin(nullptr, nullptr, nullptr, "0"); + if (part->launch(&A_all, nullptr) == RAD_OK) st_stream_sync(nullptr); + const std::vector part_ref = fetch(d_part, (size_t)(rows * total * S * 4)); + for (const Pv& v : { Pv{ "mhc_pre_partial, 8 chunks, old", nullptr, nullptr, "0", nullptr }, + Pv{ "mhc_pre_partial, 8 chunks, rule", nullptr, nullptr, nullptr, nullptr }, + Pv{ "mhc_pre_partial, 8 chunks, four-slot x1", nullptr, nullptr, "1", "1" }, + Pv{ "mhc_pre_partial, 8 chunks, four-slot x2", nullptr, nullptr, "1", "2" }, + Pv{ "mhc_pre_partial, 8 chunks, four-slot x4", nullptr, nullptr, "1", "4" }, + Pv{ "mhc_pre_partial, 8 chunks, rows4 at every M", nullptr, "1", "0", nullptr }, + Pv{ "mhc_pre_partial, 8 chunks, scalar-row", nullptr, "1000000", "0", nullptr } }) { + pin(nullptr, v.rows4, nullptr, v.pvec, v.prows); + st_memset(d_part, 0xff, (size_t)(rows * total * S * 4)); + const double us = timed(part, &A_all); + const bool is_ref = v.pvec && !std::strcmp(v.pvec, "0") && !v.rows4; + line(v.what, us, (double)rows * W * 2, us < 0 || is_ref ? std::string() + : cmp(fetch(d_part, (size_t)(rows * total * S * 4)), part_ref)); + } + pin(nullptr, nullptr, nullptr); + line("mhc_pre_partial, 1 chunk (a TP8 rank's)", timed(part, &A_one), (double)rows * W * 2 / 8, ""); + if (part->launch(&A_all, nullptr) == RAD_OK) st_stream_sync(nullptr); + for (const Pv& v : { Pv{ "mhc_pre_finish, old", "old", nullptr, nullptr, nullptr }, + Pv{ "mhc_pre_finish, rule", nullptr, nullptr, nullptr, nullptr }, + Pv{ "mhc_pre_finish, scalar mix, wide read", "scalar", nullptr, nullptr, nullptr } }) { + pin(v.finish, nullptr, nullptr); + st_memset(d_x, 0xff, (size_t)(rows * n * 2)); + const double us = timed(fin, &A_fin); + line(v.what, us, hx, us < 0 ? "" : cmp(outputs(), ref)); + } + const double post_bytes = (double)rows * (2 * W + n) * 2; + pin(nullptr, nullptr, "0"); + const double us_post_old = timed(post, &A_post); + const std::vector post_ref = fetch(d_out, (size_t)(rows * W * 2)); + line("mhc_post, old", us_post_old, post_bytes, ""); + pin(nullptr, nullptr, nullptr); + st_memset(d_out, 0xff, (size_t)(rows * W * 2)); + const double us_post = timed(post, &A_post); + line("mhc_post, rule", us_post, post_bytes, + us_post < 0 ? "" : cmp(fetch(d_out, (size_t)(rows * W * 2)), post_ref)); + for (int i = 0; i < 5; ++i) { + if (had[i]) setenv(kEnv[i], saved[i].c_str(), 1); + else unsetenv(kEnv[i]); + } +} + +/* router_sigmoid_topk's wave-per-row select against the serial scan (RADIANCE_ROUTER_SELECT=old), + * byte for byte over ids and weights with their pitches filled, so an overrun or a missed slot + * shows. Logits, bias and outputs are pitched, the bias strided. `ties` puts logits on steps of + * 1/2 and the bias on steps of 1/8, so many experts share a rank and the lower-index rule + * decides. `iters` below zero compares only, as a case; otherwise both are timed. */ +static void router_select(const Plugin& pl, int64_t rows, int64_t ne, int64_t k, int norm, + bool ties, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + const RadKernelInfo* r = find(pl, "router_sigmoid_topk_f32"); + if (!r) { ok("router_sigmoid_topk_f32 select", false, "row absent"); return; } + if (rows < 1 || rows > 65535 || ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne) { + std::printf("--perfrouter: 1 <= M <= 65535, top_k <= n_expert <= 512, top_k <= 32\n"); + return; + } + const int64_t lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1; + std::vector lg((size_t)(rows * lp)), bv((size_t)(ne * bp)); + for (size_t i = 0; i < lg.size(); ++i) { + const int u = (int)(st_mix32((uint32_t)i * 7u + 13u) % 2001) - 1000; + lg[i] = ties ? (float)(u % 8) * 0.5f : (float)u / 200; + } + for (size_t i = 0; i < bv.size(); ++i) { + const int u = (int)(st_mix32((uint32_t)i * 3u + 101u) % 2001) - 1000; + bv[i] = ties ? (float)(u % 5) * 0.125f : (float)u / 2000; + } + void* d_l = dalloc(lg.size() * 4); + void* d_b = dalloc(bv.size() * 4); + void* d_i = dalloc((size_t)(rows * ip * 4)); + void* d_w = dalloc((size_t)(rows * wp * 4)); + if (!d_l || !d_b || !d_i || !d_w) { ok("router_sigmoid_topk_f32 select", false, "allocation failed"); return; } + st_memcpy(d_l, lg.data(), lg.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_b, bv.data(), bv.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { T(d_l, RAD_F32, { rows, ne }), T(d_b, RAD_F32, { ne }), + T(d_i, RAD_I32, { rows, k }), T(d_w, RAD_F32, { rows, k }) }; + ts[0].stride[0] = lp; ts[1].stride[0] = bp; ts[2].stride[0] = ip; ts[3].stride[0] = wp; + std::vector ps = { PI("M", rows), PI("n_expert", ne), PI("top_k", k), + PI("norm", norm), PF("route_scale", 2.5), PS("dtype", "f32") }; + RadArgs a{}; + a.t = ts.data(); a.n_t = 4; a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + + const char* saved = std::getenv("RADIANCE_ROUTER_SELECT"); + const std::string keep = saved ? saved : ""; + auto run = [&](const char* form, std::vector* out, double* us) -> int { + if (form) setenv("RADIANCE_ROUTER_SELECT", form, 1); + else unsetenv("RADIANCE_ROUTER_SELECT"); + st_memset(d_i, 0xa5, (size_t)(rows * ip * 4)); + st_memset(d_w, 0xa5, (size_t)(rows * wp * 4)); + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : RAD_E_DEVICE; + out->resize((size_t)(rows * (ip + wp) * 4)); + st_memcpy(out->data(), d_i, (size_t)(rows * ip * 4), hipMemcpyDeviceToHost); + st_memcpy(out->data() + rows * ip * 4, d_w, (size_t)(rows * wp * 4), hipMemcpyDeviceToHost); + if (!check) *us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + return (int)RAD_OK; + }; + std::vector old, got; + double us_old = 0, us_new = 0; + const int orc = run("old", &old, &us_old); + const int nrc = orc == RAD_OK ? run(nullptr, &got, &us_new) : orc; + if (saved) setenv("RADIANCE_ROUTER_SELECT", keep.c_str(), 1); + else unsetenv("RADIANCE_ROUTER_SELECT"); + const bool same = nrc == RAD_OK && got == old; + if (check) { + size_t first = 0; + if (nrc == RAD_OK && !same) while (first < got.size() && got[first] == old[first]) ++first; + ok(fmt("router_sigmoid_topk select at M=%lld n_expert=%lld top_k=%lld norm=%d%s: " + "byte-identical to the serial scan", (long long)rows, (long long)ne, (long long)k, + norm, ties ? ", tied ranks" : "").c_str(), same, + nrc != RAD_OK ? fmt("rc=%d", nrc) : same ? "" : fmt("first byte %zu", first)); + return; + } + if (nrc != RAD_OK) { std::printf("--perfrouter: launch failed (rc %d)\n", nrc); return; } + std::printf("router_sigmoid_topk, M=%lld (n_expert %lld, top %lld, norm %d), %s, %d launches\n", + (long long)rows, (long long)ne, (long long)k, norm, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", iters); + std::printf(" %-28s %8.1f us\n", "serial scan (old)", us_old); + std::printf(" %-28s %8.1f us%s\n", "wave per row", us_new, + same ? " = old" : " DIFFERS from old"); +} + +/* ---- GLM's decode fusions of the MoE block (r4d_glm.hip), each against the separate launches it + * replaces, byte for byte over every output buffer including its tail. `iters` below zero compares + * only, as a case; otherwise both are timed, the chain as its launches back to back. */ +static void fuse_line(const char* what, double us_old, double us_new, bool same) { + std::printf(" %-34s %8.1f us\n", fmt("%s, separate", what).c_str(), us_old); + std::printf(" %-34s %8.1f us%s\n", fmt("%s, fused", what).c_str(), us_new, + same ? " = old" : " DIFFERS from old"); +} + +/* router_sigmoid_topk_scatter against router_sigmoid_topk, moe_scatter and the ungated shared + * arm's `fill`, at GLM's shape (288 experts, top 8). `mode` 0 random ranks, 1 tied ranks, 2 every + * other row with fewer finite ranks than top_k (NaN logits): the selection writes expert 0 for the + * empty slots and both forms sort them as written. */ +static void moefuse_router(const Plugin& pl, int64_t rows, int mode, int iters, + bool inverse = false) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + const char* what = "router_sigmoid_topk_scatter_f32"; + const RadKernelInfo* fr = find(pl, what); + const RadKernelInfo* sr = find(pl, "router_sigmoid_topk_f32"); + const RadKernelInfo* sc = find(pl, inverse ? "moe_scatter_inv_i32" : "moe_scatter_i32"); + const RadKernelInfo* fl = find(pl, "fill_bf16"); + if (!fr || !sr || !sc || !fl) { ok(what, false, "a row is absent"); return; } + const int64_t ne = 288, k = 8, slots = rows * k; + if (rows < 1 || slots > 1024) { + std::printf(" router at M=%lld: past the sort's one workgroup (M <= 128); the separate " + "launches serve\n", (long long)rows); + return; + } + std::vector lg((size_t)(rows * ne)), bv((size_t)ne); + for (size_t i = 0; i < lg.size(); ++i) { + const int u = (int)(st_mix32((uint32_t)i * 7u + 13u + (uint32_t)rows) % 2001) - 1000; + lg[i] = mode == 1 ? (float)(u % 8) * 0.5f : (float)u / 200; + } + for (size_t i = 0; i < bv.size(); ++i) { + const int u = (int)(st_mix32((uint32_t)i * 3u + 101u) % 2001) - 1000; + bv[i] = mode == 1 ? (float)(u % 5) * 0.125f : (float)u / 2000; + } + if (mode == 2) + for (int64_t r = 0; r < rows; r += 2) { + for (int64_t e = 0; e < ne; ++e) lg[(size_t)(r * ne + e)] = NAN; + for (int64_t j = 0; j < r % 5; ++j) + lg[(size_t)(r * ne + (int64_t)(st_mix32((uint32_t)(r * 31 + j)) % (uint32_t)ne))] = + 0.25f * (float)j; + } + /* ids, weights, sorted, offsets, counts, gate, inverse: each with a 64-byte tail */ + const int n_out = inverse ? 7 : 6; + const size_t sz[7] = { (size_t)slots * 4 + 64, (size_t)slots * 4 + 64, (size_t)slots * 4 + 64, + (size_t)(ne + 1) * 4 + 64, (size_t)ne * 4 + 64, (size_t)rows * 2 + 64, + (size_t)slots * 4 + 64 }; + void* d_l = dalloc(lg.size() * 4); + void* d_b = dalloc(bv.size() * 4); + void* o[2][7]; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 7; ++j) o[f][j] = dalloc(sz[j]); + if (!d_l || !d_b) { ok(what, false, "allocation failed"); return; } + for (int f = 0; f < 2; ++f) for (int j = 0; j < 7; ++j) + if (!o[f][j]) { ok(what, false, "allocation failed"); return; } + st_memcpy(d_l, lg.data(), lg.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_b, bv.data(), bv.size() * 4, hipMemcpyHostToDevice); + auto opds = [&](int f) { + return std::vector{ + T(d_l, RAD_F32, { rows, ne }), T(d_b, RAD_F32, { ne }), T(o[f][0], RAD_I32, { rows, k }), + T(o[f][1], RAD_F32, { rows, k }), T(o[f][2], RAD_I32, { slots }), + T(o[f][3], RAD_I32, { ne + 1 }), T(o[f][4], RAD_I32, { ne }), + T(o[f][5], RAD_BF16, { rows, 1 }), T(o[f][6], RAD_I32, { slots }) }; + }; + std::vector ch = opds(0), fu = opds(1); + if (!inverse) fu.pop_back(); + std::vector t_sel(ch.begin(), ch.begin() + 4); + std::vector t_sort = { ch[2], ch[4], ch[5], ch[6] }; + if (inverse) t_sort.push_back(ch[8]); + std::vector t_fill = { ch[7] }; + std::vector p_sel = { PI("M", rows), PI("n_expert", ne), PI("top_k", k), PI("norm", 1), + PF("route_scale", 2.5), PS("dtype", "f32") }; + std::vector p_sort = { PI("M", rows), PI("n_expert", ne), PI("top_k", k), + PI("expert_base", 0) }; + std::vector p_fill = { PI("M", rows), PI("n", 1), PS("dtype", "bf16"), PF("value", 1.0) }; + std::vector p_fu = { PI("M", rows), PI("n_expert", ne), PI("n_local", ne), + PI("top_k", k), PI("norm", 1), PF("route_scale", 2.5), + PS("dtype", "f32"), PI("expert_base", 0) }; + auto args = [](std::vector& t, std::vector& p) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); a.world_size = 1; + return a; + }; + RadArgs a_sel = args(t_sel, p_sel), a_sort = args(t_sort, p_sort), a_fill = args(t_fill, p_fill); + RadArgs a_fu = args(fu, p_fu); + auto chain = [&]() { + int rc = sr->launch(&a_sel, nullptr); + if (rc == RAD_OK) rc = sc->launch(&a_sort, nullptr); + if (rc == RAD_OK) rc = fl->launch(&a_fill, nullptr); + return rc; + }; + auto fused = [&]() { return fr->launch(&a_fu, nullptr); }; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 7; ++j) st_memset(o[f][j], 0xa5, sz[j]); + const int orc = chain(), nrc = fused(); + const bool ran = orc == RAD_OK && nrc == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + bool same = ran; + int first = -1; + for (int j = 0; j < n_out && ran; ++j) + if (fetch_bytes(o[0][j], sz[j]) != fetch_bytes(o[1][j], sz[j])) { same = false; if (first < 0) first = j; } + static const char* const kOut[7] = { "ids", "weights", "sorted", "offsets", "counts", "gate", + "inverse" }; + if (check) { + ok(fmt("router_sigmoid_topk_scatter at M=%lld%s%s: byte-identical to the selection, the " + "sort and the gate fill", (long long)rows, + mode == 1 ? ", tied ranks" : mode == 2 ? ", NaN rows" : "", + inverse ? ", with the inverse" : "").c_str(), same, + !ran ? fmt("rc %d / %d", orc, nrc) : same ? "" : fmt("%s differ", kOut[first])); + return; + } + if (!ran) { std::printf("--perfmoefuse: router launch failed (rc %d / %d)\n", orc, nrc); return; } + const double us_old = st_time_us([&](int) { chain(); }, iters, nullptr); + const double us_new = st_time_us([&](int) { fused(); }, iters, nullptr); + fuse_line(inverse ? "router + scatter_inv + gate" : "router + scatter + gate", us_old, us_new, + same); +} + +/* moe_scatter_inv and moe_gather_inv against moe_scatter and moe_gather at GLM's shape (288 experts, + * top 8, 4096 wide, f32 routing weights, the ungated shared arm folded in): the sort's three outputs, + * the inverse against the table built from `sorted`, and the gathered rows, byte for byte. Each row + * routes to 8 distinct experts; `slice` sorts only experts [72, 216), dropping the rest. Timed, the + * pairs and the gathers alone. Above 512 slots the old gather builds its table in two prepass + * launches, above 1024 the sort takes three. */ +static void moefuse_gather(const Plugin& pl, int64_t rows, bool slice, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + const char* what = "moe_gather_inv_bf16"; + const RadKernelInfo* si = find(pl, "moe_scatter_inv_i32"); + const RadKernelInfo* gi = find(pl, what); + const RadKernelInfo* so = find(pl, "moe_scatter_i32"); + const RadKernelInfo* go = find(pl, "moe_gather_bf16"); + if (!si || !gi || !so || !go) { ok(what, false, "a row is absent"); return; } + const int64_t ne = 288, k = 8, n = 4096, slots = rows * k; + const int64_t nl = slice ? 144 : ne, base = slice ? 72 : 0; + std::vector ids((size_t)slots); + for (int64_t r = 0; r < rows; ++r) { + std::vector pool((size_t)ne); + for (int64_t e = 0; e < ne; ++e) pool[(size_t)e] = (int32_t)e; + for (int64_t j = 0; j < k; ++j) { + const int64_t pick = j + (int64_t)(st_mix32((uint32_t)(r * 97 + j)) % (uint32_t)(ne - j)); + std::swap(pool[(size_t)j], pool[(size_t)pick]); + ids[(size_t)(r * k + j)] = pool[(size_t)j]; + } + } + std::vector ye((size_t)(slots * n)), sh((size_t)(rows * n)), sg((size_t)rows, h_to_bf16(1.0f)); + for (size_t i = 0; i < ye.size(); ++i) + ye[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i + 7u) % 2001) - 1000) / 1000); + for (size_t i = 0; i < sh.size(); ++i) + sh[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i + 99u) % 2001) - 1000) / 1000); + std::vector ew((size_t)slots); + for (size_t i = 0; i < ew.size(); ++i) ew[i] = (float)(st_mix32((uint32_t)i + 5u) % 1000) / 2000; + void* d_ids = dalloc(ids.size() * 4); + void* d_ye = dalloc(ye.size() * 2); + void* d_sh = dalloc(sh.size() * 2); + void* d_sg = dalloc(sg.size() * 2); + void* d_ew = dalloc(ew.size() * 4); + /* sorted, offsets, counts, gathered rows, then the inverse: each with a 64-byte tail */ + const size_t sz[5] = { (size_t)slots * 4 + 64, (size_t)(nl + 1) * 4 + 64, (size_t)nl * 4 + 64, + (size_t)(rows * n) * 2 + 64, (size_t)slots * 4 + 64 }; + void* o[2][5]; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 5; ++j) o[f][j] = dalloc(sz[j]); + if (!d_ids || !d_ye || !d_sh || !d_sg || !d_ew) { ok(what, false, "allocation failed"); return; } + for (int f = 0; f < 2; ++f) for (int j = 0; j < 5; ++j) + if (!o[f][j]) { ok(what, false, "allocation failed"); return; } + st_memcpy(d_ids, ids.data(), ids.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_ye, ye.data(), ye.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_sh, sh.data(), sh.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_sg, sg.data(), sg.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_ew, ew.data(), ew.size() * 4, hipMemcpyHostToDevice); + std::vector p_s = { PI("M", rows), PI("n_expert", nl), PI("top_k", k), + PI("expert_base", base) }; + std::vector p_g = { PI("M", rows), PI("n", n), PI("top_k", k), PS("dtype", "bf16"), + PS("act", "none") }; + std::vector s_old = { T(d_ids, RAD_I32, { rows, k }), T(o[0][0], RAD_I32, { slots }), + T(o[0][1], RAD_I32, { nl + 1 }), T(o[0][2], RAD_I32, { nl }) }; + std::vector s_new = { s_old[0], T(o[1][0], RAD_I32, { slots }), + T(o[1][1], RAD_I32, { nl + 1 }), T(o[1][2], RAD_I32, { nl }), + T(o[1][4], RAD_I32, { slots }) }; + auto gops = [&](void* table, void* y) { + return std::vector{ T(d_ye, RAD_BF16, { slots, n }), T(d_ew, RAD_F32, { rows, k }), + T(table, RAD_I32, { slots }), T(d_sh, RAD_BF16, { rows, n }), + T(d_sg, RAD_BF16, { rows, 1 }), T(y, RAD_BF16, { rows, n }) }; + }; + std::vector g_old = gops(o[0][0], o[0][3]), g_new = gops(o[1][4], o[1][3]); + auto args = [](std::vector& t, std::vector& p, const RadKernelInfo* r) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); a.world_size = 1; + const int64_t need = r->scratch ? r->scratch(&a) : 0; + if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; } + return a; + }; + RadArgs a_so = args(s_old, p_s, so), a_si = args(s_new, p_s, si); + RadArgs a_go = args(g_old, p_g, go), a_gi = args(g_new, p_g, gi); + auto pair_old = [&]() { int rc = so->launch(&a_so, nullptr); return rc == RAD_OK ? go->launch(&a_go, nullptr) : rc; }; + auto pair_new = [&]() { int rc = si->launch(&a_si, nullptr); return rc == RAD_OK ? gi->launch(&a_gi, nullptr) : rc; }; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 5; ++j) st_memset(o[f][j], 0xa5, sz[j]); + const int orc = pair_old(), nrc = pair_new(); + const bool ran = orc == RAD_OK && nrc == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + bool same = ran; + int first = -1; + for (int j = 0; j < 4 && ran; ++j) + if (fetch_bytes(o[0][j], sz[j]) != fetch_bytes(o[1][j], sz[j])) { same = false; if (first < 0) first = j; } + if (ran) { + /* the inverse is the table the old gather builds from `sorted` */ + std::vector srt((size_t)slots), inv((size_t)slots + 16), want((size_t)slots, -1); + st_memcpy(srt.data(), o[0][0], (size_t)slots * 4, hipMemcpyDeviceToHost); + st_memcpy(inv.data(), o[1][4], ((size_t)slots + 16) * 4, hipMemcpyDeviceToHost); + for (int64_t p = 0; p < slots; ++p) if (srt[(size_t)p] >= 0) want[(size_t)srt[(size_t)p]] = (int32_t)p; + bool tail = true; + for (int i = 0; i < 16; ++i) tail = tail && inv[(size_t)slots + (size_t)i] == (int32_t)0xa5a5a5a5; + if (!tail || !std::equal(want.begin(), want.end(), inv.begin())) { same = false; if (first < 0) first = 4; } + } + static const char* const kOut[5] = { "sorted", "offsets", "counts", "gathered rows", "inverse" }; + if (check) { + ok(fmt("moe_scatter_inv + moe_gather_inv at M=%lld%s: byte-identical to moe_scatter + " + "moe_gather", (long long)rows, slice ? ", a slice" : "").c_str(), same, + !ran ? fmt("rc %d / %d", orc, nrc) : same ? "" : fmt("%s differ", kOut[first])); + return; + } + if (!ran) { std::printf("--perfmoefuse: gather launch failed (rc %d / %d)\n", orc, nrc); return; } + const double us_po = st_time_us([&](int) { pair_old(); }, iters, nullptr); + const double us_pn = st_time_us([&](int) { pair_new(); }, iters, nullptr); + const double us_go = st_time_us([&](int) { go->launch(&a_go, nullptr); }, iters, nullptr); + const double us_gn = st_time_us([&](int) { gi->launch(&a_gi, nullptr); }, iters, nullptr); + fuse_line("scatter + gather", us_po, us_pn, same); + fuse_line("gather alone", us_go, us_gn, same); +} + +/* swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 at limit 10, over `rows` rows + * of width `n` (GLM at TP8: 256 for the routed and shared experts, 1536 for the dense layers). + * `mode` 0 values far past the clamp, 1 the clamp edges and all-zero groups, 2 NaN and infinite + * inputs. `with_y` also has the fused op write the bf16 product, compared with the chain's. */ +static void moefuse_swiglu(const Plugin& pl, int64_t rows, int64_t n, int mode, bool with_y, + int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + const char* what = "swiglu_clamped_quant_fp8"; + const RadKernelInfo* fr = find(pl, what); + const RadKernelInfo* sw = find(pl, "swiglu_clamped_bf16"); + const RadKernelInfo* qa = find(pl, "quant_act_fp8"); + if (!fr || !sw || !qa) { ok(what, false, "a row is absent"); return; } + const int64_t nkb = (n + 127) / 128; + std::vector gu((size_t)(rows * 2 * n)); + const uint16_t lim = h_to_bf16(10.0f), past = (uint16_t)(lim + 1); + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = 0; c < 2 * n; ++c) { + const size_t i = (size_t)(r * 2 * n + c); + const uint32_t h = st_mix32((uint32_t)i * 5u + 77u); + uint16_t v = h_to_bf16((float)((int)(h % 2001) - 1000) / 25); + const uint32_t pick = (h >> 16) % 16; + if (mode == 1) { + if (pick == 0) v = lim; + else if (pick == 1) v = past; + else if (pick == 2) v = (uint16_t)(lim | 0x8000u); + else if (pick == 3) v = (uint16_t)(past | 0x8000u); + else if (pick == 4) v = h_to_bf16(-200.0f); + if (r % 3 == 0 && c % n < 128) v = 0; + } else if (mode == 2) { + if (pick == 0) v = 0x7fc0; + else if (pick == 1) v = 0x7f80; + else if (pick == 2) v = 0xff80; + } + gu[i] = v; + } + /* q, scale, product: each with a 64-byte tail */ + const size_t sz[3] = { (size_t)(rows * n) + 64, (size_t)(rows * nkb) * 4 + 64, + (size_t)(rows * n) * 2 + 64 }; + void* d_g = dalloc(gu.size() * 2); + void* o[2][3]; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 3; ++j) o[f][j] = dalloc(sz[j]); + if (!d_g) { ok(what, false, "allocation failed"); return; } + for (int f = 0; f < 2; ++f) for (int j = 0; j < 3; ++j) + if (!o[f][j]) { ok(what, false, "allocation failed"); return; } + st_memcpy(d_g, gu.data(), gu.size() * 2, hipMemcpyHostToDevice); + std::vector t_sw = { T(d_g, RAD_BF16, { rows, 2 * n }), T(o[0][2], RAD_BF16, { rows, n }) }; + std::vector t_qa = { t_sw[1], T(o[0][0], RAD_F8E4M3, { rows, n }), + T(o[0][1], RAD_F32, { rows, nkb }) }; + std::vector t_fu = { t_sw[0], T(o[1][0], RAD_F8E4M3, { rows, n }), + T(o[1][1], RAD_F32, { rows, nkb }), T(o[1][2], RAD_BF16, { rows, n }) }; + if (!with_y) absent(t_fu[3]); + std::vector p_sw = { PI("M", rows), PI("n", n), PF("limit", 10.0), PS("dtype", "bf16") }; + std::vector p_qa = { PI("M", rows), PI("n", n), PI("group", 128), PS("dtype", "bf16") }; + std::vector p_fu = { PI("M", rows), PI("n", n), PF("limit", 10.0), PI("group", 128), + PS("dtype", "bf16") }; + auto args = [](std::vector& t, std::vector& p) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); a.world_size = 1; + return a; + }; + RadArgs a_sw = args(t_sw, p_sw), a_qa = args(t_qa, p_qa), a_fu = args(t_fu, p_fu); + auto chain = [&]() { + int rc = sw->launch(&a_sw, nullptr); + if (rc == RAD_OK) rc = qa->launch(&a_qa, nullptr); + return rc; + }; + auto fused = [&]() { return fr->launch(&a_fu, nullptr); }; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 3; ++j) st_memset(o[f][j], 0xa5, sz[j]); + const int orc = chain(), nrc = fused(); + const bool ran = orc == RAD_OK && nrc == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + bool same = ran; + int first = -1; + for (int j = 0; j < (with_y ? 3 : 2) && ran; ++j) + if (fetch_bytes(o[0][j], sz[j]) != fetch_bytes(o[1][j], sz[j])) { same = false; if (first < 0) first = j; } + if (ran && !with_y && fetch_bytes(o[1][2], sz[2]) != std::vector(sz[2], 0xa5)) { + same = false; if (first < 0) first = 2; + } + static const char* const kOut[3] = { "codes", "scales", "bf16 product" }; + if (check) { + ok(fmt("swiglu_clamped_quant_fp8 at M=%lld n=%lld%s%s: byte-identical to swiglu_clamped " + "and quant_act_fp8", (long long)rows, (long long)n, with_y ? ", with bf16" : "", + mode == 1 ? ", clamp edges" : mode == 2 ? ", NaN and inf" : "").c_str(), same, + !ran ? fmt("rc %d / %d", orc, nrc) : same ? "" : fmt("%s differ", kOut[first])); + return; + } + if (!ran) { std::printf("--perfmoefuse: swiglu launch failed (rc %d / %d)\n", orc, nrc); return; } + const double us_old = st_time_us([&](int) { chain(); }, iters, nullptr); + const double us_new = st_time_us([&](int) { fused(); }, iters, nullptr); + fuse_line(fmt("swiglu + quant %lldx%lld", (long long)rows, (long long)n).c_str(), us_old, us_new, + same); +} + +/* --perfmoefuse: every decode fusion of GLM's MoE block at one M, separate against fused. */ +static void moefuse_perf(const Plugin& pl, int64_t rows, int iters) { + std::printf("GLM MoE decode fusions, M=%lld (288 experts, top 8, TP8 widths), %s, %d launches\n", + (long long)rows, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", iters); + moefuse_router(pl, rows, 0, iters); + /* The routed arm's rows (M times top_k) and the shared arm's, both 256 wide at TP8. */ + moefuse_swiglu(pl, rows * 8, 256, 0, false, iters); + moefuse_swiglu(pl, rows, 256, 0, false, iters); + moefuse_router(pl, rows, 0, iters, true); + moefuse_gather(pl, rows, false, iters); +} + +/* gemm_nt_f32 at every tile form (RADIANCE_F32_GEMM_TILE), each compared byte for byte with the + * one-wave-per-output legacy kernel. Rows are pitched and the output keeps a filled pitch, so an + * overrun or a missed tail shows as a byte difference. Timed, every form also prints its time, + * its GB/s on weight + input + output and its TFLOP/s; weights rotate over copies past the + * last-level cache, as in bf16_perf. */ +static void f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int iters, bool timed) { + const RadKernelInfo* r = find(pl, "gemm_nt_f32_bf16"); + if (!r) { ok("gemm_nt_f32_bf16 forms", false, "row absent"); return; } + const int64_t xp = K + 5, yp = N + 3; + const size_t wbytes = (size_t)N * (size_t)K * 4, ybytes = (size_t)M * (size_t)yp * 4; + int copies = 1; + if (timed) { + copies = (int)(((size_t)256 << 20) / wbytes) + 1; + if (copies > 64) copies = 64; + } + void* d_x = dalloc((size_t)M * (size_t)xp * 2); + void* d_w = dalloc(wbytes * (size_t)copies); + void* d_y = dalloc(ybytes); + if (!d_x || !d_w || !d_y) { ok("gemm_nt_f32_bf16 forms", false, "allocation failed"); return; } + { + std::vector x((size_t)M * (size_t)xp); + for (size_t i = 0; i < x.size(); ++i) + x[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) / 1000); + st_memcpy(d_x, x.data(), x.size() * 2, hipMemcpyHostToDevice); + std::vector w((size_t)N * (size_t)K); + for (size_t i = 0; i < w.size(); ++i) + w[i] = (float)((int)(st_mix32((uint32_t)i + 0x51ed27u) % 2001) - 1000) / 8000; + for (int c = 0; c < copies; ++c) + st_memcpy((uint8_t*)d_w + (size_t)c * wbytes, w.data(), wbytes, hipMemcpyHostToDevice); + } + std::vector ts = { + T(d_x, RAD_BF16, { M, K }), T(d_w, RAD_F32, { N, K }), T(d_y, RAD_F32, { M, N }), + }; + ts[0].stride[0] = xp; ts[2].stride[0] = yp; + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PS("dtype", "bf16") }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = 3; a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + + const char* saved = std::getenv("RADIANCE_F32_GEMM_TILE"); + const std::string keep = saved ? saved : ""; + auto run = [&](const char* form, std::vector* out) -> int { + if (form) setenv("RADIANCE_F32_GEMM_TILE", form, 1); + else unsetenv("RADIANCE_F32_GEMM_TILE"); + std::vector fill(ybytes, 0xa5); + st_memcpy(d_y, fill.data(), ybytes, hipMemcpyHostToDevice); + ts[1].data = d_w; + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : RAD_E_DEVICE; + out->resize(ybytes); + st_memcpy(out->data(), d_y, ybytes, hipMemcpyDeviceToHost); + return (int)RAD_OK; + }; + static const char* kForms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", "4x4", "8x4", + "16x2", "16x4", nullptr }; + std::vector legacy, got; + const int lrc = run("legacy", &legacy); + ok(fmt("gemm_nt_f32 legacy form at M=%lld N=%lld K=%lld", (long long)M, (long long)N, + (long long)K).c_str(), lrc == RAD_OK); + if (lrc == RAD_OK) { + for (const char* const* f = kForms;; ++f) { + const char* form = *f; + const int rc = run(form, &got); + const bool same = rc == RAD_OK && got == legacy; + size_t first = 0; + if (rc == RAD_OK && !same) + while (first < got.size() && got[first] == legacy[first]) ++first; + ok(fmt("gemm_nt_f32 form %s at M=%lld N=%lld K=%lld: byte-identical to legacy", + form ? form : "default", (long long)M, (long long)N, (long long)K).c_str(), + same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); + if (!form) break; + } + } + if (timed && lrc == RAD_OK) { + const double bytes = (double)wbytes + (double)M * K * 2 + (double)M * N * 4; + const double flop = 2.0 * (double)M * (double)N * (double)K; + std::printf("\ngemm_nt_f32 N=%lld K=%lld M=%lld %.2f MiB weight, %d copies, %d iters\n", + (long long)N, (long long)K, (long long)M, (double)wbytes / (1 << 20), copies, + iters); + static const char* kTimed[] = { "legacy", "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", "4x4", + "8x4", "16x2", "16x4", nullptr }; + for (const char* const* f = kTimed;; ++f) { + const char* form = *f; + if (form) setenv("RADIANCE_F32_GEMM_TILE", form, 1); + else unsetenv("RADIANCE_F32_GEMM_TILE"); + const double us = st_time_us([&](int i) { + ts[1].data = (uint8_t*)d_w + (size_t)(i % copies) * wbytes; + r->launch(&a, nullptr); + }, iters, nullptr); + std::printf(" %-8s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", form ? form : "default", + us, bytes / (us * 1e3), flop / (us * 1e6)); + if (!form) break; + } + ts[1].data = d_w; + } + if (saved) setenv("RADIANCE_F32_GEMM_TILE", keep.c_str(), 1); + else unsetenv("RADIANCE_F32_GEMM_TILE"); +} + +/* gemm_fp8a8_f32scale's dense forms (RADIANCE_FP8F32_FORM: decode at several R x S, rows) each + * compared byte for byte with the legacy 16x64 tile; the output keeps a filled pitch, so an + * overrun or a missed row shows. Timed, every form also prints its time and GB/s on the weight and its scale plane, the + * weight rotating over copies past the last-level cache. */ +static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int iters, bool timed) { + const RadKernelInfo* r = find(pl, "gemm_fp8a8_f32scale"); + if (!r) { ok("gemm_fp8a8_f32scale forms", false, "row absent"); return; } + const int64_t sk = K / 128, yp = N + 8; + const size_t wb = (size_t)(N * K), sb = (size_t)((N / 128) * sk * 4), yb = (size_t)(M * yp * 2); + int copies = 1; + if (timed) { + copies = (int)(((size_t)256 << 20) / wb) + 1; + if (copies > 64) copies = 64; + } + void* d_a = dalloc((size_t)(M * K)); + void* d_as = dalloc((size_t)(M * sk * 4)); + void* d_w = dalloc(wb * (size_t)copies); + void* d_s = dalloc(sb); + void* d_y = dalloc(yb); + if (!d_a || !d_as || !d_w || !d_s || !d_y) { ok("gemm_fp8a8_f32scale forms", false, "allocation failed"); return; } + { + std::vector a((size_t)(M * K)), w(wb); + for (size_t i = 0; i < a.size(); ++i) + a[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i * 7u + 3u) % 2001) - 1000) / 250); + for (size_t i = 0; i < w.size(); ++i) + w[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i + 0x9e37u) % 2001) - 1000) / 500); + st_memcpy(d_a, a.data(), a.size(), hipMemcpyHostToDevice); + for (int c = 0; c < copies; ++c) + st_memcpy((uint8_t*)d_w + (size_t)c * wb, w.data(), wb, hipMemcpyHostToDevice); + std::vector as((size_t)(M * sk)), s(sb / 4); + for (size_t i = 0; i < as.size(); ++i) as[i] = 0.001f + (float)(st_mix32((uint32_t)i + 5u) % 97) * 1e-4f; + for (size_t i = 0; i < s.size(); ++i) s[i] = 0.002f + (float)(st_mix32((uint32_t)i + 11u) % 89) * 1e-4f; + st_memcpy(d_as, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, s.data(), sb, hipMemcpyHostToDevice); + } + std::vector ts = { + T(d_a, RAD_F8E4M3, { M, K }), T(d_as, RAD_F32, { M, sk }), T(d_w, RAD_F8E4M3, { N, K }), + T(d_s, RAD_F32, { N / 128, sk }), T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), + T(nullptr, RAD_U8, { 1 }), + }; + ts[4].stride[0] = yp; + absent(ts[5]); absent(ts[6]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "fp8a8f32") }; + 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; + const char* saved = std::getenv("RADIANCE_FP8F32_FORM"); + const std::string keep = saved ? saved : ""; + auto set = [](const char* form) { + if (form) setenv("RADIANCE_FP8F32_FORM", form, 1); + else unsetenv("RADIANCE_FP8F32_FORM"); + }; + auto run = [&](const char* form, std::vector* out) -> int { + set(form); + std::vector fill(yb, 0xa5); + st_memcpy(d_y, fill.data(), yb, hipMemcpyHostToDevice); + ts[2].data = d_w; + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK) return rc; + if (st_stream_sync(nullptr) != hipSuccess) return (int)RAD_E_DEVICE; + out->resize(yb); + st_memcpy(out->data(), d_y, yb, hipMemcpyDeviceToHost); + return (int)RAD_OK; + }; + std::vector legacy, got; + const int lrc = run("legacy", &legacy); + ok(fmt("gemm_fp8a8_f32scale legacy form at M=%lld N=%lld K=%lld", (long long)M, (long long)N, + (long long)K).c_str(), lrc == RAD_OK); + static const char* kForms[] = { "decode", "decode1x16", "decode2x16", "decode3x8", + "decode1x8x2", "decode1x8x4", "decode2x8x2", "decode3x8x2", + "decode2x4x4", "rows1", "rows4", nullptr }; + if (lrc == RAD_OK) { + for (const char* const* f = kForms;; ++f) { + const int rc = run(*f, &got); + const bool same = rc == RAD_OK && got == legacy; + size_t first = 0; + if (rc == RAD_OK && !same) while (first < got.size() && got[first] == legacy[first]) ++first; + ok(fmt("gemm_fp8a8_f32scale form %s at M=%lld N=%lld K=%lld: byte-identical to legacy", + *f ? *f : "default", (long long)M, (long long)N, (long long)K).c_str(), + same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); + if (!*f) break; + } + } + if (timed && lrc == RAD_OK) { + const double bytes = (double)(wb + sb), flop = 2.0 * (double)M * (double)N * (double)K; + std::printf("\ngemm_fp8a8_f32scale N=%lld K=%lld M=%lld %.2f MiB weight + scales, %d copies, " + "%d iters\n", (long long)N, (long long)K, (long long)M, bytes / (1 << 20), copies, iters); + static const char* kTimed[] = { "legacy", "decode1x8", "decode1x16", "decode3x8", + "decode1x8x2", "decode1x16x2", "decode1x4x4", + "decode1x8x4", "decode2x8x2", "decode2x4x2", + "decode2x4x4", "decode3x8x2", "decode3x4x2", "rows1", + "rows2", nullptr }; + for (const char* const* f = kTimed;; ++f) { + set(*f); + const double us = st_time_us([&](int i) { + ts[2].data = (uint8_t*)d_w + (size_t)(i % copies) * wb; + r->launch(&a, nullptr); + }, iters, nullptr); + std::printf(" %-11s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", *f ? *f : "default", us, + bytes / (us * 1e3), flop / (us * 1e6)); + if (!*f) break; + } + ts[2].data = d_w; + } + if (saved) setenv("RADIANCE_FP8F32_FORM", keep.c_str(), 1); + else unsetenv("RADIANCE_FP8F32_FORM"); +} + +/* The block-quantised trunk GEMMs GLM's checkpoints resolve to, at one shape: E4M3 with F32 + * 128x128 block scales (gemm_fp8a8_f32scale, the MLA and dense-MLP projections) and OCP-MXFP4 + * (the shared experts' rows: skinny, decode split and tiled). GB/s is on the weight and its scale + * plane; weights rotate over copies past the last-level cache. Operands hold constants. */ +static void q_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters) { + if (N % 16 || K % 64 || M < 1) { + std::printf("--perfq: N a multiple of 16, K of 64, M >= 1\n"); + return; + } + const int64_t sk = (K + 127) / 128; + void* d_a = dalloc((size_t)(M * K)); + void* d_as = dalloc((size_t)(M * sk * 4)); + void* d_y = dalloc((size_t)(M * N * 2)); + if (!d_a || !d_as || !d_y) { std::printf("--perfq: hipMalloc failed\n"); return; } + { + std::vector a((size_t)(M * K), 0x38); + st_memcpy(d_a, a.data(), a.size(), hipMemcpyHostToDevice); + std::vector as((size_t)(M * sk), 1.0f / 448); + st_memcpy(d_as, as.data(), as.size() * 4, hipMemcpyHostToDevice); + } + auto copies_for = [](size_t bytes) { + int c = (int)(((size_t)256 << 20) / bytes) + 1; + return c > 64 ? 64 : c; + }; + std::printf("\nquantised trunk GEMMs N=%lld K=%lld M=%lld %d iters\n", (long long)N, + (long long)K, (long long)M, iters); + if (N % 128 == 0 && K % 128 == 0) fp8f32_forms(pl, M, N, K, iters, true); + { + const size_t wb = (size_t)(N * K / 2), sb = (size_t)((K / 32) * N); + const int copies = copies_for(wb); + void* d_w = dalloc(wb * (size_t)copies); + void* d_s = dalloc(sb); + void* d_r = dalloc((size_t)N); + if (!d_w || !d_s || !d_r) { std::printf("--perfq: hipMalloc failed\n"); return; } + std::vector w(wb, 0x22), s(sb, 127), r((size_t)N, 127); + for (int c = 0; c < copies; ++c) + st_memcpy((uint8_t*)d_w + (size_t)c * wb, w.data(), wb, hipMemcpyHostToDevice); + st_memcpy(d_s, s.data(), sb, hipMemcpyHostToDevice); + st_memcpy(d_r, r.data(), (size_t)N, hipMemcpyHostToDevice); + std::vector ts = { + T(d_a, RAD_F8E4M3, { M, K }), T(d_as, RAD_F32, { M, sk }), T(d_w, RAD_U8, { (int64_t)wb }), + T(d_s, RAD_U8, { (int64_t)sb }), T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), + T(d_r, RAD_U8, { N }), + }; + absent(ts[5]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "mxfp4a8") }; + std::printf(" OCP-MXFP4: %.2f MiB, %d copies\n", (double)(wb + sb) / (1 << 20), copies); + for (const char* row : { "gemm_mxfp4a8_nt_m64", "gemm_mxfp4a8_decode", "gemm_mxfp4a8_tiled" }) + perf_row(pl, row, ts, ps, d_w, wb, copies, (double)(wb + sb), iters); + } +} + /* The bf16 skinny GEMM at one shape, every variant, side by side, with the working set rotated * past the last-level cache (rad-tune's absolute numbers vary too much between runs to choose a * default from). @@ -14360,7 +17900,7 @@ static void sample_argmax_case(const Plugin& pl) { * a page id of -1 inside the scored range is never selected, whatever its score; * two runs give byte-identical tables (atomic placement would not). */ -static void qsa_select_case(const Plugin& pl) { +static void qsa_select_case(const Plugin& pl, int signed_scores = 0) { const char* what = "qsa_select vs a host sort, with ties, a tail and a dead page"; const RadKernelInfo* r = find(pl, "qsa_select_i32"); if (!r) { ok(what, false, "row absent"); return; } @@ -14379,6 +17919,7 @@ static void qsa_select_case(const Plugin& pl) { if (b < live) { /* A coarse grid: 40 values over hundreds of blocks puts many on the threshold. */ sc[i] = (float)((b * 17 + m * 7) % 40) * 0.25f; + if (signed_scores) sc[i] -= signed_scores == 1 ? 5.0f : 20.0f; bt[i] = (int32_t)((b * 31 + m * 11) % pages); /* A dead page with a winning score, inside the scored range. */ if (b == live / 3) { sc[i] = 1e6f; bt[i] = -1; } @@ -14447,6 +17988,7 @@ static void qsa_select_case(const Plugin& pl) { }; std::vector ps = { PI("M", M), PI("blocks", nb), PI("topk", topk), PI("ratio", ratio), PI("seqs", M) }; + if (signed_scores) ps.push_back(PI("signed", 1)); RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); @@ -14667,8 +18209,9 @@ static void qsa_select_wide_case(const Plugin& pl) { static const char* const kDist[] = { "continuous", "coarse, heavy ties", "one first-digit bin, in LDS", "one first-digit bin, past LDS", - "fine ties at the threshold" }; - for (int dist = 0; dist < 5; ++dist) { + "fine ties at the threshold", "signed, heavy ties", + "negative, heavy ties" }; + for (int dist = 0; dist < 7; ++dist) { std::vector sc((size_t)(M * nb)); for (auto& v : sc) { const uint64_t u = rnd(); @@ -14681,6 +18224,8 @@ static void qsa_select_wide_case(const Plugin& pl) { case 2: v = (u % 8 == 0) ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break; case 3: v = 1.0f + (float)(u % 60000) * 1e-6f; break; + case 5: v = (float)(u % 23)*0.25f-3.0f; break; + case 6: v = -(float)(u % 23)*0.25f-1.0f; break; /* ~5000 distinct scores, a few times each: the sampled list is short and the * threshold is a tie. */ default: v = (float)(u % 4999) * 0.01f; break; @@ -14707,6 +18252,7 @@ static void qsa_select_wide_case(const Plugin& pl) { T(d_se, RAD_I32, { M, topk + 1 }), T(d_ns, RAD_I32, { M }), T(d_su, RAD_I32, { M }) }; std::vector ps = { PI("M", M), PI("blocks", nb), PI("topk", topk), PI("ratio", ratio), PI("seqs", S) }; + if (dist >= 5) ps.push_back(PI("signed", 1)); RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); @@ -16578,23 +20124,6 @@ static void ar_pattern_worker(ArPattern* t) { st_free(out); } -/* An environment variable set (or, with a null value, cleared) for one scope and restored after - * it: the eight-rank two-shot reads its settings at every init. */ -struct ScopedEnv { - const char* name; - bool had; - std::string kept; - ScopedEnv(const char* n, const char* v) : name(n) { - const char* was = std::getenv(n); - had = was != nullptr; - if (was) kept = was; - if (v) setenv(n, v, 1); else unsetenv(n); - } - ~ScopedEnv() { if (had) setenv(name, kept.c_str(), 1); else unsetenv(name); } - ScopedEnv(const ScopedEnv&) = delete; - ScopedEnv& operator=(const ScopedEnv&) = delete; -}; - struct ArPatternRun { const char* dtype; std::vector sizes; int oop; std::vector pieces = {}; /* per size, as ArPattern::pieces */ @@ -18513,6 +22042,7 @@ static void device_phase(const Plugin& pl) { /* --- the paged cache's write side --- */ kv_store_case(pl, "kv_store_bf16", "bf16"); + kv_store_case(pl, "kv_store_bf16", "bf16", true); kv_store_case(pl, "kv_store_fp8", "fp8_e4m3"); kv_store_v4_case(pl); kv_store_v4_case(pl, true); @@ -20073,6 +23603,8 @@ static void device_phase(const Plugin& pl) { if (sel("qsa_select_i32")) { if (!g_case) std::printf("\nthe QSA selection, against a host sort\n"); qsa_select_case(pl); + qsa_select_case(pl, 1); + qsa_select_case(pl, 2); qsa_select_prefill_case(pl); qsa_select_wide_case(pl); qsa_select_split_one(pl, "qsa_select split across chunks vs the same launch unsplit", @@ -20243,6 +23775,61 @@ static void device_phase(const Plugin& pl) { } } + if (sel("glm_index_layout")) glm_index_layout_check(pl); + if (sel("fp8_f32scale")) { + for (int64_t m : { 1, 17, 65 }) { + fp8_f32scale_check(pl, false, m); + fp8_f32scale_check(pl, true, m); + fp8_f32scale_check(pl, true, m, true); + } + fp8_f32scale_check(pl, false, 130); + for (int64_t n : { 1536, 512, 2048, 4096, 3072 }) + for (int64_t m : { 1, 6, 48, 128, 2048 }) { + const int64_t k = n == 2048 ? 1536 : n == 4096 ? 2048 : 4096; + fp8f32_forms(pl, m, n, k, 0, false); + } + for (int64_t m : { 1, 6, 48, 128, 2048 }) fp8f32_forms(pl, m, 4096, 1536, 0, false); + fp8f32_forms(pl, 37, 256, 1536, 0, false); + fp8f32_forms(pl, 129, 128, 384, 0, false); + fp8_f32scale_check(pl, true, 4, false, true); + fp8_f32scale_check(pl, true, 4, true, true); + fp8_f32scale_check(pl, true, 1, false, true, 288); + fp8_f32scale_check(pl, true, 4, true, true, 288); + fp8_f32scale_check(pl, true, 65, false); + fp8_f32scale_check(pl, true, 65, true); + // The rule takes the expert-major form; pinned, the row tiles stay covered, and every + // stage and column-tile count meets several column tiles, a K of one stage and of + // several, and runs past sixteen rows. + const char* const pins[3] = { "RADIANCE_FP8F32_DECODE_EXPERTS", + "RADIANCE_FP8F32_EXPERTS_STAGE_K", + "RADIANCE_FP8F32_EXPERTS_COLTILES" }; + std::string kept[3]; + bool given[3]; + for (int i = 0; i < 3; ++i) { + const char* v = std::getenv(pins[i]); + given[i] = v; + if (v) kept[i] = v; + } + setenv(pins[0], "0", 1); + fp8_f32scale_check(pl, true, 17, true, true, 6, 512, 512); + fp8_f32scale_check(pl, true, 65, false); + setenv(pins[0], "1", 1); + for (const char* stage : { "128", "256" }) + for (const char* tiles : { "1", "4" }) { + setenv(pins[1], stage, 1); + setenv(pins[2], tiles, 1); + fp8_f32scale_check(pl, true, 17, true, true, 6, 512, 512); + fp8_f32scale_check(pl, true, 4, false, true, 288, 512, 384); + fp8_f32scale_check(pl, true, 65, false); + } + for (int i = 0; i < 3; ++i) { + if (given[i]) + setenv(pins[i], kept[i].c_str(), 1); + else + unsetenv(pins[i]); + } + } + if (sel("moe_gemm_w4a8_mod4")) { if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM over four classes, against its " "two-class form and a host decode\n"); @@ -20289,6 +23876,344 @@ static void device_phase(const Plugin& pl) { moe_down_dec_case(pl, kMoeDnShapes[1], "fp8a8", { 40, 96 }); } + for (const char* nm : { "mhc_pre_bf16", "mhc_post_bf16", "mhc_contract_bf16" }) + if (sel(nm)) { + mhc_check(pl, nm, 1, 31, 2); + mhc_check(pl, nm, 7, 4096, 4); + if (!std::strcmp(nm, "mhc_pre_bf16")) { + mhc_check(pl, nm, 1, 4096, 4); + mhc_check(pl, nm, 4, 4096, 4); + mhc_check(pl, nm, 33, 4096, 4); + mhc_check(pl, nm, 65, 4096, 4); + } + mhc_check(pl, nm, 33, 129, 8); + } + if (sel("mhc_pre_bf16") || sel("mhc_post_bf16")) { + /* Every finish and partial form and the vector mhc_post against the old dispatch, at the + * decode, verify and prefill row counts and on 16-byte rows, the vector paths' case. */ + for (int64_t rows : { 1, 6, 48, 128, 2048 }) mhcpre_perf(pl, rows, -1); + } + if (sel("mhc_pre_partial_bf16") || sel("mhc_pre_finish_bf16")) { + for (int world : { 2, 4, 8 }) + for (int64_t rows : { 1, 4, 31, 32, 33, 65, 130 }) + mhc_split_check(pl, rows, world, nullptr, nullptr); + for (const char* env : { "RADIANCE_MHC_PREFILL_COEFF4", "RADIANCE_MHC_PREFILL_ROWS4", + "RADIANCE_MHC_PREFILL_WARP" }) + for (int64_t rows : { 33, 130 }) mhc_split_check(pl, rows, 8, env, "0"); + } + if (sel("swiglu_clamped_bf16")) { + for (int64_t rows : { 1, 7, 33 }) + for (int64_t n : { 31, 259, 4096 }) mhc_check(pl, "swiglu_clamped_bf16", rows, n, 0); + } + if (sel("router_sigmoid_topk_f32")) { + for (int64_t rows : { 1, 7, 33 }) + for (int64_t ne : { 32, 288, 512 }) + for (int norm : { 0, 1 }) mhc_check(pl, "router_sigmoid_topk_f32", rows, ne, norm); + for (int64_t rows : { 1, 6, 20, 48, 256 }) + for (bool ties : { false, true }) router_select(pl, rows, 288, 8, 1, ties, -1); + for (int64_t ne : { 8, 32, 300, 512 }) + for (int64_t k : { (int64_t)1, (int64_t)8, ne < 32 ? ne : 32 }) + router_select(pl, 20, ne, k, 0, true, -1); + } + if (sel("swiglu_clamped_quant_fp8")) { + for (int64_t rows : { 1, 8, 48, 384 }) + for (int mode : { 0, 1, 2 }) moefuse_swiglu(pl, rows, 256, mode, false, -1); + for (int64_t n : { 4, 132, 1536 }) moefuse_swiglu(pl, 7, n, 1, true, -1); + moefuse_swiglu(pl, 6, 256, 2, true, -1); + } + if (sel("router_sigmoid_topk_scatter_f32")) { + for (int64_t rows : { 1, 6, 8, 24, 33, 48, 128 }) + for (int mode : { 0, 1, 2 }) moefuse_router(pl, rows, mode, -1); + for (int64_t rows : { 1, 48, 128 }) moefuse_router(pl, rows, 2, -1, true); + } + if (sel("moe_scatter_inv_i32") || sel("moe_gather_inv_bf16")) { + /* 512 slots is the old gather's self-scan bound, 1024 the sort's one workgroup. */ + for (int64_t rows : { 1, 6, 48, 64, 65, 128, 129, 256 }) + for (bool slice : { false, true }) moefuse_gather(pl, rows, slice, -1); + } + if (sel("dsa_pool_fp8")) { + for (int64_t rows : { 1, 7, 33, 2048 }) + for (int pattern : { 0, 1, 2, 3 }) mhc_check(pl, "dsa_pool_fp8", rows, 128, pattern); + for (int64_t rows : { 1, 7, 33, 2048 }) + for (int pattern : { 1, 2 }) mhc_check(pl, "dsa_pool_fp8", rows, 128, pattern, true); + } + if (sel("dsa_query_fp8")) { + for (int64_t rows : { 1, 32, 64, 128, 1056 }) + for (int pattern : { 0, 1, 2, 3 }) mhc_check(pl, "dsa_query_fp8", rows, 128, pattern); + } + if (sel("gemm_nt_f32_bf16")) { + for (int64_t rows : { 1, 2, 4, 33 }) + for (int64_t cols : { 32, 288 }) mhc_check(pl, "gemm_nt_f32_bf16", rows, cols, 4096); + mhc_check(pl, "gemm_nt_f32_bf16", 7, 31, 129); + for (int64_t rows : { 64, 130 }) + for (int64_t cols : { 36, 288 }) mhc_check(pl, "gemm_nt_f32_bf16", rows, cols, 4096); + for (int64_t rows : { 1, 2, 3, 8, 33, 64, 130 }) + for (int64_t cols : { 4, 32, 36, 288 }) f32_forms(pl, rows, cols, 4096, 0, false); + f32_forms(pl, 7, 31, 129, 0, false); + f32_forms(pl, 70, 13, 130, 0, false); + } + if (sel("dsa_score_fp8")) { + dsa_score_check(pl, 1, 17); + dsa_score_check(pl, 7, 257); + dsa_score_check(pl, 33, 17); + dsa_score_check(pl, 1, 4096); + dsa_score_check(pl, 4, 32768); + dsa_score_check(pl, 1, 17, true); + dsa_score_check(pl, 4, 257, true); + dsa_score_check(pl, 4, 32768, true); + } + if (sel("mla_attn_bf16")) { + mla_check(pl, 1, 1, 3); + mla_check(pl, 7, 16, 17); + mla_check(pl, 33, 16, 17); + mla_check(pl, 1, 16, 513); + mla_check(pl, 2, 16, 513); + mla_check(pl, 4, 16, 513); + mla_check(pl, 1, 64, 17); + mla_check(pl, 7, 8, 17); + mla_check(pl, 4, 8, 513); + mla_check(pl, 33, 8, 17); + for (int requests : { 1, 2, 4 }) + for (int64_t heads : { 8, 16 }) + mla_check(pl, requests, heads, 513, "mla_attn_bf16", MlaFill::full); + mla_check(pl, 7, 8, 65, "mla_attn_bf16", MlaFill::topk, nullptr, 0, 16); + } + if (sel("mla_project_bf16")) { + for (const char* mode : { "absorb", "expand" }) { + for (int64_t rows : { 1, 2, 4, 33 }) + for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode); + mla_project_check(pl, 1, 1, mode); + mla_project_check(pl, 1, 64, mode); + for (int64_t rows : { 1, 4, 33 }) + for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode, true); + } + /* Every row form against the one-row kernels, byte for byte, with tails at 3, 33 and 130. */ + for (int64_t rows : { 1, 3, 6, 33, 130 }) project_forms(pl, rows, -1); + } + if (sel("mla_attn_matrix_bf16")) { + mla_check(pl, 7, 16, 17, "mla_attn_matrix_bf16"); + mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16"); + mla_check(pl, 1, 16, 513, "mla_attn_matrix_bf16"); + mla_check(pl, 2, 16, 513, "mla_attn_matrix_bf16"); + mla_check(pl, 4, 16, 513, "mla_attn_matrix_bf16"); + mla_check(pl, 1, 64, 17, "mla_attn_matrix_bf16"); + mla_check(pl, 4, 4, 17, "mla_attn_matrix_bf16"); + mla_check(pl, 4, 12, 17, "mla_attn_matrix_bf16"); + for (int requests : { 1, 2, 4 }) + for (int64_t heads : { 8, 16 }) + mla_check(pl, requests, heads, 513, "mla_attn_matrix_bf16", MlaFill::full, + heads == 8 ? "mla_attn_bf16" : nullptr); + /* Eight heads pair two requests a tile: odd counts leave a half-empty last tile, ragged and + * full tables never share a key between the pair, prefill tables mostly do. */ + for (int requests : { 1, 2, 4, 7, 33 }) + for (int64_t blocks : { 17, 513 }) + mla_check(pl, requests, 8, blocks, "mla_attn_matrix_bf16", MlaFill::ragged, + "mla_attn_bf16"); + mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::full, "mla_attn_bf16"); + mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::full, "mla_attn_bf16"); + mla_check(pl, 25, 40, 17, "mla_attn_matrix_bf16", MlaFill::ragged, "mla_attn_bf16"); + for (int requests : { 2, 7, 33 }) + for (int64_t blocks : { 17, 513 }) + mla_check(pl, requests, 8, blocks, "mla_attn_matrix_bf16", MlaFill::prefill, + "mla_attn_bf16"); + for (int64_t heads : { 8, 16 }) + mla_check(pl, 128, heads, 513, "mla_attn_matrix_bf16", MlaFill::prefill, + "mla_attn_bf16"); + /* Past the DSA budget every row selects its own blocks: neighbours share most of them, at + * table positions a single exchange shifts. */ + for (int64_t swaps : { 0, 4, 16, 64 }) + mla_check(pl, 7, 8, 65, "mla_attn_matrix_bf16", MlaFill::topk, "mla_attn_bf16", 0, + swaps); + mla_check(pl, 33, 8, 513, "mla_attn_matrix_bf16", MlaFill::topk, "mla_attn_bf16", 0, 16); + mla_check(pl, 4, 16, 65, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 4); + { /* The positional pairing, kept for comparison; tables wider than the union's lists + * (kUnionBlocks, 520) take it too. */ + ScopedEnv positional("RADIANCE_MLA_PAIR", "pos"); + mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr); + mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr); + mla_check(pl, 7, 8, 65, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 16); + } + mla_check(pl, 4, 8, 600, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 16); + /* The element-wise key load, the fallback for a cache the vectors cannot read. */ + mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr, 1); + mla_check(pl, 4, 16, 513, "mla_attn_matrix_bf16", MlaFill::full, nullptr, 1); + mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr, 1); + mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr, 1); + } + if (sel("kda_update_k128_v128_bf16")) { + for (const char* mode : { "prefill", "verify" }) + for (int accepted : { 1, 2, 3 }) { + kda_check(pl, mode, false, accepted); + kda_check(pl, mode, true, accepted); + kda_check(pl, mode, false, accepted, true); + kda_check(pl, mode, true, accepted, true); + } + /* Every form against the one-row shuffle-sum kernel, byte for byte, in all four modes. */ + for (int64_t M : { 1, 7, 48, 300 }) kda_forms(pl, M, -1); + } + if (sel("moe_gemm_mxfp4a8")) { + for (int m : { 1, 17, 65, 257 }) + for (int parts : { 1, 2 }) + for (bool pooled : { false, true }) + for (const char* order : { "token", "sorted" }) + mx_experts_check(pl, m, parts, pooled, order); + for (int shape : { 1, 2, 3, 4 }) + for (int m : { 1, 4, 17 }) + mx_experts_check(pl, m, shape % 2 ? 2 : 1, m == 1, m == 17 ? "sorted" : "token", + shape); + for (int shape : { 1, 2, 3, 4 }) + mx_experts_check(pl, 257, shape % 2 ? 2 : 1, true, "sorted", shape); + // Exercise automatic GLM prefill selection with the real expert count/top-k. + for (int shape : { 1, 2, 3, 4 }) + mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, "sorted", shape, false, 288, 8); + mx_experts_check(pl, 1, 1, false, "token", 0, true); + // The rule takes the expert-major form at decode (at GLM's TP8 slices also above). Pinned, + // the row groups and the TP8 prefill form stay covered, and every expert-major stage and + // column-tile count meets narrow, parted and wide experts and runs of a hundred rows. + // Both weight decodes (RADIANCE_MXFP4_LUT) meet every form; dropped slots inside the runs + // and runs under 16 rows (288 experts) reach the TP8 prefill form at 65 and 257 tokens, + // with and without its stage prefetch (RADIANCE_MXFP4_PREFILL_PIPE). + constexpr int kPins = 10; + const char* const pins[kPins] = { + "RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_EXPERTS_STAGE_K", + "RADIANCE_MXFP4_EXPERTS_COLTILES", "RADIANCE_MXFP4_LUT", + "RADIANCE_MXFP4_ALIGNED_JOBS", "RADIANCE_MXFP4_PREFILL_N32", + "RADIANCE_MXFP4_PREFILL_M32", "RADIANCE_MXFP4_PREFILL_N64", + "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", "RADIANCE_MXFP4_PREFILL_PIPE" + }; + std::string kept[kPins]; + bool given[kPins]; + for (int i = 0; i < kPins; ++i) { + const char* v = std::getenv(pins[i]); + given[i] = v; + if (v) kept[i] = v; + } + // P64 is the rule at GLM's TP8 slices from 769 rows; off here, so the forms above stay the + // ones these cases name, and pinned or by its rule further down. + constexpr int kP64 = 12; + const char* const p64[kP64] = { "RADIANCE_MXFP4_PREFILL_P64", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", + "RADIANCE_MXFP4_PREFILL_P64_BM", + "RADIANCE_MXFP4_PREFILL_P64_BN", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", + "RADIANCE_MXFP4_PREFILL_P64_COLTILES", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", + "RADIANCE_MXFP4_PREFILL_P64_T_BM64", + "RADIANCE_MXFP4_PREFILL_P64_T_BN128", + "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", + "RADIANCE_MXFP4_PREFILL_P64_DB" }; + std::string kept64[kP64]; + bool given64[kP64]; + for (int i = 0; i < kP64; ++i) { + const char* v = std::getenv(p64[i]); + given64[i] = v; + if (v) kept64[i] = v; + } + for (int i = 1; i < kP64; ++i) unsetenv(p64[i]); + setenv(p64[0], "0", 1); + for (const char* lut : { "0", "1" }) { + setenv(pins[3], lut, 1); + setenv(pins[0], "0", 1); + for (int shape : { 1, 2, 3, 4 }) + mx_experts_check(pl, 17, shape % 2 ? 2 : 1, false, "sorted", shape); + mx_experts_check(pl, 1, 1, false, "token", 0, true); + for (const char* pipe : { "0", "1" }) { + setenv(pins[9], pipe, 1); + for (int shape : { 3, 4 }) { + mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, "sorted", shape, false, 288, + 8); + for (int m : { 65, 257 }) + mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, + shape == 4 ? "sorted" : "token", shape, false, 288, 8, + true); + } + // The TP8 prefill form outside GLM's slices: E8M0 codes 0 and 255, narrower and + // shorter odd experts, dropped slots. + for (int i = 4; i < 9; ++i) setenv(pins[i], "1", 1); + mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); + mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); + for (int i = 4; i < 9; ++i) unsetenv(pins[i]); + } + unsetenv(pins[9]); + setenv(pins[0], "1", 1); + for (const char* stage : { "128", "256" }) + for (const char* tiles : { "1", "4" }) { + setenv(pins[1], stage, 1); + setenv(pins[2], tiles, 1); + mx_experts_check(pl, 17, 1, false, "sorted", 2); + mx_experts_check(pl, 4, 2, true, "token", 3); + mx_experts_check(pl, 17, 2, false, "token"); + mx_experts_check(pl, 257, 2, true, "sorted"); + mx_experts_check(pl, 65, 1, false, "sorted", 4, false, 288, 8, true); + } + unsetenv(pins[1]); + unsetenv(pins[2]); + } + // The P64 form pinned below its row bounds: every BM x BN x stage at GLM's TP8 slices over + // 288 experts and 65 tokens (runs of about two rows, dropped slots), column tiles 1 and 4 + // with and without the LDS output at 257 tokens, and outside GLM's slices E8M0 codes 0 and + // 255 with narrower and shorter odd experts; then by its rule at 1024, 2048 and 4096 tokens + // (gate_up BM32 BN64 K256, BM64 BN64 K256 and BM64 BN128 K128 with the LDS output, down BM32 + // BN64 K128 x4 and BM64 BN128 K128 x4 with the LDS output). It always takes the table decode. + auto pin = [&](int bm, int bn, int sk, int ct, int out, int db = 0) { + const int v[8] = { 1, 0, 0, bm, bn, sk, ct, out }; + for (int i = 0; i < 8; ++i) setenv(p64[i], std::to_string(v[i]).c_str(), 1); + setenv(p64[11], db ? "1" : "0", 1); + }; + setenv(pins[0], "0", 1); + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + for (int sk : { 128, 256 }) { + pin(bm, bn, sk, 4, 0); + for (int shape : { 3, 4 }) + mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, + shape == 4 ? "sorted" : "token", shape, false, 288, 8, + true); + } + for (int out : { 0, 1 }) + for (int ct : { 1, 4 }) { + pin(64, 128, 128, ct, out); + for (int shape : { 3, 4 }) + mx_experts_check(pl, 257, shape % 2 ? 2 : 1, true, + shape == 4 ? "sorted" : "token", shape, false, 288, 8, true); + } + for (int out : { 0, 1 }) { + pin(64, 128, 128, 4, out); + mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); + mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); + } + // The double buffer at gate_up's slice wherever two stages fit, and with E8M0 codes 0 and + // 255 outside GLM's slices. + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) { + pin(bm, bn, 128, 4, bm == 64 && bn == 128, 1); + mx_experts_check(pl, 257, 2, true, "token", 3, false, 288, 8, true); + } + pin(32, 64, 256, 4, 0, 1); + mx_experts_check(pl, 257, 2, true, "token", 3, false, 288, 8, true); + mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); + for (int i = 0; i < kP64; ++i) unsetenv(p64[i]); + unsetenv(pins[0]); + for (int m : { 1024, 2048 }) + for (int shape : { 3, 4 }) + mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, shape == 4 ? "sorted" : "token", + shape, false, 288, 8, true); + mx_experts_check(pl, 4096, 1, true, "sorted", 4, false, 288, 8, true); + for (int i = 0; i < kP64; ++i) { + if (given64[i]) + setenv(p64[i], kept64[i].c_str(), 1); + else + unsetenv(p64[i]); + } + for (int i = 0; i < kPins; ++i) { + if (given[i]) + setenv(pins[i], kept[i].c_str(), 1); + else + unsetenv(pins[i]); + } + } + if (sel("hc_read_e4m3")) { if (!g_case) std::printf("\nthe gated residual's read at the prefill tile, every form " "against the decode tiles'\n"); @@ -20689,6 +24614,10 @@ static void usage(void) { " --perf N K M [iters]: time the fp8 decode GEMMs at one shape and print the\n" " weight bandwidth each reaches.\n" " --perfbf16 N K M [iters]: the bf16 skinny GEMM at every variant it has.\n" + " --perff32 N K M [iters]: gemm_nt_f32 at every tile form, each compared byte\n" + " for byte with the legacy kernel, with GB/s and TFLOP/s.\n" + " --perfq N K M [iters]: the block-quantised trunk rows GLM resolves to: E4M3 with\n" + " F32 block scales and the three OCP-MXFP4 rows, GB/s on weight + scales.\n" " --perfw8 N K M [iters]: the 8-bit trunk GEMMs -- block E4M3 W8A8 and the int8\n" " rows -- at one shape, each with its TFLOP/s.\n" " --perfw2 N K M [iters]: the int2 DFlash2 draft head at every variant it has.\n" @@ -20737,6 +24666,41 @@ static void usage(void) { " a card: one-shot and two-shot at the block rule and at 4..64 blocks,\n" " each checked against the rank-order fold; numel 0 runs the decode\n" " and prefill messages at 4096 wide. dtype bf16 (default) or fp32.\n" + " --perfmxf8 M [iters] [experts] [top_k] [skew]: the same at the FP8 experts with f32\n" + " block scales (moe_gemm_fp8a8_f32scale, GLM's MTP layer).\n" + " --perfmhcpre M [iters]: mhc_pre (whole, partials alone, finish alone) and\n" + " mhc_post at GLM's shape, every form against the old dispatch.\n" + " --perfrouter M [iters]: router_sigmoid_topk at GLM's shape (288 experts, top 8),\n" + " the wave-per-row select against the serial scan.\n" + " --perfmoefuse M [iters]: GLM's decode fusions of the MoE block at M token\n" + " rows (288 experts, top 8, TP8 widths), each against the separate\n" + " launches it replaces: time of both and a byte comparison of every\n" + " output (`= old` or DIFFERS). The router fusion takes M <= 128.\n" + " --perfkda M [iters]: kda_update at GLM's TP8 shape: prefill of M tokens (one\n" + " sequence, and three anchored) and the 8x6 verify step, every row and\n" + " prefetch form timed and compared byte for byte with the old kernel.\n" + " --perfproject M [iters]: mla_project at GLM's TP8 shape, both modes, every\n" + " rows-a-group form timed and compared byte for byte with the old kernels.\n" + " --perfmx M [iters] [experts] [top_k] [skew]: the MXFP4 expert GEMM at GLM's\n" + " TP8 slices (gate_up 512 x 4096, down 4096 x 256) over a routing of an\n" + " M-token chunk (288 experts, top 8 by default; uniform, or `skew` a Gamma\n" + " CV per expert as g1.0 or a Zipf exponent as z1.1): time, touched weight\n" + " bytes, GB/s and TFLOP/s per projection; the rule, the expert-major form\n" + " at each pinned stage and column-tile count, the row groups and from 512\n" + " routed rows every prefill form and the P64 raster (BM x BN x stage,\n" + " down also x column tiles), each compared with the bytes of the pinned\n" + " TP8 prefill form.\n" + " --perfmla M blocks heads [iters] [fill]: MLA attention without the oracle, so\n" + " a 2048-row prefill chunk at 2k/8k context fits (blocks 513/2049).\n" + " The wave row and the matrix row at both key loads (paired tiles at\n" + " 8 heads) on the same operands: us, TFLOP/s over the visible\n" + " positions, and the difference to the wave row in bf16 steps. fill is\n" + " prefill (two sequences, default), fresh (one), ragged, SxR for a\n" + " decode step of S sequences with R rows each (M becomes S*R), or\n" + " topk:d[:context] for one sequence past the DSA budget: each row its\n" + " own top blocks-1 in block order, d blocks exchanged between\n" + " neighbours (context 16*(blocks-1) tokens by default). Each matrix\n" + " form also reports its second passes.\n" " --perfqsa CTX [M] [iters]: the QSA indexer at a real context length. It is\n" " the only decode op that grows with context, and at 200K it is\n" " about a third of the step. M is 1 + n_spec.\n" @@ -20750,10 +24714,13 @@ int main(int argc, char** argv) { const char* real_file = nullptr; long long real_woff = 0, real_soff = 0, real_n = 0, real_k = 0; long long perf_n = 0, perf_k = 0, perf_m = 0; - int perf_it = 50, perf_w2 = 0, perf_bf = 0, perf_w8 = 0; + int perf_it = 50, perf_w2 = 0, perf_bf = 0, perf_w8 = 0, perf_f32 = 0, perf_q = 0; long long sop_m = 0, sop_k = 0; int sop_it = 2000; long long qsa_ctx = 0, qsa_m = 4; + long long mla_m = 0, mla_blocks = 0, mla_heads = 0; + int mla_it = 20; + const char* mla_fill = "prefill"; int qsa_it = 200; long long hc_m = 0; int hc_it = 20; @@ -20776,6 +24743,18 @@ int main(int argc, char** argv) { long long ar8_n = -1; int ar8_it = 200; const char* ar8_dt = "bf16"; + long long mx_m = 0, mx_e = 288, mx_k = 8; + const char* mx_skew = nullptr; + bool mx_f8 = false; + int mx_it = 100; + long long mhc_m = 0; + int mhc_it = 200; + long long rt_m = 0; + int rt_it = 200; + long long mf_m = 0; + int mf_it = 200; + long long kda_m = 0, proj_m = 0; + int kda_it = 50, proj_it = 100; for (int i = 1; i < argc; ++i) { if (!std::strcmp(argv[i], "--real")) { if (i + 5 >= argc) { usage(); return 2; } @@ -20798,6 +24777,22 @@ int main(int argc, char** argv) { perf_k = std::strtoll(argv[++i], nullptr, 0); perf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perff32")) { + /* gemm_nt_f32 at every tile form (see f32_forms). */ + if (i + 3 >= argc) { usage(); return 2; } + perf_f32 = 1; + perf_n = std::strtoll(argv[++i], nullptr, 0); + perf_k = std::strtoll(argv[++i], nullptr, 0); + perf_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfq")) { + /* GLM's block-quantised trunk rows (see q_perf). */ + if (i + 3 >= argc) { usage(); return 2; } + perf_q = 1; + perf_n = std::strtoll(argv[++i], nullptr, 0); + perf_k = std::strtoll(argv[++i], nullptr, 0); + perf_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfw8")) { if (i + 3 >= argc) { usage(); return 2; } perf_w8 = 1; @@ -20819,6 +24814,15 @@ int main(int argc, char** argv) { qsa_ctx = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfmla")) { + /* MLA attention at a prefill chunk, matrix forms against the wave row. */ + if (i + 3 >= argc) { usage(); return 2; } + mla_m = std::strtoll(argv[++i], nullptr, 0); + mla_blocks = std::strtoll(argv[++i], nullptr, 0); + mla_heads = std::strtoll(argv[++i], nullptr, 0); + auto digits = [](const char* t) { return *t && std::strspn(t, "0123456789") == std::strlen(t); }; + if (i + 1 < argc && digits(argv[i + 1])) mla_it = (int)std::strtol(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d && !digits(argv[i + 1])) mla_fill = argv[++i]; } else if (!std::strcmp(argv[i], "--cold")) { if (i + 1 >= argc) { usage(); return 2; } g_cold = std::strtoll(argv[++i], nullptr, 0) << 20; @@ -20869,6 +24873,36 @@ int main(int argc, char** argv) { ar8_n = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_it = (int)std::strtol(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_dt = argv[++i]; + } else if (!std::strcmp(argv[i], "--perfmhcpre")) { + /* mhc_pre and mhc_post at GLM's shape, every form, against the old dispatch. */ + if (i + 1 >= argc) { usage(); return 2; } + mhc_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mhc_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfrouter")) { + if (i + 1 >= argc) { usage(); return 2; } + rt_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) rt_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfmoefuse")) { + if (i + 1 >= argc) { usage(); return 2; } + mf_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mf_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfkda") || !std::strcmp(argv[i], "--perfproject")) { + /* kda_update or mla_project at GLM's TP8 shape, every form, against the old kernel. */ + if (i + 1 >= argc) { usage(); return 2; } + const bool kda = !std::strcmp(argv[i], "--perfkda"); + (kda ? kda_m : proj_m) = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) + (kda ? kda_it : proj_it) = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfmx") || !std::strcmp(argv[i], "--perfmxf8")) { + mx_f8 = !std::strcmp(argv[i], "--perfmxf8"); + /* An expert GEMM at GLM's TP8 slices over an M-token chunk, every form: MXFP4, or with + * --perfmxf8 the FP8 experts with f32 block scales. */ + if (i + 1 >= argc) { usage(); return 2; } + mx_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_it = (int)std::strtol(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_e = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_k = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_skew = argv[++i]; } else if (!std::strcmp(argv[i], "--perfhc")) { /* The gated residual's read at M rows. */ if (i + 1 >= argc) { usage(); return 2; } @@ -20988,6 +25022,67 @@ int main(int argc, char** argv) { dfree_all(); #else skip("eight-rank all-reduce timing", "built without HIP"); +#endif + return 0; + } + if (mhc_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + mhcpre_perf(pl, mhc_m, mhc_it); + dfree_all(); +#else + skip("mhc timing", "built without HIP"); +#endif + return 0; + } + if (rt_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + router_select(pl, rt_m, 288, 8, 1, false, rt_it); + dfree_all(); +#else + skip("router timing", "built without HIP"); +#endif + return 0; + } + if (mf_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + moefuse_perf(pl, mf_m, mf_it); + dfree_all(); +#else + skip("MoE fusion timing", "built without HIP"); +#endif + return g_fail ? 1 : 0; + } + if (kda_m || proj_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + if (kda_m) kda_forms(pl, kda_m, kda_it); + if (proj_m) project_forms(pl, proj_m, proj_it); + dfree_all(); +#else + skip("kda_update and mla_project timing", "built without HIP"); +#endif + return 0; + } + if (mx_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + mx_perf(pl, mx_m, mx_it, mx_e, mx_k, mx_f8, mx_skew); + dfree_all(); +#else + skip("MXFP4 expert GEMM timing", "built without HIP"); +#endif + return 0; + } + if (mla_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + mla_perf(pl, mla_m, mla_blocks, mla_heads, mla_it, mla_fill); + dfree_all(); +#else + skip("MLA attention timing", "built without HIP"); #endif return 0; } @@ -21015,7 +25110,9 @@ int main(int argc, char** argv) { if (perf_n) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP - if (perf_bf) bf16_perf(pl, perf_n, perf_k, perf_m, perf_it); + if (perf_f32) f32_forms(pl, perf_m, perf_n, perf_k, perf_it, true); + else if (perf_q) q_perf(pl, perf_n, perf_k, perf_m, perf_it); + else if (perf_bf) bf16_perf(pl, perf_n, perf_k, perf_m, perf_it); else if (perf_w8) w8_perf(pl, perf_n, perf_k, perf_m, perf_it); else if (perf_w2) w2_perf(pl, perf_n, perf_k, perf_m, perf_it); else fp8_perf(pl, perf_n, perf_k, perf_m, perf_it); @@ -21043,6 +25140,7 @@ int main(int argc, char** argv) { * a faulting row may print nothing. */ if (g_case) { if (!load(&pl, path)) return CH_FAIL; + g_plugin = path; device_phase(pl); if (!g_matched) skip(g_case, "no smoke case"); std::fflush(stdout); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 91505e41..8caf64ae 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -66,6 +66,7 @@ #include #include +#include #include "r4d_plugin.h" #include "rad_sample.h" @@ -364,6 +365,91 @@ extern "C" int r4d_shape_gemm_nt_bias(const RadParam* p, int n_p, int operand, R R4D_PICK(l); } +extern "C" int r4d_shape_moe_mxfp4(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K"); + const int64_t N1 = rad_param_geti(p, n_p, "N_odd", N), K1 = rad_param_geti(p, n_p, "K_odd", K); + const int64_t ne = pi(p, n_p, "n_expert"), top = pi(p, n_p, "top_k"); + const char* order = rad_param_gets(p, n_p, "a_order", ""); + const int64_t ar = !std::strcmp(order, "sorted") ? M * top : M; + const int64_t nk = std::max(K, K1), nn = std::max(N, N1); + RadOpdDesc s0 = opd((uint32_t)RAD_U8, (ne + 1) / 2, N, K / 32); + RadOpdDesc s1 = opd((uint32_t)RAD_U8, ne / 2, N1, K1 / 32); + s0.fill = s1.fill = RAD_FILL_INDEX; + s0.idx_const = s1.idx_const = 127; + const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, ar, nk), + opd((uint32_t)RAD_F32, ar, nk / 128), + opd((uint32_t)RAD_FP4E2M1, (ne + 1) / 2, N, K), + s0, + opd_idx(M * top, 0, M * top), + opd_idx(ne + 1, 0, M * top + 1), + opd((uint32_t)RAD_FP4E2M1, ne / 2, N1, K1), + s1, + opd((uint32_t)RAD_BF16, M * top, nn) }; + R4D_PICK(l); +} + +extern "C" int r4d_shape_kda_update(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const char* form = rad_param_gets(p, n_p, "state_form", ""); + if (!std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED; + const int64_t M = pi(p, n_p, "M"), H = pi(p, n_p, "heads"); + const int64_t K = pi(p, n_p, "head_k"), V = pi(p, n_p, "head_v"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const char* mode = rad_param_gets(p, n_p, "mode", ""); + const int64_t history = !std::strcmp(mode, "verify") ? M : 1; + const RadOpdDesc l[] = { + opd(D, M, H, K), opd(D, M, H, K), opd(D, M, H, V), opd(D, M, H, K), opd(D, M, H), + opd((uint32_t)RAD_F32, H), opd((uint32_t)RAD_F32, H * K), + opd((uint32_t)RAD_F32, history + 1, H, V, K), + opd_idx(1, history, history + 1, -1, RAD_OPD_F_IDX_UNIQUE), + opd_idx(2, 0, M, -1, RAD_OPD_F_IDX_CU), + opd_idx(1, 0, 0, 1), opd_idx(1, 0, 0, 1), opd(D, M, H, V), + }; + R4D_PICK(l); +} + +extern "C" int r4d_shape_mhc_pre(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, hc * n), opd((uint32_t)RAD_F32, hc * (hc + 2), hc * n), + opd((uint32_t)RAD_F32, 3), opd((uint32_t)RAD_F32, hc * (hc + 2)), opd(D, M, n), + opd((uint32_t)RAD_F32, M, hc), opd((uint32_t)RAD_F32, M, hc * hc) }; + R4D_PICK(l); +} +/* The partial matrix: per chunk the hc*(hc+2) coefficient partials and the sum of squares, padded to + * a multiple of four floats (docs/OPS.md). */ +static int64_t mhc_part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; } +extern "C" int r4d_shape_mhc_pre_partial(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const int64_t chunks = pi(p, n_p, "chunks"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, hc * n), opd((uint32_t)RAD_F32, hc * (hc + 2), hc * n), + opd((uint32_t)RAD_F32, M, chunks * mhc_part_stride(hc)) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mhc_pre_finish(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const int64_t chunk = pi(p, n_p, "chunk"); + const int64_t chunks = chunk > 0 ? hc * n / chunk : 0; + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, chunks * mhc_part_stride(hc)), + opd(D, M, hc * n), opd((uint32_t)RAD_F32, 3), opd((uint32_t)RAD_F32, hc * (hc + 2)), + opd(D, M, n), opd((uint32_t)RAD_F32, M, hc), opd((uint32_t)RAD_F32, M, hc * hc) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mhc_post(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, n), opd(D, M, hc * n), opd((uint32_t)RAD_F32, M, hc), + opd((uint32_t)RAD_F32, M, hc * hc), opd(D, M, hc * n) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mhc_contract(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, hc * n), opd(D, M, n) }; + R4D_PICK(l); +} + /* ---- the gated residual (r4d_hc_bf16.hip's three shims). `inject` and `group` default on, so a * query naming neither describes what every trunk connection runs; 0 for either describes one of * the two exceptions: the final mixer, and a read whose consumer wants bf16. */ @@ -496,6 +582,83 @@ extern "C" int r4d_shape_silu_mul(const RadParam* p, int n_p, int operand, const RadOpdDesc l[] = { opd(D, M, 2 * n), opd(D, M, n) }; R4D_PICK(l); } +extern "C" int r4d_shape_router_sigmoid_topk(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, ne), opd((uint32_t)RAD_F32, ne), opd_idx(M, k, ne), + opd(D, M, k) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_router_sigmoid_topk_scatter(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k"); + const int64_t nl = pi(p, n_p, "n_local", ne); + if (ne <= 0 || ne > 512 || k <= 0 || k > ne || nl <= 0 || nl > ne || M * k > 1024) + return RAD_E_UNSUPPORTED; + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, ne), + opd((uint32_t)RAD_F32, ne), + opd_idx(M, k, ne), + opd(D, M, k), + opd((uint32_t)RAD_I32, M * k), + opd((uint32_t)RAD_I32, nl + 1), + opd((uint32_t)RAD_I32, nl), + opd((uint32_t)RAD_BF16, M, 1), + opd((uint32_t)RAD_I32, M * k) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_dsa_pool(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), ratio = pi(p, n_p, "ratio"); + const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M * ratio, 2 * n), + opd((uint32_t)RAD_F32, ratio, n), + opd((uint32_t)RAD_F8E4M3, M, n), + opd((uint32_t)RAD_F32, M, 1), + opd_none(), + opd_none() }; + R4D_PICK(l); +} +extern "C" int r4d_shape_dsa_query(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); + const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, n), opd((uint32_t)RAD_F8E4M3, M, n), + opd((uint32_t)RAD_F32, M, 1) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mla_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), h = pi(p, n_p, "heads"), d = pi(p, n_p, "head_dim"), + l = pi(p, n_p, "latent_dim"); + const char* mode = r4d_pgets(p, n_p, "mode"); + const bool absorb = mode && !std::strcmp(mode, "absorb"), + expand = mode && !std::strcmp(mode, "expand"); + if (!absorb && !expand) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, absorb ? d : l), + opd((uint32_t)RAD_BF16, h * 2 * d, l), + opd((uint32_t)RAD_BF16, M, h, absorb ? l : d) }; + R4D_PICK(list); +} +extern "C" int r4d_shape_dsa_score(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), H = pi(p, n_p, "heads"); + const int64_t B = pi(p, n_p, "blocks"), S = pi(p, n_p, "seqs"), pages = S * B; + const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, M, H, n), + opd((uint32_t)RAD_F32, M, H), + opd((uint32_t)RAD_F32, M, H), + opd((uint32_t)RAD_F8E4M3, pages, n), + opd((uint32_t)RAD_F32, pages), + opd_idx(S, B, pages), + opd_idx(S + 1, 0, M, -1, RAD_OPD_F_IDX_CU), + opd_idx(S, 0, 0, B), + opd((uint32_t)RAD_F32, M, B) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mla_attn(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), D = pi(p, n_p, "latent_dim"), H = pi(p, n_p, "heads"); + const int64_t B = pi(p, n_p, "blocks"), bs = pi(p, n_p, "block_size"), + pages = std::max((int64_t)2, B * M); + const uint32_t dt = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(dt, M, H, D), opd(dt, pages, 1, bs, D), opd_idx(M, B, pages), + opd_idx(M, 0, 0, B * bs), opd(dt, M, H, D) }; + R4D_PICK(l); +} extern "C" int r4d_shape_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1020,6 +1183,12 @@ extern "C" int r4d_shape_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, int op * r4d_rowtopk_bf16.hip). * ========================================================================================= */ +extern "C" int r4d_shape_gemm_nt_f32(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K"); + const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, K), opd((uint32_t)RAD_F32, N, K), + opd((uint32_t)RAD_F32, M, N) }; + R4D_PICK(l); +} extern "C" int r4d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1243,6 +1412,22 @@ extern "C" int r4d_shape_moe_scatter(const RadParam* p, int n_p, int operand, Ra R4D_PICK(l); } +extern "C" int r4d_shape_moe_scatter_inv(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t ne = pi(p, n_p, "n_expert"); + const int64_t k = pi(p, n_p, "top_k"); + if (ne <= 0 || ne > 512 || k <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd_idx(M, k, ne, -1), + opd((uint32_t)RAD_I32, M * k), + opd((uint32_t)RAD_I32, ne + 1), + opd((uint32_t)RAD_I32, ne), + opd((uint32_t)RAD_I32, M * k), + }; + R4D_PICK(l); +} + extern "C" int r4d_shape_moe_gemm_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); const int64_t N0 = pi(p, n_p, "N"), K0 = pi(p, n_p, "K"); @@ -1339,6 +1524,12 @@ extern "C" int r4d_shape_moe_gather(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } +/* moe_gather's list with the slot table in place of `sorted_tok`: the same draw, since a valid + * table, like a valid sort, holds distinct rows of `y_expert` (and -1 for a dropped slot). */ +extern "C" int r4d_shape_moe_gather_inv(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return r4d_shape_moe_gather(p, n_p, operand, out); +} + /* row_topk -- exact per-row top-R of a wide bf16 matrix (shim in r4d_rowtopk_bf16.hip). R is at * most 32, stage 2's PT. */ extern "C" int r4d_shape_row_topk(const RadParam* p, int n_p, int operand, diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 51e97566..bf2b8296 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -357,14 +357,16 @@ endif() # ================================================================== libr4d's kernels, on the host # # Some libr4d ops (the sandwich-norm joins, expert_scale) have no libref oracle by design -# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of six units written -# against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins, -# expert_scale, the QSA block selection, whose four kernels a card-less build otherwise never -# runs, and the runtime-LoRA pair. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread -# is a fiber, and __syncthreads and cross-lane ops are barriers (one not reached uniformly is -# reported as a deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select, -# the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, and for the -# LoRA pair libref itself when the test can load it. +# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of thirteen units +# written against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins, +# expert_scale, the QSA block selection, the runtime-LoRA pair, the F32 routing projection's tile +# forms, GLM's mHC read with its chunk split, the F32-scale E4M3 GEMM's forms, GLM's KDA +# recurrence, the MXFP4 expert GEMM's forms, the MLA matrix row's pairings and GLM's MoE decode +# fusions, whose kernels a card-less build otherwise never runs. emu/hip/hip_runtime.h supplies the +# HIP names, each GPU thread is a fiber, and __syncthreads and cross-lane ops are barriers (one not +# reached uniformly is reported as a deadlock). Checked against ports of libref's ref_attn_paged and +# ref_qsa_select, the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, +# and for the LoRA pair libref itself when the test can load it. # # Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang # C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so @@ -376,8 +378,10 @@ set(R4D_DIR ${CMAKE_SOURCE_DIR}/libr4d) set(R4D_EMU ${CMAKE_CURRENT_SOURCE_DIR}/r4d_emu) set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_f32.hip ${R4D_DIR}/r4d_norm_join_bf16.hip ${R4D_DIR}/r4d_expert_scale_bf16.hip - ${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip) -set(R4D_EMU_TESTS attn pick norm escale qsa lora) + ${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip + ${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip + ${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip) +set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse) set(R4D_EMU_BUILT OFF) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") # No fiber switch for this ISA. @@ -413,7 +417,10 @@ else() set(objs "") foreach(src ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp ${R4D_EMU}/test_attn.cpp ${R4D_EMU}/test_pick.cpp ${R4D_EMU}/test_norm.cpp - ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp) + ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp + ${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp + ${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp + ${R4D_EMU}/test_moefuse.cpp) get_filename_component(stem ${src} NAME_WE) set(lang "") if(src MATCHES "\\.hip$") @@ -450,7 +457,7 @@ else() endif() endif() if(R4D_EMU_BUILT) - foreach(t pick norm escale qsa lora) + foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse) add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t}) endforeach() # The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel, @@ -460,7 +467,7 @@ if(R4D_EMU_BUILT) COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_attn --shard ${k}/3) endforeach() set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick - r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora + r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT}) # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can # load one -- expand bit for bit, shrink to its bound. diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 3349b8a5..67b6ed7c 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -995,6 +995,25 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) { for (const Band& x : b) CHECK_EQ(picked(x.dom[RAD_DOMAIN_DEVICE].row), "attn_vit_h72_bf16"); } +/* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves + * every M up to its bound, a decode step's rows and a prefill chunk alike. RADIANCE_MLA_MATRIX_MAX_M + * lowers that bound, which this case does not cover. */ +TEST(libr4d_resolves_the_mla_attention_by_rows) { + const std::string so = libr4d(); + if (so.empty()) return; + if (std::getenv("RADIANCE_MLA_MATRIX_MAX_M")) return; + Registry r; + CHECK(r.load_plugin(so, 0) >= 0); + Geometry g; + g.set_i("latent_dim", 512); + g.set_i("heads", 8); + g.set_i("blocks", 513); + g.set_i("block_size", 4); + g.set_s("dtype", "bf16"); + CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 2048, g)), "2048:mla_attn_matrix_bf16 "); + CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 48, g)), "48:mla_attn_matrix_bf16 "); +} + /* ================================================================== constraints that are not intervals */ namespace { std::string extra_dir() { return home() + "/testkernels/extra"; } diff --git a/tests/r4d_emu/emu/emu.cpp b/tests/r4d_emu/emu/emu.cpp index 840c96b2..7a8cd47c 100644 --- a/tests/r4d_emu/emu/emu.cpp +++ b/tests/r4d_emu/emu/emu.cpp @@ -2,6 +2,7 @@ #include "rad_plugin.h" #include #include +#include #include #include #include @@ -47,11 +48,12 @@ struct Sched { std::vector f; void* main_sp = nullptr; int cur = -1, nthreads = 0; - EmuIdx bid{}; + EmuIdx bid{}, bdim{}, gdim{}; void (*body)(void*) = nullptr; void* ctx = nullptr; - /* block barrier */ + /* block barrier; or_acc[g % 3] collects __syncthreads_or's predicates at generation g */ int arrive = 0; unsigned gen = 0; + int or_acc[3] = {}; /* wave barriers and exchange slots, double-buffered by parity */ int warrive[64] = {}; unsigned wgen[64] = {}; int slot[64][2][32] = {}; @@ -82,15 +84,26 @@ extern "C" void emu_entry(); EmuIdx& emu_thread_idx() { return S.f[S.cur].tid; } EmuIdx& emu_block_idx() { return S.bid; } +EmuIdx& emu_block_dim() { return S.bdim; } +EmuIdx& emu_grid_dim() { return S.gdim; } void __syncthreads() { Fiber& me = S.f[S.cur]; const unsigned g = S.gen; - if (++S.arrive == S.nthreads) { S.arrive = 0; ++S.gen; return; } + /* Clearing the next generation's slot here, as the barrier completes, keeps it ahead of every + * write to it (threads arrive at g + 1 only after g completes) and behind every read of the + * slot it shares a residue with (g - 2's, read before arriving at g - 1). */ + if (++S.arrive == S.nthreads) { S.arrive = 0; S.or_acc[(g + 1) % 3] = 0; ++S.gen; return; } me.waiting = 1; while (S.gen == g) yield(); me.waiting = 0; } +int __syncthreads_or(int p) { + const unsigned g = S.gen; + if (p) S.or_acc[g % 3] = 1; + __syncthreads(); + return S.or_acc[g % 3]; +} static void wave_barrier(int w) { Fiber& me = S.f[S.cur]; @@ -165,6 +178,23 @@ static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8]; emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) { return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) { return (float)v; }); } +namespace { +struct Bytes8 { + uint8_t v[8]; + uint8_t operator[](int e) const { return v[e]; } +}; +} +static uint8_t g_qa[64][2][32][8], g_qb[64][2][32][8]; +emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c) { + Bytes8 pa, pb; + std::memcpy(pa.v, &a, 8); + std::memcpy(pb.v, &b, 8); + return emu_wmma(g_qa, g_qb, pa, pb, c, [](uint8_t v) { return rad_fp8e4m3_to_f32(v); }); +} +emu_v8i emu_wmma_iu8(bool, emu_v2i, bool, emu_v2i, emu_v8i, bool) { + std::fprintf(stderr, "emu: v_wmma_i32_16x16x16_iu8 is not emulated\n"); + std::abort(); +} unsigned emu_ballot(bool p) { int l; const int* s = exchange(p ? 1 : 0, &l, kOpBallot); @@ -236,6 +266,8 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t } lds_reserve(dyn_lds); S.body = body; S.ctx = ctx; S.nthreads = n; + S.bdim = EmuIdx{block.x, block.y, block.z}; + S.gdim = EmuIdx{grid.x, grid.y, grid.z}; S.f.resize(n); for (auto& f : S.f) if (!f.stack) f.stack.reset(new char[kStack]); for (unsigned bz = 0; bz < grid.z; ++bz) @@ -244,6 +276,7 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t S.bid = EmuIdx{bx, by, bz}; std::memset(g_lds, 0xA5, dyn_lds); S.arrive = 0; S.gen = 0; + for (int& a : S.or_acc) a = 0; for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; } for (int t = 0; t < n; ++t) { Fiber& f = S.f[t]; diff --git a/tests/r4d_emu/emu/hip/hip_runtime.h b/tests/r4d_emu/emu/hip/hip_runtime.h index 31d786d9..8f46b49e 100644 --- a/tests/r4d_emu/emu/hip/hip_runtime.h +++ b/tests/r4d_emu/emu/hip/hip_runtime.h @@ -15,8 +15,12 @@ #define __device__ #define __host__ #define __shared__ static +#define __constant__ #define __forceinline__ inline #define __launch_bounds__(n) +/* R4D_WAVES (r4d_common.h) names a kernel attribute; on the host it becomes an empty attribute */ +#define amdgpu_waves_per_eu(lo, hi) +#define __align__(n) __attribute__((aligned(n))) struct dim3 { unsigned x, y, z; @@ -29,6 +33,25 @@ inline hipError_t hipGetLastError() { return 0; } /* one device, with the R9700's 64 KiB of LDS a workgroup, which launchers size dynamic LDS by */ struct hipDeviceProp_t { size_t sharedMemPerBlock; }; inline hipError_t hipGetDevice(int* d) { *d = 0; return hipSuccess; } +/* no graphs: a stream never captures */ +enum hipStreamCaptureStatus { hipStreamCaptureStatusNone = 0 }; +inline hipError_t hipStreamIsCapturing(hipStream_t, hipStreamCaptureStatus* s) { + *s = hipStreamCaptureStatusNone; + return hipSuccess; +} +/* every launch runs to completion before it returns */ +inline hipError_t hipDeviceSynchronize() { return hipSuccess; } +/* __device__ variables are host globals, so a symbol copy is a memcpy */ +enum hipMemcpyKind { hipMemcpyHostToDevice = 1, hipMemcpyDeviceToHost = 2 }; +#define HIP_SYMBOL(s) (&(s)) +inline hipError_t hipMemcpyFromSymbol(void* dst, const void* sym, size_t n, size_t off, hipMemcpyKind) { + std::memcpy(dst, (const char*)sym + off, n); + return hipSuccess; +} +inline hipError_t hipMemcpyToSymbol(const void* sym, const void* src, size_t n, size_t off, hipMemcpyKind) { + std::memcpy((char*)sym + off, src, n); + return hipSuccess; +} inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) { *p = hipDeviceProp_t{}; p->sharedMemPerBlock = 64 * 1024; @@ -38,9 +61,15 @@ inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) { struct EmuIdx { unsigned x, y, z; }; EmuIdx& emu_thread_idx(); EmuIdx& emu_block_idx(); +EmuIdx& emu_block_dim(); +EmuIdx& emu_grid_dim(); #define threadIdx (emu_thread_idx()) #define blockIdx (emu_block_idx()) +#define blockDim (emu_block_dim()) +#define gridDim (emu_grid_dim()) void __syncthreads(); +/* the block barrier, returning whether any thread passed a nonzero predicate */ +int __syncthreads_or(int p); int emu_bpermute(int addr, int v); int emu_readlane(int v, int lane); #define __builtin_amdgcn_ds_bpermute(a, v) emu_bpermute((a), (v)) @@ -73,6 +102,14 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) { return r; } #define __builtin_amdgcn_perm(a, b, s) emu_perm((a), (b), (s)) +/* HIP's __byte_perm: result byte i is the byte of {y, x} (x low) that the low three bits of + * nibble i of s name; only the low four nibbles are read */ +inline unsigned __byte_perm(unsigned x, unsigned y, unsigned s) { + const unsigned long long d = ((unsigned long long)y << 32) | x; + unsigned r = 0; + for (int i = 0; i < 4; ++i) r |= (unsigned)((d >> (8 * ((s >> (4 * i)) & 7u))) & 0xffu) << (8 * i); + return r; +} /* s_barrier is the workgroup barrier. Fibers share one memory and switch only at barriers, so a * fence or a scheduling barrier orders nothing more. */ #define __builtin_amdgcn_s_barrier() __syncthreads() @@ -81,15 +118,38 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) { /* LDS atomics: fibers switch only at barriers, so a plain read-modify-write is indivisible */ template inline T atomicAdd(T* p, T v) { const T o = *p; *p = o + v; return o; } +template +inline T atomicMin(T* p, T v) { const T o = *p; if (v < o) *p = v; return o; } +template +inline T atomicMax(T* p, T v) { const T o = *p; if (v > o) *p = v; return o; } +template +inline T atomicCAS(T* p, T expect, T v) { const T o = *p; if (o == expect) *p = v; return o; } /* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N] * lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */ typedef short emu_v8s __attribute__((ext_vector_type(8))); typedef float emu_v8f __attribute__((ext_vector_type(8))); emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c); +/* the __bf16 fragments of r4d_gdn_wmma.h, the same bits */ +typedef __bf16 emu_v8bf __attribute__((ext_vector_type(8))); +inline emu_v8f emu_wmma_bf16(emu_v8bf a, emu_v8bf b, emu_v8f c) { + return emu_wmma_bf16(__builtin_bit_cast(emu_v8s, a), __builtin_bit_cast(emu_v8s, b), c); +} #define __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c) emu_wmma_bf16((a), (b), (c)) typedef _Float16 emu_v8h __attribute__((ext_vector_type(8))); emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c); #define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c)) +/* v_wmma_f32_16x16x16_fp8_fp8 (gfx12, wave32): the bf16 form's layout with eight E4M3 bytes a + * lane, element e in byte e. Each output is c plus its 16 products in k order: not the hardware's + * internal order, but a function of the output's own row, column and c alone, as the hardware's + * is, which is what a comparison of two kernels over the same fragments relies on. */ +typedef int emu_v2i __attribute__((ext_vector_type(2))); +emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c); +#define __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c) emu_wmma_fp8((a), (b), (c)) +/* v_wmma_i32_16x16x16_iu8: not emulated; reported when reached */ +typedef int emu_v8i __attribute__((ext_vector_type(8))); +emu_v8i emu_wmma_iu8(bool sa, emu_v2i a, bool sb, emu_v2i b, emu_v8i c, bool clamp); +#define __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(sa, a, sb, b, c, cl) \ + emu_wmma_iu8((sa), (a), (sb), (b), (c), (cl)) /* global_load_tr_b128: not emulated; reported when reached */ emu_v8s emu_load_tr_b128(const void* p); #define __builtin_amdgcn_global_load_tr_b128_v8i16(p) emu_load_tr_b128((const void*)(p)) @@ -120,9 +180,34 @@ inline uint2 make_uint2(unsigned a, unsigned b) { return uint2{a, b}; } inline float4 make_float4(float a, float b, float c, float d) { return float4{a, b, c, d}; } inline float __uint_as_float(unsigned u) { float f; std::memcpy(&f, &u, 4); return f; } inline float rsqrtf(float x) { return 1.0f / std::sqrt(x); } /* v_rsq_f32 is within an ulp of it */ +/* The device's fast exponential is not bit-exact to expf; here it is expf, so a test compares two + * kernels that both take it, never a kernel against a host value of it. */ +inline float __expf(float x) { return std::exp(x); } inline unsigned __float_as_uint(float f) { unsigned u; std::memcpy(&u, &f, 4); return u; } inline float __int_as_float(int u) { float f; std::memcpy(&f, &u, 4); return f; } inline int __float_as_int(float f) { int u; std::memcpy(&u, &f, 4); return u; } +/* The float shuffles over ds_bpermute, for one-dimensional blocks, within groups of `width` + * lanes: __shfl_xor reads lane L ^ mask, __shfl lane `src`, __shfl_down lane L + delta (its own + * value past the group's end) */ +inline float emu_shfl_from(float v, int src) { + return __int_as_float(emu_bpermute(src << 2, __float_as_int(v))); +} +inline float __shfl_xor(float v, int mask, int width = 32) { + const int lane = (int)threadIdx.x & 31; + return emu_shfl_from(v, (lane & ~(width - 1)) | ((lane ^ mask) & (width - 1))); +} +inline float __shfl(float v, int src, int width = 32) { + const int lane = (int)threadIdx.x & 31; + return emu_shfl_from(v, (lane & ~(width - 1)) | (src & (width - 1))); +} +inline float __shfl_down(float v, unsigned delta, int width = 32) { + const int lane = (int)threadIdx.x & 31, in_group = lane & (width - 1); + return emu_shfl_from(v, in_group + (int)delta < width ? lane + (int)delta : lane); +} +/* HIP declares the classification functions in the global namespace */ +using std::isfinite; +inline int min(int a, int b) { return a < b ? a : b; } +inline int max(int a, int b) { return a > b ? a : b; } /* one block at a time, every thread a fiber; `dyn_lds` bytes of dynamic LDS */ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t dyn_lds = 0); @@ -154,6 +239,9 @@ int emu_emit(const char* name, void (*k)(P...), dim3 g, dim3 b, size_t lds, cons } #define R4D_EMIT(stream, kernel, grid, block, lds, ...) \ emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__) +/* hipLaunchKernelGGL, for units that launch with it directly: the same call as R4D_EMIT. */ +#define hipLaunchKernelGGL(kernel, grid, block, lds, stream, ...) \ + ((void)(stream), (void)emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__)) /* R4D_DYN_LDS (r4d_launch.h): the launch's dynamic LDS, poisoned at each block's start and ending * at an inaccessible page (its start 16-byte aligned), so a read before any write shows and one * past the end faults */ diff --git a/tests/r4d_emu/test_f32.cpp b/tests/r4d_emu/test_f32.cpp new file mode 100644 index 00000000..b6232903 --- /dev/null +++ b/tests/r4d_emu/test_f32.cpp @@ -0,0 +1,260 @@ +/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. Every tile form + * (RADIANCE_F32_GEMM_TILE) must match the one-wave-per-output legacy kernel bit for bit, and the + * legacy kernel must match its arithmetic written out here: lane l folds k = l, l+32, ... with + * fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding + * stay untouched. + * + * router_sigmoid_topk from the same unit: the wave-per-row select must match the serial scan + * (RADIANCE_ROUTER_SELECT=old) bit for bit, and the scan its arithmetic written out here, on + * random and on tied ranks, with the outputs' pitch padding untouched. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include +#include +#include +#include +#include +#include + +static float legacy_model(const uint16_t* x, const float* w, int k) { + float lane[32]; + for (int l = 0; l < 32; ++l) { + float s = 0; + for (int j = l; j < k; j += 32) s = std::fmaf(b2f(x[j]), w[j], s); + lane[l] = s; + } + for (int mask = 16; mask; mask >>= 1) { + float next[32]; + for (int l = 0; l < 32; ++l) next[l] = lane[l] + lane[l ^ mask]; + std::memcpy(lane, next, sizeof lane); + } + return lane[0]; +} + +static void router_model(const float* lg, const float* bias, int bp, int ne, int k, int norm, + float factor, int* ids, float* w) { + float prob[512], rank[512], chosen[32], total = 0; + int index[32]; + for (int e = 0; e < ne; ++e) { + prob[e] = 1.0f / (1.0f + expf(-lg[e])); + rank[e] = prob[e] + bias[(size_t)e * bp]; + } + for (int j = 0; j < k; ++j) { + int best = 0; + for (int e = 1; e < ne; ++e) + if (rank[e] > rank[best]) best = e; + index[j] = best; + chosen[j] = prob[best]; + total += chosen[j]; + rank[best] = -INFINITY; + } + const float mult = norm ? factor / (total + 1e-20f) : factor; + for (int j = 0; j < k; ++j) { + ids[j] = index[j]; + w[j] = chosen[j] * mult; + } +} + +static void router_cases(std::mt19937& rng, int& cases, int& fails) { + struct Shape { + int M, ne, k, norm; + bool ties; + }; + const Shape shapes[] = { { 1, 288, 8, 1, false }, { 6, 288, 8, 1, false }, + { 20, 288, 8, 1, true }, { 48, 288, 8, 1, false }, + { 6, 288, 8, 1, true }, { 5, 8, 8, 0, true }, + { 5, 32, 32, 0, true }, { 7, 300, 8, 1, false }, + { 3, 512, 32, 1, true } }; + std::uniform_int_distribution ud(-1000, 1000); + for (const Shape& sh : shapes) { + const int M = sh.M, ne = sh.ne, k = sh.k, lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1; + const float factor = 2.5f; + std::vector lg((size_t)M * lp), bias((size_t)ne * bp); + for (auto& v : lg) v = sh.ties ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200; + for (auto& v : bias) v = sh.ties ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000; + RadTensor t[4]{}; + t[0].data = lg.data(); + t[0].dtype = RAD_F32; + t[0].rank = 2; + t[0].shape[0] = M; + t[0].shape[1] = ne; + t[0].stride[0] = lp; + t[0].stride[1] = 1; + t[1].data = bias.data(); + t[1].dtype = RAD_F32; + t[1].rank = 1; + t[1].shape[0] = ne; + t[1].stride[0] = bp; + t[2].dtype = RAD_I32; + t[2].rank = 2; + t[2].shape[0] = M; + t[2].shape[1] = k; + t[2].stride[0] = ip; + t[2].stride[1] = 1; + t[3].dtype = RAD_F32; + t[3].rank = 2; + t[3].shape[0] = M; + t[3].shape[1] = k; + t[3].stride[0] = wp; + t[3].stride[1] = 1; + RadParam p[6]{}; + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "n_expert", RAD_P_INT, ne }; + p[2] = { "top_k", RAD_P_INT, k }; + p[3] = { "norm", RAD_P_INT, sh.norm }; + p[4].key = "route_scale"; + p[4].kind = RAD_P_F64; + p[4].dval = factor; + p[5].key = "dtype"; + p[5].kind = RAD_P_STR; + p[5].sval = "f32"; + RadArgs a{}; + a.t = t; + a.n_t = 4; + a.p = p; + a.n_p = 6; + auto run = [&](const char* form, std::vector& ids, std::vector& w) { + ids.assign((size_t)M * ip, -77); + w.assign((size_t)M * wp, -7.25f); + t[2].data = ids.data(); + t[3].data = w.data(); + if (form) + setenv("RADIANCE_ROUTER_SELECT", form, 1); + else + unsetenv("RADIANCE_ROUTER_SELECT"); + return r4d_rad_router_sigmoid_topk(&a, nullptr); + }; + std::vector ids_old, ids_new; + std::vector w_old, w_new; + ++cases; + if (run("old", ids_old, w_old) != RAD_OK) { + std::printf("FAIL router scan launch M=%d ne=%d\n", M, ne); + ++fails; + continue; + } + int bad = 0; + for (int r = 0; r < M; ++r) { + int mi[32]; + float mw[32]; + router_model(&lg[(size_t)r * lp], bias.data(), bp, ne, k, sh.norm, factor, mi, mw); + bad += std::memcmp(mi, &ids_old[(size_t)r * ip], (size_t)k * 4) != 0; + bad += std::memcmp(mw, &w_old[(size_t)r * wp], (size_t)k * 4) != 0; + for (int c = k; c < ip; ++c) bad += ids_old[(size_t)r * ip + c] != -77; + for (int c = k; c < wp; ++c) bad += w_old[(size_t)r * wp + c] != -7.25f; + } + if (bad) { + std::printf("FAIL router scan against its model at M=%d ne=%d k=%d: %d\n", M, ne, k, + bad); + ++fails; + } + ++cases; + const int rc = run(nullptr, ids_new, w_new); + if (rc != RAD_OK || ids_new != ids_old || + std::memcmp(w_new.data(), w_old.data(), w_new.size() * 4) != 0) { + std::printf("FAIL router wave select at M=%d ne=%d k=%d%s (rc %d)\n", M, ne, k, + sh.ties ? " tied" : "", rc); + ++fails; + } + } + unsetenv("RADIANCE_ROUTER_SELECT"); +} + +int main() { + std::mt19937 rng(17); + std::normal_distribution nd(0.f, 1.f); + const char* forms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", + "4x4", "8x4", "16x2", "16x4", nullptr }; + struct Shape { + int M, N, K; + }; + const Shape shapes[] = { { 1, 288, 512 }, { 3, 36, 129 }, { 8, 288, 129 }, { 33, 32, 512 }, + { 70, 36, 129 }, { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } }; + int fails = 0, cases = 0; + for (const Shape& sh : shapes) { + const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3; + std::vector x((size_t)M * xp); + std::vector w((size_t)N * K); + for (auto& v : x) v = f2b(nd(rng)); + for (auto& v : w) v = nd(rng) * 0.03f; + RadTensor t[3]{}; + t[0].data = x.data(); + t[0].dtype = RAD_BF16; + t[0].rank = 2; + t[0].shape[0] = M; + t[0].shape[1] = K; + t[0].stride[0] = xp; + t[0].stride[1] = 1; + t[1].data = w.data(); + t[1].dtype = RAD_F32; + t[1].rank = 2; + t[1].shape[0] = N; + t[1].shape[1] = K; + t[1].stride[0] = K; + t[1].stride[1] = 1; + t[2].dtype = RAD_F32; + t[2].rank = 2; + t[2].shape[0] = M; + t[2].shape[1] = N; + t[2].stride[0] = yp; + t[2].stride[1] = 1; + RadParam p[4]{}; + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "N", RAD_P_INT, N }; + p[2] = { "K", RAD_P_INT, K }; + p[3].key = "dtype"; + p[3].kind = RAD_P_STR; + p[3].sval = "bf16"; + RadArgs a{}; + a.t = t; + a.n_t = 3; + a.p = p; + a.n_p = 4; + auto run = [&](const char* form, std::vector& y) { + y.assign((size_t)M * yp, -7.25f); + t[2].data = y.data(); + if (form) + setenv("RADIANCE_F32_GEMM_TILE", form, 1); + else + unsetenv("RADIANCE_F32_GEMM_TILE"); + return r4d_rad_gemm_nt_f32(&a, nullptr); + }; + std::vector legacy, got; + ++cases; + if (run("legacy", legacy) != RAD_OK) { + std::printf("FAIL legacy launch M=%d N=%d K=%d\n", M, N, K); + ++fails; + continue; + } + int bad = 0; + for (int r = 0; r < M; ++r) { + for (int c = 0; c < N; ++c) { + const float e = legacy_model(&x[(size_t)r * xp], &w[(size_t)c * K], K); + bad += std::memcmp(&e, &legacy[(size_t)r * yp + c], 4) != 0; + } + for (int c = N; c < yp; ++c) bad += legacy[(size_t)r * yp + c] != -7.25f; + } + if (bad) { + std::printf("FAIL legacy kernel against its model at M=%d N=%d K=%d: %d words\n", M, N, + K, bad); + ++fails; + } + for (const char* const* f = forms;; ++f) { + ++cases; + const int rc = run(*f, got); + const bool same = + rc == RAD_OK && std::memcmp(got.data(), legacy.data(), got.size() * 4) == 0; + if (!same) { + std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d)\n", *f ? *f : "default", M, N, + K, rc); + ++fails; + } + if (!*f) break; + } + } + unsetenv("RADIANCE_F32_GEMM_TILE"); + router_cases(rng, cases, fails); + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_fp8f32.cpp b/tests/r4d_emu/test_fp8f32.cpp new file mode 100644 index 00000000..e68543e5 --- /dev/null +++ b/tests/r4d_emu/test_fp8f32.cpp @@ -0,0 +1,110 @@ +/* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT + * emulator. The decode and row-tile forms (RADIANCE_FP8F32_FORM, each R x S x C and row count) must + * match the legacy 16x64 tile + * bit for bit: the same fragments, the same mma chain per 128-K block and the same fold order. + * Ragged row counts, pitched rows and a K that leaves the decode form's last wave group partly + * idle are covered; the output's pitch padding stays untouched. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include +#include +#include +#include +#include +#include + +static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = 2; + t.shape[0] = rows; + t.shape[1] = cols; + t.stride[0] = ld; + t.stride[1] = 1; + return t; +} + +int main() { + std::mt19937 rng(31); + std::normal_distribution nd(0.f, 1.f); + struct Shape { + int M, N, K; + }; + const Shape shapes[] = { { 1, 256, 512 }, { 6, 128, 1536 }, { 17, 256, 512 }, + { 48, 128, 512 }, { 70, 128, 384 }, { 130, 128, 256 }, + { 3, 128, 4096 } }; + const char* forms[] = { "decode", "decode1x4", "decode1x32", "decode2x8", + "decode3x16", "decode1x8x2", "decode1x4x4", "decode2x8x2", + "decode3x4x2", "decode2x4x4", "rows1", "rows2", + "rows4", nullptr }; + int fails = 0, cases = 0; + for (const Shape& sh : shapes) { + const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, yp = N + 8; + std::vector a((size_t)M * ap), w((size_t)N * K); + for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng)); + for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f); + std::vector as((size_t)M * kb), ws((size_t)(N / 128) * kb); + // Scales over twelve octaves: K blocks of very different weight cancel, so a changed + // summation order shows through the bf16 output. + std::uniform_real_distribution oct(-6.f, 6.f); + for (auto& v : as) v = std::exp2(oct(rng)); + for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f; + RadTensor t[7] = { mat(a.data(), RAD_F8E4M3, M, K, ap), + mat(as.data(), RAD_F32, M, kb, kb), + mat(w.data(), RAD_F8E4M3, N, K, K), + mat(ws.data(), RAD_F32, N / 128, kb, kb), + RadTensor{}, + RadTensor{}, + RadTensor{} }; + RadParam p[5]{}; + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "N", RAD_P_INT, N }; + p[2] = { "K", RAD_P_INT, K }; + p[3] = { "group", RAD_P_INT, 128 }; + p[4].key = "dtype"; + p[4].kind = RAD_P_STR; + p[4].sval = "fp8a8f32"; + auto run = [&](const char* form, std::vector& y) { + y.assign((size_t)M * yp, 0x7777); + t[4] = mat(y.data(), RAD_BF16, M, N, yp); + setenv("RADIANCE_FP8F32_FORM", form, 1); + RadArgs ar{}; + ar.t = t; + ar.n_t = 7; + ar.p = p; + ar.n_p = 5; + return r4d_rad_fp8_f32scale(&ar, nullptr); + }; + std::vector legacy, got; + ++cases; + if (run("legacy", legacy) != RAD_OK) { + std::printf("FAIL legacy M=%d N=%d K=%d\n", M, N, K); + ++fails; + continue; + } + int nonzero = 0; + for (int r = 0; r < M; ++r) + for (int c = 0; c < N; ++c) nonzero += legacy[(size_t)r * yp + c] != 0; + if (nonzero < M * N / 2) { + std::printf("FAIL legacy output mostly zero at M=%d\n", M); + ++fails; + } + for (const char* const* f = forms; *f; ++f) { + ++cases; + const int rc = run(*f, got); + if (rc != RAD_OK || got != legacy) { + size_t i = 0; + while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i; + std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d, first word %zu)\n", *f, M, N, K, + rc, i); + ++fails; + } + } + } + unsetenv("RADIANCE_FP8F32_FORM"); + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_kda.cpp b/tests/r4d_emu/test_kda.cpp new file mode 100644 index 00000000..65cdba48 --- /dev/null +++ b/tests/r4d_emu/test_kda.cpp @@ -0,0 +1,187 @@ +/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator. Every row and prefetch form + * must give the old one-row kernel's output and whole state buffer bit for bit, in all four modes: + * prefill per candidate and anchored, verify per candidate and anchored (after the replay of the + * accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten slot + * are mixed in. The GPU check of the same claim is r4d_selftest's kda_forms. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include +#include +#include +#include +#include +#include +#include + +static RadTensor tens(void* p, uint32_t dt, std::vector shape) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + t.shape[i] = shape[i]; + t.stride[i] = st; + st *= shape[i]; + } + return t; +} +static uint16_t f2b(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +struct Case { + const char* name; + const char* mode; + bool anchor; + int64_t width; + std::vector cu, idx, accepted, init; + std::vector> counts; +}; + +int main() { + std::mt19937 rng(41); + std::uniform_real_distribution u(-1.f, 1.f); + const int64_t H = 2, D = 128, slots = 16, tokens = 9; + std::vector state0((size_t)(slots * H * D * D)), alog((size_t)H), bias((size_t)(H * D)); + for (auto& v : state0) v = u(rng); + for (auto& v : alog) v = 0.5f * u(rng); + for (auto& v : bias) v = u(rng); + std::vector in[5]; + for (int i = 0; i < 5; ++i) { + in[i].resize((size_t)(tokens * H * (i == 4 ? 1 : D))); + for (auto& v : in[i]) v = f2b((i >= 3 ? 2.f : 1.f) * u(rng)); + } + const std::vector cases = { + { "prefill, per candidate", + "prefill", + false, + 1, + { 0, 4, 4, 9 }, + { 3, 4, -1 }, + { 1, 1, 1 }, + { 0, 1, 1 }, + {} }, + { "prefill, anchored", + "prefill", + true, + 2, + { 0, 5, 9 }, + { 1, 2, 3, 4 }, + { 1, 1 }, + { 1, 0 }, + {} }, + { "verify, per candidate", + "verify", + false, + 4, + { 0, 4, 7, 9 }, + { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1 }, + { 3, 2, 1 }, + { 1, 0, 1 }, + {} }, + { "verify, anchored", + "verify", + true, + 4, + { 0, 4, 7, 9 }, + { 1, 9, 5, 9, 2, 9, 6, 9, 3, 9, 7, 9 }, + { 3, 2, 1 }, + { 1, 1, 0 }, + { { 5, 4.f }, { 6, 3.f }, { 7, 0.f } } }, + }; + struct Form { + const char* rows; + const char* prefetch; + }; + const Form forms[] = { { "1", "1" }, { "2", "1" }, { "4", "1" }, + { "1", "0" }, { "2", "0" }, { "4", "0" } }; + int fails = 0, checks = 0; + for (const Case& c : cases) { + std::vector start = state0; + for (const auto& sc : c.counts) + for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second; + const int64_t seqs = (int64_t)c.cu.size() - 1; + std::vector idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init; + auto run = [&](std::vector& out, std::vector& state) { + out.assign((size_t)(tokens * H * D), 0x7777); + state = start; + RadTensor t[13] = { tens(in[0].data(), RAD_BF16, { tokens, H, D }), + tens(in[1].data(), RAD_BF16, { tokens, H, D }), + tens(in[2].data(), RAD_BF16, { tokens, H, D }), + tens(in[3].data(), RAD_BF16, { tokens, H, D }), + tens(in[4].data(), RAD_BF16, { tokens, H }), + tens(alog.data(), RAD_F32, { H }), + tens(bias.data(), RAD_F32, { H * D }), + tens(state.data(), RAD_F32, { slots, H, D, D }), + tens(idx.data(), RAD_I32, { seqs, c.width }), + tens(cu.data(), RAD_I32, { seqs + 1 }), + tens(acc.data(), RAD_I32, { seqs }), + tens(init.data(), RAD_I32, { seqs }), + tens(out.data(), RAD_BF16, { tokens, H, D }) }; + RadParam p[10]{}; + p[0] = { "heads", RAD_P_INT, H }; + p[1] = { "head_k", RAD_P_INT, D }; + p[2] = { "head_v", RAD_P_INT, D }; + p[3].key = "lower_bound"; + p[3].kind = RAD_P_F64; + p[3].dval = -5; + p[4].key = "scale"; + p[4].kind = RAD_P_F64; + p[4].dval = 1.0 / std::sqrt(128.0); + p[5].key = "l2_eps"; + p[5].kind = RAD_P_F64; + p[5].dval = 1e-6; + p[6].key = "mode"; + p[6].kind = RAD_P_STR; + p[6].sval = c.mode; + p[7].key = "state_form"; + p[7].kind = RAD_P_STR; + p[7].sval = c.anchor ? "anchor" : "per_candidate"; + p[8].key = "dtype"; + p[8].kind = RAD_P_STR; + p[8].sval = "bf16"; + RadArgs a{}; + a.t = t; + a.n_t = 13; + a.p = p; + a.n_p = 9; + return r4d_rad_kda_update(&a, nullptr); + }; + std::vector ref_out, out; + std::vector ref_state, state; + setenv("RADIANCE_KDA_FORM", "old", 1); + if (run(ref_out, ref_state) != RAD_OK) { + std::printf("FAIL %s: old form refused\n", c.name); + ++fails; + continue; + } + unsetenv("RADIANCE_KDA_FORM"); + bool written = false; + for (size_t i = 0; i < ref_out.size(); ++i) written = written || ref_out[i] != 0x7777; + if (!written) { + std::printf("FAIL %s: the old form wrote no output\n", c.name); + ++fails; + } + for (const Form& f : forms) { + setenv("RADIANCE_KDA_ROWS", f.rows, 1); + setenv("RADIANCE_KDA_PREFETCH", f.prefetch, 1); + ++checks; + const bool same = run(out, state) == RAD_OK && out == ref_out && + std::memcmp(state.data(), ref_state.data(), state.size() * 4) == 0; + if (!same) { + ++fails; + std::printf("FAIL %s, %s rows a wave, prefetch %s: differs from the old form\n", + c.name, f.rows, f.prefetch); + } + } + unsetenv("RADIANCE_KDA_ROWS"); + unsetenv("RADIANCE_KDA_PREFETCH"); + } + std::printf("kda_update forms against the old kernel: %d of %d bit-identical\n", checks - fails, + checks); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_mhc.cpp b/tests/r4d_emu/test_mhc.cpp new file mode 100644 index 00000000..82bd77e6 --- /dev/null +++ b/tests/r4d_emu/test_mhc.cpp @@ -0,0 +1,283 @@ +/* tests/r4d_emu: GLM's mHC read split by residual chunks (r4d_mhc.hip) on the host SIMT emulator. + * Each rank's mhc_pre_partial over its chunks, the partials joined row by row as the + * row-interleaved all_gather lays them out, then mhc_pre_finish, must give mhc_pre's x, post and + * comb bit for bit, under each of mhc_pre's kernel switches; the partial matrix's padding slots + * are zero. Every form is also held to the old dispatch, bit for bit. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include +#include +#include +#include +#include +#include + +static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = 2; + t.shape[0] = rows; + t.shape[1] = cols; + t.stride[0] = ld; + t.stride[1] = 1; + return t; +} +static RadTensor vec(void* p, int64_t n) { + RadTensor t{}; + t.data = p; + t.dtype = RAD_F32; + t.rank = 1; + t.shape[0] = n; + t.stride[0] = 1; + return t; +} + +int main() { + std::mt19937 rng(23); + std::normal_distribution nd(0.f, 1.f); + const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; + std::vector fn((size_t)(mix * W)), scale = { 0.7f, 0.9f, 1.1f }, base((size_t)mix); + for (auto& v : fn) v = nd(rng) * 0.01f; + for (auto& v : base) v = nd(rng) * 0.5f; + struct Form { + const char* env; + const char* value; + }; + const Form forms[] = { { nullptr, nullptr }, + { "RADIANCE_MHC_PREFILL_COEFF4", "0" }, + { "RADIANCE_MHC_PREFILL_ROWS4", "0" }, + { "RADIANCE_MHC_PREFILL_WARP", "0" } }; + int fails = 0, cases = 0; + for (int64_t rows : { 1, 5, 37 }) { + const int64_t hp = W + 6, xp = n + 2; + std::vector h((size_t)(rows * hp)); + for (auto& v : h) v = f2b(nd(rng)); + for (const Form& f : forms) { + if (f.env) setenv(f.env, f.value, 1); + RadParam coef[8]{}; + coef[0] = { "M", RAD_P_INT, rows }; + coef[1] = { "n", RAD_P_INT, n }; + coef[2] = { "hc", RAD_P_INT, hc }; + coef[3] = { "iterations", RAD_P_INT, 20 }; + coef[4].key = "eps"; + coef[4].kind = RAD_P_F64; + coef[4].dval = 1e-5; + coef[5].key = "hc_eps"; + coef[5].kind = RAD_P_F64; + coef[5].dval = 1e-6; + coef[6].key = "dtype"; + coef[6].kind = RAD_P_STR; + coef[6].sval = "bf16"; + std::vector x((size_t)(rows * xp), 0x7777); + std::vector post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc)); + RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp), + mat(fn.data(), RAD_F32, mix, W, W), + vec(scale.data(), 3), + vec(base.data(), mix), + mat(x.data(), RAD_BF16, rows, n, xp), + mat(post.data(), RAD_F32, rows, hc, hc), + mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadArgs a{}; + a.t = t; + a.n_t = 7; + a.p = coef; + a.n_p = 7; + if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) { + std::printf("FAIL mhc_pre M=%lld\n", (long long)rows); + ++fails; + continue; + } + for (int world : { 2, 4, 8 }) { + ++cases; + const int64_t mine = total / world; + std::vector gathered((size_t)(rows * total * S)); + bool padded = true, launched = true; + for (int rank = 0; rank < world; ++rank) { + std::vector part((size_t)(rows * mine * S), 7.0f); + RadTensor pt[3] = { t[0], t[1], + mat(part.data(), RAD_F32, rows, mine * S, mine * S) }; + RadParam pp[7]{}; + pp[0] = { "M", RAD_P_INT, rows }; + pp[1] = { "n", RAD_P_INT, n }; + pp[2] = { "hc", RAD_P_INT, hc }; + pp[3] = { "chunk", RAD_P_INT, 2048 }; + pp[4] = { "first", RAD_P_INT, rank * mine }; + pp[5] = { "chunks", RAD_P_INT, mine }; + pp[6].key = "dtype"; + pp[6].kind = RAD_P_STR; + pp[6].sval = "bf16"; + RadArgs pa{}; + pa.t = pt; + pa.n_t = 3; + pa.p = pp; + pa.n_p = 7; + launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK; + for (int64_t r = 0; r < rows; ++r) { + for (int64_t c = 0; c < mine; ++c) + for (int64_t j = mix + 1; j < S; ++j) + padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f; + std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)], + &part[(size_t)(r * mine * S)], (size_t)(mine * S * 4)); + } + } + std::vector x2((size_t)(rows * xp), 0x7777); + std::vector post2(post.size()), comb2(comb.size()); + RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S), + t[0], + t[2], + t[3], + mat(x2.data(), RAD_BF16, rows, n, xp), + mat(post2.data(), RAD_F32, rows, hc, hc), + mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadParam fp[8]; + std::memcpy(fp, coef, sizeof coef); + fp[6] = { "chunk", RAD_P_INT, 2048 }; + fp[7].key = "dtype"; + fp[7].kind = RAD_P_STR; + fp[7].sval = "bf16"; + RadArgs fa{}; + fa.t = ft; + fa.n_t = 7; + fa.p = fp; + fa.n_p = 8; + launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK; + const bool same = launched && x2 == x && + std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 && + std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0; + if (!same || !padded) { + std::printf("FAIL M=%lld world %d %s%s%s: %s\n", (long long)rows, world, + f.env ? f.env : "default", f.env ? "=" : "", f.env ? f.value : "", + !launched ? "launch" + : !padded ? "padding" + : "differs"); + ++fails; + } + } + if (f.env) unsetenv(f.env); + } + } + /* Every form against the old dispatch (one-wave finish from 32 rows, scalar mix and read + * below, scalar-row and rows4 partials, the per-output mhc_post) on 16-byte rows, where the + * vector paths run: mhc_pre's x, post and comb, mhc_pre_partial's matrix and mhc_post's + * output, bit for bit. */ + struct Pin { + const char* what; + const char* finish; + const char* vec; + const char* prow; + }; + const Pin pins[] = { { "rule", nullptr, nullptr, nullptr }, + { "finish scalar", "scalar", nullptr, nullptr }, + { "partials four-slot, 1 row a wave", nullptr, "1", "1" }, + { "partials four-slot, 2 rows a wave", nullptr, "1", "2" }, + { "partials four-slot, 4 rows a wave", nullptr, "1", "4" } }; + auto pin = [](const char* k, const char* v) { + if (v) + setenv(k, v, 1); + else + unsetenv(k); + }; + for (int64_t rows : { 1, 5, 16, 37, 64 }) { + std::vector h((size_t)(rows * W)), y((size_t)(rows * n)); + for (auto& v : h) v = f2b(nd(rng)); + for (auto& v : y) v = f2b(nd(rng)); + RadParam coef[7]{}; + coef[0] = { "M", RAD_P_INT, rows }; + coef[1] = { "n", RAD_P_INT, n }; + coef[2] = { "hc", RAD_P_INT, hc }; + coef[3] = { "iterations", RAD_P_INT, 20 }; + coef[4].key = "eps"; + coef[4].kind = RAD_P_F64; + coef[4].dval = 1e-6; + coef[5].key = "hc_eps"; + coef[5].kind = RAD_P_F64; + coef[5].dval = 1e-6; + coef[6].key = "dtype"; + coef[6].kind = RAD_P_STR; + coef[6].sval = "bf16"; + struct Out { + std::vector x, o; + std::vector p, c, part; + }; + auto run = [&](Out* r) { + r->x.assign((size_t)(rows * n), 0x7777); + r->o.assign((size_t)(rows * W), 0x7777); + r->p.assign((size_t)(rows * hc), 0); + r->c.assign((size_t)(rows * hc * hc), 0); + r->part.assign((size_t)(rows * total * S), 7.0f); + RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, W), + mat(fn.data(), RAD_F32, mix, W, W), + vec(scale.data(), 3), + vec(base.data(), mix), + mat(r->x.data(), RAD_BF16, rows, n, n), + mat(r->p.data(), RAD_F32, rows, hc, hc), + mat(r->c.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadArgs a{}; + a.t = t; + a.n_t = 7; + a.p = coef; + a.n_p = 7; + bool okay = r4d_rad_mhc_pre(&a, nullptr) == RAD_OK; + RadTensor pt[3] = { t[0], t[1], + mat(r->part.data(), RAD_F32, rows, total * S, total * S) }; + RadParam pp[7]{}; + pp[0] = { "M", RAD_P_INT, rows }; + pp[1] = { "n", RAD_P_INT, n }; + pp[2] = { "hc", RAD_P_INT, hc }; + pp[3] = { "chunk", RAD_P_INT, 2048 }; + pp[4] = { "first", RAD_P_INT, 0 }; + pp[5] = { "chunks", RAD_P_INT, total }; + pp[6].key = "dtype"; + pp[6].kind = RAD_P_STR; + pp[6].sval = "bf16"; + RadArgs pa{}; + pa.t = pt; + pa.n_t = 3; + pa.p = pp; + pa.n_p = 7; + okay = okay && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK; + RadTensor ot[5] = { mat(y.data(), RAD_BF16, rows, n, n), t[0], t[5], t[6], + mat(r->o.data(), RAD_BF16, rows, W, W) }; + RadArgs oa{}; + oa.t = ot; + oa.n_t = 5; + oa.p = coef; + oa.n_p = 7; + return okay && r4d_rad_mhc_post(&oa, nullptr) == RAD_OK; + }; + Out ref, got; + pin("RADIANCE_MHC_FINISH", "old"); + pin("RADIANCE_MHC_PARTIAL_VEC", "0"); + pin("RADIANCE_MHC_POST_VEC", "0"); + const bool ref_ok = run(&ref); + pin("RADIANCE_MHC_POST_VEC", nullptr); + for (const Pin& f : pins) { + ++cases; + pin("RADIANCE_MHC_FINISH", f.finish); + pin("RADIANCE_MHC_PARTIAL_VEC", f.vec); + pin("RADIANCE_MHC_PARTIAL_ROWS", f.prow); + const bool launched = ref_ok && run(&got); + const char* bad = !launched ? "launch" + : got.x != ref.x ? "x" + : std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post" + : std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb" + : std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4) + ? "partials" + : got.o != ref.o ? "mhc_post" + : nullptr; + if (bad) { + std::printf("FAIL M=%lld %s against the old dispatch: %s differs\n", + (long long)rows, f.what, bad); + ++fails; + } + } + for (const char* k : + { "RADIANCE_MHC_FINISH", "RADIANCE_MHC_PARTIAL_VEC", "RADIANCE_MHC_PARTIAL_ROWS" }) + unsetenv(k); + } + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_mla.cpp b/tests/r4d_emu/test_mla.cpp new file mode 100644 index 00000000..fd8d5330 --- /dev/null +++ b/tests/r4d_emu/test_mla.cpp @@ -0,0 +1,408 @@ +/* Drives libr4d's MLA matrix row (r4d_mla.hip, attend_matrix) through the SIMT emulator and checks + * every output element against an f64 softmax over each row's own table. The cases put the paired + * tile (eight heads of two neighbouring rows) on the tables it meets in serving: a prefill chunk + * whose rows share one table, and rows past the DSA budget, where each row selects its own top + * blocks and neighbours share most blocks but rarely a table position. The conflict counters + * (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" void r4d_mla_matrix_pin_form(int form); +extern "C" void r4d_mla_matrix_stats(unsigned long long* out); + +namespace { + +constexpr int D = 512, BS = 4; + +enum class Fill { prefill, topk, ragged, repeat }; + +struct Case { + std::string name; + int rows, heads, blocks; + Fill fill; + int swaps = 0; /* topk: blocks exchanged between neighbouring rows */ + int context = 0; /* topk: tokens of the sequence the rows end */ + bool scratch = false; /* lets the launcher split the history */ + int form = 0; /* r4d_mla_matrix_pin_form */ + int expect_second = -1; /* positional pairing: 0 no second pass, 1 some, -1 either */ + bool bitwise_a = true; /* the union's request r equals the positional pairing's bit for bit */ + bool bitwise_all = false; /* both requests do (the tables agree position by position) */ + bool union_falls_back = false; /* the table is wider than the union's lists */ +}; + +/* Tables as qsa_select emits them past its budget: for the queries at positions context-rows .. + * context-1 of one sequence, each row the top blocks-1 of its complete blocks, the strictly higher + * ones in block order and a short tie run after them, then the partial page. Row r's choice is row + * r-1's with `swaps` members exchanged for non-members. Pages are a fixed shuffle of the blocks. */ +void topk_tables(int rows, int blocks, int context, int swaps, std::mt19937& rng, + std::vector& bt, std::vector& len, int& pages) { + const int topk = blocks - 1, universe = context / BS + 1, ties = std::min(4, topk); + pages = universe; + std::vector page(universe); + for (int i = 0; i < universe; ++i) page[i] = i; + std::shuffle(page.begin(), page.end(), rng); + std::vector in(universe, 0); + std::vector members; + auto tie_rank = [](int b) { return (uint32_t)b * 2654435761u ^ 0x9e3779b9u; }; + bt.assign((size_t)rows * blocks, -1); + len.assign(rows, 0); + for (int r = 0; r < rows; ++r) { + const int p = context - rows + r, n = (p + 1) / BS; + if (n <= topk) { + for (int b = 0; b < n; ++b) + if (!in[b]) { + in[b] = 1; + members.push_back(b); + } + } else { + while ((int)members.size() < topk) { + const int b = (int)(rng() % (unsigned)n); + if (!in[b]) { + in[b] = 1; + members.push_back(b); + } + } + for (int s = 0; s < swaps; ++s) { + int add; + do add = (int)(rng() % (unsigned)n); + while (in[add]); + const size_t drop = rng() % members.size(); + in[members[drop]] = 0; + members[drop] = add; + in[add] = 1; + } + } + std::vector order(members); + std::sort(order.begin(), order.end()); + if (n > topk) { + std::vector tied(order); + std::sort(tied.begin(), tied.end(), + [&](int a, int b) { return tie_rank(a) < tie_rank(b); }); + tied.resize(ties); + std::sort(tied.begin(), tied.end()); + order.erase(std::remove_if( + order.begin(), order.end(), + [&](int b) { return std::binary_search(tied.begin(), tied.end(), b); }), + order.end()); + order.insert(order.end(), tied.begin(), tied.end()); + } + int out = 0; + for (int b : order) bt[(size_t)r * blocks + out++] = page[b]; + if ((p + 1) % BS) bt[(size_t)r * blocks + out++] = page[n]; + len[r] = out ? (out - 1) * BS + p % BS + 1 : 0; + } +} + +int run(const Case& c, std::mt19937& rng) { + const int M = c.rows, H = c.heads, B = c.blocks; + std::vector bt, len; + int pages = 0; + if (c.fill == Fill::topk) { + topk_tables(M, B, c.context, c.swaps, rng, bt, len, pages); + } else if (c.fill == Fill::prefill) { + /* one sequence, its rows the last M positions of the capacity, one table */ + pages = B + 1; + bt.assign((size_t)M * B, -1); + len.assign(M, 0); + for (int r = 0; r < M; ++r) { + for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = (b * 7 + 3) % pages; + len[r] = B * BS - M + r + 1; + } + } else if (c.fill == Fill::repeat) { + /* every page twice in a row's table and shifted by one entry from row to row, so a page + * repeats within a table and between the pair */ + pages = M + B; + bt.assign((size_t)M * B, -1); + len.assign(M, 0); + for (int r = 0; r < M; ++r) { + for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = ((b + r) / 2 * 5) % pages; + len[r] = B * BS - r % 3; + } + } else { + /* every row its own scattered table, with holes and out-of-range pages */ + pages = M * B; + bt.assign((size_t)M * B, -1); + len.assign(M, 0); + for (int r = 0; r < M; ++r) { + for (int b = 0; b < B; ++b) + bt[(size_t)r * B + b] = b % 17 == 3 ? -1 + : b % 19 == 5 ? pages + 3 + : (b * 7 + r * 11) % pages; + len[r] = r % 5 == 4 ? 0 : B * BS - 1 - r % 7; + } + } + std::normal_distribution nrm(0.f, 1.f); + std::vector qb((size_t)M * H * D), kvb((size_t)pages * BS * D); + for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng)); + for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng)); + std::vector out((size_t)M * H * D, 0xffff); + + auto tens = [](void* p, uint32_t dt, std::vector shape) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + t.shape[i] = shape[i]; + t.stride[i] = st; + st *= shape[i]; + } + return t; + }; + RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }), + tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }), + tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }), + tens(out.data(), RAD_BF16, { M, H, D }) }; + std::vector p; + auto pi = [&](const char* k, long long v) { + RadParam x{}; + x.key = k; + x.kind = RAD_P_INT; + x.ival = v; + p.push_back(x); + }; + auto pf = [&](const char* k, double v) { + RadParam x{}; + x.key = k; + x.kind = RAD_P_F64; + x.dval = v; + p.push_back(x); + }; + pi("M", M); + pi("latent_dim", D); + pi("heads", H); + pi("blocks", B); + pi("block_size", BS); + const double scale = 0.0625; + pf("scale", scale); + RadArgs a{}; + a.t = t; + a.n_t = 5; + a.p = p.data(); + a.n_p = (int)p.size(); + std::vector scratch; + if (c.scratch) { + const int64_t need = r4d_rad_mla_attn_matrix_scratch(&a); + scratch.assign((size_t)need + 16, 0); + a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15); + a.scratch_bytes = need; + } + + /* the f64 reference */ + std::vector want((size_t)M * H * D); + std::vector sc; + for (int r = 0; r < M; ++r) + for (int h = 0; h < H; ++h) { + const int live = std::min(std::max(len[r], 0), B * BS); + sc.assign(live, -INFINITY); + double mx = -INFINITY; + auto row_of = [&](int j) -> const uint16_t* { + const int pg = bt[(size_t)r * B + j / BS]; + return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr; + }; + const uint16_t* qr = &qb[((size_t)r * H + h) * D]; + for (int j = 0; j < live; ++j) { + const uint16_t* k = row_of(j); + if (!k) continue; + double dot = 0; + for (int d = 0; d < D; ++d) + dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]); + sc[j] = dot * scale; + mx = std::max(mx, sc[j]); + } + std::vector acc(D, 0.0); + double sum = 0; + for (int j = 0; j < live; ++j) { + if (sc[j] == -INFINITY) continue; + const double w = std::exp(sc[j] - mx); + sum += w; + const uint16_t* k = row_of(j); + for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]); + } + for (int d = 0; d < D; ++d) + want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0; + } + + /* Both pairings on the same operands: the positional one (RADIANCE_MLA_PAIR=pos) and the + * union, which must never take a second pass. */ + const bool paired = H % 16 == 8; + std::vector by_pos; + int fails = 0; + for (const char* pairing : { "pos", "union" }) { + if (!paired && !std::strcmp(pairing, "union")) break; + setenv("RADIANCE_MLA_PAIR", pairing, 1); + std::fill(out.begin(), out.end(), 0xffff); + unsigned long long stats[3]; + r4d_mla_matrix_stats(stats); + r4d_mla_matrix_pin_form(c.form); + const int rc = r4d_rad_mla_attn_matrix(&a, nullptr); + r4d_mla_matrix_pin_form(0); + r4d_mla_matrix_stats(stats); + unsetenv("RADIANCE_MLA_PAIR"); + if (rc != RAD_OK) { + std::printf("%-40s %-5s launch returned %d\n", c.name.c_str(), pairing, rc); + ++fails; + continue; + } + double max_err = 0; + long bad = 0; + for (size_t i = 0; i < out.size(); ++i) { + const float got = rad_bf16_to_f32(out[i]); + const double e = std::fabs(got - want[i]); + if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad; + if (std::isfinite(got)) max_err = std::max(max_err, e); + } + bool ok = bad == 0; + std::string note; + const bool by_page = !std::strcmp(pairing, "union"); + if (!by_page) { + by_pos = out; + if (c.expect_second >= 0 && (stats[1] > 0) != (c.expect_second == 1)) { + note += + c.expect_second ? " (expected a second pass)" : " (expected no second pass)"; + ok = false; + } + } else { + if ((stats[1] > 0) != c.union_falls_back) { + note += c.union_falls_back ? " (expected the positional fallback)" + : " (the union took a second pass)"; + ok = false; + } + /* Request r of each pair walks its own table in its own order, as the positional + * pairing does, so at one split it must agree to the bit; r+1 sums in another order. */ + size_t first_diff_a = 0, diff_b = 0; + double max_ab = 0; + for (int r = 0; r < M; ++r) + for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) { + if (out[i] == by_pos[i]) continue; + if (r % 2 == 0) + ++first_diff_a; + else + ++diff_b; + max_ab = std::max(max_ab, (double)std::fabs(rad_bf16_to_f32(out[i]) - + rad_bf16_to_f32(by_pos[i]))); + } + char buf[160]; + std::snprintf(buf, sizeof buf, " vs pos: %zu/%zu differ (r/r+1), max abs %.2e", + first_diff_a, diff_b, max_ab); + note += buf; + if (c.bitwise_a && first_diff_a) { + note += " (request r differs)"; + ok = false; + } + if (c.bitwise_all && diff_b) { + note += " (request r+1 differs)"; + ok = false; + } + } + std::printf("%-40s %-5s M %3d H %2d blocks %3d passes %5llu raster %5llu second %5llu " + "max_abs %.2e bad %ld%s %s\n", + c.name.c_str(), pairing, M, H, B, stats[0], stats[2], stats[1], max_err, bad, + note.c_str(), ok ? "PASS" : "FAIL"); + fails += !ok; + } + return fails; +} + +/* The launcher prints the running totals every 1024th counted launch and must leave them + * standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */ +int periodic_report() { + std::vector q(2 * 8 * D, 0x3f80), kv(4 * BS * D, 0x3f80), out(2 * 8 * D); + std::vector bt = { 0, 1 }, len = { 4, 3 }; + RadTensor t[5]{}; + auto set = [](RadTensor& x, void* p, uint32_t dt, std::vector shape) { + x.data = p; + x.dtype = dt; + x.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + x.shape[i] = shape[i]; + x.stride[i] = st; + st *= shape[i]; + } + }; + set(t[0], q.data(), RAD_BF16, { 2, 8, D }); + set(t[1], kv.data(), RAD_BF16, { 4, 1, BS, D }); + set(t[2], bt.data(), RAD_I32, { 2, 1 }); + set(t[3], len.data(), RAD_I32, { 2 }); + set(t[4], out.data(), RAD_BF16, { 2, 8, D }); + RadParam p[6]{}; + const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" }; + const long long vals[5] = { 2, D, 8, 1, BS }; + for (int i = 0; i < 5; ++i) { + p[i].key = keys[i]; + p[i].kind = RAD_P_INT; + p[i].ival = vals[i]; + } + p[5].key = "scale"; + p[5].kind = RAD_P_F64; + p[5].dval = 0.0625; + RadArgs a{}; + a.t = t; + a.n_t = 5; + a.p = p; + a.n_p = 6; + unsigned long long stats[3]; + r4d_mla_matrix_stats(stats); + for (int i = 0; i < 1024; ++i) + if (r4d_rad_mla_attn_matrix(&a, nullptr) != RAD_OK) { + std::printf("periodic report: launch failed\n"); + return 1; + } + r4d_mla_matrix_stats(stats); + const bool ok = stats[0] == 1024 && stats[2] == 1024 && stats[1] == 0; + std::printf("periodic report: %llu passes over %llu raster chunks after 1024 launches %s\n", + stats[0], stats[2], ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} + +} // namespace + +int main(int argc, char** argv) { + setenv("RADIANCE_MLA_CONFLICT_STATS", "1", 1); + /* name, rows, heads, blocks, fill, swaps, context, scratch, form, expect_second, bitwise_a, + * bitwise_all, union_falls_back */ + std::vector cases = { + { "prefill, one table", 8, 8, 65, Fill::prefill, 0, 0, false, 0, 0, true, true }, + { "prefill, odd rows, split", 7, 8, 33, Fill::prefill, 0, 0, true, 0, 0, true, true }, + { "prefill, 16 heads", 4, 16, 33, Fill::prefill, 0, 0, false, 0, 0 }, + { "prefill, 24 heads (three pairs)", 5, 24, 17, Fill::prefill, 0, 0, false, 0, 0, true, + true }, + { "topk d=0", 8, 8, 65, Fill::topk, 0, 600, false, 0, 0, true, true }, + { "topk d=4", 8, 8, 65, Fill::topk, 4, 600, false, 0, 1 }, + { "topk d=16", 8, 8, 65, Fill::topk, 16, 600, false, 0, 1 }, + { "topk d=64 (disjoint neighbours)", 6, 8, 65, Fill::topk, 64, 600, false, 0, 1 }, + { "topk d=16, 513 blocks", 4, 8, 513, Fill::topk, 16, 8192, false, 0, 1 }, + /* a split cuts the union's walk elsewhere than the positional raster */ + { "topk d=4, odd rows, split", 5, 8, 33, Fill::topk, 4, 400, true, 0, 1, false }, + { "topk d=4, element load", 4, 8, 33, Fill::topk, 4, 400, false, 1, 1 }, + { "topk d=4, 16 heads", 4, 16, 33, Fill::topk, 4, 400, false, 0, 0 }, + { "topk, table past the union's lists", 4, 8, 600, Fill::topk, 16, 4000, false, 0, 1, true, + true, true }, + { "repeated pages", 6, 8, 33, Fill::repeat, 0, 0, false, 0, -1 }, + { "repeated pages, split", 3, 8, 33, Fill::repeat, 0, 0, true, 0, -1, false }, + { "ragged, holes and bad pages", 7, 8, 17, Fill::ragged, 0, 0, false, 0, -1 }, + { "ragged, split", 3, 8, 17, Fill::ragged, 0, 0, true, 0, -1, false }, + }; + const char* filter = argc > 1 ? argv[1] : nullptr; + int fails = 0; + for (size_t i = 0; i < cases.size(); ++i) { + if (filter && cases[i].name.find(filter) == std::string::npos) continue; + std::mt19937 rng(20261018u + (unsigned)i); + fails += run(cases[i], rng); + } + if (!filter) fails += periodic_report(); + std::printf("%d failure(s)\n", fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_moefuse.cpp b/tests/r4d_emu/test_moefuse.cpp new file mode 100644 index 00000000..eb7a1da5 --- /dev/null +++ b/tests/r4d_emu/test_moefuse.cpp @@ -0,0 +1,614 @@ +/* tests/r4d_emu: GLM's decode fusions of the MoE block (r4d_glm.hip) on the host SIMT emulator, + * each byte for byte against the separate launches it replaces. + * + * router_sigmoid_topk_scatter against router_sigmoid_topk (the emulated kernel), then moe_scatter's + * stable counting sort over its ids written out here, then the `fill` of the shared gate with 1: + * random, tied and NaN ranks (a row with fewer finite ranks than top_k selects expert 0 for its + * empty slots, and the sort takes those as written), slices and protected experts, rows past 64 + * wrapping over the waves, the sort's bound and its refusal past it. Pitch padding, guards past + * every output and the gate's untouched rows show an overrun. + * + * swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 (both emulated): codes, + * scales and the optional bf16 product, at GLM's widths and ragged ones, with values far past the + * clamp, exactly on it and one bf16 step beyond, all-zero groups (scale 1), a gate so negative the + * sigmoid underflows, and NaN and infinite inputs. + * + * moe_scatter_inv and moe_gather_inv: the small sort's kernel with the inverse against itself + * without, and the inverse against the table the gather builds from `sorted`; then moe_gather's + * kernel reading that inverse against its self-scan (T <= 512) or the prepass's table (above), at + * GLM's f32 routing weights and bf16 ones, with the ungated shared arm, a sigmoid-gated one and + * none, and slices that drop slots. moe_scatter's three-pass form (T > 1024) is not here: its + * kernels take dynamic LDS through `extern __shared__`, which the emulator cannot give; the card + * checks it (r4d_selftest --case moe_scatter_inv_i32). */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include "r4d_moe_sort.h" +#include "r4d_moe_gather.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int32_t kPoison = -77; +constexpr uint16_t kGatePoison = 0x7e57; + +/* moe_scatter's contract: slot i = token * top_k + slot goes to its expert's run in ascending i; + * an expert outside the slice drops the slot; protected experts are placed last in list order; + * sorted rows past the live count are -1. */ +struct SortModel { + std::vector sorted, off, cnt; +}; +int32_t place_of(int32_t e, int nl, const std::vector& prot) { + int32_t below = 0; + for (size_t j = 0; j < prot.size(); ++j) { + if (prot[j] == e) return nl - (int32_t)prot.size() + (int32_t)j; + below += prot[j] < e; + } + return e - below; +} +SortModel sort_model(const std::vector& ids, int M, int k, int ip, int nl, int base, + const std::vector& prot) { + const int T = M * k; + std::vector place((size_t)T); + SortModel s; + s.cnt.assign((size_t)nl, 0); + s.off.assign((size_t)nl + 1, 0); + s.sorted.assign((size_t)T, -1); + for (int i = 0; i < T; ++i) { + const int32_t e = ids[(size_t)(i / k) * ip + i % k] - base; + place[(size_t)i] = e >= 0 && e < nl ? place_of(e, nl, prot) : -1; + if (place[(size_t)i] >= 0) ++s.cnt[(size_t)place[(size_t)i]]; + } + for (int e = 0; e < nl; ++e) s.off[(size_t)e + 1] = s.off[(size_t)e] + s.cnt[(size_t)e]; + std::vector seen((size_t)nl, 0); + for (int i = 0; i < T; ++i) + if (place[(size_t)i] >= 0) { + const int32_t e = place[(size_t)i]; + s.sorted[(size_t)(s.off[(size_t)e] + seen[(size_t)e]++)] = i; + } + return s; +} + +/* The table the gather builds from `sorted` (gather_kernel's self-scan, or its prepass): slot + * sorted[p] at row p, every other slot -1. */ +std::vector inverse_of(const std::vector& sorted) { + std::vector inv(sorted.size(), -1); + for (size_t p = 0; p < sorted.size(); ++p) + if (sorted[p] >= 0) inv[(size_t)sorted[p]] = (int32_t)p; + return inv; +} + +/* moe_scatter's small-form kernel (r4d_moe_sort.h) over contiguous ids, with or without the + * inverse. */ +struct Scatter { + int rc = RAD_OK; + std::vector sorted, off, cnt, inv; +}; +Scatter scatter_kernel(const std::vector& ids, int nl, int base, const char* protect, + bool with_inv) { + const int T = (int)ids.size(); + Scatter s; + s.sorted.assign((size_t)T, kPoison); + s.off.assign((size_t)nl + 1, kPoison); + s.cnt.assign((size_t)nl, kPoison); + s.inv.assign((size_t)T, kPoison); + RadParam pp{}; + pp.key = "protect"; + pp.kind = RAD_P_STR; + pp.sval = protect; + RadArgs pa{}; + pa.p = &pp; + pa.n_p = protect ? 1 : 0; + r4d_moesort::Protect prot; + s.rc = r4d_moesort::protect_of(&pa, nl, &prot); + if (s.rc != RAD_OK) return s; + if (with_inv) + R4D_EMIT(nullptr, (r4d_moesort::scatter_small_kernel), dim3(1), dim3(256), 0, + ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl, + (int32_t)base, prot, s.inv.data()); + else + R4D_EMIT(nullptr, (r4d_moesort::scatter_small_kernel), dim3(1), dim3(256), 0, + ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl, + (int32_t)base, prot, (int32_t*)nullptr); + return s; +} + +struct RouterShape { + int M, ne, k, norm; + int mode; /* 0 random, 1 tied ranks, 2 NaN rows */ + int nl, base; /* the slice: nl 0 is the whole router */ + const char* protect; + bool gate; +}; + +void router_scatter_cases(std::mt19937& rng, int& cases, int& fails) { + const RouterShape shapes[] = { + { 1, 288, 8, 1, 0, 0, 0, nullptr, true }, { 2, 288, 8, 1, 0, 0, 0, nullptr, true }, + { 6, 288, 8, 1, 0, 0, 0, nullptr, true }, { 8, 288, 8, 1, 1, 0, 0, nullptr, true }, + { 9, 288, 8, 1, 0, 0, 0, nullptr, false }, { 16, 288, 8, 1, 2, 0, 0, nullptr, true }, + { 17, 288, 8, 1, 0, 0, 0, nullptr, true }, { 24, 288, 8, 1, 1, 0, 0, nullptr, true }, + { 33, 288, 8, 1, 0, 0, 0, nullptr, true }, { 48, 288, 8, 1, 0, 0, 0, nullptr, true }, + { 48, 288, 8, 1, 2, 0, 0, nullptr, true }, { 65, 288, 8, 1, 1, 0, 0, nullptr, true }, + { 100, 288, 8, 0, 0, 0, 0, nullptr, true }, { 128, 288, 8, 1, 0, 0, 0, nullptr, true }, + { 24, 288, 8, 1, 0, 144, 144, nullptr, true }, { 24, 288, 8, 1, 1, 96, 32, "3,7,90", true }, + { 48, 512, 8, 1, 0, 0, 0, nullptr, true }, { 32, 32, 32, 0, 1, 0, 0, nullptr, true }, + { 5, 300, 10, 1, 2, 0, 0, "0,299", true }, + }; + std::uniform_int_distribution ud(-1000, 1000); + for (const RouterShape& sh : shapes) { + const int M = sh.M, ne = sh.ne, k = sh.k, T = M * k; + const int nl = sh.nl ? sh.nl : ne, base = sh.base; + const int lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1, gp = 3; + const float factor = 2.5f; + std::vector lg((size_t)M * lp), bias((size_t)ne * bp); + for (auto& v : lg) v = sh.mode == 1 ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200; + for (auto& v : bias) + v = sh.mode == 1 ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000; + if (sh.mode == 2) + for (int r = 0; r < M; r += 2) { + /* every other row keeps (r % 5) finite ranks, fewer than top_k */ + for (int e = 0; e < ne; ++e) lg[(size_t)r * lp + e] = NAN; + for (int j = 0; j < r % 5; ++j) + lg[(size_t)r * lp + (size_t)(ud(rng) + 1000) % ne] = 0.25f * (float)j; + } + std::vector prot; + if (sh.protect) + for (const char* p = sh.protect; *p;) { + char* end = nullptr; + prot.push_back((int)std::strtol(p, &end, 10)); + p = *end == ',' ? end + 1 : end; + } + + RadTensor t[8]{}; + t[0].data = lg.data(); + t[0].dtype = RAD_F32; + t[0].rank = 2; + t[0].shape[0] = M; + t[0].shape[1] = ne; + t[0].stride[0] = lp; + t[0].stride[1] = 1; + t[1].data = bias.data(); + t[1].dtype = RAD_F32; + t[1].rank = 1; + t[1].shape[0] = ne; + t[1].stride[0] = bp; + t[2].dtype = RAD_I32; + t[2].rank = 2; + t[2].shape[0] = M; + t[2].shape[1] = k; + t[2].stride[0] = ip; + t[2].stride[1] = 1; + t[3].dtype = RAD_F32; + t[3].rank = 2; + t[3].shape[0] = M; + t[3].shape[1] = k; + t[3].stride[0] = wp; + t[3].stride[1] = 1; + t[4].dtype = RAD_I32; + t[4].rank = 1; + t[4].shape[0] = T; + t[4].stride[0] = 1; + t[5].dtype = RAD_I32; + t[5].rank = 1; + t[5].shape[0] = nl + 1; + t[5].stride[0] = 1; + t[6].dtype = RAD_I32; + t[6].rank = 1; + t[6].shape[0] = nl; + t[6].stride[0] = 1; + t[7].dtype = RAD_BF16; + t[7].rank = 2; + t[7].shape[0] = M; + t[7].shape[1] = 1; + t[7].stride[0] = gp; + t[7].stride[1] = 1; + std::vector p(9); + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "n_expert", RAD_P_INT, ne }; + p[2] = { "top_k", RAD_P_INT, k }; + p[3] = { "norm", RAD_P_INT, sh.norm }; + p[4].key = "route_scale"; + p[4].kind = RAD_P_F64; + p[4].dval = factor; + p[5].key = "dtype"; + p[5].kind = RAD_P_STR; + p[5].sval = "f32"; + p[6] = { "n_local", RAD_P_INT, nl }; + p[7] = { "expert_base", RAD_P_INT, base }; + p[8].key = "protect"; + p[8].kind = RAD_P_STR; + p[8].sval = sh.protect; + const int n_p = sh.protect ? 9 : 8; + + /* the separate launches: the selection, then the sort and fill modelled */ + std::vector ids_ref((size_t)M * ip, kPoison); + std::vector w_ref((size_t)M * wp, -7.25f); + t[2].data = ids_ref.data(); + t[3].data = w_ref.data(); + RadArgs sel{}; + sel.t = t; + sel.n_t = 4; + sel.p = p.data(); + sel.n_p = 6; + ++cases; + if (r4d_rad_router_sigmoid_topk(&sel, nullptr) != RAD_OK) { + std::printf("FAIL router_sigmoid_topk launch M=%d ne=%d\n", M, ne); + ++fails; + continue; + } + const SortModel ref = sort_model(ids_ref, M, k, ip, nl, base, prot); + /* moe_scatter's own kernel over the ids, contiguous as it reads them, held to the model; + * with the inverse, which must be the table the gather builds from `sorted`. */ + std::vector flat((size_t)T); + for (int i = 0; i < T; ++i) flat[(size_t)i] = ids_ref[(size_t)(i / k) * ip + i % k]; + Scatter ks = scatter_kernel(flat, nl, base, sh.protect, true); + ++cases; + if (ks.rc != RAD_OK || ks.sorted != ref.sorted || ks.off != ref.off || ks.cnt != ref.cnt || + ks.inv != inverse_of(ref.sorted)) { + std::printf("FAIL moe_scatter kernel against its model at M=%d ne=%d slice %d+%d\n", M, + ne, base, nl); + ++fails; + } + + for (int with_inv = 0; with_inv < 2; ++with_inv) { + std::vector ids((size_t)M * ip, kPoison), sorted((size_t)T + 4, kPoison), + off((size_t)nl + 5, kPoison), cnt((size_t)nl + 4, kPoison), + inv((size_t)T + 4, kPoison); + std::vector w((size_t)M * wp, -7.25f); + std::vector gate((size_t)(M + 2) * gp, kGatePoison); + RadTensor tf[9]; + std::memcpy(tf, t, sizeof t); + tf[2].data = ids.data(); + tf[3].data = w.data(); + tf[4].data = sorted.data(); + tf[5].data = off.data(); + tf[6].data = cnt.data(); + tf[7].data = sh.gate ? gate.data() : nullptr; + tf[8] = tf[4]; + tf[8].data = inv.data(); + RadArgs a{}; + a.t = tf; + a.n_t = with_inv ? 9 : 8; + a.p = p.data(); + a.n_p = n_p; + ++cases; + const int rc = r4d_rad_router_sigmoid_topk_scatter(&a, nullptr); + int bad = 0; + bad += ids != ids_ref; + bad += std::memcmp(w.data(), w_ref.data(), w.size() * 4) != 0; + bad += std::memcmp(sorted.data(), ks.sorted.data(), (size_t)T * 4) != 0; + bad += std::memcmp(off.data(), ks.off.data(), (size_t)(nl + 1) * 4) != 0; + bad += std::memcmp(cnt.data(), ks.cnt.data(), (size_t)nl * 4) != 0; + if (with_inv) bad += std::memcmp(inv.data(), ks.inv.data(), (size_t)T * 4) != 0; + for (int i = 0; i < 4; ++i) + bad += sorted[(size_t)T + i] != kPoison || off[(size_t)nl + 1 + i] != kPoison || + cnt[(size_t)nl + i] != kPoison || inv[(size_t)T + i] != kPoison; + if (!with_inv) + for (int i = 0; i < T; ++i) bad += inv[(size_t)i] != kPoison; + for (int r = 0; r < M + 2; ++r) + for (int c = 0; c < gp; ++c) { + const uint16_t want = sh.gate && r < M && c == 0 ? 0x3f80 : kGatePoison; + bad += gate[(size_t)r * gp + c] != want; + } + if (rc != RAD_OK || bad) { + std::printf( + "FAIL router_sigmoid_topk_scatter at M=%d ne=%d k=%d mode %d slice %d+%d%s%s%s " + "(rc %d, %d mismatching outputs)\n", + M, ne, k, sh.mode, base, nl, sh.protect ? " protect " : "", + sh.protect ? sh.protect : "", with_inv ? " with inverse" : "", rc, bad); + ++fails; + } + } + } + /* Past the sort's one workgroup: refused, nothing written. */ + { + const int M = 129, ne = 288, k = 8; + std::vector lg((size_t)M * ne, 0.5f), bias((size_t)ne, 0.f), + w((size_t)M * k, -7.25f); + std::vector ids((size_t)M * k, kPoison), sorted((size_t)M * k, kPoison), + off((size_t)ne + 1, kPoison), cnt((size_t)ne, kPoison); + RadTensor t[7]{}; + auto mat = [](RadTensor& x, void* d, uint32_t dt, int r, int c) { + x.data = d; + x.dtype = dt; + x.rank = 2; + x.shape[0] = r; + x.shape[1] = c; + x.stride[0] = c; + x.stride[1] = 1; + }; + auto vec = [](RadTensor& x, void* d, int n) { + x.data = d; + x.dtype = RAD_I32; + x.rank = 1; + x.shape[0] = n; + x.stride[0] = 1; + }; + mat(t[0], lg.data(), RAD_F32, M, ne); + t[1].data = bias.data(); + t[1].dtype = RAD_F32; + t[1].rank = 1; + t[1].shape[0] = ne; + t[1].stride[0] = 1; + mat(t[2], ids.data(), RAD_I32, M, k); + mat(t[3], w.data(), RAD_F32, M, k); + vec(t[4], sorted.data(), M * k); + vec(t[5], off.data(), ne + 1); + vec(t[6], cnt.data(), ne); + RadParam p[6]{}; + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "n_expert", RAD_P_INT, ne }; + p[2] = { "top_k", RAD_P_INT, k }; + p[3] = { "norm", RAD_P_INT, 1 }; + p[4].key = "route_scale"; + p[4].kind = RAD_P_F64; + p[4].dval = 2.5; + p[5].key = "dtype"; + p[5].kind = RAD_P_STR; + p[5].sval = "f32"; + RadArgs a{}; + a.t = t; + a.n_t = 7; + a.p = p; + a.n_p = 6; + ++cases; + const int rc = r4d_rad_router_sigmoid_topk_scatter(&a, nullptr); + if (rc == RAD_OK || ids[0] != kPoison || sorted[0] != kPoison) { + std::printf("FAIL router_sigmoid_topk_scatter served M*top_k=%d past the sort's bound " + "(rc %d)\n", + M * k, rc); + ++fails; + } + } +} + +struct QuantShape { + int M, n; + float limit; + int mode; /* 0 random past the clamp, 1 clamp edges and zero groups, 2 NaN and inf */ + bool y; /* the fused op also writes the bf16 product */ +}; + +void swiglu_quant_cases(std::mt19937& rng, int& cases, int& fails) { + const QuantShape shapes[] = { + { 1, 256, 10.f, 0, false }, { 8, 256, 10.f, 0, true }, { 48, 256, 10.f, 1, false }, + { 384, 256, 10.f, 0, false }, { 6, 1536, 10.f, 0, true }, { 3, 2048, 10.f, 1, true }, + { 5, 132, 7.f, 1, true }, { 7, 4, 10.f, 0, true }, { 9, 256, 10.f, 2, true }, + { 2, 260, 0.5f, 2, false }, + }; + std::normal_distribution nd(0.f, 1.f); + std::uniform_int_distribution ud(0, 15); + for (const QuantShape& sh : shapes) { + const int M = sh.M, n = sh.n, nkb = (n + 127) / 128; + const int gp = 2 * n + 6, yp = n + 5, qp = n + 8, sp = nkb + 3; + std::vector gu((size_t)M * gp, f2b(-3.f)); + const uint16_t lim = f2b(sh.limit), past = (uint16_t)(lim + 1); + for (int r = 0; r < M; ++r) + for (int c = 0; c < 2 * n; ++c) { + float v = nd(rng) * 6.f; + uint16_t h = f2b(v); + if (sh.mode == 1) { + const int pick = ud(rng); + if (pick == 0) + h = lim; + else if (pick == 1) + h = past; + else if (pick == 2) + h = (uint16_t)(lim | 0x8000u); + else if (pick == 3) + h = (uint16_t)(past | 0x8000u); + else if (pick == 4) + h = f2b(-200.f); + /* rows divisible by 3 hold an all-zero first group */ + if (r % 3 == 0 && (c % n) < 128) h = (c < n && (c & 1)) ? f2b(-0.f) : 0; + } else if (sh.mode == 2) { + const int pick = ud(rng); + if (pick == 0) + h = 0x7fc0; /* NaN */ + else if (pick == 1) + h = 0x7f80; /* +inf */ + else if (pick == 2) + h = 0xff80; /* -inf */ + } + gu[(size_t)r * gp + c] = h; + } + RadTensor t[4]{}; + t[0].data = gu.data(); + t[0].dtype = RAD_BF16; + t[0].rank = 2; + t[0].shape[0] = M; + t[0].shape[1] = 2 * n; + t[0].stride[0] = gp; + t[0].stride[1] = 1; + auto mat = [](RadTensor& x, uint32_t dt, int r, int c, int pitch) { + x.dtype = dt; + x.rank = 2; + x.shape[0] = r; + x.shape[1] = c; + x.stride[0] = pitch; + x.stride[1] = 1; + }; + RadParam pc[4]{}; + pc[0] = { "M", RAD_P_INT, M }; + pc[1] = { "n", RAD_P_INT, n }; + pc[2].key = "limit"; + pc[2].kind = RAD_P_F64; + pc[2].dval = sh.limit; + pc[3].key = "dtype"; + pc[3].kind = RAD_P_STR; + pc[3].sval = "bf16"; + RadParam pq[4]{}; + pq[0] = { "M", RAD_P_INT, M }; + pq[1] = { "n", RAD_P_INT, n }; + pq[2] = { "group", RAD_P_INT, 128 }; + pq[3].key = "dtype"; + pq[3].kind = RAD_P_STR; + pq[3].sval = "bf16"; + RadParam pf[5]{}; + pf[0] = pc[0]; + pf[1] = pc[1]; + pf[2] = pc[2]; + pf[3] = pq[2]; + pf[4] = pc[3]; + + std::vector y_ref((size_t)M * yp, 0x7e57), y((size_t)M * yp, 0x7e57); + std::vector q_ref((size_t)M * qp, 0xa5), q((size_t)M * qp, 0xa5); + std::vector s_ref((size_t)M * sp, -7.25f), s((size_t)M * sp, -7.25f); + RadTensor tc[2] = { t[0], {} }; + mat(tc[1], RAD_BF16, M, n, yp); + tc[1].data = y_ref.data(); + RadArgs ac{}; + ac.t = tc; + ac.n_t = 2; + ac.p = pc; + ac.n_p = 4; + RadTensor tq[3] = { tc[1], {}, {} }; + mat(tq[1], RAD_F8E4M3, M, n, qp); + tq[1].data = q_ref.data(); + mat(tq[2], RAD_F32, M, nkb, sp); + tq[2].data = s_ref.data(); + RadArgs aq{}; + aq.t = tq; + aq.n_t = 3; + aq.p = pq; + aq.n_p = 4; + ++cases; + if (r4d_rad_swiglu_clamped(&ac, nullptr) != RAD_OK || + r4d_rad_quant_act_fp8(&aq, nullptr) != RAD_OK) { + std::printf("FAIL swiglu_clamped + quant_act_fp8 launch M=%d n=%d\n", M, n); + ++fails; + continue; + } + RadTensor tf[4] = { t[0], {}, {}, {} }; + mat(tf[1], RAD_F8E4M3, M, n, qp); + tf[1].data = q.data(); + mat(tf[2], RAD_F32, M, nkb, sp); + tf[2].data = s.data(); + mat(tf[3], RAD_BF16, M, n, yp); + tf[3].data = sh.y ? y.data() : nullptr; + RadArgs af{}; + af.t = tf; + af.n_t = 4; + af.p = pf; + af.n_p = 5; + const int rc = r4d_rad_swiglu_clamped_quant_fp8(&af, nullptr); + int bad = 0; + bad += q != q_ref; + bad += std::memcmp(s.data(), s_ref.data(), s.size() * 4) != 0; + if (sh.y) + bad += y != y_ref; + else + for (uint16_t v : y) bad += v != 0x7e57; + if (rc != RAD_OK || bad) { + std::printf("FAIL swiglu_clamped_quant_fp8 at M=%d n=%d limit %g mode %d%s (rc %d, %d " + "mismatching outputs)\n", + M, n, (double)sh.limit, sh.mode, sh.y ? " with bf16" : "", rc, bad); + ++fails; + } + } +} + +struct GatherShape { + int M, n, nl, base; + bool f32w; /* GLM's f32 routing weights, else bf16 */ + int shared; /* 0 none, 1 the ungated arm (gate 1, act none), 2 a sigmoid gate */ +}; + +/* moe_gather's kernel (r4d_moe_gather.h) as its launcher runs it, reading the table moe_scatter_inv + * wrote, against the same kernel building the table itself from `sorted` (T <= 512) or reading the + * prepass's table (above). Ids are distinct per row from 288 experts, a slice drops slots. */ +void gather_inverse_cases(std::mt19937& rng, int& cases, int& fails) { + const GatherShape shapes[] = { + { 1, 4096, 288, 0, true, 1 }, { 6, 4096, 288, 0, true, 1 }, { 8, 512, 288, 0, true, 1 }, + { 24, 512, 144, 72, true, 1 }, { 48, 256, 288, 0, true, 1 }, { 64, 256, 288, 0, true, 0 }, + { 100, 256, 96, 0, true, 1 }, { 6, 300, 288, 0, false, 2 }, { 33, 256, 288, 0, false, 0 }, + }; + const int k = 8, ne = 288; + std::normal_distribution nd(0.f, 1.f); + for (const GatherShape& sh : shapes) { + const int M = sh.M, n = sh.n, T = M * k, nl = sh.nl; + std::vector ids((size_t)T); + for (int r = 0; r < M; ++r) { + std::vector pool(ne); + for (int e = 0; e < ne; ++e) pool[(size_t)e] = e; + std::shuffle(pool.begin(), pool.end(), rng); + for (int j = 0; j < k; ++j) ids[(size_t)(r * k + j)] = pool[(size_t)j]; + } + Scatter plain = scatter_kernel(ids, nl, sh.base, nullptr, false); + Scatter inv = scatter_kernel(ids, nl, sh.base, nullptr, true); + ++cases; + if (plain.rc != RAD_OK || inv.rc != RAD_OK || inv.sorted != plain.sorted || + inv.off != plain.off || inv.cnt != plain.cnt || inv.inv != inverse_of(plain.sorted)) { + std::printf("FAIL moe_scatter with the inverse at M=%d slice %d+%d\n", M, sh.base, nl); + ++fails; + continue; + } + const int ye_ld = n + 3, ew_ld = k + 2, y_ld = n + 5, sh_ld = n + 1, sg_ld = 2; + std::vector ye((size_t)T * ye_ld), shp((size_t)M * sh_ld), sg((size_t)M * sg_ld); + for (auto& v : ye) v = f2b(nd(rng)); + for (auto& v : shp) v = f2b(nd(rng)); + for (size_t i = 0; i < sg.size(); ++i) sg[i] = sh.shared == 1 ? f2b(1.f) : f2b(nd(rng)); + std::vector ewf((size_t)M * ew_ld); + std::vector ewb((size_t)M * ew_ld); + for (size_t i = 0; i < ewf.size(); ++i) { + ewf[i] = std::fabs(nd(rng)) * 0.3f; + ewb[i] = f2b(ewf[i]); + } + const void* ew = sh.f32w ? (const void*)ewf.data() : (const void*)ewb.data(); + const uint16_t* shv = sh.shared ? shp.data() : nullptr; + const uint16_t* sgv = sh.shared ? sg.data() : nullptr; + const int sig = sh.shared == 2; + const bool small = T <= (int)r4d_moegather::kGatherSelfT; + /* the launcher's rule: the self-scan up to 512 slots, the prepass's table above */ + const std::vector table = inverse_of(plain.sorted); + const unsigned gy = (unsigned)((n + 255) / 256); + auto gather = [&](const int32_t* tab, const int32_t* sorted, std::vector& y) { + y.assign((size_t)M * y_ld, 0x7e57); + if (sh.f32w) + R4D_EMIT(nullptr, (r4d_moegather::gather_kernel<256, true>), dim3((unsigned)M, gy), + dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n, + (uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted, + (uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig); + else + R4D_EMIT(nullptr, (r4d_moegather::gather_kernel<256, false>), dim3((unsigned)M, gy), + dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n, + (uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted, + (uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig); + }; + std::vector y_old, y_new; + if (small) + gather(nullptr, plain.sorted.data(), y_old); + else + gather(table.data(), nullptr, y_old); + gather(inv.inv.data(), nullptr, y_new); + ++cases; + if (y_new != y_old) { + size_t first = 0; + while (first < y_new.size() && y_new[first] == y_old[first]) ++first; + std::printf("FAIL moe_gather from the inverse at M=%d n=%d slice %d+%d %s weights, " + "shared %d: first difference at %zu\n", + M, n, sh.base, nl, sh.f32w ? "f32" : "bf16", sh.shared, first); + ++fails; + } + } +} + +} // namespace + +int main() { + std::mt19937 rng(23); + int fails = 0, cases = 0; + router_scatter_cases(rng, cases, fails); + swiglu_quant_cases(rng, cases, fails); + gather_inverse_cases(rng, cases, fails); + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_moemx.cpp b/tests/r4d_emu/test_moemx.cpp new file mode 100644 index 00000000..1ef630ce --- /dev/null +++ b/tests/r4d_emu/test_moemx.cpp @@ -0,0 +1,482 @@ +/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. Every form + * the RADIANCE_MXFP4_* switches reach must match the arithmetic-decode row-group form bit for bit, + * and both a host restatement of the per-element sequence: per 128 of K in order, per 32-wide group + * a fresh 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * + * E8M0 scale with two roundings and an add. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, + * dropped slots inside runs and past the routed rows, columns an odd expert does not have, a + * shorter K for odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes + * and pointer tables. The P64 forms (RADIANCE_MXFP4_PREFILL_P64) run at every BM, BN, stage and + * column-tile count, pinned below their row bound, with jobs cut at 32 and 64 rows, column + * blocks past N and the output through LDS at aligned and odd pitches. The table decode is also + * held to the arithmetic one over every code. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "r4d_mxfp4.h" +#include +#include +#include +#include +#include +#include +#include + +extern const char* emu_last_kernel; + +/* The arithmetic decode the kernels used before the table (r4d_moe_mxfp4.hip, fp4x4 and its + * byte interleave), restated as the reference of r4d_mxfp4_unpack8_exact. */ +static uint32_t fp4x4_ref(uint32_t n) { + const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u; + const uint32_t mask = (flag << 5) - (flag >> 3); + return (((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) | + ((n & 0x08080808u) << 4); +} +static int check_decode() { + int fails = 0; + auto one = [&](uint32_t w) { + const uint32_t low = fp4x4_ref(w & 0x0f0f0f0fu), high = fp4x4_ref((w >> 4) & 0x0f0f0f0fu); + const uint32_t lo_ref = __byte_perm(low, high, 0x5140), + hi_ref = __byte_perm(low, high, 0x7362); + uint32_t lo, hi, tlo, thi; + r4d_mxfp4_unpack8_exact(w, &lo, &hi); + r4d_mxfp4_unpack8(w, 0, &tlo, &thi); + if (lo != lo_ref || hi != hi_ref || lo != tlo || hi != thi) { + if (fails < 4) + std::printf("FAIL decode of %08x: table %08x %08x, arithmetic %08x %08x\n", w, hi, + lo, hi_ref, lo_ref); + ++fails; + } + /* each byte against the e2m1 value it encodes */ + for (int e = 0; e < 8; ++e) { + const uint32_t c = (w >> (4 * e)) & 15u; + static const float mag[8] = { 0.f, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f }; + const float want = (c & 8u ? -1.f : 1.f) * mag[c & 7u]; + const uint8_t b = (uint8_t)(((e < 4 ? lo : hi) >> (8 * (e & 3))) & 0xffu); + if (rad_fp8e4m3_to_f32(b) != want || (b & 0x80u) != (c & 8u ? 0x80u : 0u)) { + if (fails < 4) std::printf("FAIL code %x at element %d -> byte %02x\n", c, e, b); + ++fails; + } + } + }; + /* the bytes decode independently: every pair of adjacent bytes exhaustively, at both halves + * of the word, and random words over all four */ + for (uint32_t v = 0; v < 65536; ++v) { + one(v); + one(v << 16); + one(v << 8); + } + std::mt19937 rng(7); + for (int i = 0; i < 200000; ++i) one((uint32_t)rng()); + return fails; +} + +struct Case { + const char* name; + int N, K, N_odd, K_odd, parts, top; + bool sorted_a, tables, exceptional; + std::vector runs; + int tail; // dropped slots past the routed rows +}; + +/* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative + * default NaN, and an add of two NaNs returns its first operand, whose side the compiler may swap; + * the card generates the positive quiet NaN, so a NaN's sign carries no information here. */ +static bool nan16(uint16_t v) { return (v & 0x7f80u) == 0x7f80u && (v & 0x7fu); } +static size_t first_diff(const std::vector& a, const std::vector& b) { + for (size_t i = 0; i < a.size() && i < b.size(); ++i) + if (a[i] != b[i] && !(nan16(a[i]) && nan16(b[i]))) return i; + return a.size() == b.size() ? a.size() : std::min(a.size(), b.size()); +} +static bool same16(const std::vector& a, const std::vector& b) { + return a.size() == b.size() && first_diff(a, b) == a.size(); +} + +static RadTensor ten(void* p, uint32_t dt, std::vector shape, + std::vector stride) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + for (size_t i = 0; i < shape.size(); ++i) { + t.shape[i] = shape[i]; + t.stride[i] = stride[i]; + } + return t; +} + +int main() { + int fails = check_decode(), cases = 1; + if (fails) std::printf("FAIL table decode: %d mismatches\n", fails); + + const std::vector runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 }; + const Case all[] = { + { "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6 }, + { "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9, + 2 }, + { "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4 }, + { "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4 }, + { "decode band, row groups of 4", + 64, + 384, + 64, + 384, + 2, + 2, + false, + true, + false, + { 0, 1, 15, 16, 17, 30 }, + 3 }, + { "decode band, row groups of 1", + 64, + 256, + 32, + 256, + 1, + 2, + true, + false, + true, + { 1, 0, 3, 15, 1 }, + 2 }, + { "P64 jobs at 32 and 64 rows, N under a block", + 96, + 512, + 96, + 384, + 1, + 2, + false, + false, + false, + { 32, 33, 31, 96, 128, 129, 0, 2 }, + 9 }, + { "P64 resident A, column tiles cut", + 192, + 256, + 128, + 128, + 2, + 4, + true, + true, + true, + { 64, 63, 65, 1, 0, 127, 17 }, + 5 }, + }; + struct Form { + const char* env; + int stage, tiles, lut; + const char* kernel; + bool prefill; + bool pipe = false; + }; + /* env: DECODE_EXPERTS, ALIGNED_JOBS, PREFILL_N32, PREFILL_M32, PREFILL_N64, PREFILL_CACHE_ROWS */ + const Form forms[] = { + { "100000", 256, 1, 0, "moe_mxfp4_expert_kernel<4, 256, false>", false }, + { "100000", 256, 1, 1, "moe_mxfp4_expert_kernel<4, 256, true>", false }, + { "100000", 256, 4, 0, "moe_mxfp4_expert_staged_kernel<256, 4, false>", false }, + { "100000", 256, 4, 1, "moe_mxfp4_expert_staged_kernel<256, 4, true>", false }, + { "100000", 128, 1, 0, "moe_mxfp4_expert_staged_kernel<128, 1, false>", false }, + { "100000", 128, 1, 1, "moe_mxfp4_expert_staged_kernel<128, 1, true>", false }, + { "100000", 128, 4, 0, "moe_mxfp4_expert_staged_kernel<128, 4, false>", false }, + { "100000", 128, 4, 1, "moe_mxfp4_expert_staged_kernel<128, 4, true>", false }, + { "000000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", false }, + { "010000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", true }, + { "001000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true }, + { "011000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true }, + { "011100", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 2, false, true>", true }, + { "011110", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, false, true>", true }, + { "011111", 0, 0, 0, "moe_mxfp4_fp8_kernel<4, 2, true, false>", true }, + { "011111", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, true, true>", true }, + { "011111", 0, 0, 0, "moe_mxfp4_prefill_kernel", true, true }, + { "011111", 0, 0, 1, "moe_mxfp4_prefill_kernel", true, true }, + }; + /* P64 at every raster point, column tiles 4 (the resident form's default) and 1, and the LDS + * output at the default; the K of a case picks streamed or resident A. */ + struct P64 { + int bm, bn, sk, ct, out, db = 0; + }; + std::vector p64s; + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + for (int sk : { 128, 256 }) + for (int ct : { 1, 4 }) p64s.push_back({ bm, bn, sk, ct, 0 }); + p64s.push_back({ 64, 128, 128, 4, 1 }); + p64s.push_back({ 32, 64, 256, 1, 1 }); + /* The double buffer at every BM x BN x stage: where two stages do not fit in LDS, and with + * resident A, the single-buffer form runs. */ + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + for (int sk : { 128, 256 }) p64s.push_back({ bm, bn, sk, 4, 0, 1 }); + p64s.push_back({ 64, 128, 128, 4, 1, 1 }); + static const char* const kP64[] = { "RADIANCE_MXFP4_PREFILL_P64", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", + "RADIANCE_MXFP4_PREFILL_P64_BM", + "RADIANCE_MXFP4_PREFILL_P64_BN", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", + "RADIANCE_MXFP4_PREFILL_P64_COLTILES", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", + "RADIANCE_MXFP4_PREFILL_P64_T_BM64", + "RADIANCE_MXFP4_PREFILL_P64_T_BN128", + "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", + "RADIANCE_MXFP4_PREFILL_P64_DB" }; + /* The rule's tile with nothing pinned, by its row bounds (unset: this test's few rows are + * under all of them); the widest tiles take the LDS output. */ + struct Rule { + const char* t_bm64; + const char* t_bn128; + const char* t_down; + const char* streamed; + const char* resident; + }; + const Rule rules[] = { { nullptr, nullptr, nullptr, "<32, 64, 256, 1, false>", + "<32, 64, 128, 4, true>" }, + { "0", nullptr, nullptr, "<64, 64, 256, 1, false>", "<32, 64, 128, 4, true>" }, + { "0", "0", "0", "<64, 128, 128, 1, false>", "<64, 128, 128, 4, true>" } }; + static const char* const kEnv[] = { + "RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_ALIGNED_JOBS", + "RADIANCE_MXFP4_PREFILL_N32", "RADIANCE_MXFP4_PREFILL_M32", + "RADIANCE_MXFP4_PREFILL_N64", "RADIANCE_MXFP4_PREFILL_CACHE_ROWS" + }; + + for (const Case& c : all) { + const int E = (int)c.runs.size(), NK = std::max(c.K, c.K_odd), OUT = std::max(c.N, c.N_odd); + int routed = 0; + for (int r : c.runs) routed += r; + const int T = (routed + c.tail + c.top - 1) / c.top * c.top; + // An odd pitch on every other case: the LDS output's 16-byte stores need an aligned row. + const int Arows = c.sorted_a ? T : T / c.top, ap = NK + 16, asp = NK / 128 + 1, + yp = OUT + ((&c - all) % 2 ? 5 : 8); + std::mt19937 rng(1000 + cases); + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution oct(-6.f, 6.f); + std::vector a((size_t)Arows * ap); + for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng) * 2.f); + std::vector as((size_t)Arows * asp); + for (auto& v : as) v = std::exp2(oct(rng)); + std::vector offsets(E + 1, 0), sorted(T, -1), owner(T, -1); + for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + c.runs[e]; + for (int e = 0; e < E; ++e) + for (int r = offsets[e]; r < offsets[e + 1]; ++r) { + owner[r] = e; + // A dropped slot about every eleventh row, the first rows of some runs included. + sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T); + } + const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd }, + nexp[2] = { (E + 1) / 2, E / 2 }; + std::vector w[2], s[2]; + std::vector wt[2], st[2]; + for (int q = 0; q < 2; ++q) { + w[q].resize((size_t)nexp[q] * n[q] * k[q] / 2); + s[q].resize((size_t)nexp[q] * n[q] * k[q] / 32); + for (auto& v : w[q]) v = (uint8_t)rng(); + static const uint8_t special[] = { 0, 255, 1, 254, 127 }; + for (size_t i = 0; i < s[q].size(); ++i) + s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5] + : (uint8_t)(118 + rng() % 16); + for (int x = 0; x < nexp[q]; ++x) { + wt[q].push_back(w[q].data() + (size_t)x * n[q] * k[q] / 2); + st[q].push_back(s[q].data() + (size_t)x * n[q] * k[q] / 32); + } + } + auto plane = [&](int q, bool scale) { + const int64_t cols = scale ? k[q] / 32 : k[q]; + void* p = c.tables ? (void*)(scale ? st[q].data() : wt[q].data()) + : (void*)(scale ? s[q].data() : w[q].data()); + RadTensor t = ten(p, scale ? RAD_E8M0 : RAD_FP4E2M1, { nexp[q], n[q], cols }, + { c.tables ? 0 : (int64_t)n[q] * cols, cols, 1 }); + return t; + }; + + /* the per-element sequence, on the host */ + std::vector ref((size_t)T * yp, 0x7777); + for (int r = 0; r < T; ++r) + for (int col = 0; col < OUT; ++col) { + uint16_t& out = ref[(size_t)r * yp + col]; + out = 0; + if (owner[r] < 0 || sorted[r] < 0) continue; + const int e = owner[r], q = e & 1, ar = c.sorted_a ? r : sorted[r] / c.top; + const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw; + const bool valid = within < cw; + const int wn = (col / pw) * cw + within; + const uint8_t* wr = + w[q].data() + (size_t)(e / 2) * n[q] * k[q] / 2 + (size_t)wn * k[q] / 2; + const uint8_t* sr = + s[q].data() + (size_t)(e / 2) * n[q] * k[q] / 32 + (size_t)wn * k[q] / 32; + float total = 0.f; + for (int kb = 0; kb < k[q]; kb += 128) + for (int g = 0; g < 4; ++g) { + float raw = 0.f; + for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk) { + const uint32_t code = valid ? (wr[kk / 2] >> (4 * (kk & 1))) & 15u : 0u; + uint32_t lo, hi; + r4d_mxfp4_unpack8_exact(code, &lo, &hi); + raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + kk]) * + rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu)); + } + const uint32_t x = valid ? sr[kb / 32 + g] : 127u; + uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u; + float scale; + std::memcpy(&scale, &bits, 4); + float t = raw * as[(size_t)ar * asp + kb / 128]; + t = t * scale; + total = total + t; + } + uint32_t u; + std::memcpy(&u, &total, 4); + out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> + 16); // f32_to_bf16, r4d_common.h + } + + RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }), + ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }), + plane(0, false), + plane(0, true), + ten(sorted.data(), RAD_I32, { T }, { 1 }), + ten(offsets.data(), RAD_I32, { E + 1 }, { 1 }), + plane(1, false), + plane(1, true), + RadTensor{} }; + RadParam p[11]{}; + auto pi = [](const char* key, long long v) { + RadParam x{}; + x.key = key; + x.kind = RAD_P_INT; + x.ival = v; + return x; + }; + auto ps = [](const char* key, const char* v) { + RadParam x{}; + x.key = key; + x.kind = RAD_P_STR; + x.sval = v; + return x; + }; + p[0] = pi("M", T / c.top); + p[1] = pi("N", c.N); + p[2] = pi("K", c.K); + p[3] = pi("N_odd", c.N_odd); + p[4] = pi("K_odd", c.K_odd); + p[5] = pi("n_expert", E); + p[6] = pi("top_k", c.top); + p[7] = pi("parts", c.parts); + p[8] = pi("group", 128); + p[9] = ps("a_order", c.sorted_a ? "sorted" : "token"); + p[10] = ps("dtype", "mxfp4a8"); + auto run = [&](const Form& f, std::vector& y) { + y.assign((size_t)T * yp, 0x7777); + t[8] = ten(y.data(), RAD_BF16, { T, OUT }, { yp, 1 }); + for (int i = 0; i < 6; ++i) setenv(kEnv[i], f.env[i] == '1' ? "1" : "0", 1); + if (f.stage) { + setenv("RADIANCE_MXFP4_EXPERTS_STAGE_K", std::to_string(f.stage).c_str(), 1); + setenv("RADIANCE_MXFP4_EXPERTS_COLTILES", std::to_string(f.tiles).c_str(), 1); + } + setenv("RADIANCE_MXFP4_LUT", f.lut ? "1" : "0", 1); + setenv("RADIANCE_MXFP4_PREFILL_PIPE", f.pipe ? "1" : "0", 1); + RadArgs ar{}; + ar.t = t; + ar.n_t = 9; + ar.p = p; + ar.n_p = 11; + emu_last_kernel = ""; + return r4d_rad_moe_mxfp4(&ar, nullptr); + }; + auto run_p64 = [&](const P64& f, std::vector& y) { + const int v[8] = { 1, 0, 0, f.bm, f.bn, f.sk, f.ct, f.out }; + for (int i = 0; i < 8; ++i) setenv(kP64[i], std::to_string(v[i]).c_str(), 1); + setenv(kP64[11], f.db ? "1" : "0", 1); + const Form base = { "000000", 0, 0, 1, "", false }; + const int rc = run(base, y); + setenv(kP64[0], "0", 1); + return rc; + }; + const Form alt = { "000000", 0, 0, 0, "moe_mxfp4_fp8_kernel<1, 1, false, false>", false }; + std::vector legacy, got; + ++cases; + int rc = run(alt, legacy); + if (rc != RAD_OK || !std::strstr(emu_last_kernel, alt.kernel)) { + std::printf("FAIL %s: reference form rc %d kernel %s\n", c.name, rc, emu_last_kernel); + ++fails; + continue; + } + if (!same16(legacy, ref)) { + const size_t i = first_diff(legacy, ref); + std::printf("FAIL %s: reference form against the host sequence at row %zu col %zu: " + "%04x, want %04x\n", + c.name, i / yp, i % yp, legacy[i], ref[i]); + ++fails; + } + int live = 0; + for (uint16_t v : ref) live += v != 0 && v != 0x7777; + if (live < T * OUT / 3) { + std::printf("FAIL %s: output mostly zero\n", c.name); + ++fails; + } + for (const Form& f : forms) { + if (f.prefill && T < 512) continue; + ++cases; + rc = run(f, got); + const bool reached = std::strstr(emu_last_kernel, f.kernel) != nullptr; + if (rc != RAD_OK || !reached || !same16(got, legacy)) { + const size_t i = first_diff(got, legacy); + std::printf( + "FAIL %s: form %s stage %d tiles %d lut %d ran %s (want %s), rc %d, first " + "word %zu\n", + c.name, f.env, f.stage, f.tiles, f.lut, emu_last_kernel, f.kernel, rc, i); + ++fails; + } + } + const bool resident = NK <= 256; + for (const Rule& u : rules) { + ++cases; + for (const char* v : kP64) unsetenv(v); + setenv(kP64[0], "1", 1); + setenv(kP64[1], "0", 1); + setenv(kP64[2], "0", 1); + if (u.t_bm64) setenv(kP64[8], u.t_bm64, 1); + if (u.t_bn128) setenv(kP64[9], u.t_bn128, 1); + if (u.t_down) setenv(kP64[10], u.t_down, 1); + const Form base = { "000000", 0, 0, 1, "", false }; + rc = run(base, got); + for (const char* v : kP64) unsetenv(v); + const std::string want = + std::string("moe_mxfp4_p64_kernel") + (resident ? u.resident : u.streamed); + if (rc != RAD_OK || !std::strstr(emu_last_kernel, want.c_str()) || + !same16(got, legacy)) { + std::printf("FAIL %s: P64 rule ran %s (want %s), rc %d, first word %zu\n", c.name, + emu_last_kernel, want.c_str(), rc, first_diff(got, legacy)); + ++fails; + } + } + for (const P64& f : p64s) { + ++cases; + rc = run_p64(f, got); + const bool db = f.db && !resident && (f.sk == 128 || (f.bm == 32 && f.bn == 64)); + const std::string want = "moe_mxfp4_p64_kernel<" + std::to_string(f.bm) + ", " + + std::to_string(f.bn) + ", " + std::to_string(f.sk) + ", " + + (resident ? std::to_string(f.ct) : "1") + ", " + + (resident ? "true" : "false") + (db ? ", true>" : ">"); + const bool reached = std::strstr(emu_last_kernel, want.c_str()) != nullptr; + if (rc != RAD_OK || !reached || !same16(got, legacy)) { + const size_t i = first_diff(got, legacy); + std::printf("FAIL %s: P64 bm %d bn %d stage %d tiles %d out %d db %d ran %s (want " + "%s), rc %d, " + "first word %zu (row %zu col %zu: %04x, want %04x)\n", + c.name, f.bm, f.bn, f.sk, f.ct, f.out, f.db, emu_last_kernel, + want.c_str(), rc, i, i / yp, i % yp, i < got.size() ? got[i] : 0, + i < legacy.size() ? legacy[i] : 0); + ++fails; + } + } + } + for (const char* v : kEnv) unsetenv(v); + for (const char* v : kP64) unsetenv(v); + unsetenv("RADIANCE_MXFP4_EXPERTS_STAGE_K"); + unsetenv("RADIANCE_MXFP4_EXPERTS_COLTILES"); + unsetenv("RADIANCE_MXFP4_LUT"); + unsetenv("RADIANCE_MXFP4_PREFILL_PIPE"); + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} From 544753fc4064d7dcb07edf364a4afa8ac00dd4e2 Mon Sep 17 00:00:00 2001 From: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:10:49 +0200 Subject: [PATCH 061/152] arch/common: GLM-5.3's blocks, and f32 scales, MXFP4 experts and sigmoid routing in the shared ones New blocks: mHC (rad_block_mhc.h), KDA and its state (rad_block_glm_kda.h, rad_block_kda_state.h), absorbed MLA over a latent cache (rad_block_glm_mla.h, rad_block_mla_latent.h), the DSA indexer and its paged key cache (rad_block_glm_indexer.h, rad_block_dsa_cache.h), the correction-bias router (rad_block_glm_router.h), and rad_tp_split.h: a replicated f32 projection computed column-split over the ranks and all-gathered, so every value is the replicated one's bits (from RADIANCE_GLM_TP_SPLIT_ROWS rows, 256 by default). The shared blocks gain what GLM's checkpoint stores, each off unless a model asks for it: - LinearFP8 reads a block-fp8 weight whose scale plane is f32 (dtype fp8a8f32), and the import check accepts that form beside bf16 scales. - GateQuantFP8 serves a clamped SwiGLU (swiglu_clamped), optionally fused with its quantiser. - MoeFP8 takes MXFP4 experts (format 8) and block-fp8 experts with f32 scales (format 9), the sigmoid router with f32 weights, an ungated shared arm, the router/scatter fusion and the sort's inverse handed to the gather (moe_scatter_inv, moe_gather_inv) where they resolve. - The MLP's gated fold excludes the forms it cannot serve (f32 scales, a clamped product). share_test checks that KDA's convolution weight shards per head across its three parts at TP4. --- arch/common/rad_block_dsa_cache.h | 150 +++++++++++++++++ arch/common/rad_block_glm_indexer.h | 109 ++++++++++++ arch/common/rad_block_glm_kda.h | 102 +++++++++++ arch/common/rad_block_glm_mla.h | 118 +++++++++++++ arch/common/rad_block_glm_router.h | 82 +++++++++ arch/common/rad_block_kda_state.h | 128 ++++++++++++++ arch/common/rad_block_mhc.h | 136 +++++++++++++++ arch/common/rad_block_mla_latent.h | 84 ++++++++++ arch/common/rad_block_mlp_fp8.h | 21 ++- arch/common/rad_block_moe_fp8.h | 252 ++++++++++++++++++++++------ arch/common/rad_fp8.h | 87 +++++++++- arch/common/rad_tp_split.h | 72 ++++++++ tests/share_test.cpp | 16 ++ 13 files changed, 1296 insertions(+), 61 deletions(-) create mode 100644 arch/common/rad_block_dsa_cache.h create mode 100644 arch/common/rad_block_glm_indexer.h create mode 100644 arch/common/rad_block_glm_kda.h create mode 100644 arch/common/rad_block_glm_mla.h create mode 100644 arch/common/rad_block_glm_router.h create mode 100644 arch/common/rad_block_kda_state.h create mode 100644 arch/common/rad_block_mhc.h create mode 100644 arch/common/rad_block_mla_latent.h create mode 100644 arch/common/rad_tp_split.h diff --git a/arch/common/rad_block_dsa_cache.h b/arch/common/rad_block_dsa_cache.h new file mode 100644 index 00000000..52cc782a --- /dev/null +++ b/arch/common/rad_block_dsa_cache.h @@ -0,0 +1,150 @@ +/* GLM's stateful compressed-index core. The caller supplies projected queries, + * signed F32 head gates, and [LayerNorm(key), pool_gate] BF16 rows. No RoPE. + * Query projections are replicated across TP ranks; selected pages belong to MLA. */ +#ifndef RAD_BLOCK_DSA_CACHE_H +#define RAD_BLOCK_DSA_CACHE_H +#include "rad_arch.h" + +namespace rad { +namespace arch { +struct DsaCache { + struct Config { + int64_t blocks = 0, work = 0, ring = 0, topk = 512; + }; + struct Wire { + rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0; + rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0; + rad_buf score = 0, selected = 0, nsel = 0, length = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + rad_kvgroup index = 0, tail = 0, attention = 0; + rad_weight ape = 0; + rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg, + const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group, + rad_kvgroup* index_group, const char* ape_source) { + g = geom; + c = cfg; + w = wire; + layer = l; + attention = attn; + tail = tail_group; + if (!b || !index_group || !ape_source || !attention || !tail || c.blocks < 1 || + c.work < (g.max_tok + 3) / 4 + g.max_seqs || c.ring < 4 + g.max_spec || c.topk != 512 || + !w.query || !w.codes || !w.scales || !w.gate || !w.kg || !w.stage || !w.page || + !w.bpos || !w.nc || !w.pooled || !w.pool_scale || !w.score || !w.selected || !w.nsel || + !w.length) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, tail)); + const char* name = nm.f("blk.%d.index_ape", l); + RAD_ARCH_TRY(map_copy(b, name, ape_source)); + ape = decl_w(b, name, RAD_F32, { 4, 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(l)); + if (!ape) return RAD_E_INVAL; + // Query buffers are [tokens*32,128]; scoring uses their rank-three view. + op_query = rw(b, + RAD_OP(b, "dsa_query", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.query }, { w.codes, w.scales }); + op_work = rw( + b, + RAD_OP(b, "qsa_work", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), RAD_INT("ratio", 4), + RAD_INT("ring", c.ring), RAD_INT("seqs", g.max_seqs), + RAD_INT("work", c.work), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.kg }, { w.stage, w.page, w.bpos, w.nc }); + // Declare immediately before the cache consumer: page size comes from that op. + if (!*index_group) { + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = RAD_U8; + d.n_head_kv = 1; + d.head_dim = 17; + *index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d); + } + index = *index_group; + if (!index) return RAD_E_INVAL; + op_pool = + rw(b, + RAD_OP(b, "dsa_pool", + RAD_PARAMS(RAD_RANGE("M", 1, c.work), RAD_INT("n", 128), RAD_INT("ratio", 4), + RAD_INT("block_size", 4), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(ape)), + { w.stage, w.page }, { w.pooled, w.pool_scale }); + if (!op_pool || rad_kv_block_size(b, index) != 4) return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, index)); + op_tail = rw(b, + RAD_OP(b, "qsa_tail_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), + RAD_INT("ratio", 4), RAD_INT("ring", c.ring), + RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.kg }, {}); + op_score = rw(b, + RAD_OP(b, "dsa_score", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128), + RAD_INT("heads", 32), RAD_INT("blocks", c.blocks), + RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")), + RAD_NOWEIGHTS), + { w.codes, w.scales, w.gate, w.nc }, { w.score }); + op_select = rw(b, + RAD_OP(b, "qsa_select", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", c.blocks), + RAD_INT("topk", 512), RAD_INT("ratio", 4), + RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)), + RAD_NOWEIGHTS), + { w.score, w.nc }, { w.selected, w.nsel, w.length }); + return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, const RadBatch* batch) const { + const auto* ib = kv_batch(batch, index); + const auto* tb = kv_batch(batch, tail); + const auto* ab = kv_batch(batch, attention); + if (!ib || !tb || !ab || !ib->block_table || !ab->block_table || !tb->state_index) { + rad_step_fail(ctx, "DSA requires index/attention block tables and tail state indices"); + return; + } + const int64_t T = batch->n_tok, S = batch->n_seq; + const int64_t work = (T + 3) / 4 + S, + pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1; + RAD_ISSUE_N(ctx, op_query, T * 32, brows(w.query, T * 32), brows(w.codes, T * 32), + brows(w.scales, T * 32)); + RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), + praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), + praw2(tb->state_index, RAD_I32, S, pitch), + praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), RAD_NONE, + brows(w.stage, work * 4), brows(w.page, work), brows(w.bpos, work), + brows(w.nc, S)); + RAD_ISSUE_N(ctx, op_pool, work, brows(w.stage, work * 4), RAD_W(ape), brows(w.pooled, work), + brows(w.pool_scale, work), brows(w.page, work), kv_cache(index, layer)); + // Gather before overwriting the tail; the wider ring preserves rejected-token rollback. + RAD_ISSUE_N(ctx, op_tail, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), + praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), + praw2(tb->state_index, RAD_I32, S, pitch)); + int64_t live = ((int64_t)batch->max_ctx_len + T + batch->n_spec + 4) / 4 + 1; + if (live > c.blocks) live = c.blocks; + // T is the total across sequences, so the conservative bound can exceed the + // per-sequence page table. Columns without a table entry cannot be scored. + if (live > ib->block_table_pitch) live = ib->block_table_pitch; + if (live < 1) live = 1; + RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32), + brows(w.gate, T), kv_cache(index, layer), RAD_NONE, + praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), + praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S), + bcol_at(w.score, 0, c.blocks, 0, live, T)); + RAD_ISSUE_N(ctx, op_select, T, bcol_at(w.score, 0, c.blocks, 0, live, T), + praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S), + praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1), + brows(w.selected, T), brows(w.nsel, T), brows(w.length, T)); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_glm_indexer.h b/arch/common/rad_block_glm_indexer.h new file mode 100644 index 00000000..59d81696 --- /dev/null +++ b/arch/common/rad_block_glm_indexer.h @@ -0,0 +1,109 @@ +/* Replicated GLM indexer front end. Casts bridge ordinary linear rows to the + * flattened per-head quantizer and join normalized keys with learned pool gates. */ +#ifndef RAD_BLOCK_GLM_INDEXER_H +#define RAD_BLOCK_GLM_INDEXER_H +#include "rad_fp8.h" +#include "rad_block_dsa_cache.h" +#include "rad_tp_split.h" + +namespace rad { +namespace arch { +struct GlmIndexer { + struct Wire { + rad_buf input = 0, q_low = 0, q_wide = 0, kg_raw = 0; + DsaCache::Wire cache{}; + }; + Geom g{}; + Wire w{}; + LinearFP8 query{}, key_gate{}; + DsaCache cache{}; + rad_weight gain = 0, bias = 0, head_weight = 0; + rad_op op_norm = 0, op_query_copy = 0, op_gate_copy = 0, op_head = 0; + SplitF32Proj head_split{}; + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, + const char* prefix, const DsaCache::Config& cfg, rad_kvgroup attention, + rad_kvgroup tail, rad_kvgroup* index) { + g = geom; + w = wire; + if (!b || !prefix || g.n_embd != 4096 || !w.input || !w.q_low || !w.q_wide || !w.kg_raw) + return RAD_E_INVAL; + Geom bg = g; + bg.w_bf16 = true; + auto act = [](rad_buf x) { + ActFP8 a{}; + a.x = x; + return a; + }; + RAD_ARCH_TRY(query.declare(b, nm, bg, nm.f("blk.%d.index_query", l), 4096, 1536, + RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.wq_b.weight", prefix) }, act(w.q_low), w.q_wide)); + RAD_ARCH_TRY(key_gate.declare( + b, nm, bg, nm.f("blk.%d.index_key_gate", l), 256, 4096, RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.wk.weight", prefix), nm.ckpt("%s.index_kpool_compress_gate", prefix) }, + act(w.input), w.kg_raw, 0, { 128, 128 })); + const char *gn = nm.f("blk.%d.index_norm.weight", l), + *bn = nm.f("blk.%d.index_norm.bias", l), + *hn = nm.f("blk.%d.index_head.weight", l); + RAD_ARCH_TRY(map_copy(b, gn, nm.ckpt("%s.k_norm.weight", prefix))); + RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.k_norm.bias", prefix))); + RAD_ARCH_TRY(map_copy(b, hn, nm.ckpt("%s.weights_proj.weight", prefix))); + gain = decl_w(b, gn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + bias = decl_w(b, bn, RAD_F32, { 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + head_weight = decl_w(b, hn, RAD_F32, { 32, 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(l)); + if (!gain || !bias || !head_weight) return RAD_E_INVAL; + op_norm = rw(b, + RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(gain, bias)), + { w.kg_raw }, { w.cache.kg }); + op_query_copy = rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { w.q_wide }, { w.cache.query }); + op_gate_copy = rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { w.kg_raw }, { w.cache.kg }); + op_head = rw(b, + RAD_OP(b, "gemm_nt_f32", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 32), + RAD_INT("K", 4096), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(head_weight)), + { w.input }, { w.cache.gate }); + RAD_ARCH_TRY(head_split.declare(b, nm, g, nm.f("blk.%d.index_head", l), g.max_tok, 32, 4096, + head_weight, w.input, w.cache.gate)); + RAD_ARCH_TRY(cache.declare(b, nm, g, l, cfg, w.cache, attention, tail, index, + nm.ckpt("%s.index_kpool_compress_ape", prefix))); + return op_norm && op_query_copy && op_gate_copy && op_head ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + auto act = [](rad_buf x) { + ActFP8 a{}; + a.x = x; + return a; + }; + query.step(ctx, act(w.q_low), w.q_wide, T); + RAD_ISSUE_N(ctx, op_query_copy, T * 32, brows(w.q_wide, T), brows(w.cache.query, T * 32)); + key_gate.step(ctx, act(w.input), w.kg_raw, T); + RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias), + bcol(w.cache.kg, 0, 128, T)); + RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T), + bcol(w.cache.kg, 128, 128, T)); + if (head_split.takes(T)) + head_split.step(ctx, T, brows(w.input, T), head_weight, brows(w.cache.gate, T)); + else + RAD_ISSUE_N(ctx, op_head, T, brows(w.input, T), RAD_W(head_weight), + brows(w.cache.gate, T)); + cache.step(ctx, batch); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_glm_kda.h b/arch/common/rad_block_glm_kda.h new file mode 100644 index 00000000..6617ae0f --- /dev/null +++ b/arch/common/rad_block_glm_kda.h @@ -0,0 +1,102 @@ +/* GLM KDA projections around the recurrent/cache core. These checkpoint weights + * are BF16. The two low-rank gate paths have no intervening activation. The + * caller supplies normalized input and owns the mHC residual connection. */ +#ifndef RAD_BLOCK_GLM_KDA_H +#define RAD_BLOCK_GLM_KDA_H +#include "rad_fp8.h" +#include "rad_block_kda_state.h" + +namespace rad { +namespace arch { +struct GlmKda { + struct Wire { + rad_buf input = 0, forget_low = 0, gate_low = 0, out = 0; + KdaState::Wire core{}; + }; + Geom g{}; + Wire w{}; + KdaState core{}; + LinearFP8 qkv{}, beta{}, forget_a{}, forget_b{}, gate_a{}, gate_b{}, output{}; + rad_op op_ar = 0; + int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const Wire& wire, + const char* prefix, const KdaState::Src& src, rad_kvgroup state, + rad_kvgroup history, bool reduce = true) { + g = geom; + w = wire; + if (!b || !prefix || g.n_embd != 4096 || g.world < 1 || 64 % g.world || !w.input || + !w.forget_low || !w.gate_low || !w.out || w.input == w.out || + w.forget_low == w.gate_low) + return RAD_E_INVAL; + // All seven projections are plain BF16 in the pinned checkpoint. + Geom bg = g; + bg.w_bf16 = true; + const int64_t width = 8192 / g.world, heads = 64 / g.world; + const auto group = grp_layer(layer); + auto act = [](rad_buf x) { + ActFP8 a{}; + a.x = x; + return a; + }; + const auto input = act(w.input); + RAD_ARCH_TRY(qkv.declare( + b, nm, bg, nm.f("blk.%d.attn_qkv", layer), 3 * width, 4096, RAD_SHARD_ROW, group, + { nm.ckpt("%s.q_proj.weight", prefix), nm.ckpt("%s.k_proj.weight", prefix), + nm.ckpt("%s.v_proj.weight", prefix) }, + input, w.core.qkv, 0, { width, width, width })); + RAD_ARCH_TRY(beta.declare(b, nm, bg, nm.f("blk.%d.attn_beta", layer), heads, 4096, + RAD_SHARD_ROW, group, { nm.ckpt("%s.b_proj.weight", prefix) }, + input, w.core.beta)); + RAD_ARCH_TRY(forget_a.declare( + b, nm, bg, nm.f("blk.%d.attn_forget_a", layer), 128, 4096, RAD_SHARD_NONE, group, + { nm.ckpt("%s.f_a_proj.weight", prefix) }, input, w.forget_low)); + RAD_ARCH_TRY(forget_b.declare( + b, nm, bg, nm.f("blk.%d.attn_forget_b", layer), width, 128, RAD_SHARD_ROW, group, + { nm.ckpt("%s.f_b_proj.weight", prefix) }, act(w.forget_low), w.core.a)); + RAD_ARCH_TRY(gate_a.declare(b, nm, bg, nm.f("blk.%d.attn_gate_a", layer), 128, 4096, + RAD_SHARD_NONE, group, + { nm.ckpt("%s.g_a_proj.weight", prefix) }, input, w.gate_low)); + RAD_ARCH_TRY(gate_b.declare(b, nm, bg, nm.f("blk.%d.attn_gate_b", layer), width, 128, + RAD_SHARD_ROW, group, { nm.ckpt("%s.g_b_proj.weight", prefix) }, + act(w.gate_low), w.core.gate)); + KdaState::Config cfg; + cfg.heads = heads; + RAD_ARCH_TRY(core.declare(b, nm, bg, layer, state, history, cfg, w.core, src)); + RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width, + RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) }, + act(w.core.out), w.out)); + if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 || + !gate_b.bf16 || !output.bf16) + return RAD_E_UNSUPPORTED; + if (reduce && g.world > 1) + op_ar = rw(b, + RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4096, g.max_tok * 4096), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { w.out }, { w.out }); + return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK; + } + void step(RadCtx* ctx, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + auto act = [](rad_buf x) { + ActFP8 a{}; + a.x = x; + return a; + }; + const auto input = act(w.input); + qkv.step(ctx, input, w.core.qkv, T); + beta.step(ctx, input, w.core.beta, T); + forget_a.step(ctx, input, w.forget_low, T); + forget_b.step(ctx, act(w.forget_low), w.core.a, T); + gate_a.step(ctx, input, w.gate_low, T); + gate_b.step(ctx, act(w.gate_low), w.core.gate, T); + core.step(ctx, batch); + output.step(ctx, act(w.core.out), w.out, T); + if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_glm_mla.h b/arch/common/rad_block_glm_mla.h new file mode 100644 index 00000000..1fe2089b --- /dev/null +++ b/arch/common/rad_block_glm_mla.h @@ -0,0 +1,118 @@ +/* No-RoPE GLM MLA. prepare() exposes normalized Q-lora for the replicated + * indexer; finish() consumes its selection. The caller owns the mHC residual. */ +#ifndef RAD_BLOCK_GLM_MLA_H +#define RAD_BLOCK_GLM_MLA_H +#include "rad_fp8.h" +#include "rad_block_mla_latent.h" + +namespace rad { +namespace arch { +struct GlmMla { + struct Wire { + ActFP8 input{}, q_low{}, attn{}; + rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0; + MlaLatent::Wire core{}; + }; + Geom g{}; + Wire w{}; + int layer = 0; + rad_kvgroup kv = 0; + LinearFP8 q_a{}, kv_a{}, q_b{}, output{}; + NormQuantFP8 q_norm{}; + QuantFP8 attn_quant{}; + MlaLatent core{}; + rad_weight q_gain = 0, kv_gain = 0; + rad_op op_kv_norm = 0, op_store = 0, op_ar = 0; + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, + const char* prefix, rad_kvgroup group, bool reduce = true, + bool defer_finish = false) { + g = geom; + w = wire; + layer = l; + kv = group; + if (!b || !prefix || !kv || g.n_embd != 4096 || g.world < 1 || 64 % g.world || !w.input.x || + !w.q_raw || !w.kv_raw || !w.latent || !w.out || !w.q_low.x || !w.attn.x || + w.attn.x != w.core.out) + return RAD_E_INVAL; + const auto wg = grp_layer(l); + RAD_ARCH_TRY(q_a.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), 1536, 4096, RAD_SHARD_NONE, + wg, { nm.ckpt("%s.q_a_proj.weight", prefix) }, w.input, w.q_raw)); + RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), 512, 4096, RAD_SHARD_NONE, + wg, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", prefix) }, w.input, + w.kv_raw)); + const char* qn = nm.f("blk.%d.attn_q_a_norm.weight", l); + const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l); + RAD_ARCH_TRY(map_copy(b, qn, nm.ckpt("%s.q_a_layernorm.weight", prefix))); + RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", prefix))); + q_gain = decl_w(b, qn, RAD_F32, { 1536 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg); + kv_gain = decl_w(b, kn, RAD_F32, { 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg); + if (!q_gain || !kv_gain) return RAD_E_INVAL; + RAD_ARCH_TRY(q_norm.declare(b, g, q_gain, w.q_raw, w.q_low, 1536)); + op_kv_norm = rw(b, + RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 512), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(kv_gain)), + { w.kv_raw }, { w.latent }); + if (!op_kv_norm) return RAD_E_INVAL; + RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), 16384 / g.world, 1536, + RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, + w.q_low, w.core.q)); + // Cache stores contiguous halves of the normalized latent, with no duplicated K/V. + op_store = rw(b, + RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", 256), + RAD_INT("n_head_kv", 1), RAD_INT("block_size", 4), + RAD_STR("kv_dtype", "bf16")), + RAD_NOWEIGHTS), + { w.latent }, {}); + if (!op_store) return RAD_E_INVAL; + return defer_finish ? RAD_OK : declare_finish(b, nm, prefix, reduce); + } + int declare_finish(RadBuilder* b, Names& nm, const char* prefix, bool reduce = true) { + MlaLatent::Config cfg; + cfg.heads = 64 / g.world; + RAD_ARCH_TRY( + core.declare(b, nm, g, layer, kv, cfg, w.core, nm.ckpt("%s.kv_b_proj.weight", prefix))); + RAD_ARCH_TRY(attn_quant.declare(b, g, w.attn, 16384 / g.world)); + RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096, + 16384 / g.world, RAD_SHARD_COL, grp_layer(layer), + { nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out)); + if (reduce && g.world > 1) + op_ar = rw(b, + RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4096, g.max_tok * 4096), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { w.out }, { w.out }); + return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL; + } + void prepare(RadCtx* ctx, const RadBatch* batch) const { + const auto* kb = kv_batch(batch, kv); + if (!kb || !kb->slot_mapping) { + rad_step_fail(ctx, "GLM MLA requires latent cache slot mapping"); + return; + } + const int64_t T = batch->n_tok; + q_a.step(ctx, w.input, w.q_raw, T); + kv_a.step(ctx, w.input, w.kv_raw, T); + q_norm.step(ctx, T); + RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T)); + q_b.step(ctx, w.q_low, w.core.q, T); + RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T), + praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer)); + } + void finish(RadCtx* ctx, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + core.step(ctx, T); + attn_quant.step(ctx, T); + output.step(ctx, w.attn, w.out, T); + if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_glm_router.h b/arch/common/rad_block_glm_router.h new file mode 100644 index 00000000..ce48cf2f --- /dev/null +++ b/arch/common/rad_block_glm_router.h @@ -0,0 +1,82 @@ +/* GLM noaux_tc router. Correction bias changes selection only; mixture weights + * come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */ +#ifndef RAD_BLOCK_GLM_ROUTER_H +#define RAD_BLOCK_GLM_ROUTER_H +#include "rad_tp_split.h" +#include + +namespace rad { +namespace arch { +struct GlmRouter { + struct Config { + int64_t experts = 288, top_k = 8, rows = 32; + int norm = 1; + double route_scale = 2.5; + }; + struct Src { + const char *weight = nullptr, *correction = nullptr; + }; + struct Wire { + rad_buf input = 0, logits = 0, ids = 0, weights = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + rad_weight projection = 0, correction = 0; + rad_op op_project = 0, op_select = 0; + SplitF32Proj split{}; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name, + const Config& cfg, const Wire& wire, const Src& src) { + g = geom; + c = cfg; + w = wire; + if (!b || !name || !src.weight || !src.correction || g.n_embd < 1 || c.experts < 1 || + c.experts > 512 || c.top_k < 1 || c.top_k > c.experts || c.rows < 1 || + c.rows > g.max_tok || !std::isfinite(c.route_scale) || c.route_scale <= 0 || !w.input || + !w.logits || !w.ids || !w.weights || w.logits == w.weights) + return RAD_E_INVAL; + const char *pn = nm.f("%s.weight", name), *cn = nm.f("%s.correction", name); + RAD_ARCH_TRY(map_copy(b, pn, src.weight)); + RAD_ARCH_TRY(map_copy(b, cn, src.correction)); + projection = decl_w(b, pn, RAD_F32, { c.experts, g.n_embd }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(layer)); + correction = decl_w(b, cn, RAD_F32, { c.experts }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(layer)); + if (!projection || !correction) return RAD_E_INVAL; + op_project = rw(b, + RAD_OP(b, "gemm_nt_f32", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.experts), + RAD_INT("K", g.n_embd), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(projection)), + { w.input }, { w.logits }); + RAD_ARCH_TRY(split.declare(b, nm, g, name, c.rows, c.experts, g.n_embd, projection, w.input, + w.logits)); + op_select = + rw(b, + RAD_OP(b, "router_sigmoid_topk", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.experts), + RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm), + RAD_F64("route_scale", c.route_scale), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(correction)), + { w.logits }, { w.ids, w.weights }); + return op_project && op_select ? RAD_OK : RAD_E_INVAL; + } + void project(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const { + if (split.takes(rows)) + split.step(ctx, rows, brow_slice(w.input, first, rows, g.n_embd), projection, + brow_slice(w.logits, output_first, rows, c.experts)); + else + RAD_ISSUE_N(ctx, op_project, rows, brow_slice(w.input, first, rows, g.n_embd), + RAD_W(projection), brow_slice(w.logits, output_first, rows, c.experts)); + } + void step(RadCtx* ctx, int64_t first, int64_t rows, int64_t output_first = 0) const { + project(ctx, first, rows, output_first); + RAD_ISSUE_N(ctx, op_select, rows, brow_slice(w.logits, output_first, rows, c.experts), + RAD_W(correction), brow_slice(w.ids, output_first, rows, c.top_k), + brow_slice(w.weights, output_first, rows, c.top_k)); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_kda_state.h b/arch/common/rad_block_kda_state.h new file mode 100644 index 00000000..559245d3 --- /dev/null +++ b/arch/common/rad_block_kda_state.h @@ -0,0 +1,128 @@ +/* GLM's recurrent core over already projected inputs. ple_conv supplies exactly + * causal depthwise convolution + SiLU, including cold start and accepted-history rollback. */ +#ifndef RAD_BLOCK_KDA_STATE_H +#define RAD_BLOCK_KDA_STATE_H +#include "rad_arch.h" +#include + +namespace rad { +namespace arch { +struct KdaState { + struct Config { + int64_t heads = 16, dim = 128, width = 4; + double lower = -5; + }; + struct Src { + const char *q_conv = nullptr, *k_conv = nullptr, *v_conv = nullptr, *alog = nullptr, + *bias = nullptr, *norm = nullptr; + }; + struct Wire { + rad_buf qkv = 0, conv = 0, a = 0, beta = 0, gate = 0, out = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + rad_kvgroup state = 0, history = 0; + rad_weight taps = 0, alog = 0, bias = 0, norm = 0; + rad_op op_conv = 0, op_verify = 0, op_prefill = 0, op_norm = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup st, rad_kvgroup cv, + const Config& cfg, const Wire& wire, const Src& src) { + g = geom; + c = cfg; + w = wire; + layer = l; + state = st; + history = cv; + if (!b || !st || !cv || c.heads < 1 || c.dim != 128 || c.width != 4 || g.max_spec > 31 || + !std::isfinite(c.lower) || c.lower >= 0 || !w.qkv || !w.conv || !w.a || !w.beta || + !w.gate || !w.out || w.qkv == w.conv || !src.q_conv || !src.k_conv || !src.v_conv || + !src.alog || !src.bias || !src.norm) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st)); + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv)); + const int64_t width = c.heads * c.dim; + const char *tn = nm.f("blk.%d.ssm_conv.weight", l), *an = nm.f("blk.%d.ssm_a", l), + *bn = nm.f("blk.%d.ssm_dt_bias", l), *nn = nm.f("blk.%d.ssm_norm.weight", l); + RAD_ARCH_TRY(map_concat(b, tn, { src.q_conv, src.k_conv, src.v_conv })); + RAD_ARCH_TRY(map_copy(b, an, src.alog)); + RAD_ARCH_TRY(map_copy(b, bn, src.bias)); + RAD_ARCH_TRY(map_copy(b, nn, src.norm)); + taps = decl_w(b, tn, RAD_BF16, { 3 * width, c.width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, + grp_layer(l), 0, { width, width, width }); + alog = + decl_w(b, an, RAD_F32, { c.heads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + bias = decl_w(b, bn, RAD_F32, { width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + norm = + decl_w(b, nn, RAD_F32, { c.dim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + if (!taps || !alog || !bias || !norm) return RAD_E_INVAL; + op_conv = rw(b, + RAD_OP(b, "ple_conv", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 3 * width), + RAD_INT("width", c.width), RAD_INT("dilation", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(taps)), + { w.qkv }, { w.conv }); + for (int verify = 0; verify < 2; ++verify) { + const rad_op op = rw( + b, + RAD_OP(b, "kda_update", + RAD_PARAMS( + RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_k", c.dim), RAD_INT("head_v", c.dim), + RAD_F64("lower_bound", c.lower), + RAD_F64("scale", 1.0 / std::sqrt((double)c.dim)), + RAD_F64("l2_eps", 1e-6), RAD_STR("mode", verify ? "verify" : "prefill"), + RAD_STR("dtype", "bf16"), + RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate")), + RAD_WEIGHTS(alog, bias)), + { w.conv, w.a, w.beta }, { w.out }); + if (verify) + op_verify = op; + else + op_prefill = op; + } + op_norm = rw(b, + RAD_OP(b, "gdn_gated_rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", c.dim), + RAD_F64("eps", g.eps), RAD_STR("act", "sigmoid")), + RAD_WEIGHTS(norm)), + { w.out, w.gate }, { w.out }); + return op_conv && op_verify && op_prefill && op_norm ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, const RadBatch* batch) const { + const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history); + if (!st || !cv || !st->state_index || !cv->state_index) { + rad_step_fail(ctx, "KDA requires recurrent and convolution state indices"); + return; + } + const int64_t T = batch->n_tok, S = batch->n_seq, width = c.heads * c.dim; + const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1; + int64_t D = 0, DT = 0; + batch_split(batch, &D, &DT); + for (int verify = 1; verify >= 0; --verify) { + const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T; + if (!seqs) continue; + const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1); + const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs); + const RadOperand accepted = + verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE; + RAD_ISSUE_N(ctx, op_conv, rows, brows(w.qkv, rows), RAD_W(taps), + kv_cache(history, layer), cu, RAD_NONE, + praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted, + brows(w.conv, rows)); + RAD_ISSUE_N(ctx, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, width, rows), + bcol(w.conv, width, width, rows), bcol(w.conv, 2 * width, width, rows), + brows(w.a, rows), brows(w.beta, rows), RAD_W(alog), RAD_W(bias), + kv_cache(state, layer), + praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted, + init, brows(w.out, rows)); + } + RAD_ISSUE_N(ctx, op_norm, T, brows(w.out, T), brows(w.gate, T), RAD_W(norm), + brows(w.out, T)); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_mhc.h b/arch/common/rad_block_mhc.h new file mode 100644 index 00000000..71bdaec5 --- /dev/null +++ b/arch/common/rad_block_mhc.h @@ -0,0 +1,136 @@ +/* GLM manifold-constrained residual connections. The mixed residual must have a + * separate destination: each output stream reads every original input stream. */ +#ifndef RAD_BLOCK_MHC_H +#define RAD_BLOCK_MHC_H +#include "rad_tp_split.h" +#include + +namespace rad { +namespace arch { +struct ManifoldConn { + struct Config { + int64_t hc = 4, iterations = 20; + double eps = 1e-6, hc_eps = 1e-6; + }; + struct Src { + const char *fn = nullptr, *scale = nullptr, *base = nullptr; + }; + struct Wire { + rad_buf h = 0, x = 0, y = 0, out = 0; + // Saved by read(), consumed by write() after the block produces y. + rad_buf post = 0, comb = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + rad_weight w_fn = 0, w_scale = 0, w_base = 0; + rad_op op_pre = 0, op_post = 0; + /* Above the split threshold under TP, GLM's projection is split by residual chunks: each rank + * computes the partials of its chunks with mhc_pre's own kernels, an all_gather joins them, + * and mhc_pre_finish completes the read on every rank (rad_tp_split.h). */ + static constexpr int64_t kChunk = 2048, kPartStride = 28; + rad_buf part = 0, parts = 0; + rad_op op_partial = 0, op_gather = 0, op_finish = 0; + int64_t split_rows = 0, part_row = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int layer, const char* name, + const Config& cfg, const Wire& wire, const Src& src, bool defer_post = false) { + g = geom; + c = cfg; + w = wire; + if (!b || !name || !src.fn || !src.scale || !src.base || g.n_embd < 1 || g.max_tok < 1 || + c.hc < 2 || c.hc > 8 || c.iterations < 1 || c.iterations > 256 || + !std::isfinite(c.eps) || !std::isfinite(c.hc_eps) || c.eps <= 0 || c.hc_eps < 0 || + !w.h || !w.x || !w.y || !w.out || !w.post || !w.comb || w.h == w.out || w.h == w.x || + w.h == w.y || w.x == w.out || w.y == w.out || w.post == w.comb) + return RAD_E_INVAL; + const int64_t width = c.hc * g.n_embd, mix = c.hc * (c.hc + 2); + const char *fn = nm.f("%s.fn", name), *scale = nm.f("%s.scale", name), + *base = nm.f("%s.base", name); + RAD_ARCH_TRY(map_copy(b, fn, src.fn)); + RAD_ARCH_TRY(map_copy(b, scale, src.scale)); + RAD_ARCH_TRY(map_copy(b, base, src.base)); + // Mixing coefficients are F32 in the checkpoint; keep them replicated under TP. + const rad_weight wf = w_fn = decl_w(b, fn, RAD_F32, { mix, width }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(layer)); + const rad_weight ws = w_scale = decl_w(b, scale, RAD_F32, { 3 }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(layer)); + const rad_weight wb = w_base = decl_w(b, base, RAD_F32, { mix }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(layer)); + if (!wf || !ws || !wb) return RAD_E_INVAL; + op_pre = rw(b, + RAD_OP(b, "mhc_pre", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations), + RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(wf, ws, wb)), + { w.h }, { w.x, w.post, w.comb }); + if (!op_pre) return RAD_E_INVAL; + RAD_ARCH_TRY(declare_split(b, nm, name)); + return defer_post ? RAD_OK : declare_post(b); + } + int declare_split(RadBuilder* b, Names& nm, const char* name) { + const int64_t total = c.hc * g.n_embd / kChunk; + split_rows = glm_tp_split_rows(); + if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || !split_rows || total % g.world) { + split_rows = 0; + return RAD_OK; + } + const int64_t mine = total / g.world, T = g.max_tok; + part_row = mine * kPartStride; + part = decl_b(b, nm.f("%s.part", name), RAD_F32, { T, part_row }); + parts = decl_b(b, nm.f("%s.parts", name), RAD_F32, { T, total * kPartStride }); + op_partial = + rw(b, + RAD_OP(b, "mhc_pre_partial", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), RAD_INT("hc", c.hc), + RAD_INT("chunk", kChunk), RAD_INT("first", g.rank * mine), + RAD_INT("chunks", mine), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_fn)), + { w.h }, { part }); + op_gather = rw(b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", part_row, T * part_row), + RAD_STR("dtype", "f32"), RAD_INT("row", part_row)), + RAD_NOWEIGHTS), + { part }, { parts }); + op_finish = rw(b, + RAD_OP(b, "mhc_pre_finish", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_INT("hc", c.hc), RAD_INT("iterations", c.iterations), + RAD_F64("eps", c.eps), RAD_F64("hc_eps", c.hc_eps), + RAD_INT("chunk", kChunk), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_scale, w_base)), + { parts, w.h }, { w.x, w.post, w.comb }); + return part && parts && op_partial && op_gather && op_finish ? RAD_OK : RAD_E_INVAL; + } + int declare_post(RadBuilder* b) { + op_post = rw(b, + RAD_OP(b, "mhc_post", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_INT("hc", c.hc), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + { w.y, w.h, w.post, w.comb }, { w.out }); + return op_post ? RAD_OK : RAD_E_INVAL; + } + void read(RadCtx* ctx, int64_t rows) const { + if (split_rows && rows >= split_rows) { + RAD_ISSUE_N(ctx, op_partial, rows, brows(w.h, rows), RAD_W(w_fn), brows(part, rows)); + RAD_ISSUE_N(ctx, op_gather, rows * part_row, brows(part, rows), brows(parts, rows)); + RAD_ISSUE_N(ctx, op_finish, rows, brows(parts, rows), brows(w.h, rows), RAD_W(w_scale), + RAD_W(w_base), brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows)); + return; + } + RAD_ISSUE_N(ctx, op_pre, rows, brows(w.h, rows), RAD_W(w_fn), RAD_W(w_scale), RAD_W(w_base), + brows(w.x, rows), brows(w.post, rows), brows(w.comb, rows)); + } + void write(RadCtx* ctx, int64_t rows) const { + RAD_ISSUE_N(ctx, op_post, rows, brows(w.y, rows), brows(w.h, rows), brows(w.post, rows), + brows(w.comb, rows), brows(w.out, rows)); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_mla_latent.h b/arch/common/rad_block_mla_latent.h new file mode 100644 index 00000000..abeb3e94 --- /dev/null +++ b/arch/common/rad_block_mla_latent.h @@ -0,0 +1,84 @@ +/* Absorbed GLM MLA core. The caller projects/norms q and stores the current + * latent before step(). Complete heads shard as rows of the shared K/V weight. */ +#ifndef RAD_BLOCK_MLA_LATENT_H +#define RAD_BLOCK_MLA_LATENT_H +#include "rad_arch.h" +#include + +namespace rad { +namespace arch { +struct MlaLatent { + struct Config { + int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513; + }; + struct Wire { + rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + rad_kvgroup kv = 0; + rad_weight projection = 0; + rad_op op_absorb = 0, op_attn = 0, op_expand = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group, + const Config& cfg, const Wire& wire, const char* source) { + g = geom; + c = cfg; + w = wire; + layer = l; + kv = group; + if (!b || !source || !group || c.heads < 1 || c.blocks < 1 || !w.q || !w.q_latent || + !w.attn_latent || !w.out || !w.selected || !w.length || w.q == w.q_latent || + w.q_latent == w.attn_latent || w.attn_latent == w.out || c.latent_dim != 512 || + c.head_dim != 256) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, group)); + const char* name = nm.f("blk.%d.attn_kv_b.weight", l); + RAD_ARCH_TRY(map_copy(b, name, source)); + // The conversion recipe decodes this small projection only. + projection = decl_w(b, name, RAD_BF16, { c.heads * 2 * c.head_dim, c.latent_dim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + if (!projection) return RAD_E_INVAL; + op_absorb = rw( + b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), + RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(projection)), + { w.q }, { w.q_latent }); + op_attn = + rw(b, + RAD_OP(b, "mla_attn", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim), + RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks), + RAD_INT("block_size", 4), + RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.q_latent, w.selected, w.length }, { w.attn_latent }); + if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL; + op_expand = rw( + b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), + RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(projection)), + { w.attn_latent }, { w.out }); + return op_absorb && op_attn && op_expand ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, int64_t rows) const { + RAD_ISSUE_N(ctx, op_absorb, rows, brows(w.q, rows), RAD_W(projection), + brows(w.q_latent, rows)); + RAD_ISSUE_N(ctx, op_attn, rows, brows(w.q_latent, rows), kv_cache(kv, layer), + brows(w.selected, rows), brows(w.length, rows), brows(w.attn_latent, rows)); + RAD_ISSUE_N(ctx, op_expand, rows, brows(w.attn_latent, rows), RAD_W(projection), + brows(w.out, rows)); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index ddb5dfd9..9849e43b 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -60,13 +60,16 @@ struct MlpFP8 { /* The next block absorbs this block's closing all-reduce, so this one must not issue it. * Counterpart of `ar_in`; both sides ask ar_fused_ok(g, T), so they agree. */ bool ar_out = false; + /* Set before declare: a clamped product (`swiglu_limit`) and its quantiser as one launch + * (GateQuantFP8::fuse_clamped). */ + bool swiglu_quant = false; /* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add * (false for the first block of a chain). `add_out`: issue the trailing add here. See * rad_fp8.h. */ int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const Src& src, bool fold = false, bool add_out = true, - int ar_in = kArNone, bool ar_out_ = false); + int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0); void step(RadCtx* c, const RadBatch* batch) const; /* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */ void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); } @@ -76,7 +79,7 @@ struct MlpFP8 { inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const Src& src, bool fold, bool add_out, - int ar_in, bool ar_out_) { + int ar_in, bool ar_out_, double swiglu_limit) { g = geom; w = wire; layer = l; ar_out = ar_out_; @@ -96,12 +99,16 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co * (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales. */ const char* down_base = nm.f("blk.%d.ffn_down", l); RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down })); - RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x)); + gq_ffn.fuse_clamped = swiglu_quant; + RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x, + false, swiglu_limit)); - /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, MXFP4, rotated 5-bit, 4-bit and int8 - * gate_up weights take the pair. Declared over int8 codes, only a host kernel would take it, - * and that would pin the layer's weights to the host. */ - if (!gate_up.bf16 && !gate_up.mx && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) + /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit + * and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product. + * Declared over int8 codes, only a host kernel would take it, and that would pin the layer's + * weights to the host. */ + if (swiglu_limit <= 0 && !gate_up.bf16 && !gate_up.f32_scale && !gate_up.mx && + !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) op_gated = decl_gated_fold(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, { w.h.q, w.h.s }, gq_ffn.want_x diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index 240b82ba..9690f686 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -48,6 +48,7 @@ #define RAD_BLOCK_MOE_FP8_H #include "rad_fp8.h" +#include "rad_block_glm_router.h" #include "rad_device.h" #include @@ -72,8 +73,10 @@ static const int64_t kMoeRouterFusedRows = 64; * * The core's histogram (core/runtime/ctx.cpp) shows which experts were chosen and dbg_resid shows * each arm's magnitude; neither shows the weights, so a top-k that sums to 0.4 instead of 1 would - * go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all. */ -inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew) { + * go unnoticed. Synchronises the stream. Off unless set: a layer number, or negative for all. + * `f32`: the weights are f32 rather than bf16 (the sigmoid router). */ +inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, rad_buf ew, + bool f32 = false) { static const char* dbg = std::getenv("RADIANCE_DEBUG_ROUTING"); if (!dbg || !ids || !ew) return; static const int want = (int)std::strtol(dbg, nullptr, 10); @@ -85,8 +88,9 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, RadStream s = rad_stream(c_); std::vector vi((size_t)top_k); std::vector vw((size_t)top_k); + std::vector vf((size_t)top_k); rad_memcpy_async(vi.data(), pi, top_k * 4, s); - rad_memcpy_async(vw.data(), pw, top_k * 2, s); + rad_memcpy_async(f32?(void*)vf.data():(void*)vw.data(), pw, top_k * (f32?4:2), s); rad_stream_sync(s); std::string line; @@ -95,6 +99,7 @@ inline void moe_debug_weights(RadCtx* c_, int layer, int64_t top_k, rad_buf ids, const uint32_t u = (uint32_t)vw[(size_t)r] << 16; float f; std::memcpy(&f, &u, 4); + if (f32) f = vf[(size_t)r]; sum += f; char b[48]; std::snprintf(b, sizeof b, "%s%d:%.4f", r ? " " : "", vi[(size_t)r], f); @@ -167,6 +172,23 @@ struct MoeFP8 { * units a routed GEMM's tail leaves idle. */ int64_t shared_lo = 0, shared_hi = 0; int norm_topk = 1; /* renormalise the kept routing weights to sum to one */ + /* GLM routing (GlmRouter): sigmoid scores with a correction bias, top-k, `route_scale` on + * the kept weights, which are then f32 in `ew`. */ + int sigmoid_router = 0; + /* With `sigmoid_router`: the selection, the scatter and an ungated shared arm's gate fill in + * one launch (`router_sigmoid_topk_scatter`) wherever the pass fits the sort's one + * workgroup; the separate ops otherwise. Byte-identical either way. */ + int router_fuse = 0; + /* Block-fp8 experts whose scale plane is f32 (format 9, dtype fp8a8f32). */ + int expert_f32_scale = 0; + double route_scale = 1.0; + /* Clamp of the SwiGLU product (swiglu_clamped); 0 is none. */ + double swiglu_limit = 0.0; + /* With `swiglu_limit`: the clamped product and its quantiser as one launch + * (GateQuantFP8::fuse_clamped), for the routed and the shared arm. */ + int swiglu_quant = 0; + /* A shared arm without its sigmoid gate: the gate plane is filled with 1. */ + int shared_ungated = 0; /* 4-bit experts (`i4*bf16[1x128]`) rather than E4M3 (`fp8_e4m3*bf16[128x128]`); for * Qwen3.8-Flash-Next this decides whether the model fits two cards (see the `moe_gemm_w4a8` * registry row). It is the stored encoding: probe() reads it from the first expert's @@ -176,6 +198,8 @@ struct MoeFP8 { * A packed 4-bit row is K/2 bytes, so a width shard must fall on a scale group; declare() * checks this per rank. */ int expert_w4 = 0; + /* OCP E2M1 codes with E8M0 scales per 32 of K; kept canonical for host-tier reads. */ + int expert_mx = 0; /* Rotated: a 128-wide Walsh-Hadamard along K baked into the stored expert weight and the * activation meeting it (the encoding's `fwht128` transform, dtype `w4a8h`; only with * `expert_w4`). @@ -242,11 +266,14 @@ struct MoeFP8 { /* the routing, one row per token */ rad_buf logits = 0; /* [max_tok, n_expert_all] bf16, the model's expert count */ rad_buf ids = 0; /* [max_tok, top_k] i32 */ - rad_buf ew = 0; /* [max_tok, top_k] bf16 */ + rad_buf ew = 0; /* [max_tok, top_k] F32 for sigmoid_router, BF16 otherwise */ rad_buf eoff = 0; /* [n_expert + 1] i32 */ rad_buf ecnt = 0; /* [n_expert] i32 */ /* the expert planes, one row per (token, slot), a pass tall */ rad_buf sorted = 0; /* [rows * top_k] i32, pass-relative slot indices */ + /* Each slot's row in `sorted`, -1 when dropped; with it the sort writes the gather's slot + * table (moe_scatter_inv, moe_gather_inv). Optional. */ + rad_buf inv = 0; /* [rows * top_k] i32 */ rad_buf egu = 0; /* [rows * top_k, 2 * n_ff_exp] bf16 */ ActFP8 eff{}; /* [rows * top_k, n_ff_exp] */ rad_buf edn = 0; /* [rows * top_k, n_embd] bf16, in sorted order */ @@ -268,6 +295,7 @@ struct MoeFP8 { Config cfg{}; const char* norm = nullptr; const char* router = nullptr; /* mlp.gate.weight, [n_expert, n_embd] bf16 */ + const char* router_bias = nullptr; /* GLM noaux_tc correction bias */ const char* experts = nullptr; /* prefix; "..{gate,up,down}_proj.weight" */ const char* shared = nullptr; /* prefix; ".{gate,up,down}_proj.weight" */ /* Stacked checkpoints (recent releases) store all experts in two tensors: @@ -287,6 +315,7 @@ struct MoeFP8 { int layer = 0; rad_weight w_norm = 0, w_router = 0, w_sgate = 0; + GlmRouter glm_router{}; /* The input was normed and quantised by the caller; this block declares no norm. */ bool ext_in = false; /* The weight runs. Only the first handle and the count reach an issue (RAD_WTAB); the rest are @@ -297,6 +326,9 @@ struct MoeFP8 { GateQuantFP8 gq_exp{}, gq_sh{}; LinearFP8 sh_gate_up{}, sh_down{}; rad_op op_router = 0, op_topk = 0, op_scatter = 0; + /* `op_scatter` is moe_scatter_inv and `op_gather` moe_gather_inv: the sort writes `w.inv` and + * the gather reads it (Wire::inv). */ + bool scatter_inv = false, gather_inv = false; /* `router_topk_scatter`, if it resolves: topk and scatter in one launch. The pair is declared * either way, since the fused form is bounded by the sort's single workgroup and a prefill * chunk exceeds it. */ @@ -308,6 +340,11 @@ struct MoeFP8 { rad_op op_router_fused = 0; int64_t router_fused_rows = 0; bool router_fused_gate = false; + /* `router_sigmoid_topk_scatter` (Config::router_fuse), up to `sigmoid_scatter_rows` tokens, + * writing the shared gate's fill too when `sigmoid_scatter_gate`. */ + rad_op op_sigmoid_scatter = 0; + int64_t sigmoid_scatter_rows = 0; + bool sigmoid_scatter_gate = false; /* The rotated re-quantisation of the block input, declared only when `expert_rot` is set and * the caller does not already write `w.hr`. */ rad_op op_hq = 0; @@ -390,11 +427,11 @@ struct MoeFP8 { static int probe(RadBuilder* b, Names& nm, int l, const Src& src, Config* cfg); /* The format `e` names: 0 block fp8, 1 four-bit, 2 four-bit rotated, 3 plain bf16, 4 the * rotated w4nl codebook, 5 and 6 that codebook at E4M3 scales per 64 and 32 of K, 7 its - * five-bit form per 64; RAD_E_DTYPE otherwise. */ + * five-bit form per 64, 8 OCP MXFP4, 9 block fp8 at f32 scales; RAD_E_DTYPE otherwise. */ static int format_of(const RadEncoding& e); /* format_of's numbers as the grouped GEMMs' dtype strings. */ - static constexpr const char* kServed[8] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h", - "w4nl64a8h", "w4nl32a8h", "w5nl64a8h" }; + static constexpr const char* kServed[10] = { "fp8a8", "w4a8", "w4a8h", "bf16", "w4nla8h", + "w4nl64a8h", "w4nl32a8h", "w5nl64a8h", "mxfp4a8", "fp8a8f32" }; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const Src& src, bool fold = false, bool add_out = true, @@ -424,6 +461,7 @@ struct MoeFP8 { }; inline int MoeFP8::format_of(const RadEncoding& e) { + if (linear_is_mxfp4(e)) return 8; if (rad_enc_is(&e, "plain") && e.n_planes == 1 && e.plane[0].dtype == RAD_BF16) return 3; if (!rad_enc_is(&e, "affine")) return RAD_E_DTYPE; const RadEncPlane* sc = rad_enc_plane(&e, "scale"); @@ -443,7 +481,11 @@ inline int MoeFP8::format_of(const RadEncoding& e) { return 7; return RAD_E_DTYPE; } - if (!sc || sc->dtype != RAD_BF16) return RAD_E_DTYPE; + if (!sc) return RAD_E_DTYPE; + if (e.n_planes == 2 && e.plane[0].dtype == RAD_F8E4M3 && sc->dtype == RAD_F32 && + !e.transform[0] && sc->block[0] == 128 && sc->block[1] == 128) + return 9; + if (sc->dtype != RAD_BF16) return RAD_E_DTYPE; if (e.n_planes == 3) { const RadEncPlane* t = rad_enc_plane(&e, "table"); if (t && t->kind == RAD_PLANE_TABLE && t->dtype == RAD_F32 && t->extent[0] == 1 && @@ -530,7 +572,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config "(fp8_e4m3*bf16[128x128]), four-bit (i4*bf16[1x128], optionally " "/fwht128; or u4 codes into a 16-entry f32 table, /fwht128) or plain " "bf16; or the codebook at E4M3 scales a 64 or 32 of K under a fixed " - "f32, or its 32-entry five-bit form at a 64. " + "f32, or its 32-entry five-bit form at a 64, or OCP MXFP4 " + "(fp4_e2m1*e8m0[1x32]). " "Convert it with a recipe that makes one of them.\n", guw, en); return RAD_E_DTYPE; } @@ -542,6 +585,8 @@ inline int MoeFP8::probe(RadBuilder* b, Names& nm, int l, const Src& src, Config cfg->expert_g64 = (f == 5 || f == 7) ? 2 : f == 6 ? 4 : 0; cfg->expert_w5 = f == 7 ? 1 : 0; cfg->expert_bf16 = f == 3 ? 1 : 0; + cfg->expert_mx = f == 8 ? 1 : 0; + cfg->expert_f32_scale = f == 9 ? 1 : 0; return RAD_OK; } @@ -560,6 +605,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the * all-reduce carries the others' share. */ const bool shared = c.n_ff_shared > 0 && src.shared; + if (shared && c.shared_ungated && src.shared_gate) return RAD_E_INVAL; /* Whether `w.sgate` is excluded from buffer sharing; set with the shared arm and required by * the fused router's gate write (see there). */ bool sgate_concurrent = false; @@ -592,7 +638,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, } prot.clear(); { - const int want = c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6 + const int want = c.expert_f32_scale ? 9 : c.expert_mx ? 8 : c.expert_bf16 ? 3 : c.expert_w5 ? 7 : c.expert_g64 == 4 ? 6 : c.expert_g64 ? 5 : c.expert_nl ? 4 : c.expert_w4 ? (c.expert_rot ? 2 : 1) : 0; auto fmt_of = [&](int64_t e, RadEncoding (&enc)[2], int (&fe)[2], const char* (&nmv)[2]) { @@ -665,16 +711,33 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* The router is replicated (see Config::n_expert_all): every rank computes the same routing * from the full residual stream, so `sorted_tok` and `expert_offset` agree across ranks - * without a collective. */ + * without a collective. The sigmoid router (GlmRouter) declares its own projection. */ + if (!c.sigmoid_router) { RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_inp.weight", l), src.router)); w_router = decl_w(b, nm.f("blk.%d.ffn_gate_inp.weight", l), RAD_BF16, {c.n_expert_all, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + } if (!ext_in) RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd, fold ? w.x : 0, 0, ar_in)); + if (c.sigmoid_router) { + if (!src.router_bias) return RAD_E_INVAL; + GlmRouter::Config rc; + rc.experts = c.n_expert_all; + rc.top_k = c.top_k; + rc.rows = c.rows; + rc.norm = c.norm_topk; + rc.route_scale = c.route_scale; + const GlmRouter::Wire wire{ w.h.x, w.logits, w.ids, w.ew }; + const GlmRouter::Src rs{ src.router, src.router_bias }; + RAD_ARCH_TRY(glm_router.declare(b, nm, g, l, nm.f("blk.%d.glm_router", l), rc, wire, rs)); + w_router = glm_router.projection; + op_router = glm_router.op_project; + op_topk = glm_router.op_select; + } else { op_router = rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", c.n_expert_all), RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), @@ -686,6 +749,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.logits}, {w.ids, w.ew}); + } /* Protected experts are sorted last (`protect`); layers without them declare no protect * list, so it is the last parameter and cut off. */ const int n_prot = prot_list ? 1 : 0; @@ -693,8 +757,15 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RadParam ps[] = { RAD_RANGE("M", 1, c.rows), RAD_INT("n_expert", c.n_expert), RAD_INT("top_k", c.top_k), RAD_INT("expert_base", c.expert_base), RAD_STR("protect", prot_list) }; - op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS), - {w.ids}, {w.sorted, w.eoff, w.ecnt}); + /* With `w.inv` the sort also writes the gather's slot table. It writes everything + * moe_scatter does, so a moe_gather_inv that does not resolve leaves moe_gather to serve. */ + if (w.inv && rad_op_declared(b, "moe_scatter_inv") && rad_op_declared(b, "moe_gather_inv")) + op_scatter = rw(b, rad_decl_op(b, "moe_scatter_inv", ps, 4 + n_prot, RAD_NOWEIGHTS), + {w.ids}, {w.sorted, w.eoff, w.ecnt, w.inv}); + scatter_inv = op_scatter != 0; + if (!op_scatter) + op_scatter = rw(b, rad_decl_op(b, "moe_scatter", ps, 4 + n_prot, RAD_NOWEIGHTS), + {w.ids}, {w.sorted, w.eoff, w.ecnt}); } /* topk and scatter in one launch. At decode each is a single 256-thread workgroup ranking @@ -705,9 +776,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, * M*top_k <= 1024 and three above (for a stable sort without atomics), and only the first is * fusible. That covers decode (eight sequences at depth 3 and top_k 10 is 320); prefill * chunks exceed it. The pair is declared either way, so the graph and buffer plan do not - * depend on it. */ + * depend on it. The sigmoid router selects in its own op and takes no fused pair. */ topk_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows ? c.rows : kMoeSortRows / c.top_k; + if (c.sigmoid_router || scatter_inv) topk_scatter_rows = 0; /* Asked for only where a loaded library declares it: a CPU-only engine would refuse the * declare, and the two separate ops serve without it. */ if (topk_scatter_rows > 0 && rad_op_declared(b, "router_topk_scatter")) { @@ -752,6 +824,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, * the parity classes. */ const bool split = c.ff_hi[0] > 0 || c.ff_hi4[0] > 0; ncls = c.ff_hi4[0] > 0 ? 4 : 2; + if (c.expert_mx && ncls == 4) { + fprintf(stderr, "radiance: MXFP4 experts use two parity tables; use equal TP width slices\n"); + return RAD_E_UNSUPPORTED; + } if (ncls == 4 && n_reg < 4) { fprintf(stderr, "radiance: layer %d serves %lld quantised experts on this rank; four " "classes need at least one each\n", l, (long long)n_reg); @@ -791,7 +867,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* The codes view's dtype and planes; a codebook's table is selected with its codes so the * relayout sees it. */ auto edt_of = [&](int f) { - return f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4 + return f == 8 ? (uint32_t)RAD_FP4E2M1 : f == 7 ? (uint32_t)RAD_U5 : c.expert_nl ? (uint32_t)RAD_U4 : c.expert_w4 ? (uint32_t)RAD_I4 : (uint32_t)RAD_F8E4M3; }; const uint32_t edt[2] = { edt_of(fmt[0]), edt_of(fmt[1]) }; @@ -819,19 +895,23 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const int sh_row = ep ? RAD_SHARD_NONE : RAD_SHARD_ROW; const int sh_col = ep ? RAD_SHARD_NONE : RAD_SHARD_COL; const int n_parts = ep ? 0 : 2; - /* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit. `sdiv` is - * how many weight rows or columns one scale covers along the split dimension. */ - const int64_t sdiv = c.expert_w4 ? 1 : RAD_FP8_BLOCK; + /* The scale grid: one per 128x128 tile for E4M3, one per row per 128 of K for 4-bit (per 32 + * for MXFP4). `sdiv` is how many weight rows or columns one scale covers along the split + * dimension. */ + const int64_t sdiv = (c.expert_w4 || c.expert_mx) ? 1 : RAD_FP8_BLOCK; /* The dtype string per projection selects the grouped GEMM; its layout hook then accepts the * experts' encoding or the kernel is not a candidate. */ const char* const edtype[2] = { kServed[fmt[0]], kServed[fmt[1]] }; /* The scale views: bf16 per (row, 128 of K) or per 128x128 tile for E4M3, or for the 64-group - * forms E4M3 per (row, 64 of K) selected with the fixed second level. With two planes it is a + * forms E4M3 per (row, 64 of K) selected with the fixed second level; f32 per 128x128 tile + * (expert_f32_scale) or E8M0 per (row, 32 of K) for MXFP4. With two planes it is a * view of the logical weight, like the codes view (rad_builder.cpp): declared at the weight's * extents and sliced in its columns, with the stored [rows, K/64] plane left to the layout * hook. `sgk` is the K one declared scale column covers. */ - const uint32_t sdt = c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16; - const int64_t sgk = c.expert_g64 ? 1 : RAD_FP8_BLOCK; + const uint32_t sdt = c.expert_f32_scale ? (uint32_t)RAD_F32 + : c.expert_mx ? (uint32_t)RAD_E8M0 + : c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16; + const int64_t sgk = c.expert_mx ? RAD_MX_GROUP : c.expert_g64 ? 1 : RAD_FP8_BLOCK; const char* escale = c.expert_g64 ? "scale,scale.1" : "scale"; /* This class's slice of each expert: gate and up rows [lo, hi), down columns [lo, hi), scale * planes the same in their own units. */ @@ -880,7 +960,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, Geom gx = g; gx.w_bf16 = true; RAD_ARCH_TRY(gq_exp.declare(b, gx, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k, - true, false)); + true, false, c.swiglu_limit)); op_dn = rw(b, rad_decl_op(b, "moe_gemm", RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), RAD_INT("K", c.n_ff_exp), RAD_INT("n_expert", ne), @@ -914,8 +994,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, nm.f("blk.%d.ffn_gate_up_exps.%lld.weight", l, (long long)(c.expert_base + e)), escale, sdt, - {c.expert_w4 ? 2 * wq[q] : fp8_blocks(2 * wq[q]), - c.expert_w4 ? g.n_embd / sgk : fp8_blocks(g.n_embd)}, + {(c.expert_w4 || c.expert_mx) ? 2 * wq[q] : fp8_blocks(2 * wq[q]), + (c.expert_w4 || c.expert_mx) ? g.n_embd / sgk : fp8_blocks(g.n_embd)}, RAD_ACCESS_CONDITIONAL, sh_row, grp_expert_slot(l, (int)s, 0), parts, n_parts); if (!h) return RAD_E_INVAL; @@ -941,7 +1021,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, nm.f("blk.%d.ffn_down_exps.%lld.weight", l, (long long)(c.expert_base + e)), escale, sdt, - {c.expert_w4 ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk}, + {(c.expert_w4 || c.expert_mx) ? g.n_embd : fp8_blocks(g.n_embd), wq[q] / sgk}, RAD_ACCESS_CONDITIONAL, sh_col, grp_expert_slot(l, (int)s, 1)); if (!h) return RAD_E_INVAL; RAD_ARCH_TRY(span(h, q, sgk)); @@ -1012,8 +1092,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* The down projection's input can be rotated in place: `w.eff` is read only by the down GEMM, * which takes the codes alone (no bf16 product is written), so the gated quantiser resolves to * the rotated op at no extra launch. */ + gq_exp.fuse_clamped = c.swiglu_quant != 0; RAD_ARCH_TRY(gq_exp.declare(b, g, w.egu, w.eff, c.n_ff_exp, "silu", c.rows * c.top_k, - false, rot)); + false, rot, c.swiglu_limit)); { const std::vector tab = tables(w_dn, w_dns); rad_op h = ncls == 4 @@ -1116,7 +1197,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, Geom gx = g; gx.w_bf16 = true; RAD_ARCH_TRY(gq_prot.declare(b, gx, b_pgu, pff, wp, "silu", c.rows * c.top_k, true, - false)); + false, c.swiglu_limit)); op_pdn = rw(b, rad_decl_op(b, "moe_gemm", RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd), RAD_INT("K", wp), RAD_INT("n_expert", np), @@ -1209,18 +1290,20 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* The gather folds the shared arm in, so `w.moe` is never written; `scale_rows` plus a * separate gather would be two dispatches per layer and a 160 KiB round trip. */ gfold = shared; - { - rad_buf grd[5] = { w.edn, w.ew, w.sorted, w.sout, w.sgate }; + for (int form = scatter_inv ? 0 : 1; form < 2 && !op_gather; ++form) { + rad_buf grd[5] = { w.edn, w.ew, form ? w.sorted : w.inv, w.sout, w.sgate }; rad_buf gwr[1] = { w.h.x }; - op_gather = RAD_OP(b, "moe_gather", + op_gather = RAD_OP(b, form ? "moe_gather" : "moe_gather_inv", RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", g.n_embd), RAD_INT("top_k", c.top_k), RAD_STR("dtype", g.dtype), - RAD_STR("act", gfold ? "sigmoid" : "none")), + RAD_STR("act", gfold && !c.shared_ungated ? "sigmoid" : "none")), RAD_NOWEIGHTS); - if (!op_gather) return RAD_E_INVAL; + if (!op_gather) continue; + gather_inv = !form; rad_op_reads (b, op_gather, grd, gfold ? 5 : 3); rad_op_writes(b, op_gather, gwr, 1); } + if (!op_gather) return RAD_E_INVAL; /* ---- the shared expert. Ordinary dense linears over the same normed input. */ if (shared) { @@ -1243,7 +1326,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.q8)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.s8)); } - if (!w.sff.q || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8))) + if (!w.sff.q || c.swiglu_limit>0 || (sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8))) RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate)); @@ -1258,8 +1341,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, { c.n_ff_shared, c.n_ff_shared }, c.shared_lo, c.shared_hi)); /* An int8 down projection fed the int8 pair reads no bf16 plane, so none is written. */ + gq_sh.fuse_clamped = c.swiglu_quant != 0; RAD_ARCH_TRY(gq_sh.declare(b, g, w.sgu, w.sff, c.n_ff_shared, "silu", c.rows, - sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8))); + sh_down.reads_x && !(w.sff.q8_fed && sh_down.probed_i8), false, + c.swiglu_limit)); RAD_ARCH_TRY(sh_down.declare(b, nm, g, down_base, g.n_embd, c.n_ff_shared, RAD_SHARD_COL, grp_layer(l), { nm.ckpt("%s.down_proj.weight", src.shared) }, @@ -1267,7 +1352,14 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, c.shared_lo, c.shared_hi)); /* The shared gate, replicated like the router so every rank computes the same gate. One * output column: the skinny GEMM kernel clamps its N tile rather than masking, so N = 1 is - * legal. */ + * legal. An ungated arm (shared_ungated) fills the gate with 1 instead. */ + if (c.shared_ungated) { + op_sgate = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("n", 1), + RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, {w.sgate}); + } else { RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), src.shared_gate)); w_sgate = decl_w(b, nm.f("blk.%d.ffn_gate_shexp.weight", l), RAD_BF16, {1, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); @@ -1276,6 +1368,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_sgate)), {w.h.x}, {w.sgate}); + } } /* ---- The router GEMM and `router_topk_scatter` as one op, plus the shared gate when the @@ -1290,7 +1383,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, * * The parameter list, weights and write set are conditional, so each is an array cut to * length. */ - if (op_topk_scatter && rad_op_declared(b, "router_gemm_topk_scatter")) { + if (op_topk_scatter && !c.shared_ungated && rad_op_declared(b, "router_gemm_topk_scatter")) { router_fused_rows = topk_scatter_rows < kMoeRouterFusedRows ? topk_scatter_rows : kMoeRouterFusedRows; const bool gate = op_sgate != 0; @@ -1319,6 +1412,50 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, router_fused_gate = op_router_fused && gate; } + /* GLM's selection and the sort as one op, plus the ungated shared arm's gate fill. Declared + * here for the reason the fused router above is: it writes `w.sgate` ahead of `op_sgate`'s + * declared index, which is safe only with `sgate` out of the sharing pool. Its other outputs + * and its input are also declared by the ops it replaces, so their planned lifetimes cover it. + * Undeclared or unresolved, the separate ops serve. */ + if (c.sigmoid_router && c.router_fuse) { + if (!rad_op_declared(b, "router_sigmoid_topk_scatter")) { + static bool told = false; + if (!told) rad_note(b, "no loaded library declares router_sigmoid_topk_scatter; the " + "selection and the sort stay separate launches"); + told = true; + } else { + sigmoid_scatter_rows = (int64_t)c.rows * c.top_k <= kMoeSortRows + ? c.rows : kMoeSortRows / c.top_k; + const bool gate = op_sgate != 0 && c.shared_ungated; + if (gate && !sgate_concurrent) { + fprintf(stderr, "radiance: layer %d: the fused selection writes the shared gate " + "ahead of its declared writer, which needs `sgate` out of the " + "sharing pool, and it is not\n", l); + return RAD_E_STATE; + } + const RadParam sp[] = { + RAD_RANGE("M", 1, sigmoid_scatter_rows), RAD_INT("n_expert", c.n_expert_all), + RAD_INT("n_local", c.n_expert), RAD_INT("top_k", c.top_k), + RAD_INT("norm", c.norm_topk), RAD_F64("route_scale", c.route_scale), + RAD_STR("dtype", "f32"), RAD_INT("expert_base", c.expert_base), + RAD_STR("protect", prot_list), + }; + const int n_sp = (int)(sizeof(sp) / sizeof(sp[0])) - (prot_list ? 0 : 1); + op_sigmoid_scatter = rad_decl_op(b, "router_sigmoid_topk_scatter", sp, n_sp, + &glm_router.correction, 1); + if (op_sigmoid_scatter) { + const rad_buf rd[1] = { w.logits }; + rad_buf wr[7] = { w.ids, w.ew, w.sorted, w.eoff, w.ecnt }; + int n_wr = 5; + if (gate) wr[n_wr++] = w.sgate; + if (scatter_inv) wr[n_wr++] = w.inv; + rad_op_reads (b, op_sigmoid_scatter, rd, 1); + rad_op_writes(b, op_sigmoid_scatter, wr, n_wr); + } + sigmoid_scatter_gate = op_sigmoid_scatter && gate; + } + } + if (g.world > 1) op_ar = rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world), @@ -1347,7 +1484,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, {w.x, w.h.x}, {w.x}); /* The layer as the prefetch sees it, indexed by model expert number (what the router ranks). */ - if (!c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) { + if (!c.sigmoid_router && !c.expert_bf16 && c.n_expert_all > 0 && n_reg > 0) { const int64_t na = c.n_expert_all; xp_parts.assign((size_t)(na * 4), 0); xp_count_at.assign((size_t)na, -1); @@ -1376,7 +1513,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool gate_done) const { /* `gate_done`: the fused router already wrote this pass's gate. */ - if (!gate_done) + if (!gate_done && c.shared_ungated) + RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.sgate, r0, rows, 1)); + else if (!gate_done) RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate), brow_slice(w.sgate, r0, rows, 1)); sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows); @@ -1415,7 +1554,18 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o /* The fused router when it resolved and the pass fits: router, topk + scatter and (with * `router_fused_gate`) the shared gate in one launch. Otherwise the separate ops. */ const bool rfused = op_router_fused && rows <= router_fused_rows; - if (rfused) + const bool sfused = op_sigmoid_scatter && rows <= sigmoid_scatter_rows; + if (sfused) { + glm_router.project(c_, r0, rows, r0); + RAD_ISSUE_N(c_, op_sigmoid_scatter, rows, brow_slice(w.logits, r0, rows, ne_all), + RAD_W(glm_router.correction), brow_slice(w.ids, r0, rows, k), + brow_slice(w.ew, r0, rows, k), brows(w.sorted, rows * k), + brows(w.eoff, ne + 1), ecnt, + sigmoid_scatter_gate ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE, + scatter_inv ? brows(w.inv, rows * k) : RAD_NONE); + } else if (c.sigmoid_router) { + glm_router.step(c_, r0, rows, r0); + } else if (rfused) RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router), router_fused_gate ? RAD_W(w_sgate) : RAD_NONE, brow_slice(w.logits, r0, rows, ne_all), @@ -1426,17 +1576,23 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router), brow_slice(w.logits, r0, rows, ne_all)); /* topk + scatter fused, or the pair. In the fused op `w.ids` is an output. */ - if (rfused) { + if (rfused || sfused) { /* the fused router wrote all five */ } else if (op_topk_scatter && rows <= topk_scatter_rows) { RAD_ISSUE_N(c_, op_topk_scatter, rows, brow_slice(w.logits, r0, rows, ne_all), brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k), brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt); } else { + if (!c.sigmoid_router) RAD_ISSUE_N(c_, op_topk, rows, brow_slice(w.logits, r0, rows, ne_all), brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k)); - RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k), - brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt); + if (scatter_inv) + RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k), + brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt, + brows(w.inv, rows * k)); + else + RAD_ISSUE_N(c_, op_scatter, rows, brow_slice(w.ids, r0, rows, k), + brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt); } /* The rotated quantisation of the input, when the experts are rotated and the caller did not @@ -1476,7 +1632,8 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1), RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2), brows(w.egu, rows * k)); - if (shared) shared_up(c_, T, r0, rows, rfused && router_fused_gate); + if (shared) shared_up(c_, T, r0, rows, + (rfused && router_fused_gate) || (sfused && sigmoid_scatter_gate)); gq_exp.step(c_, w.egu, rows * k, 0, rows * k); if (shared) gq_sh.step(c_, w.sgu, T, r0, rows); if (c.expert_bf16) @@ -1562,7 +1719,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool o * the block's delta into `h.x`. */ if (!gather_taken(g, T, gather_out_rows, gather_out_rows6)) RAD_ISSUE_N(c_, op_gather, rows, brows(w.edn, rows * k), brow_slice(w.ew, r0, rows, k), - brows(w.sorted, rows * k), + brows(gather_inv ? w.inv : w.sorted, rows * k), gfold ? brow_slice(w.sout, r0, rows, g.n_embd) : RAD_NONE, gfold ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE, brow_slice(w.h.x, r0, rows, g.n_embd)); @@ -1640,9 +1797,10 @@ inline void MoeFP8::route_report(RadCtx* c_) const { * It reports the last pass, which is the whole step by default (`c.rows` is the prefill * chunk). With more passes it is a sample, adequate for a popularity estimate. * - * `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16. - * Nothing in the core reads it (the heat engine uses `expert_count`). */ - moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew); + * `expert_w` stays null: RadRouting declares it `const float*` but these weights are bf16 + * (f32 under the sigmoid router). Nothing in the core reads it (the heat engine uses + * `expert_count`). */ + moe_debug_weights(c_, layer, c.top_k, w.ids, w.ew, c.sigmoid_router != 0); RadRouting r{}; r.expert_ids = (const int32_t*)rad_buf_ptr(c_, w.ids); r.expert_w = nullptr; diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index e1f57cc5..13ab6679 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -474,6 +474,15 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c struct GateQuantFP8 { ActFP8 a{}; rad_op op = 0; + /* The swiglu_clamped path (`limit` > 0): `op` writes the clamped bf16 product and `op_quant` + * quantises it into the codes; with `clamped_fused`, `op` is `swiglu_clamped_quant_fp8` doing + * both and `op_quant` is unset. */ + rad_op op_quant = 0; + bool clipped = false; + /* Set before declare: serve the clamped path as one `swiglu_clamped_quant_fp8` where a loaded + * library declares it and it resolves (E4M3 codes only). Byte-identical to the pair. */ + bool fuse_clamped = false; + bool clamped_fused = false; /* Whether the bf16 product is written. A consumer of the bf16 value must request it * (docs/OPS.md), but a block-fp8 down_proj reads only codes and scales; only one that reads * the bf16 plane (LinearFP8::reads_x) needs it. Skipping it saves [T, n_ff] per layer (18.2 GB @@ -491,7 +500,7 @@ struct GateQuantFP8 { int declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n, const char* act_name = "silu", int64_t max_rows = 0, bool bf16_out = true, - bool rot = false); + bool rot = false, double limit = 0); void step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; }; @@ -500,13 +509,55 @@ struct GateQuantFP8 { * bf16 output is unrotated either way. */ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, const ActFP8& act, int64_t n, const char* act_name, int64_t max_rows, - bool bf16_out, bool rot) { + bool bf16_out, bool rot, double limit) { a = act; want_x = bf16_out; + op_quant = 0; this->n = n; /* bf16 linears read the product itself: `silu_mul` into the bf16 plane only, and no * rotation. */ bf16 = g.w_bf16; + clipped = limit > 0; + clamped_fused = false; + if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL; + if (clipped) { + if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu")) return RAD_E_INVAL; + const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; + if (fuse_clamped && !bf16 && !a.q8_fed && a.cq() && a.cs() && + rad_op_declared(b, "swiglu_clamped_quant_fp8")) { + op = + RAD_OP(b, "swiglu_clamped_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS); + if (op) { + const rad_buf wr[3] = { a.cq(), a.cs(), a.x }; + rad_op_reads(b, op, &gate_up, 1); + rad_op_writes(b, op, wr, want_x ? 3 : 2); + clamped_fused = true; + return RAD_OK; + } + } + want_x = true; + op = rw(b, + RAD_OP(b, "swiglu_clamped", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("limit", limit), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + { gate_up }, { a.x }); + if (!bf16) { + if (!a.cq() || !a.cs()) return RAD_E_INVAL; + op_quant = + rw(b, + RAD_OP(b, a.q8_fed ? "quant_act_i8g" : "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + { a.x }, { a.cq(), a.cs() }); + if (!op_quant) return RAD_E_INVAL; + } + return op?RAD_OK:RAD_E_INVAL; + } if (bf16) { if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu") != 0) { fprintf(stderr, "radiance: a bf16 gate is silu over [gate|up] into a bf16 plane; " @@ -555,6 +606,22 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, inline void GateQuantFP8::step(RadCtx* c, rad_buf gate_up, int64_t T, int64_t r0, int64_t rows) const { if (rows <= 0) rows = T - r0; + if (clamped_fused) { + RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), + brow_slice(a.cq(), r0, rows, n), + brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK), + want_x ? brow_slice(a.x, r0, rows, n) : RAD_NONE); + return; + } + if (clipped) { + RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), + brow_slice(a.x, r0, rows, n)); + if (op_quant) + RAD_ISSUE_N(c, op_quant, rows, brow_slice(a.x, r0, rows, n), + brow_slice(a.cq(), r0, rows, n), + brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK)); + return; + } if (bf16 || op_q) { RAD_ISSUE_N(c, op, rows, brow_slice(gate_up, r0, rows, 2 * n), brow_slice(a.x, r0, rows, n)); if (op_q) @@ -607,6 +674,9 @@ struct LinearFP8 { /* Plain bf16 weight read by `gemm_nt` over the bf16 activation (Geom::w_bf16): no scale plane, * no quantiser. */ bool bf16 = false; + /* Block-fp8 weight whose scale plane is f32 rather than bf16 (GLM's checkpoints), read by + * `gemm_nt_q` at dtype fp8a8f32. Read from the weight's encoding. */ + bool f32_scale = false; /* Int8 weight read by `gemm_nt_q` at dtype i8a8: i8 codes with a bf16 scale per row per 128 of * K (libquant `codes=i8 group=128 scale=bf16`), against an i8 activation with an f32 scale per * (row, 128). A quarter of E4M3's error at the same bytes, and iu8 WMMA runs at the fp8 rate. @@ -1268,12 +1338,13 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha if (known) { const RadEncPlane* sc = rad_enc_plane(&enc, "scale"); if (!rad_enc_is(&enc, "affine") || enc.n_planes != 2 || enc.transform[0] || - enc.plane[0].dtype != RAD_F8E4M3 || !sc || sc->dtype != RAD_BF16 || + enc.plane[0].dtype != RAD_F8E4M3 || !sc || + (sc->dtype != RAD_BF16 && sc->dtype != RAD_F32) || sc->block[0] != RAD_FP8_BLOCK || sc->block[1] != RAD_FP8_BLOCK) { char en[256]; rad_enc_format(&enc, en, sizeof en); fprintf(stderr, "radiance: '%s' is %s, which this model's linears do not read; they " - "read bf16, fp8_e4m3*bf16[128x128], i8*bf16[1x128], " + "read bf16, fp8_e4m3*bf16[128x128] or *f32[128x128], i8*bf16[1x128], " "fp4_e2m1*e8m0[1x32], u4*f16[1x128]-u4[1x128] (or a u8 zero) and the " "ParoQuant forms. A recipe rule stores the weight in one of them " "(docs/TOOLS.md, the import rule for a shipped int4 grid)\n", wn, en); @@ -1299,13 +1370,15 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha RAD_ARCH_TRY(rp.set(row_parts, RAD_FP8_BLOCK, RAD_FP8_BLOCK, base, "scale blocks")); const char* sn = nm.f("%s.scale", base); + const auto* fp8_scale = known ? rad_enc_plane(&enc, "scale") : nullptr; + f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32; /* One stored weight, two operands: the codes and scale plane of `.weight`, block fp8 in * the checkpoint or made so by rad-convert's recipe. */ w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, rp.w, rp.n); ws_row_div = RAD_FP8_BLOCK; - ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, - access, shard, grp, rp.s, rp.n); + ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16, + { fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n); if (!w || !ws) return RAD_E_INVAL; /* An uneven slice; the scale plane takes the same slice in blocks. */ if (span_hi > 0) { @@ -1326,7 +1399,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; op = rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", f32_scale?"fp8a8f32":"fp8a8")), RAD_WEIGHTS(w, ws)), { a.q, a.s }, { y }); return RAD_OK; diff --git a/arch/common/rad_tp_split.h b/arch/common/rad_tp_split.h new file mode 100644 index 00000000..48217c60 --- /dev/null +++ b/arch/common/rad_tp_split.h @@ -0,0 +1,72 @@ +/* GLM's replicated F32 work split over the tensor-parallel ranks: each rank computes a disjoint + * part with the replicated kernel's own arithmetic and an all_gather moves the parts to every rank, + * so every value is bit-identical to the replicated computation's. */ +#ifndef RAD_TP_SPLIT_H +#define RAD_TP_SPLIT_H +#include "rad_arch.h" +#include + +namespace rad { +namespace arch { +/* Rows from which a replicated F32 projection splits its columns over the ranks + * (RADIANCE_GLM_TP_SPLIT_ROWS, 0 never). Below it the collective's latency outweighs the + * saved arithmetic, so decode keeps the replicated form. */ +inline int64_t glm_tp_split_rows() { + const char* e = std::getenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + if (!e || !*e) return 256; + const long long v = std::strtoll(e, nullptr, 10); + return v > 0 ? (int64_t)v : 0; +} + +/* The split's ops are declared whatever the step size, and each gather's message as a range of + * rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph + * with the same fixed parameters. + * + * A replicated [n, k] F32 projection computed column-split: rank r runs the same gemm_nt_f32 on + * rows [r*n/world, (r+1)*n/world) of the weight and a row-interleaved all_gather lays the slices + * out as the full [M, n]. The kernel computes every output column independently of n and the + * gather moves bytes, so each value is bit-identical to the replicated projection's. */ +struct SplitF32Proj { + rad_buf part = 0; + rad_op op_part = 0, op_gather = 0; + int64_t cols = 0, k = 0, min_rows = 0, first_col = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n, + int64_t width, rad_weight weight, rad_buf input, rad_buf output) { + min_rows = glm_tp_split_rows(); + if (g.world < 2 || !min_rows || n % g.world || (n / g.world * 4) % 16) { + min_rows = 0; + return RAD_OK; + } + cols = n / g.world; + k = width; + first_col = g.rank * cols; + part = decl_b(b, nm.f("%s.part", name), RAD_F32, { rows, cols }); + op_part = rw(b, + RAD_OP(b, "gemm_nt_f32", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", cols), RAD_INT("K", k), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(weight)), + { input }, { part }); + op_gather = rw( + b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", cols, rows * cols), + RAD_STR("dtype", "f32"), RAD_INT("row", cols)), + RAD_NOWEIGHTS), + { part }, { output }); + return part && op_part && op_gather ? RAD_OK : RAD_E_INVAL; + } + bool takes(int64_t rows) const { return min_rows && rows >= min_rows; } + void step(RadCtx* ctx, int64_t rows, RadOperand input, rad_weight weight, + RadOperand output) const { + RadOperand slice = RAD_W(weight); + slice.offset = first_col * k; + slice.rows = cols; + RAD_ISSUE_N(ctx, op_part, rows, input, slice, brows(part, rows)); + RAD_ISSUE_N(ctx, op_gather, rows * cols, brows(part, rows), output); + } +}; +} +} // namespace rad::arch +#endif diff --git a/tests/share_test.cpp b/tests/share_test.cpp index d4bb2aea..c7ad2b5b 100644 --- a/tests/share_test.cpp +++ b/tests/share_test.cpp @@ -300,4 +300,20 @@ TEST(a_unit_inner_dimension_is_sharded_as_the_matrix_it_leaves) { CHECK_EQ(weight_share(w, e, 3, stack, 2, 0, s, &why), RAD_E_SHAPE); } +TEST(glm_kda_tp4_takes_each_head_shard_from_all_three_convolution_parts) { + const auto e = rad_enc_plain(RAD_BF16); + const auto w = decl(e, { 0 }, 3 * 8192, 4, RAD_SHARD_ROW, 4, { 2048, 2048, 2048 }); + const int64_t shape[] = { 3 * 8192, 1, 4 }; + for (int rank = 0; rank < 4; ++rank) { + PlaneShare s[RAD_ENC_MAX_PLANES]; + REQUIRE_EQ(weight_share(w, e, 3, shape, 4, rank, s, nullptr), RAD_OK); + REQUIRE_EQ(s[0].rects.size(), (size_t)3); + for (int part = 0; part < 3; ++part) { + CHECK_EQ(s[0].rects[part].row0, (int64_t)(part * 8192 + rank * 2048)); + CHECK_EQ(s[0].rects[part].rows, (int64_t)2048); + CHECK_EQ(s[0].rects[part].bytes, (int64_t)8); + } + } +} + RAD_TEST_MAIN() From fba4ee018813e1d09d2f9632333ea2f1cef2f3aa Mon Sep 17 00:00:00 2001 From: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:13:01 +0200 Subject: [PATCH 062/152] glm5next: GLM-5.3-Flash -- mHC streams, KDA and sparse latent MLA, MXFP4 experts, native MTP An architecture plugin for GLM-5.3-Flash (45 layers, 4096 wide) from its Quark MXFP4 export: four mHC residual streams; KDA layers and full layers with absorbed MLA behind the DSA indexer; a MoE block of 288 MXFP4 experts (top 8, sigmoid routing with a correction bias and route_scale 2.5) and an ungated shared expert; clamped SwiGLU; the block-fp8 attention and MTP weights at their f32 scales; and its native MTP layer as the drafter. Under tensor parallelism experts shard by width, MLA by whole heads, and the f32 router and index-head projections split their columns from 256 rows. The MoE block's decode fusions are on by default (RADIANCE_GLM_ROUTER_FUSE, RADIANCE_GLM_SWIGLU_QUANT, RADIANCE_GLM_GATHER_INVERSE; 0 restores the separate launches, byte for byte). Its tool-call format is derived from the chat template, as for the other models. data/recipes/glm53-mxfp4.recipe decodes only the combined MLA projection to bf16; every other weight keeps its stored encoding. arch_test declares the model at one, two, four and eight ranks and lints its steps: the mHC connections, the routing's f32 path, the head-complete MLA shards, the indexer's cache pages and tail ring, KDA's local heads, the expert geometry at TP4 and TP8, that the sizing declares give the real graph at every arena level, where the decode fusions replace their launches, and, with the fusions off, a pinned graph and step hash. Co-Authored-By: Nunze --- arch/glm5next/CMakeLists.txt | 7 + arch/glm5next/glm5next.cpp | 552 ++++++++++++ data/recipes/glm53-mxfp4.recipe | 4 + tests/arch_test.cpp | 1438 +++++++++++++++++++++++++++++++ tests/shipped_plugins_test.cpp | 4 +- 5 files changed, 2003 insertions(+), 2 deletions(-) create mode 100644 arch/glm5next/CMakeLists.txt create mode 100644 arch/glm5next/glm5next.cpp create mode 100644 data/recipes/glm53-mxfp4.recipe diff --git a/arch/glm5next/CMakeLists.txt b/arch/glm5next/CMakeLists.txt new file mode 100644 index 00000000..4b695812 --- /dev/null +++ b/arch/glm5next/CMakeLists.txt @@ -0,0 +1,7 @@ +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(glm5next LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() +rad_add_plugin(glm5next architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/glm5next.cpp) diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp new file mode 100644 index 00000000..4b443707 --- /dev/null +++ b/arch/glm5next/glm5next.cpp @@ -0,0 +1,552 @@ +/* GLM-5.3-Flash: four mHC streams, KDA/latent MLA, mixed Quark weights, + * width-sharded routed experts and a native serial next-token decoder. + * This plugin uses only the public ABI and the installed common headers. */ +#include +#include +#include +#include +#include +#include +#include + +namespace glm5next { +using namespace rad::arch; +struct Layer { + bool full = false, draft = false; + ManifoldConn attn_hc{}, ffn_hc{}; + NormQuantFP8 norm{}; + GlmKda kda{}; + GlmMla mla{}; + GlmIndexer index{}; + MlpFP8 dense{}; + MoeFP8 moe{}; + rad_op residual = 0; +}; +struct Model { + Names nm{}, dnm{ "mtp" }; + Geom g{}; + std::vector layers; + Layer draft{}; + rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0; + rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0, + logits = 0; + ActFP8 act{}, ff{}; + GlmKda::Wire kw{}; + GlmMla::Wire aw{}; + GlmIndexer::Wire iw{}; + MlpFP8::Wire dw{}; + MoeFP8::Wire mw{}; + rad_weight token = 0, head = 0, final_gain = 0; + rad_op embed = 0, embed_ar = 0, expand = 0, contract = 0, norm = 0, gather = 0, head_op = 0; + rad_buf mtp_x = 0, mtp_h = 0, mtp_e = 0, mtp_concat = 0, mtp_final = 0; + rad_weight en = 0, hn = 0, eh = 0, mnorm = 0; + rad_op mprev = 0, membed = 0, membed_ar = 0, men = 0, mhn = 0, meh = 0, mnorm_op = 0, + mselect = 0, mback = 0, mcopy = 0, mhead = 0; + bool have_mtp = false; + bool fuse_router = false, fuse_swiglu = false, gather_inverse = false; +}; +static std::unique_ptr models[MAX_RANKS]; +static thread_local std::unique_ptr probe_model; + +static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) { + char nested[160]; + std::snprintf(nested, sizeof nested, "text_config.%s", key); + return rad_meta_geti(m, key, rad_meta_geti(m, nested, fallback)); +} +static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) { + if (g.world == 1) return 0; + return rw(b, + RAD_OP(b, "all_reduce", + RAD_PARAMS( + RAD_INT("world_size", g.world), RAD_RANGE("numel", 4096, g.max_tok * 4096), + RAD_STR("dtype", "bf16"), RAD_INT("exact", exact ? 1 : g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); +} +static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y, int64_t n = 4096) { + return rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { x }, { y }); +} +static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_buf y) { + return rw(b, + RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} +static int buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + const int64_t T = g.max_tok, W = 8192 / g.world, F = 2048 / g.world; + auto bf = [&](const char* n, int64_t width) { + return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); + }; + auto a = [&](ActFP8& v, const char* n, int64_t width) { + v.x = bf(n, width); + return v.declare_qs(b, nm, g, n, width); + }; + m.h0 = bf("manifold", 16384); + m.h1 = bf("manifold_mid", 16384); + m.x = bf("collapsed", 4096); + m.y = bf("attn_delta", 4096); + m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 }); + m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 }); + RAD_ARCH_TRY(a(m.act, "normalized", 4096)); + m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, 4096 }, RAD_BUF_PERSIST); + m.logit_input = decl_b(b, nm.f("logit_input"), RAD_BF16, { g.max_logit_rows, 4096 }); + m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab }); + RAD_ARCH_TRY(rad_declare_logits(b, m.logits)); + m.kw.input = m.act.x; + m.kw.out = m.y; + m.kw.forget_low = bf("forget_low", 128); + m.kw.gate_low = bf("gate_low", 128); + m.kw.core.qkv = bf("qkv", 3 * W); + m.kw.core.conv = bf("convolved", 3 * W); + m.kw.core.a = bf("forget", W); + m.kw.core.beta = bf("beta", 64 / g.world); + m.kw.core.gate = bf("gate", W); + m.kw.core.out = bf("recurrent_out", W); + m.aw.input = m.act; + m.aw.q_raw = bf("q_raw", 1536); + m.aw.kv_raw = bf("kv_raw", 512); + RAD_ARCH_TRY(a(m.aw.q_low, "q_low", 1536)); + m.aw.latent = bf("latent", 512); + m.aw.out = m.y; + m.aw.core.q = bf("query", 16384 / g.world); + m.aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, 64 / g.world, 512 }); + m.aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, 64 / g.world, 512 }); + RAD_ARCH_TRY(a(m.aw.attn, "expanded", 16384 / g.world)); + m.aw.core.out = m.aw.attn.x; + m.aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { T, 513 }); + m.aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { T }); + const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1; + m.iw.input = m.act.x; + m.iw.q_low = m.aw.q_low.x; + m.iw.q_wide = bf("index_query", 4096); + m.iw.kg_raw = bf("index_key_gate", 256); + auto& iw = m.iw.cache; + iw.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 }); + iw.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { T * 32, 128 }); + iw.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { T * 32, 1 }); + iw.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { T, 32 }); + iw.kg = bf("index_normalized_key_gate", 256); + iw.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 }); + iw.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work }); + iw.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work }); + iw.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs }); + iw.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 }); + iw.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 }); + iw.score = decl_b(b, nm.f("index_scores"), RAD_F32, { T, blocks }); + iw.selected = m.aw.core.selected; + iw.length = m.aw.core.length; + iw.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T }); + m.dw.x = m.x; + m.dw.h = m.act; + m.dw.gate_up = bf("dense_gate_up", 2 * g.n_ff); + RAD_ARCH_TRY(a(m.dw.ffn, "dense_ff", g.n_ff)); + const int64_t R = T; + m.mw.x = m.x; + m.mw.h = m.act; + m.mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 }); + m.mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 }); + m.mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 }); + m.mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 }); + m.mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }); + m.mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { R * 8 }); + if (m.gather_inverse) m.mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { R * 8 }); + m.mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { R * 8, 2 * F }); + m.mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { R * 8, F }); + RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "expert_ff", F, R * 8)); + m.mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { R * 8, 4096 }); + m.mw.sgu = bf("shared_gate_up", 2 * F); + RAD_ARCH_TRY(a(m.mw.sff, "shared_ff", F)); + m.mw.sout = bf("shared_out", 4096); + m.mw.sgate = bf("shared_one", 1); + return RAD_OK; +} +static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool draft) { + const auto& g = m.g; + lay.draft = draft; + lay.full = draft || l % 4 == 3; + const char* pre = nm.ckpt("model.language_model.layers.%d", l); + const char* ap = nm.ckpt("%s.self_attn", pre); + rad_buf input = draft ? m.mtp_x : m.x; + if (!draft) { + ManifoldConn::Config hc; + hc.eps = g.eps; + ManifoldConn::Wire a{ m.h0, m.x, m.y, m.h1, m.post, m.comb }; + ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb }; + ManifoldConn::Src as{ nm.ckpt("%s.hc_attn_fn", pre), nm.ckpt("%s.hc_attn_scale", pre), + nm.ckpt("%s.hc_attn_base", pre) }; + ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre), + nm.ckpt("%s.hc_ffn_base", pre) }; + RAD_ARCH_TRY(lay.attn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_attn", l), hc, a, as, true)); + // Declare ffn mHC after the attention below: declaration order is liveness. + (void)f; + (void)fs; + } + const char* nn = nm.f("blk.%d.attn_norm.weight", l); + RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre))); + const auto gain = + decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096)); + if (lay.full) { + RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true)); + DsaCache::Config c; + c.blocks = (g.max_ctx + 3) / 4 + 1; + c.work = (g.max_tok + 3) / 4 + g.max_seqs; + c.ring = 4 + g.max_spec; + RAD_ARCH_TRY(lay.index.declare(b, nm, g, l, m.iw, nm.ckpt("%s.indexer", ap), c, m.latent, + m.tail, &m.index)); + RAD_ARCH_TRY(lay.mla.declare_finish(b, nm, ap)); + } else { + KdaState::Src s{ nm.ckpt("%s.q_conv1d.weight", ap), nm.ckpt("%s.k_conv1d.weight", ap), + nm.ckpt("%s.v_conv1d.weight", ap), nm.ckpt("%s.A_log", ap), + nm.ckpt("%s.dt_bias", ap), nm.ckpt("%s.o_norm.weight", ap) }; + RAD_ARCH_TRY(lay.kda.declare(b, nm, g, l, m.kw, ap, s, m.state, m.conv)); + } + if (!draft) { + RAD_ARCH_TRY(lay.attn_hc.declare_post(b)); + ManifoldConn::Config hc; + hc.eps = g.eps; + ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb }; + ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre), + nm.ckpt("%s.hc_ffn_base", pre) }; + RAD_ARCH_TRY(lay.ffn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_ffn", l), hc, f, fs, true)); + } else { + lay.residual = rw(b, + RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.mtp_x, m.y }, { m.mtp_x }); + // All history rows fill the draft cache; only proposal rows need its FFN. + m.mselect = rw(b, + RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.mtp_x }, { m.mtp_h }); + m.mback = copy(b, g, m.mtp_h, m.mtp_x); + } + if (l < 3) { + auto w = m.dw; + w.x = input; + MlpFP8::Src s{ nm.ckpt("%s.post_attention_layernorm.weight", pre), + nm.ckpt("%s.mlp.gate_proj.weight", pre), + nm.ckpt("%s.mlp.up_proj.weight", pre), + nm.ckpt("%s.mlp.down_proj.weight", pre) }; + lay.dense.swiglu_quant = m.fuse_swiglu; + RAD_ARCH_TRY(lay.dense.declare(b, nm, g, l, w, s, false, draft, kArNone, false, 10)); + } else { + auto w = m.mw; + w.x = input; + MoeFP8::Src s; + s.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre); + s.router = nm.ckpt("%s.mlp.gate.weight", pre); + s.router_bias = nm.ckpt("%s.mlp.gate.e_score_correction_bias", pre); + s.experts = nm.ckpt("%s.mlp.experts", pre); + s.shared = nm.ckpt("%s.mlp.shared_experts", pre); + s.cfg.n_expert = s.cfg.n_expert_all = 288; + s.cfg.top_k = 8; + s.cfg.n_ff_exp = s.cfg.n_ff_shared = 2048 / g.world; + s.cfg.rows = g.max_tok; + s.cfg.sigmoid_router = 1; + s.cfg.route_scale = 2.5; + s.cfg.swiglu_limit = 10; + s.cfg.shared_ungated = 1; + s.cfg.router_fuse = m.fuse_router; + s.cfg.swiglu_quant = m.fuse_swiglu; + for (int q = 0; q < 2; ++q) { + s.cfg.ff_lo[q] = g.rank * (2048 / g.world); + s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world); + } + RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg)); + RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft)); + } + if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b)); + return RAD_OK; +} +/* A decode fusion of the MoE block, on unless its variable is 0. Each is byte-identical to the + * launches it replaces, so the switch is about speed alone; 0 restores the separate launches. */ +static int fusion_switch(const char* name, bool* out) { + const char* e = std::getenv(name); + *out = true; + if (!e || !*e || !std::strcmp(e, "1")) return RAD_OK; + if (!std::strcmp(e, "0")) { + *out = false; + return RAD_OK; + } + fprintf(stderr, "radiance: %s='%s'; it is 0 or 1\n", name, e); + return RAD_E_INVAL; +} +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS) + return RAD_E_INVAL; + const int world = ctx->world_size ? ctx->world_size : 1; + if ((world != 1 && world != 2 && world != 4 && world != 8) || meta->n_embd != 4096 || + meta->n_layers != 45 || meta->n_vocab != 154880 || + cfg(meta, "num_nextn_predict_layers", 0) != 1 || cfg(meta, "hc_mult", 0) != 4 || + cfg(meta, "n_routed_experts", 0) != 288 || cfg(meta, "index_topk", 0) != 2048 || + ctx->max_spec > 31 || (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16)) + return RAD_E_UNSUPPORTED; + auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank]; + slot = std::make_unique(); + auto& m = *slot; + auto& g = m.g; + m.nm = Names(ctx->scope); + auto& nm = m.nm; + g.n_layer = 45; + g.n_embd = 4096; + g.head_dim = 256; + g.n_head_all = g.n_head_kv_all = 64; + g.n_head = g.n_head_kv = 64 / world; + g.n_ff_all = 12288; + g.n_ff = 12288 / world; + g.n_vocab_all = 154880; + g.n_vocab = shard_extent(154880, world, ctx->rank); + g.vocab_off = shard_begin(154880, world, ctx->rank); + g.rank = ctx->rank; + g.world = world; + g.attn_world = world; + g.attn_rank = ctx->rank; + g.max_tok = ctx->max_tok; + g.max_ctx = ctx->max_ctx; + g.max_seqs = ctx->max_seqs; + g.max_spec = ctx->max_spec; + g.max_logit_rows = std::min(g.max_tok, g.max_seqs * (g.max_spec + 1)); + if (ctx->max_out_rows > g.max_logit_rows) g.max_logit_rows = ctx->max_out_rows; + g.eps = meta->rms_eps; + g.wire_exact = !ctx->tp_wire_lossy; + g.wire_min_bytes = ctx->tp_wire_min_bytes; + if (g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0) return RAD_E_INVAL; + RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_ROUTER_FUSE", &m.fuse_router)); + RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_SWIGLU_QUANT", &m.fuse_swiglu)); + RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_GATHER_INVERSE", &m.gather_inverse)); + RAD_ARCH_TRY(buffers(b, m)); + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.head_dim = 256; + m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d); + d = {}; + d.kind = RAD_KV_LINEAR; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.state_dim[0] = 4 + g.max_spec; + d.state_dim[1] = 256; + m.tail = rad_decl_kv_group(b, nm.f("kv_index_tail"), &d); + d = {}; + d.kind = RAD_KV_LINEAR; + d.dtype = RAD_F32; + d.n_head_kv = 64 / world; + d.state_dim[0] = d.state_dim[1] = 128; + m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d); + d = {}; + d.kind = RAD_KV_CONV; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.head_dim = 3 * 8192 / world; + d.conv_width = 4; + m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d); + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), + nm.ckpt("model.language_model.embed_tokens.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"))); + RAD_ARCH_TRY( + map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.language_model.norm.weight"))); + m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB, + RAD_SHARD_ROW, grp_model()); + m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, 4096 }, RAD_ACCESS_VOCAB, + RAD_SHARD_ROW, grp_model()); + m.final_gain = decl_w(b, nm.f("output_norm.weight"), RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model()); + m.embed = rw(b, + RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(m.token)), + {}, { m.x }); + m.embed_ar = reduce(b, g, m.x, true); + m.expand = copy(b, g, m.x, m.h0); + m.layers.resize(45); + for (int l = 0; l < 45; ++l) RAD_ARCH_TRY(layer(b, m, m.layers[l], nm, l, false)); + m.contract = rw(b, + RAD_OP(b, "mhc_contract", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_INT("hc", 4), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.h0 }, { m.x }); + m.norm = norm(b, g, m.final_gain, m.x, m.final_hidden); + m.gather = rw(b, + RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.final_hidden }, { m.logit_input }); + m.head_op = + rw(b, + RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab), + RAD_INT("n_embd", 4096), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.head)), + { m.logit_input }, { m.logits }); + if (g.max_spec > 0) { + auto& dn = m.dnm; + m.mtp_x = decl_b(b, dn.f("x"), RAD_BF16, { g.max_tok, 4096 }); + m.mtp_h = decl_b(b, dn.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST); + m.mtp_e = decl_b(b, dn.f("embedding"), RAD_BF16, { g.max_tok, 4096 }); + m.mtp_concat = decl_b(b, dn.f("concat"), RAD_BF16, { g.max_tok, 8192 }); + m.mtp_final = decl_b(b, dn.f("final"), RAD_BF16, { g.max_tok, 4096 }); + const char* pre = "model.language_model.layers.45"; + auto weight = [&](const char* n, const char* src) { + const char* name = dn.f("%s", n); + if (map_copy(b, name, dn.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0; + return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(45)); + }; + m.en = weight("enorm.weight", "enorm.weight"); + m.hn = weight("hnorm.weight", "hnorm.weight"); + m.mnorm = weight("output_norm.weight", "shared_head.norm.weight"); + RAD_ARCH_TRY(map_copy(b, dn.f("eh_proj.weight"), dn.ckpt("%s.eh_proj.weight", pre))); + m.eh = decl_w(b, dn.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(45)); + m.mprev = rw(b, + RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.final_hidden }, { m.mtp_h }); + m.membed = rw(b, + RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(m.token)), + {}, { m.mtp_e }); + m.membed_ar = reduce(b, g, m.mtp_e, true); + m.men = norm(b, g, m.en, m.mtp_e, m.mtp_concat); + m.mhn = norm(b, g, m.hn, m.mtp_h, m.mtp_concat); + m.meh = rw(b, + RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096), + RAD_INT("K", 8192), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.eh)), + { m.mtp_concat }, { m.mtp_x }); + RAD_ARCH_TRY(layer(b, m, m.draft, dn, 45, true)); + m.mnorm_op = norm(b, g, m.mnorm, m.mtp_x, m.mtp_final); + m.mcopy = copy(b, g, m.mtp_final, m.mtp_h); + m.mhead = + rw(b, + RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab), + RAD_INT("n_embd", 4096), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.head)), + { m.mtp_h }, { m.logits }); + RadDrafterDecl dd{}; + dd.name = "mtp"; + dd.kind = RAD_DRAFT_SERIAL; + dd.depth = g.max_spec; + dd.mask_token = -1; + RAD_ARCH_TRY(rad_declare_drafter(b, &dd)); + m.have_mtp = true; + } + rad_note(b, + "GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP %s", + world, m.have_mtp ? "enabled" : "disabled"); + return RAD_OK; +} +static void attention(RadCtx* c, Layer& l, const RadBatch* batch) { + l.norm.step(c, batch->n_tok); + if (l.full) { + l.mla.prepare(c, batch); + l.index.step(c, batch); + l.mla.finish(c, batch); + } else + l.kda.step(c, batch); +} +static void step(RadCtx* c, const RadBatch* batch) { + auto& m = *models[rad_rank(c)]; + const int64_t T = batch->n_tok; + if (batch->enc) { + rad_step_fail(c, "GLM vision is not implemented by this text plugin"); + return; + } + if (batch->draft_pass) { + if (!m.have_mtp || batch->draft_pass == 1) { + rad_step_fail(c, "GLM MTP pass is not declared or has invalid round 1"); + return; + } + if (batch->draft_pass < 0 && batch->n_out > 0) + RAD_ISSUE_N(c, m.mprev, batch->n_out, RAD_B(m.final_hidden), + praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.mtp_h, batch->n_out)); + RAD_ISSUE_N(c, m.membed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), + brows(m.mtp_e, T)); + if (m.membed_ar) RAD_ISSUE_N(c, m.membed_ar, T * 4096, brows(m.mtp_e, T), RAD_NONE); + RAD_ISSUE_N(c, m.men, T, brows(m.mtp_e, T), RAD_W(m.en), bcol(m.mtp_concat, 0, 4096, T)); + RAD_ISSUE_N(c, m.mhn, T, brows(m.mtp_h, T), RAD_W(m.hn), bcol(m.mtp_concat, 4096, 4096, T)); + RAD_ISSUE_N(c, m.meh, T, brows(m.mtp_concat, T), RAD_W(m.eh), brows(m.mtp_x, T)); + auto& l = m.draft; + l.norm.step(c, T); + l.mla.prepare(c, batch); + l.index.step(c, batch); + if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return; + l.mla.finish(c, batch); + RAD_ISSUE_N(c, l.residual, T, brows(m.mtp_x, T), brows(m.y, T), brows(m.mtp_x, T)); + const int64_t L = batch->draft_pass < 0 ? batch->n_draft_out : T; + if (batch->draft_pass < 0) { + RAD_ISSUE_N(c, m.mselect, L, RAD_B(m.mtp_x), praw(batch->draft_out_ids, RAD_I32, L), + brows(m.mtp_h, L)); + RAD_ISSUE_N(c, m.mback, L, brows(m.mtp_h, L), brows(m.mtp_x, L)); + } + l.moe.step_rows(c, L); + RAD_ISSUE_N(c, m.mnorm_op, L, brows(m.mtp_x, L), RAD_W(m.mnorm), brows(m.mtp_final, L)); + RAD_ISSUE_N(c, m.mcopy, L, brows(m.mtp_final, L), brows(m.mtp_h, L)); + RAD_ISSUE_N(c, m.mhead, L, brows(m.mtp_h, L), RAD_W(m.head), brows(m.logits, L)); + return; + } + RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T)); + if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * 4096, brows(m.x, T), RAD_NONE); + for (int i = 0; i < 4; ++i) + RAD_ISSUE_N(c, m.expand, T, brows(m.x, T), bcol(m.h0, i * 4096, 4096, T)); + for (int i = 0; i < 45; ++i) { + auto& l = m.layers[i]; + l.attn_hc.read(c, T); + attention(c, l, batch); + l.attn_hc.write(c, T); + l.ffn_hc.read(c, T); + if (i < 3) + l.dense.step(c, batch); + else + l.moe.step(c, batch); + l.ffn_hc.write(c, T); + } + RAD_ISSUE_N(c, m.contract, T, brows(m.h0, T), brows(m.x, T)); + RAD_ISSUE_N(c, m.norm, T, brows(m.x, T), RAD_W(m.final_gain), brows(m.final_hidden, T)); + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.final_hidden, T), + praw(batch->out_ids, RAD_I32, batch->n_out), + brows(m.logit_input, batch->n_out)); + RAD_ISSUE_N(c, m.head_op, batch->n_out, brows(m.logit_input, batch->n_out), RAD_W(m.head), + brows(m.logits, batch->n_out)); + } +} +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = 3; + out->shape_probe_ok = 1; + return RAD_OK; +} +} // namespace glm5next +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(glm5next) +RAD_ARCH_PLUGIN(glm5next, "glm5next", "", "0.1.0", + "GLM-5.3-Flash mixed MXFP4/FP8, mHC/KDA/MLA and native serial MTP") +#endif diff --git a/data/recipes/glm53-mxfp4.recipe b/data/recipes/glm53-mxfp4.recipe new file mode 100644 index 00000000..f8a805c1 --- /dev/null +++ b/data/recipes/glm53-mxfp4.recipe @@ -0,0 +1,4 @@ +# Decode only the small combined MLA projection, which the absorbed attention reads in bf16. +# Unmatched weights keep their stored encoding, including MXFP4 routed/shared experts +# and the mixed FP8/BF16 trunk and MTP weights. Covers trunk and draft scope names. +*attn_kv_b.weight cast dtype=bf16 diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index f858d8ba..84fbdf83 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -27,6 +27,8 @@ #include #include #include +#include +#include /* ==================================================================== the recording builder */ namespace { @@ -480,6 +482,16 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s #include "../arch/embgemma2/embgemma2.cpp" /* Qwen-Image 2.1: a generator conditioned by Qwen3-VL. */ #include "../arch/qwenimage21/qwenimage21.cpp" +/* GLM-5.3-Flash: its connection, router, attention and cache blocks, and the plugin. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include "../arch/glm5next/glm5next.cpp" /* ==================================================================== fixtures and helpers */ namespace { @@ -2298,6 +2310,1377 @@ TEST(the_encodings_the_model_holds_choose_the_flash_next_kernels) { CHECK(!p.layers[0].hc_mix.mix_e4m3); } +TEST(manifold_connections_preserve_saved_coefficients_and_use_a_separate_residual_destination) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + ManifoldConn::Config cfg; + ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", + "model.layers.3.hc_attn_base" }; + ManifoldConn::Wire w; + w.h = decl_b(&b, "h", RAD_BF16, { 32, 16384 }); + w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); + w.y = decl_b(&b, "y", RAD_BF16, { 32, 4096 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16384 }); + w.post = decl_b(&b, "post", RAD_F32, { 32, 4 }); + w.comb = decl_b(&b, "comb", RAD_F32, { 32, 16 }); + ManifoldConn conn; + REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)3); + CHECK_EQ(b.weights[0].d.shape[0], 24); + CHECK_EQ(b.weights[0].d.shape[1], 16384); + CHECK_EQ(b.weights[1].d.shape[0], 3); + CHECK_EQ(b.weights[2].d.shape[0], 24); + for (const auto& weight : b.weights) { + CHECK_EQ(weight.d.dtype, RAD_F32); + CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); + } + CHECK(b.ops[conn.op_pre - 1].reads == std::vector({ w.h })); + CHECK(b.ops[conn.op_pre - 1].writes == std::vector({ w.x, w.post, w.comb })); + CHECK(b.ops[conn.op_post - 1].reads == std::vector({ w.y, w.h, w.post, w.comb })); + CHECK(b.ops[conn.op_post - 1].writes == std::vector({ w.out })); + RadCtx ctx; + conn.read(&ctx, 4); + conn.write(&ctx, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, conn.op_pre); + CHECK_EQ(ctx.issues[1].op, conn.op_post); + CHECK_EQ(ctx.issues[0].n, 4); + CHECK_EQ(ctx.issues[1].n, 4); + REQUIRE_EQ(ctx.issues[0].opd.size(), (size_t)7); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); + const rad_weight coefficients[] = { conn.w_fn, conn.w_scale, conn.w_base }; + for (int i = 0; i < 3; ++i) { + CHECK_EQ(ctx.issues[0].opd[i + 1].kind, RAD_OPK_WEIGHT); + CHECK_EQ(ctx.issues[0].opd[i + 1].handle, coefficients[i]); + } + CHECK_EQ(ctx.issues[0].opd[4].handle, w.x); + CHECK_EQ(ctx.issues[0].opd[5].handle, w.post); + CHECK_EQ(ctx.issues[0].opd[6].handle, w.comb); + REQUIRE_EQ(ctx.issues[1].opd.size(), (size_t)5); + const rad_buf expected[] = { w.y, w.h, w.post, w.comb, w.out }; + for (int i = 0; i < 5; ++i) { + CHECK_EQ(ctx.issues[1].opd[i].handle, expected[i]); + CHECK_EQ(ctx.issues[1].opd[i].rows, 4); + } + auto invalid = w; + invalid.out = w.h; + ManifoldConn refused; + CHECK_EQ(refused.declare(&b, nm, g, 3, "bad", cfg, invalid, src), RAD_E_INVAL); +} + +TEST(manifold_read_splits_its_projection_by_chunks_over_ranks_from_the_row_threshold) { + using namespace rad::arch; + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + for (int world : { 1, 2, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.world = world; + g.rank = rank; + ManifoldConn::Config cfg; + ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", + "model.layers.3.hc_attn_base" }; + ManifoldConn::Wire w; + w.h = decl_b(&b, "h", RAD_BF16, { 512, 16384 }); + w.x = decl_b(&b, "x", RAD_BF16, { 512, 4096 }); + w.y = decl_b(&b, "y", RAD_BF16, { 512, 4096 }); + w.out = decl_b(&b, "out", RAD_BF16, { 512, 16384 }); + w.post = decl_b(&b, "post", RAD_F32, { 512, 4 }); + w.comb = decl_b(&b, "comb", RAD_F32, { 512, 16 }); + ManifoldConn conn; + REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); + const bool split = world > 1; + const int64_t mine = 8 / world; + CHECK_EQ(count_op(b, "mhc_pre"), 1); + CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 1 : 0); + CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); + CHECK_EQ(count_op(b, "mhc_pre_finish"), split ? 1 : 0); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); + if (split) { + const RecOp* part = find_op(b, "mhc_pre_partial"); + const RecOp* gather = find_op(b, "all_gather"); + const RecOp* finish = find_op(b, "mhc_pre_finish"); + REQUIRE(part && gather && finish); + CHECK_EQ(pint(part, "chunk"), 2048); + CHECK_EQ(pint(part, "first"), rank * mine); + CHECK_EQ(pint(part, "chunks"), mine); + CHECK(part->w == std::vector({ conn.w_fn })); + CHECK(part->reads == std::vector({ w.h })); + CHECK(part->writes == std::vector({ conn.part })); + CHECK_EQ(pint(gather, "world_size"), world); + CHECK_EQ(pint(gather, "row"), mine * 28); + CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); + CHECK_EQ(param(gather, "numel")->ival, mine * 28); + CHECK_EQ(param(gather, "numel")->ihi, 512 * mine * 28); + CHECK_EQ(pstr(gather, "dtype"), "f32"); + CHECK(gather->reads == std::vector({ conn.part })); + CHECK(gather->writes == std::vector({ conn.parts })); + CHECK_EQ(pint(finish, "chunk"), 2048); + CHECK_EQ(pint(finish, "iterations"), 20); + CHECK(finish->w == std::vector({ conn.w_scale, conn.w_base })); + CHECK(finish->reads == std::vector({ conn.parts, w.h })); + CHECK(finish->writes == std::vector({ w.x, w.post, w.comb })); + CHECK_EQ(find_b(b, "blk.3.mhc_attn.parts")->d.shape[1], 8 * 28); + } + RadCtx ctx; + conn.read(&ctx, 300); + conn.read(&ctx, 255); + if (split) { + REQUIRE_EQ(ctx.issues.size(), (size_t)4); + CHECK_EQ(ctx.issues[0].op, conn.op_partial); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); + CHECK_EQ(ctx.issues[0].opd[0].rows, 300); + CHECK_EQ(ctx.issues[0].opd[1].handle, conn.w_fn); + CHECK_EQ(ctx.issues[0].opd[2].handle, conn.part); + CHECK_EQ(ctx.issues[1].op, conn.op_gather); + CHECK_EQ(ctx.issues[1].n, 300 * mine * 28); + CHECK_EQ(ctx.issues[1].opd[1].handle, conn.parts); + CHECK_EQ(ctx.issues[1].opd[1].rows, 300); + CHECK_EQ(ctx.issues[2].op, conn.op_finish); + REQUIRE_EQ(ctx.issues[2].opd.size(), (size_t)7); + const uint32_t expected[] = { conn.parts, w.h, conn.w_scale, conn.w_base, + w.x, w.post, w.comb }; + for (int i = 0; i < 7; ++i) CHECK_EQ(ctx.issues[2].opd[i].handle, expected[i]); + CHECK_EQ(ctx.issues[3].op, conn.op_pre); + } else { + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, conn.op_pre); + CHECK_EQ(ctx.issues[1].op, conn.op_pre); + } + } +} + +TEST(glm_routing_keeps_f32_logits_and_correction_replicated_under_tp4) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 128; + g.world = 4; + g.rank = rank; + GlmRouter::Config cfg; + GlmRouter::Wire w; + w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); + w.logits = decl_b(&b, "logits", RAD_F32, { 32, 288 }); + w.ids = decl_b(&b, "ids", RAD_I32, { 32, 8 }); + w.weights = decl_b(&b, "weights", RAD_F32, { 32, 8 }); + GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", + "model.layers.3.mlp.gate.e_score_correction_bias" }; + GlmRouter router; + REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)2); + for (const auto& weight : b.weights) { + CHECK_EQ(weight.d.dtype, RAD_F32); + CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); + } + CHECK_EQ(b.weights[0].d.shape[0], 288); + CHECK_EQ(b.weights[0].d.shape[1], 4096); + CHECK_EQ(b.ops[router.op_project - 1].op, std::string("gemm_nt_f32")); + CHECK_EQ(b.ops[router.op_select - 1].op, std::string("router_sigmoid_topk")); + RadCtx ctx; + router.step(&ctx, 7, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); + CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); + CHECK_EQ(ctx.issues[0].opd[0].rows, 4); + CHECK_EQ(ctx.issues[1].opd[1].handle, router.correction); + CHECK_EQ(ctx.issues[1].opd[2].handle, w.ids); + CHECK_EQ(ctx.issues[1].opd[3].handle, w.weights); + } +} + +TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold) { + using namespace rad::arch; + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + for (int world : { 1, 2, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.world = world; + g.rank = rank; + GlmRouter::Config cfg; + cfg.rows = 512; + GlmRouter::Wire w; + w.input = decl_b(&b, "hidden", RAD_BF16, { 512, 4096 }); + w.logits = decl_b(&b, "logits", RAD_F32, { 512, 288 }); + w.ids = decl_b(&b, "ids", RAD_I32, { 512, 8 }); + w.weights = decl_b(&b, "weights", RAD_F32, { 512, 8 }); + GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", + "model.layers.3.mlp.gate.e_score_correction_bias" }; + GlmRouter router; + REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); + const bool split = world > 1; + const int64_t cols = 288 / world; + CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); + CHECK_EQ(count_op(b, "gemm_nt_f32"), split ? 2 : 1); + // The weight stays whole and replicated: decode keeps the unsplit projection. + CHECK_EQ(b.weights[0].d.shape[0], 288); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); + if (split) { + const RecOp* part = find_op(b, "gemm_nt_f32", 1); + const RecOp* gather = find_op(b, "all_gather"); + REQUIRE(part && gather); + CHECK_EQ(pint(part, "N"), cols); + CHECK_EQ(pint(part, "K"), 4096); + CHECK(part->w == std::vector({ router.projection })); + CHECK(part->reads == std::vector({ w.input })); + CHECK(part->writes == std::vector({ router.split.part })); + CHECK_EQ(pint(gather, "world_size"), world); + CHECK_EQ(pint(gather, "row"), cols); + CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); + CHECK_EQ(param(gather, "numel")->ival, cols); + CHECK_EQ(param(gather, "numel")->ihi, 512 * cols); + CHECK_EQ(pstr(gather, "dtype"), "f32"); + CHECK(gather->reads == std::vector({ router.split.part })); + CHECK(gather->writes == std::vector({ w.logits })); + } + RadCtx ctx; + router.step(&ctx, 7, 300, 7); + if (split) { + REQUIRE_EQ(ctx.issues.size(), (size_t)3); + CHECK_EQ(ctx.issues[0].op, router.split.op_part); + CHECK_EQ(ctx.issues[0].n, 300); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); + CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); + CHECK_EQ(ctx.issues[0].opd[0].rows, 300); + CHECK_EQ(ctx.issues[0].opd[1].kind, RAD_OPK_WEIGHT); + CHECK_EQ(ctx.issues[0].opd[1].handle, router.projection); + CHECK_EQ(ctx.issues[0].opd[1].offset, rank * cols * 4096); + CHECK_EQ(ctx.issues[0].opd[1].rows, cols); + CHECK_EQ(ctx.issues[0].opd[2].handle, router.split.part); + CHECK_EQ(ctx.issues[0].opd[2].rows, 300); + CHECK_EQ(ctx.issues[1].op, router.split.op_gather); + CHECK_EQ(ctx.issues[1].n, 300 * cols); + CHECK_EQ(ctx.issues[1].opd[0].handle, router.split.part); + CHECK_EQ(ctx.issues[1].opd[1].handle, w.logits); + CHECK_EQ(ctx.issues[1].opd[1].offset, 7 * 288); + CHECK_EQ(ctx.issues[1].opd[1].rows, 300); + CHECK_EQ(ctx.issues[2].op, router.op_select); + } else { + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, router.op_project); + } + ctx.issues.clear(); + router.step(&ctx, 0, 255); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, router.op_project); + } + { + setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "64", 1); + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 128; + g.world = 8; + g.rank = 5; + GlmRouter::Config cfg; + cfg.rows = 128; + GlmRouter::Wire w; + w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); + w.logits = decl_b(&b, "logits", RAD_F32, { 128, 288 }); + w.ids = decl_b(&b, "ids", RAD_I32, { 128, 8 }); + w.weights = decl_b(&b, "weights", RAD_F32, { 128, 8 }); + GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", + "model.layers.3.mlp.gate.e_score_correction_bias" }; + GlmRouter router; + REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); + RadCtx ctx; + router.step(&ctx, 0, 64); + router.step(&ctx, 0, 63); + REQUIRE_EQ(ctx.issues.size(), (size_t)5); + CHECK_EQ(ctx.issues[0].op, router.split.op_part); + CHECK_EQ(ctx.issues[3].op, router.op_project); + setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "0", 1); + RadBuilder off; + GlmRouter whole; + auto w2 = w; + w2.input = decl_b(&off, "hidden", RAD_BF16, { 128, 4096 }); + w2.logits = decl_b(&off, "logits", RAD_F32, { 128, 288 }); + w2.ids = decl_b(&off, "ids", RAD_I32, { 128, 8 }); + w2.weights = decl_b(&off, "weights", RAD_F32, { 128, 8 }); + REQUIRE_EQ(whole.declare(&off, nm, g, 3, "blk.3.router", cfg, w2, src), RAD_OK); + CHECK_EQ(count_op(off, "all_gather"), 0); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + } +} + +TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const rad_kvgroup kv = rad_decl_kv_group(&b, "latent", &kd); + MlaLatent::Config cfg; + MlaLatent::Wire w; + w.q = decl_b(&b, "q", RAD_BF16, { 32, 16, 256 }); + w.q_latent = decl_b(&b, "ql", RAD_BF16, { 32, 16, 512 }); + w.attn_latent = decl_b(&b, "al", RAD_BF16, { 32, 16, 512 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 256 }); + w.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); + w.length = decl_b(&b, "length", RAD_I32, { 32 }); + MlaLatent block; + REQUIRE_EQ( + block.declare(&b, nm, g, 3, kv, cfg, w, "model.layers.3.self_attn.kv_b_proj.weight"), + RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)1); + CHECK_EQ(b.weights[0].d.dtype, RAD_BF16); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[0].d.shape[0], 8192); + CHECK_EQ(b.weights[0].d.shape[1], 512); + RadCtx ctx; + block.step(&ctx, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)3); + CHECK_EQ(b.ops[ctx.issues[0].op - 1].op, std::string("mla_project")); + CHECK_EQ(b.ops[ctx.issues[1].op - 1].op, std::string("mla_attn")); + CHECK_EQ(b.ops[ctx.issues[2].op - 1].op, std::string("mla_project")); + CHECK_EQ(ctx.issues[1].opd[1].kind, RAD_OPK_KV); + CHECK_EQ(ctx.issues[1].opd[2].handle, w.selected); + CHECK_EQ(ctx.issues[1].opd[3].handle, w.length); + CHECK_EQ(ctx.issues[2].opd[1].handle, block.projection); + } +} + +TEST( + glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) { + using namespace rad::arch; + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + for (int world : { 1, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + RadBuildCtx build{}; + build.rank = rank; + build.world_size = world; + build.max_tok = rank == 0 ? 512 : 16; + build.max_seqs = 4; + build.max_ctx = 4096; + build.max_spec = 3; + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + const auto& m = *glm5next::models[rank]; + CHECK(m.have_mtp); + CHECK_EQ(b.drafter.kind, RAD_DRAFT_SERIAL); + CHECK_EQ(b.drafter.depth, 3); + CHECK_EQ(m.layers.size(), (size_t)45); + int full = 0; + for (int l = 0; l < 45; ++l) { + const auto& layer = m.layers[l]; + full += layer.full; + CHECK(layer.attn_hc.op_pre < layer.norm.op); + CHECK(layer.attn_hc.op_post < layer.ffn_hc.op_pre); + if (layer.full) { + CHECK(layer.index.cache.op_select < layer.mla.core.op_attn); + CHECK(layer.mla.output.op < layer.attn_hc.op_post); + } else + CHECK(layer.kda.output.op < layer.attn_hc.op_post); + if (l >= 3) { + CHECK_EQ(layer.moe.c.expert_mx, 1); + CHECK(layer.moe.op_gather < layer.ffn_hc.op_post); + } + } + CHECK_EQ(full, 11); + CHECK_EQ(m.draft.moe.c.expert_f32_scale, 1); + for (const auto& map : b.maps) + if (map.declared.starts_with("mtp.")) + for (const auto& source : map.src) CHECK(!source.starts_with("mtp.model.")); + int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, + slots[] = { 0, 1 }, out[] = { 1 }; + int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; + std::vector kv(b.kv_groups.size()); + for (size_t i = 0; i < kv.size(); ++i) { + kv[i].group = (rad_kvgroup)i + 1; + kv[i].slot_mapping = slots; + kv[i].block_table = tables; + kv[i].block_table_pitch = 32; + kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; + kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; + } + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 2; + batch.n_seq = 1; + batch.token_ids = ids; + batch.positions = positions; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv.data(); + batch.n_kv_groups = (int)kv.size(); + batch.n_out = 1; + batch.out_ids = out; + RadCtx ctx; + ctx.b = &b; + ctx.rank = rank; + ctx.world = world; + ctx.batch = &batch; + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "mhc_pre"), 90); + CHECK_EQ(std::count(ops.begin(), ops.end(), "kda_update"), 34); + CHECK_EQ(std::count(ops.begin(), ops.end(), "mla_attn"), 11); + // Two rows stay under the split threshold: 42 routers and 11 index heads, replicated. + CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt_f32"), 53); + CHECK_EQ(std::count(ops.begin(), ops.end(), "all_gather"), 0); + // The split is declared on every rank whatever its step size; only rank 0 issues it here. + const bool split = world > 1; + // 43 routers and 12 index heads (MTP included), and the 90 mHC reads. + CHECK_EQ(count_op(b, "all_gather"), split ? 55 + 90 : 0); + CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0); + ctx.issues.clear(); + batch.draft_pass = -1; + batch.n_draft_out = 1; + batch.draft_out_ids = out; + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + const auto draft_ops = issued_ops(b, ctx); + CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mhc_pre"), 0); + CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mla_attn"), 1); + CHECK_EQ(ctx.issues.back().op, m.mhead); + CHECK(m.mselect < m.draft.moe.op_router); + for (const auto& issue : ctx.issues) { + if (issue.op == m.draft.moe.op_router || issue.op == m.mnorm_op) + CHECK_EQ(issue.opd[0].rows, 1); // Only the row producing a proposal. + if (issue.op == m.draft.residual) + CHECK_EQ(issue.opd[0].rows, 2); // Full history still fills attention caches. + } + ctx.issues.clear(); + batch.n_draft_out = 0; + glm5next::step(&ctx, &batch); + const auto history = issued_ops(b, ctx); + CHECK(std::find(history.begin(), history.end(), "kv_store") != history.end()); + CHECK(std::find(history.begin(), history.end(), "moe_gemm_q") == history.end()); + if (rank == 0) { + std::vector long_ids(512, 7), long_positions(512), long_slots(512), + long_tables(1024); + for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; + int32_t long_cu[] = { 0, 512 }, last = 511; + for (auto& group : kv) { + group.slot_mapping = long_slots.data(); + group.block_table = long_tables.data(); + group.block_table_pitch = 1024; + } + batch.n_tok = 512; + batch.token_ids = long_ids.data(); + batch.positions = long_positions.data(); + batch.cu_seqlens = long_cu; + batch.out_ids = &last; + batch.draft_pass = 0; + batch.max_q_len = 512; + ctx.issues.clear(); + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + { + // 512 rows reach the split: each projection runs on its column slice and each + // mHC read on its chunks, both gathered; at TP1 nothing changes. + const auto long_ops = issued_ops(b, ctx); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "gemm_nt_f32"), 53); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_gather"), + world > 1 ? 53 + 90 : 0); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre"), + world > 1 ? 0 : 90); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre_finish"), + world > 1 ? 90 : 0); + for (const auto& issue : ctx.issues) { + if (b.ops[issue.op - 1].op != "gemm_nt_f32") continue; + const int64_t n = pint(&b.ops[issue.op - 1], "N"); + if (world == 1) + CHECK(n == 288 || n == 32); + else { + CHECK(n == 288 / world || n == 32 / world); + CHECK_EQ(issue.opd[1].rows, n); + } + } + } + for (int l = 3; l < 45; ++l) { + // A prefill routes its full batch once, reusing each expert's + // weights across its rows instead of re-reading them in chunks. + CHECK_EQ(std::count_if(ctx.issues.begin(), ctx.issues.end(), + [&](const auto& issue) { + const auto& moe = m.layers[l].moe; + return issue.op == moe.op_router || + issue.op == moe.glm_router.split.op_part; + }), + 1); + } + // Arena-lending probes must not replace the model the serving + // graph's handles refer to, even when they declare fewer rows. + const auto* live = glm5next::models[rank].get(); + RadBuilder pb; + pb.kv_block = 4; + pb.encs = b.encs; + auto small = build; + small.shape_probe = 1; + small.max_tok = 1; + REQUIRE_EQ(glm5next::declare(&pb, &meta, &small), RAD_OK); + CHECK_EQ(glm5next::models[rank].get(), live); + CHECK_EQ(glm5next::models[rank]->g.max_tok, 512); + RadArchProbe capabilities{}; + REQUIRE_EQ(glm5next::probe(&meta, &capabilities), RAD_OK); + CHECK_EQ(capabilities.shape_probe_ok, 1); + std::array results{}; + std::vector probes; + for (int i = 0; i < 8; ++i) + probes.emplace_back([&, i] { + RadBuilder parallel; + parallel.kv_block = 4; + parallel.encs = b.encs; + auto level = build; + level.rank = i % 4; + level.max_tok = i < 4 ? 256 : 1024; + level.shape_probe = 1; + results[i] = glm5next::declare(¶llel, &meta, &level); + }); + for (auto& thread : probes) thread.join(); + for (int status : results) CHECK_EQ(status, RAD_OK); + CHECK_EQ(glm5next::models[rank].get(), live); + } + } +} + +/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and + * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row + * counts and buffer rows smaller. The TP split declares its ops whatever the step size and its + * gathers' message as a range. */ +TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) { + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + // 256 is the default threshold; at 2048 the 256- and 1024-row levels lie below it. + const int world = 8, rank = 3; + for (const char* split : { "256", "2048" }) + for (int64_t R : { 256, 3072 }) { + setenv("RADIANCE_GLM_TP_SPLIT_ROWS", split, 1); + auto encs = [&](RadBuilder& b) { + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + }; + RadBuildCtx c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 4096; + c.max_seqs = 8; + c.max_ctx = 32768; + c.max_spec = 3; + RadBuilder full; + encs(full); + REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); + RadBuildCtx p = c; + p.max_tok = R; + p.shape_probe = 1; + RadBuilder small; + encs(small); + REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); + REQUIRE_EQ(small.ops.size(), full.ops.size()); + int differ = 0; + for (size_t i = 0; i < full.ops.size(); ++i) { + if (small.ops[i].op != full.ops[i].op) { + ++differ; + continue; + } + REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); + for (size_t k = 0; k < full.ops[i].p.size(); ++k) { + const RecParam& a = full.ops[i].p[k]; + const RecParam& q = small.ops[i].p[k]; + if (a.kind == RAD_P_RANGE) continue; + // A capacity may shrink: its kernel writes by its operands' extents. + if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) + continue; + if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { + fprintf(stderr, + " split %s R %lld: op %zu '%s' param '%s': " + "%lld real, %lld small\n", + split, (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), + a.ival, q.ival); + ++differ; + } + } + } + CHECK_EQ(differ, 0); + REQUIRE_EQ(small.bufs.size(), full.bufs.size()); + for (size_t i = 0; i < full.bufs.size(); ++i) + for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) + CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); + } + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); +} + +/* The MoE block's decode fusions (RADIANCE_GLM_*): each switch, alone and with the others, changes + * exactly its launches against the step without switches, over a two-row trunk step, its draft + * pass and a 512-row prefill (past the router fusion's one-workgroup sort), with the step lint + * clean throughout. A switch value other than 0 or 1 is refused. */ +TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + const char* const env[] = { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", + "RADIANCE_GLM_GATHER_INVERSE" }; + const int n_env = (int)(sizeof env / sizeof env[0]); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + auto clear = [&]() { + for (const char* e : env) unsetenv(e); + }; + using Counts = std::map; + /* Launches the first two switches remove (negative) and add, per step: trunk, draft pass, + * prefill. The trunk has 42 MoE layers, each a routed and a shared clamped SwiGLU, and three + * dense ones. The third turns every remaining sort and gather into its inverse form. */ + struct Delta { + const char* op; + int trunk, draft, prefill; + }; + const std::vector deltas[] = { + { { "router_sigmoid_topk_scatter", 42, 1, 0 }, + { "router_sigmoid_topk", -42, -1, 0 }, + { "moe_scatter", -42, -1, 0 }, + { "fill", -42, -1, 0 } }, + { { "swiglu_clamped_quant_fp8", 87, 2, 87 }, + { "swiglu_clamped", -87, -2, -87 }, + { "quant_act_fp8", -87, -2, -87 } }, + }; + for (int world : { 1, 8 }) { + Counts base[3]; + for (int mask = 0; mask < (1 << n_env); ++mask) { + // At one rank only the extremes: no switch reads the world. + if (world == 1 && mask && mask != (1 << n_env) - 1) continue; + for (int e = 0; e < n_env; ++e) setenv(env[e], mask >> e & 1 ? "1" : "0", 1); + RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + RadBuildCtx build{}; + build.rank = 0; + build.world_size = world; + build.max_tok = 512; + build.max_seqs = 4; + build.max_ctx = 4096; + build.max_spec = 3; + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, + slots[] = { 0, 1 }, out[] = { 1 }; + int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; + std::vector kv(b.kv_groups.size()); + for (size_t i = 0; i < kv.size(); ++i) { + kv[i].group = (rad_kvgroup)i + 1; + kv[i].slot_mapping = slots; + kv[i].block_table = tables; + kv[i].block_table_pitch = 32; + kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; + kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; + } + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 2; + batch.n_seq = 1; + batch.token_ids = ids; + batch.positions = positions; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv.data(); + batch.n_kv_groups = (int)kv.size(); + batch.n_out = 1; + batch.out_ids = out; + RadCtx ctx; + ctx.b = &b; + ctx.rank = 0; + ctx.world = world; + ctx.batch = &batch; + Counts got[3]; + /* With the inverse, the fused selection writes it as its ninth operand and the gather + * reads it as its third. */ + const rad_buf inv = find_b(b, "expert_inverse") + ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) + : 0; + CHECK_EQ(inv != 0, (mask & 4) != 0); + auto run = [&](int k) { + ctx.issues.clear(); + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + CHECK_LINT(b, &ctx); + for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; + for (const auto& is : ctx.issues) { + const RecOp* o = b.op_of(is.op); + if (!o || !inv) continue; + if (o->op == "router_sigmoid_topk_scatter") + CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && + is.opd[8].handle == inv); + if (o->op == "moe_gather_inv") + CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && + is.opd[2].handle == inv); + } + }; + run(0); + batch.draft_pass = -1; + batch.n_draft_out = 1; + batch.draft_out_ids = out; + run(1); + std::vector long_ids(512, 7), long_positions(512), long_slots(512), + long_tables(1024); + for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; + int32_t long_cu[] = { 0, 512 }, last = 511; + for (auto& group : kv) { + group.slot_mapping = long_slots.data(); + group.block_table = long_tables.data(); + group.block_table_pitch = 1024; + } + batch.n_tok = 512; + batch.token_ids = long_ids.data(); + batch.positions = long_positions.data(); + batch.cu_seqlens = long_cu; + batch.out_ids = &last; + batch.draft_pass = 0; + batch.n_draft_out = 0; + batch.max_q_len = 512; + run(2); + if (mask == 0) { + for (int k = 0; k < 3; ++k) base[k] = got[k]; + continue; + } + for (int k = 0; k < 3; ++k) { + Counts want = base[k]; + for (int e = 0; e < 2; ++e) + if (mask >> e & 1) + for (const Delta& d : deltas[e]) + want[d.op] += k == 0 ? d.trunk : k == 1 ? d.draft : d.prefill; + if (mask & 4) { + want["moe_scatter_inv"] += want["moe_scatter"]; + want["moe_scatter"] = 0; + want["moe_gather_inv"] += want["moe_gather"]; + want["moe_gather"] = 0; + } + for (auto it = want.begin(); it != want.end();) + it = it->second == 0 ? want.erase(it) : std::next(it); + if (got[k] != want) { + fprintf(stderr, " world %d switches %d step %d:", world, mask, k); + for (const auto& [op, n] : want) + if (got[k][op] != n) + fprintf(stderr, " %s %d (want %d)", op.c_str(), got[k][op], n); + for (const auto& [op, n] : got[k]) + if (!want.count(op)) fprintf(stderr, " %s %d (want 0)", op.c_str(), n); + fprintf(stderr, "\n"); + } + CHECK(got[k] == want); + } + } + } + for (const char* e : env) { + clear(); + setenv(e, "2", 1); + RadBuilder b; + RadBuildCtx build{}; + build.rank = 0; + build.world_size = 8; + build.max_tok = 64; + build.max_seqs = 4; + build.max_ctx = 4096; + build.max_spec = 3; + CHECK_EQ(glm5next::declare(&b, &meta, &build), RAD_E_INVAL); + } + clear(); +} + +TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ring) { + using namespace rad::arch; + for (bool front : { false, true }) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.max_seqs = 4; + g.max_spec = 3; + RadKVGroupDecl ad{}; + ad.kind = RAD_KV_FULL; + ad.dtype = RAD_BF16; + ad.n_head_kv = 1; + ad.head_dim = 256; + const auto attn = rad_decl_kv_group(&b, "attn", &ad); + // Claim the attention group's consumer before declaring the index group. + RAD_OP(&b, "mla_attn", RAD_PARAMS(RAD_INT("block_size", 4)), RAD_NOWEIGHTS); + RadKVGroupDecl td{}; + td.kind = RAD_KV_LINEAR; + td.dtype = RAD_BF16; + td.n_head_kv = 1; + td.state_dim[0] = 7; + td.state_dim[1] = 256; + const auto tail = rad_decl_kv_group(&b, "tail", &td); + DsaCache::Wire w; + w.query = decl_b(&b, "query", RAD_BF16, { 1024, 128 }); + w.codes = decl_b(&b, "codes", RAD_F8E4M3, { 1024, 128 }); + w.scales = decl_b(&b, "scales", RAD_F32, { 1024, 1 }); + w.gate = decl_b(&b, "gates", RAD_F32, { 32, 32 }); + w.kg = decl_b(&b, "kg", RAD_BF16, { 32, 256 }); + w.stage = decl_b(&b, "stage", RAD_BF16, { 48, 256 }); + w.page = decl_b(&b, "page", RAD_I32, { 12 }); + w.bpos = decl_b(&b, "bpos", RAD_I32, { 12 }); + w.nc = decl_b(&b, "nc", RAD_I32, { 4 }); + w.pooled = decl_b(&b, "pooled", RAD_F8E4M3, { 12, 128 }); + w.pool_scale = decl_b(&b, "pool_scale", RAD_F32, { 12, 1 }); + w.score = decl_b(&b, "score", RAD_F32, { 32, 1024 }); + w.selected = decl_b(&b, "sel", RAD_I32, { 32, 513 }); + w.nsel = decl_b(&b, "nsel", RAD_I32, { 32 }); + w.length = decl_b(&b, "len", RAD_I32, { 32 }); + DsaCache block; + DsaCache::Config cfg; + cfg.blocks = 1024; + cfg.work = 12; + cfg.ring = 7; + rad_kvgroup index = 0; + GlmIndexer indexer; + if (front) { + GlmIndexer::Wire iw; + iw.cache = w; + iw.input = decl_b(&b, "input", RAD_BF16, { 32, 4096 }); + iw.q_low = decl_b(&b, "q_low", RAD_BF16, { 32, 1536 }); + iw.q_wide = decl_b(&b, "q_wide", RAD_BF16, { 32, 4096 }); + iw.kg_raw = decl_b(&b, "kg_raw", RAD_BF16, { 32, 256 }); + REQUIRE_EQ(indexer.declare(&b, nm, g, 3, iw, "indexer", cfg, attn, tail, &index), + RAD_OK); + block = indexer.cache; + CHECK_EQ(b.weights[indexer.head_weight - 1].d.dtype, RAD_F32); + CHECK_EQ(b.weights[indexer.query.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[indexer.key_gate.w - 1].d.shard, RAD_SHARD_NONE); + } else + REQUIRE_EQ(block.declare(&b, nm, g, 3, cfg, w, attn, tail, &index, "indexer.pool.ape"), + RAD_OK); + CHECK_EQ(b.kv_groups[index - 1].d.dtype, RAD_U8); + CHECK_EQ(b.kv_groups[index - 1].d.head_dim, 17); + int32_t ibt[16]{}, abt[16]{}, sidx[12]{}, cu[] = { 0, 3, 8 }, pos[8]{}; + RadKVGroupBatch kv[3]{}; + kv[0].group = index; + kv[0].block_table = ibt; + kv[0].block_table_pitch = 8; + kv[1].group = tail; + kv[1].state_index = sidx; + kv[1].state_index_pitch = 6; + kv[2].group = attn; + kv[2].block_table = abt; + kv[2].block_table_pitch = 8; + RadBatch batch{}; + batch.n_tok = 8; + batch.n_seq = 2; + batch.n_spec = 2; + batch.kv = kv; + batch.n_kv_groups = 3; + batch.positions = pos; + batch.cu_seqlens = cu; + batch.max_ctx_len = 64; // Mixed-row bound exceeds the eight physical table columns. + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + if (front) { + indexer.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)12); + CHECK_EQ(ctx.issues[1].op, indexer.op_query_copy); + CHECK_EQ(ctx.issues[1].opd[1].rows, 256); + CHECK_EQ(ctx.issues[3].op, indexer.op_norm); + CHECK_EQ(ctx.issues[4].opd[0].offset, 128); + CHECK_EQ(ctx.issues[5].op, indexer.op_head); + ctx.issues.erase(ctx.issues.begin(), ctx.issues.begin() + 6); + } else + block.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)6); + CHECK_EQ(ctx.issues[0].n, 256); + CHECK(ctx.issues[1].opd[5].raw == ibt); + CHECK_EQ(ctx.issues[1].opd[4].cols, 6); + CHECK_EQ(ctx.issues[2].op, block.op_pool); + CHECK_EQ(ctx.issues[2].opd[5].handle, index); + CHECK_EQ(ctx.issues[3].op, block.op_tail); + CHECK_EQ(ctx.issues[4].opd[0].rows, 256); + CHECK_EQ(ctx.issues[4].opd[3].handle, index); + CHECK_EQ(ctx.issues[4].opd[4].kind, RAD_OPK_NONE); + CHECK(ctx.issues[4].opd[5].raw == ibt); + CHECK_EQ(ctx.issues[4].opd[8].cols, 8); + CHECK_EQ(ctx.issues[5].opd[0].cols, 8); + CHECK(ctx.issues[5].opd[1].raw == abt); + } +} + +TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.n_ff = 3072; + g.max_tok = 32; + g.world = 4; + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + b.encs = { { "ffn_gate_up", fp8 }, { "ffn_down", fp8 } }; + MlpFP8::Wire w; + w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); + w.h.x = decl_b(&b, "h", RAD_BF16, { 32, 4096 }); + REQUIRE_EQ(w.h.declare_qs(&b, nm, g, "h", 4096), RAD_OK); + w.gate_up = decl_b(&b, "gate_up", RAD_BF16, { 32, 6144 }); + w.ffn.x = decl_b(&b, "ffn", RAD_BF16, { 32, 3072 }); + REQUIRE_EQ(w.ffn.declare_qs(&b, nm, g, "ffn", 3072), RAD_OK); + MlpFP8 block; + MlpFP8::Src src{ "post_attention_layernorm.weight", "mlp.gate_proj.weight", + "mlp.up_proj.weight", "mlp.down_proj.weight" }; + REQUIRE_EQ(block.declare(&b, nm, g, 0, w, src, false, false, kArNone, false, 10), RAD_OK); + CHECK_EQ(block.op_gated, 0); + CHECK_EQ(b.ops[block.gq_ffn.op - 1].op, std::string("swiglu_clamped")); + RadCtx ctx; + ctx.b = &b; + block.slice(&ctx, 8, 4, 4); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "swiglu_clamped"), 1); + CHECK(std::find(ops.begin(), ops.end(), "gemm_nt_q_gated") == ops.end()); + CHECK(std::find(ops.begin(), ops.end(), "quant_act_fp8") != ops.end()); +} + +TEST(glm_mla_stores_one_normalized_latent_and_exposes_q_lora_before_sparse_attention) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const auto kv = rad_decl_kv_group(&b, "latent", &kd); + auto buf = [&](const char* name, int64_t n) { + return decl_b(&b, name, RAD_BF16, { 32, n }); + }; + GlmMla::Wire w; + w.input.x = buf("input", 4096); + w.q_raw = buf("q_raw", 1536); + w.kv_raw = buf("kv_raw", 512); + w.q_low.x = buf("q_low", 1536); + w.latent = buf("latent_out", 512); + w.out = buf("out", 4096); + REQUIRE_EQ(w.input.declare_qs(&b, nm, g, "input", 4096), RAD_OK); + REQUIRE_EQ(w.q_low.declare_qs(&b, nm, g, "q_low", 1536), RAD_OK); + w.core.q = buf("q", 4096); + w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { 32, 16, 512 }); + w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { 32, 16, 512 }); + w.core.out = buf("expanded", 4096); + w.attn.x = w.core.out; + REQUIRE_EQ(w.attn.declare_qs(&b, nm, g, "expanded", 4096), RAD_OK); + w.core.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); + w.core.length = decl_b(&b, "length", RAD_I32, { 32 }); + GlmMla block; + REQUIRE_EQ(block.declare(&b, nm, g, 3, w, "attn", kv), RAD_OK); + CHECK_EQ(b.weights[block.q_a.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[block.q_b.w - 1].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); + int32_t slots[4]{}; + RadKVGroupBatch kb{}; + kb.group = kv; + kb.slot_mapping = slots; + RadBatch batch{}; + batch.n_tok = 4; + batch.kv = &kb; + batch.n_kv_groups = 1; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.prepare(&ctx, &batch); + auto find_issue = [&](rad_op op) -> const RecIssue* { + for (const auto& issue : ctx.issues) + if (issue.op == op) return &issue; + return nullptr; + }; + const auto* store = find_issue(block.op_store); + REQUIRE(store); + CHECK_EQ(store->opd[0].handle, w.latent); + CHECK_EQ(store->opd[0].cols, 256); + CHECK_EQ(store->opd[1].offset, 256); + CHECK_EQ(store->opd[1].cols, 256); + CHECK(store->opd[2].raw == slots); + const auto before = issued_ops(b, ctx); + CHECK(std::find(before.begin(), before.end(), "mla_attn") == before.end()); + block.finish(&ctx, &batch); + const auto* attn = find_issue(block.core.op_attn); + REQUIRE(attn); + CHECK_EQ(attn->opd[2].handle, w.core.selected); + CHECK_EQ(ctx.issues.back().op, block.op_ar); + } +} + +TEST(glm_kda_projects_local_heads_and_reduces_only_after_the_output_projection) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.rank = rank; + g.max_spec = 3; + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; + sd.n_head_kv = 16; + sd.state_dim[0] = sd.state_dim[1] = 128; + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 1; + cd.head_dim = 6144; + cd.conv_width = 4; + const auto state = rad_decl_kv_group(&b, "state", &sd), + history = rad_decl_kv_group(&b, "conv", &cd); + auto buf = [&](const char* name, int64_t width) { + return decl_b(&b, name, RAD_BF16, { 32, width }); + }; + GlmKda::Wire w; + w.input = buf("input", 4096); + w.forget_low = buf("forget_low", 128); + w.gate_low = buf("gate_low", 128); + w.out = buf("out", 4096); + w.core.qkv = buf("qkv", 6144); + w.core.conv = buf("conv_out", 6144); + w.core.a = buf("a", 2048); + w.core.beta = buf("beta", 16); + w.core.gate = buf("gate", 2048); + w.core.out = buf("core_out", 2048); + KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", + "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; + GlmKda block; + REQUIRE_EQ(block.declare(&b, nm, g, 0, w, "attn", src, state, history), RAD_OK); + CHECK_EQ(b.weights[block.qkv.w - 1].d.n_row_parts, 3); + CHECK_EQ(b.weights[block.forget_a.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[block.forget_b.w - 1].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); + int32_t cu[] = { 0, 4 }, ctxlens[] = { 0 }, indices[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }; + RadKVGroupBatch kv[2]{}; + kv[0].group = state; + kv[0].state_index = indices; + kv[0].state_index_pitch = 6; + kv[1].group = history; + kv[1].state_index = ci; + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 4; + batch.n_seq = 1; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv; + batch.n_kv_groups = 2; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.step(&ctx, &batch); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt"), 7); + CHECK_EQ(std::count(ops.begin(), ops.end(), "silu"), 0); + REQUIRE_EQ(ctx.issues.size(), (size_t)11); + CHECK_EQ(ctx.issues[9].op, block.output.op); + CHECK_EQ(ctx.issues[10].op, block.op_ar); + CHECK_EQ(ctx.issues[10].opd[0].handle, w.out); + } +} + +TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.max_spec = 3; + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; + sd.n_head_kv = 16; + sd.state_dim[0] = sd.state_dim[1] = 128; + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 1; + cd.head_dim = 6144; + cd.conv_width = 4; + const rad_kvgroup st = rad_decl_kv_group(&b, "state", &sd), + cv = rad_decl_kv_group(&b, "conv", &cd); + KdaState::Wire w; + w.qkv = decl_b(&b, "qkv", RAD_BF16, { 32, 6144 }); + w.conv = decl_b(&b, "filtered", RAD_BF16, { 32, 6144 }); + w.a = decl_b(&b, "a", RAD_BF16, { 32, 2048 }); + w.beta = decl_b(&b, "beta", RAD_BF16, { 32, 16 }); + w.gate = decl_b(&b, "gate", RAD_BF16, { 32, 2048 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 128 }); + KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", + "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; + KdaState block; + KdaState::Config cfg; + REQUIRE_EQ(block.declare(&b, nm, g, 0, st, cv, cfg, w, src), RAD_OK); + CHECK_EQ(b.weights[block.taps - 1].d.n_row_parts, 3); + for (int p = 0; p < 3; ++p) CHECK_EQ(b.weights[block.taps - 1].d.row_parts[p], 2048); + CHECK_EQ(b.weights[block.bias - 1].d.shape[0], 2048); + for (rad_op op : { block.op_prefill, block.op_verify }) { + bool found = false; + for (const auto& p : b.ops[op - 1].p) + if (p.key == "state_form") { + CHECK_EQ(p.sval, std::string("anchor")); + found = true; + } + CHECK(found); + } + int32_t cu[] = { 0, 3, 8 }, ctxlens[] = { 11, 0 }, accepted[] = { 2, 1 }; + int32_t indices[] = { 0, 0, 0, 2, 2, 2, 1, 1, 1, 3, 3, 3 }, conv_indices[] = { 0, 1 }; + RadKVGroupBatch kv[2]{}; + kv[0].group = st; + kv[0].state_index = indices; + kv[0].state_index_pitch = 6; + kv[1].group = cv; + kv[1].state_index = conv_indices; + kv[1].state_index_pitch = 1; + RadBatch batch{}; + batch.phase = RAD_PHASE_MIXED; + batch.n_tok = 8; + batch.n_seq = 2; + batch.n_seq_decode = 1; + batch.n_tok_decode = 3; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.num_accepted = accepted; + batch.kv = kv; + batch.n_kv_groups = 2; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)5); + CHECK_EQ(ctx.issues[0].op, block.op_conv); + CHECK_EQ(ctx.issues[0].n, 3); + CHECK_EQ(ctx.issues[1].op, block.op_verify); + CHECK_EQ(ctx.issues[1].opd[0].cols, 2048); + CHECK_EQ(ctx.issues[1].opd[1].offset, 2048); + CHECK_EQ(ctx.issues[1].opd[2].offset, 4096); + CHECK_EQ(ctx.issues[2].op, block.op_conv); + CHECK_EQ(ctx.issues[2].n, 8); + CHECK(ctx.issues[2].opd[3].raw == cu + 1); + CHECK_EQ(ctx.issues[2].opd[7].kind, RAD_OPK_NONE); + CHECK_EQ(ctx.issues[3].op, block.op_prefill); + CHECK(ctx.issues[3].opd[8].raw == indices + 6); + CHECK(ctx.issues[3].opd[9].raw == cu + 1); + CHECK_EQ(ctx.issues[3].opd[0].offset, 0); + CHECK_EQ(ctx.issues[3].opd[0].rows, 8); + CHECK_EQ(ctx.issues[4].op, block.op_norm); +} + +TEST(mxfp4_expert_declarations_preserve_tp4_and_tp8_scale_geometry_and_movement_groups) { + using namespace rad::arch; + const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + REQUIRE(rad_enc_valid(&mx)); + CHECK_EQ(MoeFP8::format_of(mx), 8); + for (int world : { 4, 8 }) + for (bool glm : { false, true }) + for (int rank = 0; rank < world; ++rank) { + const int64_t F = 2048 / world; + RadBuilder b; + b.encs = { { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx } }; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = world; + g.rank = rank; + MoeFP8::Src src{}; + src.router = "mlp.gate.weight"; + src.experts = "mlp.experts"; + src.cfg.n_expert = src.cfg.n_expert_all = 288; + src.cfg.top_k = 8; + src.cfg.n_ff_exp = F; + src.cfg.rows = 32; + if (glm) { + src.router_bias = "mlp.gate.e_score_correction_bias"; + src.shared = "mlp.shared_experts"; + src.cfg.sigmoid_router = 1; + src.cfg.route_scale = 2.5; + src.cfg.swiglu_limit = 10; + src.cfg.shared_ungated = 1; + src.cfg.n_ff_shared = F; + } + for (int q = 0; q < 2; ++q) { + src.cfg.ff_lo[q] = rank * F; + src.cfg.ff_hi[q] = (rank + 1) * F; + } + REQUIRE_EQ(MoeFP8::probe(&b, nm, 3, src, &src.cfg), RAD_OK); + CHECK_EQ(src.cfg.expert_mx, 1); + CHECK_EQ(src.cfg.expert_w4, 0); + MoeFP8::Wire w{}; + auto buf = [&](const char* name, uint32_t dt, int64_t rows, int64_t cols) { + return decl_b(&b, name, dt, { rows, cols }); + }; + w.h.x = buf("h", RAD_BF16, 32, 4096); + REQUIRE_EQ(w.h.declare_qs(&b, nm, g, "h", 4096), RAD_OK); + w.logits = buf("logits", glm ? RAD_F32 : RAD_BF16, 32, 288); + w.ids = buf("ids", RAD_I32, 32, 8); + w.ew = buf("ew", glm ? RAD_F32 : RAD_BF16, 32, 8); + w.eoff = decl_b(&b, "offset", RAD_I32, { 289 }); + w.ecnt = decl_b(&b, "count", RAD_I32, { 288 }); + w.sorted = decl_b(&b, "sorted", RAD_I32, { 256 }); + w.egu = buf("gate_up", RAD_BF16, 256, 2 * F); + w.eff.x = buf("ff", RAD_BF16, 256, F); + REQUIRE_EQ(w.eff.declare_qs(&b, nm, g, "ff", F, 256), RAD_OK); + w.edn = buf("down", RAD_BF16, 256, 4096); + if (glm) { + w.sgu = buf("shared_gu", RAD_BF16, 32, 2 * F); + w.sff.x = buf("shared_ff", RAD_BF16, 32, F); + REQUIRE_EQ(w.sff.declare_qs(&b, nm, g, "shared_ff", F), RAD_OK); + w.sout = buf("shared_out", RAD_BF16, 32, 4096); + w.sgate = buf("shared_one", RAD_BF16, 32, 1); + } + MoeFP8 moe; + REQUIRE_EQ(moe.declare(&b, nm, g, 3, w, src, false, false), RAD_OK); + CHECK_EQ(moe.ncls, 2); + if (glm) { + CHECK_EQ(b.weights[moe.w_router - 1].d.dtype, RAD_F32); + CHECK_EQ(b.ops[moe.op_topk - 1].op, std::string("router_sigmoid_topk")); + CHECK_EQ(moe.op_topk_scatter, 0); + CHECK_EQ(moe.op_router_fused, 0); + CHECK_EQ(b.ops[moe.gq_exp.op - 1].op, std::string("swiglu_clamped")); + CHECK_EQ(b.ops[moe.gq_sh.op - 1].op, std::string("swiglu_clamped")); + CHECK_EQ(b.ops[moe.op_sgate - 1].op, std::string("fill")); + CHECK_EQ(moe.w_sgate, 0); + bool plain_shared = false; + for (const auto& p : b.ops[moe.op_gather - 1].p) + if (p.key == "act") plain_shared = p.sval == "none"; + CHECK(plain_shared); + RadCtx ctx; + ctx.b = &b; + ctx.rank = rank; + ctx.world = world; + moe.pass(&ctx, 8, 4, 4); + const auto ops = issued_ops(b, ctx); + CHECK(std::find(ops.begin(), ops.end(), "router_sigmoid_topk") != ops.end()); + CHECK(std::find(ops.begin(), ops.end(), "router_topk") == ops.end()); + CHECK_EQ(std::count(ops.begin(), ops.end(), "swiglu_clamped"), 2); + CHECK_EQ(std::count(ops.begin(), ops.end(), "fill"), 1); + for (const auto& issue : ctx.issues) + if (issue.op == moe.op_sgate) { + REQUIRE_EQ(issue.opd.size(), (size_t)1); + CHECK_EQ(issue.opd[0].handle, w.sgate); + CHECK_EQ(issue.opd[0].offset, 4); + } + } + for (int e = 0; e < 288; ++e) { + const auto& gu = b.weights[moe.w_gu[e] - 1]; + const auto& gs = b.weights[moe.w_gus[e] - 1]; + const auto& dn = b.weights[moe.w_dn[e] - 1]; + const auto& ds = b.weights[moe.w_dns[e] - 1]; + CHECK_EQ(gu.d.dtype, RAD_FP4E2M1); + CHECK_EQ(dn.d.dtype, RAD_FP4E2M1); + CHECK_EQ(gs.d.dtype, RAD_E8M0); + CHECK_EQ(ds.d.dtype, RAD_E8M0); + CHECK_EQ(gs.d.shape[0], 2 * F); + CHECK_EQ(gs.d.shape[1], 128); + CHECK_EQ(ds.d.shape[0], 4096); + CHECK_EQ(ds.d.shape[1], F / 32); + CHECK_EQ(gu.span_lo, rank * F); + CHECK_EQ(gs.span_lo, rank * F); + CHECK_EQ(dn.span_lo, rank * F); + CHECK_EQ(ds.span_lo, rank * (F / 32)); + CHECK_EQ(gu.d.access, RAD_ACCESS_CONDITIONAL); + CHECK_EQ(dn.d.access, RAD_ACCESS_CONDITIONAL); + } + for (rad_op h : { moe.op_gu, moe.op_dn }) { + const RecOp* op = b.op_of(h); + REQUIRE(op != nullptr); + CHECK_EQ(op->op, std::string("moe_gemm_q")); + bool found = false; + for (const auto& p : op->p) + if (p.key == "dtype") { + CHECK_EQ(p.sval, std::string("mxfp4a8")); + found = true; + } + CHECK(found); + } + } +} + /* A quantised container may keep one linear as the checkpoint holds it. Flash-Next's recipe leaves * the QSA indexer's projection plain bf16 (its top-k is a hard choice between blocks), so in a * four-bit model with fp8 linears it is declared bf16 and read by `gemm_nt` over its input's bf16 @@ -8092,6 +9475,61 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { } } +/* With the decode fusions switched off, GLM declares and steps the graph and launches it had + * before them, at one and eight ranks: a 4096-row prefill after history, a mixed step, a decode + * step, a verify and its draft passes. */ +TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) { + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + struct Case { + int world; + uint64_t graph, steps; + }; + const Case cases[] = { { 1, 0xd48139cb64abf0b1ull, 0x6982726c635df529ull }, + { 8, 0x90fc5bc69f1cfb10ull, 0x197c95726131b817ull } }; + for (const char* e : + { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" }) + setenv(e, "0", 1); + unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + for (const Case& cs : cases) { + RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + RadBuildCtx ctx = spec_ctx(0, cs.world, 3); + ctx.max_tok = 4096; + ctx.max_seqs = 8; + ctx.max_ctx = 200000; + REQUIRE_EQ(glm5next::declare(&b, &meta, &ctx), RAD_OK); + const uint64_t g = graph_hash(b); + const uint64_t s = pinned_steps(b, glm5next::step, 0, cs.world); + fprintf(stderr, " pin: glm5next world %d: graph 0x%016llxull, steps 0x%016llxull\n", + cs.world, (unsigned long long)g, (unsigned long long)s); + CHECK_EQ(g, cs.graph); + CHECK_EQ(s, cs.steps); + } + for (const char* e : + { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" }) + unsetenv(e); +} + /* Under a span a Flash-Next prefill of two intervals runs a pass at a time. At every world its * connection reads take a pass each and the indexer scores its pass-tall plane in windows, the MTP * head's pass included. At four ranks the step is pipelined (step_pipelined): every layer's diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index e471b4c5..10bc8aa2 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -89,8 +89,8 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { } const std::set> want = { { "breeze", "" }, { "embeddinggemma2", "" }, { "gemma3", "" }, { "gemma4", "" }, - { "gemma4", "compressed-tensors" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, - { "qwen35", "" }, + { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" }, + { "llama", "fp8_e4m3" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" }, { "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; From 778cbf315e45411cf95e48e846e770622cd33a12 Mon Sep 17 00:00:00 2001 From: Nunze Date: Mon, 19 Oct 2026 17:29:05 +0200 Subject: [PATCH 063/152] docs, compose: GLM-5.3-Flash The glm5next section of ARCHITECTURES.md (geometry, traps, KV groups, linears, tensor parallelism, the MoE decode fusions, measurements), the conversion and the four RADIANCE_GLM_* variables in GUIDE.md, the README's models table. deploy/compose/glm53-flash.yaml serves the container on eight R9700s with the expert plane resident and the native MTP layer drafting, with the flags of the measured run. Co-Authored-By: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com> --- README.md | 10 +++ deploy/compose/glm53-flash.yaml | 22 +++++ docs/ARCHITECTURES.md | 153 ++++++++++++++++++++++++++++++++ docs/GUIDE.md | 8 ++ 4 files changed, 193 insertions(+) create mode 100644 deploy/compose/glm53-flash.yaml diff --git a/README.md b/README.md index 7c7a649b..390a22c4 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` | | Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | | TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` | +| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, eight cards | `glm53-flash-mxfp4.rad` (171 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` | | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | | EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` | @@ -66,6 +67,15 @@ naming the two languages and refuses the plain turn the server renders at startu `translategemma-27b.yaml` serves a plain Gemma 3 template (`deploy/compose/gemma3.jinja`) and a client sends on `/v1/completions` the prompt the checkpoint's template renders. +GLM-5.3-Flash is converted from AMD's Quark export (`amd/GLM-5.3-Flash-Quark-MXFP4`) with +`data/recipes/glm53-mxfp4.recipe`, which keeps every weight as stored except the latent +attention's small kv_b, decoded to bf16. At 171 GiB it takes eight R9700s (`--tp 8`), every expert +resident, and its own MTP layer drafts. On eight R9700s it prefills 3958 tok/s at 6k tokens, +decodes 166 tok/s on one stream and 426 over eight, and 506 under eight streams of agent turns. +It serves text only, with a bf16 KV cache. Its template knows the reasoning efforts `low` and +`high` and renders any other as its maximum, so `glm53-flash.yaml` maps `medium` and `xhigh` +to `high`. + The ParoQuant containers keep the trunk exactly as the ParoQuant releases ship it, with the learned Givens rotations it was trained in. Convert int4 from `z-lab/Qwen3.8-27B-PARO`, int5 from `Launch80/Qwen3.8-27B-PARO-int5` and MXFP4 from `MisterSnrub/Qwen3.8-27B-PARO-MXFP4-v2`, each with diff --git a/deploy/compose/glm53-flash.yaml b/deploy/compose/glm53-flash.yaml new file mode 100644 index 00000000..da2f8374 --- /dev/null +++ b/deploy/compose/glm53-flash.yaml @@ -0,0 +1,22 @@ +# GLM-5.3-Flash from AMD's Quark export (data/recipes/glm53-mxfp4.recipe): MXFP4 experts, +# block-FP8 attention, the native MTP layer as the drafter. It takes eight 32 GB cards with the +# whole expert plane in VRAM; text only. The KV cache is bf16, the only one the plugin declares. +# +# A hybrid reuses a cached prefix only from a recurrent-state checkpoint at or below it, so the +# interval is 1024, which keeps a 1.5k-token system prompt's first 1024 tokens; --prefill-span 4 +# lets a lone prefill take four intervals a step. The template knows the reasoning efforts low +# and high and renders any other word as its maximum, hence the map. +name: radiance-glm53-flash +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-glm53-flash + command: > + --model /models/glm53-flash-mxfp4.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 8 --placement all_vram --gpu-headroom-mib 1024 --embedding-placement vram + --max-num-seqs 8 --max-model-len 32768 + --max-num-batched-tokens 4096 --prefill-span 4 + --checkpoint-interval 1024 --checkpoint-slots 64 --prefix-cache-mib 4096 + --num-speculative-tokens 5 --draft-window adaptive + --reasoning-effort low --reasoning-effort-map medium=high,xhigh=high diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 8a946764..bda1b0ce 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -14,6 +14,7 @@ plugin claims. | `arch/qwen35_w8a8` | `qwen35` | `w8a8_fwht128` | `qwen35_fp8` with an int8 trunk: i8 weights with a bf16 scale per 128 of K, rotated by a 128-wide Hadamard, against int8 activations under the same rotation (`data/recipes/q38-27b-w8a8-df2.recipe`) | | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert | +| `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Text only, bf16 KV | | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | | `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release, served w4a8. Optional draft head: Google's assistant (`rad-convert --draft-model`), with no cache of its own (`rad_drafter_shared_kv`) | @@ -375,6 +376,158 @@ The vision tower is declared when the container carries one and `--mm-max-patche --- +# `glm5next`: GLM-5.3-Flash + +`arch/glm5next` serves the language model of GLM-5.3-Flash (`model_type: glm5_next`) from AMD's +Quark export, `amd/GLM-5.3-Flash-Quark-MXFP4`. Quark is an import path, not an execution format: +the plugin claims the empty descriptor and reads each weight's encoding from the container +(`data/recipes/glm53-mxfp4.recipe` changes one weight a layer, below). The vision tower is not +mapped, so never converted, and an image request fails its step. The reference is SGLang's +`glm5_next.py` and `glm5_next_nextn.py` at AMD's pinned commit 654df43. + +``` +45 layers, hidden 4096, vocab 154880 (embedding and lm_head separate, bf16) +mHC: 4 residual streams, a 16384-wide row; 20 Sinkhorn passes, hc_eps 1e-6; the embedding is + copied into every stream, and the mean of the streams feeds the final norm +layers 3, 7, ..., 43 (l % 4 == 3): sparse MLA, no RoPE + q_a 4096 -> 1536, RMS-normed; kv_a 4096 -> 512, RMS-normed: the cached latent + 64 heads, q/k and v head_dim 256: q_b 1536 -> 16384, kv_b 512 -> 64 x (256 + 256), + o 16384 -> 4096, scores scaled by 1/sqrt(256), absorbed (attention over the latent) + DSA indexer: 32 heads of 128 from the normed q latent (wq_b 1536 -> 4096); a key of 128 + (LayerNorm, eps 1e-6, affine) and 128 pool-gate logits from the layer input; 4 keys + pooled to 1, Hadamard-rotated, E4M3; head gates f32 (32 x 4096), signed; + index_topk 2048 = 512 blocks of 4 tokens +the other 34 layers: KDA, 64 heads of 128 + q, k, v 4096 -> 3 x 8192, causal depthwise conv of width 4 + SiLU, q and k L2-normed, + scores scaled by 1/sqrt(128) + forget gate per channel through rank 128 (4096 -> 128 -> 8192), lower bound -5; + beta per head (4096 -> 64); output gate through rank 128, sigmoid-gated RMS norm per head +feed-forward: layers 0-2 dense SwiGLU 2 x 12288; layers 3-44 MoE + 288 routed experts of 2048 at top-8, sigmoid scores, correction bias (noaux_tc, one group), + weights normalized and scaled by 2.5; one shared expert of 2048 without a gate + every SwiGLU clamped at 10 +MTP: checkpoint layer 45 -- enorm, hnorm, eh_proj 8192 -> 4096, one MLA + indexer layer with + MoE, shared_head.norm; no mHC; the trunk's embedding and lm_head +max_position_embeddings 1048576 +``` + +Traps: + +- **`comb` is indexed `[source, destination]`.** Each connection's write is + `out[dst] = post[dst] * y + sum_src comb[src, dst] * h[src]`; the transpose has every shape + valid and is another model. `out` must be a separate buffer: each output stream reads every + input stream (`rad_block_mhc.h`). +- **The router and the index head gates stay f32.** Both projections are f32 weights against a + bf16 activation with f32 results (`gemm_nt_f32`), and the routing weights reach the gather + as f32. Rounding any of them to bf16 changes which experts and which blocks are picked, and a + weight rounded before the gather's sum can cancel to 0 where f32 keeps 0.125 (the libref + fixture). The correction bias ranks the experts only; the mixture weights are the selected + unbiased sigmoids. +- **The index scores are signed.** The ReLU comes before the head weighting, and a gate can be + negative, so a block's score can be. `qsa_select` runs with `signed` 1; QSA's ranking clamps + at zero and picks another set whenever a live score is negative (docs/OPS.md). +- **The SwiGLU is clamped, asymmetrically.** The gate is clipped above at 10 before the SiLU and + not below; the up projection on both sides. The unclamped FP8 epilogue of the dense + feed-forward does not apply, and `MlpFP8` turns it off when a limit is given. +- **Quark's excluded layers are block FP8, not bf16.** The export is MXFP4 globally and names + the attention and MTP layers in `layer_quant_config` as E4M3 with an f32 `weight_scale` per + 128 x 128, multiplicative. Read as bf16-scaled `fp8a8`, a scale bf16 cannot hold would round; + they are served `fp8a8f32`. The importer accepts an override only if it is MXFP4 or this + block FP8 and refuses any other, a null or empty one included, by name. +- **`head_dim` is 0 in the config.** The KDA and MLA widths come from their own keys; the + plugin fixes 128 and 256 and refuses a checkpoint whose hidden size, layer, vocabulary, + stream, expert, `index_topk` or MTP layer counts are not these. +- **MTP concatenates the normalized embedding first,** the normalized previous hidden second. +- **No RoPE anywhere** (`qk_rope_head_dim` 0); the indexer's only rotation is the Hadamard. + +**KV groups.** Five, all bf16 or wider; a `--kv-cache-dtype` other than bf16 is refused at +declare. + +| group | kind | per layer | layers | +|---|---|---|---| +| `kv_latent` | `RAD_KV_FULL`, bf16, 1 head of 256, block 4 | the 512-wide normed latent, its two halves in the K and V slots | 11 MLA + MTP | +| `kv_dsa_index` | `RAD_KV_FULL`, u8, block 4 | one page a pooled key: 128 E4M3 codes and their f32 scale (`dsa_pool`'s cache form) | 11 MLA + MTP | +| `kv_index_tail` | `RAD_KV_LINEAR`, bf16, `[4 + spec, 256]` | the key and gate rows not yet pooled; the ring is wider by the draft depth so a rejected draft rolls back | 11 MLA + MTP | +| `kv_kda` | `RAD_KV_LINEAR`, f32, 128 x 128 a head | the recurrent state, 64 / tp heads a rank | 34 KDA | +| `kv_kda_conv` | `RAD_KV_CONV`, bf16, width 4 | the convolution history, 3 x 8192 / tp channels a rank | 34 KDA | + +The latent and the index are replicated: every rank keeps the whole latent cache. The model is a +hybrid, so a prefix-cache hit is usable only from a state checkpoint at or below it, and +`--checkpoint-interval` decides how much of a shared system prompt is reused. + +**Linears.** Each weight is served as the export stores it: + +| weights | stored | served | +|---|---|---| +| routed and shared experts, layers 3-44 | MXFP4: E2M1, an E8M0 scale per 32 | `moe_gemm_q` mxfp4a8, an E4M3 activation scaled per (row, 128) | +| MLA q_a, kv_a, q_b, o (trunk and MTP); dense feed-forward, layers 0-2 | E4M3, an f32 scale per 128 x 128 | `gemm_nt_q` fp8a8f32 | +| MTP layer's experts | E4M3, an f32 scale per 128 x 128 | `moe_gemm_q` fp8a8f32 | +| MLA kv_b | quantised | decoded to bf16 by the recipe; `mla_project` absorbs and expands with it | +| KDA's seven projections; indexer wq_b, wk with the pool gate | bf16 | `gemm_nt` | +| router, index head gates, mHC projections | f32 | `gemm_nt_f32`, `mhc_pre` | +| embedding, lm_head, MTP eh_proj | bf16 | `embed_lookup`, `logits_gemm`, `gemm_nt` | + +The container holds 25845 weights, 171.32 GiB; at eight ranks each card holds 22.06 GiB of them, +19.67 GiB the routed experts. + +**MTP.** The plugin declares checkpoint layer 45 as a serial drafter (`RAD_DRAFT_SERIAL`), depth +3 unless `--num-speculative-tokens` says otherwise (at most 31). Its history pass writes the draft +layer's latent, index and tail for every row and runs its MoE on the proposal rows only. + +**Tensor parallelism.** At 1, 2, 4 or 8 ranks; declare refuses any other. `arch_test` declares and +steps the whole plugin at 1, 4 and 8, and the connection, router and indexer splits at 1, 2, 4 +and 8. + +- The routed and the shared experts split their 2048 width into equal contiguous slices, 256 a + rank at eight; each rank computes its slice of every expert, and the block's all-reduce sums + them. The dense feed-forward splits its 12288 the same way. +- MLA splits by whole heads: the rows of q_b and kv_b (8 heads a rank at eight) and the columns + of o. q_a, kv_a and the latent are replicated. +- KDA splits its 64 heads, with them the q/k/v rows, the convolution taps and the state; the two + rank-128 projections into the gates are replicated. +- The indexer is replicated whole. +- The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact. +- The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each + connection's mHC projection of 24 x 16384) are replicated. From a pass of + `RADIANCE_GLM_TP_SPLIT_ROWS` rows (default 256; 0 never), each rank computes a disjoint part + with the replicated kernel and an `all_gather` joins the parts, so every value is + bit-identical: the router and the head gates split their output columns, the mHC projection + its 16384-wide input into eight 2048-column chunks, whose partials `mhc_pre_finish` completes + on every rank. Below the threshold, as in decode, the collective costs more than it saves. + +**MoE decode fusions.** Three, each byte-identical to the launches it replaces, on unless its +variable is `0`; any value but `0` or `1` refuses the start. + +| variable | one launch for | where it applies | +|---|---|---| +| `RADIANCE_GLM_ROUTER_FUSE` | `router_sigmoid_topk`, `moe_scatter` and the shared gate's `fill`: `router_sigmoid_topk_scatter` | passes of up to 128 rows (`M * top_k` <= 1024, one workgroup's sort); 84 launches fewer a trunk decode step, 2 a draft pass | +| `RADIANCE_GLM_SWIGLU_QUANT` | `swiglu_clamped` and `quant_act_fp8`: `swiglu_clamped_quant_fp8` | the routed and shared arms and the three dense layers; 87 fewer a trunk step, 2 a draft pass | +| `RADIANCE_GLM_GATHER_INVERSE` | none: the sort writes each slot's row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) instead of searching `sorted` | every MoE pass | + +With all three at `0` the graph and the launches are those +`glm53_without_fusion_switches_is_the_pinned_graph_and_steps` pins. Paired on the eight R9700s +below, greedy text at a fixed draft depth of 3 is identical with and without them, and eight +agent streams decode 456 tok/s against 452, one 144 against 140. + +**Measured** on eight R9700s (gfx1201, 32 GB; four on PCIe Gen5 x16, four on Gen5 x8) at TP8 with +the flags of `deploy/compose/glm53-flash.yaml` (32768 tokens of context, eight sequences, MTP with +an adaptive window up to 5, reasoning effort low). BetterBench quick, temperature 0.7, cold +prefix cache, and a load generator of agent turns (3.3k-token prompts, 400 tokens out): + +| measurement | result | +|---|---| +| prefill, 1511 / 5936 / 11829 / 22138 prompt tokens | 3474 / 3958 / 3951 / 3817 tok/s | +| prefill, one 19861-token prompt | 5.0 s to the first token, 3982 tok/s | +| decode, one stream, weighted over the categories | 166 tok/s, an update every 22.7 ms at p99 | +| decode, 1 / 2 / 4 / 8 streams, aggregate | 145 / 221 / 316 / 426 tok/s | +| agent load, 1 / 4 / 8 streams, aggregate | 146 / 347 / 506 tok/s, MTP acceptance 0.60 / 0.59 / 0.65 | + +A second agent run at eight streams after the same restart gave 482. The links count: with three +of the x8 links fallen back to Gen4, the same build prefilled 3368 / 3664 / 3610 / 3512 tok/s at +the four depths above. + +--- + # Sample size Top-1 agreement between two numeric formats is one Bernoulli trial per prompt, so at p ≈ 0.93 its diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 2e7c5c3d..d3b45689 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -479,6 +479,12 @@ rad-convert /srv/models/google/translategemma-27b-it \ CALIB=/srv/calib/translategemma rad-convert /srv/models/google/translategemma-27b-it \ --recipe data/recipes/translategemma-27b-mxfp4-gptq.recipe -o translategemma-27b-mxfp4-gptq.rad +# GLM-5.3-Flash from AMD's Quark export: MXFP4 experts and block-FP8 attention kept as stored, +# the latent attention's kv_b decoded to bf16; text only, the vision tower is not converted. +# 171 GiB, served on eight 32 GB cards (docs/ARCHITECTURES.md) +rad-convert /srv/models/amd/GLM-5.3-Flash-Quark-MXFP4 \ + --recipe data/recipes/glm53-mxfp4.recipe -o glm53-flash-mxfp4.rad + # unsloth's NVFP4 Qwen3.8-27B with the DFlash2 drafter: the NVFP4 MLPs and the FP8 linears beside # them made MXFP4 by one recipe, the head block fp8 rad-convert /srv/models/unsloth/Qwen3.8-27B-NVFP4 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \ @@ -2748,6 +2754,8 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` | | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | | `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | +| `RADIANCE_GLM_TP_SPLIT_ROWS` | `arch/glm5next` under tensor parallelism: the pass height from which the router, the index head gates and the mHC projection split their f32 work over the ranks and gather it, bit-identical to the replicated form (default 256; `0` or a value that does not parse never splits) | +| `RADIANCE_GLM_ROUTER_FUSE`, `RADIANCE_GLM_SWIGLU_QUANT`, `RADIANCE_GLM_GATHER_INVERSE` | `arch/glm5next`'s MoE decode fusions, each byte-identical to the launches it replaces: unset, empty or `1` on, `0` off, any other value refuses the start. For comparing, not for deployment (docs/ARCHITECTURES.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) | From 685ec5bd858a31e90ba0431e844e3353c8c266fc Mon Sep 17 00:00:00 2001 From: Deadcode Date: Mon, 19 Oct 2026 21:58:07 +0200 Subject: [PATCH 064/152] radiance 1.9.0 New models: - LTX-2.5 (base and distilled): video with a stereo soundtrack from text or from text and a first frame, on one card, with its duration head, tiled VAE decoding, the diffusion decoder and the x2 latent upsampler - Krea 2 Raw and Turbo, and FLUX.3 [klein] and its base: text to image, and for FLUX.3 edits from up to ten reference pictures, on one card - GLM-5.3-Flash from AMD's Quark MXFP4 export, on eight cards (John McDonough, Nunze) - Gemma 3 / TranslateGemma 27B with an optional DFlash2 drafter (mici81) Engine: - --kv-cache-dtype fp8_v4 and k6_v4 for Gemma 3 and Qwen3.8-Flash-Next (mici81) - the rotated int8 trunk (i8a8h) for Qwen3.8-27B (eddie168168) - eight-rank all-reduce bands, weighted shards and pieces (Nunze); --host-headroom-mib (sfjes) - the dashboard shows the single-stream decode floor and its most recent window (Memoria) Fixes: prefix-cache reservations kept until their save lands (baKon), tool calls in Responses namespaces (#119), system messages merged when a template refuses several (#137), a prefill continued with no open step (#127), calibration of a Gram accumulation (#122), JSON Schema patterns read unanchored (davetha), GLM-style tool calls, the KV floor counting every sequence's state. Plugin ABI 24. --- CMakeLists.txt | 2 +- Dockerfile | 11 +- NOTICE | 26 +- README.md | 6 + abi/rad_abi.h | 2 +- abi/rad_builder.h | 120 +- abi/rad_runtime.h | 64 +- arch/common/rad_arch.h | 11 + arch/common/rad_block_mhc.h | 4 +- arch/common/rad_tp_split.h | 17 +- arch/common/rad_vae2d.h | 430 +++ arch/flux3/CMakeLists.txt | 10 + arch/flux3/flux3.cpp | 1247 +++++++ arch/flux3distilled/CMakeLists.txt | 11 + arch/flux3distilled/flux3distilled.cpp | 13 + arch/gemma3/gemma3.cpp | 9 +- arch/glm5next/glm5next.cpp | 25 +- arch/krea2/CMakeLists.txt | 10 + arch/krea2/krea2.cpp | 1389 ++++++++ arch/ltx2/CMakeLists.txt | 10 + arch/ltx2/ltx2.cpp | 4193 +++++++++++++++++++++++ arch/qwen4exp_fp8/qwen4exp_fp8.cpp | 40 +- arch/qwenimage21/qwenimage21.cpp | 286 +- core/build/rad_builder.cpp | 155 +- core/config.cpp | 2 +- core/engine.cpp | 30 +- core/engine_probe.cpp | 4 + core/format/checkpoint.cpp | 72 +- core/gen/driver.cpp | 281 +- core/gen/driver.h | 11 +- core/gen/gen.cpp | 61 + core/gen/gen.h | 16 + core/gen/video.h | 32 +- core/gen/video_driver.cpp | 395 ++- core/gen/video_driver.h | 19 +- core/mem/prefix.cpp | 7 +- core/mm/imaging.cpp | 25 +- core/mm/imaging.h | 2 + core/mm/media.cpp | 109 + core/mm/media.h | 8 + core/rad_core.h | 13 +- core/runtime/ctx.cpp | 11 +- core/runtime/ctx.h | 2 + core/sched/metrics.h | 106 +- core/sched/scheduler.cpp | 14 +- core/sched/scheduler.h | 4 +- core/server/dashboard.cpp | 87 +- core/server/iface.h | 33 +- core/server/images.cpp | 123 +- core/server/oai.cpp | 97 +- core/server/oai.h | 10 +- core/server/server.cpp | 39 +- core/server/server.h | 8 +- core/server/videos.cpp | 239 +- core/text/chat.cpp | 78 +- core/util/rad_util.cpp | 17 +- data/recipes/flux-3-klein-fp8.recipe | 24 + data/recipes/krea-2-bf16.recipe | 23 + data/recipes/krea-2-fp8.recipe | 41 + data/recipes/ltx-2.5-bf16.recipe | 14 + data/recipes/ltx-2.5-fp8.recipe | 37 + deploy/compose/flux-3-klein.yaml | 15 + deploy/compose/krea-2-raw.yaml | 14 + deploy/compose/krea-2-turbo.yaml | 14 + deploy/compose/ltx-2.5.yaml | 15 + docs/ARCHITECTURES.md | 218 +- docs/DOCKER.md | 11 +- docs/GUIDE.md | 139 +- docs/OPS.md | 242 +- libavx/CMakeLists.txt | 1 + libavx/avx_attn.cpp | 178 + libavx/avx_audio.cpp | 31 + libavx/avx_cases.cpp | 65 +- libavx/avx_gen.cpp | 139 +- libavx/avx_isa.h | 9 +- libavx/avx_ltx.cpp | 604 ++++ libavx/avx_registry.cpp | 146 +- libavx/avx_video.cpp | 22 +- libquant/lq_gptq.cpp | 13 +- libr4d/CMakeLists.txt | 1 + libr4d/r4d.h | 1 + libr4d/r4d_ar_entry.hip | 7 +- libr4d/r4d_attn_dense_bf16.hip | 68 +- libr4d/r4d_attn_gen.hip | 100 +- libr4d/r4d_attn_paged_gqa8.hip | 65 +- libr4d/r4d_attn_paged_h256_gqa12.hip | 2 + libr4d/r4d_attn_paged_h256_gqa6_bs4.hip | 2 + libr4d/r4d_audio.hip | 44 + libr4d/r4d_fp8_f32scale.hip | 304 +- libr4d/r4d_gen.hip | 190 +- libr4d/r4d_glm.hip | 100 +- libr4d/r4d_kda.hip | 189 +- libr4d/r4d_ltx.hip | 1091 ++++++ libr4d/r4d_mhc.hip | 158 +- libr4d/r4d_mla.hip | 54 +- libr4d/r4d_model_bf16.hip | 39 +- libr4d/r4d_moe_mxfp4.hip | 429 +-- libr4d/r4d_plugin.h | 38 + libr4d/r4d_rows.cpp | 611 +++- libr4d/r4d_selftest.cpp | 2615 +++++++++----- libr4d/r4d_shapes.cpp | 8 +- libr4d/r4d_upscaler.hip | 161 +- libr4d/r4d_video.hip | 55 +- libref/ref_attn.cpp | 150 + libref/ref_audio.cpp | 34 + libref/ref_gen.cpp | 152 +- libref/ref_ltx.cpp | 722 ++++ libref/ref_ops.h | 43 + libref/ref_registry.cpp | 176 +- libref/ref_shapes.cpp | 264 +- libref/ref_video.cpp | 28 +- tests/CMakeLists.txt | 9 +- tests/abi_layout_rows.h | 51 + tests/abi_layout_table.h | 61 +- tests/abi_layout_test.cpp | 6 +- tests/arch_test.cpp | 449 +-- tests/chat_test.cpp | 30 + tests/gen_test.cpp | 95 + tests/images_test.cpp | 27 + tests/place_test.cpp | 85 +- tests/plugin_test.cpp | 4 +- tests/r4d_emu/test_f32.cpp | 122 +- tests/r4d_emu/test_fp8f32.cpp | 68 +- tests/r4d_emu/test_kda.cpp | 100 +- tests/r4d_emu/test_mhc.cpp | 283 +- tests/r4d_emu/test_mla.cpp | 31 +- tests/r4d_emu/test_moemx.cpp | 358 +- tests/ref_test.cpp | 228 +- tests/runtime_test.cpp | 25 +- tests/sched_test.cpp | 53 +- tests/server_fakes.h | 4 + tests/server_test.cpp | 58 + tests/shipped_plugins_test.cpp | 7 +- tests/video_gen_test.cpp | 398 ++- tests/videos_test.cpp | 218 ++ vendor/UPSTREAM | 6 +- 136 files changed, 18917 insertions(+), 3821 deletions(-) create mode 100644 arch/common/rad_vae2d.h create mode 100644 arch/flux3/CMakeLists.txt create mode 100644 arch/flux3/flux3.cpp create mode 100644 arch/flux3distilled/CMakeLists.txt create mode 100644 arch/flux3distilled/flux3distilled.cpp create mode 100644 arch/krea2/CMakeLists.txt create mode 100644 arch/krea2/krea2.cpp create mode 100644 arch/ltx2/CMakeLists.txt create mode 100644 arch/ltx2/ltx2.cpp create mode 100644 data/recipes/flux-3-klein-fp8.recipe create mode 100644 data/recipes/krea-2-bf16.recipe create mode 100644 data/recipes/krea-2-fp8.recipe create mode 100644 data/recipes/ltx-2.5-bf16.recipe create mode 100644 data/recipes/ltx-2.5-fp8.recipe create mode 100644 deploy/compose/flux-3-klein.yaml create mode 100644 deploy/compose/krea-2-raw.yaml create mode 100644 deploy/compose/krea-2-turbo.yaml create mode 100644 deploy/compose/ltx-2.5.yaml create mode 100644 libavx/avx_ltx.cpp create mode 100644 libr4d/r4d_ltx.hip create mode 100644 libref/ref_ltx.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 80dda3fc..a6fbedcf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is the server release that /version reports. The plugin ABI version is separate and is # read from abi/rad_abi.h below. -project(radiance VERSION 1.8.1 LANGUAGES C CXX) +project(radiance VERSION 1.9.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/Dockerfile b/Dockerfile index 14cd05d7..d0c0c375 100644 --- a/Dockerfile +++ b/Dockerfile @@ -219,11 +219,12 @@ ARG TEST_EXCLUDE= # ctest --test-dir /build -L gpu --output-on-failure # Tests run TEST_JOBS at a time, else JOBS (default one per two hardware threads, about one per # core on an SMT machine: the per-binary CPU budgets in tests/CMakeLists.txt hold for tests that do -# not share a core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The build -# sandbox forbids io_uring, so avx_check skips its file-backed gather case, and perf_event_open, so -# the tests that bound work count CPU time rather than instructions (tests/work_counter.h). The -# `oot` suite (every shipped plugin rebuilt against the installed package) repeats this stage's -# whole compile, so it runs from the development tree instead (tests/oot_plugins.sh). +# not share a core); the `perf` entries, which assert wall-clock costs, run alone (RUN_SERIAL). The +# build sandbox forbids io_uring, so avx_check skips its file-backed gather case, and +# perf_event_open, so the tests that bound work count CPU time rather than instructions +# (tests/work_counter.h). The `oot` suite (every shipped plugin rebuilt against the installed +# package) repeats this stage's whole compile, so it runs from the development tree instead +# (tests/oot_plugins.sh). RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ bash /src/docker/llvm-check.sh /build \ && RAD_TEST_CPU_BUDGET_SCALE="${TEST_CPU_BUDGET_SCALE}" \ diff --git a/NOTICE b/NOTICE index 0d450ed3..b4769e03 100644 --- a/NOTICE +++ b/NOTICE @@ -15,7 +15,8 @@ Written by Deadcode, with contributions from: adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused - w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume + w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, and the + Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files - mechkbfan: the token embedding in the pinned host pool - Code000: the n-gram gather on the card and the MTP head's history-pass skip - baKon: three-rank tensor parallelism, serving any world size from the shipped container, the @@ -23,7 +24,8 @@ Written by Deadcode, with contributions from: context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, curl, jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave, - and runtime LoRA adapters served beside the base model and picked per request + runtime LoRA adapters served beside the base model and picked per request, and the prefix cache's + reserved snapshots held until their save lands - hazyumps: static YaRN for the Qwen rotary paths - malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit @@ -37,9 +39,27 @@ Written by Deadcode, with contributions from: - gearwave00001: /v1/messages as Claude Code sends it - devmilan: the NVFP4 and FP8 compressed-tensors imports - sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix - reuse that leaves a windowed group alone + reuse that leaves a windowed group alone -- and --host-headroom-mib - zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime +- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the + sandwich junction's all-reduce and its DFlash2 drafter -- the fp8_v4 and k6_v4 KV caches, GPTQ's + factorisations through LAPACK and a column-split linear's Hessian from per-rank parts, + R4D_AR_MAX_BLOCKS for two engines on one set of cards, and added tokens decoded as HuggingFace + decodes them +- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the + out-of-tree test at the tree's VOPD setting +- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes +- Nunze: the eight-rank all-reduce's bands, weighted shards from the PCIe links and pieces, the + sampler's candidate width at eight ranks, the image test stage's parallelism, budgets and + exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose + name the opener opens +- John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and + sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their + reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the + one-sequence KV floor over the live plan, and prefill staging paid by expert residency +- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and + the bringup time in /stats This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. diff --git a/README.md b/README.md index 390a22c4..d1546995 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,12 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | +| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` | +| Krea 2 Raw FP8: the same, undistilled | `krea-2-raw-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-raw-radiance-fp8) | `krea-2-raw.yaml` | +| FLUX.3 [klein] FP8: text to image and edits from up to ten pictures, one card | `flux-3-klein-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-fp8) | `flux-3-klein.yaml` | +| FLUX.3 [klein] base FP8 | `flux-3-klein-base-fp8.rad` (9.3 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-flux-3-klein-base-fp8) | `flux-3-klein.yaml` | +| LTX-2.5 distilled FP8: video with its stereo soundtrack from text or a first frame, one card | `ltx-2.5-distilled-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-distilled-fp8) | `ltx-2.5.yaml` | +| LTX-2.5 base FP8 | `ltx-2.5-fp8.rad` (37 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-ltx-2.5-fp8) | `ltx-2.5.yaml` | | MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` | | FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` | | MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` | diff --git a/abi/rad_abi.h b/abi/rad_abi.h index ad302026..292e14b4 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -17,7 +17,7 @@ extern "C" { * kind of plugin reports it, and a plugin that does not report exactly this version is refused at * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 23u +#define RAD_ABI_VERSION 24u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 839904da..5b1713c5 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -72,7 +72,8 @@ const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* df * [21HD/16, 22HD/16) V's scales (absmax / 7) * * Codes are two's complement (int4 -7..7, int6 -31..31). The group is declared at RAD_F8E4M3 with - * head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read it. */ + * head_dim the row's bytes / 2 so the core sizes pages from it; only the layout's kernels read + * it. */ enum { RAD_KVQ_NONE = 0, RAD_KVQ_V4 = 1, @@ -428,7 +429,7 @@ int rad_op_declared(RadBuilder* b, const char* op); * convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component * that knows both sides, and rad-convert reads the map from it (spec §2.4). */ enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1, RAD_MAP_WNORM = 2, RAD_MAP_ROWS = 3, - RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5 }; + RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6 }; typedef struct RadNameMap { const char* declared; /* the name given to rad_decl_weight */ @@ -472,7 +473,13 @@ typedef struct RadNameMap { * divided by max(usage, 1e-5), in f32. Successive EMA maps for one name stack their codebooks * along dim 0, as CONCAT maps extend (a residual quantiser's codebooks as one table). * - * TRANSPOSE and EMA are computed at convert in f32, like WNORM, and stored as the recipe says. */ + * RAD_MAP_TAP keeps one index of one dimension of src[0], dropping that dimension: index + * src_index[0] (negative counts from the end) of dimension `concat_dim`. A causal 3-D convolution + * run on a single frame reads only its last temporal tap, so [cout, cin, kt, kh, kw] read at tap -1 + * of dimension 2 is the 2-D convolution it then is. + * + * TRANSPOSE, EMA and TAP are computed at convert in f32, like WNORM, and stored as the recipe + * says. */ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m); @@ -653,8 +660,21 @@ enum { RAD_GEN_PASS_COND = 1, RAD_GEN_PASS_DENOISE = 2, RAD_GEN_PASS_DECODE = 3 * in all three; a picture of h x w tokens holds the count in the first, and its row * and column, centred on zero (-(n - n/2) .. n/2 - 1), in the other two, after which * the count moves on by max(h, w). Text rows attend causally, a picture's rows to - * each other both ways, every row to every row before it. */ -enum { RAD_GEN_LAYOUT_JOINT_GRID = 1 }; + * each other both ways, every row to every row before it. + * + * JOINT_STEP the conditioning is not cached as keys and values but rides in every denoising + * step beside the image, since the model updates it as it goes. The conditioning + * is the prompt's rows after `drop_prefix`, then `pad_token` rows up to a multiple + * of `pad_multiple`, then each reference picture's latent tokens in raster order + * (the pictures are not in the prompt; `tmpl_image` is unused). No KV group is + * declared: the COND pass leaves the conditioning's rows in the plugin's own state, + * once for every lane the request's images run in, and each DENOISE entry is that + * conditioning followed by the image (RadGenBatch, "the joint layout"). Rotary + * positions are four f32 components (t, h, w, l): a text or padding row is (0, 0, + * 0, l), l its index with `rope_text_l` and 0 without; a picture's token at row h, + * column w (from 0) is (0, s h, s w, l) with s `rope_hw_scale`, l -(1 + k) for + * the k-th reference picture and 0 for the image being made. */ +enum { RAD_GEN_LAYOUT_JOINT_GRID = 1, RAD_GEN_LAYOUT_JOINT_STEP = 2 }; typedef struct RadGeneratorDecl { const char* name; /* "qwen-image" -- for messages */ @@ -716,6 +736,25 @@ typedef struct RadGeneratorDecl { * pixels of the image a decode pass made. */ int64_t max_lanes; rad_buf image_out; + + /* ---- the JOINT_STEP layout (zero for JOINT_GRID) */ + /* The most rows one conditioning lays out (text, padding and reference latents together): + * the plugin keeps `cond_rows` rows a lane a branch, and a longer prompt is refused. */ + int64_t cond_rows; + double rope_hw_scale; + int32_t rope_text_l; + int32_t pad_multiple; + int32_t pad_token; + /* Guidance as the model's card states its scale s: 1 when s means cond + s (cond - uncond), + * which the core runs as s + 1, 0 when it means uncond + s (cond - uncond). `default_cfg` is + * in the card's terms. */ + int32_t cfg_original; + /* The negative prompt guidance uses when a request names none ("" is a prompt); null when a + * guided request must name its own. */ + const char* default_negative; + /* 1: a reference picture is shrunk to `ref_area` only when larger and cut to `size_multiple` + * by a centred crop; 0: resized to `ref_area` at its own aspect. */ + int32_t ref_shrink_only; } RadGeneratorDecl; int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d); @@ -934,6 +973,77 @@ typedef struct RadVideoGenDecl { * and fewer than the default schedule's. */ double upscale_max; int32_t upscale_refine; + + /* ---- appended in ABI 24 (LTX-2.5) */ + /* The sampler's form. 0: the grid points above. 1: diffusers' FlowMatchEulerDiscrete as + * LTX-2 runs it -- a request's `steps` are its evaluations n, between 1 and max_steps; sigmas + * linspace(1, 1/n, n), computed in f64 and taken to f32, and with `dyn_shift` 1 shifted by mu + * as exp(mu) / (exp(mu) + 1/s - 1) in f32, mu linear in the video's latent tokens from + * `base_seq` (`base_shift`) to `max_seq` (`max_shift`); then, with `shift_terminal` > 0, + * stretched so the last is shift_terminal; and a closing 0. A trained schedule (n_rungs > 0) + * is the rungs taken to f32 and a closing 0, with default_steps and max_steps both n_rungs. + * Both modalities step the same sigmas; shift_video and shift_audio are unused. */ + int32_t sched_kind; + int32_t dyn_shift; + double base_shift, max_shift; + int64_t base_seq, max_seq; + double shift_terminal; + /* With latent upscaling under a trained schedule of form 1: the sigmas the evaluations after + * the upscale step through (a second stage's own schedule, its first the sigma the upscaled + * latents are re-noised to), instead of the schedule's tail. The small size then runs every + * rung, its last to the clean estimate, and a request's refinement is n_refine_rungs. */ + int32_t n_refine_rungs; + const double* refine_rungs; + /* The text rows of every VSTEP pass, whatever the prompt's length (0: the prompt's tokens): + * a model whose text encoder writes a fixed number of rows. */ + int64_t step_text_rows; + /* Guidance terms (RadVideoGenBatch::guidance_h) when `guidance` is 1: the defaults a request + * that names none gets, the video's scale, spatio-temporal scale, modality scale and rescale, + * then the soundtrack's four. A request whose video or soundtrack scale is not 1 is guided + * against a negative prompt: its own, else `default_negative` (null: ""). The VCOND pass then + * carries both prompts, the positive first (two cu_seqlens entries). */ + int32_t guidance; + double guidance_default[8]; + const char* default_negative; + /* Image to video: 1 when the model can start from a first frame (OpenAI's + * `input_reference`), handed to the VCOND pass resized to the size the first evaluations run + * at (RadVideoGenBatch `image`), after an H.264 round trip at `image_crf` when that is > 0 + * (the compression the model was trained against). */ + int32_t image_cond; + int32_t image_crf; + /* A left-padded text encoder: the VCOND pass's positions count so that each prompt ends at + * `text_left_pad` - 1, the place it holds in a sequence padded on the left to that length (0: + * from 0). */ + int64_t text_left_pad; + /* The soundtrack's latent rows a step carries for each latent (0: audio_channels, a stream of + * rows a channel); a model whose latent holds every channel at once carries 1. */ + int32_t audio_streams; + /* A latent upscaler of one fixed factor, upscale_max: a request's sides must then be + * multiples of size_multiple x upscale_max, so the small size is exactly the full size over + * the factor. */ + int32_t upscale_exact; + /* A length head: a model that predicts from the prompt how long its video should be. With + * `duration_out` set, every VCOND pass writes to it (f32 [1], device) the natural log of that + * length in seconds. For a request that names no length the core takes its exponent, clamps it + * to [duration_min, duration_max] seconds, rounds it to frames at the frame rate and floors + * that to the chunk grid (frames_per_chunk n + frames_tail; one chunk more when the floor falls + * under duration_min and duration_max allows it), then holds it to min_chunks..max_chunks and + * to what a pass carries. Until that VCOND pass is done such a request is shaped at + * `default_chunks`, so the pass may not depend on the length: its geometry carries the + * provisional frame count, and `t_video` / `t_audio` the provisional schedule. 0: a request + * that names no length is made at default_chunks. `duration_dtype` is the precision the model + * takes the exponent in: RAD_F32, or RAD_BF16 for a head run in bf16, whose length is + * exp(x) in f32 rounded to bf16. Frames round half to even, as Python's round(). */ + rad_buf duration_out; + double duration_min, duration_max; + uint32_t duration_dtype; + /* Decoders: a model with more than one way to turn its latents into frames names them, + * space-separated, its default first (LTX-2.5: "vae diffusion"). A request may name one; every + * VDECODE pass carries its index (RadVideoGenBatch::decoder). `decoder_max_area`, when set, + * holds each decoder's largest frame in pixels (0: max_area), and a request over it is refused. + * Null: one decoder. */ + const char* decoders; + const int64_t* decoder_max_area; } RadVideoGenDecl; int rad_declare_video_generator(RadBuilder* b, const RadVideoGenDecl* d); diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index c7694a95..912a25b4 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -315,6 +315,43 @@ typedef struct RadGenBatch { int32_t dec_lane; int32_t dec_height, dec_width; /* pixels */ int32_t dec_preview; /* the lane's preview latent, not its state */ + + /* ---- the joint layout (RAD_GEN_LAYOUT_JOINT_STEP) + * COND: `branch` is 0 for the prompt and 1 for the negative prompt, and `n_lane` / `lane_h` / + * `lane` name every lane the conditioning's images run in; the plugin keeps the + * conditioning's row r for lane l at its own row (2 l + branch) cond_rows + r. The prompt's + * last `n_pad` tokens are the padding, and `valid_cu` is {0, the tokens before it}. `rope_f` + * is the conditioning's positions, [4, rows] f32 component-major. + * DENOISE: each entry's rows are its conditioning and then its image's latent tokens, so + * `cu_seqlens` bounds both together. `src` [n_tok] names a row's source: >= 0 the plugin's + * conditioning row (as above), < 0 the image row -(1 + k) of the compact image order, in + * which `img_cu` [n_seq + 1] bounds each entry's image and `img_rows` [n_img] is each image + * row's place in the pass. `mode_cu` [3 n_seq + 1] cuts each entry into its text (padding + * included), its reference pictures and its image: entry e's text is rows [mode_cu[3e], + * mode_cu[3e + 1]), its pictures [mode_cu[3e + 1], mode_cu[3e + 2]), its image up to + * mode_cu[3e + 3]. `rope_f` is [4, n_tok]. Everything sigma, cfg, pair, lane, flags and seed + * say is per entry as for JOINT_GRID, and the lane ops read `img_cu`. */ + int32_t branch; + int32_t n_pad; + const int32_t* valid_cu; + int64_t n_img; + const int32_t* img_cu; + const int32_t* img_rows; + const int32_t* mode_cu; + const float* rope_f; + /* DENOISE: the rows again in mode-major order -- every entry's text, then every entry's + * pictures, then every entry's image (the compact image order) -- for a model whose early + * blocks run each mode on its own. `mode_rows` [n_tok] is each one's place in the pass, + * `mode_src` [n_tok] its source as `src` names it, and `mode_rope_f` holds the positions mode + * by mode, mode m's a dense [4, n_m] block at 4 times its start; + * `n_mode_h` [3] counts each mode's rows, so mode m starts at the sum of the counts before + * it, and `mode_ccu` [3, n_seq + 1] bounds each entry's rows of each mode from that start + * (mode m's cu_seqlens at mode_ccu + m (n_seq + 1), each beginning at 0). */ + const int32_t* mode_rows; + const int32_t* mode_src; + const int32_t* mode_ccu; + const int64_t* n_mode_h; + const float* mode_rope_f; } RadGenBatch; /* An entry's flags on a DENOISE pass. */ @@ -450,7 +487,8 @@ typedef struct RadVideoGenBatch { /* f32 [6]: the video's timestep, sigma and next sigma, then the soundtrack's. */ const float* sched; const float* pos; /* f32 [3, n_tok]: RAD_VPOS_STEP */ - /* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first. */ + /* u32 [2, 2]: the video's noise seed and the soundtrack's, low word first (VSTEP, VUPSCALE and + * VDECODE passes; a decoder that denoises draws from it). */ const uint32_t* seed; /* ---- VDECODE */ @@ -468,6 +506,24 @@ typedef struct RadVideoGenBatch { * soundtrack's) the latents are re-noised to; `seed` is a step's. */ RadVideoGeom geom_from; const float* upscale; /* f32 [1]: the factor the network is told */ + + /* ---- appended in ABI 24 */ + /* VCOND with a negative prompt: `n_neg` of the pass's tokens, after the prompt's. */ + int32_t n_neg; + /* The request's guidance, f32 [8] host: the video's scale, its spatio-temporal scale, its + * modality scale and its rescale, then the soundtrack's four; a model's own defaults where + * the request named none. */ + const float* guidance_h; + /* VCOND with a first frame (RadVideoGenDecl::image_cond): `image` [height, width, 3] bf16 in + * [-1, 1], device; null without one. Every later pass carries `has_image` 1 for such a + * request. */ + const uint16_t* image; + int32_t has_image; + /* guidance_h on the device, f32 [8], for ops that read the terms. */ + const float* guidance; + /* VDECODE: the decoder the request named (RadVideoGenDecl::decoders), its index; 0 the + * default. */ + int32_t decoder; } RadVideoGenBatch; /* RadVideoGenBatch::geom_d. The request's latent geometry, then a VDECODE pass's chunk: the latent @@ -483,7 +539,11 @@ enum { * first three are also the source volume; (frames, H, W) the target volume; then both in * patches, (frames, h / patch, w / patch) and (frames, H / patch, W / patch). */ RAD_VGEOM_UP_SRC = 16, RAD_VGEOM_UP_DST = 21, RAD_VGEOM_UP_PSRC = 24, RAD_VGEOM_UP_PDST = 27, - RAD_VGEOM_N = 32 + /* The soundtrack's latents as a volume of single latents, (n_audio, 1, 1); and the video's + * rows cut at its first latent frame, {0, that frame's patches, every patch} (a first frame + * a model conditions on at its own timestep). */ + RAD_VGEOM_AUDIO_VOL = 32, RAD_VGEOM_FIRST_CU = 35, + RAD_VGEOM_N = 40 }; /* ================================================================== operands */ diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index d593f816..c138838a 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -450,6 +450,17 @@ inline int map_transpose(RadBuilder* b, const char* declared, const char* src) { return rad_decl_name_map(b, &m); } +/* One index of one dimension of a checkpoint tensor (RAD_MAP_TAP): a causal 3-D convolution's + * last temporal tap is map_tap(b, name, src, 2, -1). */ +inline int map_tap(RadBuilder* b, const char* declared, const char* src, int dim, int index) { + RadNameMap m = map_base(declared, RAD_MAP_TAP); + m.n_src = 1; + m.src[0] = src; + m.src_index[0] = index; + m.concat_dim = dim; + return rad_decl_name_map(b, &m); +} + /* An EMA codebook: the embedding sums over max(cluster usage, 1e-5), row by row (RAD_MAP_EMA). */ inline int map_ema(RadBuilder* b, const char* declared, const char* sums, const char* usage) { RadNameMap m = map_base(declared, RAD_MAP_EMA); diff --git a/arch/common/rad_block_mhc.h b/arch/common/rad_block_mhc.h index 71bdaec5..67b21d15 100644 --- a/arch/common/rad_block_mhc.h +++ b/arch/common/rad_block_mhc.h @@ -72,8 +72,8 @@ struct ManifoldConn { } int declare_split(RadBuilder* b, Names& nm, const char* name) { const int64_t total = c.hc * g.n_embd / kChunk; - split_rows = glm_tp_split_rows(); - if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || !split_rows || total % g.world) { + split_rows = kGlmTpSplitRows; + if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) { split_rows = 0; return RAD_OK; } diff --git a/arch/common/rad_tp_split.h b/arch/common/rad_tp_split.h index 48217c60..68a92125 100644 --- a/arch/common/rad_tp_split.h +++ b/arch/common/rad_tp_split.h @@ -4,19 +4,12 @@ #ifndef RAD_TP_SPLIT_H #define RAD_TP_SPLIT_H #include "rad_arch.h" -#include namespace rad { namespace arch { -/* Rows from which a replicated F32 projection splits its columns over the ranks - * (RADIANCE_GLM_TP_SPLIT_ROWS, 0 never). Below it the collective's latency outweighs the - * saved arithmetic, so decode keeps the replicated form. */ -inline int64_t glm_tp_split_rows() { - const char* e = std::getenv("RADIANCE_GLM_TP_SPLIT_ROWS"); - if (!e || !*e) return 256; - const long long v = std::strtoll(e, nullptr, 10); - return v > 0 ? (int64_t)v : 0; -} +/* Rows from which a replicated F32 projection splits its columns over the ranks. Below it the + * collective's latency outweighs the saved arithmetic, so decode keeps the replicated form. */ +constexpr int64_t kGlmTpSplitRows = 256; /* The split's ops are declared whatever the step size, and each gather's message as a range of * rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph @@ -33,8 +26,8 @@ struct SplitF32Proj { int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n, int64_t width, rad_weight weight, rad_buf input, rad_buf output) { - min_rows = glm_tp_split_rows(); - if (g.world < 2 || !min_rows || n % g.world || (n / g.world * 4) % 16) { + min_rows = kGlmTpSplitRows; + if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) { min_rows = 0; return RAD_OK; } diff --git a/arch/common/rad_vae2d.h b/arch/common/rad_vae2d.h new file mode 100644 index 00000000..f228c5ad --- /dev/null +++ b/arch/common/rad_vae2d.h @@ -0,0 +1,430 @@ +/* rad_vae2d.h -- an image VAE (encoder or decoder) as a recorded list of ops over NHWC images. + * + * Image size varies per request, so a VAE's ops are declared once for the largest image and issued + * with each pass's extents (`Vae::issue`). Qwen-Image 2.1's residual Wan-2.2 VAE, Qwen-Image's + * and Krea 2's Wan-2.1 one and FLUX's GroupNorm one are each a few lines of `conv`, `norm`, + * `resblock` and `attention` calls in their plugin. + */ +#pragma once +#include + +#include +#include +#include +#include +#include + +namespace rad { +namespace arch { + +/* ================================================================== the VAE as a recorded graph + * + * Image size varies per request, so the VAE's ops are declared once for the largest image and + * issued with the actual extents: every image operand is a raw [height, width * channels] view of + * its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the + * stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare() + * and step() walk the same list. + * + * Every output is its own buffer, sized for its stage; the planner shares storage between those + * whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued + * in declaration order. */ +struct VImg { + rad_buf buf = 0; + int64_t ch = 0; + int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */ +}; + +struct VOp { + enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN, GNORM, LIN } kind = CONV; + rad_op op = 0; + VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */ + rad_weight w = 0, b = 0; + int k = 1, up = 1, stride = 1; + int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */ +}; + +/* What a checkpoint stores a VAE's convolutions as. */ +enum VaeConvForm { + VAE_CONV_2D, /* [cout, cin, k, k] */ + VAE_CONV_CAUSAL, /* a causal 3-D convolution [cout, cin, kt, k, k], run on one frame: its + * last temporal tap (RAD_MAP_TAP) */ +}; + +struct Vae { + std::vector ops; + Names* nm = nullptr; + RadBuilder* b = nullptr; + const char* scope = ""; /* "dec" or "enc" */ + bool down = false; /* an encoder: a level halves the side */ + int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */ + int n_buf = 0; + int first_group = 0; + /* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows + * (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts), + * so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its + * band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach + * the band. The ops before it include the mid-block's attention, which reads every pixel, and + * run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no + * tail. */ + int band_from = -1; + int64_t halo = 0; + std::vector whole; + VaeConvForm form = VAE_CONV_2D; + /* group_norm's statistics scratch, one for every GroupNorm op (they run one after another). */ + rad_buf gn_stats = 0; + + int64_t px_at(int lvl) const { + int64_t p = base_px; + for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4; + return p; + } + VImg img(int64_t ch, int lvl) { + VImg v; + v.ch = ch; + v.lvl = lvl; + v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch }); + return v; + } + rad_weight wt(const char* name, const char* src, std::initializer_list shape, + bool tap = false) { + if ((tap ? map_tap(b, name, src, 2, -1) : map_copy(b, name, src)) < 0) return 0; + return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, + grp_layer(first_group)); + } + + /* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */ + VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad, + const char* ckpt) { + VOp o; + o.kind = VOp::CONV; + o.x = x; + o.up = up; + o.stride = stride; + int lvl = x.lvl; + if (up == 2) lvl = down ? lvl - 1 : lvl + 1; + if (stride == 2) lvl = down ? lvl + 1 : lvl - 1; + o.y = img(cout, lvl); + o.k = k; + o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k }, + form == VAE_CONV_CAUSAL); + o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout }); + o.op = RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch), + RAD_INT("cout", cout), RAD_INT("k", k), + RAD_INT("stride", stride), RAD_STR("pad", pad), + RAD_INT("up", up), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(o.w, o.b)); + /* An input with no buffer is the picture the pass staged, read where it lies. */ + if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf }); + else rw(b, o.op, {}, { o.y.buf }); + ops.push_back(o); + return o.y; + } + /* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */ + VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) { + VOp o; + o.kind = VOp::NORM; + o.x = x; + o.y = img(x.ch, x.lvl); + const char* dn = nm->f("%s.gamma", ckpt); + if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{}; + o.w = gamma_rank == 4 + ? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group)) + : decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group)); + o.op = rw(b, RAD_OP(b, "l2norm_chan", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch), + RAD_STR("act", silu ? "silu" : "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(o.w)), + { x.buf }, { o.y.buf }); + ops.push_back(o); + return o.y; + } + VImg add(const VImg& x, const VImg& z) { + VOp o; + o.kind = VOp::ADD; + o.x = x; + o.z = z; + o.y = img(x.ch, x.lvl); + o.op = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x.buf, z.buf }, { o.y.buf }); + ops.push_back(o); + return o.y; + } + /* y += the resampling shortcut of x (in place on y). */ + void shortcut(const VImg& x, const VImg& y, int ft) { + VOp o; + o.kind = down ? VOp::S2D : VOp::D2S; + o.x = x; + o.y = y; + o.up = ft; + o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch), + RAD_INT("cout", y.ch), RAD_INT("ft", ft), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x.buf, y.buf }, { y.buf }); + ops.push_back(o); + } + /* A residual block, in -> out channels. */ + VImg resblock(const VImg& x, int64_t out, const char* ckpt) { + VImg h = x; + if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt)); + VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4); + t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt)); + t = norm(t, true, nm->f("%s.norm2", ckpt), 4); + t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt)); + return add(t, h); + } + /* The mid-block's single-head attention over every pixel. */ + VImg attention(const VImg& x, const char* ckpt) { + const int64_t C = x.ch; + VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3); + VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt)); + VOp o; + o.kind = VOp::ATTN; + o.x = qkv; + o.y = img(C, x.lvl); + o.qkv_ch = 3 * C; + o.op = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)C))), + RAD_NOWEIGHTS), + { qkv.buf }, { o.y.buf }); + ops.push_back(o); + VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt)); + return add(p, x); + } + + /* PyTorch's GroupNorm over the whole picture, `silu` or not (FLUX's VAE). Not row-local, so a + * VAE that has one runs whole (no banded tail). */ + VImg gnorm(const VImg& x, bool silu, const char* ckpt, int64_t groups, double eps) { + VOp o; + o.kind = VOp::GNORM; + o.x = x; + o.y = img(x.ch, x.lvl); + o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { x.ch }); + o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { x.ch }); + if (!gn_stats) + gn_stats = decl_b(b, nm->f("%s.gn_stats", scope), RAD_F32, { 64 * (2 + 3 * 1024) }); + o.k = (int)groups; + o.op = RAD_OP(b, "group_norm", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch), + RAD_INT("groups", groups), RAD_F64("eps", eps), + RAD_STR("act", silu ? "silu" : "none"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(o.w, o.b)); + rw(b, o.op, { x.buf, gn_stats }, { o.y.buf, gn_stats }); + ops.push_back(o); + return o.y; + } + /* A per-pixel linear with a bias (a 1x1 convolution kept as a Linear): `cout` from x's + * channels. */ + VImg lin(const VImg& x, int64_t cout, const char* ckpt) { + VOp o; + o.kind = VOp::LIN; + o.x = x; + o.y = img(cout, x.lvl); + o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch }); + o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout }); + o.op = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("N", cout), + RAD_INT("K", x.ch), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(o.w, o.b)), + { x.buf }, { o.y.buf }); + ops.push_back(o); + return o.y; + } + /* A GroupNorm residual block (FLUX's VAE, diffusers' ResnetBlock2D): norm1, silu, conv1, + * norm2, silu, conv2, plus the input or its 1x1 `conv_shortcut`. */ + VImg resblock_gn(const VImg& x, int64_t out, const char* ckpt, int64_t groups, double eps) { + VImg h = x; + if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt)); + VImg t = gnorm(x, true, nm->f("%s.norm1", ckpt), groups, eps); + t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt)); + t = gnorm(t, true, nm->f("%s.norm2", ckpt), groups, eps); + t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt)); + return add(t, h); + } + /* diffusers' single-head VAE attention: GroupNorm, to_q / to_k / to_v linears with biases, + * attention over every pixel, to_out.0, plus the input. */ + VImg attention_gn(const VImg& x, const char* ckpt, int64_t groups, double eps) { + const int64_t C = x.ch; + VImg t = gnorm(x, false, nm->f("%s.group_norm", ckpt), groups, eps); + VImg q = lin(t, C, nm->f("%s.to_q", ckpt)); + VImg k = lin(t, C, nm->f("%s.to_k", ckpt)); + VImg v = lin(t, C, nm->f("%s.to_v", ckpt)); + VOp o; + o.kind = VOp::ATTN; + o.x = q; + o.y = img(C, x.lvl); + o.z = k; + o.w = 0; + o.qkv_ch = 0; + o.k = 0; + o.op = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)C))), + RAD_NOWEIGHTS), + { q.buf, k.buf, v.buf }, { o.y.buf }); + attn_v.push_back({ ops.size(), v }); + ops.push_back(o); + VImg p = lin(o.y, C, nm->f("%s.to_out.0", ckpt)); + return add(p, x); + } + /* The value image of each separate-projection attention, by op index. */ + std::vector> attn_v; + const VImg* value_of(size_t i) const { + for (const auto& e : attn_v) if (e.first == i) return &e.second; + return nullptr; + } + + /* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens, + * for the decoder), in the op's schema order, and its ranged value. */ + static int64_t side(int64_t s0, int lvl, bool dn) { + int64_t s = s0; + for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2; + return s; + } + /* Declares `cu`, a buffer of the plugin's, as read by every attention: issue() hands it to + * them. */ + int attn_reads(rad_buf cu) const { + for (const VOp& o : ops) + if (o.kind == VOp::ATTN) RAD_ARCH_TRY(rad_op_reads(b, o.op, &cu, 1)); + return RAD_OK; + } + /* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the + * level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with + * `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */ + void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input, + size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const; + + bool is_whole(rad_buf v) const { + for (rad_buf w : whole) if (w == v) return true; + return false; + } + /* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most + * any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x + * upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail + * holds an op that is not row-local, or reads a whole buffer above level 0. */ + int64_t band_halo() const { + if (band_from < 0 || ops.empty()) return -1; + std::vector> need{ { ops.back().y.buf, 0 } }; + auto get = [&](rad_buf v) -> int64_t { + for (const auto& e : need) if (e.first == v) return e.second; + return 0; + }; + auto want = [&](rad_buf v, int64_t m) { + for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; } + need.push_back({ v, m }); + }; + for (size_t i = ops.size(); i-- > (size_t)band_from;) { + const VOp& o = ops[i]; + const int64_t my = get(o.y.buf); + switch (o.kind) { + case VOp::CONV: { + if (o.stride != 1) return -1; + const int64_t m = my + o.k / 2; + want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m); + break; + } + case VOp::NORM: want(o.x.buf, my); break; + case VOp::LIN: want(o.x.buf, my); break; + case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break; + case VOp::D2S: want(o.x.buf, (my + 1) / 2); break; + default: return -1; + } + } + int64_t h = 0; + for (size_t i = (size_t)band_from; i < ops.size(); ++i) { + const VOp& o = ops[i]; + for (const VImg* v : { &o.x, &o.z }) + if (v->buf && is_whole(v->buf)) { + if (v->lvl != 0) return -1; + h = std::max(h, get(v->buf)); + } + } + return h; + } +}; + +inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, + const void* input, size_t from, size_t to, int64_t row0) const { + auto ptr = [&](const VImg& v) -> const void* { + if (!v.buf) return input; + const char* p = (const char*)rad_buf_ptr(c, v.buf); + return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p; + }; + auto view = [&](const VImg& v, int64_t* H, int64_t* W) { + *H = side(H0, v.lvl, down); + *W = side(W0, v.lvl, down); + return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch); + }; + auto rows = [&](const VImg& v, int64_t cols) { + const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down); + return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols); + }; + for (size_t i = from; i < to && i < ops.size(); ++i) { + const VOp& o = ops[i]; + int64_t Hx, Wx, Hy, Wy; + switch (o.kind) { + case VOp::CONV: { + const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy); + RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y); + break; + } + case VOp::NORM: { + const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); + RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch)); + break; + } + case VOp::ADD: { + const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); + RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch)); + break; + } + case VOp::D2S: + case VOp::S2D: { + const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy); + RAD_ISSUE_N(c, o.op, Hy * Wy, x, y); + break; + } + case VOp::ATTN: { + const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); + const int64_t C = o.y.ch, n = H * W; + if (const VImg* v = value_of(i)) { + /* Separate q, k and v images. */ + RAD_ISSUE_N(c, o.op, n, rows(o.x, C), rows(o.z, C), rows(*v, C), cu, + brows(o.y.buf, n)); + } else { + /* q, k and v are column slices of the qkv rows, at its 3C pitch. */ + RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n), + bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n)); + } + break; + } + case VOp::GNORM: { + const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); + RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE, + RAD_P_T2(rad_buf_ptr(c, gn_stats), RAD_F32, 1, 64 * (2 + 3 * 1024)), + rows(o.y, o.y.ch)); + break; + } + case VOp::LIN: { + const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); + RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), RAD_W(o.b), RAD_NONE, + rows(o.y, o.y.ch)); + break; + } + } + } +} + +} /* namespace arch */ +} /* namespace rad */ diff --git a/arch/flux3/CMakeLists.txt b/arch/flux3/CMakeLists.txt new file mode 100644 index 00000000..1e15fd62 --- /dev/null +++ b/arch/flux3/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/flux3 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(flux3 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(flux3 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3.cpp) diff --git a/arch/flux3/flux3.cpp b/arch/flux3/flux3.cpp new file mode 100644 index 00000000..3eb721ac --- /dev/null +++ b/arch/flux3/flux3.cpp @@ -0,0 +1,1247 @@ +/* flux3 -- FLUX.3 [klein] (the step-distilled release and its base): text and up to ten + * reference pictures to an RGB image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt (diffusers' FLUX.3 modular pipeline): + * + * Conditioning network: Qwen3-VL-4B-Instruct's language model over the prompt in its chat + * template, right-padded to a multiple of 80 tokens. The padding takes part: each padding token + * sits at position 1 and attends to the prompt alone (`attn_cross`, the core's `valid_cu`). The + * generator reads eight hidden states per token (after layers 3, 7, ..., 31) side by side, + * 20480 values, through `context_embedder`. + * + * Denoiser: a 5.6B diffusion transformer over three modes, the text, the reference pictures' + * latents (VAE-encoded, the generator's own encoder; the conditioning network never sees them) + * and the image. Every block is parallel: `h += gate (attn(n) + mlp(n))`, `n` a LayerNorm with + * no affine times (1 + scale) plus shift. Five blocks per mode run each mode on its own, then + * 28 joint blocks run all three together; each mode takes its own shift, scale and gate from + * its own projection of the timestep embedding (the text and pictures at time 0, the image at + * the step's), separately for the early and the joint blocks. The step-distilled release is a + * flow map: the embedding of the time the step goes to is added to every mode's. A four-axis + * rotary (t, h, w, l) over the joint sequence: text along l, the image at (0, h/2, w/2, 0) and + * reference k at l = -(1 + k). + * + * Since every row changes with the step, nothing is cached as keys: the conditioning pass + * leaves each lane's text and reference rows (after their embedders) in its store, and every + * denoising step runs the three modes' early blocks over them and the image (mode-major rows) + * and the joint blocks over the entries ([text | pictures | image] each, the core's JOINT_STEP + * layout). + * + * Decoder: FLUX.2's VAE, 32 channels at 8x with GroupNorm and a single-head mid-block + * attention; a latent token is 2 x 2 of its pixels (128 values), normalised by the VAE's + * BatchNorm running statistics. + * + * The distilled release samples 16 steps without guidance, the base 50 with guidance 3.5 and an + * empty negative prompt; both a constant shift of 6.93. + * + * ============================== WHAT IS QUANTISED ============================== + * + * Every linear of the language model and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16 + * throughout when the first joint block's projection is plain; the embedders, the timestep MLPs, + * the modulations, the output layer and the VAE stay bf16. + * + * ============================== TENSOR PARALLEL ============================== + * + * The language model and the DiT blocks split by heads and feed-forward width. A parallel + * block's two branch outputs are added before their one all-reduce (the sum of the partial sums). + * Everything else, the VAE included (its GroupNorm reads the whole picture), runs on every rank. + */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef FLUX3_NS +#define FLUX3_NS flux3 +#define FLUX3_ID "flux3" +#endif + +namespace FLUX3_NS { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image: 2048 x 2048 pixels, 16384 latent tokens; 1024 x 1024 is the default. */ +enum { kMaxImageTokens = 16384 }; +/* Reference pictures: ten at most, each shrunk to 1024 x 1024 pixels of area when larger. */ +enum { kMaxRefs = 10, kRefArea = 1024 * 1024 }; +/* The prompt with its padding, at most; the pipeline pads to a multiple of 80. */ +enum { kMaxText = 1040, kPadMultiple = 80 }; +/* A reference picture's latent tokens at most: its area over 16 x 16 and the slack of its sides' + * rounding (the driver's bound). */ +static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 10 + 64; } +/* The longest conditioning: the text and every reference picture's tokens. */ +static inline int64_t cond_rows() { return kMaxText + kMaxRefs * ref_tokens_max(); } +/* Images in flight. Each lane keeps both branches' conditioning (cond_rows() rows apiece). */ +enum { kMaxLanes = 4 }; +/* The language model's hidden states read: hidden_states[i], the output of layer i - 1. */ +static const int kTaps[] = { 4, 8, 12, 16, 20, 24, 28, 32 }; +enum { kNTaps = 8 }; +/* Modes, in the order the joint layout lays an entry out. */ +enum { kText = 0, kRefs = 1, kImage = 2 }; + +/* ================================================================== the model */ +struct TeLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0; + int tap = -1; +}; + +/* A parallel block: the modulated LayerNorm (the previous block's gated sum added first), then + * attention and the SwiGLU from the same normed rows, their outputs added. */ +struct Block { + rad_weight w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, ff_in{}, ff_out{}; + GateQuantFP8 gq{}; + QuantFP8 q_attn{}; + rad_op op_n = 0, op_qkr = 0, op_attn = 0, op_sum = 0, op_ar = 0; +}; + +enum : int { + kGrpCtx = 1000, + kGrpVaeEnc = 1100, + kGrpVaeDec = 1200, + kGrpDit = 2000, /* model-level weights; the blocks kGrpDit + 1.. */ +}; + +struct Model { + Names nm{""}; + Geom gt{}, gd{}; + bool flow_map = false; + std::string te_pre; + + /* ---- the language model and context_embedder */ + rad_weight w_tok = 0, w_ctx = 0; + rad_op op_embed = 0, op_iota = 0, op_ctx = 0, op_store_t = 0; + rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0, b_tidx = 0, b_taps = 0, b_ctx = 0; + ActFP8 a_th{}, a_tattn{}, a_tffn{}; + std::vector te; + + /* ---- the reference pictures: the encoder, the mode, 2 x 2 tokens, BatchNorm, the embedder */ + Vae enc{}; + VImg enc_q{}; + rad_weight w_bnm = 0, w_bnv = 0, w_xc = 0; + rad_op op_enc_mode = 0, op_enc_zero = 0, op_enc_s2d = 0, op_enc_bn = 0, op_xc = 0, + op_store_r = 0, op_lstore_lat = 0, op_lstore_mask = 0, op_ecu = 0; + rad_buf b_emode = 0, b_epack = 0, b_elat = 0, b_eemb = 0, b_ecu = 0; + double bn_eps = 1e-4; + + /* ---- the timestep and every modulation */ + rad_weight w_t1 = 0, w_t2 = 0, w_tt1 = 0, w_tt2 = 0, w_fmod = 0; + rad_weight w_early[3] = {}, w_single[3] = {}; + rad_op op_tp = 0, op_tpt = 0, op_one = 0, op_zero = 0, op_iota3 = 0; + rad_op op_t1 = 0, op_ts = 0, op_t2 = 0, op_tt1 = 0, op_tts = 0, op_tt2 = 0; + rad_op op_addt = 0, op_actimg = 0, op_actzero = 0, op_fmod = 0; + rad_op op_early[3] = {}, op_single[3] = {}, op_ilv[3] = {}; + rad_buf b_tp = 0, b_e1 = 0, b_e1s = 0, b_temb = 0, b_tpt = 0, b_tt1 = 0, b_tt1s = 0; + rad_buf b_ttgt = 0; + rad_buf b_aimg = 0, b_azero = 0, b_idx3 = 0, b_fmod = 0; + rad_buf b_early[3] = {}, b_smod[3] = {}, b_single = 0; + + /* ---- the DiT */ + int64_t C = 128; + int64_t t_ch = 256; /* the timestep sinusoid's width */ + rad_weight w_xi = 0; + rad_op op_randn = 0, op_lgather = 0, op_xi = 0, op_gtxt = 0, op_join = 0, op_g2 = 0, op_g3 = 0, + op_gimg = 0, op_nout = 0, op_pout = 0, op_euler = 0; + rad_buf b_lat = 0, b_xc = 0, b_h = 0, b_qkv = 0, b_o = 0, b_gu = 0, b_f = 0, b_sum = 0, + b_hi = 0, b_fz = 0, b_v = 0; + ActFP8 a_hm{}, a_attn{}, a_ffn{}; + std::vector mode[3], single; + LinearFP8 qkv0{}; + rad_weight w_pout = 0; + + /* ---- per-image state and conditioning store (PERSIST) */ + rad_buf b_state = 0, b_prev = 0, b_inp = 0, b_mask = 0, b_store = 0; + + /* ---- the decoder */ + Vae dec{}; + VImg dec_out{}; + rad_op op_dbn = 0, op_dzero = 0, op_unpack = 0, op_cu4 = 0, op_rgb = 0; + rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0; +}; + +static Model g_model[MAX_RANKS]; + +static std::vector meta_list(const RadModelMeta* m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(m, key, nullptr); + while (s && *s) { + char* e = nullptr; + const double x = std::strtod(s, &e); + if (e == s) { ++s; continue; } + v.push_back(x); + s = e; + } + return v; +} + +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A bf16 linear without a bias, read whole on every rank. */ +static rad_op dense(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t N, int64_t K, + int64_t rows, rad_buf in, rad_buf out, rad_weight* w, int access, int group) { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), RAD_BF16, { N, K }, access, + group); + if (!*w) return 0; + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w)), + { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, + rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op all_reduce(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows) { + if (g.world <= 1) return 0; + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, rows * g.n_embd), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + const char* arch = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strncmp(arch, "Flux3", 5) != 0) { + fprintf(stderr, "radiance: flux3: the container's pipeline is '%s', not FLUX.3's\n", arch); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "transformer.in_channels", 128) != 128 || + rad_meta_geti(meta, "vae.latent_channels", 32) != 32) { + fprintf(stderr, "radiance: flux3: the DiT must read 128-value tokens of a 32-channel " + "VAE\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== declare */ +/* The language model up to its last tap; a tapped layer's output goes to its 2560 columns of the + * stacked row, which context_embedder reads. */ +static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = kMaxText; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(), E = g.n_embd; + const char* pre = m.te_pre.c_str(); + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, E }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, E }); + m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, E }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", E, T)); + m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim }); + m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T)); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, E }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T)); + m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { T, kNTaps * E }); + m.b_tidx = decl_b(b, nm.f("te.rows"), RAD_I32, { T }); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", E), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + m.op_iota = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("start", 0), + RAD_INT("step", 1)), + RAD_NOWEIGHTS), + {}, { m.b_tidx }); + const std::vector sec = meta_list(meta, "text_config.rope_scaling.mrope_section"); + char sections[48]; + if (sec.size() == 3) + std::snprintf(sections, sizeof sections, "%d %d %d", (int)sec[0], (int)sec[1], (int)sec[2]); + else + std::snprintf(sections, sizeof sections, "24 20 20"); + const int n_run = kTaps[kNTaps - 1]; + if (g.n_layer < n_run) { + fprintf(stderr, "radiance: flux3: the text encoder has %lld layers; its last tap is after " + "layer %d\n", (long long)g.n_layer, n_run); + return RAD_E_INVAL; + } + m.te.resize((size_t)n_run); + for (int l = 0; l < n_run; ++l) { + TeLayer& L = m.te[(size_t)l]; + for (int t = 0; t < kNTaps; ++t) if (kTaps[t] == l + 1) L.tap = t; + const char* lp = nm.f("%s.layers.%d", pre, l); + L.w_n1 = wcopy(b, nm.f("te.blk.%d.attn_norm.weight", l), + nm.ckpt("%s.input_layernorm.weight", lp), RAD_F32, { E }, RAD_ACCESS_PER_TOKEN, l); + L.w_n2 = wcopy(b, nm.f("te.blk.%d.ffn_norm.weight", l), + nm.ckpt("%s.post_attention_layernorm.weight", lp), RAD_F32, { E }, + RAD_ACCESS_PER_TOKEN, l); + L.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", l), nm.ckpt("%s.self_attn.q_norm.weight", lp), + RAD_BF16, { g.head_dim }, RAD_ACCESS_PER_TOKEN, l); + L.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", l), nm.ckpt("%s.self_attn.k_norm.weight", lp), + RAD_BF16, { g.head_dim }, RAD_ACCESS_PER_TOKEN, l); + if (!L.w_n1 || !L.w_n2 || !L.w_qn || !L.w_kn) return RAD_E_INVAL; + L.op_n1 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n1)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_th, E)); + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("te.blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, E, + RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.self_attn.q_proj.weight", lp), + nm.ckpt("%s.self_attn.k_proj.weight", lp), + nm.ckpt("%s.self_attn.v_proj.weight", lp) }, + m.a_th, m.b_tkv, T, { q_dim, kv_dim, kv_dim })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_STR("mode", "imrope"), + RAD_INT("rotary_dim", g.head_dim), + RAD_STR("sections", nm.f("%s", sections))), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); + /* The padding attends to the prompt only: its keys are the prompt's (valid_cu). */ + L.op_attn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim))), + RAD_NOWEIGHTS), + { m.b_tkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_tattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("te.blk.%d.attn_output", l), E, q_dim, + RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.self_attn.o_proj.weight", lp) }, m.a_tattn, m.b_th2, + T)); + L.op_ar1 = all_reduce(b, g, m.b_th2, T); + L.op_add1 = add_op(b, T, E, m.b_tx, m.b_th2, m.b_tx); + L.op_n2 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n2)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_th, E)); + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("te.blk.%d.ffn_gate_up", l), 2 * g.n_ff, E, + RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.mlp.gate_proj.weight", lp), + nm.ckpt("%s.mlp.up_proj.weight", lp) }, + m.a_th, m.b_tgu, T, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_tgu, m.a_tffn, g.n_ff, "silu", T, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("te.blk.%d.ffn_down", l), E, g.n_ff, + RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.mlp.down_proj.weight", lp) }, m.a_tffn, m.b_th2, + T)); + L.op_ar2 = all_reduce(b, g, m.b_th2, T); + L.op_add2 = add_op(b, T, E, m.b_tx, m.b_th2, m.b_tx); + if (L.tap >= 0) + L.op_tap = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps }); + if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 || + (L.tap >= 0 && !L.op_tap)) + return RAD_E_INVAL; + } + /* ---- context_embedder over the stacked taps, into every lane's store */ + const int64_t D = m.gd.n_embd; + m.b_ctx = decl_b(b, nm.f("ctx.out"), RAD_BF16, { T, D }); + m.op_ctx = dense(b, nm, "ctx", "transformer.context_embedder", D, kNTaps * E, T, m.b_taps, + m.b_ctx, &m.w_ctx, RAD_ACCESS_PER_REQUEST, kGrpCtx); + m.op_store_t = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_INT("stride", 2 * cond_rows()), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ctx, m.b_store }, { m.b_store }); + return m.op_embed && m.op_iota && m.op_ctx && m.op_store_t ? RAD_OK : RAD_E_INVAL; +} + +/* FLUX.2's VAE encoder for the reference pictures (and a repainted picture), its mode, the 2 x 2 + * tokens, the BatchNorm, and the reference embedder into the store. */ +static int declare_encoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Vae& v = m.enc; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "venc"; + v.down = true; + v.first_group = kGrpVaeEnc; + v.base_px = ref_tokens_max() * 256 > (int64_t)kMaxImageTokens * 256 + ? ref_tokens_max() * 256 : (int64_t)kMaxImageTokens * 256; + /* The mid-block attends over the 8x grid: four of the pass's 16x tokens a 16x token. */ + m.b_ecu = decl_b(b, nm.f("venc.cu"), RAD_I32, { 2 }); + m.op_ecu = rw(b, RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)), + RAD_NOWEIGHTS), + {}, { m.b_ecu }); + if (!m.op_ecu) return RAD_E_INVAL; + std::vector ch = meta_list(meta, "vae.block_out_channels"); + if (ch.empty()) ch = { 128, 256, 512, 512 }; + const int64_t nres = rad_meta_geti(meta, "vae.layers_per_block", 2); + const int64_t groups = rad_meta_geti(meta, "vae.norm_num_groups", 32); + const int64_t zc = rad_meta_geti(meta, "vae.latent_channels", 32); + const double eps = 1e-6; + const int64_t nb = (int64_t)ch.size(); + VImg x = v.conv(VImg{ 0, 3, 0 }, (int64_t)ch[0], 3, 1, 1, "same", "vae.encoder.conv_in"); + for (int64_t i = 0; i < nb; ++i) { + for (int64_t r = 0; r < nres; ++r) + x = v.resblock_gn(x, (int64_t)ch[(size_t)i], + nm.f("vae.encoder.down_blocks.%lld.resnets.%lld", (long long)i, + (long long)r), groups, eps); + if (i + 1 < nb) + x = v.conv(x, x.ch, 3, 2, 1, "down", + nm.f("vae.encoder.down_blocks.%lld.downsamplers.0.conv", (long long)i)); + } + x = v.resblock_gn(x, x.ch, "vae.encoder.mid_block.resnets.0", groups, eps); + x = v.attention_gn(x, "vae.encoder.mid_block.attentions.0", groups, eps); + x = v.resblock_gn(x, x.ch, "vae.encoder.mid_block.resnets.1", groups, eps); + x = v.gnorm(x, true, "vae.encoder.conv_norm_out", groups, eps); + x = v.conv(x, 2 * zc, 3, 1, 1, "same", "vae.encoder.conv_out"); + m.enc_q = v.conv(x, 2 * zc, 1, 1, 1, "same", "vae.quant_conv"); + if (!m.enc_q.buf) return RAD_E_INVAL; + RAD_ARCH_TRY(v.attn_reads(m.b_ecu)); + /* The mode (the first zc channels) as a dense image, its 2 x 2 tokens (s2d_avg_add over one + * value a group is a plain space-to-depth into c 4 + 2 i + j), then the BatchNorm. */ + const int64_t px8 = v.px_at(m.enc_q.lvl), tok = (px8 + 3) / 4; + m.b_emode = decl_b(b, nm.f("venc.mode"), RAD_BF16, { px8, zc }); + m.b_epack = decl_b(b, nm.f("venc.pack"), RAD_BF16, { tok, 4 * zc }); + m.b_elat = decl_b(b, nm.f("venc.lat"), RAD_BF16, { tok, 4 * zc }); + m.b_eemb = decl_b(b, nm.f("venc.emb"), RAD_BF16, { tok, m.gd.n_embd }); + std::string ones, zeros; + for (int64_t k = 0; k < zc; ++k) { ones += k ? " 1" : "1"; zeros += k ? " 0" : "0"; } + static thread_local std::string s_ones, s_zeros; + s_ones = ones; + s_zeros = zeros; + m.op_enc_mode = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, px8), RAD_INT("n", zc), + RAD_STR("mul", s_ones.c_str()), + RAD_STR("add", s_zeros.c_str()), RAD_STR("mode", "fma"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.enc_q.buf }, { m.b_emode }); + m.op_enc_zero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("n", 4 * zc), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_epack }); + m.op_enc_s2d = rw(b, RAD_OP(b, "s2d_avg_add", + RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("cin", zc), + RAD_INT("cout", 4 * zc), RAD_INT("ft", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_emode, m.b_epack }, { m.b_epack }); + m.w_bnm = wcopy(b, nm.f("vae.bn.mean"), nm.ckpt("vae.bn.running_mean"), RAD_BF16, { 4 * zc }, + RAD_ACCESS_PER_REQUEST, kGrpVaeEnc); + m.w_bnv = wcopy(b, nm.f("vae.bn.var"), nm.ckpt("vae.bn.running_var"), RAD_BF16, { 4 * zc }, + RAD_ACCESS_PER_REQUEST, kGrpVaeEnc); + m.bn_eps = rad_meta_getf(meta, "vae.batch_norm_eps", 1e-4); + m.op_enc_bn = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("n", 4 * zc), + RAD_STR("mode", "norm"), RAD_INT("var", 1), + RAD_F64("eps", m.bn_eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_bnm, m.w_bnv)), + { m.b_epack }, { m.b_elat }); + /* A reference's tokens through its embedder into the store after the text; a repainted + * picture's into its lanes with the mask. */ + m.op_xc = dense(b, nm, "dit.x_cond", "transformer.x_embedders.image_cond", m.gd.n_embd, 4 * zc, + tok, m.b_elat, m.b_eemb, &m.w_xc, RAD_ACCESS_PER_REQUEST, kGrpDit); + m.op_store_r = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, tok), RAD_INT("n", m.gd.n_embd), + RAD_INT("stride", 2 * cond_rows()), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_eemb, m.b_store }, { m.b_store }); + m.op_lstore_lat = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens), + RAD_INT("n", 4 * zc), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_elat, m.b_inp }, { m.b_inp }); + m.op_lstore_mask = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)kMaxImageTokens), + RAD_INT("n", 1), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_mask }, { m.b_mask }); + return m.op_enc_mode && m.op_enc_zero && m.op_enc_s2d && m.w_bnm && m.w_bnv && m.op_enc_bn && + m.op_xc && m.op_store_r && m.op_lstore_lat && m.op_lstore_mask + ? RAD_OK : RAD_E_INVAL; +} + +/* One parallel block's weights and ops over at most `rows` rows. `gated`: the norm adds the + * previous block's gated sum first. */ +static int declare_block(RadBuilder* b, Model& m, Block& B, const char* pre, const char* dn, + int grp, int64_t rows, bool gated, const char* sections, rad_buf mod) { + Geom& g = m.gd; + Names& nm = m.nm; + const int64_t D = g.n_embd, qd = g.q_dim(), hd = g.head_dim; + const double eps = g.eps; + B.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.attn.norm_q.weight", pre), RAD_F32, + { hd }, RAD_ACCESS_PER_TOKEN, grp); + B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32, + { hd }, RAD_ACCESS_PER_TOKEN, grp); + if (!B.w_qn || !B.w_kn) return RAD_E_INVAL; + const bool q = !g.w_bf16; + auto norm = [&](bool gt) { + rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D), + RAD_F64("eps", eps), RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("gated", gt ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS) + : RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", D), + RAD_F64("eps", eps), RAD_INT("gated", gt ? 1 : 0), + RAD_STR("dtype", "bf16"), RAD_STR("norm", "layer")), + RAD_NOWEIGHTS); + if (!op) return op; + /* The residual, the modulation table and, gated, the branch sum. */ + rad_buf rd[4] = { m.b_xc, m.b_h, mod, m.b_sum }; + rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h }; + rad_buf wb[2] = { m.a_hm.x, m.b_h }; + rad_op_reads(b, op, rd, gt ? 4 : 3); + if (q) rad_op_writes(b, op, wq, 3); + else rad_op_writes(b, op, wb, 2); + return op; + }; + B.op_n = norm(gated); + RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW, + grp_layer(grp), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) }, + m.a_hm, m.b_qkv, rows, { qd, qd, qd })); + B.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", g.theta), RAD_F64("eps", eps), + RAD_STR("mode", "gptj_blocks"), RAD_INT("rotary_dim", hd), + RAD_STR("sections", sections)), + RAD_WEIGHTS(B.w_qn, B.w_kn)), + { m.b_qkv }, { m.b_qkv }); + B.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.a_attn.x }); + RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) }, m.a_attn, + m.b_o, rows)); + RAD_ARCH_TRY(B.ff_in.declare(b, nm, g, nm.f("%s.ffn_in", dn), 2 * g.n_ff, D, RAD_SHARD_ROW, + grp_layer(grp), { nm.ckpt("%s.ff.linear_in.weight", pre) }, m.a_hm, + m.b_gu, rows, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(B.gq.declare(b, g, m.b_gu, m.a_ffn, g.n_ff, "silu", rows, true)); + RAD_ARCH_TRY(B.ff_out.declare(b, nm, g, nm.f("%s.ffn_out", dn), D, g.n_ff, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.ff.linear_out.weight", pre) }, + m.a_ffn, m.b_f, rows)); + B.op_sum = add_op(b, rows, D, m.b_o, m.b_f, m.b_sum); + B.op_ar = all_reduce(b, g, m.b_sum, rows); + return B.op_n && B.op_qkr && B.op_attn && B.op_sum ? RAD_OK : RAD_E_INVAL; +} + +static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const int64_t T = g.max_tok, S = g.max_seqs, D = g.n_embd, C = m.C; + const int gx = kGrpDit; + const int64_t NI = std::min(T, 2 * (int64_t)kMaxImageTokens); + const int64_t te = rad_meta_geti(meta, "transformer.timestep_channels", 256); + m.t_ch = te; + + /* ---- timestep embeddings, the MLP over 2 S rows at once: rows [0, S) the image's time, rows + * [S, 2 S) time 0's, whose sinusoid is [cos 0 | sin 0], ones then zeros. With a flow map the + * target time's embedding is added to both halves. silu of each half feeds the modulations. + * Every op is issued once a step: an op issued again over other buffers would outrun the + * arena's plan, which orders buffers by declaration. */ + m.b_tp = decl_b(b, nm.f("dit.tp"), RAD_BF16, { 2 * S, te }); + m.b_e1 = decl_b(b, nm.f("dit.e1"), RAD_BF16, { 2 * S, D }); + m.b_e1s = decl_b(b, nm.f("dit.e1s"), RAD_BF16, { 2 * S, D }); + m.b_temb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { 2 * S, D }); + m.b_aimg = decl_b(b, nm.f("dit.a_img"), RAD_BF16, { S, D }); + m.b_azero = decl_b(b, nm.f("dit.a_zero"), RAD_BF16, { S, D }); + auto tstep = [&](rad_buf out) { + return rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", te), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_INT("round", 3), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { out }); + }; + m.op_tp = tstep(m.b_tp); + auto fill = [&](double v) { + return rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", te / 2), + RAD_STR("dtype", "bf16"), RAD_F64("value", v)), + RAD_NOWEIGHTS), + {}, { m.b_tp }); + }; + m.op_one = fill(1.0); + m.op_zero = fill(0.0); + m.op_t1 = dense(b, nm, "dit.t1", "transformer.timestep_embedder.linear_1", D, te, 2 * S, + m.b_tp, m.b_e1, &m.w_t1, RAD_ACCESS_PER_TOKEN, gx); + m.op_ts = unary(b, "silu", 2 * S, D, m.b_e1, m.b_e1s); + m.op_t2 = dense(b, nm, "dit.t2", "transformer.timestep_embedder.linear_2", D, D, 2 * S, m.b_e1s, + m.b_temb, &m.w_t2, RAD_ACCESS_PER_TOKEN, gx); + if (m.flow_map) { + m.b_tpt = decl_b(b, nm.f("dit.tp_tgt"), RAD_BF16, { S, te }); + m.b_tt1 = decl_b(b, nm.f("dit.tt1"), RAD_BF16, { S, D }); + m.b_tt1s = decl_b(b, nm.f("dit.tt1s"), RAD_BF16, { S, D }); + m.b_ttgt = decl_b(b, nm.f("dit.t_tgt"), RAD_BF16, { S, D }); + m.op_tpt = tstep(m.b_tpt); + m.op_tt1 = dense(b, nm, "dit.tt1", "transformer.target_timestep_embedder.linear_1", D, te, + S, m.b_tpt, m.b_tt1, &m.w_tt1, RAD_ACCESS_PER_TOKEN, gx); + m.op_tts = unary(b, "silu", S, D, m.b_tt1, m.b_tt1s); + m.op_tt2 = dense(b, nm, "dit.tt2", "transformer.target_timestep_embedder.linear_2", D, D, + S, m.b_tt1s, m.b_ttgt, &m.w_tt2, RAD_ACCESS_PER_TOKEN, gx); + /* Issued on each half of the same buffers. */ + m.op_addt = add_op(b, S, D, m.b_temb, m.b_ttgt, m.b_temb); + if (!m.op_tpt || !m.op_tt1 || !m.op_tts || !m.op_tt2 || !m.op_addt) return RAD_E_INVAL; + } + m.op_actimg = unary(b, "silu", S, D, m.b_temb, m.b_aimg); + m.op_actzero = unary(b, "silu", S, D, m.b_temb, m.b_azero); + if (!m.op_tp || !m.op_one || !m.op_zero || !m.op_t1 || !m.op_ts || !m.op_t2 || !m.op_actimg || + !m.op_actzero) + return RAD_E_INVAL; + + /* ---- every mode's modulations: the early ones by mode (each mode's blocks find an entry's + * row by their own cu), the joint ones interleaved as [3 S, 3 D], entry e's mode k at row + * 3 e + k (the joint blocks find a row's segment by mode_cu) */ + static const char* kModeName[3] = { "txt", "image_cond", "image" }; + m.b_idx3 = decl_b(b, nm.f("dit.idx3"), RAD_I32, { S }); + m.op_iota3 = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("start", 0), RAD_INT("step", 3)), + RAD_NOWEIGHTS), + {}, { m.b_idx3 }); + m.b_single = decl_b(b, nm.f("dit.mod_single"), RAD_BF16, { 3 * S, 3 * D }); + for (int k = 0; k < 3; ++k) { + const rad_buf act = k == kImage ? m.b_aimg : m.b_azero; + m.b_early[k] = decl_b(b, nm.f("dit.mod_early.%d", k), RAD_BF16, { S, 3 * D }); + m.b_smod[k] = decl_b(b, nm.f("dit.mod_s.%d", k), RAD_BF16, { S, 3 * D }); + m.op_early[k] = dense(b, nm, nm.f("dit.early.%s", kModeName[k]), + nm.ckpt("transformer.early_stream_modulations.%s.linear", kModeName[k]), + 3 * D, D, S, act, m.b_early[k], &m.w_early[k], RAD_ACCESS_PER_TOKEN, gx); + m.op_single[k] = dense(b, nm, nm.f("dit.single.%s", kModeName[k]), + nm.ckpt("transformer.single_stream_modulations.%s.linear", + kModeName[k]), + 3 * D, D, S, act, m.b_smod[k], &m.w_single[k], RAD_ACCESS_PER_TOKEN, + gx); + m.op_ilv[k] = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", 3 * D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_smod[k], m.b_idx3, m.b_single }, { m.b_single }); + if (!m.op_early[k] || !m.op_single[k] || !m.op_ilv[k]) return RAD_E_INVAL; + } + /* The output layer's (scale, shift) from silu(image temb), reordered to (shift, scale). */ + { + const char* src = nm.ckpt("transformer.norm_out.linear.weight"); + RAD_ARCH_TRY(map_rows(b, nm.f("dit.norm_out.weight"), { { src, (int)D, D }, { src, 0, D } })); + m.w_fmod = decl_w(b, nm.f("dit.norm_out.weight"), RAD_BF16, { 2 * D, D }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(gx)); + m.b_fmod = decl_b(b, nm.f("dit.mod_out"), RAD_BF16, { S, 2 * D }); + m.op_fmod = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", 2 * D), + RAD_INT("K", D), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_fmod)), + { m.b_aimg }, { m.b_fmod }); + if (!m.w_fmod || !m.op_fmod) return RAD_E_INVAL; + } + + /* ---- the rows: the image's latents through its embedder, the store's text and pictures, + * all mode-major in `xc` (text, pictures, image), then joined entry by entry into `h` */ + m.b_lat = decl_b(b, nm.f("dit.lat"), RAD_BF16, { NI, C }); + m.b_xc = decl_b(b, nm.f("dit.xc"), RAD_BF16, { T, D }); + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + m.op_randn = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state }); + m.op_lgather = rw(b, RAD_OP(b, "lane_gather", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_lat }); + m.op_xi = dense(b, nm, "dit.x_img", "transformer.x_embedders.image", D, C, NI, m.b_lat, m.b_xc, + &m.w_xi, RAD_ACCESS_PER_TOKEN, gx); + m.op_gtxt = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_store }, { m.b_xc }); + if (!m.op_randn || !m.op_lgather || !m.op_xi || !m.op_gtxt) return RAD_E_INVAL; + + /* ---- the blocks' buffers */ + const int64_t qd = g.q_dim(); + m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D }); + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd }); + m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd }); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd)); + m.b_o = decl_b(b, nm.f("dit.o"), RAD_BF16, { T, D }); + m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff)); + m.b_f = decl_b(b, nm.f("dit.f"), RAD_BF16, { T, D }); + m.b_sum = decl_b(b, nm.f("dit.sum"), RAD_BF16, { T, D }); + + const std::vector ax = meta_list(meta, "transformer.axes_dims_rope"); + if (!ax.empty() && (ax.size() != 4 || (int64_t)(ax[0] + ax[1] + ax[2] + ax[3]) != g.head_dim)) { + fprintf(stderr, "radiance: flux3: transformer.axes_dims_rope must be four widths summing " + "to the head\n"); + return RAD_E_INVAL; + } + const char* sections = ax.empty() ? "16 16 16 16" + : nm.f("%d %d %d %d", (int)ax[0] / 2, (int)ax[1] / 2, + (int)ax[2] / 2, (int)ax[3] / 2); + + /* The early blocks, five a mode, then the joint blocks; the ops are declared in issue + * order: text, pictures, image, joint. */ + const int64_t nl = rad_meta_geti(meta, "transformer.num_layers", 5); + const int64_t ns = rad_meta_geti(meta, "transformer.num_single_layers", 28); + int grp = kGrpDit + 1; + for (int k = 0; k < 3; ++k) { + m.mode[k].resize((size_t)nl); + for (int64_t i = 0; i < nl; ++i) { + const char* pre = k == kText + ? nm.ckpt("transformer.txt_mode_blocks.%d", (int)i) + : nm.ckpt("transformer.mode_blocks.%s.%d", kModeName[k], (int)i); + RAD_ARCH_TRY(declare_block(b, m, m.mode[k][(size_t)i], pre, + nm.f("dit.mode.%d.%d", k, (int)i), grp++, T, i > 0, + sections, m.b_early[k])); + } + } + /* The early stacks' last sums gated in where each mode's rows lie in the mode-major order, + * then the rows joined. */ + m.op_g2 = rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_sum, m.b_early[0], m.b_early[1], m.b_early[2], m.b_xc }, { m.b_xc }); + m.op_join = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_xc, m.b_h }, { m.b_h }); + m.single.resize((size_t)ns); + for (int64_t i = 0; i < ns; ++i) + RAD_ARCH_TRY(declare_block(b, m, m.single[(size_t)i], + nm.ckpt("transformer.single_transformer_blocks.%d", (int)i), + nm.f("dit.single.%d", (int)i), grp++, T, i > 0, sections, + m.b_single)); + /* The joint stack's last sum gated in. */ + m.op_g3 = rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_sum, m.b_single, m.b_h }, { m.b_h }); + if (!m.op_g3) return RAD_E_INVAL; + + /* ---- the output: the image rows, the final adaptive LayerNorm, proj_out, the step */ + m.b_hi = decl_b(b, nm.f("dit.h_img"), RAD_BF16, { NI, D }); + m.b_fz = decl_b(b, nm.f("dit.fz"), RAD_BF16, { NI, D }); + m.b_v = decl_b(b, nm.f("dit.v"), RAD_BF16, { NI, C }); + m.op_gimg = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_h }, { m.b_hi }); + m.op_nout = rw(b, RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), RAD_F64("eps", g.eps), + RAD_INT("gated", 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS), + { m.b_fmod, m.b_hi }, { m.b_hi, m.b_fz }); + m.op_pout = dense(b, nm, "dit.proj_out", "transformer.proj_out", C, D, NI, m.b_fz, m.b_v, + &m.w_pout, RAD_ACCESS_PER_TOKEN, gx); + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_v, m.b_inp, m.b_mask, m.b_state, m.b_prev }, { m.b_state, m.b_prev }); + return m.op_g2 && m.op_join && m.op_gimg && m.op_nout && m.op_pout && m.op_euler + ? RAD_OK : RAD_E_INVAL; +} + +/* FLUX.2's VAE decoder: the latent denormalised by the BatchNorm, unpacked to 32 channels, then + * GroupNorm residual blocks, the mid-block attention and nearest-neighbour upsampling, run whole + * on every rank. */ +static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Vae& v = m.dec; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = kGrpVaeDec; + v.base_px = (int64_t)kMaxImageTokens * 4; + std::vector ch = meta_list(meta, "vae.decoder_block_out_channels"); + if (ch.empty()) ch = meta_list(meta, "vae.block_out_channels"); + if (ch.empty()) ch = { 128, 256, 512, 512 }; + const int64_t nres = rad_meta_geti(meta, "vae.layers_per_block", 2); + const int64_t groups = rad_meta_geti(meta, "vae.norm_num_groups", 32); + const int64_t zc = rad_meta_geti(meta, "vae.latent_channels", 32); + const double eps = 1e-6; + const int64_t NT = kMaxImageTokens; + m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zc }); + m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zc }); + m.b_cu4 = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 }); + m.op_dbn = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", 4 * zc), + RAD_STR("mode", "denorm"), RAD_INT("var", 1), + RAD_F64("eps", m.bn_eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_bnm, m.w_bnv)), + { m.b_state, m.b_prev }, { m.b_dl }); + m.op_dzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("n", zc), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_decin }); + m.op_unpack = rw(b, RAD_OP(b, "d2s_add", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("cin", 4 * zc), + RAD_INT("cout", zc), RAD_INT("ft", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dl, m.b_decin }, { m.b_decin }); + m.op_cu4 = rw(b, RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)), + RAD_NOWEIGHTS), + {}, { m.b_cu4 }); + if (!m.op_dbn || !m.op_dzero || !m.op_unpack || !m.op_cu4) return RAD_E_INVAL; + const std::vector rch(ch.rbegin(), ch.rend()); + VImg x{ m.b_decin, zc, 0 }; + if (rad_meta_geti(meta, "vae.use_post_quant_conv", 1)) + x = v.conv(x, zc, 1, 1, 1, "same", "vae.post_quant_conv"); + x = v.conv(x, (int64_t)rch[0], 3, 1, 1, "same", "vae.decoder.conv_in"); + x = v.resblock_gn(x, x.ch, "vae.decoder.mid_block.resnets.0", groups, eps); + x = v.attention_gn(x, "vae.decoder.mid_block.attentions.0", groups, eps); + x = v.resblock_gn(x, x.ch, "vae.decoder.mid_block.resnets.1", groups, eps); + for (size_t i = 0; i < rch.size(); ++i) { + for (int64_t r = 0; r < nres + 1; ++r) + x = v.resblock_gn(x, (int64_t)rch[i], + nm.f("vae.decoder.up_blocks.%d.resnets.%d", (int)i, (int)r), groups, + eps); + if (i + 1 < rch.size()) + x = v.conv(x, x.ch, 3, 1, 2, "same", nm.f("vae.decoder.up_blocks.%d.upsamplers.0.conv", + (int)i)); + } + x = v.gnorm(x, true, "vae.decoder.conv_norm_out", groups, eps); + m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out"); + if (!m.dec_out.buf) return RAD_E_INVAL; + RAD_ARCH_TRY(v.attn_reads(m.b_cu4)); + const int64_t px = (int64_t)kMaxImageTokens * 256; + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST); + m.op_rgb = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + return m.op_rgb ? RAD_OK : RAD_E_INVAL; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16)); + Names& nm = m.nm; + m.te_pre = std::strstr(rad_meta_gets(meta, "architectures", ""), "ForConditionalGeneration") + ? "model.language_model" : "language_model"; + m.flow_map = rad_meta_geti(meta, "transformer.flow_map", 0) != 0; + + Geom& gd = m.gd; + gd = m.gt; + gd.head_dim = rad_meta_geti(meta, "transformer.attention_head_dim", 128); + gd.n_head_all = rad_meta_geti(meta, "transformer.num_attention_heads", 24); + gd.n_head_kv_all = gd.n_head_all; + gd.n_embd = gd.head_dim * gd.n_head_all; + gd.n_ff_all = (int64_t)(gd.n_embd * rad_meta_getf(meta, "transformer.mlp_ratio", 3.0)); + gd.eps = (float)rad_meta_getf(meta, "transformer.eps", 1e-6); + gd.theta = (float)rad_meta_getf(meta, "transformer.rope_theta", 10000.0); + gd.n_layer = rad_meta_geti(meta, "transformer.num_single_layers", 28); + RAD_ARCH_TRY(divide_or_fail(gd.n_head_all, gd.world, "transformer.num_attention_heads", + &gd.n_head)); + gd.n_head_kv = gd.n_head; + gd.kv_off = 0; + RAD_ARCH_TRY(divide_or_fail(gd.n_ff_all, gd.world, "the DiT's feed-forward width", &gd.n_ff)); + if (m.gt.n_embd * kNTaps != rad_meta_geti(meta, "transformer.joint_attention_dim", 20480)) { + fprintf(stderr, "radiance: flux3: the DiT reads %lld-wide conditioning and %d taps of the " + "text encoder are %lld\n", + (long long)rad_meta_geti(meta, "transformer.joint_attention_dim", 0), kNTaps, + (long long)(m.gt.n_embd * kNTaps)); + return RAD_E_INVAL; + } + m.C = rad_meta_geti(meta, "transformer.in_channels", 128); + { + LinearFP8& probe = m.qkv0; + RAD_ARCH_TRY(probe.probe(b, nm, gd, "dit.single.0.attn_qkv", + { "transformer.single_transformer_blocks.0.attn.to_q.weight", + "transformer.single_transformer_blocks.0.attn.to_k.weight", + "transformer.single_transformer_blocks.0.attn.to_v.weight" })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.single.0.attn_qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + gd.w_bf16 = m.gt.w_bf16 = plain; + } + + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_inp = decl_b(b, nm.f("lat_repaint"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_mask = decl_b(b, nm.f("lat_mask"), RAD_F32, { lane_rows, 1 }, RAD_BUF_PERSIST); + m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, + { 2 * (int64_t)kMaxLanes * cond_rows(), gd.n_embd }, RAD_BUF_PERSIST); + RAD_ARCH_TRY(declare_te(b, meta, m)); + RAD_ARCH_TRY(declare_encoder(b, meta, m)); + RAD_ARCH_TRY(declare_dit(b, meta, m)); + RAD_ARCH_TRY(declare_decoder(b, meta, m)); + + if (!ctx->shape_probe) { + RadGeneratorDecl d{}; + d.name = m.flow_map ? "flux-3-image-klein" : "flux-3-image-klein-base"; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.tmpl_text = "<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"; + d.tmpl_edit = d.tmpl_text; + d.drop_prefix = ""; + d.latent_channels = m.C; + d.latent_scale = 16; + d.size_multiple = 16; + d.pixel_channels = 3; + d.slot_rows = 1; + d.max_tokens = kMaxImageTokens; + d.max_refs = kMaxRefs; + d.ref_area = kRefArea; + d.ref_shrink_only = 1; + d.default_width = 1024; + d.default_height = 1024; + d.default_steps = m.flow_map ? 16 : 50; + d.shift = rad_meta_getf(meta, "scheduler.shift", 6.93); + d.dyn_shift = (int32_t)rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 0); + d.shift_exp = std::strcmp(rad_meta_gets(meta, "scheduler.time_shift_type", "exponential"), + "exponential") == 0; + d.base_shift = rad_meta_getf(meta, "scheduler.base_shift", 0.5); + d.max_shift = rad_meta_getf(meta, "scheduler.max_shift", 1.15); + d.base_seq = rad_meta_geti(meta, "scheduler.base_image_seq_len", 256); + d.max_seq = rad_meta_geti(meta, "scheduler.max_image_seq_len", 4096); + d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.0); + d.default_cfg = m.flow_map ? 1.0 : 3.5; + d.default_negative = ""; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + d.cond_rows = cond_rows(); + d.rope_hw_scale = 0.5; + d.rope_text_l = 1; + d.pad_multiple = kPadMultiple; + d.pad_token = (int32_t)rad_meta_geti(meta, "pad_token_id", + rad_meta_geti(meta, "text_config.pad_token_id", 151643)); + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + rad_note(b, "rank %d/%d: FLUX.3 [klein]%s -- text encoder %d of %lld layers, DiT %zu x 3 early " + "+ %zu joint blocks (%lld heads a rank, ff %lld), %s linears", + m.gt.rank, m.gt.world, m.flow_map ? " (flow map)" : " base", kTaps[kNTaps - 1], + (long long)m.gt.n_layer, m.mode[0].size(), m.single.size(), (long long)gd.n_head, + (long long)gd.n_ff, gd.w_bf16 ? "bf16" : "block-fp8"); + return RAD_OK; +} + +/* ================================================================== step */ +static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { + const Geom& g = m.gt; + const RadGenBatch* G = batch->gen_b; + const int64_t T = batch->n_tok, E = g.n_embd; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), + brows(m.b_tx, T)); + RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T)); + const RadOperand pos = praw2(batch->rope_pos, RAD_I32, 3, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); + const RadOperand cuk = praw(G->valid_cu, RAD_I32, 2); + for (const TeLayer& L : m.te) { + RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_tx, T), RAD_W(L.w_n1), brows(m.a_th.x, T)); + L.q_h.step(c, T); + L.qkv.step(c, m.a_th, m.b_tkv, T); + RAD_ISSUE_N(c, L.op_qkr, T, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), + bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, cuk, brows(m.a_tattn.x, T)); + L.q_attn.step(c, T); + L.o.step(c, m.a_tattn, m.b_th2, T); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, T * E, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_tx, T), RAD_W(L.w_n2), brows(m.a_th.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, m.a_th, m.b_tgu, T); + L.gq.step(c, m.b_tgu, T); + L.down.step(c, m.a_tffn, m.b_th2, T); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * E, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + if (L.tap >= 0) + RAD_ISSUE_N(c, L.op_tap, T, brows(m.b_tx, T), brows(m.b_tidx, T), + bcol(m.b_taps, L.tap * E, E, T)); + } +} + +/* One picture through the encoder to its normalised tokens in `elat` (n tokens). */ +static int64_t step_encode(RadCtx* c, const Model& m, const uint16_t* px, int64_t h, int64_t w, + const int32_t* px_cu) { + RAD_ISSUE_N(c, m.op_ecu, 2, praw(px_cu + 1, RAD_I32, 1), brows(m.b_ecu, 2)); + m.enc.issue(c, h, w, brows(m.b_ecu, 2), px); + const int64_t h8 = h / 8, w8 = w / 8, n8 = h8 * w8, n = n8 / 4, zc = m.C / 4; + RAD_ISSUE_N(c, m.op_enc_mode, n8, bcol(m.enc_q.buf, 0, zc, n8), brows(m.b_emode, n8)); + RAD_ISSUE_N(c, m.op_enc_zero, n, brows(m.b_epack, n)); + RAD_ISSUE_N(c, m.op_enc_s2d, n, RAD_P_T2(rad_buf_ptr(c, m.b_emode), RAD_BF16, h8, w8 * zc), + RAD_P_T2(rad_buf_ptr(c, m.b_epack), RAD_BF16, h8 / 2, (w8 / 2) * m.C)); + RAD_ISSUE_N(c, m.op_enc_bn, n, brows(m.b_epack, n), RAD_W(m.w_bnm), RAD_W(m.w_bnv), + brows(m.b_elat, n)); + return n; +} + +/* The conditioning: the text through the language model and context_embedder, each reference + * picture through the encoder and its embedder, all into every lane's store at this branch; a + * repainted picture's tokens and its mask into the lanes. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t T = batch->n_tok, D = m.gd.n_embd; + const int64_t base = (int64_t)G->branch * cond_rows(); + const int64_t store_rows = 2 * (int64_t)kMaxLanes * cond_rows(); + const RadOperand lanes = praw(G->lane, RAD_I32, G->n_lane); + step_te(c, batch, m); + RAD_ISSUE_N(c, m.op_ctx, T, brows(m.b_taps, T), RAD_W(m.w_ctx), brows(m.b_ctx, T)); + RAD_ISSUE_N(c, m.op_store_t, T, brows(m.b_ctx, T), lanes, + brow_slice(m.b_store, base, store_rows - base, D)); + int64_t row = T; + const int64_t n_ref = G->n_px - (G->inpaint ? 1 : 0); + for (int64_t i = 0; i < G->n_px; ++i) { + const int32_t off = G->px_h[3 * i], ph = G->px_h[3 * i + 1], pw = G->px_h[3 * i + 2]; + const uint16_t* px = (const uint16_t*)G->px + (int64_t)off * 3; + const int64_t n = step_encode(c, m, px, ph, pw, G->px_cu + 2 * i); + if (i < n_ref) { + RAD_ISSUE_N(c, m.op_xc, n, brows(m.b_elat, n), RAD_W(m.w_xc), brows(m.b_eemb, n)); + RAD_ISSUE_N(c, m.op_store_r, n, brows(m.b_eemb, n), lanes, + brow_slice(m.b_store, base + row, store_rows - base - row, D)); + row += n; + } else { + const int64_t L = (int64_t)kMaxLanes * kMaxImageTokens; + RAD_ISSUE_N(c, m.op_lstore_lat, n, brows(m.b_elat, n), lanes, brows(m.b_inp, L)); + RAD_ISSUE_N(c, m.op_lstore_mask, n, praw2(G->inp_mask, RAD_F32, n, 1), lanes, + brows(m.b_mask, L)); + } + } +} + +/* A stack of parallel blocks over `R` rows of `x` from row `r0`: `acu` bounds the attention, + * `mcu` the modulation's segments, `s` the [shift | scale] rows and `gt` the gate rows. */ +static void step_blocks(RadCtx* c, const Model& m, const std::vector& stack, rad_buf x, + int64_t r0, int64_t R, const RadOperand& acu, const RadOperand& mcu, + const RadOperand& s, const RadOperand& gt, const RadOperand& pos) { + const Geom& g = m.gd; + const int64_t D = g.n_embd, qd = g.q_dim(), nD = D / RAD_FP8_BLOCK; + const bool q8 = !g.w_bf16; + const RadOperand xv = brow_slice(x, r0, R, D); + for (size_t i = 0; i < stack.size(); ++i) { + const Block& B = stack[i]; + const bool gated = i > 0; + if (q8) + RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE, + s, RAD_NONE, mcu, xv, brows(m.a_hm.q, R), brows(m.a_hm.s, R), RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n, R, gated ? brows(m.b_sum, R) : RAD_NONE, gated ? gt : RAD_NONE, + s, RAD_NONE, mcu, xv, brows(m.a_hm.x, R)); + B.qkv.step(c, m.a_hm, m.b_qkv, R); + RAD_ISSUE_N(c, B.op_qkr, R, brows(m.b_qkv, R), pos, RAD_W(B.w_qn), RAD_W(B.w_kn)); + RAD_ISSUE_N(c, B.op_attn, R, bcol(m.b_qkv, 0, qd, R), bcol(m.b_qkv, qd, qd, R), + bcol(m.b_qkv, 2 * qd, qd, R), acu, brows(m.a_attn.x, R)); + B.q_attn.step(c, R); + B.o.step(c, m.a_attn, m.b_o, R); + B.ff_in.step(c, m.a_hm, m.b_gu, R); + B.gq.step(c, m.b_gu, R); + B.ff_out.step(c, m.a_ffn, m.b_f, R); + RAD_ISSUE_N(c, B.op_sum, R, brows(m.b_o, R), brows(m.b_f, R), brows(m.b_sum, R)); + if (B.op_ar) RAD_ISSUE_N(c, B.op_ar, R * D, brows(m.b_sum, R), RAD_NONE); + } + (void)nD; +} + +static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const Geom& g = m.gd; + const int64_t N = batch->n_tok, S = batch->n_seq, NI = G->n_img, C = m.C, D = g.n_embd; + const int64_t nt = G->n_mode_h[kText], nr = G->n_mode_h[kRefs]; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1); + const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1); + const RadOperand lanes = praw(G->lane, RAD_I32, S); + const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens; + + /* ---- the timestep embeddings and every modulation */ + RAD_ISSUE_N(c, m.op_tp, S, praw(G->sigma, RAD_F32, S), brows(m.b_tp, S)); + RAD_ISSUE_N(c, m.op_one, S, bcol_at(m.b_tp, S, m.t_ch, 0, m.t_ch / 2, S)); + RAD_ISSUE_N(c, m.op_zero, S, bcol_at(m.b_tp, S, m.t_ch, m.t_ch / 2, m.t_ch / 2, S)); + RAD_ISSUE_N(c, m.op_t1, 2 * S, brows(m.b_tp, 2 * S), RAD_W(m.w_t1), brows(m.b_e1, 2 * S)); + RAD_ISSUE_N(c, m.op_ts, 2 * S, brows(m.b_e1, 2 * S), brows(m.b_e1s, 2 * S)); + RAD_ISSUE_N(c, m.op_t2, 2 * S, brows(m.b_e1s, 2 * S), RAD_W(m.w_t2), brows(m.b_temb, 2 * S)); + if (m.flow_map) { + RAD_ISSUE_N(c, m.op_tpt, S, praw(G->sigma_next, RAD_F32, S), brows(m.b_tpt, S)); + RAD_ISSUE_N(c, m.op_tt1, S, brows(m.b_tpt, S), RAD_W(m.w_tt1), brows(m.b_tt1, S)); + RAD_ISSUE_N(c, m.op_tts, S, brows(m.b_tt1, S), brows(m.b_tt1s, S)); + RAD_ISSUE_N(c, m.op_tt2, S, brows(m.b_tt1s, S), RAD_W(m.w_tt2), brows(m.b_ttgt, S)); + for (int64_t h = 0; h < 2; ++h) + RAD_ISSUE_N(c, m.op_addt, S, brow_slice(m.b_temb, h * S, S, D), brows(m.b_ttgt, S), + brow_slice(m.b_temb, h * S, S, D)); + } + RAD_ISSUE_N(c, m.op_actimg, S, brows(m.b_temb, S), brows(m.b_aimg, S)); + RAD_ISSUE_N(c, m.op_actzero, S, brow_slice(m.b_temb, S, S, D), brows(m.b_azero, S)); + RAD_ISSUE_N(c, m.op_iota3, S, brows(m.b_idx3, S)); + for (int k = 0; k < 3; ++k) { + const rad_buf act = k == kImage ? m.b_aimg : m.b_azero; + RAD_ISSUE_N(c, m.op_early[k], S, brows(act, S), RAD_W(m.w_early[k]), + brows(m.b_early[k], S)); + RAD_ISSUE_N(c, m.op_single[k], S, brows(act, S), RAD_W(m.w_single[k]), + brows(m.b_smod[k], S)); + RAD_ISSUE_N(c, m.op_ilv[k], S, brows(m.b_smod[k], S), brows(m.b_idx3, S), + brow_slice(m.b_single, k, 3 * S - k, 3 * D)); + } + RAD_ISSUE_N(c, m.op_fmod, S, brows(m.b_aimg, S), RAD_W(m.w_fmod), brows(m.b_fmod, S)); + + /* ---- the rows, mode-major in `xc`: the store's text and pictures, the image's latents */ + RAD_ISSUE_N(c, m.op_randn, NI, praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + lanes, icu, brows(m.b_state, LR)); + RAD_ISSUE_N(c, m.op_lgather, NI, brows(m.b_state, LR), lanes, icu, brows(m.b_lat, NI)); + RAD_ISSUE_N(c, m.op_xi, NI, brows(m.b_lat, NI), RAD_W(m.w_xi), + brow_slice(m.b_xc, nt + nr, NI, D)); + if (nt + nr > 0) + RAD_ISSUE_N(c, m.op_gtxt, nt + nr, brows(m.b_store, 2 * (int64_t)kMaxLanes * cond_rows()), + praw(G->mode_src, RAD_I32, nt + nr), brows(m.b_xc, nt + nr)); + + /* ---- each mode's early blocks over its own rows, the last sum gated in */ + const int64_t r0[3] = { 0, nt, nt + nr }, rn[3] = { nt, nr, NI }; + const float* mpos = G->mode_rope_f; + for (int k = 0; k < 3; ++k) { + if (rn[k] <= 0) continue; + const RadOperand mc = praw(G->mode_ccu + k * (S + 1), RAD_I32, S + 1); + const RadOperand s = bcol(m.b_early[k], 0, 2 * D, S), gt = bcol(m.b_early[k], 2 * D, D, S); + /* This mode's positions, a dense [4, rn] block at 4 r0. */ + step_blocks(c, m, m.mode[k], m.b_xc, r0[k], rn[k], mc, mc, s, gt, + praw2(mpos + 4 * r0[k], RAD_F32, 4, rn[k])); + RAD_ISSUE_N(c, m.op_g2, rn[k], brows(m.b_sum, rn[k]), gt, mc, + brow_slice(m.b_xc, r0[k], rn[k], D)); + } + /* ---- joined entry by entry, the joint blocks, the last sum gated in */ + RAD_ISSUE_N(c, m.op_join, N, brows(m.b_xc, N), praw(G->mode_rows, RAD_I32, N), + brows(m.b_h, N)); + const RadOperand mcu = praw(G->mode_cu, RAD_I32, 3 * S + 1); + const RadOperand ss = bcol(m.b_single, 0, 2 * D, 3 * S), sg = bcol(m.b_single, 2 * D, D, 3 * S); + step_blocks(c, m, m.single, m.b_h, 0, N, cu, mcu, ss, sg, praw2(G->rope_f, RAD_F32, 4, N)); + RAD_ISSUE_N(c, m.op_g3, N, brows(m.b_sum, N), sg, mcu, brows(m.b_h, N)); + + /* ---- the image rows out */ + RAD_ISSUE_N(c, m.op_gimg, NI, brows(m.b_h, N), praw(G->img_rows, RAD_I32, NI), + brows(m.b_hi, NI)); + RAD_ISSUE_N(c, m.op_nout, NI, RAD_NONE, RAD_NONE, brows(m.b_fmod, S), RAD_NONE, icu, + brows(m.b_hi, NI), brows(m.b_fz, NI)); + RAD_ISSUE_N(c, m.op_pout, NI, brows(m.b_fz, NI), RAD_W(m.w_pout), brows(m.b_v, NI)); + RAD_ISSUE_N(c, m.op_euler, NI, brows(m.b_v, NI), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->cfg, RAD_F32, S), + praw(G->pair, RAD_I32, S), lanes, praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), icu, brows(m.b_inp, LR), brows(m.b_mask, LR), + brows(m.b_state, LR), brows(m.b_prev, LR)); + (void)C; +} + +static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dbn, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C), + RAD_W(m.w_bnm), RAD_W(m.w_bnv), brows(m.b_dl, n)); + const int64_t zc = C / 4, H0 = 2 * H, W0 = 2 * W; + RAD_ISSUE_N(c, m.op_dzero, H0 * W0, brows(m.b_decin, H0 * W0)); + RAD_ISSUE_N(c, m.op_unpack, H0 * W0, RAD_P_T2(rad_buf_ptr(c, m.b_dl), RAD_BF16, H, W * C), + RAD_P_T2(rad_buf_ptr(c, m.b_decin), RAD_BF16, H0, W0 * zc)); + RAD_ISSUE_N(c, m.op_cu4, 2, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_cu4, 2)); + m.dec.issue(c, H0, W0, brows(m.b_cu4, 2), nullptr); + const int64_t npx = (int64_t)G->dec_height * G->dec_width; + RAD_ISSUE_N(c, m.op_rgb, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->gen_b) { + rad_step_fail(c, "flux3 is an image generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_COND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_DENOISE: step_denoise(c, batch, m); return; + case RAD_GEN_PASS_DECODE: step_decode(c, batch, m); return; + default: rad_step_fail(c, "flux3: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: an image at the largest size with one reference picture and its + * longest text, both branches of guidance. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kMaxText + ref_tokens_max()); + out->gen_patches = 0; + return RAD_OK; +} + +} /* namespace FLUX3_NS */ + +#ifndef RAD_ARCH_NO_EXPORTS +/* One more level of expansion so `#NS` sees the expanded namespace. */ +#define FLUX3_PROBE_X(NS) RAD_ARCH_PROBE(NS) +#define FLUX3_PLUGIN_X(NS, ...) RAD_ARCH_PLUGIN(NS, __VA_ARGS__) +FLUX3_PROBE_X(FLUX3_NS) +FLUX3_PLUGIN_X(FLUX3_NS, FLUX3_ID, "", "0.1.0", + "FLUX.3 [klein] and its base: Qwen3-VL-4B's stacked layers, a 5.6B three-mode " + "diffusion transformer over the text, up to ten reference pictures and the image, " + "and FLUX.2's VAE; bf16 or block-fp8 linears") +#endif diff --git a/arch/flux3distilled/CMakeLists.txt b/arch/flux3distilled/CMakeLists.txt new file mode 100644 index 00000000..e7c3a492 --- /dev/null +++ b/arch/flux3distilled/CMakeLists.txt @@ -0,0 +1,11 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/flux3distilled -B build -DCMAKE_PREFIX_PATH=`); see +# cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(flux3distilled LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(flux3distilled architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flux3distilled.cpp) diff --git a/arch/flux3distilled/flux3distilled.cpp b/arch/flux3distilled/flux3distilled.cpp new file mode 100644 index 00000000..418932bd --- /dev/null +++ b/arch/flux3distilled/flux3distilled.cpp @@ -0,0 +1,13 @@ +/* flux3distilled -- arch/flux3 under the architecture name of FLUX.3 [klein]'s step-distilled + * release. + * + * The released pipeline is a `Flux3DistilledModularPipeline` and its base a + * `Flux3ModularPipeline`, so rad-convert names them `flux3distilled` and `flux3`. Both hold the same + * networks; the transformer's `flow_map` flag is what tells them apart inside the plugin. A + * separate .so because a plugin answers to one architecture name (spec §2.4). Everything else is + * arch/flux3/flux3.cpp. + */ +#define FLUX3_NS flux3distilled +#define FLUX3_ID "flux3distilled" + +#include "../flux3/flux3.cpp" diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index 058635f8..6580ff94 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -867,13 +867,12 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1}); dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad}); dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)}); - /* Rescoring against the trunk's head needs logit_rerank to read its rows; RADIANCE_G3_DF_RERANK=0 - * keeps the coarse head's scores. */ + /* Candidates are rescored against the trunk's head when logit_rerank can read its rows (fp8 + * or int8) and every candidate a rank proposes is one it owns; the planes are then kRerankR + * wide and the selector reads the first sel_topk. */ { - const char* rr = std::getenv("RADIANCE_G3_DF_RERANK"); const uint32_t hd = weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16); - if (!(rr && rr[0] == '0') && (hd == RAD_F8E4M3 || hd == RAD_I8) && - (Dflash2::head_sharded(dg) || dg.world <= 1)) { + if ((hd == RAD_F8E4M3 || hd == RAD_I8) && (Dflash2::head_sharded(dg) || dg.world <= 1)) { m.df.w_lm = m.w_lm; m.df.top_w = Dflash2::kRerankR; } diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index 4b443707..1e8c394f 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -43,7 +43,6 @@ struct Model { rad_op mprev = 0, membed = 0, membed_ar = 0, men = 0, mhn = 0, meh = 0, mnorm_op = 0, mselect = 0, mback = 0, mcopy = 0, mhead = 0; bool have_mtp = false; - bool fuse_router = false, fuse_swiglu = false, gather_inverse = false; }; static std::unique_ptr models[MAX_RANKS]; static thread_local std::unique_ptr probe_model; @@ -159,7 +158,7 @@ static int buffers(RadBuilder* b, Model& m) { m.mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 }); m.mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }); m.mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { R * 8 }); - if (m.gather_inverse) m.mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { R * 8 }); + m.mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { R * 8 }); m.mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { R * 8, 2 * F }); m.mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { R * 8, F }); RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "expert_ff", F, R * 8)); @@ -242,7 +241,7 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra nm.ckpt("%s.mlp.gate_proj.weight", pre), nm.ckpt("%s.mlp.up_proj.weight", pre), nm.ckpt("%s.mlp.down_proj.weight", pre) }; - lay.dense.swiglu_quant = m.fuse_swiglu; + lay.dense.swiglu_quant = true; RAD_ARCH_TRY(lay.dense.declare(b, nm, g, l, w, s, false, draft, kArNone, false, 10)); } else { auto w = m.mw; @@ -261,8 +260,8 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra s.cfg.route_scale = 2.5; s.cfg.swiglu_limit = 10; s.cfg.shared_ungated = 1; - s.cfg.router_fuse = m.fuse_router; - s.cfg.swiglu_quant = m.fuse_swiglu; + s.cfg.router_fuse = 1; + s.cfg.swiglu_quant = 1; for (int q = 0; q < 2; ++q) { s.cfg.ff_lo[q] = g.rank * (2048 / g.world); s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world); @@ -273,19 +272,6 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b)); return RAD_OK; } -/* A decode fusion of the MoE block, on unless its variable is 0. Each is byte-identical to the - * launches it replaces, so the switch is about speed alone; 0 restores the separate launches. */ -static int fusion_switch(const char* name, bool* out) { - const char* e = std::getenv(name); - *out = true; - if (!e || !*e || !std::strcmp(e, "1")) return RAD_OK; - if (!std::strcmp(e, "0")) { - *out = false; - return RAD_OK; - } - fprintf(stderr, "radiance: %s='%s'; it is 0 or 1\n", name, e); - return RAD_E_INVAL; -} static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; @@ -326,9 +312,6 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.wire_exact = !ctx->tp_wire_lossy; g.wire_min_bytes = ctx->tp_wire_min_bytes; if (g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0) return RAD_E_INVAL; - RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_ROUTER_FUSE", &m.fuse_router)); - RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_SWIGLU_QUANT", &m.fuse_swiglu)); - RAD_ARCH_TRY(fusion_switch("RADIANCE_GLM_GATHER_INVERSE", &m.gather_inverse)); RAD_ARCH_TRY(buffers(b, m)); RadKVGroupDecl d{}; d.kind = RAD_KV_FULL; diff --git a/arch/krea2/CMakeLists.txt b/arch/krea2/CMakeLists.txt new file mode 100644 index 00000000..d59a4ae7 --- /dev/null +++ b/arch/krea2/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/krea2 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(krea2 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(krea2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/krea2.cpp) diff --git a/arch/krea2/krea2.cpp b/arch/krea2/krea2.cpp new file mode 100644 index 00000000..9e994f53 --- /dev/null +++ b/arch/krea2/krea2.cpp @@ -0,0 +1,1389 @@ +/* krea2 -- Krea 2 (Raw and Turbo): text to an RGB image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt (diffusers' Krea2Pipeline): + * + * Conditioning network: the language model of Qwen3-VL-4B over the prompt in Qwen-Image's + * template. The generator reads twelve of its hidden states per token (after layers 1, 4, ..., + * 34, before any final norm) and drops the template's fixed system turn. + * + * Denoiser: a 12.9B single-stream diffusion transformer. A small text-fusion transformer first + * turns each token's twelve tapped states into one row: two blocks attending across the twelve + * (a token's taps are twelve consecutive rows here), a learned Linear(12, 1) over them + * (`mix_rows`), two blocks attending across the tokens, then `txt_in` to the DiT's width. The + * 28 blocks run over one joint sequence, the text and then the image, every row of it modulated + * by the step's timestep: `h += gate1 attn(norm1(h)(1 + scale1) + shift1)`, `h += gate2 + * mlp(norm2(h)(1 + scale2) + shift2)`, where the six modulation rows are one projection of the + * timestep embedding shared by every block plus a learned table of each block's own + * (`table_add`), gates without tanh. Attention is grouped (48 query heads, 12 key heads) with a + * sigmoid output gate, q/k RMS norms and a three-axis rotary (text at the origin, an image token + * at (0, row, column)). Every RMS norm is zero-centred, its gain 1 + w in f32. + * + * Since the text rows change with the step, nothing is cached: the conditioning pass leaves the + * text rows `txt_in` makes in each lane's store, and every denoising step runs them with the + * image (the core's JOINT_STEP layout, abi/rad_builder.h). + * + * Decoder: Qwen-Image's VAE (Wan 2.1's, its causal 3-D convolutions on one frame), 16 latent + * channels at 8x; a latent token is 2 x 2 of its pixels (64 values), so 16 pixels a token side. + * + * Raw samples 28 steps with guidance 4.5 in the card's terms (cond + 4.5 (cond - uncond), an + * empty negative prompt) on a resolution-shifted schedule; Turbo 8 steps without guidance at a + * fixed shift. Both come from the container's scheduler configuration and pipeline name. + * + * ============================== WHAT IS QUANTISED ============================== + * + * One plugin serves bf16 and block-fp8 containers: every linear of the language model, of the + * text fusion and of the DiT's blocks is a LinearFP8 (rad_fp8.h), bf16 throughout when the first + * DiT projection is plain. txt_in, img_in, the timestep MLP and modulation, the final layer and + * the VAE stay bf16. + * + * ============================== TENSOR PARALLEL ============================== + * + * The language model, the text fusion and the DiT blocks split by heads and feed-forward width, + * an all-reduce after each output projection; everything else is replicated. The decoder splits + * by rows after its mid-block, as Qwen-Image 2.1's does (rad_vae2d.h). + */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace krea2 { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image: 2048 x 2048 pixels, 16384 latent tokens. 1024 x 1024 is the default. */ +enum { kMaxImageTokens = 16384 }; +/* The longest conditioning in rows: the pipeline's max_sequence_length. The prompt the language + * model reads is that plus the template's system turn, at most kTeRows. */ +enum { kCondRows = 512, kTeRows = kCondRows + 64 }; +/* Images in flight, and so the lanes of latent state. */ +enum { kMaxLanes = 8 }; +/* The language model's hidden states the generator reads: hidden_states[i] for these i, the + * output of layer i - 1. Layers past the last tap are not run. */ +static const int kTaps[] = { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 }; +enum { kNTaps = 12 }; + +static const char* kSysPrompt = + "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial " + "relationships of the objects and background:"; + +/* ================================================================== the model */ +struct TeLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0; + int tap = -1; /* this layer's output is tap `tap`, or none */ +}; + +/* A text-fusion block: pre-norm attention (q/k norms, no rotary, sigmoid output gate) and a + * SwiGLU, each added back to its residual `x`. */ +struct FuseBlock { + rad_buf x = 0; + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, gate{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_h2{}, q_attn{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkn = 0, op_attn = 0, op_gq = 0, op_sig = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0; +}; + +struct DitLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0, w_tab = 0; + rad_op op_tab = 0; /* the shared modulation plus this block's table, into its columns */ + LinearFP8 qkv{}, gate{}, o{}, gate_up{}, down{}; + QuantFP8 q_attn{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_n2 = 0, op_qkr = 0, op_attn = 0, op_gq = 0, op_sig = 0; + rad_op op_ar1 = 0, op_ar2 = 0; +}; + +/* Weight groups (movement units) by network. */ +enum : int { + kGrpFuse = 1000, /* the text fusion's blocks, kGrpFuse + i */ + kGrpTxtIn = 1100, + kGrpVaeDec = 1200, + kGrpDit = 2000, /* the DiT's model-level weights; its blocks kGrpDit + 1.. */ +}; + +struct Model { + Names nm{""}; + Geom gt{}, gf{}, gd{}; /* the language model's, the text fusion's and the DiT's geometry */ + bool turbo = false; + std::string te_pre; /* the language model's tensor prefix */ + + /* ---- the language model */ + rad_weight w_tok = 0; + rad_op op_embed = 0, op_iota = 0; + rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0, b_tidx = 0; + ActFP8 a_th{}, a_tattn{}, a_tffn{}; + std::vector te; + rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */ + + /* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks + * over the mixed rows `b_ft` */ + rad_buf b_fqkv = 0, b_fg = 0, b_fo = 0, b_fgu = 0, b_fcu = 0; + ActFP8 a_fh{}, a_fattn{}, a_fffn{}; + rad_op op_fcu = 0, op_mix = 0; + rad_weight w_mix = 0; + std::vector lw, rf; /* the layer-wise and the refiner blocks */ + rad_buf b_ft = 0; /* [T, n_embd] the mixed rows, the refiner's residual */ + + /* ---- txt_in: zero-centred RMSNorm, a linear, gelu_tanh, a linear, into the lanes */ + rad_weight w_txn = 0, w_tx1 = 0, b_tx1 = 0, w_tx2 = 0, b_tx2 = 0; + rad_op op_txn = 0, op_tx1 = 0, op_txg = 0, op_tx2 = 0, op_store = 0; + rad_buf b_txa = 0, b_txb = 0, b_txt = 0; + + /* ---- the timestep: embedding, MLP, the shared modulation and every block's tables */ + rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_mod = 0, b_mod = 0, w_ftab = 0; + rad_op op_temb = 0, op_t1 = 0, op_tg = 0, op_t2 = 0, op_tg2 = 0, op_mod = 0, op_ftab = 0; + rad_buf b_tproj = 0, b_te1 = 0, b_te1g = 0, b_temb = 0, b_tembg = 0, b_tmod = 0, b_mods = 0, + b_fmod = 0; + + /* ---- the DiT */ + int64_t C = 64; /* latent channels a token */ + rad_weight w_imgin = 0, b_imgin = 0; + rad_op op_randn = 0, op_lgather = 0, op_imgin = 0, op_join = 0, op_g2 = 0, op_gimg = 0; + rad_buf b_lat = 0, b_himg = 0, b_h = 0, b_qkv = 0, b_g = 0, b_ao = 0, b_gu = 0, b_hi = 0; + ActFP8 a_hm{}, a_attn{}, a_ffn{}; + std::vector dit; + LinearFP8 qkv0{}; + rad_weight w_fn = 0, w_pout = 0, b_pout = 0; + rad_op op_fn = 0, op_pout = 0, op_euler = 0; + rad_buf b_fz = 0, b_v = 0; + + /* ---- the per-image state and the conditioning store (PERSIST) */ + rad_buf b_state = 0, b_prev = 0, b_store = 0; + + /* ---- the VAE */ + Vae dec{}; + VImg dec_out{}; + rad_buf b_dl = 0, b_dl2 = 0, b_decin = 0, b_cu4 = 0, b_img = 0, b_rgbf = 0; + rad_op op_dinv = 0, op_dadd = 0, op_dzero = 0, op_unpack = 0, op_cu4 = 0, op_rgb = 0; + rad_op op_bands = 0, op_rgb_bands = 0; + std::string inv_std, mean, ones, zeros; +}; + +static Model g_model[MAX_RANKS]; + +/* A space-separated list off the container (rad-convert flattens arrays that way). */ +static std::vector meta_list(const RadModelMeta* m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(m, key, nullptr); + while (s && *s) { + char* e = nullptr; + const double x = std::strtod(s, &e); + if (e == s) { ++s; continue; } + v.push_back(x); + s = e; + } + return v; +} + +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A bf16 linear with a bias, read whole on every rank. */ +static rad_op dense_bias(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t N, + int64_t K, int64_t rows, rad_buf in, rad_buf out, rad_weight* w, + rad_weight* bias, int access, int group) { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), RAD_BF16, { N, K }, access, + group); + *bias = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { N }, access, group); + if (!*w || !*bias) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w, *bias)), + { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, + rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op all_reduce(RadBuilder* b, const Geom& g, rad_buf x, int64_t rows) { + if (g.world <= 1) return 0; + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, rows * g.n_embd), + RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); +} + +/* A zero-centred RMSNorm (gain 1 + w in f32, the norm and gain rounded once): rmsnorm's + * `wadd`. */ +static rad_op zc_norm(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, + rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16"), RAD_F64("wadd", 1.0)), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +/* The attention's sigmoid output gate: `gate_quant_fp8` (gate, multiply and the out projection's + * quantiser in one pass) over fp8 linears, or `sigmoid` then `mul` over bf16 ones and wherever no + * loaded library declares the fused op (the out projection's quantiser then runs on its own). + * Rows are (token, head) pairs of `head_dim` columns. Returns the gate op; `sig` is the pair's + * sigmoid, written into `g` itself. */ +static rad_op out_gate(RadBuilder* b, const Geom& g, int64_t rows, int64_t width, rad_buf gate, + const ActFP8& attn, rad_op* sig) { + const int64_t hd = g.head_dim; + if (g.w_bf16 || !rad_op_declared(b, "gate_quant_fp8")) { + *sig = rw(b, RAD_OP(b, "sigmoid", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { gate }, { gate }); + return rw(b, RAD_OP(b, "mul", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { attn.x, gate }, { attn.x }); + } + *sig = 0; + return rw(b, RAD_OP(b, "gate_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows * (width / hd)), RAD_INT("n", hd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16"), + RAD_STR("act", "sigmoid")), + RAD_NOWEIGHTS), + { gate, attn.x }, { attn.cq(), attn.cs(), attn.x }); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta) { + const char* arch = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strncmp(arch, "Krea2", 5) != 0) { + fprintf(stderr, "radiance: krea2: the container's pipeline is '%s', not Krea 2's\n", arch); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "transformer.num_text_layers", kNTaps) != kNTaps || + rad_meta_geti(meta, "vae.z_dim", 16) != 16 || + rad_meta_geti(meta, "transformer.in_channels", 64) != 64) { + fprintf(stderr, "radiance: krea2: the DiT must read twelve tapped layers and 64-value " + "tokens of a 16-channel VAE\n"); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== declare */ +static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = kTeRows; /* the prompt with its system turn */ + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const char* pre = m.te_pre.c_str(); + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd }); + m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd, T)); + m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim }); + m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T)); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T)); + m.b_taps = decl_b(b, nm.f("te.taps"), RAD_BF16, { (int64_t)kTeRows * kNTaps, g.n_embd }); + m.b_tidx = decl_b(b, nm.f("te.tap_idx"), RAD_I32, { T }); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + /* Row 12 t of the taps for token t; a tap i is scattered at row offset i. */ + m.op_iota = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("start", 0), + RAD_INT("step", kNTaps)), + RAD_NOWEIGHTS), + {}, { m.b_tidx }); + + const std::vector sec = meta_list(meta, "text_config.rope_scaling.mrope_section"); + char sections[48]; + if (sec.size() == 3) + std::snprintf(sections, sizeof sections, "%d %d %d", (int)sec[0], (int)sec[1], (int)sec[2]); + else + std::snprintf(sections, sizeof sections, "24 20 20"); + + /* Layers up to the last tap only. */ + const int n_run = kTaps[kNTaps - 1]; + if (g.n_layer < n_run) { + fprintf(stderr, "radiance: krea2: the text encoder has %lld layers; its last tap is after " + "layer %d\n", (long long)g.n_layer, n_run); + return RAD_E_INVAL; + } + m.te.resize((size_t)n_run); + for (int l = 0; l < n_run; ++l) { + TeLayer& L = m.te[(size_t)l]; + for (int t = 0; t < kNTaps; ++t) if (kTaps[t] == l + 1) L.tap = t; + const char* lp = nm.f("%s.layers.%d", pre, l); + L.w_n1 = wcopy(b, nm.f("te.blk.%d.attn_norm.weight", l), + nm.ckpt("%s.input_layernorm.weight", lp), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, l); + L.w_n2 = wcopy(b, nm.f("te.blk.%d.ffn_norm.weight", l), + nm.ckpt("%s.post_attention_layernorm.weight", lp), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, l); + L.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", l), nm.ckpt("%s.self_attn.q_norm.weight", lp), + RAD_BF16, { g.head_dim }, RAD_ACCESS_PER_TOKEN, l); + L.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", l), nm.ckpt("%s.self_attn.k_norm.weight", lp), + RAD_BF16, { g.head_dim }, RAD_ACCESS_PER_TOKEN, l); + if (!L.w_n1 || !L.w_n2 || !L.w_qn || !L.w_kn) return RAD_E_INVAL; + L.op_n1 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n1)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("te.blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, + g.n_embd, RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.self_attn.q_proj.weight", lp), + nm.ckpt("%s.self_attn.k_proj.weight", lp), + nm.ckpt("%s.self_attn.v_proj.weight", lp) }, + m.a_th, m.b_tkv, T, { q_dim, kv_dim, kv_dim })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_STR("mode", "imrope"), + RAD_INT("rotary_dim", g.head_dim), + RAD_STR("sections", nm.f("%s", sections))), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + { m.b_tkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_tattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("te.blk.%d.attn_output", l), g.n_embd, q_dim, + RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.self_attn.o_proj.weight", lp) }, m.a_tattn, m.b_th2, + T)); + L.op_ar1 = all_reduce(b, g, m.b_th2, T); + L.op_add1 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + L.op_n2 = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_n2)), + { m.b_tx }, { m.a_th.x }); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("te.blk.%d.ffn_gate_up", l), 2 * g.n_ff, + g.n_embd, RAD_SHARD_ROW, grp_layer(l), + { nm.ckpt("%s.mlp.gate_proj.weight", lp), + nm.ckpt("%s.mlp.up_proj.weight", lp) }, + m.a_th, m.b_tgu, T, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_tgu, m.a_tffn, g.n_ff, "silu", T, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("te.blk.%d.ffn_down", l), g.n_embd, g.n_ff, + RAD_SHARD_COL, grp_layer(l), + { nm.ckpt("%s.mlp.down_proj.weight", lp) }, m.a_tffn, m.b_th2, + T)); + L.op_ar2 = all_reduce(b, g, m.b_th2, T); + L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + if (L.tap >= 0) + L.op_tap = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps }); + if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 || + (L.tap >= 0 && !L.op_tap)) + return RAD_E_INVAL; + } + return m.op_embed && m.op_iota ? RAD_OK : RAD_E_INVAL; +} + +/* One text-fusion block over at most `rows` rows of the residual `x`. */ +static int declare_fuse_block(RadBuilder* b, Model& m, FuseBlock& F, const char* pre, int grp, + int64_t rows, rad_buf x) { + F.x = x; + Geom& g = m.gf; + Names& nm = m.nm; + const int64_t D = g.n_embd, qd = g.q_dim(), hd = g.head_dim; + const double eps = g.eps; + const char* dn = nm.f("fuse.%d", grp - kGrpFuse); + F.w_n1 = wcopy(b, nm.f("%s.norm1.weight", dn), nm.ckpt("%s.norm1.weight", pre), RAD_F32, { D }, + RAD_ACCESS_PER_REQUEST, grp); + F.w_n2 = wcopy(b, nm.f("%s.norm2.weight", dn), nm.ckpt("%s.norm2.weight", pre), RAD_F32, { D }, + RAD_ACCESS_PER_REQUEST, grp); + F.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.attn.norm_q.weight", pre), RAD_F32, + { hd }, RAD_ACCESS_PER_REQUEST, grp); + F.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), RAD_F32, + { hd }, RAD_ACCESS_PER_REQUEST, grp); + if (!F.w_n1 || !F.w_n2 || !F.w_qn || !F.w_kn) return RAD_E_INVAL; + F.op_n1 = zc_norm(b, rows, D, eps, F.w_n1, F.x, m.a_fh.x); + RAD_ARCH_TRY(F.q_h.declare(b, g, m.a_fh, D)); + RAD_ARCH_TRY(F.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_ROW, + grp_layer(grp), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) }, + m.a_fh, m.b_fqkv, rows, { qd, qd, qd })); + RAD_ARCH_TRY(F.gate.declare(b, nm, g, nm.f("%s.attn_gate", dn), qd, D, RAD_SHARD_ROW, + grp_layer(grp), { nm.ckpt("%s.attn.to_gate.weight", pre) }, m.a_fh, + m.b_fg, rows)); + /* q/k norms alone (no rotary in the fusion), zero-centred. */ + F.op_qkn = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", 10000.0), RAD_F64("eps", eps), + RAD_INT("rotary_dim", 0), RAD_F64("wadd", 1.0)), + RAD_WEIGHTS(F.w_qn, F.w_kn)), + { m.b_fqkv }, { m.b_fqkv }); + F.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_fqkv }, { m.a_fattn.x }); + F.op_gq = out_gate(b, g, rows, qd, m.b_fg, m.a_fattn, &F.op_sig); + if (F.op_sig) RAD_ARCH_TRY(F.q_attn.declare(b, g, m.a_fattn, qd)); + RAD_ARCH_TRY(F.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) }, + m.a_fattn, m.b_fo, rows)); + F.op_ar1 = all_reduce(b, g, m.b_fo, rows); + F.op_add1 = add_op(b, rows, D, F.x, m.b_fo, F.x); + F.op_n2 = zc_norm(b, rows, D, eps, F.w_n2, F.x, m.a_fh.x); + RAD_ARCH_TRY(F.q_h2.declare(b, g, m.a_fh, D)); + RAD_ARCH_TRY(F.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D, + RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.ff.gate.weight", pre), + nm.ckpt("%s.ff.up.weight", pre) }, + m.a_fh, m.b_fgu, rows, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(F.gq.declare(b, g, m.b_fgu, m.a_fffn, g.n_ff, "silu", rows, true)); + RAD_ARCH_TRY(F.down.declare(b, nm, g, nm.f("%s.ffn_down", dn), D, g.n_ff, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.ff.down.weight", pre) }, m.a_fffn, + m.b_fo, rows)); + F.op_ar2 = all_reduce(b, g, m.b_fo, rows); + F.op_add2 = add_op(b, rows, D, F.x, m.b_fo, F.x); + if (!F.op_n1 || !F.op_qkn || !F.op_attn || !F.op_gq || !F.op_add1 || !F.op_n2 || !F.op_add2) + return RAD_E_INVAL; + return RAD_OK; +} + +static int declare_fusion(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gf; + Names& nm = m.nm; + const int64_t D = g.n_embd, qd = g.q_dim(); + const int64_t RL = (int64_t)kCondRows * kNTaps; /* the layer-wise blocks' rows */ + m.a_fh.x = decl_b(b, nm.f("fuse.h"), RAD_BF16, { RL, D }); + RAD_ARCH_TRY(m.a_fh.declare_qs(b, nm, g, "fuse.h", D, RL)); + m.b_fqkv = decl_b(b, nm.f("fuse.qkv"), RAD_BF16, { RL, 3 * qd }); + m.b_fg = decl_b(b, nm.f("fuse.gate"), RAD_BF16, { RL, qd }); + m.a_fattn.x = decl_b(b, nm.f("fuse.attn"), RAD_BF16, { RL, qd }); + RAD_ARCH_TRY(m.a_fattn.declare_qs(b, nm, g, "fuse.attn", qd, RL)); + m.b_fo = decl_b(b, nm.f("fuse.o"), RAD_BF16, { RL, D }); + m.b_fgu = decl_b(b, nm.f("fuse.gate_up"), RAD_BF16, { RL, 2 * g.n_ff }); + m.a_fffn.x = decl_b(b, nm.f("fuse.ffn"), RAD_BF16, { RL, g.n_ff }); + RAD_ARCH_TRY(m.a_fffn.declare_qs(b, nm, g, "fuse.ffn", g.n_ff, RL)); + m.b_fcu = decl_b(b, nm.f("fuse.cu"), RAD_I32, { kCondRows + 1 }); + m.b_ft = decl_b(b, nm.f("fuse.out"), RAD_BF16, { kCondRows, D }); + + /* The layer-wise blocks attend within each token's twelve rows: cu 0, 12, 24, ... */ + m.op_fcu = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kCondRows + 1), RAD_INT("start", 0), + RAD_INT("step", kNTaps)), + RAD_NOWEIGHTS), + {}, { m.b_fcu }); + const int nlw = (int)rad_meta_geti(meta, "transformer.num_layerwise_text_blocks", 2); + const int nrf = (int)rad_meta_geti(meta, "transformer.num_refiner_text_blocks", 2); + m.lw.resize((size_t)nlw); + m.rf.resize((size_t)nrf); + for (int i = 0; i < nlw; ++i) { + RAD_ARCH_TRY(declare_fuse_block(b, m, m.lw[(size_t)i], + nm.f("transformer.text_fusion.layerwise_blocks.%d", i), + kGrpFuse + i, RL, m.b_taps)); + /* Their attention reads the twelve-row bounds. */ + RAD_ARCH_TRY(rad_op_reads(b, m.lw[(size_t)i].op_attn, &m.b_fcu, 1)); + } + RAD_ARCH_TRY(map_copy(b, nm.f("fuse.mix.weight"), + nm.ckpt("transformer.text_fusion.projector.weight"))); + /* The release stores the projector, embedders, modulations and output layer f32, which are + * served bf16 as diffusers runs them: a recipe casts them. */ + if (weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16) != RAD_BF16) { + fprintf(stderr, "radiance: krea2: 'fuse.mix.weight' is stored %s; convert with " + "data/recipes/krea-2-bf16.recipe or krea-2-fp8.recipe, which cast the " + "release's f32 tensors\n", + rad_dtype_name(weight_codes_dtype(b, "fuse.mix.weight", RAD_BF16))); + return RAD_E_UNSUPPORTED; + } + m.w_mix = decl_w(b, nm.f("fuse.mix.weight"), RAD_BF16, { 1, kNTaps }, RAD_ACCESS_PER_REQUEST, + RAD_SHARD_NONE, grp_layer(kGrpFuse)); + m.op_mix = rw(b, RAD_OP(b, "mix_rows", + RAD_PARAMS(RAD_RANGE("M", 1, kCondRows), RAD_INT("n", D), + RAD_INT("k", kNTaps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_mix)), + { m.b_taps }, { m.b_ft }); + for (int i = 0; i < nrf; ++i) + RAD_ARCH_TRY(declare_fuse_block(b, m, m.rf[(size_t)i], + nm.f("transformer.text_fusion.refiner_blocks.%d", i), + kGrpFuse + nlw + i, kCondRows, m.b_ft)); + if (!m.op_fcu || !m.w_mix || !m.op_mix) return RAD_E_INVAL; + + /* ---- txt_in, into each lane's conditioning store */ + const int64_t Dd = m.gd.n_embd; + m.b_txa = decl_b(b, nm.f("txt.a"), RAD_BF16, { kCondRows, D }); + m.b_txb = decl_b(b, nm.f("txt.b"), RAD_BF16, { kCondRows, Dd }); + m.b_txt = decl_b(b, nm.f("txt.out"), RAD_BF16, { kCondRows, Dd }); + m.w_txn = wcopy(b, nm.f("txt.norm.weight"), nm.ckpt("transformer.txt_in.norm.weight"), RAD_F32, + { D }, RAD_ACCESS_PER_REQUEST, kGrpTxtIn); + m.op_txn = zc_norm(b, kCondRows, D, g.eps, m.w_txn, m.b_ft, m.b_txa); + m.op_tx1 = dense_bias(b, nm, "txt.l1", "transformer.txt_in.linear_1", Dd, D, kCondRows, m.b_txa, + m.b_txb, &m.w_tx1, &m.b_tx1, RAD_ACCESS_PER_REQUEST, kGrpTxtIn); + m.op_txg = unary(b, "gelu_tanh", kCondRows, Dd, m.b_txb, m.b_txb); + m.op_tx2 = dense_bias(b, nm, "txt.l2", "transformer.txt_in.linear_2", Dd, Dd, kCondRows, + m.b_txb, m.b_txt, &m.w_tx2, &m.b_tx2, RAD_ACCESS_PER_REQUEST, kGrpTxtIn); + /* Lane l's branch b at rows (2 l + b) kCondRows: the store's `stride` is two branches. */ + m.op_store = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, kCondRows), RAD_INT("n", Dd), + RAD_INT("stride", 2 * (int64_t)kCondRows), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_txt, m.b_store }, { m.b_store }); + return m.w_txn && m.op_txn && m.op_tx1 && m.op_txg && m.op_tx2 && m.op_store ? RAD_OK + : RAD_E_INVAL; +} + +/* The DiT's six modulation rows, reordered to rms_mod's [shift | scale] pairs: the checkpoint + * holds (prescale, preshift, pregate, postscale, postshift, postgate). */ +static int map_mod_rows(RadBuilder* b, const char* declared, const char* src, int64_t D) { + return map_rows(b, declared, { { src, (int)D, D }, { src, 0, D }, { src, (int)(2 * D), D }, + { src, (int)(4 * D), D }, { src, (int)(3 * D), D }, + { src, (int)(5 * D), D } }); +} + +static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const int64_t T = g.max_tok, S = g.max_seqs; + const int64_t D = g.n_embd, hd = g.head_dim, qd = g.q_dim(), kvd = g.kv_dim(); + const int64_t C = m.C, L = g.n_layer; + const double eps = g.eps; + const int gx = kGrpDit; + const int64_t NI = std::min(T, 2 * (int64_t)kMaxImageTokens); /* image rows a pass */ + + /* ---- the timestep: [cos | sin] of 1000 bf16(t) over 256, linear, gelu_tanh, linear (temb); + * the shared modulation from gelu_tanh(temb), then each block's table added (table_add), and + * the final layer's from temb itself. */ + const int64_t te = rad_meta_geti(meta, "transformer.timestep_embed_dim", 256); + m.b_tproj = decl_b(b, nm.f("dit.tproj"), RAD_BF16, { S, te }); + m.b_te1 = decl_b(b, nm.f("dit.te1"), RAD_BF16, { S, D }); + m.b_te1g = decl_b(b, nm.f("dit.te1g"), RAD_BF16, { S, D }); + m.b_temb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { S, D }); + m.b_tembg = decl_b(b, nm.f("dit.tembg"), RAD_BF16, { S, D }); + m.b_tmod = decl_b(b, nm.f("dit.tmod"), RAD_BF16, { S, 6 * D }); + m.b_mods = decl_b(b, nm.f("dit.mods"), RAD_BF16, { S, L * 6 * D }); + m.b_fmod = decl_b(b, nm.f("dit.fmod"), RAD_BF16, { S, 2 * D }); + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", te), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_INT("round", 2), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_t1 = dense_bias(b, nm, "dit.t1", "transformer.time_embed.linear_1", D, te, S, m.b_tproj, + m.b_te1, &m.w_t1, &m.b_t1, RAD_ACCESS_PER_TOKEN, gx); + m.op_tg = unary(b, "gelu_tanh", S, D, m.b_te1, m.b_te1g); + m.op_t2 = dense_bias(b, nm, "dit.t2", "transformer.time_embed.linear_2", D, D, S, m.b_te1g, + m.b_temb, &m.w_t2, &m.b_t2, RAD_ACCESS_PER_TOKEN, gx); + m.op_tg2 = unary(b, "gelu_tanh", S, D, m.b_temb, m.b_tembg); + RAD_ARCH_TRY(map_mod_rows(b, nm.f("dit.mod.weight"), nm.ckpt("transformer.time_mod_proj.weight"), + D)); + m.w_mod = decl_w(b, nm.f("dit.mod.weight"), RAD_BF16, { 6 * D, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(gx)); + RAD_ARCH_TRY(map_mod_rows(b, nm.f("dit.mod.bias"), nm.ckpt("transformer.time_mod_proj.bias"), + D)); + m.b_mod = decl_w(b, nm.f("dit.mod.bias"), RAD_BF16, { 6 * D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(gx)); + if (!m.w_mod || !m.b_mod) return RAD_E_INVAL; + m.op_mod = rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("N", 6 * D), RAD_INT("K", D), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_mod, m.b_mod)), + { m.b_tembg }, { m.b_tmod }); + /* Each block's table, its six rows reordered as the projection's, added to the shared + * modulation into the block's 6D columns of `mods` (declared with the blocks). */ + /* The final layer's (scale, shift), reordered to (shift, scale). */ + { + const char* src = nm.ckpt("transformer.final_layer.scale_shift_table"); + RAD_ARCH_TRY(map_rows(b, nm.f("dit.final.table"), { { src, 1, 1 }, { src, 0, 1 } })); + m.w_ftab = decl_w(b, nm.f("dit.final.table"), RAD_BF16, { 2, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(gx)); + } + m.op_ftab = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), RAD_INT("L", 2), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_ftab)), + { m.b_temb }, { m.b_fmod }); + if (!m.op_temb || !m.op_t1 || !m.op_tg || !m.op_t2 || !m.op_tg2 || !m.op_mod || !m.w_ftab || + !m.op_ftab) + return RAD_E_INVAL; + + /* ---- the input rows: the image's latents a lane at a time through img_in, joined with the + * lanes' text rows into the pass's [text | image] entries */ + m.b_lat = decl_b(b, nm.f("dit.lat"), RAD_BF16, { NI, C }); + m.b_himg = decl_b(b, nm.f("dit.himg"), RAD_BF16, { NI, D }); + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + m.op_randn = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state }); + m.op_lgather = rw(b, RAD_OP(b, "lane_gather", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_lat }); + m.op_imgin = dense_bias(b, nm, "dit.img_in", "transformer.img_in", D, C, NI, m.b_lat, m.b_himg, + &m.w_imgin, &m.b_imgin, RAD_ACCESS_PER_TOKEN, gx); + m.op_join = rw(b, RAD_OP(b, "gather_rows2", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_store, m.b_himg }, { m.b_h }); + if (!m.op_randn || !m.op_lgather || !m.op_imgin || !m.op_join) return RAD_E_INVAL; + + /* ---- the blocks */ + m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D }); + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, qd + 2 * kvd }); + m.b_g = decl_b(b, nm.f("dit.gate"), RAD_BF16, { T, qd }); + m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd }); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd)); + m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D }); + m.b_gu = decl_b(b, nm.f("dit.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff)); + + const std::vector ax = meta_list(meta, "transformer.axes_dims_rope"); + const int64_t a0 = ax.size() == 3 ? (int64_t)ax[0] : 32, a1 = ax.size() == 3 ? (int64_t)ax[1] : 48, + a2 = ax.size() == 3 ? (int64_t)ax[2] : 48; + if (a0 + a1 + a2 != hd) { + fprintf(stderr, "radiance: krea2: transformer.axes_dims_rope must sum to the head\n"); + return RAD_E_INVAL; + } + const char* sections = nm.f("%lld %lld %lld", (long long)a0 / 2, (long long)a1 / 2, + (long long)a2 / 2); + const double theta = rad_meta_getf(meta, "transformer.rope_theta", 1000.0); + + /* The modulated norm, gated by the branch before it when `gated`, into the next linear's + * input (codes for fp8, the bf16 plane for bf16). */ + auto mod_norm = [&](rad_weight w, bool gated) { + const bool q = !g.w_bf16; + rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)), + RAD_WEIGHTS(w)) + : RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)), + RAD_WEIGHTS(w)); + if (!op) return op; + rad_buf rd[3] = { m.b_mods, m.b_h, m.b_ao }; + rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h }; + rad_buf wb[2] = { m.a_hm.x, m.b_h }; + rad_op_reads(b, op, rd, gated ? 3 : 2); + if (q) rad_op_writes(b, op, wq, 3); + else rad_op_writes(b, op, wb, 2); + return op; + }; + + m.dit.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + DitLayer& B = m.dit[(size_t)l]; + const int li = (int)l; + const int grp = kGrpDit + 1 + li; + const char* pre = nm.ckpt("transformer.transformer_blocks.%d", li); + const char* dn = nm.f("dit.blk.%d", li); + B.w_n1 = wcopy(b, nm.f("%s.norm1.weight", dn), nm.ckpt("%s.norm1.weight", pre), RAD_BF16, + { D }, RAD_ACCESS_PER_TOKEN, grp); + B.w_n2 = wcopy(b, nm.f("%s.norm2.weight", dn), nm.ckpt("%s.norm2.weight", pre), RAD_BF16, + { D }, RAD_ACCESS_PER_TOKEN, grp); + B.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.attn.norm_q.weight", pre), + RAD_F32, { hd }, RAD_ACCESS_PER_TOKEN, grp); + B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.attn.norm_k.weight", pre), + RAD_F32, { hd }, RAD_ACCESS_PER_TOKEN, grp); + if (!B.w_n1 || !B.w_n2 || !B.w_qn || !B.w_kn) return RAD_E_INVAL; + { + const char* src = nm.ckpt("%s.scale_shift_table", pre); + RAD_ARCH_TRY(map_rows(b, nm.f("%s.table", dn), + { { src, 1, 1 }, { src, 0, 1 }, { src, 2, 1 }, { src, 4, 1 }, + { src, 3, 1 }, { src, 5, 1 } })); + B.w_tab = decl_w(b, nm.f("%s.table", dn), RAD_BF16, { 6, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(grp)); + B.op_tab = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", 6 * D), + RAD_INT("L", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.w_tab)), + { m.b_tmod, m.b_mods }, { m.b_mods }); + if (!B.w_tab || !B.op_tab) return RAD_E_INVAL; + } + B.op_n1 = mod_norm(B.w_n1, l > 0); + if (l == 0) B.qkv = m.qkv0; + RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), qd + 2 * kvd, D, + RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.attn.to_q.weight", pre), + nm.ckpt("%s.attn.to_k.weight", pre), + nm.ckpt("%s.attn.to_v.weight", pre) }, + m.a_hm, m.b_qkv, 0, { qd, kvd, kvd })); + RAD_ARCH_TRY(B.gate.declare(b, nm, g, nm.f("%s.attn_gate", dn), qd, D, RAD_SHARD_ROW, + grp_layer(grp), { nm.ckpt("%s.attn.to_gate.weight", pre) }, + m.a_hm, m.b_g)); + B.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "gptj_blocks"), + RAD_INT("rotary_dim", hd), RAD_STR("sections", sections), + RAD_F64("wadd", 1.0)), + RAD_WEIGHTS(B.w_qn, B.w_kn)), + { m.b_qkv }, { m.b_qkv }); + B.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.a_attn.x }); + B.op_gq = out_gate(b, g, T, qd, m.b_g, m.a_attn, &B.op_sig); + if (B.op_sig) RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.attn.to_out.0.weight", pre) }, + m.a_attn, m.b_ao)); + B.op_ar1 = all_reduce(b, g, m.b_ao, T); + B.op_n2 = mod_norm(B.w_n2, true); + RAD_ARCH_TRY(B.gate_up.declare(b, nm, g, nm.f("%s.ffn_gate_up", dn), 2 * g.n_ff, D, + RAD_SHARD_ROW, grp_layer(grp), + { nm.ckpt("%s.ff.gate.weight", pre), + nm.ckpt("%s.ff.up.weight", pre) }, + m.a_hm, m.b_gu, 0, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(B.gq.declare(b, g, m.b_gu, m.a_ffn, g.n_ff, "silu", 0, true)); + RAD_ARCH_TRY(B.down.declare(b, nm, g, nm.f("%s.ffn_down", dn), D, g.n_ff, RAD_SHARD_COL, + grp_layer(grp), { nm.ckpt("%s.ff.down.weight", pre) }, m.a_ffn, + m.b_ao)); + B.op_ar2 = all_reduce(b, g, m.b_ao, T); + if (!B.op_n1 || !B.op_qkr || !B.op_attn || !B.op_gq || !B.op_n2) return RAD_E_INVAL; + } + + /* ---- the output: the last block's feed-forward gated in, the image's rows picked out, the + * final adaptive norm and proj_out, and the sampler's step */ + m.b_hi = decl_b(b, nm.f("dit.h_img"), RAD_BF16, { NI, D }); + m.b_fz = decl_b(b, nm.f("dit.fz"), RAD_BF16, { NI, D }); + m.b_v = decl_b(b, nm.f("dit.v"), RAD_BF16, { NI, C }); + m.op_g2 = rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_ao, m.b_mods, m.b_h }, { m.b_h }); + m.op_gimg = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_h }, { m.b_hi }); + m.w_fn = wcopy(b, nm.f("dit.final.norm.weight"), nm.ckpt("transformer.final_layer.norm.weight"), + RAD_BF16, { D }, RAD_ACCESS_PER_TOKEN, gx); + m.op_fn = rw(b, RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("gated", 0), RAD_STR("dtype", "bf16"), + RAD_F64("wadd", 1.0), RAD_INT("norm_once", 1)), + RAD_WEIGHTS(m.w_fn)), + { m.b_fmod, m.b_hi }, { m.b_hi, m.b_fz }); + m.op_pout = dense_bias(b, nm, "dit.proj_out", "transformer.final_layer.linear", C, D, NI, + m.b_fz, m.b_v, &m.w_pout, &m.b_pout, RAD_ACCESS_PER_TOKEN, gx); + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_v, m.b_state, m.b_prev }, { m.b_state, m.b_prev }); + return m.op_g2 && m.op_gimg && m.w_fn && m.op_fn && m.op_pout && m.op_euler ? RAD_OK + : RAD_E_INVAL; +} + +/* The decoder: the latent denormalised, the 2 x 2 tokens unpacked to the VAE's 16 channels, then + * Wan 2.1's decoder on one frame. Its resblock, conv_in, conv_out and post_quant_conv convolutions + * are causal 3-D ones read at their last tap; the attention's and the upsamplers' are 2-D. */ +static int declare_decoder(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Vae& v = m.dec; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = kGrpVaeDec; + v.base_px = (int64_t)kMaxImageTokens * 4; + v.form = VAE_CONV_CAUSAL; + const int64_t base = rad_meta_geti(meta, "vae.base_dim", 96); + const int64_t zd = rad_meta_geti(meta, "vae.z_dim", 16); + const int64_t nres = rad_meta_geti(meta, "vae.num_res_blocks", 2); + std::vector mult = meta_list(meta, "vae.dim_mult"); + std::vector td = meta_list(meta, "vae.temperal_downsample"); + if (mult.empty()) mult = { 1, 2, 4, 4 }; + if (td.empty()) td = { 0, 1, 1 }; + const std::vector mean = meta_list(meta, "vae.latents_mean"); + const std::vector sd = meta_list(meta, "vae.latents_std"); + if ((int64_t)mean.size() != zd || (int64_t)sd.size() != zd || mult.size() != 4) { + fprintf(stderr, "radiance: krea2: the VAE's latents_mean / latents_std / dim_mult are not " + "Wan 2.1's\n"); + return RAD_E_INVAL; + } + /* The packed channel c 4 + k reads latent channel c: the statistics repeated four times. The + * reference divides by bf16(1 / std) and adds the mean, each rounded. */ + for (int64_t k = 0; k < 4 * zd; ++k) { + char t[64]; + std::snprintf(t, sizeof t, "%s%.9g", k ? " " : "", 1.0 / sd[(size_t)(k / 4)]); + m.inv_std += t; + std::snprintf(t, sizeof t, "%s%.9g", k ? " " : "", mean[(size_t)(k / 4)]); + m.mean += t; + m.ones += k ? " 1" : "1"; + m.zeros += k ? " 0" : "0"; + } + const int64_t NT = kMaxImageTokens; + m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zd }); + m.b_dl2 = decl_b(b, nm.f("vdec.lat2"), RAD_BF16, { NT, 4 * zd }); + m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zd }); + m.b_cu4 = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 }); + m.op_dinv = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", 4 * zd), + RAD_STR("mul", m.inv_std.c_str()), + RAD_STR("add", m.zeros.c_str()), RAD_STR("mode", "inv"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state, m.b_prev }, { m.b_dl }); + m.op_dadd = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", 4 * zd), + RAD_STR("mul", m.ones.c_str()), + RAD_STR("add", m.mean.c_str()), RAD_STR("mode", "fma"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dl }, { m.b_dl2 }); + m.op_dzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("n", zd), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_decin }); + m.op_unpack = rw(b, RAD_OP(b, "d2s_add", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("cin", 4 * zd), + RAD_INT("cout", zd), RAD_INT("ft", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dl2, m.b_decin }, { m.b_decin }); + m.op_cu4 = rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)), + RAD_NOWEIGHTS), + {}, { m.b_cu4 }); + if (!m.op_dinv || !m.op_dadd || !m.op_dzero || !m.op_unpack || !m.op_cu4) return RAD_E_INVAL; + + /* dims = base * [mult[-1]] + mult reversed; up block i reads dims[i] (halved after an + * upsampler) and writes dims[i + 1]. */ + std::vector dims{ base * (int64_t)mult.back() }; + for (int i = 3; i >= 0; --i) dims.push_back(base * (int64_t)mult[(size_t)i]); + VImg x{ m.b_decin, zd, 0 }; + x = v.conv(x, zd, 1, 1, 1, "same", "vae.post_quant_conv"); + x = v.conv(x, dims[0], 3, 1, 1, "same", "vae.decoder.conv_in"); + x = v.resblock(x, dims[0], "vae.decoder.mid_block.resnets.0"); + v.form = VAE_CONV_2D; + x = v.attention(x, "vae.decoder.mid_block.attentions.0"); + v.form = VAE_CONV_CAUSAL; + x = v.resblock(x, dims[0], "vae.decoder.mid_block.resnets.1"); + v.band_from = (int)v.ops.size(); + v.whole.push_back(m.b_decin); + for (const VOp& o : v.ops) v.whole.push_back(o.y.buf); + for (int i = 0; i < 4; ++i) { + for (int r = 0; r < nres + 1; ++r) + x = v.resblock(x, dims[(size_t)i + 1], nm.f("vae.decoder.up_blocks.%d.resnets.%d", i, r)); + if (i != 3) { + v.form = VAE_CONV_2D; + x = v.conv(x, dims[(size_t)i + 1] / 2, 3, 1, 2, "same", + nm.f("vae.decoder.up_blocks.%d.upsamplers.0.resample.1", i)); + v.form = VAE_CONV_CAUSAL; + } + } + x = v.norm(x, true, "vae.decoder.norm_out", 4); + m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out"); + if (!m.dec_out.buf) return RAD_E_INVAL; + RAD_ARCH_TRY(v.attn_reads(m.b_cu4)); + const int64_t px = (int64_t)kMaxImageTokens * 256; + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST); + m.op_rgb = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + if (!m.op_rgb) return RAD_E_INVAL; + v.halo = v.band_halo(); + if (v.halo <= 0) { + fprintf(stderr, "radiance: krea2: the decoder after its mid-block is not row-local\n"); + return RAD_E_INVAL; + } + /* More than one rank: each runs a band of the tail and the bands are gathered (qwenimage21's + * scheme: a band is ceil(H / world) latent rows plus a halo each side). Level 0 is the + * unpacked latent, two rows a token row, eight pixels a latent row. */ + const int world = m.gt.world; + if (world > 1) { + const int64_t H0 = 4 * (int64_t)kMaxImageTokens; + const int64_t bpx = (H0 / world + H0 / (2 * v.halo) + 1) * 64; + m.b_rgbf = decl_b(b, nm.f("vdec.bands"), RAD_BF16, { world * bpx, 3 }); + m.op_bands = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", world), + RAD_RANGE("numel", 1, bpx * 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_rgbf }); + m.op_rgb_bands = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_rgbf }, { m.b_img }); + if (!m.op_bands || !m.op_rgb_bands) return RAD_E_INVAL; + } + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16)); + Names& nm = m.nm; + /* Qwen3VLModel's tensors (language_model.*) or a ...ForConditionalGeneration's + * (model.language_model.*). */ + m.te_pre = std::strstr(rad_meta_gets(meta, "architectures", ""), "ForConditionalGeneration") + ? "model.language_model" : "language_model"; + m.turbo = std::strstr(rad_meta_gets(meta, "pipeline._class_name", ""), "Turbo") != nullptr || + rad_meta_geti(meta, "pipeline.is_distilled", 0) != 0; + + /* ---- the text fusion's and the DiT's geometry, off the transformer's config */ + Geom& gf = m.gf; + gf = m.gt; + gf.n_embd = rad_meta_geti(meta, "transformer.text_hidden_dim", 2560); + gf.n_head_all = rad_meta_geti(meta, "transformer.text_num_attention_heads", 20); + gf.n_head_kv_all = rad_meta_geti(meta, "transformer.text_num_key_value_heads", gf.n_head_all); + gf.head_dim = gf.n_embd / gf.n_head_all; + gf.n_ff_all = rad_meta_geti(meta, "transformer.text_intermediate_size", 6912); + gf.eps = (float)rad_meta_getf(meta, "transformer.norm_eps", 1e-5); + gf.max_tok = (int64_t)kCondRows * kNTaps; + RAD_ARCH_TRY(divide_or_fail(gf.n_head_all, gf.world, "the text fusion's heads", &gf.n_head)); + RAD_ARCH_TRY(divide_or_fail(gf.n_head_kv_all, gf.world, "the text fusion's KV heads", + &gf.n_head_kv)); + RAD_ARCH_TRY(divide_or_fail(gf.n_ff_all, gf.world, "the text fusion's feed-forward width", + &gf.n_ff)); + if (gf.n_head != gf.n_head_kv || gf.head_dim != 128) { + fprintf(stderr, "radiance: krea2: the text fusion must be multi-head at head_dim 128\n"); + return RAD_E_UNSUPPORTED; + } + Geom& gd = m.gd; + gd = m.gt; + gd.n_layer = rad_meta_geti(meta, "transformer.num_layers", 28); + gd.head_dim = rad_meta_geti(meta, "transformer.attention_head_dim", 128); + gd.n_head_all = rad_meta_geti(meta, "transformer.num_attention_heads", 48); + gd.n_head_kv_all = rad_meta_geti(meta, "transformer.num_key_value_heads", 12); + gd.n_embd = gd.head_dim * gd.n_head_all; + gd.n_ff_all = rad_meta_geti(meta, "transformer.intermediate_size", 16384); + gd.eps = (float)rad_meta_getf(meta, "transformer.norm_eps", 1e-5); + RAD_ARCH_TRY(divide_or_fail(gd.n_head_all, gd.world, "transformer.num_attention_heads", + &gd.n_head)); + RAD_ARCH_TRY(divide_or_fail(gd.n_head_kv_all, gd.world, "transformer.num_key_value_heads", + &gd.n_head_kv)); + RAD_ARCH_TRY(divide_or_fail(gd.n_ff_all, gd.world, "the DiT's feed-forward width", &gd.n_ff)); + gd.kv_off = 0; + if (gd.n_layer >= 1000 || gf.n_layer > kGrpTxtIn - kGrpFuse) return RAD_E_UNSUPPORTED; + m.C = rad_meta_geti(meta, "transformer.in_channels", 64); + + /* ---- bf16 or block fp8: what the container holds for the first DiT projection decides it + * for every linear of every network (rad_fp8.h, Geom::w_bf16). */ + { + LinearFP8& probe = m.qkv0; + RAD_ARCH_TRY(probe.probe(b, nm, gd, "dit.blk.0.attn_qkv", + { "transformer.transformer_blocks.0.attn.to_q.weight", + "transformer.transformer_blocks.0.attn.to_k.weight", + "transformer.transformer_blocks.0.attn.to_v.weight" })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + gd.w_bf16 = gf.w_bf16 = m.gt.w_bf16 = plain; + } + + /* ---- the per-image state, the conditioning store, and in issue order the language model, + * the text fusion, the DiT and the decoder */ + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, + { 2 * (int64_t)kMaxLanes * kCondRows, gd.n_embd }, RAD_BUF_PERSIST); + RAD_ARCH_TRY(declare_te(b, meta, m)); + RAD_ARCH_TRY(declare_fusion(b, meta, m)); + RAD_ARCH_TRY(declare_dit(b, meta, m)); + RAD_ARCH_TRY(declare_decoder(b, meta, m)); + + /* ---- what the core drives */ + if (!ctx->shape_probe) { + static thread_local std::string tmpl, drop; + tmpl = std::string("<|im_start|>system\n") + kSysPrompt + + "<|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"; + drop = std::string("<|im_start|>system\n") + kSysPrompt + "<|im_end|>\n<|im_start|>user\n"; + RadGeneratorDecl d{}; + d.name = m.turbo ? "krea-2-turbo" : "krea-2"; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.tmpl_text = tmpl.c_str(); + d.tmpl_edit = tmpl.c_str(); + d.drop_prefix = drop.c_str(); + d.latent_channels = m.C; + d.latent_scale = 16; + d.size_multiple = 16; + d.pixel_channels = 3; + d.slot_rows = 1; + d.max_tokens = kMaxImageTokens; + d.max_refs = 0; + d.ref_area = 1; + d.default_width = 1024; + d.default_height = 1024; + /* Raw: 28 steps on the resolution-shifted schedule, guidance 4.5 in the card's terms. + * Turbo: 8 steps at a fixed mu of 1.15 (base and max shift equal), no guidance. */ + d.default_steps = m.turbo ? 8 : 28; + d.n_sigmas = 0; + d.sigmas = nullptr; + d.shift = rad_meta_getf(meta, "scheduler.shift", 1.0); + d.dyn_shift = (int32_t)rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 1); + d.shift_exp = std::strcmp(rad_meta_gets(meta, "scheduler.time_shift_type", "exponential"), + "exponential") == 0; + d.base_shift = m.turbo ? 1.15 : rad_meta_getf(meta, "scheduler.base_shift", 0.5); + d.max_shift = m.turbo ? 1.15 : rad_meta_getf(meta, "scheduler.max_shift", 1.15); + d.base_seq = rad_meta_geti(meta, "scheduler.base_image_seq_len", 256); + d.max_seq = rad_meta_geti(meta, "scheduler.max_image_seq_len", 6400); + d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.0); + d.cfg_original = 1; + d.default_cfg = m.turbo ? 0.0 : 4.5; + d.default_negative = ""; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + d.cond_rows = kCondRows; + d.rope_hw_scale = 1.0; + d.rope_text_l = 0; + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu " + "blocks, DiT %lld blocks (%lld/%lld heads a rank, ff %lld), %s linears", + m.gt.rank, m.gt.world, m.turbo ? " Turbo" : "", kTaps[kNTaps - 1], + (long long)m.gt.n_layer, m.lw.size(), m.rf.size(), (long long)gd.n_layer, + (long long)gd.n_head, (long long)gd.n_head_kv, (long long)gd.n_ff, + gd.w_bf16 ? "bf16" : "block-fp8"); + return RAD_OK; +} + +/* ================================================================== step */ +/* The language model over the prompt (the system turn included, as the reference runs it), each + * tapped layer's rows scattered to the taps at row 12 t + i. */ +static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { + const Geom& g = m.gt; + const int64_t T = batch->n_tok; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), + brows(m.b_tx, T)); + RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T)); + const RadOperand pos = praw2(batch->rope_pos, RAD_I32, 3, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, 2); + for (const TeLayer& L : m.te) { + RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_tx, T), RAD_W(L.w_n1), brows(m.a_th.x, T)); + L.q_h.step(c, T); + L.qkv.step(c, m.a_th, m.b_tkv, T); + RAD_ISSUE_N(c, L.op_qkr, T, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), + bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, brows(m.a_tattn.x, T)); + L.q_attn.step(c, T); + L.o.step(c, m.a_tattn, m.b_th2, T); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_tx, T), RAD_W(L.w_n2), brows(m.a_th.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, m.a_th, m.b_tgu, T); + L.gq.step(c, m.b_tgu, T); + L.down.step(c, m.a_tffn, m.b_th2, T); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + if (L.tap >= 0) + RAD_ISSUE_N(c, L.op_tap, T, brows(m.b_tx, T), brows(m.b_tidx, T), + brow_slice(m.b_taps, L.tap, (int64_t)kTeRows * kNTaps - L.tap, + g.n_embd)); + } +} + +/* One text-fusion block over `R` rows of its residual from row `r0`, bounded by `cu`. */ +static void step_fuse(RadCtx* c, const Model& m, const FuseBlock& F, int64_t r0, int64_t R, + const RadOperand& cu) { + const Geom& g = m.gf; + const int64_t D = g.n_embd, qd = g.q_dim(), hd = g.head_dim; + const RadOperand x = brow_slice(F.x, r0, R, D); + RAD_ISSUE_N(c, F.op_n1, R, x, RAD_W(F.w_n1), brows(m.a_fh.x, R)); + F.q_h.step(c, R); + F.qkv.step(c, m.a_fh, m.b_fqkv, R); + F.gate.step(c, m.a_fh, m.b_fg, R); + RAD_ISSUE_N(c, F.op_qkn, R, brows(m.b_fqkv, R), RAD_NONE, RAD_W(F.w_qn), RAD_W(F.w_kn)); + RAD_ISSUE_N(c, F.op_attn, R, bcol(m.b_fqkv, 0, qd, R), bcol(m.b_fqkv, qd, qd, R), + bcol(m.b_fqkv, 2 * qd, qd, R), cu, brows(m.a_fattn.x, R)); + if (F.op_sig) { + RAD_ISSUE_N(c, F.op_sig, R, brows(m.b_fg, R), brows(m.b_fg, R)); + RAD_ISSUE_N(c, F.op_gq, R, brows(m.a_fattn.x, R), brows(m.b_fg, R), brows(m.a_fattn.x, R)); + F.q_attn.step(c, R); + } else { + const int64_t rh = R * (qd / hd), nb = hd / RAD_FP8_BLOCK; + RAD_ISSUE_N(c, F.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_fg), RAD_BF16, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_fattn.x), RAD_BF16, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_fattn.cq()), RAD_F8E4M3, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_fattn.cs()), RAD_F32, rh, nb), + RAD_P_T2(rad_buf_ptr(c, m.a_fattn.x), RAD_BF16, rh, hd)); + } + F.o.step(c, m.a_fattn, m.b_fo, R); + if (F.op_ar1) RAD_ISSUE_N(c, F.op_ar1, R * D, brows(m.b_fo, R), RAD_NONE); + RAD_ISSUE_N(c, F.op_add1, R, x, brows(m.b_fo, R), x); + RAD_ISSUE_N(c, F.op_n2, R, x, RAD_W(F.w_n2), brows(m.a_fh.x, R)); + F.q_h2.step(c, R); + F.gate_up.step(c, m.a_fh, m.b_fgu, R); + F.gq.step(c, m.b_fgu, R); + F.down.step(c, m.a_fffn, m.b_fo, R); + if (F.op_ar2) RAD_ISSUE_N(c, F.op_ar2, R * D, brows(m.b_fo, R), RAD_NONE); + RAD_ISSUE_N(c, F.op_add2, R, x, brows(m.b_fo, R), x); +} + +/* The conditioning: the language model's taps, the text fusion over the tokens after the system + * turn (the layer-wise blocks over each token's twelve taps, the mix, the refiner over the + * tokens), txt_in, and the rows into every lane's store at this branch. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t P = G->rows, drop = batch->n_tok - P; + const int64_t D = m.gf.n_embd, Dd = m.gd.n_embd, RL = P * kNTaps; + step_te(c, batch, m); + RAD_ISSUE_N(c, m.op_fcu, P + 1, brows(m.b_fcu, P + 1)); + for (const FuseBlock& F : m.lw) step_fuse(c, m, F, drop * kNTaps, RL, brows(m.b_fcu, P + 1)); + RAD_ISSUE_N(c, m.op_mix, P, brow_slice(m.b_taps, drop * kNTaps, RL, D), RAD_W(m.w_mix), + brows(m.b_ft, P)); + const RadOperand cu = praw(G->seg_cu, RAD_I32, 2); + for (const FuseBlock& F : m.rf) step_fuse(c, m, F, 0, P, cu); + RAD_ISSUE_N(c, m.op_txn, P, brows(m.b_ft, P), RAD_W(m.w_txn), brows(m.b_txa, P)); + RAD_ISSUE_N(c, m.op_tx1, P, brows(m.b_txa, P), RAD_W(m.w_tx1), RAD_W(m.b_tx1), RAD_NONE, + brows(m.b_txb, P)); + RAD_ISSUE_N(c, m.op_txg, P, brows(m.b_txb, P), brows(m.b_txb, P)); + RAD_ISSUE_N(c, m.op_tx2, P, brows(m.b_txb, P), RAD_W(m.w_tx2), RAD_W(m.b_tx2), RAD_NONE, + brows(m.b_txt, P)); + RAD_ISSUE_N(c, m.op_store, P, brows(m.b_txt, P), praw(G->lane, RAD_I32, G->n_lane), + brow_slice(m.b_store, (int64_t)G->branch * kCondRows, + 2 * (int64_t)kMaxLanes * kCondRows - G->branch * kCondRows, Dd)); +} + +/* One denoising step: the entries' modulation, the joint rows, the blocks, and the image rows' + * output through the sampler. */ +static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const Geom& g = m.gd; + const int64_t N = batch->n_tok, S = batch->n_seq, NI = G->n_img; + const int64_t D = g.n_embd, qd = g.q_dim(), kvd = g.kv_dim(), hd = g.head_dim; + const int64_t L = g.n_layer, W = L * 6 * D, nD = D / RAD_FP8_BLOCK; + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, S + 1); + const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1); + const RadOperand lanes = praw(G->lane, RAD_I32, S); + const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens; + + /* ---- modulation: the timestep MLP, the shared projection, each block's table, the final */ + RAD_ISSUE_N(c, m.op_temb, S, praw(G->sigma, RAD_F32, S), brows(m.b_tproj, S)); + RAD_ISSUE_N(c, m.op_t1, S, brows(m.b_tproj, S), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, + brows(m.b_te1, S)); + RAD_ISSUE_N(c, m.op_tg, S, brows(m.b_te1, S), brows(m.b_te1g, S)); + RAD_ISSUE_N(c, m.op_t2, S, brows(m.b_te1g, S), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, + brows(m.b_temb, S)); + RAD_ISSUE_N(c, m.op_tg2, S, brows(m.b_temb, S), brows(m.b_tembg, S)); + RAD_ISSUE_N(c, m.op_mod, S, brows(m.b_tembg, S), RAD_W(m.w_mod), RAD_W(m.b_mod), RAD_NONE, + brows(m.b_tmod, S)); + RAD_ISSUE_N(c, m.op_ftab, S, brows(m.b_temb, S), RAD_W(m.w_ftab), brows(m.b_fmod, S)); + + /* ---- the rows: the images' latents (noise on a first step), img_in, joined with the text */ + RAD_ISSUE_N(c, m.op_randn, NI, praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + lanes, icu, brows(m.b_state, LR)); + RAD_ISSUE_N(c, m.op_lgather, NI, brows(m.b_state, LR), lanes, icu, brows(m.b_lat, NI)); + RAD_ISSUE_N(c, m.op_imgin, NI, brows(m.b_lat, NI), RAD_W(m.w_imgin), RAD_W(m.b_imgin), RAD_NONE, + brows(m.b_himg, NI)); + RAD_ISSUE_N(c, m.op_join, N, brows(m.b_store, 2 * (int64_t)kMaxLanes * kCondRows), + brows(m.b_himg, NI), praw(G->src, RAD_I32, N), brows(m.b_h, N)); + + /* ---- the blocks; block l's modulation is columns [6 l D, 6 (l + 1) D) of `mods`: + * (preshift, prescale), pregate, (postshift, postscale), postgate */ + const RadOperand pos = praw2(G->rope_f, RAD_F32, 4, N); + auto mod = [&](int64_t l, int k, int width) { return bcol_at(m.b_mods, 0, W, (6 * l + k) * D, + width * D, S); }; + const bool q8 = !g.w_bf16; + for (int64_t l = 0; l < L; ++l) { + const DitLayer& B = m.dit[(size_t)l]; + /* The block's modulation: the shared projection plus its own table, into its columns. */ + RAD_ISSUE_N(c, B.op_tab, S, brows(m.b_tmod, S), RAD_W(B.w_tab), + bcol_at(m.b_mods, 0, W, l * 6 * D, 6 * D, S)); + if (q8) + RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE, + l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu, + brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n1, N, l > 0 ? brows(m.b_ao, N) : RAD_NONE, + l > 0 ? mod(l - 1, 5, 1) : RAD_NONE, mod(l, 0, 2), RAD_W(B.w_n1), cu, + brows(m.b_h, N), brows(m.a_hm.x, N)); + B.qkv.step(c, m.a_hm, m.b_qkv, N); + B.gate.step(c, m.a_hm, m.b_g, N); + RAD_ISSUE_N(c, B.op_qkr, N, brows(m.b_qkv, N), pos, RAD_W(B.w_qn), RAD_W(B.w_kn)); + RAD_ISSUE_N(c, B.op_attn, N, bcol(m.b_qkv, 0, qd, N), bcol(m.b_qkv, qd, kvd, N), + bcol(m.b_qkv, qd + kvd, kvd, N), cu, brows(m.a_attn.x, N)); + if (B.op_sig) { + RAD_ISSUE_N(c, B.op_sig, N, brows(m.b_g, N), brows(m.b_g, N)); + RAD_ISSUE_N(c, B.op_gq, N, brows(m.a_attn.x, N), brows(m.b_g, N), brows(m.a_attn.x, N)); + B.q_attn.step(c, N); + } else { + const int64_t rh = N * (qd / hd), nb = hd / RAD_FP8_BLOCK; + RAD_ISSUE_N(c, B.op_gq, rh, RAD_P_T2(rad_buf_ptr(c, m.b_g), RAD_BF16, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_attn.x), RAD_BF16, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_attn.cq()), RAD_F8E4M3, rh, hd), + RAD_P_T2(rad_buf_ptr(c, m.a_attn.cs()), RAD_F32, rh, nb), + RAD_P_T2(rad_buf_ptr(c, m.a_attn.x), RAD_BF16, rh, hd)); + } + B.o.step(c, m.a_attn, m.b_ao, N); + if (B.op_ar1) RAD_ISSUE_N(c, B.op_ar1, N * D, brows(m.b_ao, N), RAD_NONE); + if (q8) + RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2), + cu, brows(m.b_h, N), brows(m.a_hm.q, N), brows(m.a_hm.s, N), RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n2, N, brows(m.b_ao, N), mod(l, 2, 1), mod(l, 3, 2), RAD_W(B.w_n2), + cu, brows(m.b_h, N), brows(m.a_hm.x, N)); + B.gate_up.step(c, m.a_hm, m.b_gu, N); + B.gq.step(c, m.b_gu, N); + B.down.step(c, m.a_ffn, m.b_ao, N); + if (B.op_ar2) RAD_ISSUE_N(c, B.op_ar2, N * D, brows(m.b_ao, N), RAD_NONE); + } + (void)nD; + /* ---- the last block's feed-forward gated in, the image rows out, the final layer */ + RAD_ISSUE_N(c, m.op_g2, N, brows(m.b_ao, N), mod(L - 1, 5, 1), cu, brows(m.b_h, N)); + RAD_ISSUE_N(c, m.op_gimg, NI, brows(m.b_h, N), praw(G->img_rows, RAD_I32, NI), + brows(m.b_hi, NI)); + RAD_ISSUE_N(c, m.op_fn, NI, RAD_NONE, RAD_NONE, brows(m.b_fmod, S), RAD_W(m.w_fn), icu, + brows(m.b_hi, NI), brows(m.b_fz, NI)); + RAD_ISSUE_N(c, m.op_pout, NI, brows(m.b_fz, NI), RAD_W(m.w_pout), RAD_W(m.b_pout), RAD_NONE, + brows(m.b_v, NI)); + RAD_ISSUE_N(c, m.op_euler, NI, brows(m.b_v, NI), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->cfg, RAD_F32, S), + praw(G->pair, RAD_I32, S), lanes, praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), icu, RAD_NONE, RAD_NONE, brows(m.b_state, LR), + brows(m.b_prev, LR)); +} + +/* One image's latent to RGB: denormalised, unpacked to the VAE's grid, decoded (in row bands + * with more than one rank). */ +static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dinv, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C), + brows(m.b_dl, n)); + RAD_ISSUE_N(c, m.op_dadd, n, brows(m.b_dl, n), brows(m.b_dl2, n)); + const int64_t zd = C / 4, H0 = 2 * H, W0 = 2 * W; + RAD_ISSUE_N(c, m.op_dzero, H0 * W0, brows(m.b_decin, H0 * W0)); + RAD_ISSUE_N(c, m.op_unpack, H0 * W0, + RAD_P_T2(rad_buf_ptr(c, m.b_dl2), RAD_BF16, H, W * C), + RAD_P_T2(rad_buf_ptr(c, m.b_decin), RAD_BF16, H0, W0 * zd)); + RAD_ISSUE_N(c, m.op_cu4, 2, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_cu4, 2)); + const RadOperand cu = brows(m.b_cu4, 2); + const int64_t npx = (int64_t)G->dec_height * G->dec_width; + const int world = m.gt.world, rank = m.gt.rank; + const int64_t band = (H0 + world - 1) / world, halo = m.dec.halo; + if (!m.op_bands || band + 2 * halo >= H0) { + m.dec.issue(c, H0, W0, cu, nullptr); + RAD_ISSUE_N(c, m.op_rgb, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); + return; + } + m.dec.issue(c, H0, W0, cu, nullptr, 0, (size_t)m.dec.band_from); + const int64_t a = rank * band; + const int64_t lo = std::max(0, a - halo), hi = std::min(H0, a + band + halo); + m.dec.issue(c, hi - lo, W0, cu, nullptr, (size_t)m.dec.band_from, (size_t)-1, lo); + const int64_t bpx = band * 8 * W0 * 8; + const char* out = (const char*)rad_buf_ptr(c, m.dec_out.buf) + + (a - lo) * 8 * W0 * 8 * 3 * (int64_t)sizeof(uint16_t); + RAD_ISSUE_N(c, m.op_bands, bpx * 3, RAD_P_T2(out, RAD_BF16, bpx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_rgbf), RAD_BF16, world * bpx, 3)); + RAD_ISSUE_N(c, m.op_rgb_bands, npx, RAD_P_T2(rad_buf_ptr(c, m.b_rgbf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->gen_b) { + rad_step_fail(c, "krea2 is an image generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_COND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_DENOISE: step_denoise(c, batch, m); return; + case RAD_GEN_PASS_DECODE: step_decode(c, batch, m); return; + default: rad_step_fail(c, "krea2: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: one image at the largest size with guidance, its text both ways. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kCondRows); + out->gen_patches = 0; + return RAD_OK; +} + +} /* namespace krea2 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(krea2) +RAD_ARCH_PLUGIN(krea2, "krea2", "", "0.1.0", + "Krea 2 / Krea 2 Turbo: Qwen3-VL-4B taps through a text-fusion transformer, a 12.9B " + "single-stream diffusion transformer over the joint text and image, and Wan 2.1's " + "VAE; bf16 or block-fp8 linears") +#endif diff --git a/arch/ltx2/CMakeLists.txt b/arch/ltx2/CMakeLists.txt new file mode 100644 index 00000000..1388a407 --- /dev/null +++ b/arch/ltx2/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/ltx2 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(ltx2 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(ltx2 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/ltx2.cpp) diff --git a/arch/ltx2/ltx2.cpp b/arch/ltx2/ltx2.cpp new file mode 100644 index 00000000..e0e9f6b5 --- /dev/null +++ b/arch/ltx2/ltx2.cpp @@ -0,0 +1,4193 @@ +/* ltx2 -- LTX-2.5: a video and its stereo soundtrack from text, or from text and a first frame. + * + * ============================== THE MODEL ============================== + * + * diffusers' LTX2Pipeline (LTX-2.5's components, Lightricks/LTX-2.5-Diffusers): + * + * Text encoder: Gemma 4's language model over the prompt, left-padded to 1024 tokens (no + * template; the tokenizer's and around it). Every layer's output is kept -- the + * embeddings, each layer's but the last, and the final norm of the last -- and each token's + * stack of them is RMS-normed per layer and flattened channel-major. + * + * Connectors: per modality a projection of that stack to the DiT's width (video 4096, audio + * 2048), then 1024 rows -- the prompt's tokens, the rest filled from 128 learnable registers -- + * through eight bidirectional transformer blocks with a split rotary over the row index. + * + * Denoiser: a dual-stream DiT, 48 blocks over the video's latents (1 x 1 patches of 128 channels, + * 32 pixels a latent, 8 frames a latent frame) and the soundtrack's (25 a second, 8 channels x 16 + * mel bins). A block's video stream runs self-attention, cross-attention to its text, attention + * to the soundtrack, and a feed-forward, each behind an adaptive norm; the soundtrack's the same + * against the video. Every attention is gated per head (2 sigmoid of a logit) and normalises q + * and k across all heads. + * + * Guidance: up to four DiT evaluations a step -- the prompt, the negative prompt, the prompt with + * block 28's self-attentions bypassed (spatio-temporal guidance) and the prompt without the + * cross-modal attentions -- combined in the clean-estimate space with a rescale + * (abi/rad_builder.h, RadVideoGenDecl::guidance; the op ltx_guide). + * + * Video VAE: a causal 3D-conv decoder (four up blocks of residual blocks, depth-to-space + * resampling, PerChannelRMSNorm), 4 x 4 pixel patches out; its encoder takes a first frame in. + * + * Audio: a causal 2D-conv decoder to a stereo log-mel spectrogram at 16 kHz, a BigVGAN vocoder + * to 16 kHz, and a bandwidth extender (its own vocoder over the waveform's log-mel spectrogram + * plus a sinc-resampled skip) to 48 kHz. + * + * Latent upsampler (latent_upsampler/): two-times spatial upscaling of the video latent for the + * two-stage recipe (a distilled release's stage-2 rungs, RadVideoGenDecl::refine_rungs). + * + * Duration head (duration_head/): the length the prompt implies, pooled by one learned query + * from both connectors' output (RadVideoGenDecl::duration_out). + * + * Diffusion decoder (diffusion_decoder/): the release's second decoder, on request + * (RadVideoGenDecl::decoders): neighbourhood-attention stages over the latent, then one denoising + * step over pixel patches, tile by tile (declare_ddec says how). + * + * The passes are the core's video generator (core/gen/video_driver.h): + * + * VCOND the text encoder over both prompts, the connectors into the lane's text rows, the + * duration head over the prompt's, and with a first frame the VAE encoder into the + * lane's clean first latent frame. + * VSTEP the step's modulation tables, then each guidance evaluation the request needs, then + * one ltx_guide a modality; with a first frame, its latent frame restored. + * ADECODE the soundtrack: the audio VAE, the vocoder, the bandwidth extender. + * VDECODE chunk 0 decodes the whole video into the lane's tile store, a tile at a time for a + * frame larger than the default canvas; every chunk then stitches its frames to bytes. + * VUPSCALE the latent upsampler, then both latents re-noised for the second stage. + * + * ============================== PRECISION ============================== + * + * Every network computes in bf16, as the reference loads it; the latents, the guidance and the + * sampler are f32. The text encoder's, the connectors' and the DiT's large linears are bf16 or + * block fp8 as the container holds them (data/recipes/ltx-2.5-fp8.recipe); the vocoder runs in + * f32 (its anti-aliased activation's kernels are f32), its log-mel input rounded where the + * reference's bf16 one is. + * + * ============================== LIMITS ============================== + * + * One rank (TP 1): the DiT's q and k norms span every head, which a head split would cut. A step + * carries 121 frames at 1920 x 1088 at most; the diffusion decoder decodes the default canvas's + * area at most. The prompt enhancer and the temporal upsampler (the DFR pipeline's) are not run. + */ +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace ltx2 { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* Connector rows a prompt: the text encoder's padded length. */ +enum { kTextRows = 1024 }; +/* Requests holding state at once: one denoising, one conditioned and waiting. */ +enum { kMaxLanes = 2 }; +/* Evaluations a request may take, and the base model's default. */ +enum { kMaxSteps = 64, kDefSteps = 30 }; +/* Time: 24 frames a second; a video of n chunks is 8 n + 1 frames over n + 1 latent frames. A + * decode pass is a chunk of frames; chunk 0 decodes the whole video, a tile at a time. */ +enum { kFps = 24, kFpc = 8, kFtail = 1, kLpc = 1, kLtail = 1, kDecLat = 2 }; +enum { kMinChunks = 2, kMaxChunks = 20, kDefChunks = 15 }; +/* Space: 32 pixels a latent; sides multiples of 32 from 256, 3:1 at most; the release's 960 x 544 + * canvas by default, and four times its area at most -- the two-stage recipe's 1920 x 1088. A + * step holds at most the video rows of 121 frames at that size. */ +enum { kScale = 32, kMult = 32, kMinSide = 256, kMaxAspect = 3 }; +enum { kDefW = 960, kDefH = 544, kMaxArea = 4 * kDefW * kDefH }; +enum { kMaxVideoRows = 16 * (2 * kDefW / kScale) * (2 * kDefH / kScale) }; +/* The VAE decodes a frame of the default canvas's latents or fewer whole, as the pipeline does + * without tiling; a larger one in diffusers' tiles (enable_tiling: 512 pixels every 448, 16 latents + * every 14), blended where they overlap (tile_stitch). */ +enum { kVaeLat = kDefW * kDefH / (kScale * kScale), kTile = 16, kTileStride = 14 }; +/* The video latent's channels (a 1 x 1 patch), the VAE's pixel patch and its channels. */ +enum { kC = 128, kPix = 4, kPixC = 3 * kPix * kPix }; +/* The soundtrack: 25 latents a second of 8 channels x 16 mel bins, packed channel-major; its + * spectrogram 64 bins at 16 kHz with 160-sample hops; 48 kHz stereo out. */ +enum { kAudioRate = 25, kAudioCh = 2, kAudioC = 128, kLatCh = 8, kLatMel = 16, kMel = 64 }; +enum { kRate = 48000, kVocRate = 16000, kMelHop = 160 }; +/* Guidance terms (RadVideoGenBatch::guidance): the video's then the soundtrack's four. */ +enum { kGsV = 0, kStgV = 1, kMsV = 2, kGsA = 4, kStgA = 5, kMsA = 6 }; +/* The block whose self-attentions spatio-temporal guidance bypasses. */ +enum { kStgBlock = 28 }; +/* An evaluation of the DiT within a step: the prompt, the negative prompt, the prompt with STG, + * the prompt without the cross-modal attentions. */ +enum { kPassCond = 0, kPassUncond = 1, kPassStg = 2, kPassIso = 3, kPasses = 4 }; + +/* ================================================================== geometry, on the host */ +static int64_t max_lat_frames() { return (int64_t)kLpc * kMaxChunks + kLtail; } +static int64_t max_patches() { return (int64_t)kMaxArea / (kScale * kScale); } +static int64_t max_video_rows() { return kMaxVideoRows; } +static int64_t max_frames() { return (int64_t)kFpc * kMaxChunks + kFtail; } +static int64_t max_audio() { return (max_frames() * kAudioRate + kFps / 2) / kFps + 1; } +static int64_t max_step_rows() { return kTextRows + max_audio() + max_video_rows(); } +/* The spectrogram's frames for n audio latents (the audio VAE's causal upsampling). */ +static int64_t mel_frames(int64_t n) { return 4 * n - 3; } + +/* The VAE's tiles of an h x w latent grid, as tile_grid cuts them: one when the frame is the + * untiled decoder's, else a tile every kTileStride latents, kTile long or to the edge. */ +struct VaeTile { int64_t h, w; }; +static bool vae_tiled(int64_t h, int64_t w) { return h * w > kVaeLat; } +static std::vector vae_tiles(int64_t h, int64_t w) { + if (!vae_tiled(h, w)) return { { h, w } }; + std::vector t; + for (int64_t y0 = 0; y0 < h; y0 += kTileStride) + for (int64_t x0 = 0; x0 < w; x0 += kTileStride) + t.push_back({ std::min(kTile, h - y0), std::min(kTile, w - x0) }); + return t; +} + +/* The step's rotary coordinates, flat (the core hands them through as RadVideoGenBatch::pos): the + * video's (t, y, x) midpoints as [3, S] component-major, then the soundtrack's time midpoints, + * f32 as the reference computes them (LTX2AudioVideoRotaryPosEmbed's prepare_*_coords at 24 + * frames a second). A latent frame f spans pixel frames [max(8 f - 7, 0), 8 f + 1) over the fps; + * a latent (h, w) pixels [32 h, 32 h + 32); an audio latent mel frames [max(4 f - 3, 0), 4 f + 1) + * at 160 / 16000 s a frame. */ +static int64_t positions(const RadVideoGeom* g, float* pos, int64_t cap) { + if (!g || g->n_text < 1 || g->lat_frames < 1 || g->lat_h < 1 || g->lat_w < 1 || g->n_audio < 1) + return RAD_E_INVAL; + const int64_t F = g->lat_frames, H = g->lat_h, W = g->lat_w, S = F * H * W, A = g->n_audio; + const int64_t rows = g->n_text + A + S; + if (S > max_video_rows()) return RAD_E_INVAL; + if (!pos) return rows; + if (cap < rows) return RAD_E_INVAL; + float* pt = pos; + float* py = pos + S; + float* px = pos + 2 * S; + float* pa = pos + 3 * S; + int64_t r = 0; + for (int64_t f = 0; f < F; ++f) { + const float t0 = std::max(8.0f * (float)f + 1.0f - 8.0f, 0.0f) / (float)kFps; + const float t1 = std::max(8.0f * (float)(f + 1) + 1.0f - 8.0f, 0.0f) / (float)kFps; + const float tm = (t0 + t1) / 2.0f; + for (int64_t h = 0; h < H; ++h) + for (int64_t w = 0; w < W; ++w, ++r) { + pt[r] = tm; + py[r] = (32.0f * (float)h + 32.0f * (float)(h + 1)) / 2.0f; + px[r] = (32.0f * (float)w + 32.0f * (float)(w + 1)) / 2.0f; + } + } + for (int64_t f = 0; f < A; ++f) { + const float m0 = std::max(4.0f * (float)f + 1.0f - 4.0f, 0.0f); + const float m1 = std::max(4.0f * (float)(f + 1) + 1.0f - 4.0f, 0.0f); + const float s0 = m0 * (float)kMelHop / (float)kVocRate; + const float s1 = m1 * (float)kMelHop / (float)kVocRate; + pa[f] = (s0 + s1) / 2.0f; + } + return rows; +} + +/* ================================================================== linears */ +/* An activation a linear reads: its bf16 plane and, for block-fp8 linears, its codes, which a + * quantiser makes from the plane (QuantFP8). */ +struct Act { + ActFP8 a{}; + QuantFP8 q{}; + int64_t n = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, + int64_t width) { + n = width; + a.x = decl_b(b, nm.f("%s", name), RAD_BF16, { rows, width }); + if (!a.x) return RAD_E_INVAL; + Geom gg = g; + gg.max_tok = rows; + RAD_ARCH_TRY(a.declare_qs(b, nm, gg, name, width, rows)); + return q.declare(b, gg, a, width); + } + /* The codes of rows [r0, r0 + rows), at those rows' count. */ + void step(RadCtx* c, int64_t rows, int64_t r0 = 0) const { + if (!q.op || rows <= 0) return; + RAD_ISSUE_N(c, q.op, rows, brow_slice(a.x, r0, rows, n), brow_slice(a.cq(), r0, rows, n), + brow_slice(a.cs(), r0, rows, n / RAD_FP8_BLOCK)); + } +}; + +/* A linear, y = x W^T (+ b): `gemm_nt_bias` over the bf16 plane for a bf16 weight (the bias in the + * GEMM's one rounding, as torch's), or `gemm_nt_q` over the codes for a block-fp8 one with the + * bias added after (`table_add`, one more rounding). `small` keeps a weight bf16 in any container + * (a gate's logits: too few rows for 128-row fp8 blocks). The input and output rows may sit at + * different offsets of their buffers. */ +struct Lin { + LinearFP8 l{}; + rad_weight w = 0, bias = 0; + rad_op op = 0, op_b = 0; + bool fp8 = false; + bool mapped = false; /* the weight's name map was made already (a probe's) */ + int64_t N = 0, K = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, + std::initializer_list wsrc, std::initializer_list bsrc, + std::initializer_list parts, int64_t n_out, int64_t n_in, int access, + int group, const Act& in, rad_buf y, int64_t max_rows, bool small = false) { + N = n_out; + K = n_in; + const char* wn = nm.f("%s.weight", base); + const char* bn = nm.f("%s.bias", base); + if (bsrc.size()) { + if (bsrc.size() == 1) RAD_ARCH_TRY(map_copy(b, bn, *bsrc.begin())); + else RAD_ARCH_TRY(map_concat(b, bn, bsrc)); + bias = decl_w(b, bn, RAD_BF16, { N }, access, RAD_SHARD_NONE, grp_layer(group)); + if (!bias) return RAD_E_INVAL; + } + fp8 = !(g.w_bf16 || small); + if (!fp8) { + if (mapped) {} + else if (wsrc.size() == 1) RAD_ARCH_TRY(map_copy(b, wn, *wsrc.begin())); + else RAD_ARCH_TRY(map_concat(b, wn, wsrc)); + w = decl_w(b, wn, RAD_BF16, { N, K }, access, RAD_SHARD_NONE, grp_layer(group)); + if (!w) return RAD_E_INVAL; + op = bias ? rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows), RAD_INT("N", N), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)), + { in.a.x }, { y }) + : rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows), RAD_INT("N", N), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { in.a.x }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } + l.access = access; + l.mapped = mapped; + RAD_ARCH_TRY(l.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(group), wsrc, in.a, y, + max_rows, parts)); + if (l.bf16 || l.i8 || l.mx || l.w4 || l.paro || l.paro5) { + fprintf(stderr, "radiance: ltx2: '%s' is not block fp8; this plugin reads bf16 or " + "block-fp8 linears\n", base); + return RAD_E_UNSUPPORTED; + } + op = l.op; + if (bias) + op_b = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, max_rows), RAD_INT("n", N), + RAD_INT("L", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(bias)), + { y }, { y }); + return op && (!bias || op_b) ? RAD_OK : RAD_E_INVAL; + } + + /* Input rows [ri, ri + rows) to output rows [ro, ro + rows). */ + void step(RadCtx* c, const Act& in, rad_buf y, int64_t rows, int64_t ri = 0, + int64_t ro = 0) const { + if (rows <= 0) return; + const RadOperand out = brow_slice(y, ro, rows, N); + if (!fp8) { + if (bias) + RAD_ISSUE_N(c, op, rows, brow_slice(in.a.x, ri, rows, K), RAD_W(w), RAD_W(bias), + RAD_NONE, out); + else + RAD_ISSUE_N(c, op, rows, brow_slice(in.a.x, ri, rows, K), RAD_W(w), out); + return; + } + RAD_ISSUE_N(c, op, rows, brow_slice(in.a.q, ri, rows, K), + brow_slice(in.a.s, ri, rows, K / RAD_FP8_BLOCK), RAD_W(l.w), RAD_W(l.ws), out, + RAD_NONE, RAD_NONE); + if (op_b) RAD_ISSUE_N(c, op_b, rows, out, RAD_W(bias), out); + } +}; + +/* A weight copied as the checkpoint holds it, read whole. */ +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, const char* dtype, + rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", dtype)), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, const char* dtype, rad_buf a, rad_buf c, + rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", dtype)), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op cast_op(RadBuilder* b, int64_t rows, int64_t n, const char* from, const char* to, + rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("from", from), + RAD_STR("to", to)), + RAD_NOWEIGHTS), + { x }, { y }); +} + +/* An RMS norm over n with an optional gain (none: a gain of one), bf16. */ +static rad_op rms_op(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, w ? RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)) + : RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x }, { y }); +} + +/* `norm(x) (1 + scale) + shift`, the shift and scale one row of the table `st` per entry of + * `cu_seqlens`; with `gated` the branch before it gated in first (x += g y, g a row of `gt`). + * `norm` rms, layer or none, without a gain. */ +static rad_op mod_op(RadBuilder* b, int64_t rows, int64_t n, double eps, bool gated, + const char* norm, rad_buf st, rad_buf gt, rad_buf x, rad_buf y, rad_buf z) { + rad_op op = RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", norm)), + RAD_NOWEIGHTS); + if (!op) return 0; + rad_buf rd[4] = { st, x, gt, y }; + rad_buf wr[2] = { x, z }; + rad_op_reads(b, op, rd, gated ? 4 : 2); + rad_op_writes(b, op, wr, 2); + return op; +} + +/* x += g y, the gate one row per entry of `cu_seqlens`, no activation. */ +static rad_op gate_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf table, rad_buf y, rad_buf x) { + return rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { y, table, x }, { x }); +} + +/* A space-separated list off the container (rad-convert flattens arrays that way). */ +static std::vector meta_list(const RadModelMeta* m, const char* key) { + std::vector v; + const char* s = rad_meta_gets(m, key, nullptr); + while (s && *s) { + char* e = nullptr; + const double x = std::strtod(s, &e); + if (e == s) { ++s; continue; } + v.push_back(x); + s = e; + } + return v; +} + +static std::string ints(std::initializer_list v) { + std::string s; + for (long long x : v) { + char t[24]; + std::snprintf(t, sizeof t, "%s%lld", s.empty() ? "" : " ", x); + s += t; + } + return s; +} + +/* ================================================================== the model's parts */ +/* A text encoder layer: sliding or full attention, each class its own head geometry and rotary. */ +struct TeLayer { + bool full = false, v_from_k = false; + int64_t nh = 0, nkv = 0, hd = 0, rot = 0; + double theta = 0.0; + rad_weight w_in = 0, w_pa = 0, w_pf = 0, w_ff = 0, w_qn = 0, w_kn = 0, w_sc = 0; + Lin q{}, k{}, v{}, o{}, gu{}, down{}; + rad_op op_in = 0, op_vn = 0, op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0, op_attn = 0; + rad_op op_pa = 0, op_add1 = 0, op_pf = 0, op_act = 0, op_ff = 0, op_add2 = 0, op_sc = 0; + rad_op op_keep = 0; +}; +/* An attention class's rows: q, k, v and the attention's output. */ +struct TeClass { + rad_buf q = 0, k = 0, v = 0; + Act o{}; +}; + +/* An attention: q (k and v from the same rows for a self-attention), the per-head gate's logits, q + * and k RMS-normed across every head, the output projection. A cross-attention's k and v come from + * the context's rows. */ +struct Attn { + int64_t H = 0, hd = 0, inner = 0; + rad_weight w_qn = 0, w_kn = 0; + Lin qkv{}, kv{}, gate{}, out{}; + rad_op op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0, op_attn = 0, op_hg = 0, op_v = 0; +}; + +struct ConnBlock { + Attn at{}; + Lin up{}, down{}; + rad_op op_n1 = 0, op_add1 = 0, op_n2 = 0, op_act = 0, op_add2 = 0; +}; +/* A modality's connector: the stack's projection, the registers and the blocks. */ +struct Conn { + int64_t D = 0, H = 0, hd = 0, ff = 0; + double mult = 1.0; /* sqrt(D / text width), the normed stack's scale */ + rad_weight w_reg = 0; /* the registers, tiled to kTextRows rows */ + Lin proj{}; + rad_op op_norm = 0, op_reg = 0, op_nout = 0; + Act a_in{}, a_h{}, a_attn{}, a_ffn{}; + rad_buf b_x = 0, b_qkv = 0, b_g = 0, b_o = 0, b_up = 0; + rad_buf b_text = 0; /* PERSIST [lanes * 2 * kTextRows, D]: a lane's two prompts */ + std::vector blk; +}; + +/* A DiT block. The modulation tables are each block's learned rows plus the step's shared ones, + * made once a step into the step's tables (DitStep). */ +struct DitBlock { + Attn sv{}, sa{}, tv{}, ta{}, a2v{}, v2a{}; + Lin fv_up{}, fv_down{}, fa_up{}, fa_down{}; + rad_weight t_v = 0, t_a = 0, t_p = 0, t_pa = 0, t_cv = 0, t_cvg = 0, t_ca = 0, t_cag = 0; + rad_op op_tv = 0, op_ta = 0, op_tp = 0, op_tpa = 0, op_tcv = 0, op_tcvg = 0, op_tca = 0; + rad_op op_tcag = 0; + /* Video: the self-attention's norm (gated by the previous block's feed-forward), the text + * query's (gated by the self-attention), the text's modulation, the text gate, the two + * cross-modal modulations, the cross-modal gate, the feed-forward's norm ungated and gated by + * the text (a pass without the cross-modal attentions), the activation. Audio the same. */ + rad_op m1v = 0, m2v = 0, mtv = 0, g2v = 0, mav = 0, mvv = 0, gcv = 0, m3v = 0, m3vg = 0; + rad_op actv = 0; + rad_op m1a = 0, m2a = 0, mta = 0, g2a = 0, maa = 0, mva = 0, gca = 0, m3a = 0, m3ag = 0; + rad_op acta = 0; +}; + +/* One AdaLayerNormSingle: the timestep's MLP to `emb`, then SiLU and a linear to `temb`. */ +struct Ada { + int64_t d = 0, k = 0; + rad_weight w1 = 0, b1 = 0, w2 = 0, b2 = 0, wl = 0, bl = 0; + rad_op op1 = 0, ops1 = 0, op2 = 0, ops2 = 0, opl = 0; + rad_buf h = 0, hs = 0, emb = 0, es = 0, temb = 0; +}; + +/* A 3D residual block of the video VAE: PerChannelRMSNorm and SiLU, a convolution, again, the + * residual added. */ +struct VRes { + int64_t C = 0; + rad_weight w1 = 0, b1 = 0, w2 = 0, b2 = 0; + rad_op op_n1 = 0, op_c1 = 0, op_n2 = 0, op_c2 = 0; +}; +/* An up block: the upsampler's convolution and depth to space, then its residual blocks. */ +struct VUp { + int64_t cin = 0, cout = 0, st = 1, sh = 1, sw = 1, conv_out = 0; + rad_weight w = 0, b = 0; + rad_op op_conv = 0, op_d2s = 0, op_geom = 0; + rad_buf geom = 0; /* its output volume, i32 [3] */ + std::vector res; +}; +/* A down block: its residual blocks, then the downsampler's convolution, space to depth, and the + * input's group mean added. */ +struct VDown { + int64_t cin = 0, cout = 0, st = 1, sh = 1, sw = 1, conv_out = 0, group = 1; + std::vector res; + rad_weight w = 0, b = 0; + rad_op op_conv = 0, op_mean = 0, op_s2d = 0, op_geom = 0, op_geom_in = 0, op_next = 0; + rad_buf geom = 0, geom_in = 0; /* its convolution's volume, and its input's */ +}; + +/* An audio VAE residual block (2D, causal along time): PixelNorm and SiLU, conv, again, the + * input (or its 1x1 shortcut) added. */ +struct ARes { + int64_t cin = 0, cout = 0; + rad_weight w1 = 0, b1 = 0, w2 = 0, b2 = 0, ws = 0, bs = 0; + rad_op op_n1 = 0, op_c1 = 0, op_n2 = 0, op_c2 = 0, op_sc = 0, op_add = 0; +}; + +/* A vocoder convolution and an anti-aliased SnakeBeta (f32). */ +struct VConv { + rad_weight w = 0, b = 0; + rad_op op = 0; +}; +struct VAct { + rad_weight alpha = 0, beta = 0, up = 0, down = 0; + rad_op op = 0; +}; +struct VUnit { + VAct a1{}, a2{}; + VConv c1{}, c2{}; +}; +struct VStage { + int64_t ch = 0, rate = 0, k = 0; + VConv up{}; + VUnit u[3][3]; /* resnet j, dilation d */ + rad_op op_cu = 0, op_sum = 0, op_avg = 0; +}; +/* A vocoder (the base one or the bandwidth extender's). */ +struct Voc { + int64_t in = 0, hidden = 0, out = 0, mult = 1; + std::vector rates, ks, rk; + VConv cin{}, cout{}; + VAct act{}; + std::vector st; + rad_op op_cu0 = 0; + rad_buf in_buf = 0, wav = 0; /* its input [rows, 128] and output [rows, 2], f32 */ + std::vector cu, h, avg, t1, t2, amp[3]; +}; + +/* A latent upsampler residual block: conv, GroupNorm, SiLU, conv, GroupNorm, the residual added, + * SiLU. */ +struct URes { + rad_weight c1w = 0, c1b = 0, n1w = 0, n1b = 0, c2w = 0, c2b = 0, n2w = 0, n2b = 0; + rad_op op_c1 = 0, op_n1 = 0, op_c2 = 0, op_n2 = 0, op_add = 0, op_act = 0; +}; + +/* The diffusion decoder's neighbourhood-attention block: a deterministic stage's (pre-norm) or a + * diffusion block's (the latent context added, its norms modulated by the shared table plus its + * own). */ +struct DdBlock { + int64_t C = 0, ff = 0, kt = 0, kh = 0, kw = 0, chunk = 0; + int slot = 0; /* the q|k|v and gate|up buffers of its width */ + rad_weight w_n1 = 0, w_n2 = 0, w_nq = 0, w_nk = 0, w_o = 0, b_o = 0, w_gu = 0, w_down = 0; + rad_weight w_ctx = 0, b_ctx = 0, w_sst = 0; + rad_op op_n1 = 0, op_rope = 0, op_attn = 0, op_o = 0; + rad_op op_n2 = 0, op_gu = 0, op_act = 0, op_down = 0, op_add2 = 0; + rad_op op_ctx = 0, op_mod = 0; + /* q|k|v of a group of heads as one weight (the three projections' rows of the group), and its + * gemm into the q|k|v buffer: every head in one group, or in the diffusion stage one a group. */ + std::vector w_qkvh, b_qkvh; + std::vector op_qkvh; +}; +/* A deterministic stage: its blocks, then its pixel-shuffle upsample (a linear, then depth to + * space; the last stage's keeps the duplicate leading frame on a tile that does not start the + * video). */ +struct DdStage { + int64_t C = 0, cout = 0, st = 1, sh = 1, sw = 1; + std::vector blk; + rad_weight w_up = 0, b_up = 0; + rad_op op_proj = 0, op_d2s = 0, op_d2s_keep = 0, op_geom = 0, op_pos = 0; + rad_buf geom = 0; /* PERSIST: the stage's volume (its input grid) */ +}; + +/* Weight groups (movement units) by network. */ +enum : int { + kGrpConn = 1000, + kGrpTemb = 1100, + kGrpDit = 2000, + kGrpVae = 3000, + kGrpVenc = 3100, + kGrpAudio = 3200, + kGrpVoc = 3300, + kGrpUps = 3400, + kGrpDur = 1200, + kGrpDdec = 3500, +}; + +struct Model { + Names nm{""}; + Geom gt{}, gd{}; /* text encoder and connectors (prompt rows), DiT (step rows) */ + int64_t maxS = 0, maxA = 0, maxPpf = 0, maxVox = 0; + std::vector rungs, refine; + + /* ---- the text encoder: Gemma 4's language model, every layer's output kept */ + int64_t tC = 0, tL = 0, tFF = 0, tRows = 0; + double teps = 1e-6; + rad_weight w_tok = 0, w_tnorm = 0; + rad_op op_embed = 0, op_keep0 = 0, op_tnorm = 0; + rad_buf b_tx = 0, b_th2 = 0, b_tgu = 0, b_stack = 0; + Act a_th{}, a_tffn{}; + TeClass cls[2]; /* sliding, full */ + std::vector te; + + /* ---- the connectors */ + Conn cv{}, ca{}; + rad_buf b_rows = 0; /* i32 {0, kTextRows, 2 kTextRows} */ + rad_buf b_rpos = 0; /* i32 [2 kTextRows]: a connector row's index in its prompt */ + rad_buf b_zero = 0; /* bf16 zeros, one row of the widest connector */ + rad_op op_rows = 0, op_rpos = 0, op_zero = 0; + + /* ---- the duration head: the length the prompt implies, off both connectors' output */ + bool dur = false; + int64_t dP = 0; /* the pooler's width */ + rad_weight dw_vp = 0, dw_vpb = 0, dw_vemb = 0, dw_ap = 0, dw_apb = 0, dw_aemb = 0, dw_qt = 0; + rad_weight dw_q = 0, dw_qb = 0, dw_k = 0, dw_kb = 0, dw_v = 0, dw_vb = 0, dw_o = 0, dw_ob = 0; + rad_weight dw_h = 0, dw_hb = 0, dw_out = 0, dw_outb = 0; + rad_op op_dvp = 0, op_dap = 0, op_dvemb = 0, op_daemb = 0, op_dq0 = 0, op_dq = 0, op_dk = 0; + rad_op op_dv = 0, op_dcu = 0, op_dcuk = 0, op_dattn = 0, op_do = 0, op_dh = 0, op_dout = 0; + rad_op op_dlog = 0; + rad_buf b_dtok = 0, b_dk = 0, b_dv = 0, b_dq0 = 0, b_dq = 0, b_dat = 0, b_do = 0, b_dh = 0; + rad_buf b_dl = 0, b_dcu = 0, b_dcuk = 0, b_dur = 0; + + /* ---- the DiT */ + int64_t D = 0, Da = 0, H = 0, Ha = 0, hd = 0, hda = 0, Dc = 0, ffv = 0, ffa = 0, nb = 0; + double eps = 1e-6; + /* the step's timestep inputs {0, sigma}, their sinusoids, the eight modulation MLPs */ + rad_buf b_tin = 0, b_tsin = 0; + rad_op op_tin0 = 0, op_tin1 = 0, op_tsin = 0; + Ada ad_v{}, ad_a{}, ad_p{}, ad_pa{}, ad_cv{}, ad_cvg{}, ad_ca{}, ad_cag{}; + /* the step's tables (PERSIST): every block's rows, then the output norms' */ + rad_buf b_mv = 0, b_ma = 0, b_mp = 0, b_mpa = 0, b_mcv = 0, b_mcvg = 0, b_mca = 0, b_mcag = 0; + rad_buf b_fv = 0, b_fa = 0; + rad_weight w_fv = 0, w_fa = 0; + rad_op op_fv = 0, op_fa = 0; + /* the lanes (PERSIST): both latents and the clean first latent frame */ + rad_buf b_vstate = 0, b_astate = 0, b_first = 0; + rad_op op_rnd_v = 0, op_rnd_a = 0, op_keep_first = 0; + /* an evaluation */ + Act a_lv{}, a_la{}; + Lin pin_v{}, pin_a{}, pout_v{}, pout_a{}; + rad_op op_lv = 0, op_la = 0; + rad_buf b_hv = 0, b_ha = 0, b_qkvv = 0, b_qkva = 0, b_gv = 0, b_ga = 0, b_ov = 0, b_oa = 0; + rad_buf b_qv = 0, b_qa = 0, b_kvtv = 0, b_kvta = 0; + rad_buf b_qxv = 0, b_qxa = 0, b_kvxv = 0, b_kvxa = 0, b_gxv = 0, b_gxa = 0; + rad_buf b_upv = 0, b_upa = 0; + Act a_hv{}, a_ha{}, a_ctxv{}, a_ctxa{}, a_nv{}, a_nv2{}, a_na{}, a_na2{}; + Act a_aov{}, a_aoa{}, a_xv{}, a_xa{}, a_ffv{}, a_ffa{}, a_fv{}, a_fa{}; + std::vector dit; + rad_op op_fnv = 0, op_fna = 0; + rad_buf b_vel_v[kPasses] = {}, b_vel_a[kPasses] = {}; /* PERSIST: each evaluation's */ + rad_buf b_gst = 0; + rad_op op_gv = 0, op_ga = 0; + + /* ---- the video VAE's decoder: the whole video, a tile at a time, into the lane's tile + * store; each chunk's frames stitched to bytes. A latent frame f is pixel frames + * vAt f + vBt; a latent vAhw patches a side. */ + int64_t vC0 = 0, vAt = 1, vBt = 0, vAhw = 1, maxTiles = 0, maxStore = 0, maxSide = 0; + rad_weight vd_mean = 0, vd_std = 0, w_vcin = 0, b_vcin = 0, w_vcout = 0, b_vcout = 0; + rad_op op_vlat = 0, op_vden = 0, op_vcin = 0, op_vnout = 0, op_vcout = 0; + rad_op op_vgrid1 = 0, op_vgrid = 0, op_vcrop = 0, op_vf0 = 0, op_vst1 = 0, op_vst = 0; + std::vector vmid; + std::vector vup; + rad_buf b_vlat = 0, b_vtlat = 0, b_va = 0, b_vb = 0, b_vc = 0, b_vtiles = 0, b_frames = 0; + rad_buf b_vgrid = 0, b_vf0 = 0; + + /* ---- its encoder: a first frame into the lane's clean first latent frame */ + bool venc = false; + int64_t eC0 = 0, eCout = 0; + rad_weight w_ecin = 0, b_ecin = 0, w_ecout = 0, b_ecout = 0; + rad_op op_epatch = 0, op_ecin = 0, op_enout = 0, op_ecout = 0, op_enorm = 0, op_ef32 = 0; + rad_op op_egeomL = 0; + std::vector vdown; + std::vector emid; + rad_buf b_egeomL = 0, b_epatch = 0, b_ea = 0, b_eb = 0, b_ec = 0, b_eout = 0, b_elat = 0; + + /* ---- the audio VAE's decoder and the vocoders */ + int64_t aC0 = 0; + std::string a_mean, a_std; + rad_op op_aden = 0, op_acast = 0, op_aunpack = 0, op_acin = 0, op_anout = 0; + rad_op op_acout[2] = {}, op_amel = 0; + rad_weight w_acin = 0, b_acin = 0, w_acout[2] = {}, b_acout[2] = {}, w_amean = 0, w_astd = 0; + ARes amid[2]; + std::vector> aup; /* level 2, 1, 0 */ + std::vector aups; /* the upsamples after levels 2 and 1 */ + std::vector aups_cp; /* each upsample's rows past the first, back */ + std::vector alev_c; + rad_buf b_aden = 0, b_alat = 0, b_aimg = 0, b_aa = 0, b_ab = 0, b_ac = 0, b_as = 0; + rad_buf b_amel16 = 0, b_amel = 0; + Voc voc{}, bwe{}; + rad_weight w_basis = 0, w_melb = 0; + rad_op op_stft = 0, op_bwe = 0, op_bmel = 0, op_tail = 0; + rad_buf b_bmel16 = 0, b_bmel = 0, b_audio = 0; + + /* ---- the latent upsampler */ + bool ups = false; + int64_t uC = 0; + rad_weight u_cinw = 0, u_cinb = 0, u_ninw = 0, u_ninb = 0, u_upw = 0, u_upb = 0; + rad_weight u_coutw = 0, u_coutb = 0; + rad_op op_uden = 0, op_ucast = 0, op_ucin = 0, op_unin = 0, op_uup = 0, op_ud2s = 0; + rad_op op_ucout = 0, op_unorm = 0, op_uf32 = 0, op_ukeep = 0, op_ufirst = 0; + rad_op op_urnv = 0, op_urna = 0; + std::vector u_pre, u_post; + rad_buf b_ua = 0, b_ub = 0, b_uc = 0, b_ust = 0, b_uin = 0, b_uout = 0, b_uden = 0; + + /* ---- the diffusion decoder (diffusion_decoder/): deterministic stages 0..2 over the whole + * latent into the feature volume, then per tile stage 3 and the one-step diffusion stage into + * the tile store */ + bool ddec = false; + std::vector dst; /* the four deterministic stages */ + std::vector dblk; /* the diffusion blocks */ + int64_t dV0 = 0, dV1 = 0, dV2 = 0, dV3 = 0, dV4 = 0, dV5 = 0, dTiles = 0; + rad_weight dw_cin = 0, db_cin = 0, dw_xin = 0, db_xin = 0, dw_nout = 0, dw_cout = 0, db_cout = 0; + rad_weight dw_t1 = 0, db_t1 = 0, dw_t2 = 0, db_t2 = 0, dw_ad = 0, db_ad = 0; + rad_op op_dpad = 0, op_dcin = 0, op_dtin = 0, op_dtsin = 0, op_dt1 = 0, op_dts = 0, op_dt2 = 0; + rad_op op_das = 0, op_dad = 0, op_ddcu = 0, op_dsig = 0, op_dtgeom = 0, op_dgrid = 0; + rad_op op_dcrop = 0, op_dpos4 = 0, op_dg5[4] = {}, op_dpos5 = 0, op_dz = 0, op_dxcast = 0; + rad_op op_dxin = 0, op_dnout = 0, op_ddout = 0, op_dst = 0; + std::vector op_dnoise; /* each tile's noise: its own stream */ + rad_buf b_dz = 0, b_dx = 0, b_dfeat = 0, b_d4 = 0, b_ddh = 0, b_dctx = 0, b_dn = 0; + rad_buf b_dqkv[4] = {}, b_dg[4] = {}; /* per width 2048, 1024, 512, 256: q|k|v, gate|up */ + rad_buf b_dao = 0; /* the diffusion stage's attention, its heads side by side */ + rad_buf b_da = 0, b_dmo = 0, b_dpos = 0, b_dxt = 0, b_dxb = 0, b_dtin = 0; + rad_buf b_dtsin = 0, b_dth = 0, b_dths = 0, b_dtemb = 0, b_dtes = 0, b_dmod = 0, b_dbmod = 0; + rad_buf b_ddcu = 0, b_dsig = 0, b_dtg = 0, b_dgrid = 0, b_dg5 = 0; +}; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== check_format */ +static long long tgeti(const RadModelMeta* m, const char* key, long long def) { + char k[160]; + std::snprintf(k, sizeof k, "text_config.%s", key); + return rad_meta_geti(m, k, rad_meta_geti(m, key, def)); +} +static double tgetf(const RadModelMeta* m, const char* key, double def) { + char k[160]; + std::snprintf(k, sizeof k, "text_config.%s", key); + return rad_meta_getf(m, k, rad_meta_getf(m, key, def)); +} +static const char* tgets(const RadModelMeta* m, const char* key, const char* def) { + char k[160]; + std::snprintf(k, sizeof k, "text_config.%s", key); + return rad_meta_gets(m, k, rad_meta_gets(m, key, def)); +} + +/* What this plugin runs: LTX-2.5's components (LTX-2.3's are the same graph). Anything else is + * refused by name rather than run wrong. */ +static int check_format(const RadModelMeta* meta) { + const char* cls = rad_meta_gets(meta, "pipeline._class_name", ""); + if (std::strcmp(cls, "LTX2Pipeline") != 0 && std::strcmp(cls, "LTX2ImageToVideoPipeline") != 0) { + fprintf(stderr, "radiance: ltx2: the container's pipeline is '%s', not LTX2Pipeline\n", cls); + return RAD_E_UNSUPPORTED; + } + auto is = [&](const char* k, long long v) { return rad_meta_geti(meta, k, -9999) == v; }; + auto str = [&](const char* k, const char* v) { + return !std::strcmp(rad_meta_gets(meta, k, ""), v); + }; + struct Need { bool ok; const char* what; }; + const Need need[] = { + { is("transformer.patch_size", 1) && is("transformer.patch_size_t", 1) && + is("transformer.in_channels", kC) && is("transformer.out_channels", kC) && + is("transformer.audio_in_channels", kAudioC) && is("transformer.audio_patch_size", 1), + "1 x 1 x 1 patches of 128-channel video and audio latents" }, + { str("transformer.rope_type", "split") && is("transformer.gated_attn", 1) && + is("transformer.audio_gated_attn", 1) && is("transformer.cross_attn_mod", 1) && + is("transformer.audio_cross_attn_mod", 1) && is("transformer.perturbed_attn", 1) && + is("transformer.use_prompt_embeddings", 0) && is("transformer.use_prompt_adaln_single", 1), + "the 2.3 / 2.5 DiT (split rotary, gated attention, prompt modulation)" }, + { is("transformer.causal_offset", 1) && is("transformer.pos_embed_max_pos", 20) && + is("transformer.audio_pos_embed_max_pos", 20) && is("transformer.base_height", 2048) && + is("transformer.base_width", 2048) && is("transformer.audio_scale_factor", 4) && + is("transformer.audio_hop_length", kMelHop) && + is("transformer.audio_sampling_rate", kVocRate) && + str("transformer.vae_scale_factors", "8 32 32") && + is("transformer.timestep_scale_multiplier", 1000) && + is("transformer.cross_attn_timestep_scale_multiplier", 1000), + "the released rotary coordinates and timestep scales" }, + { is("connectors.per_modality_projections", 1) && str("connectors.rope_type", "split") && + is("connectors.video_gated_attn", 1) && is("connectors.audio_gated_attn", 1) && + is("connectors.connector_rope_base_seq_len", 4096), + "per-modality connectors with gated attention and a split rotary" }, + { is("vae.patch_size", kPix) && is("vae.patch_size_t", 1) && is("vae.latent_channels", kC) && + is("vae.timestep_conditioning", 0) && is("vae.decoder_causal", 0) && + is("vae.encoder_causal", 1) && str("vae.upsample_residual", "0 0 0 0") && + str("vae.decoder_inject_noise", "0 0 0 0 0") && + str("vae.decoder_spatial_padding_mode", "zeros") && + rad_meta_getf(meta, "vae.scaling_factor", 1.0) == 1.0, + "the 2.3 / 2.5 video VAE (4 x 4 patches, no timestep conditioning)" }, + { str("audio_vae.norm_type", "pixel") && str("audio_vae.causality_axis", "height") && + is("audio_vae.latent_channels", kLatCh) && is("audio_vae.mel_bins", kMel) && + is("audio_vae.mid_block_add_attention", 0) && is("audio_vae.output_channels", 2) && + is("audio_vae.base_channels", kAudioC) && + !rad_meta_gets(meta, "audio_vae.attn_resolutions", nullptr), + "the audio VAE (pixel norms, causal in time, 8 x 16 latents, no attention)" }, + { str("vocoder.act_fn", "snakebeta") && is("vocoder.antialias", 1) && + is("vocoder.antialias_ratio", 2) && is("vocoder.antialias_kernel_size", 12) && + is("vocoder.final_bias", 0) && !rad_meta_gets(meta, "vocoder.final_act_fn", nullptr) && + str("vocoder.bwe_act_fn", "snakebeta") && is("vocoder.bwe_antialias", 1) && + is("vocoder.bwe_final_bias", 0) && !rad_meta_gets(meta, "vocoder.bwe_final_act_fn", nullptr) && + is("vocoder.filter_length", 512) && is("vocoder.hop_length", 80) && + is("vocoder.window_length", 512) && is("vocoder.num_mel_channels", kMel) && + is("vocoder.input_sampling_rate", kVocRate) && + is("vocoder.output_sampling_rate", kRate) && is("vocoder.in_channels", 2 * kMel) && + is("vocoder.out_channels", 2) && is("vocoder.bwe_in_channels", 2 * kMel) && + is("vocoder.bwe_out_channels", 2), + "the vocoder with bandwidth extension (SnakeBeta, 16 to 48 kHz)" }, + }; + for (const Need& n : need) + if (!n.ok) { + fprintf(stderr, "radiance: ltx2: this plugin runs %s; the container's config differs\n", + n.what); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== the text encoder */ +/* Gemma 4's language model over both prompts at once (one sequence each, causal), at positions + * that end each prompt where a 1024-token left-padded sequence does (RadVideoGenDecl:: + * text_left_pad). Every output the connectors read lands in the stack, [T, C (L + 1)] read as + * [T (L + 1), C]: the embeddings, each layer's output but the last, and the last's final norm. */ +static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = m.tRows, C = m.tC, L = m.tL; + const int acc = RAD_ACCESS_PER_REQUEST; + const char* pre = "model.language_model"; + const double eps = m.teps; + + std::vector full; + RAD_ARCH_TRY(parse_layer_kinds("ltx2", tgets(meta, "layer_types", ""), { "full_attention" }, + "sliding_attention", &full)); + if ((int64_t)full.size() != L) { + fprintf(stderr, "radiance: ltx2: the text encoder names %zu layer types for %lld layers\n", + full.size(), (long long)L); + return RAD_E_INVAL; + } + const int64_t nh = tgeti(meta, "num_attention_heads", 0); + const int64_t hd_s = tgeti(meta, "head_dim", 0); + const int64_t kv_s = tgeti(meta, "num_key_value_heads", 0); + const int64_t hd_g0 = tgeti(meta, "global_head_dim", hd_s); + const int64_t kv_g0 = tgeti(meta, "num_global_key_value_heads", kv_s); + const double th_s = tgetf(meta, "rope_parameters.sliding_attention.rope_theta", 0.0); + const double th_g = tgetf(meta, "rope_parameters.full_attention.rope_theta", 0.0); + double prf = tgetf(meta, "rope_parameters.full_attention.partial_rotary_factor", 1.0); + const char* gtype = tgets(meta, "rope_parameters.full_attention.rope_type", "default"); + const int64_t win = tgeti(meta, "sliding_window", 0); + const long long k_eq_v = tgeti(meta, "attention_k_eq_v", 0); + if (nh <= 0 || hd_s <= 0 || kv_s <= 0 || !(th_s > 0.0) || !(th_g > 0.0) || + tgeti(meta, "num_kv_shared_layers", 0) != 0 || tgeti(meta, "attention_bias", 0) != 0 || + std::strcmp(tgets(meta, "hidden_activation", ""), "gelu_pytorch_tanh") != 0 || + tgeti(meta, "use_double_wide_mlp", 0) != 0 || + (std::strcmp(gtype, "proportional") && std::strcmp(gtype, "default"))) { + fprintf(stderr, "radiance: ltx2: the text encoder is not Gemma 4's dense language model " + "(no KV sharing, no biases, a tanh GELU, default or proportional rotary)\n"); + return RAD_E_UNSUPPORTED; + } + if (win > 0 && win < kTextRows) { + fprintf(stderr, "radiance: ltx2: a %lld-token sliding window shorter than the %d-token " + "prompt; this plugin runs the window as full attention\n", (long long)win, + (int)kTextRows); + return RAD_E_UNSUPPORTED; + } + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), nm.ckpt("%s.embed_tokens.weight", pre))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, C }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.w_tnorm = wcopy(b, nm.f("te.norm.weight"), nm.ckpt("%s.norm.weight", pre), RAD_BF16, { C }, acc, + (int)L); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, C }); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, C }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * m.tFF }); + m.b_stack = decl_b(b, nm.f("te.stack"), RAD_BF16, { T, C * (L + 1) }); + RAD_ARCH_TRY(m.a_th.declare(b, nm, g, "te.h", T, C)); + RAD_ARCH_TRY(m.a_tffn.declare(b, nm, g, "te.ffn", T, m.tFF)); + if (!m.w_tok || !m.w_tnorm) return RAD_E_INVAL; + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", C), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0), + RAD_F64("mult", std::sqrt((double)C))), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + m.op_keep0 = cast_op(b, T, C, "bf16", "bf16", m.b_tx, m.b_stack); + + /* Each class's rows at its own head geometry. */ + for (int k = 0; k < 2; ++k) { + int64_t qd = 0, kvd = 0; + for (int64_t l = 0; l < L; ++l) { + if ((full[(size_t)l] != 0) != (k == 1)) continue; + const int64_t hd = tgeti(meta, nm.f("per_layer_config.%lld.head_dim", (long long)l), + k ? hd_g0 : hd_s); + const int64_t kv = tgeti(meta, nm.f("per_layer_config.%lld.num_key_value_heads", + (long long)l), k ? kv_g0 : kv_s); + qd = std::max(qd, nh * hd); + kvd = std::max(kvd, kv * hd); + } + if (!qd) continue; + TeClass& K = m.cls[k]; + K.q = decl_b(b, nm.f("te.q%d", k), RAD_BF16, { T, qd }); + K.k = decl_b(b, nm.f("te.k%d", k), RAD_BF16, { T, kvd }); + K.v = decl_b(b, nm.f("te.v%d", k), RAD_BF16, { T, kvd }); + RAD_ARCH_TRY(K.o.declare(b, nm, g, nm.f("te.attn%d", k), T, qd)); + } + + m.te.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + TeLayer& Y = m.te[(size_t)l]; + const int li = (int)l; + Y.full = full[(size_t)l] != 0; + Y.nh = nh; + Y.hd = tgeti(meta, nm.f("per_layer_config.%d.head_dim", li), Y.full ? hd_g0 : hd_s); + Y.nkv = tgeti(meta, nm.f("per_layer_config.%d.num_key_value_heads", li), + Y.full ? kv_g0 : kv_s); + Y.theta = Y.full ? th_g : th_s; + Y.rot = Y.full ? (int64_t)(Y.hd * prf + 0.5) : Y.hd; + Y.v_from_k = Y.full && k_eq_v != 0; + if (Y.nkv <= 0 || nh % Y.nkv || Y.rot <= 0 || Y.rot > Y.hd || (Y.rot & 1)) return RAD_E_INVAL; + const TeClass& K = m.cls[Y.full ? 1 : 0]; + const int64_t qd = nh * Y.hd, kvd = Y.nkv * Y.hd; + const char* lp = nm.ckpt("%s.layers.%d", pre, li); + auto norm_w = [&](const char* what) { + return wcopy(b, nm.f("te.blk.%d.%s.weight", li, what), nm.ckpt("%s.%s.weight", lp, what), + RAD_BF16, { C }, acc, li); + }; + Y.w_in = norm_w("input_layernorm"); + Y.w_pa = norm_w("post_attention_layernorm"); + Y.w_pf = norm_w("pre_feedforward_layernorm"); + Y.w_ff = norm_w("post_feedforward_layernorm"); + Y.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", li), nm.ckpt("%s.self_attn.q_norm.weight", lp), + RAD_BF16, { Y.hd }, acc, li); + Y.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", li), nm.ckpt("%s.self_attn.k_norm.weight", lp), + RAD_BF16, { Y.hd }, acc, li); + Y.w_sc = wcopy(b, nm.f("te.blk.%d.layer_scalar", li), nm.ckpt("%s.layer_scalar", lp), RAD_BF16, + { 1 }, acc, li); + if (!Y.w_in || !Y.w_pa || !Y.w_pf || !Y.w_ff || !Y.w_qn || !Y.w_kn || !Y.w_sc) + return RAD_E_INVAL; + Y.op_in = rms_op(b, T, C, eps, Y.w_in, m.b_tx, m.a_th.a.x); + auto lin = [&](Lin& Z, const char* name, const char* src, int64_t N, int64_t Kd, const Act& in, + rad_buf y) { + return Z.declare(b, nm, g, nm.f("te.blk.%d.%s", li, name), + { nm.ckpt("%s.%s.weight", lp, src) }, {}, {}, N, Kd, acc, li, in, y, T); + }; + RAD_ARCH_TRY(lin(Y.q, "attn_q", "self_attn.q_proj", qd, C, m.a_th, K.q)); + RAD_ARCH_TRY(lin(Y.k, "attn_k", "self_attn.k_proj", kvd, C, m.a_th, K.k)); + if (!Y.v_from_k) RAD_ARCH_TRY(lin(Y.v, "attn_v", "self_attn.v_proj", kvd, C, m.a_th, K.v)); + /* v's weightless RMS norm, from k's raw rows when the class reads v from k (before k's + * own norm rewrites them); q and k per head with their gains; then the rotaries. */ + Y.op_vn = rw(b, RAD_OP(b, "rmsnorm_p", + RAD_PARAMS(RAD_RANGE("M", 1, T * Y.nkv), RAD_INT("n", Y.hd), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { Y.v_from_k ? K.k : K.v }, { K.v }); + Y.op_qn = rms_op(b, T * nh, Y.hd, eps, Y.w_qn, K.q, K.q); + Y.op_kn = rms_op(b, T * Y.nkv, Y.hd, eps, Y.w_kn, K.k, K.k); + auto rope = [&](int64_t heads, rad_buf x) { + return rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", Y.hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", 0), + RAD_F64("theta", Y.theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", Y.rot), + RAD_STR("ladder", + Y.full && !std::strcmp(gtype, "proportional") + ? "head" : "rotary")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + Y.op_rq = rope(nh, K.q); + Y.op_rk = rope(Y.nkv, K.k); + /* Gemma 4 scores q.k without 1 / sqrt(head_dim): the q and k norms' gains carry it. */ + Y.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", Y.hd), + RAD_INT("gqa", nh / Y.nkv), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0), + RAD_INT("max_seqlen", kTextRows)), + RAD_NOWEIGHTS), + { K.q, K.k, K.v }, { K.o.a.x }); + RAD_ARCH_TRY(lin(Y.o, "attn_output", "self_attn.o_proj", C, qd, K.o, m.b_th2)); + Y.op_pa = rms_op(b, T, C, eps, Y.w_pa, m.b_th2, m.b_th2); + Y.op_add1 = add_op(b, T, C, "bf16", m.b_tx, m.b_th2, m.b_tx); + Y.op_pf = rms_op(b, T, C, eps, Y.w_pf, m.b_tx, m.a_th.a.x); + { + const char* gw = nm.f("te.blk.%d.ffn_gate_up", li); + RAD_ARCH_TRY(Y.gu.declare(b, nm, g, gw, { nm.ckpt("%s.mlp.gate_proj.weight", lp), + nm.ckpt("%s.mlp.up_proj.weight", lp) }, + {}, { m.tFF, m.tFF }, 2 * m.tFF, C, acc, li, m.a_th, m.b_tgu, T)); + } + Y.op_act = rw(b, RAD_OP(b, "gelu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", m.tFF), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tgu }, { m.a_tffn.a.x }); + RAD_ARCH_TRY(lin(Y.down, "ffn_down", "mlp.down_proj", C, m.tFF, m.a_tffn, m.b_th2)); + Y.op_ff = rms_op(b, T, C, eps, Y.w_ff, m.b_th2, m.b_th2); + Y.op_add2 = add_op(b, T, C, "bf16", m.b_tx, m.b_th2, m.b_tx); + Y.op_sc = rw(b, RAD_OP(b, "scale", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", C), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(Y.w_sc)), + { m.b_tx }, { m.b_tx }); + /* Into the stack: a layer's output but the last's, which is normed first. */ + if (l + 1 < L) Y.op_keep = cast_op(b, T, C, "bf16", "bf16", m.b_tx, m.b_stack); + if (!Y.op_in || !Y.op_vn || !Y.op_qn || !Y.op_kn || !Y.op_rq || !Y.op_rk || !Y.op_attn || + !Y.op_pa || !Y.op_add1 || !Y.op_pf || !Y.op_act || !Y.op_ff || !Y.op_add2 || !Y.op_sc || + (l + 1 < L && !Y.op_keep)) + return RAD_E_INVAL; + } + m.op_tnorm = rms_op(b, T, C, eps, m.w_tnorm, m.b_tx, m.b_stack); + return m.op_embed && m.op_keep0 && m.op_tnorm ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== attention */ +/* The rotary an attention's q and k take: LTX-2's split rotary over `n_dims` coordinates of a + * `dim`-wide row, each coordinate over its `max`; none when n_dims is 0. */ +struct Rope { + int64_t n_dims = 0, dim = 0; + const char* max = ""; +}; + +/* An attention's weights and ops (LTX2Attention): for a self-attention q|k|v from `xin` into `bq` + * [rows, 3 inner]; for a cross-attention q from `xin` into `bq` [rows_q, inner] and k|v from + * `kvin` into `bkv` [rows_k, 2 inner]. The gate's logits into `bg`, the attention into `ao`, the + * output projection into `y` [rows_q, odim]. Every linear has a bias. A self-attention also gets + * the value copy spatio-temporal guidance bypasses it with. */ +static int attn_declare(RadBuilder* b, Model& m, const Geom& g, Attn& A, const char* dn, + const char* src, int64_t H, int64_t hd, int64_t qdim, int64_t kvdim, + int64_t odim, bool self, const Act& xin, const Act* kvin, rad_buf bq, + rad_buf bkv, rad_buf bg, const Act& ao, rad_buf y, int64_t rows_q, + int64_t rows_k, int acc, int group, const Rope& rope, double eps) { + Names& nm = m.nm; + A.H = H; + A.hd = hd; + A.inner = H * hd; + const int64_t in = A.inner; + auto w = [&](const char* name) { return nm.ckpt("%s.%s.weight", src, name); }; + auto bs = [&](const char* name) { return nm.ckpt("%s.%s.bias", src, name); }; + if (self) + RAD_ARCH_TRY(A.qkv.declare(b, nm, g, nm.f("%s.qkv", dn), { w("to_q"), w("to_k"), w("to_v") }, + { bs("to_q"), bs("to_k"), bs("to_v") }, { in, in, in }, 3 * in, + qdim, acc, group, xin, bq, rows_q)); + else { + RAD_ARCH_TRY(A.qkv.declare(b, nm, g, nm.f("%s.q", dn), { w("to_q") }, { bs("to_q") }, {}, in, + qdim, acc, group, xin, bq, rows_q)); + RAD_ARCH_TRY(A.kv.declare(b, nm, g, nm.f("%s.kv", dn), { w("to_k"), w("to_v") }, + { bs("to_k"), bs("to_v") }, { in, in }, 2 * in, kvdim, acc, group, + *kvin, bkv, rows_k)); + } + RAD_ARCH_TRY(A.gate.declare(b, nm, g, nm.f("%s.gate", dn), { w("to_gate_logits") }, + { bs("to_gate_logits") }, {}, H, qdim, acc, group, xin, bg, rows_q, + true)); + RAD_ARCH_TRY(A.out.declare(b, nm, g, nm.f("%s.out", dn), { w("to_out.0") }, { bs("to_out.0") }, {}, + odim, in, acc, group, ao, y, rows_q)); + A.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), w("norm_q"), RAD_BF16, { in }, acc, group); + A.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), w("norm_k"), RAD_BF16, { in }, acc, group); + if (!A.w_qn || !A.w_kn) return RAD_E_INVAL; + const rad_buf kb = self ? bq : bkv; + A.op_qn = rms_op(b, rows_q, in, eps, A.w_qn, bq, bq); + A.op_kn = rms_op(b, rows_k, in, eps, A.w_kn, kb, kb); + if (rope.n_dims) { + auto rop = [&](int64_t rows, rad_buf x) { + return rw(b, RAD_OP(b, "rope_split", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_head", H), + RAD_INT("head_dim", hd), RAD_INT("dim", rope.dim), + RAD_INT("n_dims", rope.n_dims), RAD_F64("theta", 10000.0), + RAD_STR("max", rope.max), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + A.op_rq = rop(rows_q, bq); + A.op_rk = rop(rows_k, kb); + if (!A.op_rq || !A.op_rk) return RAD_E_INVAL; + } + const double sc = 1.0 / std::sqrt((double)hd); + if (self) + A.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, rows_q), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", sc)), + RAD_NOWEIGHTS), + { bq }, { ao.a.x }); + else + A.op_attn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, rows_q), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", sc)), + RAD_NOWEIGHTS), + { bq, bkv }, { ao.a.x }); + A.op_hg = rw(b, RAD_OP(b, "head_gate", + RAD_PARAMS(RAD_RANGE("M", 1, rows_q), RAD_INT("n_head", H), + RAD_INT("head_dim", hd), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { bg, ao.a.x }, { ao.a.x }); + if (self) A.op_v = cast_op(b, rows_q, in, "bf16", "bf16", bq, ao.a.x); + return A.op_qn && A.op_kn && A.op_attn && A.op_hg && (!self || A.op_v) ? RAD_OK : RAD_E_INVAL; +} + +/* q and k normed and turned, the attention, the gate: the attention part both kinds share once + * their projections ran. `cu` and (cross) `cu_k` bound the query and key rows; `pq` and `pk` the + * rotary coordinates. */ +static void attn_core(RadCtx* c, const Attn& A, bool self, rad_buf bq, rad_buf bkv, rad_buf bg, + const Act& ao, int64_t nq, int64_t nk, const RadOperand& cu, + const RadOperand& cu_k, const RadOperand& pq, const RadOperand& pk) { + const int64_t in = A.inner; + const RadOperand q = bcol(bq, 0, in, nq); + const RadOperand k = self ? bcol(bq, in, in, nk) : bcol(bkv, 0, in, nk); + const RadOperand v = self ? bcol(bq, 2 * in, in, nk) : bcol(bkv, in, in, nk); + RAD_ISSUE_N(c, A.op_qn, nq, q, RAD_W(A.w_qn), q); + RAD_ISSUE_N(c, A.op_kn, nk, k, RAD_W(A.w_kn), k); + if (A.op_rq) { + RAD_ISSUE_N(c, A.op_rq, nq, q, pq); + RAD_ISSUE_N(c, A.op_rk, nk, k, pk); + } + if (self) RAD_ISSUE_N(c, A.op_attn, nq, q, k, v, cu, brows(ao.a.x, nq)); + else RAD_ISSUE_N(c, A.op_attn, nq, q, k, v, cu, cu_k, brows(ao.a.x, nq)); + RAD_ISSUE_N(c, A.op_hg, nq, brows(bg, nq), brows(ao.a.x, nq)); +} + +/* ================================================================== the connectors */ +/* A modality's connector: the normed stack scaled to its width and projected, the registers in + * the rows past the prompt's tokens, eight blocks over 1024 rows a prompt, the final norm into the + * lane's text rows. */ +static int declare_conn(RadBuilder* b, const RadModelMeta* meta, Model& m, Conn& K, const char* md) { + Names& nm = m.nm; + const Geom& g = m.gt; + const int64_t T = m.tRows, C = m.tC, Lp = m.tL + 1, R = 2 * (int64_t)kTextRows; + const int acc = RAD_ACCESS_PER_REQUEST; + const int gx = kGrpConn + (md[0] == 'v' ? 0 : 50); + const double eps = 1e-6; + K.H = rad_meta_geti(meta, nm.f("connectors.%s_connector_num_attention_heads", md), 0); + K.hd = rad_meta_geti(meta, nm.f("connectors.%s_connector_attention_head_dim", md), 0); + K.D = rad_meta_geti(meta, nm.f("connectors.%s_hidden_dim", md), 0); + K.ff = 4 * K.D; + const int64_t layers = rad_meta_geti(meta, nm.f("connectors.%s_connector_num_layers", md), 0); + const int64_t regs = rad_meta_geti(meta, nm.f("connectors.%s_connector_num_learnable_registers", md), + 0); + if (K.H <= 0 || K.hd <= 0 || K.D != K.H * K.hd || layers <= 0 || regs <= 0 || + kTextRows % regs || kTextRows / regs > 8 || + rad_meta_geti(meta, "connectors.caption_channels", 0) != C || + rad_meta_geti(meta, "connectors.text_proj_in_factor", 0) != Lp) { + fprintf(stderr, "radiance: ltx2: the %s connector's geometry does not fit the text encoder " + "(%lld channels, %lld layers kept)\n", md, (long long)C, (long long)Lp); + return RAD_E_UNSUPPORTED; + } + K.mult = std::sqrt((double)K.D / (double)C); + const char* pre = nm.ckpt("connectors.%s_connector", md); + + /* The stack, per-layer RMS-normed over its channels and scaled, then the projection. */ + RAD_ARCH_TRY(K.a_in.declare(b, nm, g, nm.f("conn.%s.in", md), T, C * Lp)); + K.op_norm = rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, T * Lp), RAD_INT("n", C), RAD_F64("eps", eps), + RAD_STR("form", "rsqrt"), RAD_INT("ileave", Lp), + RAD_STR("dtype", "bf16"), RAD_F64("mult", K.mult)), + RAD_NOWEIGHTS), + { m.b_stack }, { K.a_in.a.x }); + K.b_x = decl_b(b, nm.f("conn.%s.x", md), RAD_BF16, { R, K.D }); + RAD_ARCH_TRY(K.proj.declare(b, nm, g, nm.f("conn.%s.proj", md), + { nm.ckpt("connectors.%s_text_proj_in.weight", md) }, + { nm.ckpt("connectors.%s_text_proj_in.bias", md) }, {}, K.D, C * Lp, + acc, gx, K.a_in, K.b_x, T)); + { + const char* wn = nm.f("conn.%s.registers", md); + const char* rs = nm.ckpt("%s.learnable_registers", pre); + const int reps = (int)(kTextRows / regs); + RadNameMap mp = map_base(wn, RAD_MAP_ROWS); + for (int i = 0; i < reps; ++i) { + mp.src[mp.n_src] = rs; + mp.src_index[mp.n_src] = 0; + mp.src_rows[mp.n_src] = regs; + ++mp.n_src; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + K.w_reg = decl_w(b, wn, RAD_BF16, { (int64_t)kTextRows, K.D }, acc, RAD_SHARD_NONE, + grp_layer(gx)); + if (!K.w_reg) return RAD_E_INVAL; + K.op_reg = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", K.D), + RAD_INT("L", (int64_t)kTextRows), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(K.w_reg)), + { m.b_zero }, { K.b_x }); + } + + /* The blocks. */ + RAD_ARCH_TRY(K.a_h.declare(b, nm, g, nm.f("conn.%s.h", md), R, K.D)); + RAD_ARCH_TRY(K.a_attn.declare(b, nm, g, nm.f("conn.%s.attn", md), R, K.D)); + RAD_ARCH_TRY(K.a_ffn.declare(b, nm, g, nm.f("conn.%s.ffn", md), R, K.ff)); + K.b_qkv = decl_b(b, nm.f("conn.%s.qkv", md), RAD_BF16, { R, 3 * K.D }); + K.b_g = decl_b(b, nm.f("conn.%s.g", md), RAD_BF16, { R, K.H }); + K.b_o = decl_b(b, nm.f("conn.%s.o", md), RAD_BF16, { R, K.D }); + K.b_up = decl_b(b, nm.f("conn.%s.up", md), RAD_BF16, { R, K.ff }); + Rope rope{ 1, K.D, "4096" }; + K.blk.resize((size_t)layers); + for (int64_t l = 0; l < layers; ++l) { + ConnBlock& B = K.blk[(size_t)l]; + const char* bp = nm.ckpt("%s.transformer_blocks.%lld", pre, (long long)l); + const char* dn = nm.f("conn.%s.blk.%lld", md, (long long)l); + B.op_n1 = rms_op(b, R, K.D, eps, 0, K.b_x, K.a_h.a.x); + RAD_ARCH_TRY(attn_declare(b, m, g, B.at, dn, nm.ckpt("%s.attn1", bp), K.H, K.hd, K.D, K.D, K.D, + true, K.a_h, nullptr, K.b_qkv, 0, K.b_g, K.a_attn, K.b_o, R, R, acc, + gx, rope, eps)); + B.op_add1 = add_op(b, R, K.D, "bf16", K.b_x, K.b_o, K.b_x); + B.op_n2 = rms_op(b, R, K.D, eps, 0, K.b_x, K.a_h.a.x); + RAD_ARCH_TRY(B.up.declare(b, nm, g, nm.f("%s.ff_up", dn), + { nm.ckpt("%s.ff.net.0.proj.weight", bp) }, + { nm.ckpt("%s.ff.net.0.proj.bias", bp) }, {}, K.ff, K.D, acc, gx, + K.a_h, K.b_up, R)); + B.op_act = unary(b, "gelu_tanh", R, K.ff, "bf16", K.b_up, K.a_ffn.a.x); + RAD_ARCH_TRY(B.down.declare(b, nm, g, nm.f("%s.ff_down", dn), + { nm.ckpt("%s.ff.net.2.weight", bp) }, + { nm.ckpt("%s.ff.net.2.bias", bp) }, {}, K.D, K.ff, acc, gx, + K.a_ffn, K.b_o, R)); + B.op_add2 = add_op(b, R, K.D, "bf16", K.b_x, K.b_o, K.b_x); + if (!B.op_n1 || !B.op_add1 || !B.op_n2 || !B.op_act || !B.op_add2) return RAD_E_INVAL; + } + K.b_text = decl_b(b, nm.f("lane.%s_text", md), RAD_BF16, { (int64_t)kMaxLanes * R, K.D }, + RAD_BUF_PERSIST); + K.op_nout = rms_op(b, R, K.D, eps, 0, K.b_x, K.b_text); + return K.op_norm && K.op_reg && K.b_text && K.op_nout ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the DiT */ +/* One AdaLayerNormSingle (`mod`): the [cos | sin] sinusoids of the step's timesteps through + * linear_1, SiLU and linear_2 to `emb`, then SiLU and `linear` to `temb`, bf16 throughout. `perm` + * reorders linear's output rows in blocks of d (LTX-2's cross-modal tables hold scale before + * shift; the norms take shift first). */ +static int ada_declare(RadBuilder* b, Model& m, Ada& A, const char* dn, const char* mod, int64_t d, + int64_t k, std::initializer_list perm = {}) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpTemb; + A.d = d; + A.k = k; + const char* src = nm.ckpt("transformer.%s", mod); + A.w1 = wcopy(b, nm.f("%s.l1.weight", dn), nm.ckpt("%s.emb.timestep_embedder.linear_1.weight", src), + RAD_BF16, { d, 256 }, acc, gx); + A.b1 = wcopy(b, nm.f("%s.l1.bias", dn), nm.ckpt("%s.emb.timestep_embedder.linear_1.bias", src), + RAD_BF16, { d }, acc, gx); + A.w2 = wcopy(b, nm.f("%s.l2.weight", dn), nm.ckpt("%s.emb.timestep_embedder.linear_2.weight", src), + RAD_BF16, { d, d }, acc, gx); + A.b2 = wcopy(b, nm.f("%s.l2.bias", dn), nm.ckpt("%s.emb.timestep_embedder.linear_2.bias", src), + RAD_BF16, { d }, acc, gx); + const char* lw = nm.f("%s.lin.weight", dn); + const char* lb = nm.f("%s.lin.bias", dn); + if (perm.size()) { + std::vector pw, pb; + const char* sw = nm.ckpt("%s.linear.weight", src); + const char* sb = nm.ckpt("%s.linear.bias", src); + RadNameMap mw = map_base(lw, RAD_MAP_ROWS), mb = map_base(lb, RAD_MAP_ROWS); + for (int p : perm) { + mw.src[mw.n_src] = sw; + mw.src_index[mw.n_src] = (int)(p * d); + mw.src_rows[mw.n_src++] = d; + mb.src[mb.n_src] = sb; + mb.src_index[mb.n_src] = (int)(p * d); + mb.src_rows[mb.n_src++] = d; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mw)); + RAD_ARCH_TRY(rad_decl_name_map(b, &mb)); + A.wl = decl_w(b, lw, RAD_BF16, { k * d, d }, acc, RAD_SHARD_NONE, grp_layer(gx)); + A.bl = decl_w(b, lb, RAD_BF16, { k * d }, acc, RAD_SHARD_NONE, grp_layer(gx)); + } else { + A.wl = wcopy(b, lw, nm.ckpt("%s.linear.weight", src), RAD_BF16, { k * d, d }, acc, gx); + A.bl = wcopy(b, lb, nm.ckpt("%s.linear.bias", src), RAD_BF16, { k * d }, acc, gx); + } + if (!A.w1 || !A.b1 || !A.w2 || !A.b2 || !A.wl || !A.bl) return RAD_E_INVAL; + A.h = decl_b(b, nm.f("%s.h", dn), RAD_BF16, { 2, d }); + A.hs = decl_b(b, nm.f("%s.hs", dn), RAD_BF16, { 2, d }); + A.emb = decl_b(b, nm.f("%s.emb", dn), RAD_BF16, { 2, d }, RAD_BUF_PERSIST); + A.es = decl_b(b, nm.f("%s.es", dn), RAD_BF16, { 2, d }); + A.temb = decl_b(b, nm.f("%s.temb", dn), RAD_BF16, { 2, k * d }); + auto lin = [&](rad_weight w, rad_weight bb, int64_t N, int64_t K, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)), + { x }, { y }); + }; + A.op1 = lin(A.w1, A.b1, d, 256, m.b_tsin, A.h); + A.ops1 = unary(b, "silu", 2, d, "bf16", A.h, A.hs); + A.op2 = lin(A.w2, A.b2, d, d, A.hs, A.emb); + A.ops2 = unary(b, "silu", 2, d, "bf16", A.emb, A.es); + A.opl = lin(A.wl, A.bl, k * d, d, A.es, A.temb); + return A.op1 && A.ops1 && A.op2 && A.ops2 && A.opl ? RAD_OK : RAD_E_INVAL; +} + +/* The module over rows [r0, r0 + n) of the step's timesteps' sinusoids `tsin`, into its own rows + * [r0, r0 + n). */ +static void ada_step(RadCtx* c, const Ada& A, rad_buf tsin, int64_t r0, int64_t n) { + const int64_t d = A.d, kd = A.k * A.d; + auto rows = [&](rad_buf h, int64_t w) { return brow_slice(h, r0, n, w); }; + RAD_ISSUE_N(c, A.op1, n, rows(tsin, 256), RAD_W(A.w1), RAD_W(A.b1), RAD_NONE, rows(A.h, d)); + RAD_ISSUE_N(c, A.ops1, n, rows(A.h, d), rows(A.hs, d)); + RAD_ISSUE_N(c, A.op2, n, rows(A.hs, d), RAD_W(A.w2), RAD_W(A.b2), RAD_NONE, rows(A.emb, d)); + RAD_ISSUE_N(c, A.ops2, n, rows(A.emb, d), rows(A.es, d)); + RAD_ISSUE_N(c, A.opl, n, rows(A.es, d), RAD_W(A.wl), RAD_W(A.bl), RAD_NONE, rows(A.temb, kd)); +} + +static int declare_dit(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const Geom& g = m.gd; + const int64_t S = m.maxS, A = m.maxA, R = kTextRows, L = m.nb; + const int64_t D = m.D, Da = m.Da, Dc = m.Dc; + const int acc = RAD_ACCESS_PER_TOKEN; + const double eps = m.eps; + const int64_t La = kMaxLanes; + + /* ---- the step's timesteps {0, sigma} (the first frame's and everything else's), their + * sinusoids, and the eight modulation MLPs */ + m.b_tin = decl_b(b, nm.f("dit.tin"), RAD_F32, { 2 }); + m.b_tsin = decl_b(b, nm.f("dit.tsin"), RAD_BF16, { 2, 256 }); + m.op_tin0 = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 2), RAD_STR("dtype", "f32"), + RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_tin }); + m.op_tin1 = cast_op(b, 1, 1, "f32", "f32", m.b_tin, m.b_tin); + /* t' = f32(1000 sigma), the timestep diffusers' scheduler hands the transformer. */ + m.op_tsin = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("n", 256), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_tin }, { m.b_tsin }); + if (!m.op_tin0 || !m.op_tin1 || !m.op_tsin) return RAD_E_INVAL; + RAD_ARCH_TRY(ada_declare(b, m, m.ad_v, "dit.ada_v", "time_embed", D, 9)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_a, "dit.ada_a", "audio_time_embed", Da, 9)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_p, "dit.ada_p", "prompt_adaln", D, 2)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_pa, "dit.ada_pa", "audio_prompt_adaln", Da, 2)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_cv, "dit.ada_cv", "av_cross_attn_video_scale_shift", D, 4, + { 1, 0, 3, 2 })); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_cvg, "dit.ada_cvg", "av_cross_attn_video_a2v_gate", D, 1)); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_ca, "dit.ada_ca", "av_cross_attn_audio_scale_shift", Da, 4, + { 1, 0, 3, 2 })); + RAD_ARCH_TRY(ada_declare(b, m, m.ad_cag, "dit.ada_cag", "av_cross_attn_audio_v2a_gate", Da, 1)); + + /* ---- the step's tables (PERSIST): block l's rows at column l of each */ + m.b_mv = decl_b(b, nm.f("dit.mod_v"), RAD_BF16, { 2, L * 9 * D }, RAD_BUF_PERSIST); + m.b_ma = decl_b(b, nm.f("dit.mod_a"), RAD_BF16, { 1, L * 9 * Da }, RAD_BUF_PERSIST); + m.b_mp = decl_b(b, nm.f("dit.mod_p"), RAD_BF16, { 1, L * 2 * D }, RAD_BUF_PERSIST); + m.b_mpa = decl_b(b, nm.f("dit.mod_pa"), RAD_BF16, { 1, L * 2 * Da }, RAD_BUF_PERSIST); + m.b_mcv = decl_b(b, nm.f("dit.mod_cv"), RAD_BF16, { 1, L * 4 * D }, RAD_BUF_PERSIST); + m.b_mcvg = decl_b(b, nm.f("dit.mod_cvg"), RAD_BF16, { 1, L * D }, RAD_BUF_PERSIST); + m.b_mca = decl_b(b, nm.f("dit.mod_ca"), RAD_BF16, { 1, L * 4 * Da }, RAD_BUF_PERSIST); + m.b_mcag = decl_b(b, nm.f("dit.mod_cag"), RAD_BF16, { 1, L * Da }, RAD_BUF_PERSIST); + m.b_fv = decl_b(b, nm.f("dit.mod_fv"), RAD_BF16, { 2, 2 * D }, RAD_BUF_PERSIST); + m.b_fa = decl_b(b, nm.f("dit.mod_fa"), RAD_BF16, { 1, 2 * Da }, RAD_BUF_PERSIST); + auto table_op = [&](rad_weight t, int64_t rows, int64_t n, int64_t Lr, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_INT("L", Lr), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(t)), + { x }, { y }); + }; + m.w_fv = wcopy(b, nm.f("dit.out_table"), nm.ckpt("transformer.scale_shift_table"), RAD_BF16, + { 2, D }, acc, kGrpTemb); + m.w_fa = wcopy(b, nm.f("dit.audio_out_table"), nm.ckpt("transformer.audio_scale_shift_table"), + RAD_BF16, { 2, Da }, acc, kGrpTemb); + if (!m.w_fv || !m.w_fa) return RAD_E_INVAL; + m.op_fv = table_op(m.w_fv, 2, D, 2, m.ad_v.emb, m.b_fv); + m.op_fa = table_op(m.w_fa, 1, Da, 2, m.ad_a.emb, m.b_fa); + + /* ---- the lanes (PERSIST): both latents f32, the clean first latent frame */ + m.b_vstate = decl_b(b, nm.f("lane.video"), RAD_F32, { La * S, kC }, RAD_BUF_PERSIST); + m.b_astate = decl_b(b, nm.f("lane.audio"), RAD_F32, { La * A, kAudioC }, RAD_BUF_PERSIST); + m.b_first = decl_b(b, nm.f("lane.first"), RAD_F32, { La * m.maxPpf, kC }, RAD_BUF_PERSIST); + auto randn = [&](int64_t rows, int64_t stride, rad_buf x) { + return rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", kC), + RAD_INT("stride", stride), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + m.op_rnd_v = randn(S, S, m.b_vstate); + m.op_rnd_a = randn(A, A, m.b_astate); + m.op_keep_first = cast_op(b, m.maxPpf, kC, "f32", "f32", m.b_first, m.b_vstate); + + /* ---- an evaluation's rows */ + RAD_ARCH_TRY(m.a_lv.declare(b, nm, g, "dit.lat_v", S, kC)); + RAD_ARCH_TRY(m.a_la.declare(b, nm, g, "dit.lat_a", A, kAudioC)); + m.op_lv = cast_op(b, S, kC, "f32", "bf16", m.b_vstate, m.a_lv.a.x); + m.op_la = cast_op(b, A, kAudioC, "f32", "bf16", m.b_astate, m.a_la.a.x); + m.b_hv = decl_b(b, nm.f("dit.hv"), RAD_BF16, { S, D }); + m.b_ha = decl_b(b, nm.f("dit.ha"), RAD_BF16, { A, Da }); + RAD_ARCH_TRY(m.pin_v.declare(b, nm, g, "dit.proj_in", { nm.ckpt("transformer.proj_in.weight") }, + { nm.ckpt("transformer.proj_in.bias") }, {}, D, kC, acc, kGrpDit, + m.a_lv, m.b_hv, S, true)); + RAD_ARCH_TRY(m.pin_a.declare(b, nm, g, "dit.audio_proj_in", + { nm.ckpt("transformer.audio_proj_in.weight") }, + { nm.ckpt("transformer.audio_proj_in.bias") }, {}, Da, kAudioC, acc, + kGrpDit, m.a_la, m.b_ha, A, true)); + RAD_ARCH_TRY(m.a_hv.declare(b, nm, g, "dit.hnv", S, D)); + RAD_ARCH_TRY(m.a_ha.declare(b, nm, g, "dit.hna", A, Da)); + RAD_ARCH_TRY(m.a_ctxv.declare(b, nm, g, "dit.ctx_v", R, D)); + RAD_ARCH_TRY(m.a_ctxa.declare(b, nm, g, "dit.ctx_a", R, Da)); + RAD_ARCH_TRY(m.a_nv.declare(b, nm, g, "dit.nv_a2v", S, D)); + RAD_ARCH_TRY(m.a_nv2.declare(b, nm, g, "dit.nv_v2a", S, D)); + RAD_ARCH_TRY(m.a_na.declare(b, nm, g, "dit.na_a2v", A, Da)); + RAD_ARCH_TRY(m.a_na2.declare(b, nm, g, "dit.na_v2a", A, Da)); + RAD_ARCH_TRY(m.a_aov.declare(b, nm, g, "dit.attn_v", S, D)); + RAD_ARCH_TRY(m.a_aoa.declare(b, nm, g, "dit.attn_a", A, Da)); + RAD_ARCH_TRY(m.a_xv.declare(b, nm, g, "dit.attn_a2v", S, Dc)); + RAD_ARCH_TRY(m.a_xa.declare(b, nm, g, "dit.attn_v2a", A, Dc)); + RAD_ARCH_TRY(m.a_ffv.declare(b, nm, g, "dit.ffn_v", S, m.ffv)); + RAD_ARCH_TRY(m.a_ffa.declare(b, nm, g, "dit.ffn_a", A, m.ffa)); + RAD_ARCH_TRY(m.a_fv.declare(b, nm, g, "dit.out_v", S, D)); + RAD_ARCH_TRY(m.a_fa.declare(b, nm, g, "dit.out_a", A, Da)); + m.b_qkvv = decl_b(b, nm.f("dit.qkv_v"), RAD_BF16, { S, 3 * D }); + m.b_qkva = decl_b(b, nm.f("dit.qkv_a"), RAD_BF16, { A, 3 * Da }); + m.b_gv = decl_b(b, nm.f("dit.gate_v"), RAD_BF16, { S, m.H }); + m.b_ga = decl_b(b, nm.f("dit.gate_a"), RAD_BF16, { A, m.Ha }); + m.b_ov = decl_b(b, nm.f("dit.o_v"), RAD_BF16, { S, D }); + m.b_oa = decl_b(b, nm.f("dit.o_a"), RAD_BF16, { A, Da }); + m.b_qv = decl_b(b, nm.f("dit.q_v"), RAD_BF16, { S, D }); + m.b_qa = decl_b(b, nm.f("dit.q_a"), RAD_BF16, { A, Da }); + m.b_kvtv = decl_b(b, nm.f("dit.kv_tv"), RAD_BF16, { R, 2 * D }); + m.b_kvta = decl_b(b, nm.f("dit.kv_ta"), RAD_BF16, { R, 2 * Da }); + m.b_qxv = decl_b(b, nm.f("dit.q_a2v"), RAD_BF16, { S, Dc }); + m.b_gxv = decl_b(b, nm.f("dit.gate_a2v"), RAD_BF16, { S, m.Ha }); + m.b_kvxa = decl_b(b, nm.f("dit.kv_a2v"), RAD_BF16, { A, 2 * Dc }); + m.b_qxa = decl_b(b, nm.f("dit.q_v2a"), RAD_BF16, { A, Dc }); + m.b_gxa = decl_b(b, nm.f("dit.gate_v2a"), RAD_BF16, { A, m.Ha }); + m.b_kvxv = decl_b(b, nm.f("dit.kv_v2a"), RAD_BF16, { S, 2 * Dc }); + m.b_upv = decl_b(b, nm.f("dit.up_v"), RAD_BF16, { S, m.ffv }); + m.b_upa = decl_b(b, nm.f("dit.up_a"), RAD_BF16, { A, m.ffa }); + + /* ---- the blocks */ + const Rope rv{ 3, D, "20 2048 2048" }, ra{ 1, Da, "20" }, rx{ 1, Dc, "20" }, none{}; + m.dit.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + DitBlock& B = m.dit[(size_t)l]; + const int li = (int)l, gx = kGrpDit + 1 + li; + const char* bp = nm.ckpt("transformer.transformer_blocks.%d", li); + const char* dn = nm.f("dit.blk.%d", li); + auto attn = [&](Attn& At, const char* name, const char* src, int64_t H, int64_t hd, + int64_t qdim, int64_t kvdim, int64_t odim, bool self, const Act& xin, + const Act* kvin, rad_buf bq, rad_buf bkv, rad_buf bg, const Act& ao, rad_buf y, + int64_t rq, int64_t rk, const Rope& rope) { + return attn_declare(b, m, g, At, nm.f("%s.%s", dn, name), nm.ckpt("%s.%s", bp, src), H, hd, + qdim, kvdim, odim, self, xin, kvin, bq, bkv, bg, ao, y, rq, rk, acc, gx, + rope, eps); + }; + /* The step's tables: the block's learned rows plus the step's shared ones. */ + auto table = [&](rad_weight* w, const char* dname, const char* name, + std::initializer_list rows, int64_t d) { + const char* wn = nm.f("%s.%s", dn, dname); + bool natural = true; + int i = 0; + for (int r : rows) natural = natural && r == i++; + if (natural && (int64_t)rows.size() > 1) { + if (map_copy(b, wn, nm.ckpt("%s.%s", bp, name)) < 0) return RAD_E_INVAL; + } else { + if (rows.size() > 8) return RAD_E_INVAL; + RadNameMap mp = map_base(wn, RAD_MAP_ROWS); + for (int r : rows) { + mp.src[mp.n_src] = nm.ckpt("%s.%s", bp, name); + mp.src_index[mp.n_src] = r; + mp.src_rows[mp.n_src++] = 1; + } + if (rad_decl_name_map(b, &mp) < 0) return RAD_E_INVAL; + } + *w = decl_w(b, wn, RAD_BF16, { (int64_t)rows.size(), d }, acc, RAD_SHARD_NONE, + grp_layer(gx)); + return *w ? RAD_OK : RAD_E_INVAL; + }; + RAD_ARCH_TRY(table(&B.t_v, "table_v", "scale_shift_table", { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, D)); + RAD_ARCH_TRY(table(&B.t_a, "table_a", "audio_scale_shift_table", { 0, 1, 2, 3, 4, 5, 6, 7, 8 }, + Da)); + RAD_ARCH_TRY(table(&B.t_p, "table_p", "prompt_scale_shift_table", { 0, 1 }, D)); + RAD_ARCH_TRY(table(&B.t_pa, "table_pa", "audio_prompt_scale_shift_table", { 0, 1 }, Da)); + RAD_ARCH_TRY(table(&B.t_cv, "table_cv", "video_a2v_cross_attn_scale_shift_table", { 1, 0, 3, 2 }, + D)); + RAD_ARCH_TRY(table(&B.t_cvg, "table_cvg", "video_a2v_cross_attn_scale_shift_table", { 4 }, D)); + RAD_ARCH_TRY(table(&B.t_ca, "table_ca", "audio_a2v_cross_attn_scale_shift_table", { 1, 0, 3, 2 }, + Da)); + RAD_ARCH_TRY(table(&B.t_cag, "table_cag", "audio_a2v_cross_attn_scale_shift_table", { 4 }, Da)); + B.op_tv = table_op(B.t_v, 2, 9 * D, 1, m.ad_v.temb, m.b_mv); + B.op_ta = table_op(B.t_a, 1, 9 * Da, 1, m.ad_a.temb, m.b_ma); + B.op_tp = table_op(B.t_p, 1, 2 * D, 1, m.ad_p.temb, m.b_mp); + B.op_tpa = table_op(B.t_pa, 1, 2 * Da, 1, m.ad_pa.temb, m.b_mpa); + B.op_tcv = table_op(B.t_cv, 1, 4 * D, 1, m.ad_cv.temb, m.b_mcv); + B.op_tcvg = table_op(B.t_cvg, 1, D, 1, m.ad_cvg.temb, m.b_mcvg); + B.op_tca = table_op(B.t_ca, 1, 4 * Da, 1, m.ad_ca.temb, m.b_mca); + B.op_tcag = table_op(B.t_cag, 1, Da, 1, m.ad_cag.temb, m.b_mcag); + + /* Self-attention (block 0's q|k|v was mapped by declare's format probe). */ + if (l == 0) B.sv.qkv.mapped = true; + B.m1v = mod_op(b, S, D, eps, l > 0, "rms", m.b_mv, m.b_mv, m.b_hv, m.b_ov, m.a_hv.a.x); + B.m1a = mod_op(b, A, Da, eps, l > 0, "rms", m.b_ma, m.b_ma, m.b_ha, m.b_oa, m.a_ha.a.x); + RAD_ARCH_TRY(attn(B.sv, "attn1", "attn1", m.H, m.hd, D, D, D, true, m.a_hv, nullptr, m.b_qkvv, 0, + m.b_gv, m.a_aov, m.b_ov, S, S, rv)); + RAD_ARCH_TRY(attn(B.sa, "audio_attn1", "audio_attn1", m.Ha, m.hda, Da, Da, Da, true, m.a_ha, + nullptr, m.b_qkva, 0, m.b_ga, m.a_aoa, m.b_oa, A, A, ra)); + /* Text cross-attention: the query's norm gated by the self-attention, the text keys and + * values modulated as they are. */ + B.m2v = mod_op(b, S, D, eps, true, "rms", m.b_mv, m.b_mv, m.b_hv, m.b_ov, m.a_hv.a.x); + B.m2a = mod_op(b, A, Da, eps, true, "rms", m.b_ma, m.b_ma, m.b_ha, m.b_oa, m.a_ha.a.x); + B.mtv = mod_op(b, R, D, eps, false, "none", m.b_mp, m.b_mp, m.cv.b_text, 0, m.a_ctxv.a.x); + B.mta = mod_op(b, R, Da, eps, false, "none", m.b_mpa, m.b_mpa, m.ca.b_text, 0, m.a_ctxa.a.x); + RAD_ARCH_TRY(attn(B.tv, "attn2", "attn2", m.H, m.hd, D, D, D, false, m.a_hv, &m.a_ctxv, m.b_qv, + m.b_kvtv, m.b_gv, m.a_aov, m.b_ov, S, R, none)); + RAD_ARCH_TRY(attn(B.ta, "audio_attn2", "audio_attn2", m.Ha, m.hda, Da, Da, Da, false, m.a_ha, + &m.a_ctxa, m.b_qa, m.b_kvta, m.b_ga, m.a_aoa, m.b_oa, A, R, none)); + /* The cross-modal attentions: both streams gated by their text attention, each normed + * twice (as queries and as keys), the attentions, their gates. */ + B.g2v = gate_op(b, S, D, m.b_mv, m.b_ov, m.b_hv); + B.g2a = gate_op(b, A, Da, m.b_ma, m.b_oa, m.b_ha); + B.mav = mod_op(b, S, D, eps, false, "rms", m.b_mcv, m.b_mcv, m.b_hv, 0, m.a_nv.a.x); + B.mvv = mod_op(b, S, D, eps, false, "rms", m.b_mcv, m.b_mcv, m.b_hv, 0, m.a_nv2.a.x); + B.maa = mod_op(b, A, Da, eps, false, "rms", m.b_mca, m.b_mca, m.b_ha, 0, m.a_na.a.x); + B.mva = mod_op(b, A, Da, eps, false, "rms", m.b_mca, m.b_mca, m.b_ha, 0, m.a_na2.a.x); + RAD_ARCH_TRY(attn(B.a2v, "a2v", "audio_to_video_attn", m.Ha, m.hda, D, Da, D, false, m.a_nv, + &m.a_na, m.b_qxv, m.b_kvxa, m.b_gxv, m.a_xv, m.b_ov, S, A, rx)); + RAD_ARCH_TRY(attn(B.v2a, "v2a", "video_to_audio_attn", m.Ha, m.hda, Da, D, Da, false, m.a_na2, + &m.a_nv2, m.b_qxa, m.b_kvxv, m.b_gxa, m.a_xa, m.b_oa, A, S, rx)); + B.gcv = gate_op(b, S, D, m.b_mcvg, m.b_ov, m.b_hv); + B.gca = gate_op(b, A, Da, m.b_mcag, m.b_oa, m.b_ha); + /* The feed-forward (the video's without biases). */ + B.m3v = mod_op(b, S, D, eps, false, "rms", m.b_mv, m.b_mv, m.b_hv, 0, m.a_hv.a.x); + B.m3a = mod_op(b, A, Da, eps, false, "rms", m.b_ma, m.b_ma, m.b_ha, 0, m.a_ha.a.x); + B.m3vg = mod_op(b, S, D, eps, true, "rms", m.b_mv, m.b_mv, m.b_hv, m.b_ov, m.a_hv.a.x); + B.m3ag = mod_op(b, A, Da, eps, true, "rms", m.b_ma, m.b_ma, m.b_ha, m.b_oa, m.a_ha.a.x); + RAD_ARCH_TRY(B.fv_up.declare(b, nm, g, nm.f("%s.ff_up", dn), + { nm.ckpt("%s.ff.net.0.proj.weight", bp) }, + {}, {}, m.ffv, D, acc, gx, m.a_hv, m.b_upv, S)); + B.actv = unary(b, "gelu_tanh", S, m.ffv, "bf16", m.b_upv, m.a_ffv.a.x); + RAD_ARCH_TRY(B.fv_down.declare(b, nm, g, nm.f("%s.ff_down", dn), + { nm.ckpt("%s.ff.net.2.weight", bp) }, + {}, {}, D, m.ffv, acc, gx, m.a_ffv, m.b_ov, S)); + RAD_ARCH_TRY(B.fa_up.declare(b, nm, g, nm.f("%s.audio_ff_up", dn), + { nm.ckpt("%s.audio_ff.net.0.proj.weight", bp) }, + { nm.ckpt("%s.audio_ff.net.0.proj.bias", bp) }, {}, m.ffa, + Da, acc, gx, m.a_ha, m.b_upa, A)); + B.acta = unary(b, "gelu_tanh", A, m.ffa, "bf16", m.b_upa, m.a_ffa.a.x); + RAD_ARCH_TRY(B.fa_down.declare(b, nm, g, nm.f("%s.audio_ff_down", dn), + { nm.ckpt("%s.audio_ff.net.2.weight", bp) }, + { nm.ckpt("%s.audio_ff.net.2.bias", bp) }, {}, Da, m.ffa, acc, gx, + m.a_ffa, m.b_oa, A)); + const rad_op all[] = { B.op_tv, B.op_ta, B.op_tp, B.op_tpa, B.op_tcv, B.op_tcvg, B.op_tca, + B.op_tcag, B.m1v, B.m1a, B.m2v, B.m2a, B.mtv, B.mta, B.g2v, B.g2a, + B.mav, B.mvv, B.maa, B.mva, B.gcv, B.gca, B.m3v, B.m3a, B.m3vg, + B.m3ag, B.actv, B.acta }; + for (rad_op o : all) + if (!o) return RAD_E_INVAL; + } + + /* ---- the output: the last feed-forward gated in, LayerNorm modulated by the output tables, + * proj_out; each evaluation's velocities (PERSIST, the guidance reads them all) */ + m.op_fnv = mod_op(b, S, D, eps, true, "layer", m.b_fv, m.b_mv, m.b_hv, m.b_ov, m.a_fv.a.x); + m.op_fna = mod_op(b, A, Da, eps, true, "layer", m.b_fa, m.b_ma, m.b_ha, m.b_oa, m.a_fa.a.x); + for (int p = 0; p < kPasses; ++p) { + m.b_vel_v[p] = decl_b(b, nm.f("dit.vel_v%d", p), RAD_BF16, { S, kC }, RAD_BUF_PERSIST); + m.b_vel_a[p] = decl_b(b, nm.f("dit.vel_a%d", p), RAD_BF16, { A, kAudioC }, RAD_BUF_PERSIST); + } + RAD_ARCH_TRY(m.pout_v.declare(b, nm, g, "dit.proj_out", { nm.ckpt("transformer.proj_out.weight") }, + { nm.ckpt("transformer.proj_out.bias") }, {}, kC, D, acc, kGrpDit, + m.a_fv, m.b_vel_v[0], S, true)); + RAD_ARCH_TRY(m.pout_a.declare(b, nm, g, "dit.audio_proj_out", + { nm.ckpt("transformer.audio_proj_out.weight") }, + { nm.ckpt("transformer.audio_proj_out.bias") }, {}, kAudioC, Da, acc, + kGrpDit, m.a_fa, m.b_vel_a[0], A, true)); + /* The other evaluations' velocities are written by the same heads. */ + for (int p = 1; p < kPasses; ++p) { + RAD_ARCH_TRY(rad_op_writes(b, m.pout_v.op, &m.b_vel_v[p], 1)); + RAD_ARCH_TRY(rad_op_writes(b, m.pout_a.op, &m.b_vel_a[p], 1)); + } + + /* ---- the guided step: each modality's latent from its evaluations */ + m.b_gst = decl_b(b, nm.f("dit.guide_stats"), RAD_F32, { 8200 }); + auto guide = [&](int64_t rows, rad_buf* vel, rad_buf x) { + rad_op op = RAD_OP(b, "ltx_guide", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", kC), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + if (!op) return op; + rad_buf rd[6] = { vel[0], vel[1], vel[2], vel[3], m.b_gst, x }; + rad_buf wr[2] = { m.b_gst, x }; + rad_op_reads(b, op, rd, 6); + rad_op_writes(b, op, wr, 2); + return op; + }; + m.op_gv = guide(S, m.b_vel_v, m.b_vstate); + m.op_ga = guide(A, m.b_vel_a, m.b_astate); + return m.op_fnv && m.op_fna && m.op_gv && m.op_ga && m.op_fv && m.op_fa && m.op_rnd_v && + m.op_rnd_a && m.op_keep_first && m.op_lv && m.op_la + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the video VAE */ +/* A residual block's ops at C channels over voxel rows (`rows` at most): PerChannelRMSNorm with its + * SiLU, conv1, again, conv2 with the input added. `tpad` is the frames' padding (the decoder's + * replicate, the encoder's causal). */ +static int vres_declare(RadBuilder* b, Model& m, VRes& Rb, const char* dn, const char* src, int64_t C, + int64_t rows, const char* tpad, int group, rad_buf x, rad_buf t, rad_buf h) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN; + Rb.C = C; + Rb.w1 = wcopy(b, nm.f("%s.conv1.weight", dn), nm.ckpt("%s.conv1.conv.weight", src), RAD_BF16, + { C, C, 3, 3, 3 }, acc, group); + Rb.b1 = wcopy(b, nm.f("%s.conv1.bias", dn), nm.ckpt("%s.conv1.conv.bias", src), RAD_BF16, { C }, + acc, group); + Rb.w2 = wcopy(b, nm.f("%s.conv2.weight", dn), nm.ckpt("%s.conv2.conv.weight", src), RAD_BF16, + { C, C, 3, 3, 3 }, acc, group); + Rb.b2 = wcopy(b, nm.f("%s.conv2.bias", dn), nm.ckpt("%s.conv2.conv.bias", src), RAD_BF16, { C }, + acc, group); + if (!Rb.w1 || !Rb.b1 || !Rb.w2 || !Rb.b2) return RAD_E_INVAL; + auto norm = [&](rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", C), RAD_F64("eps", 1e-8), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); + }; + auto conv = [&](rad_weight w, rad_weight bb, rad_buf in, rad_buf res, rad_buf out) { + const rad_op op = RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", C), + RAD_INT("cout", C), RAD_INT("k", 3), RAD_INT("kt", 3), + RAD_STR("dtype", "bf16"), RAD_STR("tpad", tpad)), + RAD_WEIGHTS(w, bb)); + return res ? rw(b, op, { in, res }, { out }) : rw(b, op, { in }, { out }); + }; + Rb.op_n1 = norm(x, t); + Rb.op_c1 = conv(Rb.w1, Rb.b1, t, 0, h); + Rb.op_n2 = norm(h, t); + Rb.op_c2 = conv(Rb.w2, Rb.b2, t, x, x); + return Rb.op_n1 && Rb.op_c1 && Rb.op_n2 && Rb.op_c2 ? RAD_OK : RAD_E_INVAL; +} + +/* A dense [rows, cols] view of an arena buffer, at element offset `off` (the VAE's buffers hold + * a different width at each scale). */ +static RadOperand view(RadCtx* c, rad_buf h, uint32_t dt, int64_t rows, int64_t cols, int64_t off = 0) { + const int64_t es = dt == RAD_F32 ? 4 : dt == RAD_U8 ? 1 : 2; + return RAD_P_T2((const char*)rad_buf_ptr(c, h) + off * es, dt, rows, cols); +} + +static void vres_step(RadCtx* c, const VRes& Rb, int64_t vox, const RadOperand& geom, rad_buf x, + rad_buf t, rad_buf h) { + const int64_t C = Rb.C; + const RadOperand X = view(c, x, RAD_BF16, vox, C), Tt = view(c, t, RAD_BF16, vox, C); + const RadOperand Hh = view(c, h, RAD_BF16, vox, C); + RAD_ISSUE_N(c, Rb.op_n1, vox, X, Tt); + RAD_ISSUE_N(c, Rb.op_c1, vox, Tt, RAD_W(Rb.w1), RAD_W(Rb.b1), geom, RAD_NONE, Hh); + RAD_ISSUE_N(c, Rb.op_n2, vox, Hh, Tt); + RAD_ISSUE_N(c, Rb.op_c2, vox, Tt, RAD_W(Rb.w2), RAD_W(Rb.b2), geom, X, X); +} + +/* The decoder (LTX2VideoDecoder3d, non-causal): conv_in, the mid block, four up blocks (the + * upsampler's convolution and depth to space, then residual blocks), PerChannelRMSNorm with SiLU, + * conv_out to 4 x 4 pixel patches. The whole video at once, a tile at a time (vae_tiles: one for a + * frame of kVaeLat latents or fewer), into the lane's tile store; each chunk's frames stitched to + * bytes from it. */ +static int declare_vae(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpVae; + std::vector boc = meta_list(meta, "vae.decoder_block_out_channels"); + std::vector lpb = meta_list(meta, "vae.decoder_layers_per_block"); + std::vector uf = meta_list(meta, "vae.upsample_factor"); + const char* types = rad_meta_gets(meta, "vae.upsample_type", ""); + std::vector sts = meta_list(meta, "vae.decoder_spatio_temporal_scaling"); + std::vector ut; + for (const char* s = types; s && *s;) { + while (*s == ' ') ++s; + const char* e = s; + while (*e && *e != ' ') ++e; + if (e > s) ut.emplace_back(s, e); + s = e; + } + const size_t nup = boc.size(); + if (nup == 0 || lpb.size() != nup + 1 || uf.size() != nup || ut.size() != nup || + sts.size() != nup) { + fprintf(stderr, "radiance: ltx2: the VAE decoder's block lists disagree in length\n"); + return RAD_E_UNSUPPORTED; + } + std::reverse(boc.begin(), boc.end()); + std::reverse(lpb.begin(), lpb.end()); + std::reverse(uf.begin(), uf.end()); + std::reverse(sts.begin(), sts.end()); + + /* The volumes: latent (F, h, w) to (At F + Bt, Ah h, Aw w) after each up block; the scratch + * sized to the largest volume times channels any step of the network holds. */ + const int64_t F = max_lat_frames(), HW = kVaeLat; + int64_t At = 1, Bt = 0, Ahw = 1, C = (int64_t)boc[0], big = F * HW * C; + m.vC0 = C; + m.vup.resize(nup); + for (size_t i = 0; i < nup; ++i) { + VUp& U = m.vup[i]; + U.cout = (int64_t)boc[i] / (int64_t)uf[i]; + U.cin = C; + if (!sts[i]) { + fprintf(stderr, "radiance: ltx2: an up block without its upsampler\n"); + return RAD_E_UNSUPPORTED; + } + if (ut[i] == "spatiotemporal") { U.st = 2; U.sh = 2; U.sw = 2; } + else if (ut[i] == "temporal") { U.st = 2; U.sh = 1; U.sw = 1; } + else if (ut[i] == "spatial") { U.st = 1; U.sh = 2; U.sw = 2; } + else return RAD_E_UNSUPPORTED; + if (U.cout * (int64_t)uf[i] != C) { + fprintf(stderr, "radiance: ltx2: up block %zu would take %lld channels and has %lld; a " + "block that changes width first is not run\n", i, + (long long)(U.cout * (int64_t)uf[i]), (long long)C); + return RAD_E_UNSUPPORTED; + } + U.conv_out = C * U.st * U.sh * U.sw / (int64_t)uf[i]; + big = std::max(big, (At * F + Bt) * Ahw * HW * U.conv_out); + At *= U.st; + Bt = Bt * U.st - (U.st - 1); + Ahw *= U.sh * U.sw; + C = U.cout; + big = std::max(big, (At * F + Bt) * Ahw * HW * C); + } + const int64_t vox_out = (At * F + Bt) * Ahw * HW; + { + int64_t side = 1; + while (side * side < Ahw) ++side; + if (side * side != Ahw) return RAD_E_UNSUPPORTED; + /* The causal mapping tile_stitch reads: the first latent frame one frame. */ + if (Bt != 1 - At) return RAD_E_UNSUPPORTED; + m.vAt = At; + m.vBt = Bt; + m.vAhw = side; + } + /* The tile store holds the largest video's tiles: every size a request may ask for, at the + * most frames a step carries at that size. */ + for (int64_t Wd = kMinSide; Wd * kMinSide <= kMaxArea; Wd += kMult) + for (int64_t Hd = kMinSide; Wd * Hd <= kMaxArea; Hd += kMult) { + if (std::max(Wd, Hd) > kMaxAspect * std::min(Wd, Hd)) continue; + const int64_t h = Hd / kScale, w = Wd / kScale; + const int64_t Fl = std::min(max_lat_frames(), max_video_rows() / (h * w)); + if (Fl < (int64_t)kLpc * kMinChunks + kLtail) continue; + const std::vector tl = vae_tiles(h, w); + int64_t area = 0; + for (const VaeTile& t : tl) area += t.h * t.w; + m.maxStore = std::max(m.maxStore, (At * Fl + Bt) * Ahw * area); + m.maxTiles = std::max(m.maxTiles, (int64_t)tl.size()); + m.maxSide = std::max(m.maxSide, std::max(Wd, Hd)); + } + /* Every tile's crop reads the latent again after earlier tiles' decodes, which the planner's + * declaration order cannot see: kept. */ + m.b_vlat = decl_b(b, nm.f("vae.lat"), RAD_BF16, { m.maxS, kC }, RAD_BUF_PERSIST); + m.b_vtlat = decl_b(b, nm.f("vae.tile_lat"), RAD_BF16, { F * HW, kC }); + m.b_va = decl_b(b, nm.f("vae.a"), RAD_BF16, { big }); + m.b_vb = decl_b(b, nm.f("vae.b"), RAD_BF16, { big }); + m.b_vc = decl_b(b, nm.f("vae.c"), RAD_BF16, { big }); + m.b_vtiles = decl_b(b, nm.f("lane.tiles"), RAD_BF16, { m.maxStore, kPixC }, RAD_BUF_PERSIST); + /* The boxes are read through raw pointers the planner does not see: kept. */ + m.b_vgrid = decl_b(b, nm.f("vae.grid"), RAD_I32, { m.maxTiles, 8 }, RAD_BUF_PERSIST); + m.b_vf0 = decl_b(b, nm.f("vae.first_frame"), RAD_I32, { 1 }); + m.vd_mean = wcopy(b, nm.f("vae.latents_mean"), nm.ckpt("vae.latents_mean"), RAD_BF16, { kC }, + acc, gx); + m.vd_std = wcopy(b, nm.f("vae.latents_std"), nm.ckpt("vae.latents_std"), RAD_BF16, { kC }, acc, gx); + if (!m.vd_mean || !m.vd_std) return RAD_E_INVAL; + /* The latent to bf16 first, then denormalised in bf16, as the pipeline casts it. */ + m.op_vlat = cast_op(b, m.maxS, kC, "f32", "bf16", m.b_vstate, m.b_vlat); + m.op_vden = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxS), RAD_INT("n", kC), + RAD_STR("mode", "denorm"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.vd_mean, m.vd_std)), + { m.b_vlat }, { m.b_vlat }); + auto conv = [&](rad_weight* w, rad_weight* bb, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t rows, rad_buf in, rad_buf out) -> rad_op { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.conv.weight", src), RAD_BF16, + { cout, cin, 3, 3, 3 }, acc, gx); + *bb = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.conv.bias", src), RAD_BF16, { cout }, acc, gx); + if (!*w || !*bb) return 0; + return rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", 3), RAD_INT("kt", 3), + RAD_STR("dtype", "bf16"), RAD_STR("tpad", "replicate")), + RAD_WEIGHTS(*w, *bb)), + { in }, { out }); + }; + auto grid = [&](int64_t tile, int64_t stride) { + return rw(b, RAD_OP(b, "tile_grid", + RAD_PARAMS(RAD_RANGE("M", 1, m.maxTiles), RAD_INT("tile", tile), + RAD_INT("stride", stride)), + RAD_NOWEIGHTS), + {}, { m.b_vgrid }); + }; + /* One tile: a tile_grid row of the whole frame. */ + m.op_vgrid1 = grid(1 << 20, 1 << 20); + m.op_vgrid = grid(kTile, kTileStride); + m.op_vcrop = rw(b, RAD_OP(b, "tile_crop", + RAD_PARAMS(RAD_RANGE("M", 1, F * HW), RAD_INT("C", kC), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vlat }, { m.b_vtlat }); + m.op_vcin = conv(&m.w_vcin, &m.b_vcin, "vae.dec.conv_in", "vae.decoder.conv_in", kC, m.vC0, F * HW, + m.b_vtlat, m.b_va); + const int64_t nmid = (int64_t)lpb[0]; + m.vmid.resize((size_t)nmid); + for (int64_t r = 0; r < nmid; ++r) + RAD_ARCH_TRY(vres_declare(b, m, m.vmid[(size_t)r], nm.f("vae.dec.mid.%lld", (long long)r), + nm.ckpt("vae.decoder.mid_block.resnets.%lld", (long long)r), m.vC0, + m.maxS, "replicate", gx, m.b_va, m.b_vb, m.b_vc)); + At = 1; + Bt = 0; + int64_t Ah = 1, Aw = 1; + for (size_t i = 0; i < nup; ++i) { + VUp& U = m.vup[i]; + const int64_t vin = (At * F + Bt) * Ah * Aw * HW; + At *= U.st; + Bt = Bt * U.st - (U.st - 1); + Ah *= U.sh; + Aw *= U.sw; + const int64_t vout = (At * F + Bt) * Ah * Aw * HW; + const char* dn = nm.f("vae.dec.up.%zu", i); + const char* src = nm.ckpt("vae.decoder.up_blocks.%zu", i); + U.op_conv = conv(&U.w, &U.b, nm.f("%s.conv", dn), nm.ckpt("%s.upsamplers.0.conv", src), U.cin, + U.conv_out, vin, m.b_va, m.b_vb); + U.op_d2s = rw(b, RAD_OP(b, "d2s3d", + RAD_PARAMS(RAD_RANGE("M", 1, vin), RAD_INT("C", U.cout), + RAD_INT("st", U.st), RAD_INT("sh", U.sh), RAD_INT("sw", U.sw), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vb }, { m.b_va }); + /* Its output volume on the device, off the latent's (kept, so every reader finds it). */ + U.geom = decl_b(b, nm.f("%s.geom", dn), RAD_I32, { 3 }, RAD_BUF_PERSIST); + U.op_geom = rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_STR("src", "0 1 2"), + RAD_STR("mul", ints({ At, Ah, Aw }).c_str()), + RAD_STR("add", ints({ Bt, 0, 0 }).c_str())), + RAD_NOWEIGHTS), + {}, { U.geom }); + if (!U.op_conv || !U.op_d2s || !U.op_geom) return RAD_E_INVAL; + const int64_t nres = (int64_t)lpb[i + 1]; + U.res.resize((size_t)nres); + for (int64_t r = 0; r < nres; ++r) + RAD_ARCH_TRY(vres_declare(b, m, U.res[(size_t)r], nm.f("%s.res.%lld", dn, (long long)r), + nm.ckpt("%s.resnets.%lld", src, (long long)r), U.cout, vout, + "replicate", gx, m.b_va, m.b_vb, m.b_vc)); + } + m.op_vnout = rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, vox_out), RAD_INT("n", C), + RAD_F64("eps", 1e-8), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_va }, { m.b_vb }); + m.op_vcout = conv(&m.w_vcout, &m.b_vcout, "vae.dec.conv_out", "vae.decoder.conv_out", C, kPixC, + vox_out, m.b_vb, m.b_vtiles); + /* A chunk's frames to bytes: 4 x 4 patches, the column offset outer (LTX-2's patchifier), the + * tiles blended where they overlap; the chunk's first frame off the pass's geometry. */ + m.b_frames = decl_b(b, nm.f("frames_out"), RAD_U8, { (int64_t)(kFpc + kFtail) * kMaxArea, 3 }, + RAD_BUF_PERSIST); + m.op_vf0 = rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 1), + RAD_STR("src", ints({ RAD_VGEOM_CHUNK_LAT0 }).c_str()), + RAD_STR("mul", ints({ kFpc / kLpc }).c_str()), + RAD_STR("add", "0")), + RAD_NOWEIGHTS), + {}, { m.b_vf0 }); + auto stitch = [&](int64_t tile, int64_t stride) { + return rw(b, RAD_OP(b, "tile_stitch", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)(kFpc + kFtail) * m.maxSide), + RAD_INT("tile", tile), RAD_INT("stride", stride), + RAD_INT("scale", m.vAhw), RAD_INT("scale_t", m.vAt), + RAD_INT("p", kPix), RAD_INT("C", 3), RAD_STR("order", "wh"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vtiles, m.b_vf0 }, { m.b_frames }); + }; + m.op_vst1 = stitch(1 << 20, 1 << 20); + m.op_vst = stitch(kTile, kTileStride); + return m.op_vlat && m.op_vden && m.op_vcin && m.op_vnout && m.op_vcout && m.op_vgrid1 && + m.op_vgrid && m.op_vcrop && m.op_vf0 && m.op_vst1 && m.op_vst + ? RAD_OK + : RAD_E_INVAL; +} + +/* The encoder (LTX2VideoEncoder3d, causal) over one frame: the image in 4 x 4 patches, conv_in, + * four down blocks (residual blocks, then the downsampler: its convolution over the volume with + * its first st - 1 frames prepended, space to depth, the input's group mean added), the mid block, + * PerChannelRMSNorm with SiLU, conv_out; the mean's 128 channels normalised into the lane's clean + * first latent frame. A frame stays one frame through every temporal downsample. */ +static int declare_venc(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_REQUEST, gx = kGrpVenc; + const std::vector boc = meta_list(meta, "vae.block_out_channels"); + const std::vector lpb = meta_list(meta, "vae.layers_per_block"); + const std::vector sts = meta_list(meta, "vae.spatio_temporal_scaling"); + const char* types = rad_meta_gets(meta, "vae.downsample_type", ""); + std::vector dt; + for (const char* s = types; s && *s;) { + while (*s == ' ') ++s; + const char* e = s; + while (*e && *e != ' ') ++e; + if (e > s) dt.emplace_back(s, e); + s = e; + } + const size_t nd = boc.size(); + if (nd == 0 || lpb.size() != nd + 1 || dt.size() != nd || sts.size() != nd) { + fprintf(stderr, "radiance: ltx2: the VAE encoder's block lists disagree in length\n"); + return RAD_E_UNSUPPORTED; + } + m.venc = true; + const int64_t HW = m.maxPpf; /* latents a frame at most */ + int64_t Ahw = 64, C = kC, big = Ahw * HW * kPixC; + m.eC0 = C; + m.vdown.resize(nd); + /* The volumes: input (1, 8 h, 8 w) in latent units; the conv's (1 + tpre) frames. */ + for (size_t i = 0; i < nd; ++i) { + VDown& Dn = m.vdown[i]; + Dn.cin = C; + Dn.cout = (int64_t)boc[i]; + if (!sts[i]) return RAD_E_UNSUPPORTED; + if (dt[i] == "spatiotemporal") { Dn.st = 2; Dn.sh = 2; Dn.sw = 2; } + else if (dt[i] == "temporal") { Dn.st = 2; Dn.sh = 1; Dn.sw = 1; } + else if (dt[i] == "spatial") { Dn.st = 1; Dn.sh = 2; Dn.sw = 2; } + else return RAD_E_UNSUPPORTED; + const int64_t P = Dn.st * Dn.sh * Dn.sw; + Dn.conv_out = Dn.cout / P; + Dn.group = Dn.cin * P / Dn.cout; + if (Dn.conv_out * P != Dn.cout || Dn.group * Dn.cout != Dn.cin * P) return RAD_E_UNSUPPORTED; + big = std::max(big, Ahw * HW * C); + big = std::max(big, Dn.st * Ahw * HW * Dn.conv_out); + Ahw /= Dn.sh * Dn.sw; + C = Dn.cout; + big = std::max(big, Ahw * HW * C); + } + if (Ahw != 1) { + fprintf(stderr, "radiance: ltx2: the VAE encoder does not reach the latent's 32-pixel scale\n"); + return RAD_E_UNSUPPORTED; + } + m.eCout = C; + big = std::max(big, HW * (kC + 1)); + m.b_epatch = decl_b(b, nm.f("venc.patch"), RAD_BF16, { 64 * HW, kPixC }); + m.b_ea = decl_b(b, nm.f("venc.a"), RAD_BF16, { big }); + m.b_eb = decl_b(b, nm.f("venc.b"), RAD_BF16, { big }); + m.b_ec = decl_b(b, nm.f("venc.c"), RAD_BF16, { big }); + m.b_eout = decl_b(b, nm.f("venc.out"), RAD_BF16, { HW, kC + 1 }); + m.b_elat = decl_b(b, nm.f("venc.lat"), RAD_BF16, { HW, kC }); + m.op_epatch = rw(b, RAD_OP(b, "pix_patch", + RAD_PARAMS(RAD_RANGE("M", 1, 8 * HW), RAD_INT("p", kPix), RAD_INT("C", 3), + RAD_STR("order", "wh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_epatch }); + auto geom = [&](rad_buf* g, rad_op* op, const char* name, int64_t frames, int64_t mul) { + *g = decl_b(b, nm.f("venc.%s", name), RAD_I32, { 3 }, RAD_BUF_PERSIST); + *op = rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_STR("src", "-1 1 2"), + RAD_STR("mul", ints({ 0, mul, mul }).c_str()), + RAD_STR("add", ints({ frames, 0, 0 }).c_str())), + RAD_NOWEIGHTS), + {}, { *g }); + return *g && *op ? RAD_OK : RAD_E_INVAL; + }; + RAD_ARCH_TRY(geom(&m.b_egeomL, &m.op_egeomL, "geom_mid", 1, 1)); + auto conv = [&](rad_weight* w, rad_weight* bb, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t rows, int64_t tpre, rad_buf in, rad_buf out) -> rad_op { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.conv.weight", src), RAD_BF16, + { cout, cin, 3, 3, 3 }, acc, gx); + *bb = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.conv.bias", src), RAD_BF16, { cout }, acc, gx); + if (!*w || !*bb) return 0; + return rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", 3), RAD_INT("kt", 3), + RAD_STR("dtype", "bf16"), RAD_STR("tpad", "causal"), + RAD_INT("tpre", tpre)), + RAD_WEIGHTS(*w, *bb)), + { in }, { out }); + }; + m.op_ecin = conv(&m.w_ecin, &m.b_ecin, "venc.conv_in", "vae.encoder.conv_in", kPixC, kC, 64 * HW, 0, + m.b_epatch, m.b_ea); + if (!m.op_ecin) return RAD_E_INVAL; + Ahw = 64; + for (size_t i = 0; i < nd; ++i) { + VDown& Dn = m.vdown[i]; + const char* dn = nm.f("venc.down.%zu", i); + const char* src = nm.ckpt("vae.encoder.down_blocks.%zu", i); + const int64_t vin = Ahw * HW, nres = (int64_t)lpb[i]; + Dn.res.resize((size_t)nres); + for (int64_t r = 0; r < nres; ++r) + RAD_ARCH_TRY(vres_declare(b, m, Dn.res[(size_t)r], nm.f("%s.res.%lld", dn, (long long)r), + nm.ckpt("%s.resnets.%lld", src, (long long)r), Dn.cin, vin, + "causal", gx, m.b_ea, m.b_eb, m.b_ec)); + /* The residual's group mean into b, the convolution into c, its space to depth added. */ + const int64_t tpre = Dn.st - 1, sm = (int64_t)std::lround(std::sqrt((double)Ahw)); + Dn.op_mean = rw(b, RAD_OP(b, "s2d3d", + RAD_PARAMS(RAD_RANGE("M", 1, vin), RAD_INT("C", Dn.cin), + RAD_INT("st", Dn.st), RAD_INT("sh", Dn.sh), + RAD_INT("sw", Dn.sw), RAD_INT("tpre", tpre), + RAD_INT("group", Dn.group), RAD_STR("mode", "mean"), + RAD_INT("add", 0), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ea }, { m.b_eb }); + Dn.op_conv = conv(&Dn.w, &Dn.b, nm.f("%s.conv", dn), nm.ckpt("%s.downsamplers.0.conv", src), + Dn.cin, Dn.conv_out, vin, tpre, m.b_ea, m.b_ec); + Dn.op_s2d = rw(b, RAD_OP(b, "s2d3d", + RAD_PARAMS(RAD_RANGE("M", 1, Dn.st * vin), RAD_INT("C", Dn.conv_out), + RAD_INT("st", Dn.st), RAD_INT("sh", Dn.sh), + RAD_INT("sw", Dn.sw), RAD_STR("mode", "copy"), + RAD_INT("add", 1), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ec, m.b_eb }, { m.b_eb }); + /* The block's input volume and its convolution's ((1 + tpre) frames at this scale). */ + RAD_ARCH_TRY(geom(&Dn.geom_in, &Dn.op_geom_in, nm.f("geom_in%zu", i), 1, sm)); + RAD_ARCH_TRY(geom(&Dn.geom, &Dn.op_geom, nm.f("geom_conv%zu", i), 1 + tpre, sm)); + Ahw /= Dn.sh * Dn.sw; + /* The block's output (in b) back into the stream (a). */ + Dn.op_next = cast_op(b, Ahw * HW, Dn.cout, "bf16", "bf16", m.b_eb, m.b_ea); + if (!Dn.op_mean || !Dn.op_conv || !Dn.op_s2d || !Dn.op_next) return RAD_E_INVAL; + } + const int64_t nmid = (int64_t)lpb[nd]; + m.emid.resize((size_t)nmid); + for (int64_t r = 0; r < nmid; ++r) + RAD_ARCH_TRY(vres_declare(b, m, m.emid[(size_t)r], nm.f("venc.mid.%lld", (long long)r), + nm.ckpt("vae.encoder.mid_block.resnets.%lld", (long long)r), C, HW, + "causal", gx, m.b_ea, m.b_eb, m.b_ec)); + m.op_enout = rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, HW), RAD_INT("n", C), RAD_F64("eps", 1e-8), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ea }, { m.b_eb }); + m.op_ecout = conv(&m.w_ecout, &m.b_ecout, "venc.conv_out", "vae.encoder.conv_out", C, kC + 1, HW, 0, + m.b_eb, m.b_eout); + m.op_enorm = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, HW), RAD_INT("n", kC), + RAD_STR("mode", "norm"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.vd_mean, m.vd_std)), + { m.b_eout }, { m.b_elat }); + m.op_ef32 = cast_op(b, HW, kC, "bf16", "f32", m.b_elat, m.b_first); + return m.op_epatch && m.op_enout && m.op_ecout && m.op_enorm && m.op_ef32 && m.op_egeomL + ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the soundtrack */ +/* An audio VAE residual block over an image of (time) rows x `w` mel columns: PixelNorm with SiLU, + * conv1 (causal along time), again, conv2, the input or its 1 x 1 shortcut added. */ +static int ares_declare(RadBuilder* b, Model& m, ARes& Rb, const char* dn, const char* src, + int64_t cin, int64_t cout, int64_t px, rad_buf x, rad_buf t, rad_buf h, + rad_buf s) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpAudio; + Rb.cin = cin; + Rb.cout = cout; + auto conv = [&](rad_weight* w, rad_weight* bb, const char* name, int64_t ci, int64_t co, int64_t k, + rad_buf in, rad_buf out) -> rad_op { + *w = wcopy(b, nm.f("%s.%s.weight", dn, name), nm.ckpt("%s.%s.conv.weight", src, name), RAD_BF16, + { co, ci, k, k }, acc, gx); + *bb = wcopy(b, nm.f("%s.%s.bias", dn, name), nm.ckpt("%s.%s.conv.bias", src, name), RAD_BF16, + { co }, acc, gx); + if (!*w || !*bb) return 0; + return rw(b, RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("cin", ci), RAD_INT("cout", co), + RAD_INT("k", k), RAD_INT("stride", 1), + RAD_STR("pad", k > 1 ? "causal" : "same"), RAD_INT("up", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w, *bb)), + { in }, { out }); + }; + auto norm = [&](int64_t n, rad_buf in, rad_buf out) { + return rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", n), RAD_F64("eps", 1e-6), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); + }; + Rb.op_n1 = norm(cin, x, t); + Rb.op_c1 = conv(&Rb.w1, &Rb.b1, "conv1", cin, cout, 3, t, h); + Rb.op_n2 = norm(cout, h, t); + Rb.op_c2 = conv(&Rb.w2, &Rb.b2, "conv2", cout, cout, 3, t, h); + if (cin != cout) Rb.op_sc = conv(&Rb.ws, &Rb.bs, "nin_shortcut", cin, cout, 1, x, s); + Rb.op_add = add_op(b, px, cout, "bf16", cin != cout ? s : x, h, x); + return Rb.op_n1 && Rb.op_c1 && Rb.op_n2 && Rb.op_c2 && (cin == cout || Rb.op_sc) && Rb.op_add + ? RAD_OK : RAD_E_INVAL; +} + +static void ares_step(RadCtx* c, const ARes& Rb, int64_t H, int64_t W, rad_buf x, rad_buf t, + rad_buf h, rad_buf s) { + const int64_t px = H * W, ci = Rb.cin, co = Rb.cout; + RAD_ISSUE_N(c, Rb.op_n1, px, view(c, x, RAD_BF16, px, ci), view(c, t, RAD_BF16, px, ci)); + RAD_ISSUE_N(c, Rb.op_c1, px, view(c, t, RAD_BF16, H, W * ci), RAD_W(Rb.w1), RAD_W(Rb.b1), + view(c, h, RAD_BF16, H, W * co)); + RAD_ISSUE_N(c, Rb.op_n2, px, view(c, h, RAD_BF16, px, co), view(c, t, RAD_BF16, px, co)); + RAD_ISSUE_N(c, Rb.op_c2, px, view(c, t, RAD_BF16, H, W * co), RAD_W(Rb.w2), RAD_W(Rb.b2), + view(c, h, RAD_BF16, H, W * co)); + if (Rb.op_sc) { + RAD_ISSUE_N(c, Rb.op_sc, px, view(c, x, RAD_BF16, H, W * ci), RAD_W(Rb.ws), RAD_W(Rb.bs), + view(c, s, RAD_BF16, H, W * co)); + RAD_ISSUE_N(c, Rb.op_add, px, view(c, s, RAD_BF16, px, co), view(c, h, RAD_BF16, px, co), + view(c, x, RAD_BF16, px, co)); + } else { + RAD_ISSUE_N(c, Rb.op_add, px, view(c, x, RAD_BF16, px, co), view(c, h, RAD_BF16, px, co), + view(c, x, RAD_BF16, px, co)); + } +} + +/* A vocoder (LTX2Vocoder, f32) from `in` [rows, 128] to `V.wav` [rows x 160 or 240, 2]: conv_in, + * each stage an upsampling transposed convolution and the mean of three resnets (kernel 3, 7 and + * 11), each three dilations of anti-aliased SnakeBeta, dilated conv, again, conv and the residual; + * the last SnakeBeta and conv_out without a bias. `mult`: its input rows a mel frame of the audio + * VAE's output (the extender's input is at twice the rate). */ +static int voc_declare(RadBuilder* b, const RadModelMeta* meta, Model& m, Voc& V, const char* dn, + const char* src, const char* cfg, int64_t mult, rad_buf in) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpVoc; + static const int64_t kDil[3] = { 1, 3, 5 }; + auto key = [&](const char* k) { return nm.f("vocoder.%s%s", cfg, k); }; + V.in = 2 * kMel; + V.out = 2; + V.mult = mult; + V.in_buf = in; + V.hidden = rad_meta_geti(meta, key("hidden_channels"), 0); + for (double x : meta_list(meta, key("upsample_factors"))) V.rates.push_back((int64_t)x); + for (double x : meta_list(meta, key("upsample_kernel_sizes"))) V.ks.push_back((int64_t)x); + for (double x : meta_list(meta, key("resnet_kernel_sizes"))) V.rk.push_back((int64_t)x); + const std::vector dil = meta_list(meta, key("resnet_dilations")); + const size_t ns = V.rates.size(); + bool ok = V.hidden > 0 && ns > 0 && V.ks.size() == ns && V.rk.size() == 3 && dil.size() == 9 && + (V.hidden >> ns) >= 1; + for (size_t i = 0; ok && i < 9; ++i) ok = (int64_t)dil[i] == kDil[i % 3]; + if (!ok) { + fprintf(stderr, "radiance: ltx2: the %svocoder is not a BigVGAN of three resnets a stage " + "at dilations 1, 3, 5 (hidden %lld, %zu stages, %zu kernels, %zu resnet " + "kernels, %zu dilations)\n", cfg, (long long)V.hidden, ns, V.ks.size(), + V.rk.size(), dil.size()); + return RAD_E_UNSUPPORTED; + } + /* Rows a stage: (4 n - 3) mel frames times the upsampling so far. */ + std::vector rows(ns + 1); + rows[0] = mel_frames(m.maxA) * mult; + for (size_t s = 0; s < ns; ++s) rows[s + 1] = rows[s] * V.rates[s]; + auto cu = [&](int64_t f) { + rad_buf y = decl_b(b, nm.f("%s.cu%lld", dn, (long long)f), RAD_I32, { 2 }, RAD_BUF_PERSIST); + V.cu.push_back(y); + return rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 2), + RAD_STR("src", ints({ -1, RAD_VGEOM_N_AUDIO }).c_str()), + RAD_STR("mul", ints({ 0, 4 * f }).c_str()), + RAD_STR("add", ints({ 0, -3 * f }).c_str())), + RAD_NOWEIGHTS), + {}, { y }); + }; + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("%s.%s", dn, name), nm.ckpt("%s.%s", src, name), RAD_F32, shape, acc, gx); + }; + auto conv1 = [&](VConv& K, const char* name, int64_t ci, int64_t co, int64_t k, int64_t d, + bool bias, int64_t R, rad_buf x, rad_buf cub, rad_buf res, rad_buf y) { + K.w = wt(nm.f("%s.weight", name), { co, ci, k }); + if (bias) K.b = wt(nm.f("%s.bias", name), { co }); + if (!K.w || (bias && !K.b)) return RAD_E_INVAL; + rad_op op = bias ? RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", ci), + RAD_INT("cout", co), + RAD_INT("k", k), RAD_INT("dil", d), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(K.w, K.b)) + : RAD_OP(b, "conv1d", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("cin", ci), + RAD_INT("cout", co), + RAD_INT("k", k), RAD_INT("dil", d), RAD_STR("act", "none"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(K.w)); + K.op = res ? rw(b, op, { x, cub, res }, { y }) : rw(b, op, { x, cub }, { y }); + return K.op ? RAD_OK : RAD_E_INVAL; + }; + auto act = [&](VAct& a, const char* name, int64_t ch, int64_t R, rad_buf x, rad_buf cub, rad_buf y) { + a.alpha = wt(nm.f("%s.act.alpha", name), { ch }); + a.beta = wt(nm.f("%s.act.beta", name), { ch }); + a.up = wt(nm.f("%s.upsample.filter", name), { 1, 1, 12 }); + a.down = wt(nm.f("%s.downsample.filter", name), { 1, 1, 12 }); + if (!a.alpha || !a.beta || !a.up || !a.down) return RAD_E_INVAL; + a.op = rw(b, RAD_OP(b, "snake_aa", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", ch), RAD_INT("ratio", 2), + RAD_INT("k", 12), RAD_INT("log", 1), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(a.alpha, a.beta, a.up, a.down)), + { x, cub }, { y }); + return a.op ? RAD_OK : RAD_E_INVAL; + }; + V.op_cu0 = cu(mult); + V.h.resize(ns + 1); + V.avg.resize(ns + 1); + V.t1.resize(ns + 1); + V.t2.resize(ns + 1); + for (int j = 0; j < 3; ++j) V.amp[j].resize(ns + 1); + V.avg[0] = decl_b(b, nm.f("%s.h0", dn), RAD_F32, { rows[0], V.hidden }); + RAD_ARCH_TRY(conv1(V.cin, "conv_in", V.in, V.hidden, 7, 1, true, rows[0], in, V.cu[0], 0, V.avg[0])); + int64_t f = mult; + V.st.resize(ns); + for (size_t s = 0; s < ns; ++s) { + VStage& St = V.st[s]; + const int64_t ci = V.hidden >> s, co = V.hidden >> (s + 1), R = rows[s + 1]; + St.ch = co; + St.rate = V.rates[s]; + St.k = V.ks[s]; + f *= St.rate; + St.op_cu = cu(f); + V.h[s + 1] = decl_b(b, nm.f("%s.s%zu.in", dn, s), RAD_F32, { R, co }); + V.t1[s + 1] = decl_b(b, nm.f("%s.s%zu.t1", dn, s), RAD_F32, { R, co }); + V.t2[s + 1] = decl_b(b, nm.f("%s.s%zu.t2", dn, s), RAD_F32, { R, co }); + for (int j = 0; j < 3; ++j) + V.amp[j][s + 1] = decl_b(b, nm.f("%s.s%zu.amp%d", dn, s, j), RAD_F32, { R, co }); + St.up.w = wt(nm.f("upsamplers.%zu.weight", s), { ci, co, St.k }); + St.up.b = wt(nm.f("upsamplers.%zu.bias", s), { co }); + if (!St.up.w || !St.up.b || !St.op_cu) return RAD_E_INVAL; + St.up.op = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows[s]), RAD_INT("cin", ci), + RAD_INT("cout", co), RAD_INT("stride", St.rate), + RAD_INT("k", St.k), RAD_INT("pad", (St.k - St.rate) / 2), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(St.up.w, St.up.b)), + { V.avg[s], V.cu[s] }, { V.h[s + 1] }); + if (!St.up.op) return RAD_E_INVAL; + for (int j = 0; j < 3; ++j) { + const int ri = (int)(s * 3) + j; + for (int d = 0; d < 3; ++d) { + VUnit& U = St.u[j][d]; + const rad_buf x = d == 0 ? V.h[s + 1] : V.amp[j][s + 1]; + RAD_ARCH_TRY(act(U.a1, nm.f("resnets.%d.acts1.%d", ri, d), co, R, x, V.cu[s + 1], + V.t1[s + 1])); + RAD_ARCH_TRY(conv1(U.c1, nm.f("resnets.%d.convs1.%d", ri, d), co, co, V.rk[(size_t)j], + kDil[d], true, R, V.t1[s + 1], V.cu[s + 1], 0, V.t2[s + 1])); + RAD_ARCH_TRY(act(U.a2, nm.f("resnets.%d.acts2.%d", ri, d), co, R, V.t2[s + 1], + V.cu[s + 1], V.t1[s + 1])); + RAD_ARCH_TRY(conv1(U.c2, nm.f("resnets.%d.convs2.%d", ri, d), co, co, V.rk[(size_t)j], 1, + true, R, V.t1[s + 1], V.cu[s + 1], x, V.amp[j][s + 1])); + } + } + V.avg[s + 1] = decl_b(b, nm.f("%s.s%zu.out", dn, s), RAD_F32, { R, co }); + St.op_sum = add_op(b, R, co, "f32", V.amp[0][s + 1], V.amp[1][s + 1], V.avg[s + 1]); + St.op_avg = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", co), + RAD_STR("dtype", "f32"), + RAD_F64("div", 3.0)), + RAD_NOWEIGHTS), + { V.avg[s + 1], V.amp[2][s + 1] }, { V.avg[s + 1] }); + if (!St.op_sum || !St.op_avg) return RAD_E_INVAL; + } + const int64_t Rn = rows[ns], cn = V.hidden >> ns; + V.wav = decl_b(b, nm.f("%s.wav", dn), RAD_F32, { Rn, V.out }); + RAD_ARCH_TRY(act(V.act, "act_out", cn, Rn, V.avg[ns], V.cu[ns], V.t1[ns])); + return conv1(V.cout, "conv_out", cn, V.out, 7, 1, false, Rn, V.t1[ns], V.cu[ns], 0, V.wav); +} + +/* The soundtrack: the latent denormalised (f32) and unpacked to an image of (time) x 16 mel bins + * of 8 channels, the audio VAE's decoder (causal along time) to a stereo log-mel spectrogram, + * channel-major [frames, 2 x 64]; the vocoder to 16 kHz; the bandwidth extender's log-mel of that, + * its vocoder, and the sinc-resampled skip, to 48 kHz. */ +static int declare_audio(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpAudio; + const int64_t A = m.maxA, Tm = mel_frames(A); + const std::vector mult = meta_list(meta, "audio_vae.ch_mult"); + const int64_t base = rad_meta_geti(meta, "audio_vae.base_channels", 0); + const int64_t nrb = rad_meta_geti(meta, "audio_vae.num_res_blocks", 0); + if (mult.size() != 3 || nrb <= 0 || base <= 0) { + fprintf(stderr, "radiance: ltx2: the audio VAE is not three levels of residual blocks\n"); + return RAD_E_UNSUPPORTED; + } + m.aC0 = base * (int64_t)mult.back(); + m.b_aden = decl_b(b, nm.f("aud.den"), RAD_F32, { A, kAudioC }); + m.b_alat = decl_b(b, nm.f("aud.lat"), RAD_BF16, { A, kAudioC }); + m.b_aimg = decl_b(b, nm.f("aud.img"), RAD_BF16, { A * kLatMel, kLatCh }); + { + rad_weight& mw = m.w_amean; + rad_weight& sw = m.w_astd; + mw = wcopy(b, nm.f("aud.latents_mean"), nm.ckpt("audio_vae.latents_mean"), RAD_F32, { kAudioC }, + acc, gx); + sw = wcopy(b, nm.f("aud.latents_std"), nm.ckpt("audio_vae.latents_std"), RAD_F32, { kAudioC }, + acc, gx); + if (!mw || !sw) return RAD_E_INVAL; + m.op_aden = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, A), RAD_INT("n", kAudioC), + RAD_STR("mode", "denorm"), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(mw, sw)), + { m.b_astate }, { m.b_aden }); + } + m.op_acast = cast_op(b, A, kAudioC, "f32", "bf16", m.b_aden, m.b_alat); + m.op_aunpack = rw(b, RAD_OP(b, "d2s3d", + RAD_PARAMS(RAD_RANGE("M", 1, A), RAD_INT("C", kLatCh), RAD_INT("st", 1), + RAD_INT("sh", 1), RAD_INT("sw", kLatMel), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_alat }, { m.b_aimg }); + /* The decoder's images (time x mel x channels), the largest the last upsample's output: + * (4 A - 2) x 64 of level 1's channels. */ + const int64_t big = std::max(4 * A * kMel * base * (int64_t)mult[1], + A * kLatMel * m.aC0 * 4); + m.b_aa = decl_b(b, nm.f("aud.a"), RAD_BF16, { big }); + m.b_ab = decl_b(b, nm.f("aud.b"), RAD_BF16, { big }); + m.b_ac = decl_b(b, nm.f("aud.c"), RAD_BF16, { big }); + m.b_as = decl_b(b, nm.f("aud.s"), RAD_BF16, { big }); + m.b_amel16 = decl_b(b, nm.f("aud.mel16"), RAD_BF16, { Tm, 2 * kMel }); + m.b_amel = decl_b(b, nm.f("aud.mel"), RAD_F32, { Tm, 2 * kMel }); + const int64_t pxmax = 4 * A * kMel; + auto conv = [&](rad_weight* w, rad_weight* bb, const char* dn, const char* src, int64_t ci, + int64_t co, int up, rad_buf in, rad_buf out, int row = -1) -> rad_op { + const char* wn = nm.f("%s.weight", dn); + const char* bn = nm.f("%s.bias", dn); + if (row >= 0) { + if (map_rows(b, wn, { { nm.ckpt("%s.conv.weight", src), row, 1 } }) < 0 || + map_rows(b, bn, { { nm.ckpt("%s.conv.bias", src), row, 1 } }) < 0) + return 0; + *w = decl_w(b, wn, RAD_BF16, { co, ci, 3, 3 }, acc, RAD_SHARD_NONE, grp_layer(gx)); + *bb = decl_w(b, bn, RAD_BF16, { co }, acc, RAD_SHARD_NONE, grp_layer(gx)); + } else { + *w = wcopy(b, wn, nm.ckpt("%s.conv.weight", src), RAD_BF16, { co, ci, 3, 3 }, acc, gx); + *bb = wcopy(b, bn, nm.ckpt("%s.conv.bias", src), RAD_BF16, { co }, acc, gx); + } + if (!*w || !*bb) return 0; + return rw(b, RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, pxmax), RAD_INT("cin", ci), RAD_INT("cout", co), + RAD_INT("k", 3), RAD_INT("stride", 1), RAD_STR("pad", "causal"), + RAD_INT("up", up), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w, *bb)), + { in }, { out }); + }; + const char* dec = "audio_vae.decoder"; + m.op_acin = conv(&m.w_acin, &m.b_acin, "aud.conv_in", nm.ckpt("%s.conv_in", dec), kLatCh, m.aC0, 1, + m.b_aimg, m.b_aa); + if (!m.op_acin) return RAD_E_INVAL; + for (int i = 0; i < 2; ++i) + RAD_ARCH_TRY(ares_declare(b, m, m.amid[i], nm.f("aud.mid.%d", i), + nm.ckpt("%s.mid.block_%d", dec, i + 1), m.aC0, m.aC0, pxmax, m.b_aa, + m.b_ab, m.b_ac, m.b_as)); + /* Levels 2, 1, 0: residual blocks, then (but after level 0) the nearest upsample, its causal + * conv, and the rows past the first back into the stream. */ + int64_t cin = m.aC0; + m.aup.resize(3); + m.aups.resize(2); + m.aups_cp.resize(2); + m.alev_c.resize(3); + for (int lev = 2; lev >= 0; --lev) { + const int64_t co = base * (int64_t)mult[(size_t)lev]; + m.alev_c[(size_t)lev] = co; + std::vector& blk = m.aup[(size_t)(2 - lev)]; + blk.resize((size_t)(nrb + 1)); + for (int64_t i = 0; i <= nrb; ++i) { + RAD_ARCH_TRY(ares_declare(b, m, blk[(size_t)i], nm.f("aud.up%d.%lld", lev, (long long)i), + nm.ckpt("%s.up.%d.block.%lld", dec, lev, (long long)i), cin, co, + pxmax, m.b_aa, m.b_ab, m.b_ac, m.b_as)); + cin = co; + } + if (lev > 0) { + VConv& U = m.aups[(size_t)(2 - lev)]; + U.op = conv(&U.w, &U.b, nm.f("aud.up%d.upsample", lev), + nm.ckpt("%s.up.%d.upsample.conv", dec, lev), + co, co, 2, m.b_aa, m.b_ab); + m.aups_cp[(size_t)(2 - lev)] = cast_op(b, pxmax, co, "bf16", "bf16", m.b_ab, m.b_aa); + if (!U.op || !m.aups_cp[(size_t)(2 - lev)]) return RAD_E_INVAL; + } + } + m.op_anout = rw(b, RAD_OP(b, "pixel_norm", + RAD_PARAMS(RAD_RANGE("M", 1, pxmax), RAD_INT("n", cin), + RAD_F64("eps", 1e-6), + RAD_STR("form", "div"), RAD_STR("act", "silu"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_aa }, { m.b_ab }); + /* conv_out one output channel at a time, each into its 64 columns of the spectrogram: the + * vocoder's channel-major layout (channel 64 + mel). */ + for (int ch = 0; ch < 2; ++ch) { + m.op_acout[ch] = conv(&m.w_acout[ch], &m.b_acout[ch], nm.f("aud.conv_out%d", ch), + nm.ckpt("%s.conv_out", dec), cin, 1, 1, m.b_ab, m.b_amel16, ch); + if (!m.op_acout[ch]) return RAD_E_INVAL; + } + m.op_amel = cast_op(b, Tm, 2 * kMel, "bf16", "f32", m.b_amel16, m.b_amel); + + /* The vocoder; the extender's log-mel of its waveform (rounded as the reference's bf16 one), + * its vocoder, the skip and the clamp into the soundtrack. */ + RAD_ARCH_TRY(voc_declare(b, meta, m, m.voc, "voc", "vocoder.vocoder", "", 1, m.b_amel)); + const int64_t Sw = Tm * kMelHop; + m.w_basis = wcopy(b, nm.f("voc.stft_basis"), nm.ckpt("vocoder.mel_stft.stft_fn.forward_basis"), + RAD_BF16, { 514, 1, 512 }, acc, kGrpVoc); + m.w_melb = wcopy(b, nm.f("voc.mel_basis"), nm.ckpt("vocoder.mel_stft.mel_basis"), RAD_BF16, + { kMel, 257 }, acc, kGrpVoc); + if (!m.w_basis || !m.w_melb) return RAD_E_INVAL; + m.b_bmel16 = decl_b(b, nm.f("bwe.mel16"), RAD_BF16, { Sw / 80, 2 * kMel }); + m.b_bmel = decl_b(b, nm.f("bwe.mel"), RAD_F32, { Sw / 80, 2 * kMel }); + m.op_stft = rw(b, RAD_OP(b, "stft_logmel", + RAD_PARAMS(RAD_RANGE("M", 1, Sw / 80), RAD_INT("hop", 80), + RAD_INT("nfft", 512), RAD_INT("n_mel", kMel), + RAD_INT("ch", 2), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_basis, m.w_melb)), + { m.voc.wav }, { m.b_bmel16 }); + m.op_bmel = cast_op(b, Sw / 80, 2 * kMel, "bf16", "f32", m.b_bmel16, m.b_bmel); + RAD_ARCH_TRY(voc_declare(b, meta, m, m.bwe, "bwe", "vocoder.bwe_generator", "bwe_", 2, m.b_bmel)); + /* The vocoders' f32 convolutions read f32 weights; a pipeline saved in bf16 holds them bf16, + * and the recipes cast them back (`voc.*` and `bwe.*`, cast dtype=f32). */ + for (const char* w : { "voc.conv_in.weight", "bwe.conv_in.weight" }) { + if (weight_codes_dtype(b, w, RAD_F32) != RAD_F32) { + fprintf(stderr, "radiance: ltx2: '%s' is stored %s; the vocoders run in f32 -- convert " + "with data/recipes/ltx-2.5-bf16.recipe or ltx-2.5-fp8.recipe, which " + "cast them\n", w, rad_dtype_name(weight_codes_dtype(b, w, RAD_F32))); + return RAD_E_UNSUPPORTED; + } + } + m.b_audio = decl_b(b, nm.f("audio_out"), RAD_F32, { A * ((int64_t)kRate / kAudioRate), kAudioCh }, + RAD_BUF_PERSIST); + m.op_bwe = rw(b, RAD_OP(b, "bwe_up", + RAD_PARAMS(RAD_RANGE("M", 1, 3 * Sw), RAD_INT("ratio", 3), RAD_INT("ch", 2), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.voc.wav, m.bwe.wav }, { m.b_audio }); + /* The samples past the decoder's (its causal frames are 3 short of 4 a latent): silence. */ + m.op_tail = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 3 * kMelHop * 3), RAD_INT("n", kAudioCh), + RAD_STR("dtype", "f32"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_audio }); + return m.op_aden && m.op_acast && m.op_aunpack && m.op_anout && m.op_amel && m.op_stft && + m.op_bmel && m.op_bwe && m.op_tail + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the latent upsampler */ +/* LTX2LatentUpsamplerModel (spatial x2, no rational resampler): the clean small latent + * denormalised (f32, then bf16), initial_conv, GroupNorm and SiLU, residual blocks, each frame's + * Conv2d to four times the channels and the pixel shuffle, residual blocks at the full size, + * final_conv; normalised again (bf16) into the lane. */ +static int declare_ups(RadBuilder* b, const RadModelMeta* meta, Model& m) { + if (!rad_meta_gets(meta, "latent_upsampler._class_name", nullptr)) return RAD_OK; + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpUps; + const int64_t C = rad_meta_geti(meta, "latent_upsampler.mid_channels", 0); + const int64_t nb = rad_meta_geti(meta, "latent_upsampler.num_blocks_per_stage", 0); + if (std::strcmp(rad_meta_gets(meta, "latent_upsampler._class_name", ""), + "LTX2LatentUpsamplerModel") || + rad_meta_geti(meta, "latent_upsampler.in_channels", 0) != kC || + rad_meta_geti(meta, "latent_upsampler.dims", 0) != 3 || + rad_meta_geti(meta, "latent_upsampler.spatial_upsample", 0) != 1 || + rad_meta_geti(meta, "latent_upsampler.temporal_upsample", 1) != 0 || + rad_meta_geti(meta, "latent_upsampler.use_rational_resampler", 1) != 0 || C <= 0 || C % 32 || + nb <= 0) { + fprintf(stderr, "radiance: ltx2: latent_upsampler/ is not the spatial x2 upsampler this plugin " + "runs (3D, no rational resampler, GroupNorm over 32 groups)\n"); + return RAD_E_UNSUPPORTED; + } + m.ups = true; + m.uC = C; + /* the full size's voxels; the small size's are a quarter */ + const int64_t V = m.maxS; + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("ups.%s", name), nm.ckpt("latent_upsampler.%s", name), RAD_BF16, shape, acc, + gx); + }; + auto conv = [&](rad_weight w, rad_weight bb, int64_t ci, int64_t co, int64_t rows, rad_buf x, + rad_buf y) -> rad_op { + if (!w || !bb) return 0; + return rw(b, RAD_OP(b, "conv3d_ndhwc", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", ci), RAD_INT("cout", co), + RAD_INT("k", 3), RAD_INT("kt", 3), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)), + { x }, { y }); + }; + m.b_ust = decl_b(b, nm.f("ups.gn_stats"), RAD_F32, { 32 * (2 + 3 * 1024) }); + auto gnorm = [&](rad_weight w, rad_weight bb, bool silu, int64_t rows, rad_buf x, + rad_buf y) -> rad_op { + if (!w || !bb) return 0; + return rw(b, RAD_OP(b, "group_norm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", C), RAD_INT("groups", 32), + RAD_F64("eps", 1e-5), RAD_STR("act", silu ? "silu" : "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)), + { x, m.b_ust }, { y, m.b_ust }); + }; + m.b_uin = decl_b(b, nm.f("ups.in"), RAD_BF16, { V, kC }); + m.b_ua = decl_b(b, nm.f("ups.a"), RAD_BF16, { V, C }); + m.b_ub = decl_b(b, nm.f("ups.b"), RAD_BF16, { V, C }); + m.b_uc = decl_b(b, nm.f("ups.c"), RAD_BF16, { V, C }); + m.b_uout = decl_b(b, nm.f("ups.out"), RAD_BF16, { V, kC }); + m.b_uden = decl_b(b, nm.f("ups.den"), RAD_F32, { V, kC }); + m.op_uden = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", kC), + RAD_STR("mode", "denorm"), + RAD_STR("dtype", "f32")), + RAD_WEIGHTS(m.vd_mean, m.vd_std)), + { m.b_vstate }, { m.b_uden }); + m.op_ucast = cast_op(b, V, kC, "f32", "bf16", m.b_uden, m.b_uin); + m.u_cinw = wt("initial_conv.weight", { C, kC, 3, 3, 3 }); + m.u_cinb = wt("initial_conv.bias", { C }); + m.u_ninw = wt("initial_norm.weight", { C }); + m.u_ninb = wt("initial_norm.bias", { C }); + m.op_ucin = conv(m.u_cinw, m.u_cinb, kC, C, V, m.b_uin, m.b_ua); + m.op_unin = gnorm(m.u_ninw, m.u_ninb, true, V, m.b_ua, m.b_ua); + auto blocks = [&](const char* side, std::vector& list) { + list.resize((size_t)nb); + for (int64_t i = 0; i < nb; ++i) { + URes& U = list[(size_t)i]; + const char* p = nm.f("%s.%lld", side, (long long)i); + U.c1w = wt(nm.f("%s.conv1.weight", p), { C, C, 3, 3, 3 }); + U.c1b = wt(nm.f("%s.conv1.bias", p), { C }); + U.n1w = wt(nm.f("%s.norm1.weight", p), { C }); + U.n1b = wt(nm.f("%s.norm1.bias", p), { C }); + U.c2w = wt(nm.f("%s.conv2.weight", p), { C, C, 3, 3, 3 }); + U.c2b = wt(nm.f("%s.conv2.bias", p), { C }); + U.n2w = wt(nm.f("%s.norm2.weight", p), { C }); + U.n2b = wt(nm.f("%s.norm2.bias", p), { C }); + U.op_c1 = conv(U.c1w, U.c1b, C, C, V, m.b_ua, m.b_ub); + U.op_n1 = gnorm(U.n1w, U.n1b, true, V, m.b_ub, m.b_ub); + U.op_c2 = conv(U.c2w, U.c2b, C, C, V, m.b_ub, m.b_uc); + U.op_n2 = gnorm(U.n2w, U.n2b, false, V, m.b_uc, m.b_uc); + U.op_add = add_op(b, V, C, "bf16", m.b_uc, m.b_ua, m.b_ua); + U.op_act = unary(b, "silu", V, C, "bf16", m.b_ua, m.b_ua); + if (!U.op_c1 || !U.op_n1 || !U.op_c2 || !U.op_n2 || !U.op_add || !U.op_act) + return RAD_E_INVAL; + } + return RAD_OK; + }; + RAD_ARCH_TRY(blocks("res_blocks", m.u_pre)); + m.u_upw = wt("upsampler.0.weight", { 4 * C, C, 3, 3 }); + m.u_upb = wt("upsampler.0.bias", { 4 * C }); + if (!m.u_upw || !m.u_upb) return RAD_E_INVAL; + /* Each frame through Conv2d (issued a frame at a time), then the pixel shuffle over the volume + * (channel c 4 + 2 i_h + i_w to (2 h + i_h, 2 w + i_w)). */ + m.op_uup = rw(b, RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, V / 4), RAD_INT("cin", C), + RAD_INT("cout", 4 * C), + RAD_INT("k", 3), RAD_INT("stride", 1), RAD_STR("pad", "same"), + RAD_INT("up", 1), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.u_upw, m.u_upb)), + { m.b_ua }, { m.b_ub }); + m.op_ud2s = rw(b, RAD_OP(b, "d2s3d", + RAD_PARAMS(RAD_RANGE("M", 1, V / 4), RAD_INT("C", C), RAD_INT("st", 1), + RAD_INT("sh", 2), RAD_INT("sw", 2), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ub }, { m.b_ua }); + RAD_ARCH_TRY(blocks("post_upsample_res_blocks", m.u_post)); + m.u_coutw = wt("final_conv.weight", { kC, C, 3, 3, 3 }); + m.u_coutb = wt("final_conv.bias", { kC }); + m.op_ucout = conv(m.u_coutw, m.u_coutb, C, kC, V, m.b_ua, m.b_uout); + m.op_unorm = rw(b, RAD_OP(b, "chan_stats", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", kC), RAD_STR("mode", "norm"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.vd_mean, m.vd_std)), + { m.b_uout }, { m.b_uout }); + m.op_uf32 = cast_op(b, V, kC, "bf16", "f32", m.b_uout, m.b_vstate); + /* With a first frame, its upscaled latent frame is the new clean one: kept aside before the + * re-noise and put back after. */ + m.op_ufirst = cast_op(b, m.maxPpf, kC, "f32", "f32", m.b_vstate, m.b_first); + m.op_ukeep = cast_op(b, m.maxPpf, kC, "f32", "f32", m.b_first, m.b_vstate); + auto renoise = [&](int64_t rows, rad_buf x) { + return rw(b, RAD_OP(b, "flow_renoise", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", kC), RAD_INT("stream", 1), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { x }, { x }); + }; + m.op_urnv = renoise(V, m.b_vstate); + m.op_urna = renoise(m.maxA, m.b_astate); + return m.op_uden && m.op_ucast && m.op_ucin && m.op_unin && m.op_uup && m.op_ud2s && m.op_ucout && + m.op_unorm && m.op_uf32 && m.op_ufirst && m.op_ukeep && m.op_urnv && m.op_urna + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the duration head */ +/* LTX2DurationHead: each connector's output for the prompt (not the negative) projected to the + * pooler's width with its modality's embedding added, the two runs concatenated, one learned query + * attending over them (four heads, no mask), the pooled row through a tanh-GELU MLP to the log of + * the length in seconds, which the core reads back (RadVideoGenDecl::duration_out). */ +static int declare_dur(RadBuilder* b, const RadModelMeta* meta, Model& m) { + if (!rad_meta_gets(meta, "duration_head._class_name", nullptr)) return RAD_OK; + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_TOKEN, gx = kGrpDur; + const int64_t P = rad_meta_geti(meta, "duration_head.pooler_hidden_dim", 0); + const int64_t Hm = rad_meta_geti(meta, "duration_head.mlp_hidden_dim", 0); + const int64_t nh = rad_meta_geti(meta, "duration_head.num_pooler_heads", 0); + if (std::strcmp(rad_meta_gets(meta, "duration_head._class_name", ""), "LTX2DurationHead") || + rad_meta_geti(meta, "duration_head.video_cross_attention_dim", 0) != m.cv.D || + rad_meta_geti(meta, "duration_head.audio_cross_attention_dim", 0) != m.ca.D || + rad_meta_geti(meta, "duration_head.num_queries", 0) != 1 || P <= 0 || Hm <= 0 || + nh <= 0 || P % nh || P / nh != 64 || P > std::max(m.cv.D, m.ca.D)) { + fprintf(stderr, "radiance: ltx2: duration_head/ is not the LTX2DurationHead this plugin " + "runs (the connectors' widths in, one query, heads of 64)\n"); + return RAD_E_UNSUPPORTED; + } + m.dur = true; + m.dP = P; + const int64_t R = kTextRows; + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("dur.%s", name), nm.ckpt("duration_head.%s", name), RAD_BF16, shape, + acc, gx); + }; + m.dw_vp = wt("video_input_proj.weight", { P, m.cv.D }); + m.dw_vpb = wt("video_input_proj.bias", { P }); + m.dw_vemb = wt("video_modality_emb", { 1, P }); + m.dw_ap = wt("audio_input_proj.weight", { P, m.ca.D }); + m.dw_apb = wt("audio_input_proj.bias", { P }); + m.dw_aemb = wt("audio_modality_emb", { 1, P }); + m.dw_qt = wt("attention_pooler.query_tokens", { 1, P }); + m.dw_q = wt("attention_pooler.to_q.weight", { P, P }); + m.dw_qb = wt("attention_pooler.to_q.bias", { P }); + m.dw_k = wt("attention_pooler.to_k.weight", { P, P }); + m.dw_kb = wt("attention_pooler.to_k.bias", { P }); + m.dw_v = wt("attention_pooler.to_v.weight", { P, P }); + m.dw_vb = wt("attention_pooler.to_v.bias", { P }); + m.dw_o = wt("attention_pooler.to_out.weight", { P, P }); + m.dw_ob = wt("attention_pooler.to_out.bias", { P }); + m.dw_h = wt("mlp_hidden.weight", { Hm, P }); + m.dw_hb = wt("mlp_hidden.bias", { Hm }); + m.dw_out = wt("mlp_out.weight", { 1, Hm }); + m.dw_outb = wt("mlp_out.bias", { 1 }); + m.b_dtok = decl_b(b, nm.f("dur.tok"), RAD_BF16, { 2 * R, P }); + m.b_dk = decl_b(b, nm.f("dur.k"), RAD_BF16, { 2 * R, P }); + m.b_dv = decl_b(b, nm.f("dur.v"), RAD_BF16, { 2 * R, P }); + m.b_dq0 = decl_b(b, nm.f("dur.query"), RAD_BF16, { 1, P }); + m.b_dq = decl_b(b, nm.f("dur.q"), RAD_BF16, { 1, P }); + m.b_dat = decl_b(b, nm.f("dur.attn"), RAD_BF16, { 1, P }); + m.b_do = decl_b(b, nm.f("dur.pooled"), RAD_BF16, { 1, P }); + m.b_dh = decl_b(b, nm.f("dur.hidden"), RAD_BF16, { 1, Hm }); + m.b_dl = decl_b(b, nm.f("dur.log"), RAD_BF16, { 1, 1 }); + m.b_dcu = decl_b(b, nm.f("dur.cu"), RAD_I32, { 2 }); + m.b_dcuk = decl_b(b, nm.f("dur.cu_k"), RAD_I32, { 2 }); + m.b_dur = decl_b(b, nm.f("dur.out"), RAD_F32, { 1 }, RAD_BUF_PERSIST); + auto gemm = [&](rad_weight w, rad_weight bb, int64_t rows, int64_t N, int64_t K, rad_buf x, + rad_buf y, const char* act) -> rad_op { + if (!w || !bb || !x || !y) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16"), RAD_STR("act", act)), + RAD_WEIGHTS(w, bb)), + { x }, { y }); + }; + auto emb = [&](rad_weight w, int64_t rows, rad_buf x, rad_buf y) -> rad_op { + if (!w) return 0; + return rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", P), RAD_INT("L", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); + }; + auto iota = [&](int64_t step, rad_buf y) { + return rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("start", 0), + RAD_INT("step", step)), + RAD_NOWEIGHTS), + {}, { y }); + }; + m.op_dvp = gemm(m.dw_vp, m.dw_vpb, R, P, m.cv.D, m.cv.b_text, m.b_dtok, "none"); + m.op_dap = gemm(m.dw_ap, m.dw_apb, R, P, m.ca.D, m.ca.b_text, m.b_dtok, "none"); + m.op_dvemb = emb(m.dw_vemb, R, m.b_dtok, m.b_dtok); + m.op_daemb = emb(m.dw_aemb, R, m.b_dtok, m.b_dtok); + m.op_dq0 = emb(m.dw_qt, 1, m.b_zero, m.b_dq0); + m.op_dq = gemm(m.dw_q, m.dw_qb, 1, P, P, m.b_dq0, m.b_dq, "none"); + m.op_dk = gemm(m.dw_k, m.dw_kb, 2 * R, P, P, m.b_dtok, m.b_dk, "none"); + m.op_dv = gemm(m.dw_v, m.dw_vb, 2 * R, P, P, m.b_dtok, m.b_dv, "none"); + m.op_dcu = iota(1, m.b_dcu); + m.op_dcuk = iota(2 * R, m.b_dcuk); + m.op_dattn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("head_dim", P / nh), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dq, m.b_dk, m.b_dv, m.b_dcu, m.b_dcuk }, { m.b_dat }); + m.op_do = gemm(m.dw_o, m.dw_ob, 1, P, P, m.b_dat, m.b_do, "none"); + m.op_dh = gemm(m.dw_h, m.dw_hb, 1, Hm, P, m.b_do, m.b_dh, "gelu_tanh"); + m.op_dout = gemm(m.dw_out, m.dw_outb, 1, 1, Hm, m.b_dh, m.b_dl, "none"); + m.op_dlog = cast_op(b, 1, 1, "bf16", "f32", m.b_dl, m.b_dur); + return m.op_dvp && m.op_dap && m.op_dvemb && m.op_daemb && m.op_dq0 && m.op_dq && m.op_dk && + m.op_dv && m.op_dcu && m.op_dcuk && m.op_dattn && m.op_do && m.op_dh && + m.op_dout && m.op_dlog + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the diffusion decoder */ +/* LTX2VideoDiffusionDecoder3d (LTX-2.5's diffusion_decoder/; diffusers' ltx2_diffusion_decoder.py), + * run as the README's diffusion decode runs it, its tiling on (enable_tiling). The latent, its last + * frame repeated twice past its end (the ghost frames NATTEN's inward-shifted border needs), goes + * through four deterministic stages of neighbourhood-attention blocks (pre-norm, a 3-D rotary over + * the voxel coordinates, a SwiGLU feed-forward), each followed by a pixel-shuffle upsample; the + * first three over the whole video into the feature volume. That volume is cut as _tile_intervals + * cuts it (768 pixels every 704, 80 frames every 56: on the feature grid 96 cells every 88 and 40 + * every 28, 6 at least), and each tile runs the fourth stage (the tile starting the video drops + * the upsample's duplicate leading frame; the one ending it its ghost frames) and one denoising + * step from noise -- x0 predicted at timestep 1 -- over 4 x 4 pixel patches: eight diffusion blocks + * conditioned on the fourth stage's output, their norms modulated by the timestep's shared table + * plus each block's own. The tiles' pixels go to the tile store and blend as tile_stitch does. */ +enum { kDdTile = 96, kDdStride = 88, kDdTileT = 40, kDdStrideT = 28, kDdLeast = 6, kDdGhost = 2, + kDdGhostCells = 8, kDdMaxTiles = 16 }; +/* A feed-forward launch's hidden rows: gate and up at most this many elements. */ +static const int64_t kDdFfElems = 64ll << 20; + +/* The decoder's cut of an axis (tile_grid's `intervals` rule) and the tiles of a feature grid. */ +struct DdTile { int64_t t, t0, h, w; bool origin, trailing; }; +static int64_t dd_count(int64_t L, int64_t tile, int64_t stride) { + if (L <= tile) return 1; + int64_t n = (L + stride - 1) / stride; + while (n > 1 && L - (n - 1) * stride < kDdLeast) --n; + return n; +} +static int64_t dd_len(int64_t L, int64_t k, int64_t tile, int64_t stride) { + return k == dd_count(L, tile, stride) - 1 ? L - k * stride : std::min(tile, L - k * stride); +} +static std::vector dd_tiles(int64_t T, int64_t H, int64_t W) { + std::vector v; + const int64_t nt = dd_count(T, kDdTileT, kDdStrideT), ni = dd_count(H, kDdTile, kDdStride); + const int64_t nj = dd_count(W, kDdTile, kDdStride); + for (int64_t kt = 0; kt < nt; ++kt) + for (int64_t i = 0; i < ni; ++i) + for (int64_t j = 0; j < nj; ++j) + v.push_back({ dd_len(T, kt, kDdTileT, kDdStrideT) + (kt == nt - 1 ? kDdGhostCells : 0), + kt * kDdStrideT, dd_len(H, i, kDdTile, kDdStride), + dd_len(W, j, kDdTile, kDdStride), kt == 0, kt == nt - 1 }); + return v; +} + +static rad_op dd_gemm(RadBuilder* b, rad_weight w, rad_weight bb, int64_t rows, int64_t N, int64_t K, + std::initializer_list rd, rad_buf y) { + if (!w) return 0; + rad_op op = bb ? RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bb)) + : RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + return rw(b, op, rd, { y }); +} + +/* One block's weights and ops over at most V voxels of residual `x`. */ +static int dd_block_declare(RadBuilder* b, Model& m, DdBlock& B, const char* dn, const char* src, + int64_t C, int slot, const int64_t* kernel, int64_t V, bool diff, rad_buf x) { + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_REQUEST, gx = kGrpDdec; + B.C = C; + B.ff = (C * 4 + 15) / 16 * 16; + B.kt = kernel[0]; + B.kh = kernel[1]; + B.kw = kernel[2]; + B.slot = slot; + B.chunk = std::min(V, kDdFfElems / (2 * B.ff)); + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("%s.%s", dn, name), nm.ckpt("%s.%s", src, name), RAD_BF16, shape, acc, gx); + }; + B.w_n1 = wt("norm1.weight", { C }); + /* The diffusion stage's q|k|v of every voxel would be three times its residual (3.7 GiB at the + * largest tile), so it projects and attends a head at a time into b_dao; the others take + * every head at once. */ + const int64_t gw = diff ? 64 : C; + for (int64_t g = 0; g < C / gw; ++g) { + const char* wn = nm.f("%s.attn.qkv%lld.weight", dn, (long long)g); + const char* bn = nm.f("%s.attn.qkv%lld.bias", dn, (long long)g); + RadNameMap mw = map_base(wn, RAD_MAP_ROWS), mb = map_base(bn, RAD_MAP_ROWS); + for (const char* pr : { "to_q", "to_k", "to_v" }) { + mw.src[mw.n_src] = nm.ckpt("%s.attn.%s.weight", src, pr); + mw.src_index[mw.n_src] = (int)(g * gw); + mw.src_rows[mw.n_src++] = gw; + mb.src[mb.n_src] = nm.ckpt("%s.attn.%s.bias", src, pr); + mb.src_index[mb.n_src] = (int)(g * gw); + mb.src_rows[mb.n_src++] = gw; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mw)); + RAD_ARCH_TRY(rad_decl_name_map(b, &mb)); + B.w_qkvh.push_back(decl_w(b, wn, RAD_BF16, { 3 * gw, C }, acc, RAD_SHARD_NONE, grp_layer(gx))); + B.b_qkvh.push_back(decl_w(b, bn, RAD_BF16, { 3 * gw }, acc, RAD_SHARD_NONE, grp_layer(gx))); + if (!B.w_qkvh.back() || !B.b_qkvh.back()) return RAD_E_INVAL; + } + B.w_nq = wt("attn.norm_q.weight", { 64 }); + B.w_nk = wt("attn.norm_k.weight", { 64 }); + B.w_o = wt("attn.to_out.0.weight", { C, C }); + B.b_o = wt("attn.to_out.0.bias", { C }); + B.w_n2 = wt("norm2.weight", { C }); + /* gate and up as one weight: one gemm writes whole rows of the gate|up buffer */ + const char* gun = nm.f("%s.mlp.w_gate_up.weight", dn); + RAD_ARCH_TRY(map_concat(b, gun, { nm.ckpt("%s.mlp.w_gate.weight", src), + nm.ckpt("%s.mlp.w_up.weight", src) })); + B.w_gu = decl_w(b, gun, RAD_BF16, { 2 * B.ff, C }, acc, RAD_SHARD_NONE, grp_layer(gx)); + B.w_down = wt("mlp.w_down.weight", { C, B.ff }); + if (!B.w_n1 || !B.w_nq || !B.w_nk || !B.w_o || !B.b_o || !B.w_n2 || !B.w_gu || !B.w_down) + return RAD_E_INVAL; + const rad_buf qkv = m.b_dqkv[slot], gu = m.b_dg[slot]; + auto modded = [&](rad_weight w) { + const rad_op op = RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("n", C), RAD_F64("eps", 1e-6), + RAD_INT("gated", 0), RAD_STR("dtype", "bf16"), + RAD_INT("norm_once", 1)), + RAD_WEIGHTS(w)); + if (!op) return (rad_op)0; + const rad_buf rd[3] = { m.b_dbmod, x, m.b_ddcu }; + const rad_buf wr[2] = { x, m.b_dn }; + rad_op_reads(b, op, rd, 3); + rad_op_writes(b, op, wr, 2); + return op; + }; + if (diff) { + B.w_ctx = wt("context_proj.weight", { C, C }); + B.b_ctx = wt("context_proj.bias", { C }); + /* The block's table rows (shift, scale) of the attention's norm, then of the MLP's: the + * reference's chunks 1, 0, 4 and 3, the order rms_mod reads them in. */ + const char* tn = nm.f("%s.mod_table", dn); + RadNameMap mp = map_base(tn, RAD_MAP_ROWS); + for (int r : { 1, 0, 4, 3 }) { + mp.src[mp.n_src] = nm.ckpt("%s.scale_shift_table", src); + mp.src_index[mp.n_src] = r; + mp.src_rows[mp.n_src++] = 1; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + B.w_sst = decl_w(b, tn, RAD_BF16, { 1, 4 * C }, acc, RAD_SHARD_NONE, grp_layer(gx)); + if (!B.w_ctx || !B.b_ctx || !B.w_sst) return RAD_E_INVAL; + B.op_ctx = dd_gemm(b, B.w_ctx, B.b_ctx, V, C, C, { m.b_dctx, x }, x); + B.op_mod = rw(b, RAD_OP(b, "table_add", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 4 * C), RAD_INT("L", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(B.w_sst)), + { m.b_dmod }, { m.b_dbmod }); + B.op_n1 = modded(B.w_n1); + B.op_n2 = modded(B.w_n2); + if (!B.op_ctx || !B.op_mod) return RAD_E_INVAL; + } else { + B.op_n1 = rms_op(b, V, C, 1e-6, B.w_n1, x, m.b_dn); + B.op_n2 = rms_op(b, V, C, 1e-6, B.w_n2, x, m.b_dn); + } + const int64_t nh = gw / 64; + const rad_buf ao = diff ? m.b_dao : m.b_dn; + for (size_t g = 0; g < B.w_qkvh.size(); ++g) { + B.op_qkvh.push_back(dd_gemm(b, B.w_qkvh[g], B.b_qkvh[g], V, 3 * gw, C, { m.b_dn }, qkv)); + if (!B.op_qkvh.back()) return RAD_E_INVAL; + } + B.op_rope = RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("head_dim", 64), + RAD_INT("n_head", nh), RAD_INT("n_head_kv", nh), + RAD_F64("theta", 10000.0), RAD_F64("eps", 1e-6), + RAD_STR("mode", "gptj_blocks"), RAD_INT("rotary_dim", 64), + RAD_STR("sections", "8 12 12")), + RAD_WEIGHTS(B.w_nq, B.w_nk)); + if (B.op_rope) { + const rad_buf rd[2] = { qkv, m.b_dpos }; + rad_op_reads(b, B.op_rope, rd, 2); + rad_op_writes(b, B.op_rope, &qkv, 1); + } + B.op_attn = rw(b, RAD_OP(b, "attn_na3d", + RAD_PARAMS(RAD_RANGE("M", 1, V), RAD_INT("head_dim", 64), + RAD_INT("kt", B.kt), RAD_INT("kh", B.kh), RAD_INT("kw", B.kw), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { qkv }, { ao }); + B.op_o = dd_gemm(b, B.w_o, B.b_o, V, C, C, { ao, x }, x); + B.op_gu = dd_gemm(b, B.w_gu, 0, B.chunk, 2 * B.ff, C, { m.b_dn }, gu); + B.op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, B.chunk), RAD_INT("n", B.ff), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { gu }, { m.b_da }); + B.op_down = dd_gemm(b, B.w_down, 0, B.chunk, C, B.ff, { m.b_da }, m.b_dmo); + B.op_add2 = add_op(b, B.chunk, C, "bf16", x, m.b_dmo, x); + return B.op_n1 && B.op_n2 && B.op_rope && B.op_attn && B.op_o && B.op_gu && B.op_act && + B.op_down && B.op_add2 + ? RAD_OK + : RAD_E_INVAL; +} + +static int declare_ddec(RadBuilder* b, const RadModelMeta* meta, Model& m) { + if (!rad_meta_gets(meta, "diffusion_decoder._class_name", nullptr)) return RAD_OK; + Names& nm = m.nm; + const int acc = RAD_ACCESS_PER_REQUEST, gx = kGrpDdec; + auto list = [&](const char* k) { return meta_list(meta, nm.f("diffusion_decoder.%s", k)); }; + const std::vector ch = list("decoder_stage_channels"), dep = list("decoder_stage_depths"); + const std::vector ker = list("decoder_stage_kernels"), str = list("decoder_upsample_strides"); + const std::vector red = list("decoder_upsample_channel_reductions"); + const std::vector k5 = list("decoder_stage5_kernel"); + const std::vector want_ch = { 2048, 1024, 512, 512, 256 }, want_dep = { 4, 6, 4, 2, 8 }; + const std::vector want_str = { 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2 }; + if (std::strcmp(rad_meta_gets(meta, "diffusion_decoder._class_name", ""), + "LTX2VideoDiffusionDecoderModel") || + rad_meta_geti(meta, "diffusion_decoder.decoder_head_dim", 0) != 64 || + rad_meta_geti(meta, "diffusion_decoder.latent_channels", 0) != kC || + rad_meta_geti(meta, "diffusion_decoder.patch_size", 0) != kPix || + rad_meta_geti(meta, "diffusion_decoder.out_channels", 0) != 3 || + rad_meta_geti(meta, "diffusion_decoder.decoder_t_emb_dim", 0) != 384 || + rad_meta_geti(meta, "diffusion_decoder.decoder_num_inference_steps", 0) != 1 || + std::strcmp(rad_meta_gets(meta, "diffusion_decoder.decoder_model_output_type", ""), "x0") || + rad_meta_getf(meta, "diffusion_decoder.decoder_timestep_scale_multiplier", 0.0) != 1000.0 || + ch != want_ch || dep != want_dep || str != want_str || ker.size() != 12 || k5.size() != 3 || + red != std::vector({ 2, 2, 1, 2 })) { + fprintf(stderr, "radiance: ltx2: diffusion_decoder/ is not the LTX-2.5 diffusion decoder this " + "plugin runs (stages 2048..256 of depths 4 6 4 2 8, one x0 step, heads of " + "64)\n"); + return RAD_E_UNSUPPORTED; + } + m.ddec = true; + /* The largest volumes: the default canvas's latents a frame (the decoder's own limit), the + * longest video, the feature grid four times finer, a tile's cells and the diffusion stage's + * voxels (two a cell a side, ghost frames included in the fourth stage's output). */ + const int64_t F = max_lat_frames(), A = kVaeLat, T0 = F + kDdGhost; + m.dV0 = T0 * A; + m.dV1 = 4 * m.dV0; + m.dV2 = (2 * T0 - 1) * 4 * A; + m.dV3 = (4 * T0 - 3) * 16 * A; + const int64_t cells = std::min((int64_t)kDdTile * kDdTile, 16 * A); + m.dV4 = ((int64_t)kDdTileT + kDdGhostCells) * cells; + const int64_t ctx_rows = 2 * ((int64_t)kDdTileT + kDdGhostCells) * 4 * cells; + m.dV5 = 2 * (int64_t)kDdTileT * 4 * cells; + m.dTiles = kDdMaxTiles; + const int64_t maxV = std::max({ m.dV0, m.dV1, m.dV2, m.dV4, m.dV5 }); + m.b_dz = decl_b(b, nm.f("ddec.lat"), RAD_BF16, { m.dV0, kC }); + m.b_dx = decl_b(b, nm.f("ddec.x"), RAD_BF16, { std::max({ m.dV0 * 2048, m.dV1 * 1024, m.dV2 * 512 }) }); + m.b_dfeat = decl_b(b, nm.f("ddec.features"), RAD_BF16, { m.dV3 * 512 }); + m.b_d4 = decl_b(b, nm.f("ddec.x4"), RAD_BF16, { m.dV4 * 512 }); + m.b_ddh = decl_b(b, nm.f("ddec.h"), RAD_BF16, { m.dV5 * 256 }); + m.b_dctx = decl_b(b, nm.f("ddec.ctx"), RAD_BF16, { ctx_rows * 256 }); + m.b_dn = decl_b(b, nm.f("ddec.n"), RAD_BF16, + { std::max({ m.dV0 * 2048, m.dV1 * 1024, m.dV2 * 512, m.dV4 * 512, m.dV5 * 256 }) }); + const int64_t widths[4] = { 2048, 1024, 512, 256 }; + const int64_t qrows[4] = { m.dV0, m.dV1, std::max(m.dV2, m.dV4), m.dV5 }; + for (int s = 0; s < 4; ++s) { + /* A width's q|k|v rows, which its stage's upsample also takes as scratch; the diffusion + * stage's holds one head's. */ + int64_t rows = qrows[s]; + if (s == 2) rows = std::max({ rows, (m.dV2 * 4096 + 1535) / 1536, (m.dV4 * 2048 + 1535) / 1536 }); + m.b_dqkv[s] = decl_b(b, nm.f("ddec.qkv%lld", (long long)widths[s]), RAD_BF16, + { rows, s == 3 ? 192 : 3 * widths[s] }); + m.b_dg[s] = decl_b(b, nm.f("ddec.gu%lld", (long long)widths[s]), RAD_BF16, + { kDdFfElems / (8 * widths[s]), 8 * widths[s] }); + } + m.b_dao = decl_b(b, nm.f("ddec.attn"), RAD_BF16, { m.dV5, 256 }); + m.b_da = decl_b(b, nm.f("ddec.act"), RAD_BF16, { kDdFfElems / 2 }); + m.b_dmo = decl_b(b, nm.f("ddec.ffo"), RAD_BF16, { std::max(kDdFfElems / 8, 1) }); + m.b_dpos = decl_b(b, nm.f("ddec.pos"), RAD_I32, { 3, maxV }); + m.b_dxt = decl_b(b, nm.f("ddec.noise"), RAD_F32, { m.dV5, (int64_t)kPixC }); + m.b_dxb = decl_b(b, nm.f("ddec.noise16"), RAD_BF16, { m.dV5, (int64_t)kPixC }); + m.b_dtin = decl_b(b, nm.f("ddec.t"), RAD_F32, { 1 }); + m.b_dtsin = decl_b(b, nm.f("ddec.tsin"), RAD_BF16, { 1, 256 }); + m.b_dth = decl_b(b, nm.f("ddec.th"), RAD_BF16, { 1, 384 }); + m.b_dths = decl_b(b, nm.f("ddec.ths"), RAD_BF16, { 1, 384 }); + m.b_dtemb = decl_b(b, nm.f("ddec.temb"), RAD_BF16, { 1, 384 }); + m.b_dtes = decl_b(b, nm.f("ddec.tes"), RAD_BF16, { 1, 384 }); + m.b_dmod = decl_b(b, nm.f("ddec.mod"), RAD_BF16, { 1, 1024 }, RAD_BUF_PERSIST); + m.b_dbmod = decl_b(b, nm.f("ddec.block_mod"), RAD_BF16, { 1, 1024 }); + m.b_ddcu = decl_b(b, nm.f("ddec.cu"), RAD_I32, { 2 }, RAD_BUF_PERSIST); + m.b_dsig = decl_b(b, nm.f("ddec.sigma"), RAD_F32, { 1 }, RAD_BUF_PERSIST); + m.b_dtg = decl_b(b, nm.f("ddec.tile_geom"), RAD_I32, { 3 }, RAD_BUF_PERSIST); + m.b_dgrid = decl_b(b, nm.f("ddec.grid"), RAD_I32, { (int64_t)kDdMaxTiles, 8 }, RAD_BUF_PERSIST); + m.b_dg5 = decl_b(b, nm.f("ddec.geom5"), RAD_I32, { 3 }, RAD_BUF_PERSIST); + auto wt = [&](const char* name, std::initializer_list shape) { + return wcopy(b, nm.f("ddec.%s", name), nm.ckpt("diffusion_decoder.decoder.%s", name), RAD_BF16, + shape, acc, gx); + }; + m.dw_cin = wt("conv_in.weight", { 2048, kC }); + m.db_cin = wt("conv_in.bias", { 2048 }); + m.dw_t1 = wt("t_embedder.timestep_embedder.linear_1.weight", { 384, 256 }); + m.db_t1 = wt("t_embedder.timestep_embedder.linear_1.bias", { 384 }); + m.dw_t2 = wt("t_embedder.timestep_embedder.linear_2.weight", { 384, 384 }); + m.db_t2 = wt("t_embedder.timestep_embedder.linear_2.bias", { 384 }); + { + /* The shared table's chunks 1, 0, 4 and 3 (rms_mod's shift then scale, the attention's then + * the MLP's); the context gate and the residual gates are not read. */ + const char* wn = nm.f("ddec.adaln.weight"); + const char* bn = nm.f("ddec.adaln.bias"); + RadNameMap mw = map_base(wn, RAD_MAP_ROWS), mb = map_base(bn, RAD_MAP_ROWS); + for (int p : { 1, 0, 4, 3 }) { + mw.src[mw.n_src] = nm.ckpt("diffusion_decoder.decoder.shared_adaln.proj.weight"); + mw.src_index[mw.n_src] = p * 256; + mw.src_rows[mw.n_src++] = 256; + mb.src[mb.n_src] = nm.ckpt("diffusion_decoder.decoder.shared_adaln.proj.bias"); + mb.src_index[mb.n_src] = p * 256; + mb.src_rows[mb.n_src++] = 256; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mw)); + RAD_ARCH_TRY(rad_decl_name_map(b, &mb)); + m.dw_ad = decl_w(b, wn, RAD_BF16, { 1024, 384 }, acc, RAD_SHARD_NONE, grp_layer(gx)); + m.db_ad = decl_w(b, bn, RAD_BF16, { 1024 }, acc, RAD_SHARD_NONE, grp_layer(gx)); + } + m.dw_xin = wt("conv_in_x_t.weight", { 256, (int64_t)kPixC }); + m.db_xin = wt("conv_in_x_t.bias", { 256 }); + m.dw_nout = wt("norm_out.weight", { 256 }); + m.dw_cout = wt("conv_out.weight", { (int64_t)kPixC, 256 }); + m.db_cout = wt("conv_out.bias", { (int64_t)kPixC }); + if (!m.dw_cin || !m.db_cin || !m.dw_t1 || !m.db_t1 || !m.dw_t2 || !m.db_t2 || !m.dw_ad || !m.db_ad || + !m.dw_xin || !m.db_xin || !m.dw_nout || !m.dw_cout || !m.db_cout) + return RAD_E_INVAL; + + /* ---- once a decode: the ghost frames, the shared modulation, the constants, the grids */ + m.op_dpad = cast_op(b, m.dV0, kC, "bf16", "bf16", m.b_vlat, m.b_dz); + m.op_dtin = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 1), RAD_STR("dtype", "f32"), + RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, { m.b_dtin }); + m.op_dtsin = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 256), + RAD_F64("scale", 1000.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dtin }, { m.b_dtsin }); + m.op_dt1 = dd_gemm(b, m.dw_t1, m.db_t1, 1, 384, 256, { m.b_dtsin }, m.b_dth); + m.op_dts = unary(b, "silu", 1, 384, "bf16", m.b_dth, m.b_dths); + m.op_dt2 = dd_gemm(b, m.dw_t2, m.db_t2, 1, 384, 384, { m.b_dths }, m.b_dtemb); + m.op_das = unary(b, "silu", 1, 384, "bf16", m.b_dtemb, m.b_dtes); + m.op_dad = dd_gemm(b, m.dw_ad, m.db_ad, 1, 1024, 384, { m.b_dtes }, m.b_dmod); + m.op_ddcu = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("start", 0), + RAD_INT("step", 1 << 30)), + RAD_NOWEIGHTS), + {}, { m.b_ddcu }); + m.op_dsig = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 1), RAD_STR("dtype", "f32"), + RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, { m.b_dsig }); + auto affine = [&](const char* src, std::initializer_list mul, + std::initializer_list add, rad_buf y) { + return rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_STR("src", src), + RAD_STR("mul", ints(mul).c_str()), + RAD_STR("add", ints(add).c_str())), + RAD_NOWEIGHTS), + {}, { y }); + }; + /* The tiles cut the feature grid without its ghost cells: 4 F - 3 frames. */ + m.op_dtgeom = affine("0 1 2", { 4, 4, 4 }, { -3, 0, 0 }, m.b_dtg); + m.op_dgrid = rw(b, RAD_OP(b, "tile_grid", + RAD_PARAMS(RAD_RANGE("M", 1, kDdMaxTiles), RAD_INT("tile", kDdTile), + RAD_INT("stride", kDdStride), RAD_STR("rule", "intervals"), + RAD_INT("min", kDdLeast), RAD_INT("tile_t", kDdTileT), + RAD_INT("stride_t", kDdStrideT), RAD_INT("min_t", kDdLeast), + RAD_INT("tail", kDdGhostCells)), + RAD_NOWEIGHTS), + { m.b_dtg }, { m.b_dgrid }); + m.op_dcin = dd_gemm(b, m.dw_cin, m.db_cin, m.dV0, 2048, kC, { m.b_dz }, m.b_dx); + + /* ---- the deterministic stages: the first three over the whole latent, the fourth per tile */ + m.dst.resize(4); + const int64_t svol[4] = { m.dV0, m.dV1, m.dV2, m.dV4 }; + /* each stage's volume off the latent's (F, h, w): (F + 2, h, w), (F + 2, 2h, 2w), + * (2 F + 3, 2h, 2w), and the feature grid (4 F + 5, 4h, 4w) the tiles are cut from */ + const long long gmul[4][3] = { { 1, 1, 1 }, { 1, 2, 2 }, { 2, 2, 2 }, { 4, 4, 4 } }; + const long long gadd[4] = { 2, 2, 3, 5 }; + for (int s = 0; s < 4; ++s) { + DdStage& S = m.dst[(size_t)s]; + S.C = (int64_t)ch[(size_t)s]; + S.cout = (int64_t)ch[(size_t)s + 1]; + S.st = (int64_t)str[(size_t)(3 * s)]; + S.sh = (int64_t)str[(size_t)(3 * s + 1)]; + S.sw = (int64_t)str[(size_t)(3 * s + 2)]; + S.geom = decl_b(b, nm.f("ddec.s%d.geom", s), RAD_I32, { 3 }, RAD_BUF_PERSIST); + S.op_geom = affine("0 1 2", { gmul[s][0], gmul[s][1], gmul[s][2] }, { gadd[s], 0, 0 }, S.geom); + const rad_buf x = s < 3 ? m.b_dx : m.b_d4; + if (s == 3) + m.op_dcrop = rw(b, RAD_OP(b, "tile_crop", + RAD_PARAMS(RAD_RANGE("M", 1, m.dV4), RAD_INT("C", 512), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dfeat }, { m.b_d4 }); + S.op_pos = rw(b, RAD_OP(b, "vol_index", RAD_PARAMS(RAD_RANGE("M", 1, maxV)), RAD_NOWEIGHTS), {}, + { m.b_dpos }); + const int slot = s == 0 ? 0 : s == 1 ? 1 : 2; + int64_t kk[3] = { (int64_t)ker[(size_t)(3 * s)], (int64_t)ker[(size_t)(3 * s + 1)], + (int64_t)ker[(size_t)(3 * s + 2)] }; + S.blk.resize((size_t)dep[(size_t)s]); + for (size_t l = 0; l < S.blk.size(); ++l) + RAD_ARCH_TRY(dd_block_declare(b, m, S.blk[l], nm.f("ddec.s%d.%zu", s, l), + nm.ckpt("diffusion_decoder.decoder.det_stages.%d.%zu", s, l), + S.C, slot, kk, svol[s], false, x)); + const int64_t P = S.st * S.sh * S.sw * S.C / (int64_t)red[(size_t)s]; + S.w_up = wcopy(b, nm.f("ddec.up%d.weight", s), + nm.ckpt("diffusion_decoder.decoder.upsamples.%d.proj.weight", s), RAD_BF16, + { P, S.C }, acc, gx); + S.b_up = wcopy(b, nm.f("ddec.up%d.bias", s), + nm.ckpt("diffusion_decoder.decoder.upsamples.%d.proj.bias", s), RAD_BF16, { P }, + acc, gx); + /* The upsample's linear into its width's q|k|v buffer; the fourth stage's into the 512 one too, + * so that the diffusion stage's is first touched by its blocks and its noise can share it. */ + const rad_buf scratch = m.b_dqkv[slot]; + const rad_buf dest = s < 2 ? m.b_dx : s == 2 ? m.b_dfeat : m.b_dctx; + S.op_proj = dd_gemm(b, S.w_up, S.b_up, svol[s], P, S.C, { x }, scratch); + auto d2s = [&](int64_t drop) { + return rw(b, RAD_OP(b, "d2s3d", + RAD_PARAMS(RAD_RANGE("M", 1, svol[s]), RAD_INT("C", S.cout), + RAD_INT("st", S.st), RAD_INT("sh", S.sh), RAD_INT("sw", S.sw), + RAD_INT("drop", drop), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { scratch }, { dest }); + }; + S.op_d2s = d2s(S.st - 1); + S.op_d2s_keep = s == 3 ? d2s(0) : 0; + if (!S.op_geom || !S.op_pos || !S.w_up || !S.b_up || !S.op_proj || !S.op_d2s || + (s == 3 && (!S.op_d2s_keep || !m.op_dcrop))) + return RAD_E_INVAL; + } + /* ---- the diffusion stage, per tile: its volume, positions, noise and blocks */ + { + /* (2 t - drop - ghost, 2 h, 2 w) off the tile's row: the tile starting the video drops a + * frame, the one ending it 16 ghost frames. */ + int v = 0; + for (int origin = 0; origin < 2; ++origin) + for (int trailing = 0; trailing < 2; ++trailing) + m.op_dg5[v++] = affine("0 1 2", { 2, 2, 2 }, + { -(origin ? 1 : 0) - (trailing ? 2 * kDdGhostCells : 0), 0, 0 }, + m.b_dg5); + } + m.op_dpos5 = rw(b, RAD_OP(b, "vol_index", RAD_PARAMS(RAD_RANGE("M", 1, maxV)), RAD_NOWEIGHTS), + { m.b_dg5 }, { m.b_dpos }); + m.op_dz = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, m.dV5), RAD_INT("n", kPixC), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, { m.b_dxt }); + m.op_dnoise.resize(kDdMaxTiles); + for (int k = 0; k < kDdMaxTiles; ++k) + m.op_dnoise[(size_t)k] = rw(b, RAD_OP(b, "flow_renoise", + RAD_PARAMS(RAD_RANGE("M", 1, m.dV5), RAD_INT("n", kPixC), + RAD_INT("stream", 2 + k), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { m.b_dsig, m.b_dxt }, { m.b_dxt }); + m.op_dxcast = cast_op(b, m.dV5, kPixC, "f32", "bf16", m.b_dxt, m.b_dxb); + m.op_dxin = dd_gemm(b, m.dw_xin, m.db_xin, m.dV5, 256, kPixC, { m.b_dxb }, m.b_ddh); + m.dblk.resize((size_t)dep[4]); + const int64_t kk5[3] = { (int64_t)k5[0], (int64_t)k5[1], (int64_t)k5[2] }; + for (size_t l = 0; l < m.dblk.size(); ++l) + RAD_ARCH_TRY(dd_block_declare(b, m, m.dblk[l], nm.f("ddec.d.%zu", l), + nm.ckpt("diffusion_decoder.decoder.diff_blocks.%zu", l), 256, 3, + kk5, m.dV5, true, m.b_ddh)); + m.op_dnout = rms_op(b, m.dV5, 256, 1e-6, m.dw_nout, m.b_ddh, m.b_dn); + /* The tile's pixels to the store; it is the tile loop's last op, so the feature volume, which + * every tile's crop reads, stays live through the loop. */ + m.op_ddout = dd_gemm(b, m.dw_cout, m.db_cout, m.dV5, kPixC, 256, { m.b_dn, m.b_dfeat }, m.b_vtiles); + m.op_dst = rw(b, RAD_OP(b, "tile_stitch", + RAD_PARAMS(RAD_RANGE("M", 1, (int64_t)(kFpc + kFtail) * m.maxSide), + RAD_INT("tile", kDdTile), RAD_INT("stride", kDdStride), + RAD_STR("rule", "intervals"), RAD_INT("min", kDdLeast), + RAD_INT("tile_t", kDdTileT), RAD_INT("stride_t", kDdStrideT), + RAD_INT("min_t", kDdLeast), RAD_INT("scale", 2), + RAD_INT("scale_t", 2), RAD_INT("p", kPix), RAD_INT("C", 3), + RAD_STR("order", "wh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_vtiles, m.b_dtg, m.b_vf0 }, { m.b_frames }); + /* The store holds the largest video's tiles at the decoder's own largest canvas. */ + for (int64_t Wd = kMinSide; Wd * kMinSide <= kDefW * kDefH; Wd += kMult) + for (int64_t Hd = kMinSide; Wd * Hd <= kDefW * kDefH; Hd += kMult) { + if (std::max(Wd, Hd) > kMaxAspect * std::min(Wd, Hd)) continue; + int64_t rows = 0; + for (const DdTile& t : dd_tiles(4 * F - 3, 4 * (Hd / kScale), 4 * (Wd / kScale))) + rows += (2 * (t.t - (t.trailing ? kDdGhostCells : 0)) - (t.origin ? 1 : 0)) * 4 * t.h * t.w; + if (rows > m.maxStore || (int64_t)dd_tiles(4 * F - 3, 4 * (Hd / kScale), 4 * (Wd / kScale)).size() > kDdMaxTiles) { + fprintf(stderr, "radiance: ltx2: the diffusion decoder's tiles of %lldx%lld (%lld rows) " + "outgrow the tile store (%lld rows) or its %d tiles\n", + (long long)Wd, (long long)Hd, (long long)rows, (long long)m.maxStore, + (int)kDdMaxTiles); + return RAD_E_UNSUPPORTED; + } + } + return m.op_dpad && m.op_dtin && m.op_dtsin && m.op_dt1 && m.op_dts && m.op_dt2 && m.op_das && + m.op_dad && m.op_ddcu && m.op_dsig && m.op_dtgeom && m.op_dgrid && m.op_dcin && + m.op_dpos5 && m.op_dz && m.op_dxcast && m.op_dxin && m.op_dnout && m.op_ddout && + m.op_dst + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== declare */ +/* The distilled release's trained sigmas, and its second stage's after the latent upsampler + * (diffusers' pipelines/ltx2/utils.py, DISTILLED_SIGMA_VALUES and + * STAGE_2_DISTILLED_SIGMA_VALUES). */ +static const double kDistilled[] = { 1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875 }; +static const double kStage2[] = { 0.909375, 0.725, 0.421875 }; + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + if (ctx->is_draft) { + fprintf(stderr, "radiance: ltx2: this plugin has no draft scope\n"); + return RAD_E_UNSUPPORTED; + } + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: ltx2: runs on one rank (--tp 1): the DiT's q and k norms span " + "every head\n"); + return RAD_E_UNSUPPORTED; + } + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + Names& nm = m.nm; + RAD_ARCH_TRY(check_format(meta)); + + /* ---- the text encoder's geometry, off its config */ + m.tC = tgeti(meta, "hidden_size", 0); + m.tL = tgeti(meta, "num_hidden_layers", 0); + m.tFF = tgeti(meta, "intermediate_size", 0); + m.teps = tgetf(meta, "rms_norm_eps", 1e-6); + const int64_t vocab = tgeti(meta, "vocab_size", 0); + if (m.tC <= 0 || m.tL <= 0 || m.tFF <= 0 || vocab <= 0) { + fprintf(stderr, "radiance: ltx2: the text encoder's config names no width, depth or " + "vocabulary\n"); + return RAD_E_INVAL; + } + m.tRows = 2 * (int64_t)kTextRows; + Geom base{}; + base.rank = ctx->rank; + base.world = 1; + base.max_tok = ctx->max_tok; + base.max_seqs = ctx->max_seqs; + base.max_ctx = ctx->max_ctx; + base.n_vocab = base.n_vocab_all = vocab; + base.eps = (float)m.teps; + base.dtype = "bf16"; + base.act_dtype = RAD_BF16; + m.gt = base; + m.gt.max_tok = m.tRows; + m.gt.n_embd = m.tC; + m.gt.n_layer = m.tL; + m.gd = base; + + /* ---- the DiT's */ + m.H = rad_meta_geti(meta, "transformer.num_attention_heads", 0); + m.hd = rad_meta_geti(meta, "transformer.attention_head_dim", 0); + m.Ha = rad_meta_geti(meta, "transformer.audio_num_attention_heads", 0); + m.hda = rad_meta_geti(meta, "transformer.audio_attention_head_dim", 0); + m.nb = rad_meta_geti(meta, "transformer.num_layers", 0); + m.D = m.H * m.hd; + m.Da = m.Ha * m.hda; + m.Dc = m.Ha * m.hda; + m.ffv = 4 * m.D; + m.ffa = 4 * m.Da; + m.eps = rad_meta_getf(meta, "transformer.norm_eps", 1e-6); + if (m.D <= 0 || m.Da <= 0 || m.nb <= kStgBlock || + rad_meta_geti(meta, "transformer.cross_attention_dim", 0) != m.D || + rad_meta_geti(meta, "transformer.audio_cross_attention_dim", 0) != m.Da || + std::strcmp(rad_meta_gets(meta, "transformer.activation_fn", ""), "gelu-approximate") || + rad_meta_geti(meta, "transformer.ff_bias", 1) != 0 || + rad_meta_geti(meta, "transformer.audio_ff_bias", 0) != 1) { + fprintf(stderr, "radiance: ltx2: the DiT is not LTX-2.5's (%lld blocks of %lld + %lld wide, " + "block %d for spatio-temporal guidance, text at its width, a tanh GELU " + "feed-forward without biases on the video)\n", + (long long)m.nb, (long long)m.D, (long long)m.Da, (int)kStgBlock); + return RAD_E_UNSUPPORTED; + } + m.maxS = max_video_rows(); + m.maxA = max_audio(); + m.maxPpf = max_patches(); + if (ctx->max_tok < max_step_rows() || ctx->max_tok < m.tRows) { + fprintf(stderr, "radiance: ltx2: a pass carries %lld rows; the longest video's step needs " + "%lld\n", (long long)ctx->max_tok, (long long)max_step_rows()); + return RAD_E_INVAL; + } + + /* ---- bf16 or block fp8: what the container holds for the first DiT projection decides every + * large linear (rad_fp8.h, Geom::w_bf16) */ + { + LinearFP8 probe{}; + RAD_ARCH_TRY(probe.probe(b, nm, m.gd, "dit.blk.0.attn1.qkv", + { "transformer.transformer_blocks.0.attn1.to_q.weight", + "transformer.transformer_blocks.0.attn1.to_k.weight", + "transformer.transformer_blocks.0.attn1.to_v.weight" })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.blk.0.attn1.qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + m.gd.w_bf16 = m.gt.w_bf16 = plain; + } + + /* ---- the scheduler: the base model's shifted linspace, or the distilled release's sigmas */ + const bool distilled = rad_meta_geti(meta, "scheduler.use_dynamic_shifting", 1) == 0; + if (distilled) { + m.rungs.assign(std::begin(kDistilled), std::end(kDistilled)); + m.refine.assign(std::begin(kStage2), std::end(kStage2)); + } + + /* ---- in issue order: the conditioning pass, the step, the frames, the soundtrack, the + * upscale */ + RAD_ARCH_TRY(declare_te(b, meta, m)); + { + const int64_t wz = std::max(rad_meta_geti(meta, "connectors.video_hidden_dim", 0), + rad_meta_geti(meta, "connectors.audio_hidden_dim", 0)); + m.b_zero = decl_b(b, nm.f("conn.zero"), RAD_BF16, { 1, wz }, RAD_BUF_PERSIST); + m.b_rows = decl_b(b, nm.f("conn.rows"), RAD_I32, { 3 }, RAD_BUF_PERSIST); + m.b_rpos = decl_b(b, nm.f("conn.pos"), RAD_I32, { 2 * (int64_t)kTextRows }, RAD_BUF_PERSIST); + m.op_zero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", wz), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_zero }); + m.op_rows = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, 3), RAD_INT("start", 0), + RAD_INT("step", (int64_t)kTextRows)), + RAD_NOWEIGHTS), + {}, { m.b_rows }); + m.op_rpos = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, 2 * (int64_t)kTextRows), + RAD_INT("start", 0), + RAD_INT("step", 1), RAD_INT("period", (int64_t)kTextRows)), + RAD_NOWEIGHTS), + {}, { m.b_rpos }); + if (!m.b_zero || !m.op_zero || !m.op_rows || !m.op_rpos) return RAD_E_INVAL; + } + RAD_ARCH_TRY(declare_conn(b, meta, m, m.cv, "video")); + RAD_ARCH_TRY(declare_conn(b, meta, m, m.ca, "audio")); + if (m.cv.D != m.D || m.ca.D != m.Da) { + fprintf(stderr, "radiance: ltx2: the connectors' widths (%lld, %lld) are not the DiT's\n", + (long long)m.cv.D, (long long)m.ca.D); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(declare_dur(b, meta, m)); + RAD_ARCH_TRY(declare_dit(b, meta, m)); + RAD_ARCH_TRY(declare_vae(b, meta, m)); + RAD_ARCH_TRY(declare_venc(b, meta, m)); + RAD_ARCH_TRY(declare_audio(b, meta, m)); + RAD_ARCH_TRY(declare_ups(b, meta, m)); + RAD_ARCH_TRY(declare_ddec(b, meta, m)); + + if (!ctx->shape_probe) { + RadVideoGenDecl d{}; + d.name = distilled ? "ltx-2.5-distilled" : "ltx-2.5"; + /* Gemma's tokenizer wraps the prompt in and (its TemplateProcessing). */ + d.tmpl = "{prompt}"; + d.max_text = kTextRows; + d.fps_num = kFps; + d.fps_den = 1; + d.frames_per_chunk = kFpc; + d.frames_tail = kFtail; + d.latents_per_chunk = kLpc; + d.latents_tail = kLtail; + d.dec_latents = kDecLat; + d.min_chunks = kMinChunks; + d.max_chunks = kMaxChunks; + d.latent_scale = kScale; + d.latent_channels = kC; + d.patch = 1; + d.size_multiple = kMult; + d.min_side = kMinSide; + d.max_area = kMaxArea; + d.max_aspect = kMaxAspect; + d.default_width = kDefW; + d.default_height = kDefH; + d.default_chunks = kDefChunks; + d.sample_rate = kRate; + d.audio_rate = kAudioRate; + d.audio_channels = kAudioCh; + d.audio_latent_channels = kAudioC; + d.audio_streams = 1; + d.max_lanes = kMaxLanes; + d.frames_out = m.b_frames; + d.audio_out = m.b_audio; + d.sched_kind = 1; + d.base_shift = rad_meta_getf(meta, "scheduler.base_shift", 0.95); + d.max_shift = rad_meta_getf(meta, "scheduler.max_shift", 2.05); + d.base_seq = rad_meta_geti(meta, "scheduler.base_image_seq_len", 1024); + d.max_seq = rad_meta_geti(meta, "scheduler.max_image_seq_len", 4096); + if (distilled) { + d.n_rungs = (int32_t)m.rungs.size(); + d.rungs = m.rungs.data(); + d.default_steps = d.max_steps = d.n_rungs; + } else { + d.dyn_shift = 1; + d.shift_terminal = rad_meta_getf(meta, "scheduler.shift_terminal", 0.1); + d.default_steps = kDefSteps; + d.max_steps = kMaxSteps; + } + d.step_text_rows = kTextRows; + /* The base model is guided four ways a step by default; the distilled release unguided + * (one evaluation a step). */ + d.guidance = 1; + static const double kGuided[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 }; + static const double kPlain[8] = { 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0 }; + std::memcpy(d.guidance_default, distilled ? kPlain : kGuided, sizeof d.guidance_default); + d.image_cond = m.venc ? 1 : 0; + d.image_crf = 18; + d.text_left_pad = kTextRows; + /* The two-stage recipe: the distilled release at half size, the upsampler, its second + * stage's sigmas at the full size. */ + if (m.ups && distilled) { + d.upscale_max = 2.0; + d.upscale_exact = 1; + d.n_refine_rungs = (int32_t)m.refine.size(); + d.refine_rungs = m.refine.data(); + d.upscale_refine = d.n_refine_rungs; + } + /* The VAE decodes by default; the diffusion decoder, when the container has it, on request, + * up to the default canvas. */ + static const int64_t kDecArea[2] = { 0, (int64_t)kDefW * kDefH }; + if (m.ddec) { + d.decoders = "vae diffusion"; + d.decoder_max_area = kDecArea; + } + /* The duration head's bounds are the pipeline's defaults (LTX2AutoDurationStep). */ + if (m.dur) { + d.duration_out = m.b_dur; + d.duration_min = 1.0; + d.duration_max = 20.0; + d.duration_dtype = RAD_BF16; + } + RAD_ARCH_TRY(rad_declare_video_generator(b, &d)); + } + rad_note(b, "LTX-2.5%s: Gemma 4 text encoder %lld layers of %lld, connectors %zu + %zu blocks, " + "DiT %lld blocks (video %lld, audio %lld), %s linears; VAE %s, audio VAE + vocoder + " + "bandwidth extender%s%s", + distilled ? " distilled" : "", (long long)m.tL, (long long)m.tC, m.cv.blk.size(), + m.ca.blk.size(), (long long)m.nb, (long long)m.D, (long long)m.Da, + m.gd.w_bf16 ? "bf16" : "block-fp8", m.venc ? "decoder + encoder" : "decoder", + m.ups ? ", latent upsampler x2" : "", m.dur ? ", duration head" : ""); + return RAD_OK; +} + +/* ================================================================== step */ +/* A column slice of a table's rows [r0, r0 + n): `first` columns into a row of `pitch`. */ +static RadOperand tab(rad_buf t, int64_t r0, int64_t n, int64_t pitch, int64_t first, int64_t width) { + return bcol_at(t, r0, pitch, first, width, n); +} + +/* The conditioning pass: the text encoder over both prompts into the stack, each connector into + * the lane's text rows, and with a first frame the VAE encoder into the lane's clean frame. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const int64_t T = batch->n_tok, Tn = V->n_neg, Tp = T - Tn, lane = V->lane; + const int64_t C = m.tC, L = m.tL, Lp = L + 1, np = Tn > 0 ? 2 : 1; + const RadOperand pos = praw(batch->positions, RAD_I32, T); + const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, np + 1); + + /* ---- the text encoder */ + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_tx, T)); + RAD_ISSUE_N(c, m.op_keep0, T, brows(m.b_tx, T), bcol(m.b_stack, 0, C, T)); + for (int64_t l = 0; l < L; ++l) { + const TeLayer& Y = m.te[(size_t)l]; + const TeClass& K = m.cls[Y.full ? 1 : 0]; + const int64_t qd = Y.nh * Y.hd, kvd = Y.nkv * Y.hd; + RAD_ISSUE_N(c, Y.op_in, T, brows(m.b_tx, T), RAD_W(Y.w_in), brows(m.a_th.a.x, T)); + m.a_th.step(c, T); + Y.q.step(c, m.a_th, K.q, T); + Y.k.step(c, m.a_th, K.k, T); + if (!Y.v_from_k) Y.v.step(c, m.a_th, K.v, T); + RAD_ISSUE_N(c, Y.op_vn, T * Y.nkv, brows(Y.v_from_k ? K.k : K.v, T), brows(K.v, T)); + RAD_ISSUE_N(c, Y.op_qn, T * Y.nh, brows(K.q, T), RAD_W(Y.w_qn), brows(K.q, T)); + RAD_ISSUE_N(c, Y.op_kn, T * Y.nkv, brows(K.k, T), RAD_W(Y.w_kn), brows(K.k, T)); + RAD_ISSUE_N(c, Y.op_rq, T, bcol(K.q, 0, qd, T), pos); + RAD_ISSUE_N(c, Y.op_rk, T, bcol(K.k, 0, kvd, T), pos); + RAD_ISSUE_N(c, Y.op_attn, T, bcol(K.q, 0, qd, T), bcol(K.k, 0, kvd, T), bcol(K.v, 0, kvd, T), cu, + bcol(K.o.a.x, 0, qd, T)); + K.o.step(c, T); + Y.o.step(c, K.o, m.b_th2, T); + RAD_ISSUE_N(c, Y.op_pa, T, brows(m.b_th2, T), RAD_W(Y.w_pa), brows(m.b_th2, T)); + RAD_ISSUE_N(c, Y.op_add1, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, Y.op_pf, T, brows(m.b_tx, T), RAD_W(Y.w_pf), brows(m.a_th.a.x, T)); + m.a_th.step(c, T); + Y.gu.step(c, m.a_th, m.b_tgu, T); + RAD_ISSUE_N(c, Y.op_act, T, brows(m.b_tgu, T), brows(m.a_tffn.a.x, T)); + m.a_tffn.step(c, T); + Y.down.step(c, m.a_tffn, m.b_th2, T); + RAD_ISSUE_N(c, Y.op_ff, T, brows(m.b_th2, T), RAD_W(Y.w_ff), brows(m.b_th2, T)); + RAD_ISSUE_N(c, Y.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, Y.op_sc, T, brows(m.b_tx, T), RAD_W(Y.w_sc), brows(m.b_tx, T)); + if (Y.op_keep) + RAD_ISSUE_N(c, Y.op_keep, T, brows(m.b_tx, T), bcol(m.b_stack, (l + 1) * C, C, T)); + } + RAD_ISSUE_N(c, m.op_tnorm, T, brows(m.b_tx, T), RAD_W(m.w_tnorm), bcol(m.b_stack, L * C, C, T)); + + /* ---- the connectors */ + RAD_ISSUE_N(c, m.op_zero, 1, brows(m.b_zero, 1)); + RAD_ISSUE_N(c, m.op_rows, 3, brows(m.b_rows, 3)); + RAD_ISSUE_N(c, m.op_rpos, 2 * kTextRows, brows(m.b_rpos, 2 * kTextRows)); + const int64_t R = np * kTextRows; + const RadOperand ccu = brows(m.b_rows, np + 1); + const RadOperand rpos = brows(m.b_rpos, R); + for (const Conn* Kp : { &m.cv, &m.ca }) { + const Conn& K = *Kp; + const int64_t D = K.D; + RAD_ISSUE_N(c, K.op_norm, T * Lp, view(c, m.b_stack, RAD_BF16, T * Lp, C), + brows(K.a_in.a.x, T)); + K.a_in.step(c, T); + /* Every row the registers first, then the prompts' tokens over the front of each. */ + for (int64_t p = 0; p < np; ++p) + RAD_ISSUE_N(c, K.op_reg, 1, bcol(m.b_zero, 0, D, 1), RAD_W(K.w_reg), + view(c, K.b_x, RAD_BF16, 1, (int64_t)kTextRows * D, p * kTextRows * D)); + K.proj.step(c, K.a_in, K.b_x, Tp, 0, 0); + if (Tn > 0) K.proj.step(c, K.a_in, K.b_x, Tn, Tp, kTextRows); + for (const ConnBlock& B : K.blk) { + RAD_ISSUE_N(c, B.op_n1, R, brows(K.b_x, R), RAD_NONE, brows(K.a_h.a.x, R)); + K.a_h.step(c, R); + B.at.qkv.step(c, K.a_h, K.b_qkv, R); + B.at.gate.step(c, K.a_h, K.b_g, R); + attn_core(c, B.at, true, K.b_qkv, 0, K.b_g, K.a_attn, R, R, ccu, RAD_NONE, rpos, rpos); + K.a_attn.step(c, R); + B.at.out.step(c, K.a_attn, K.b_o, R); + RAD_ISSUE_N(c, B.op_add1, R, brows(K.b_x, R), brows(K.b_o, R), brows(K.b_x, R)); + RAD_ISSUE_N(c, B.op_n2, R, brows(K.b_x, R), RAD_NONE, brows(K.a_h.a.x, R)); + K.a_h.step(c, R); + B.up.step(c, K.a_h, K.b_up, R); + RAD_ISSUE_N(c, B.op_act, R, brows(K.b_up, R), brows(K.a_ffn.a.x, R)); + K.a_ffn.step(c, R); + B.down.step(c, K.a_ffn, K.b_o, R); + RAD_ISSUE_N(c, B.op_add2, R, brows(K.b_x, R), brows(K.b_o, R), brows(K.b_x, R)); + } + RAD_ISSUE_N(c, K.op_nout, R, brows(K.b_x, R), RAD_NONE, + brow_slice(K.b_text, lane * 2 * kTextRows, R, D)); + } + + /* ---- the duration head, over the prompt's rows of each connector */ + if (m.dur) { + const int64_t r0 = lane * 2 * kTextRows, P = m.dP; + RAD_ISSUE_N(c, m.op_dvp, kTextRows, brow_slice(m.cv.b_text, r0, kTextRows, m.cv.D), + RAD_W(m.dw_vp), RAD_W(m.dw_vpb), RAD_NONE, brows(m.b_dtok, kTextRows)); + RAD_ISSUE_N(c, m.op_dap, kTextRows, brow_slice(m.ca.b_text, r0, kTextRows, m.ca.D), + RAD_W(m.dw_ap), RAD_W(m.dw_apb), RAD_NONE, + brow_slice(m.b_dtok, kTextRows, kTextRows, P)); + RAD_ISSUE_N(c, m.op_dvemb, kTextRows, brows(m.b_dtok, kTextRows), RAD_W(m.dw_vemb), + brows(m.b_dtok, kTextRows)); + RAD_ISSUE_N(c, m.op_daemb, kTextRows, brow_slice(m.b_dtok, kTextRows, kTextRows, P), + RAD_W(m.dw_aemb), brow_slice(m.b_dtok, kTextRows, kTextRows, P)); + RAD_ISSUE_N(c, m.op_dq0, 1, bcol(m.b_zero, 0, P, 1), RAD_W(m.dw_qt), brows(m.b_dq0, 1)); + RAD_ISSUE_N(c, m.op_dq, 1, brows(m.b_dq0, 1), RAD_W(m.dw_q), RAD_W(m.dw_qb), RAD_NONE, + brows(m.b_dq, 1)); + RAD_ISSUE_N(c, m.op_dk, 2 * kTextRows, brows(m.b_dtok, 2 * kTextRows), RAD_W(m.dw_k), + RAD_W(m.dw_kb), RAD_NONE, brows(m.b_dk, 2 * kTextRows)); + RAD_ISSUE_N(c, m.op_dv, 2 * kTextRows, brows(m.b_dtok, 2 * kTextRows), RAD_W(m.dw_v), + RAD_W(m.dw_vb), RAD_NONE, brows(m.b_dv, 2 * kTextRows)); + RAD_ISSUE_N(c, m.op_dcu, 2, brows(m.b_dcu, 2)); + RAD_ISSUE_N(c, m.op_dcuk, 2, brows(m.b_dcuk, 2)); + RAD_ISSUE_N(c, m.op_dattn, 1, brows(m.b_dq, 1), brows(m.b_dk, 2 * kTextRows), + brows(m.b_dv, 2 * kTextRows), brows(m.b_dcu, 2), brows(m.b_dcuk, 2), + brows(m.b_dat, 1)); + RAD_ISSUE_N(c, m.op_do, 1, brows(m.b_dat, 1), RAD_W(m.dw_o), RAD_W(m.dw_ob), RAD_NONE, + brows(m.b_do, 1)); + RAD_ISSUE_N(c, m.op_dh, 1, brows(m.b_do, 1), RAD_W(m.dw_h), RAD_W(m.dw_hb), RAD_NONE, + brows(m.b_dh, 1)); + RAD_ISSUE_N(c, m.op_dout, 1, brows(m.b_dh, 1), RAD_W(m.dw_out), RAD_W(m.dw_outb), RAD_NONE, + brows(m.b_dl, 1)); + RAD_ISSUE_N(c, m.op_dlog, 1, brows(m.b_dl, 1), brows(m.b_dur, 1)); + } + + /* ---- a first frame through the VAE's encoder */ + if (!V->image || !m.venc) return; + const int64_t h = V->geom.lat_h, w = V->geom.lat_w, ppf = h * w; + const int64_t Hp = 8 * h, Wp = 8 * w, vin0 = Hp * Wp; + const RadOperand gd = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); + RAD_ISSUE_N(c, m.op_epatch, Hp, RAD_P_T2(V->image, RAD_BF16, 32 * h, 32 * w * 3), + view(c, m.b_epatch, RAD_BF16, Hp, Wp * kPixC)); + RAD_ISSUE_N(c, m.op_egeomL, 3, gd, brows(m.b_egeomL, 3)); + for (const VDown& Dn : m.vdown) { + RAD_ISSUE_N(c, Dn.op_geom_in, 3, gd, brows(Dn.geom_in, 3)); + RAD_ISSUE_N(c, Dn.op_geom, 3, gd, brows(Dn.geom, 3)); + } + RAD_ISSUE_N(c, m.op_ecin, vin0, view(c, m.b_epatch, RAD_BF16, vin0, kPixC), RAD_W(m.w_ecin), + RAD_W(m.b_ecin), brows(m.vdown[0].geom_in, 3), RAD_NONE, + view(c, m.b_ea, RAD_BF16, vin0, m.eC0)); + int64_t vin = vin0; + for (const VDown& Dn : m.vdown) { + const RadOperand gin = brows(Dn.geom_in, 3); + for (const VRes& Rb : Dn.res) vres_step(c, Rb, vin, gin, m.b_ea, m.b_eb, m.b_ec); + const int64_t vout = vin / (Dn.sh * Dn.sw), tv = Dn.st * vin; + RAD_ISSUE_N(c, Dn.op_mean, vin, view(c, m.b_ea, RAD_BF16, vin, Dn.cin), gin, + view(c, m.b_eb, RAD_BF16, vout, Dn.cout)); + RAD_ISSUE_N(c, Dn.op_conv, vin, view(c, m.b_ea, RAD_BF16, vin, Dn.cin), RAD_W(Dn.w), RAD_W(Dn.b), + gin, RAD_NONE, view(c, m.b_ec, RAD_BF16, tv, Dn.conv_out)); + RAD_ISSUE_N(c, Dn.op_s2d, tv, view(c, m.b_ec, RAD_BF16, tv, Dn.conv_out), brows(Dn.geom, 3), + view(c, m.b_eb, RAD_BF16, vout, Dn.cout)); + RAD_ISSUE_N(c, Dn.op_next, vout, view(c, m.b_eb, RAD_BF16, vout, Dn.cout), + view(c, m.b_ea, RAD_BF16, vout, Dn.cout)); + vin = vout; + } + const RadOperand gl = brows(m.b_egeomL, 3); + for (const VRes& Rb : m.emid) vres_step(c, Rb, ppf, gl, m.b_ea, m.b_eb, m.b_ec); + RAD_ISSUE_N(c, m.op_enout, ppf, view(c, m.b_ea, RAD_BF16, ppf, m.eCout), + view(c, m.b_eb, RAD_BF16, ppf, m.eCout)); + RAD_ISSUE_N(c, m.op_ecout, ppf, view(c, m.b_eb, RAD_BF16, ppf, m.eCout), RAD_W(m.w_ecout), + RAD_W(m.b_ecout), gl, RAD_NONE, brows(m.b_eout, ppf)); + RAD_ISSUE_N(c, m.op_enorm, ppf, bcol(m.b_eout, 0, kC, ppf), RAD_W(m.vd_mean), RAD_W(m.vd_std), + brows(m.b_elat, ppf)); + RAD_ISSUE_N(c, m.op_ef32, ppf, brows(m.b_elat, ppf), + brow_slice(m.b_first, lane * m.maxPpf, ppf, kC)); +} + +/* One DiT evaluation into evaluation `p`'s velocities: the text of prompt `branch` (0 the prompt, 1 + * the negative), `stg` bypassing block 28's self-attentions, `iso` without the cross-modal + * attentions. */ +static void dit_eval(RadCtx* c, const RadVideoGenBatch* V, const Model& m, int p, int branch, bool stg, + bool iso) { + const RadVideoGeom& gm = V->geom; + const int64_t lane = V->lane, ppf = (int64_t)gm.lat_h * gm.lat_w; + const int64_t S = (int64_t)gm.lat_frames * ppf, A = gm.n_audio, R = kTextRows, L = m.nb; + const int64_t D = m.D, Da = m.Da; + const bool first = V->has_image != 0; + /* The video's rows take the first frame's modulation (timestep 0) or everything's: two table + * rows over the first latent frame and the rest, or the second row over all of them. */ + const int64_t vr0 = first ? 0 : 1, vn = first ? 2 : 1; + const RadOperand cuv = first ? praw(V->geom_d + RAD_VGEOM_FIRST_CU, RAD_I32, 3) + : praw(V->lat_cu, RAD_I32, 2); + const RadOperand cu1 = praw(V->lat_cu, RAD_I32, 2), cua = praw(V->lat_cu + 2, RAD_I32, 2); + const RadOperand cut = brows(m.b_rows, 2); + const RadOperand pv = praw2(V->pos, RAD_F32, 3, S), pvt = praw2(V->pos, RAD_F32, 1, S); + const RadOperand pa = praw2(V->pos + 3 * S, RAD_F32, 1, A); + auto mv = [&](int64_t l, int k, int n) { + return tab(m.b_mv, vr0, vn, L * 9 * D, l * 9 * D + k * D, n * D); + }; + auto ma = [&](int64_t l, int k, int n) { + return tab(m.b_ma, 0, 1, L * 9 * Da, l * 9 * Da + k * Da, n * Da); + }; + + RAD_ISSUE_N(c, m.op_lv, S, brow_slice(m.b_vstate, lane * m.maxS, S, kC), brows(m.a_lv.a.x, S)); + RAD_ISSUE_N(c, m.op_la, A, brow_slice(m.b_astate, lane * m.maxA, A, kAudioC), brows(m.a_la.a.x, A)); + m.pin_v.step(c, m.a_lv, m.b_hv, S); + m.pin_a.step(c, m.a_la, m.b_ha, A); + const RadOperand tv = brow_slice(m.cv.b_text, (lane * 2 + branch) * R, R, D); + const RadOperand ta = brow_slice(m.ca.b_text, (lane * 2 + branch) * R, R, Da); + + for (int64_t l = 0; l < L; ++l) { + const DitBlock& B = m.dit[(size_t)l]; + const bool g0 = l > 0; + /* ---- self-attention, gated after by gate_msa; spatio-temporal guidance takes v as is */ + RAD_ISSUE_N(c, B.m1v, S, g0 ? brows(m.b_ov, S) : RAD_NONE, g0 ? mv(l - 1, 5, 1) : RAD_NONE, + mv(l, 0, 2), RAD_NONE, cuv, brows(m.b_hv, S), brows(m.a_hv.a.x, S)); + RAD_ISSUE_N(c, B.m1a, A, g0 ? brows(m.b_oa, A) : RAD_NONE, g0 ? ma(l - 1, 5, 1) : RAD_NONE, + ma(l, 0, 2), RAD_NONE, cua, brows(m.b_ha, A), brows(m.a_ha.a.x, A)); + const bool bypass = stg && l == kStgBlock; + for (int s = 0; s < 2; ++s) { + const bool vid = s == 0; + const Attn& At = vid ? B.sv : B.sa; + const Act& in = vid ? m.a_hv : m.a_ha; + const Act& ao = vid ? m.a_aov : m.a_aoa; + const rad_buf bq = vid ? m.b_qkvv : m.b_qkva, bg = vid ? m.b_gv : m.b_ga; + const int64_t n = vid ? S : A; + in.step(c, n); + At.qkv.step(c, in, bq, n); + At.gate.step(c, in, bg, n); + if (bypass) { + RAD_ISSUE_N(c, At.op_v, n, bcol(bq, 2 * At.inner, At.inner, n), brows(ao.a.x, n)); + RAD_ISSUE_N(c, At.op_hg, n, brows(bg, n), brows(ao.a.x, n)); + } else { + attn_core(c, At, true, bq, 0, bg, ao, n, n, vid ? cu1 : cua, RAD_NONE, vid ? pv : pa, + vid ? pv : pa); + } + ao.step(c, n); + At.out.step(c, ao, vid ? m.b_ov : m.b_oa, n); + } + /* ---- text cross-attention: the query's norm gated by gate_msa, the text modulated as + * it is */ + RAD_ISSUE_N(c, B.m2v, S, brows(m.b_ov, S), mv(l, 2, 1), mv(l, 6, 2), RAD_NONE, cuv, + brows(m.b_hv, S), brows(m.a_hv.a.x, S)); + RAD_ISSUE_N(c, B.m2a, A, brows(m.b_oa, A), ma(l, 2, 1), ma(l, 6, 2), RAD_NONE, cua, + brows(m.b_ha, A), brows(m.a_ha.a.x, A)); + RAD_ISSUE_N(c, B.mtv, R, RAD_NONE, RAD_NONE, tab(m.b_mp, 0, 1, L * 2 * D, l * 2 * D, 2 * D), + RAD_NONE, cut, tv, brows(m.a_ctxv.a.x, R)); + RAD_ISSUE_N(c, B.mta, R, RAD_NONE, RAD_NONE, tab(m.b_mpa, 0, 1, L * 2 * Da, l * 2 * Da, 2 * Da), + RAD_NONE, cut, ta, brows(m.a_ctxa.a.x, R)); + for (int s = 0; s < 2; ++s) { + const bool vid = s == 0; + const Attn& At = vid ? B.tv : B.ta; + const Act& in = vid ? m.a_hv : m.a_ha; + const Act& ctx = vid ? m.a_ctxv : m.a_ctxa; + const Act& ao = vid ? m.a_aov : m.a_aoa; + const rad_buf bq = vid ? m.b_qv : m.b_qa, bkv = vid ? m.b_kvtv : m.b_kvta; + const rad_buf bg = vid ? m.b_gv : m.b_ga; + const int64_t n = vid ? S : A; + in.step(c, n); + ctx.step(c, R); + At.qkv.step(c, in, bq, n); + At.gate.step(c, in, bg, n); + At.kv.step(c, ctx, bkv, R); + attn_core(c, At, false, bq, bkv, bg, ao, n, R, vid ? cu1 : cua, cut, RAD_NONE, RAD_NONE); + ao.step(c, n); + At.out.step(c, ao, vid ? m.b_ov : m.b_oa, n); + } + if (!iso) { + /* ---- the cross-modal attentions: each stream gated by its text attention, normed for + * a2v and for v2a (both before either update), the two attentions, their gates */ + RAD_ISSUE_N(c, B.g2v, S, brows(m.b_ov, S), mv(l, 8, 1), cuv, brows(m.b_hv, S)); + RAD_ISSUE_N(c, B.g2a, A, brows(m.b_oa, A), ma(l, 8, 1), cua, brows(m.b_ha, A)); + RAD_ISSUE_N(c, B.mav, S, RAD_NONE, RAD_NONE, tab(m.b_mcv, 0, 1, L * 4 * D, l * 4 * D, 2 * D), + RAD_NONE, cu1, brows(m.b_hv, S), brows(m.a_nv.a.x, S)); + RAD_ISSUE_N(c, B.mvv, S, RAD_NONE, RAD_NONE, + tab(m.b_mcv, 0, 1, L * 4 * D, l * 4 * D + 2 * D, 2 * D), RAD_NONE, cu1, + brows(m.b_hv, S), brows(m.a_nv2.a.x, S)); + RAD_ISSUE_N(c, B.maa, A, RAD_NONE, RAD_NONE, + tab(m.b_mca, 0, 1, L * 4 * Da, l * 4 * Da, 2 * Da), RAD_NONE, cua, + brows(m.b_ha, A), brows(m.a_na.a.x, A)); + RAD_ISSUE_N(c, B.mva, A, RAD_NONE, RAD_NONE, + tab(m.b_mca, 0, 1, L * 4 * Da, l * 4 * Da + 2 * Da, 2 * Da), RAD_NONE, cua, + brows(m.b_ha, A), brows(m.a_na2.a.x, A)); + m.a_nv.step(c, S); + m.a_nv2.step(c, S); + m.a_na.step(c, A); + m.a_na2.step(c, A); + /* a2v: video queries over the soundtrack's keys, each on its time axis. */ + B.a2v.qkv.step(c, m.a_nv, m.b_qxv, S); + B.a2v.gate.step(c, m.a_nv, m.b_gxv, S); + B.a2v.kv.step(c, m.a_na, m.b_kvxa, A); + attn_core(c, B.a2v, false, m.b_qxv, m.b_kvxa, m.b_gxv, m.a_xv, S, A, cu1, cua, pvt, pa); + m.a_xv.step(c, S); + B.a2v.out.step(c, m.a_xv, m.b_ov, S); + /* v2a: the soundtrack's queries over the video's keys. */ + B.v2a.qkv.step(c, m.a_na2, m.b_qxa, A); + B.v2a.gate.step(c, m.a_na2, m.b_gxa, A); + B.v2a.kv.step(c, m.a_nv2, m.b_kvxv, S); + attn_core(c, B.v2a, false, m.b_qxa, m.b_kvxv, m.b_gxa, m.a_xa, A, S, cua, cu1, pa, pvt); + m.a_xa.step(c, A); + B.v2a.out.step(c, m.a_xa, m.b_oa, A); + RAD_ISSUE_N(c, B.gcv, S, brows(m.b_ov, S), tab(m.b_mcvg, 0, 1, L * D, l * D, D), cu1, + brows(m.b_hv, S)); + RAD_ISSUE_N(c, B.gca, A, brows(m.b_oa, A), tab(m.b_mcag, 0, 1, L * Da, l * Da, Da), cua, + brows(m.b_ha, A)); + RAD_ISSUE_N(c, B.m3v, S, RAD_NONE, RAD_NONE, mv(l, 3, 2), RAD_NONE, cuv, brows(m.b_hv, S), + brows(m.a_hv.a.x, S)); + RAD_ISSUE_N(c, B.m3a, A, RAD_NONE, RAD_NONE, ma(l, 3, 2), RAD_NONE, cua, brows(m.b_ha, A), + brows(m.a_ha.a.x, A)); + } else { + RAD_ISSUE_N(c, B.m3vg, S, brows(m.b_ov, S), mv(l, 8, 1), mv(l, 3, 2), RAD_NONE, cuv, + brows(m.b_hv, S), brows(m.a_hv.a.x, S)); + RAD_ISSUE_N(c, B.m3ag, A, brows(m.b_oa, A), ma(l, 8, 1), ma(l, 3, 2), RAD_NONE, cua, + brows(m.b_ha, A), brows(m.a_ha.a.x, A)); + } + /* ---- the feed-forwards, gated by gate_mlp in the next block's first norm */ + m.a_hv.step(c, S); + B.fv_up.step(c, m.a_hv, m.b_upv, S); + RAD_ISSUE_N(c, B.actv, S, brows(m.b_upv, S), brows(m.a_ffv.a.x, S)); + m.a_ffv.step(c, S); + B.fv_down.step(c, m.a_ffv, m.b_ov, S); + m.a_ha.step(c, A); + B.fa_up.step(c, m.a_ha, m.b_upa, A); + RAD_ISSUE_N(c, B.acta, A, brows(m.b_upa, A), brows(m.a_ffa.a.x, A)); + m.a_ffa.step(c, A); + B.fa_down.step(c, m.a_ffa, m.b_oa, A); + } + RAD_ISSUE_N(c, m.op_fnv, S, brows(m.b_ov, S), mv(L - 1, 5, 1), tab(m.b_fv, vr0, vn, 2 * D, 0, 2 * D), + RAD_NONE, cuv, brows(m.b_hv, S), brows(m.a_fv.a.x, S)); + RAD_ISSUE_N(c, m.op_fna, A, brows(m.b_oa, A), ma(L - 1, 5, 1), tab(m.b_fa, 0, 1, 2 * Da, 0, 2 * Da), + RAD_NONE, cua, brows(m.b_ha, A), brows(m.a_fa.a.x, A)); + m.pout_v.step(c, m.a_fv, m.b_vel_v[p], S); + m.pout_a.step(c, m.a_fa, m.b_vel_a[p], A); +} + +/* One denoising step: the first step's noise (and first frame), the step's tables, each + * evaluation the request's guidance needs, each modality's guided Euler step, the first frame + * restored. */ +static void step_dit(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const RadVideoGeom& gm = V->geom; + const int64_t lane = V->lane, ppf = (int64_t)gm.lat_h * gm.lat_w; + const int64_t S = (int64_t)gm.lat_frames * ppf, A = gm.n_audio, L = m.nb, La = kMaxLanes; + const bool first = V->has_image != 0; + const RadOperand lane_d = praw(V->lane_d, RAD_I32, 1); + const RadOperand keep = brow_slice(m.b_vstate, lane * m.maxS, ppf, kC); + const RadOperand clean = brow_slice(m.b_first, lane * m.maxPpf, ppf, kC); + if (V->step == 0) { + RAD_ISSUE_N(c, m.op_rnd_v, S, praw(V->first_d, RAD_I32, 1), praw(V->seed, RAD_U32, 2), lane_d, + praw(V->lat_cu, RAD_I32, 2), brows(m.b_vstate, La * m.maxS)); + RAD_ISSUE_N(c, m.op_rnd_a, A, praw(V->first_d, RAD_I32, 1), praw(V->seed + 2, RAD_U32, 2), + lane_d, praw(V->lat_cu + 2, RAD_I32, 2), brows(m.b_astate, La * m.maxA)); + if (first) RAD_ISSUE_N(c, m.op_keep_first, ppf, clean, keep); + } + + /* ---- the step's tables: {0, sigma} through the eight modulation MLPs (the video's both + * rows, the rest sigma's), then each block's rows */ + RAD_ISSUE_N(c, m.op_tin0, 1, view(c, m.b_tin, RAD_F32, 1, 2)); + RAD_ISSUE_N(c, m.op_tin1, 1, praw2(V->sched + 1, RAD_F32, 1, 1), view(c, m.b_tin, RAD_F32, 1, 1, 1)); + RAD_ISSUE_N(c, m.op_tsin, 2, praw(rad_buf_ptr(c, m.b_tin), RAD_F32, 2), brows(m.b_tsin, 2)); + ada_step(c, m.ad_v, m.b_tsin, 0, 2); + for (const Ada* a : { &m.ad_a, &m.ad_p, &m.ad_pa, &m.ad_cv, &m.ad_cvg, &m.ad_ca, &m.ad_cag }) + ada_step(c, *a, m.b_tsin, 1, 1); + const int64_t D = m.D, Da = m.Da; + auto temb = [&](const Ada& a, int64_t r0, int64_t n) { + return brow_slice(a.temb, r0, n, a.k * a.d); + }; + for (int64_t l = 0; l < L; ++l) { + const DitBlock& B = m.dit[(size_t)l]; + RAD_ISSUE_N(c, B.op_tv, 2, temb(m.ad_v, 0, 2), RAD_W(B.t_v), + tab(m.b_mv, 0, 2, L * 9 * D, l * 9 * D, 9 * D)); + RAD_ISSUE_N(c, B.op_ta, 1, temb(m.ad_a, 1, 1), RAD_W(B.t_a), + tab(m.b_ma, 0, 1, L * 9 * Da, l * 9 * Da, 9 * Da)); + RAD_ISSUE_N(c, B.op_tp, 1, temb(m.ad_p, 1, 1), RAD_W(B.t_p), + tab(m.b_mp, 0, 1, L * 2 * D, l * 2 * D, 2 * D)); + RAD_ISSUE_N(c, B.op_tpa, 1, temb(m.ad_pa, 1, 1), RAD_W(B.t_pa), + tab(m.b_mpa, 0, 1, L * 2 * Da, l * 2 * Da, 2 * Da)); + RAD_ISSUE_N(c, B.op_tcv, 1, temb(m.ad_cv, 1, 1), RAD_W(B.t_cv), + tab(m.b_mcv, 0, 1, L * 4 * D, l * 4 * D, 4 * D)); + RAD_ISSUE_N(c, B.op_tcvg, 1, temb(m.ad_cvg, 1, 1), RAD_W(B.t_cvg), + tab(m.b_mcvg, 0, 1, L * D, l * D, D)); + RAD_ISSUE_N(c, B.op_tca, 1, temb(m.ad_ca, 1, 1), RAD_W(B.t_ca), + tab(m.b_mca, 0, 1, L * 4 * Da, l * 4 * Da, 4 * Da)); + RAD_ISSUE_N(c, B.op_tcag, 1, temb(m.ad_cag, 1, 1), RAD_W(B.t_cag), + tab(m.b_mcag, 0, 1, L * Da, l * Da, Da)); + } + RAD_ISSUE_N(c, m.op_fv, 2, brows(m.ad_v.emb, 2), RAD_W(m.w_fv), brows(m.b_fv, 2)); + RAD_ISSUE_N(c, m.op_fa, 1, brow_slice(m.ad_a.emb, 1, 1, Da), RAD_W(m.w_fa), brows(m.b_fa, 1)); + + /* ---- the evaluations: a term is on for either modality, each modality weighs its own */ + const float* gs = V->guidance_h; + const bool cfg = gs[kGsV] != 1.0f || gs[kGsA] != 1.0f; + const bool stg = gs[kStgV] != 0.0f || gs[kStgA] != 0.0f; + const bool iso = gs[kMsV] != 1.0f || gs[kMsA] != 1.0f; + dit_eval(c, V, m, kPassCond, 0, false, false); + if (cfg) dit_eval(c, V, m, kPassUncond, 1, false, false); + if (stg) dit_eval(c, V, m, kPassStg, 0, true, false); + if (iso) dit_eval(c, V, m, kPassIso, 0, false, true); + auto vel = [&](const rad_buf* v, int p, bool on, int64_t n) { + return on ? brows(v[p], n) : RAD_NONE; + }; + RAD_ISSUE_N(c, m.op_gv, S, vel(m.b_vel_v, kPassCond, true, S), vel(m.b_vel_v, kPassUncond, cfg, S), + vel(m.b_vel_v, kPassStg, stg, S), vel(m.b_vel_v, kPassIso, iso, S), + praw(V->guidance, RAD_F32, 4), praw(V->sched + 1, RAD_F32, 2), RAD_B(m.b_gst), + brow_slice(m.b_vstate, lane * m.maxS, S, kC)); + RAD_ISSUE_N(c, m.op_ga, A, vel(m.b_vel_a, kPassCond, true, A), vel(m.b_vel_a, kPassUncond, cfg, A), + vel(m.b_vel_a, kPassStg, stg, A), vel(m.b_vel_a, kPassIso, iso, A), + praw(V->guidance + 4, RAD_F32, 4), praw(V->sched + 4, RAD_F32, 2), RAD_B(m.b_gst), + brow_slice(m.b_astate, lane * m.maxA, A, kAudioC)); + if (first) RAD_ISSUE_N(c, m.op_keep_first, ppf, clean, keep); +} + +/* A vocoder over `rows0` input rows: each stage's sequence bounds, conv_in, the stages, the last + * activation and conv_out. */ +static void voc_step(RadCtx* c, const Voc& V, const RadVideoGenBatch* B, int64_t rows0) { + const RadOperand gd = praw(B->geom_d, RAD_I32, RAD_VGEOM_N); + auto conv = [&](const VConv& k, rad_buf x, rad_buf res, rad_buf y, int64_t R, rad_buf cu) { + RAD_ISSUE_N(c, k.op, R, brows(x, R), RAD_W(k.w), brows(cu, 2), res ? brows(res, R) : RAD_NONE, + brows(y, R), k.b ? RAD_W(k.b) : RAD_NONE); + }; + auto act = [&](const VAct& a, rad_buf x, rad_buf y, int64_t R, rad_buf cu) { + RAD_ISSUE_N(c, a.op, R, brows(x, R), RAD_W(a.alpha), RAD_W(a.beta), RAD_W(a.up), RAD_W(a.down), + brows(cu, 2), brows(y, R)); + }; + RAD_ISSUE_N(c, V.op_cu0, 2, gd, brows(V.cu[0], 2)); + conv(V.cin, V.in_buf, 0, V.avg[0], rows0, V.cu[0]); + int64_t rows = rows0; + for (size_t s = 0; s < V.st.size(); ++s) { + const VStage& St = V.st[s]; + const int64_t R = rows * St.rate; + RAD_ISSUE_N(c, St.op_cu, 2, gd, brows(V.cu[s + 1], 2)); + RAD_ISSUE_N(c, St.up.op, rows, brows(V.avg[s], rows), RAD_W(St.up.w), RAD_W(St.up.b), + brows(V.cu[s], 2), brows(V.h[s + 1], R)); + for (int j = 0; j < 3; ++j) + for (int d = 0; d < 3; ++d) { + const VUnit& U = St.u[j][d]; + const rad_buf x = d == 0 ? V.h[s + 1] : V.amp[j][s + 1]; + act(U.a1, x, V.t1[s + 1], R, V.cu[s + 1]); + conv(U.c1, V.t1[s + 1], 0, V.t2[s + 1], R, V.cu[s + 1]); + act(U.a2, V.t2[s + 1], V.t1[s + 1], R, V.cu[s + 1]); + conv(U.c2, V.t1[s + 1], x, V.amp[j][s + 1], R, V.cu[s + 1]); + } + RAD_ISSUE_N(c, St.op_sum, R, brows(V.amp[0][s + 1], R), brows(V.amp[1][s + 1], R), + brows(V.avg[s + 1], R)); + RAD_ISSUE_N(c, St.op_avg, R, brows(V.avg[s + 1], R), brows(V.amp[2][s + 1], R), + brows(V.avg[s + 1], R)); + rows = R; + } + const size_t ns = V.st.size(); + act(V.act, V.avg[ns], V.t1[ns], rows, V.cu[ns]); + conv(V.cout, V.t1[ns], 0, V.wav, rows, V.cu[ns]); +} + +/* The soundtrack, once after the last step. */ +static void step_audio(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const int64_t A = V->geom.n_audio, lane = V->lane, Tm = mel_frames(A); + RAD_ISSUE_N(c, m.op_aden, A, brow_slice(m.b_astate, lane * m.maxA, A, kAudioC), RAD_W(m.w_amean), + RAD_W(m.w_astd), brows(m.b_aden, A)); + RAD_ISSUE_N(c, m.op_acast, A, brows(m.b_aden, A), brows(m.b_alat, A)); + RAD_ISSUE_N(c, m.op_aunpack, A, brows(m.b_alat, A), + praw(V->geom_d + RAD_VGEOM_AUDIO_VOL, RAD_I32, 3), + brows(m.b_aimg, A * kLatMel)); + int64_t H = A, W = kLatMel; + RAD_ISSUE_N(c, m.op_acin, H * W, view(c, m.b_aimg, RAD_BF16, H, W * kLatCh), RAD_W(m.w_acin), + RAD_W(m.b_acin), view(c, m.b_aa, RAD_BF16, H, W * m.aC0)); + for (const ARes& Rb : m.amid) ares_step(c, Rb, H, W, m.b_aa, m.b_ab, m.b_ac, m.b_as); + for (int lev = 2; lev >= 0; --lev) { + for (const ARes& Rb : m.aup[(size_t)(2 - lev)]) + ares_step(c, Rb, H, W, m.b_aa, m.b_ab, m.b_ac, m.b_as); + if (lev == 0) break; + const int64_t co = m.alev_c[(size_t)lev]; + const VConv& U = m.aups[(size_t)(2 - lev)]; + /* The nearest x2 upsample read by the conv, then the first time row dropped. */ + RAD_ISSUE_N(c, U.op, 4 * H * W, view(c, m.b_aa, RAD_BF16, H, W * co), RAD_W(U.w), RAD_W(U.b), + view(c, m.b_ab, RAD_BF16, 2 * H, 2 * W * co)); + const int64_t px = (2 * H - 1) * 2 * W; + RAD_ISSUE_N(c, m.aups_cp[(size_t)(2 - lev)], px, + view(c, m.b_ab, RAD_BF16, px, co, 2 * W * co), view(c, m.b_aa, RAD_BF16, px, co)); + H = 2 * H - 1; + W *= 2; + } + const int64_t C0 = m.alev_c[0]; + RAD_ISSUE_N(c, m.op_anout, H * W, view(c, m.b_aa, RAD_BF16, H * W, C0), + view(c, m.b_ab, RAD_BF16, H * W, C0)); + for (int ch = 0; ch < 2; ++ch) + RAD_ISSUE_N(c, m.op_acout[ch], H * W, view(c, m.b_ab, RAD_BF16, H, W * C0), RAD_W(m.w_acout[ch]), + RAD_W(m.b_acout[ch]), bcol(m.b_amel16, ch * kMel, kMel, Tm)); + RAD_ISSUE_N(c, m.op_amel, Tm, brows(m.b_amel16, Tm), brows(m.b_amel, Tm)); + voc_step(c, m.voc, V, Tm); + const int64_t Sw = Tm * kMelHop; + RAD_ISSUE_N(c, m.op_stft, Sw / 80, brows(m.voc.wav, Sw), RAD_W(m.w_basis), RAD_W(m.w_melb), + brows(m.b_bmel16, Sw / 80)); + RAD_ISSUE_N(c, m.op_bmel, Sw / 80, brows(m.b_bmel16, Sw / 80), brows(m.b_bmel, Sw / 80)); + voc_step(c, m.bwe, V, Sw / 80); + RAD_ISSUE_N(c, m.op_bwe, 3 * Sw, brows(m.voc.wav, Sw), brows(m.bwe.wav, 3 * Sw), + brows(m.b_audio, 3 * Sw)); + const int64_t tail = V->n_samples - 3 * Sw; + if (tail > 0) + RAD_ISSUE_N(c, m.op_tail, tail, brow_slice(m.b_audio, 3 * Sw, tail, kAudioCh)); +} + +/* One chunk of frames: chunk 0 decodes the whole video into the lane's frame store first; every + * chunk turns its frames into bytes. */ +/* The decoder over one tile's latent (b_vtlat: F x h x w voxels, `tg` that volume on the device) + * to its pixel patches at `out`. */ +static void vae_decode(RadCtx* c, const Model& m, int64_t F, int64_t h, int64_t w, + const RadOperand& tg, const RadOperand& out) { + const int64_t S = F * h * w; + RAD_ISSUE_N(c, m.op_vcin, S, brows(m.b_vtlat, S), RAD_W(m.w_vcin), RAD_W(m.b_vcin), tg, RAD_NONE, + view(c, m.b_va, RAD_BF16, S, m.vC0)); + for (const VRes& Rb : m.vmid) vres_step(c, Rb, S, tg, m.b_va, m.b_vb, m.b_vc); + int64_t T = F, Hh = h, Ww = w; + RadOperand gin = tg; + for (const VUp& U : m.vup) { + const int64_t vin = T * Hh * Ww; + RAD_ISSUE_N(c, U.op_geom, 3, tg, brows(U.geom, 3)); + RAD_ISSUE_N(c, U.op_conv, vin, view(c, m.b_va, RAD_BF16, vin, U.cin), RAD_W(U.w), RAD_W(U.b), + gin, RAD_NONE, view(c, m.b_vb, RAD_BF16, vin, U.conv_out)); + T = T * U.st - (U.st - 1); + Hh *= U.sh; + Ww *= U.sw; + const int64_t vout = T * Hh * Ww; + RAD_ISSUE_N(c, U.op_d2s, vin, view(c, m.b_vb, RAD_BF16, vin, U.conv_out), gin, + view(c, m.b_va, RAD_BF16, vout, U.cout)); + gin = brows(U.geom, 3); + for (const VRes& Rb : U.res) vres_step(c, Rb, vout, gin, m.b_va, m.b_vb, m.b_vc); + } + const int64_t vout = T * Hh * Ww, C = m.vup.back().cout; + RAD_ISSUE_N(c, m.op_vnout, vout, view(c, m.b_va, RAD_BF16, vout, C), + view(c, m.b_vb, RAD_BF16, vout, C)); + RAD_ISSUE_N(c, m.op_vcout, vout, view(c, m.b_vb, RAD_BF16, vout, C), RAD_W(m.w_vcout), + RAD_W(m.b_vcout), gin, RAD_NONE, out); +} + +/* One diffusion-decoder block over V voxels of residual `xb` (a C-wide view), the volume `geom` + * on the device and its positions already in b_dpos. */ +static void dd_block_step(RadCtx* c, const Model& m, const DdBlock& B, int64_t V, rad_buf xb, + const RadOperand& geom, bool diff) { + const int64_t C = B.C; + const RadOperand X = view(c, xb, RAD_BF16, V, C), N = view(c, m.b_dn, RAD_BF16, V, C); + const rad_buf qkv = m.b_dqkv[B.slot], gu = m.b_dg[B.slot]; + if (diff) { + RAD_ISSUE_N(c, B.op_ctx, V, view(c, m.b_dctx, RAD_BF16, V, C), RAD_W(B.w_ctx), RAD_W(B.b_ctx), + X, X); + RAD_ISSUE_N(c, B.op_mod, 1, brows(m.b_dmod, 1), RAD_W(B.w_sst), brows(m.b_dbmod, 1)); + RAD_ISSUE_N(c, B.op_n1, V, RAD_NONE, RAD_NONE, bcol(m.b_dbmod, 0, 2 * C, 1), RAD_W(B.w_n1), + brows(m.b_ddcu, 2), X, N); + } else { + RAD_ISSUE_N(c, B.op_n1, V, X, RAD_W(B.w_n1), N); + } + const int64_t gw = C / (int64_t)B.op_qkvh.size(); + for (size_t g = 0; g < B.op_qkvh.size(); ++g) { + RAD_ISSUE_N(c, B.op_qkvh[g], V, N, RAD_W(B.w_qkvh[g]), RAD_W(B.b_qkvh[g]), RAD_NONE, + brows(qkv, V)); + RAD_ISSUE_N(c, B.op_rope, V, brows(qkv, V), bcol(m.b_dpos, 0, V, 3), RAD_W(B.w_nq), + RAD_W(B.w_nk)); + RAD_ISSUE_N(c, B.op_attn, V, bcol(qkv, 0, gw, V), bcol(qkv, gw, gw, V), bcol(qkv, 2 * gw, gw, V), + geom, diff ? bcol(m.b_dao, (int64_t)g * gw, gw, V) : N); + } + RAD_ISSUE_N(c, B.op_o, V, diff ? view(c, m.b_dao, RAD_BF16, V, C) : N, RAD_W(B.w_o), RAD_W(B.b_o), + X, X); + if (diff) + RAD_ISSUE_N(c, B.op_n2, V, RAD_NONE, RAD_NONE, bcol(m.b_dbmod, 2 * C, 2 * C, 1), RAD_W(B.w_n2), + brows(m.b_ddcu, 2), X, N); + else + RAD_ISSUE_N(c, B.op_n2, V, X, RAD_W(B.w_n2), N); + for (int64_t r0 = 0; r0 < V; r0 += B.chunk) { + const int64_t n = std::min(B.chunk, V - r0); + const RadOperand Nr = view(c, m.b_dn, RAD_BF16, n, C, r0 * C); + RAD_ISSUE_N(c, B.op_gu, n, Nr, RAD_W(B.w_gu), brows(gu, n)); + RAD_ISSUE_N(c, B.op_act, n, brows(gu, n), view(c, m.b_da, RAD_BF16, n, B.ff)); + RAD_ISSUE_N(c, B.op_down, n, view(c, m.b_da, RAD_BF16, n, B.ff), RAD_W(B.w_down), + view(c, m.b_dmo, RAD_BF16, n, C)); + const RadOperand Xr = view(c, xb, RAD_BF16, n, C, r0 * C); + RAD_ISSUE_N(c, B.op_add2, n, Xr, view(c, m.b_dmo, RAD_BF16, n, C), Xr); + } +} + +/* The diffusion decoder over the lane's latent (b_vlat, cast and denormalised) into the tile store + * (chunk 0 of a request that named it); the chunks then stitch from the store with op_dst. */ +static void step_ddec(RadCtx* c, const RadVideoGenBatch* V, const Model& m) { + const RadVideoGeom& gm = V->geom; + const int64_t h = gm.lat_h, w = gm.lat_w, F = gm.lat_frames, A = h * w, S = F * A; + const RadOperand gd = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); + /* The latent and its last frame twice more. */ + RAD_ISSUE_N(c, m.op_dpad, S, brows(m.b_vlat, S), view(c, m.b_dz, RAD_BF16, S, kC)); + for (int64_t g = 0; g < kDdGhost; ++g) + RAD_ISSUE_N(c, m.op_dpad, A, view(c, m.b_vlat, RAD_BF16, A, kC, (F - 1) * A * kC), + view(c, m.b_dz, RAD_BF16, A, kC, (S + g * A) * kC)); + for (const DdStage& St : m.dst) RAD_ISSUE_N(c, St.op_geom, 3, gd, brows(St.geom, 3)); + RAD_ISSUE_N(c, m.op_dtgeom, 3, gd, brows(m.b_dtg, 3)); + RAD_ISSUE_N(c, m.op_dgrid, kDdMaxTiles, brows(m.b_dtg, 3), brows(m.b_dgrid, kDdMaxTiles)); + RAD_ISSUE_N(c, m.op_dtin, 1, brows(m.b_dtin, 1)); + RAD_ISSUE_N(c, m.op_dtsin, 1, brows(m.b_dtin, 1), brows(m.b_dtsin, 1)); + RAD_ISSUE_N(c, m.op_dt1, 1, brows(m.b_dtsin, 1), RAD_W(m.dw_t1), RAD_W(m.db_t1), RAD_NONE, + brows(m.b_dth, 1)); + RAD_ISSUE_N(c, m.op_dts, 1, brows(m.b_dth, 1), brows(m.b_dths, 1)); + RAD_ISSUE_N(c, m.op_dt2, 1, brows(m.b_dths, 1), RAD_W(m.dw_t2), RAD_W(m.db_t2), RAD_NONE, + brows(m.b_dtemb, 1)); + RAD_ISSUE_N(c, m.op_das, 1, brows(m.b_dtemb, 1), brows(m.b_dtes, 1)); + RAD_ISSUE_N(c, m.op_dad, 1, brows(m.b_dtes, 1), RAD_W(m.dw_ad), RAD_W(m.db_ad), RAD_NONE, + brows(m.b_dmod, 1)); + RAD_ISSUE_N(c, m.op_ddcu, 2, brows(m.b_ddcu, 2)); + RAD_ISSUE_N(c, m.op_dsig, 1, brows(m.b_dsig, 1)); + + /* ---- stages 0..2 over the whole latent into the feature volume */ + int64_t T = F + kDdGhost, Hh = h, Ww = w; + const int64_t V0 = T * Hh * Ww; + RAD_ISSUE_N(c, m.op_dcin, V0, view(c, m.b_dz, RAD_BF16, V0, kC), RAD_W(m.dw_cin), RAD_W(m.db_cin), + RAD_NONE, view(c, m.b_dx, RAD_BF16, V0, 2048)); + for (int s = 0; s < 3; ++s) { + const DdStage& St = m.dst[(size_t)s]; + const int64_t Vs = T * Hh * Ww; + const RadOperand g = brows(St.geom, 3); + RAD_ISSUE_N(c, St.op_pos, Vs, g, bcol(m.b_dpos, 0, Vs, 3)); + for (const DdBlock& B : St.blk) dd_block_step(c, m, B, Vs, m.b_dx, g, false); + const int64_t P = St.st * St.sh * St.sw * St.cout; + const rad_buf scratch = m.b_dqkv[s]; + RAD_ISSUE_N(c, St.op_proj, Vs, view(c, m.b_dx, RAD_BF16, Vs, St.C), RAD_W(St.w_up), + RAD_W(St.b_up), RAD_NONE, view(c, scratch, RAD_BF16, Vs, P)); + T = T * St.st - (St.st - 1); + Hh *= St.sh; + Ww *= St.sw; + const rad_buf dest = s < 2 ? m.b_dx : m.b_dfeat; + RAD_ISSUE_N(c, St.op_d2s, Vs, view(c, scratch, RAD_BF16, Vs, P), g, + view(c, dest, RAD_BF16, T * Hh * Ww, St.cout)); + } + const int64_t V3 = T * Hh * Ww; + + /* ---- per tile: stage 3, then the diffusion step into the store */ + const DdStage& S3 = m.dst[3]; + const std::vector tl = dd_tiles(4 * F - 3, Hh, Ww); + const int32_t* rows = (const int32_t*)rad_buf_ptr(c, m.b_dgrid); + int64_t off = 0; + for (size_t k = 0; k < tl.size() && k < (size_t)kDdMaxTiles; ++k) { + const DdTile& t = tl[k]; + const int64_t V4 = t.t * t.h * t.w; + const RadOperand tg = praw(rows + 8 * k, RAD_I32, 3); + RAD_ISSUE_N(c, m.op_dcrop, V4, view(c, m.b_dfeat, RAD_BF16, V3, 512), brows(S3.geom, 3), + praw(rows + 8 * k, RAD_I32, 6), view(c, m.b_d4, RAD_BF16, V4, 512)); + RAD_ISSUE_N(c, S3.op_pos, V4, tg, bcol(m.b_dpos, 0, V4, 3)); + for (const DdBlock& B : S3.blk) dd_block_step(c, m, B, V4, m.b_d4, tg, false); + const int64_t P = S3.st * S3.sh * S3.sw * S3.cout; + RAD_ISSUE_N(c, S3.op_proj, V4, view(c, m.b_d4, RAD_BF16, V4, 512), RAD_W(S3.w_up), + RAD_W(S3.b_up), RAD_NONE, view(c, m.b_dqkv[2], RAD_BF16, V4, P)); + const int64_t drop = t.origin ? 1 : 0, Fc = 2 * t.t - drop; + RAD_ISSUE_N(c, t.origin ? S3.op_d2s : S3.op_d2s_keep, V4, + view(c, m.b_dqkv[2], RAD_BF16, V4, P), tg, + view(c, m.b_dctx, RAD_BF16, Fc * 4 * t.h * t.w, 256)); + const int64_t F5 = Fc - (t.trailing ? 2 * kDdGhostCells : 0), V5 = F5 * 4 * t.h * t.w; + RAD_ISSUE_N(c, m.op_dg5[(t.origin ? 2 : 0) + (t.trailing ? 1 : 0)], 3, tg, brows(m.b_dg5, 3)); + const RadOperand g5 = brows(m.b_dg5, 3); + RAD_ISSUE_N(c, m.op_dpos5, V5, g5, bcol(m.b_dpos, 0, V5, 3)); + RAD_ISSUE_N(c, m.op_dz, V5, brows(m.b_dxt, V5)); + RAD_ISSUE_N(c, m.op_dnoise[k], V5, brows(m.b_dsig, 1), praw(V->seed, RAD_U32, 2), + brows(m.b_dxt, V5)); + RAD_ISSUE_N(c, m.op_dxcast, V5, brows(m.b_dxt, V5), brows(m.b_dxb, V5)); + RAD_ISSUE_N(c, m.op_dxin, V5, brows(m.b_dxb, V5), RAD_W(m.dw_xin), RAD_W(m.db_xin), RAD_NONE, + view(c, m.b_ddh, RAD_BF16, V5, 256)); + for (const DdBlock& B : m.dblk) dd_block_step(c, m, B, V5, m.b_ddh, g5, true); + RAD_ISSUE_N(c, m.op_dnout, V5, view(c, m.b_ddh, RAD_BF16, V5, 256), RAD_W(m.dw_nout), + view(c, m.b_dn, RAD_BF16, V5, 256)); + RAD_ISSUE_N(c, m.op_ddout, V5, view(c, m.b_dn, RAD_BF16, V5, 256), RAD_W(m.dw_cout), + RAD_W(m.db_cout), RAD_NONE, view(c, m.b_vtiles, RAD_BF16, V5, kPixC, off * kPixC)); + off += V5; + } +} + +/* Chunk 0 decodes the whole video into the lane's tile store, a tile at a time (the boxes made on + * the device by tile_grid, their sizes and store offsets known here); every chunk stitches its + * frames to bytes. */ +static void step_video(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const RadVideoGeom& gm = V->geom; + const int64_t lane = V->lane, h = gm.lat_h, w = gm.lat_w, F = gm.lat_frames, S = F * h * w; + const int64_t Fo = m.vAt * F + m.vBt, sc = m.vAhw; + const bool tiled = vae_tiled(h, w); + const std::vector tl = vae_tiles(h, w); + int64_t store = 0; + for (const VaeTile& t : tl) store += Fo * t.h * sc * t.w * sc; + const RadOperand gd = praw(V->geom_d, RAD_I32, RAD_VGEOM_N); + const bool diffusion = V->decoder == 1 && m.ddec; + if (V->chunk == 0) { + RAD_ISSUE_N(c, m.op_vlat, S, brow_slice(m.b_vstate, lane * m.maxS, S, kC), brows(m.b_vlat, S)); + RAD_ISSUE_N(c, m.op_vden, S, brows(m.b_vlat, S), RAD_W(m.vd_mean), RAD_W(m.vd_std), + brows(m.b_vlat, S)); + } + if (V->chunk == 0 && diffusion) step_ddec(c, V, m); + if (V->chunk == 0 && !diffusion) { + const RadOperand g0 = praw(V->geom_d, RAD_I32, 3); + RAD_ISSUE_N(c, tiled ? m.op_vgrid : m.op_vgrid1, m.maxTiles, g0, brows(m.b_vgrid, m.maxTiles)); + const int32_t* rows = (const int32_t*)rad_buf_ptr(c, m.b_vgrid); + int64_t off = 0; + for (size_t k = 0; k < tl.size(); ++k) { + const int64_t tv = F * tl[k].h * tl[k].w, n = Fo * tl[k].h * sc * tl[k].w * sc; + const RadOperand tg = praw(rows + 8 * k, RAD_I32, 3); + RAD_ISSUE_N(c, m.op_vcrop, tv, brows(m.b_vlat, S), g0, praw(rows + 8 * k, RAD_I32, 6), + brows(m.b_vtlat, tv)); + vae_decode(c, m, F, tl[k].h, tl[k].w, tg, + view(c, m.b_vtiles, RAD_BF16, n, kPixC, off * kPixC)); + off += n; + } + } + const int64_t R = (int64_t)V->n_frames_out * h * kScale, Wpx = w * kScale; + RAD_ISSUE_N(c, m.op_vf0, 1, gd, brows(m.b_vf0, 1)); + if (diffusion) { + int64_t drows = 0; + for (const DdTile& t : dd_tiles(4 * F - 3, 4 * h, 4 * w)) + drows += (2 * (t.t - (t.trailing ? kDdGhostCells : 0)) - (t.origin ? 1 : 0)) * 4 * t.h * t.w; + RAD_ISSUE_N(c, m.op_dtgeom, 3, gd, brows(m.b_dtg, 3)); + RAD_ISSUE_N(c, m.op_dst, R, brows(m.b_vtiles, drows), brows(m.b_dtg, 3), brows(m.b_vf0, 1), + view(c, m.b_frames, RAD_U8, R, Wpx * 3)); + return; + } + RAD_ISSUE_N(c, tiled ? m.op_vst : m.op_vst1, R, brows(m.b_vtiles, store), + praw(V->geom_d, RAD_I32, 3), brows(m.b_vf0, 1), view(c, m.b_frames, RAD_U8, R, Wpx * 3)); +} + +/* The latent upscale: the clean small latent through the upsampler to the full size, both latents + * re-noised to the second stage's first sigma with streams of their own, a first frame kept + * clean. */ +static void step_upscale(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadVideoGenBatch* V = batch->vgen_b; + const RadVideoGeom& s = V->geom_from; + const RadVideoGeom& d = V->geom; + const int64_t lane = V->lane, F = d.lat_frames, C = m.uC, hs = s.lat_h, ws = s.lat_w; + const int64_t ppf = (int64_t)d.lat_h * d.lat_w, vs = F * hs * ws, vd = (int64_t)F * ppf; + const RadOperand gsrc = praw(V->geom_d + RAD_VGEOM_UP_SRC, RAD_I32, 3); + const RadOperand gdst = praw(V->geom_d + RAD_VGEOM_UP_DST, RAD_I32, 3); + const RadOperand st = RAD_B(m.b_ust); + const RadOperand lat = brow_slice(m.b_vstate, lane * m.maxS, vs, kC); + RAD_ISSUE_N(c, m.op_uden, vs, lat, RAD_W(m.vd_mean), RAD_W(m.vd_std), brows(m.b_uden, vs)); + RAD_ISSUE_N(c, m.op_ucast, vs, brows(m.b_uden, vs), brows(m.b_uin, vs)); + auto x = [&](rad_buf bf, int64_t v) { return view(c, bf, RAD_BF16, v, C); }; + RAD_ISSUE_N(c, m.op_ucin, vs, brows(m.b_uin, vs), RAD_W(m.u_cinw), RAD_W(m.u_cinb), gsrc, RAD_NONE, + x(m.b_ua, vs)); + RAD_ISSUE_N(c, m.op_unin, vs, x(m.b_ua, vs), RAD_W(m.u_ninw), RAD_W(m.u_ninb), RAD_NONE, st, + x(m.b_ua, vs)); + auto blocks = [&](const std::vector& list, int64_t v, const RadOperand& g) { + for (const URes& U : list) { + RAD_ISSUE_N(c, U.op_c1, v, x(m.b_ua, v), RAD_W(U.c1w), RAD_W(U.c1b), g, RAD_NONE, + x(m.b_ub, v)); + RAD_ISSUE_N(c, U.op_n1, v, x(m.b_ub, v), RAD_W(U.n1w), RAD_W(U.n1b), RAD_NONE, st, + x(m.b_ub, v)); + RAD_ISSUE_N(c, U.op_c2, v, x(m.b_ub, v), RAD_W(U.c2w), RAD_W(U.c2b), g, RAD_NONE, + x(m.b_uc, v)); + RAD_ISSUE_N(c, U.op_n2, v, x(m.b_uc, v), RAD_W(U.n2w), RAD_W(U.n2b), RAD_NONE, st, + x(m.b_uc, v)); + RAD_ISSUE_N(c, U.op_add, v, x(m.b_uc, v), x(m.b_ua, v), x(m.b_ua, v)); + RAD_ISSUE_N(c, U.op_act, v, x(m.b_ua, v), x(m.b_ua, v)); + } + }; + blocks(m.u_pre, vs, gsrc); + /* Each frame's Conv2d to 4 C channels, then the pixel shuffle over the volume. */ + const int64_t fr = hs * ws; + for (int64_t f = 0; f < F; ++f) + RAD_ISSUE_N(c, m.op_uup, fr, view(c, m.b_ua, RAD_BF16, hs, ws * C, f * fr * C), RAD_W(m.u_upw), + RAD_W(m.u_upb), view(c, m.b_ub, RAD_BF16, hs, ws * 4 * C, f * fr * 4 * C)); + RAD_ISSUE_N(c, m.op_ud2s, vs, view(c, m.b_ub, RAD_BF16, vs, 4 * C), gsrc, x(m.b_ua, vd)); + blocks(m.u_post, vd, gdst); + RAD_ISSUE_N(c, m.op_ucout, vd, x(m.b_ua, vd), RAD_W(m.u_coutw), RAD_W(m.u_coutb), gdst, RAD_NONE, + brows(m.b_uout, vd)); + RAD_ISSUE_N(c, m.op_unorm, vd, brows(m.b_uout, vd), RAD_W(m.vd_mean), RAD_W(m.vd_std), + brows(m.b_uout, vd)); + const RadOperand full = brow_slice(m.b_vstate, lane * m.maxS, vd, kC); + RAD_ISSUE_N(c, m.op_uf32, vd, brows(m.b_uout, vd), full); + const bool first = V->has_image != 0; + const RadOperand keep = brow_slice(m.b_vstate, lane * m.maxS, ppf, kC); + const RadOperand clean = brow_slice(m.b_first, lane * m.maxPpf, ppf, kC); + if (first) RAD_ISSUE_N(c, m.op_ufirst, ppf, keep, clean); + RAD_ISSUE_N(c, m.op_urnv, vd, praw(V->sched + 1, RAD_F32, 1), praw(V->seed, RAD_U32, 2), full); + RAD_ISSUE_N(c, m.op_urna, d.n_audio, praw(V->sched + 4, RAD_F32, 1), praw(V->seed + 2, RAD_U32, 2), + brow_slice(m.b_astate, lane * m.maxA, d.n_audio, kAudioC)); + if (first) RAD_ISSUE_N(c, m.op_ukeep, ppf, clean, keep); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->vgen_b) { + rad_step_fail(c, "ltx2 is a video generator and runs its generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_VCOND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_VSTEP: step_dit(c, batch, m); return; + case RAD_GEN_PASS_ADECODE: step_audio(c, batch, m); return; + case RAD_GEN_PASS_VDECODE: step_video(c, batch, m); return; + case RAD_GEN_PASS_VUPSCALE: + if (!m.ups) { + rad_step_fail(c, "ltx2: an upscale pass, and this container has no latent upsampler"); + return; + } + step_upscale(c, batch, m); + return; + default: + rad_step_fail(c, "ltx2: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows of the largest pass: a step of the longest video at the largest size. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = std::max(max_step_rows(), 2 * (int64_t)kTextRows); + out->gen_video = 1; + return RAD_OK; +} + +} /* namespace ltx2 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(ltx2) +RAD_ARCH_PLUGIN(ltx2, "ltx2", "", "0.1.0", + "LTX-2.5 (t2va, i2va): a Gemma 4 text encoder and connectors, the duration head, a " + "22B dual-stream audio-video diffusion transformer with four-way guidance, the " + "causal 3D video VAE (tiled past the default canvas) and the diffusion decoder, the " + "audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; " + "bf16 or block-fp8 linears") + +extern "C" int64_t rad_arch_video_positions(int which, const RadVideoGeom* g, float* pos, + int64_t cap) { + if (!g || g->n_text != ltx2::kTextRows) return RAD_E_INVAL; + if (which == RAD_VPOS_STEP) return ltx2::positions(g, pos, cap); + if (which == RAD_VPOS_DECODE) return 1; + return RAD_E_INVAL; +} +#endif diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 97f6ed5e..d30c4b58 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -649,8 +649,36 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); fd.n_head_kv = g.n_head_kv; fd.head_dim = g.head_dim; + /* --kv-cache-dtype fp8_v4 / k6_v4 (RadBuildCtx::kv_quant): V as int4 in groups of 32 with + * f16 scales, K E4M3 as above or int6 the same way (libr4d's gqa12 and four-rank gqa6 + * rows for these layers). A token's row is 25 or 22 * head_dim / 16 bytes instead of + * 2 * head_dim, so the group is declared at half that and the core sizes pages from it; + * only those kernels read the layout. The MTP head's layer shares this group. The engine + * asks only for a layout probe() offered. */ + const int kvq = fd.dtype == RAD_F8E4M3 ? ctx->kv_quant : RAD_KVQ_NONE; + const char* kvq_name = kvq == RAD_KVQ_V4 ? "fp8_v4" : kvq == RAD_KVQ_K6V4 ? "k6_v4" + : nullptr; + if (kvq != RAD_KVQ_NONE && !kvq_name) { + fprintf(stderr, "radiance: KV cache layout %d is not one this plugin knows\n", kvq); + return RAD_E_UNSUPPORTED; + } + /* A rank's ratio: twelve at one and two ranks, six at four (each KV head replicated + * across a rank pair). */ + if (kvq_name && !(g.head_dim == 256 && (g.gqa() == 12 || g.gqa() == 6))) { + fprintf(stderr, "radiance: --kv-cache-dtype %s has libr4d rows at head_dim 256 and a " + "rank's gqa 12 or 6 only; this rank is head_dim %lld, gqa %lld\n", + kvq_name, (long long)g.head_dim, (long long)g.gqa()); + return RAD_E_UNSUPPORTED; + } + const int64_t row16 = kvq == RAD_KVQ_V4 ? 25 : kvq == RAD_KVQ_K6V4 ? 22 : 32; + fd.head_dim = g.head_dim * row16 / 32; m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); - g.kv_dtype = rad_dtype_name(fd.dtype); + g.kv_dtype = kvq_name ? kvq_name : rad_dtype_name(fd.dtype); + if (kvq_name) + rad_note(b, "kv cache %s: %s K, int4 V, in groups of 32 with f16 scales, %lld bytes a " + "token and head instead of %lld", kvq_name, + kvq == RAD_KVQ_V4 ? "E4M3" : "int6", (long long)(g.head_dim * row16 / 16), + (long long)(2 * g.head_dim)); RadKVGroupDecl sd{}; sd.kind = RAD_KV_LINEAR; @@ -1622,6 +1650,16 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (meta_int2(meta, "qwen4exp.mtp_num_hidden_layers", "mtp_num_hidden_layers", 0) > 0) out->draft_depth = 3; out->shape_probe_ok = 1; /* declare() writes scratch under shape_probe */ + /* --kv-cache-dtype fp8_v4 / k6_v4: libr4d has their rows for the QSA layers' geometry + * (head_dim 256, twelve queries per KV head; gqa6 with 4-token pages at four ranks), so other + * geometries are refused at startup rather than in declare. */ + { + const long long hd = meta->head_dim ? meta->head_dim + : (meta->n_head ? meta->n_embd / meta->n_head : 0); + const long long nkv = meta->n_head_kv ? meta->n_head_kv : meta->n_head; + if (hd == 256 && nkv > 0 && meta->n_head == 12 * nkv) + out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4); + } return RAD_OK; } diff --git a/arch/qwenimage21/qwenimage21.cpp b/arch/qwenimage21/qwenimage21.cpp index ebce7b1b..70b558b5 100644 --- a/arch/qwenimage21/qwenimage21.cpp +++ b/arch/qwenimage21/qwenimage21.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include @@ -75,291 +76,6 @@ static inline int64_t ref_tokens_max() { return (int64_t)kRefArea / 256 * 11 / 1 static const char* kSysPrompt = "Comprehend and analyze the provided prompt."; -/* ================================================================== the VAE as a recorded graph - * - * Image size varies per request, so the VAE's ops are declared once for the largest image and - * issued with the actual extents: every image operand is a raw [height, width * channels] view of - * its buffer (docs/OPS.md, "Image generation"), with extents from the pass's picture size and the - * stage's scale. `Vae` records each op with what it needs to rebuild its operands, so declare() - * and step() walk the same list. - * - * Every output is its own buffer, sized for its stage; the planner shares storage between those - * whose lives do not overlap, and no buffer is reused by hand. This is sound because ops are issued - * in declaration order. */ -struct VImg { - rad_buf buf = 0; - int64_t ch = 0; - int lvl = 0; /* the side is the pass's base side times 2^lvl (decoder) or / 2^lvl (encoder) */ -}; - -struct VOp { - enum Kind { CONV, NORM, ADD, D2S, S2D, ATTN } kind = CONV; - rad_op op = 0; - VImg x{}, y{}, z{}; /* inputs x (and z for ADD), output y */ - rad_weight w = 0, b = 0; - int k = 1, up = 1, stride = 1; - int64_t qkv_ch = 0; /* ATTN: x is the [*, 3C] qkv rows, y the [*, C] output */ -}; - -struct Vae { - std::vector ops; - Names* nm = nullptr; - RadBuilder* b = nullptr; - const char* scope = ""; /* "dec" or "enc" */ - bool down = false; /* an encoder: a level halves the side */ - int64_t base_px = 0; /* pixels at level 0, the largest any pass hands it */ - int n_buf = 0; - int first_group = 0; - /* The banded tail. From op `band_from` on, every output pixel reads a bounded window of rows - * (3x3 convolutions, nearest upsampling, per-pixel norms and adds, depth-to-space shortcuts), - * so a rank can run the tail on its band of level-0 rows plus `halo` rows per side and get its - * band's pixels bit for bit: rows spoiled by a conv's zero padding at the band edge never reach - * the band. The ops before it include the mid-block's attention, which reads every pixel, and - * run whole; `whole` holds their outputs, read by the tail at the band's row offset. -1: no - * tail. */ - int band_from = -1; - int64_t halo = 0; - std::vector whole; - - int64_t px_at(int lvl) const { - int64_t p = base_px; - for (int i = 0; i < lvl; ++i) p = down ? (p + 3) / 4 : p * 4; - return p; - } - VImg img(int64_t ch, int lvl) { - VImg v; - v.ch = ch; - v.lvl = lvl; - v.buf = decl_b(b, nm->f("%s.t%d", scope, n_buf++), RAD_BF16, { px_at(lvl), ch }); - return v; - } - rad_weight wt(const char* name, const char* src, std::initializer_list shape) { - if (map_copy(b, name, src) < 0) return 0; - return decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, - grp_layer(first_group)); - } - - /* y = conv(x): k x k, stride, `up` 2 reads x upsampled, `pad` same or down. */ - VImg conv(const VImg& x, int64_t cout, int k, int stride, int up, const char* pad, - const char* ckpt) { - VOp o; - o.kind = VOp::CONV; - o.x = x; - o.up = up; - o.stride = stride; - int lvl = x.lvl; - if (up == 2) lvl = down ? lvl - 1 : lvl + 1; - if (stride == 2) lvl = down ? lvl + 1 : lvl - 1; - o.y = img(cout, lvl); - o.k = k; - o.w = wt(nm->f("%s.weight", ckpt), nm->ckpt("%s.weight", ckpt), { cout, x.ch, k, k }); - o.b = wt(nm->f("%s.bias", ckpt), nm->ckpt("%s.bias", ckpt), { cout }); - o.op = RAD_OP(b, "conv2d_nhwc", - RAD_PARAMS(RAD_RANGE("M", 1, px_at(lvl)), RAD_INT("cin", x.ch), - RAD_INT("cout", cout), RAD_INT("k", k), - RAD_INT("stride", stride), RAD_STR("pad", pad), - RAD_INT("up", up), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(o.w, o.b)); - /* An input with no buffer is the picture the pass staged, read where it lies. */ - if (x.buf) rw(b, o.op, { x.buf }, { o.y.buf }); - else rw(b, o.op, {}, { o.y.buf }); - ops.push_back(o); - return o.y; - } - /* The channel norm, `silu` or not. `gamma` is [C, 1, 1(, 1)] in the checkpoint. */ - VImg norm(const VImg& x, bool silu, const char* ckpt, int gamma_rank) { - VOp o; - o.kind = VOp::NORM; - o.x = x; - o.y = img(x.ch, x.lvl); - const char* dn = nm->f("%s.gamma", ckpt); - if (map_copy(b, dn, nm->ckpt("%s.gamma", ckpt)) < 0) return VImg{}; - o.w = gamma_rank == 4 - ? decl_w(b, dn, RAD_BF16, { x.ch, 1, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group)) - : decl_w(b, dn, RAD_BF16, { x.ch, 1, 1 }, RAD_ACCESS_PER_REQUEST, RAD_SHARD_NONE, grp_layer(first_group)); - o.op = rw(b, RAD_OP(b, "l2norm_chan", - RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch), - RAD_STR("act", silu ? "silu" : "none"), - RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(o.w)), - { x.buf }, { o.y.buf }); - ops.push_back(o); - return o.y; - } - VImg add(const VImg& x, const VImg& z) { - VOp o; - o.kind = VOp::ADD; - o.x = x; - o.z = z; - o.y = img(x.ch, x.lvl); - o.op = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("n", x.ch), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { x.buf, z.buf }, { o.y.buf }); - ops.push_back(o); - return o.y; - } - /* y += the resampling shortcut of x (in place on y). */ - void shortcut(const VImg& x, const VImg& y, int ft) { - VOp o; - o.kind = down ? VOp::S2D : VOp::D2S; - o.x = x; - o.y = y; - o.up = ft; - o.op = rw(b, RAD_OP(b, down ? "s2d_avg_add" : "d2s_add", - RAD_PARAMS(RAD_RANGE("M", 1, px_at(y.lvl)), RAD_INT("cin", x.ch), - RAD_INT("cout", y.ch), RAD_INT("ft", ft), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { x.buf, y.buf }, { y.buf }); - ops.push_back(o); - } - /* A residual block, in -> out channels. */ - VImg resblock(const VImg& x, int64_t out, const char* ckpt) { - VImg h = x; - if (x.ch != out) h = conv(x, out, 1, 1, 1, "same", nm->f("%s.conv_shortcut", ckpt)); - VImg t = norm(x, true, nm->f("%s.norm1", ckpt), 4); - t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv1", ckpt)); - t = norm(t, true, nm->f("%s.norm2", ckpt), 4); - t = conv(t, out, 3, 1, 1, "same", nm->f("%s.conv2", ckpt)); - return add(t, h); - } - /* The mid-block's single-head attention over every pixel. */ - VImg attention(const VImg& x, const char* ckpt) { - const int64_t C = x.ch; - VImg t = norm(x, false, nm->f("%s.norm", ckpt), 3); - VImg qkv = conv(t, 3 * C, 1, 1, 1, "same", nm->f("%s.to_qkv", ckpt)); - VOp o; - o.kind = VOp::ATTN; - o.x = qkv; - o.y = img(C, x.lvl); - o.qkv_ch = 3 * C; - o.op = rw(b, RAD_OP(b, "attn_dense", - RAD_PARAMS(RAD_RANGE("M", 1, px_at(x.lvl)), RAD_INT("head_dim", C), - RAD_INT("gqa", 1), RAD_INT("causal", 0), - RAD_STR("dtype", "bf16"), - RAD_F64("scale", 1.0 / std::sqrt((double)C))), - RAD_NOWEIGHTS), - { qkv.buf }, { o.y.buf }); - ops.push_back(o); - VImg p = conv(o.y, C, 1, 1, 1, "same", nm->f("%s.proj", ckpt)); - return add(p, x); - } - - /* The operands of op `o` for a pass whose level-0 picture is H0 x W0 pixels (or latent tokens, - * for the decoder), in the op's schema order, and its ranged value. */ - static int64_t side(int64_t s0, int lvl, bool dn) { - int64_t s = s0; - for (int i = 0; i < lvl; ++i) s = dn ? s / 2 : s * 2; - return s; - } - /* `cu` is {0, pixels} at the attention's level -- the pass's latent tokens -- and `input` the - * level-0 picture when the first op reads one the pass staged. Ops [from, to) are issued; with - * `row0`, H0 is a band's rows and a `whole` buffer is read from its level-0 row `row0`. */ - void issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, const void* input, - size_t from = 0, size_t to = (size_t)-1, int64_t row0 = 0) const; - - bool is_whole(rad_buf v) const { - for (rad_buf w : whole) if (w == v) return true; - return false; - } - /* The tail's halo in level-0 rows: walked back from the last op, a buffer's margin is the most - * any reader of it needs, in its own rows -- a k x k conv adds k/2, reading through a 2x - * upsample halves it rounding up, and the depth-to-space shortcut halves it. -1 when the tail - * holds an op that is not row-local, or reads a whole buffer above level 0. */ - int64_t band_halo() const { - if (band_from < 0 || ops.empty()) return -1; - std::vector> need{ { ops.back().y.buf, 0 } }; - auto get = [&](rad_buf v) -> int64_t { - for (const auto& e : need) if (e.first == v) return e.second; - return 0; - }; - auto want = [&](rad_buf v, int64_t m) { - for (auto& e : need) if (e.first == v) { e.second = std::max(e.second, m); return; } - need.push_back({ v, m }); - }; - for (size_t i = ops.size(); i-- > (size_t)band_from;) { - const VOp& o = ops[i]; - const int64_t my = get(o.y.buf); - switch (o.kind) { - case VOp::CONV: { - if (o.stride != 1) return -1; - const int64_t m = my + o.k / 2; - want(o.x.buf, o.up == 2 ? (m + 1) / 2 : m); - break; - } - case VOp::NORM: want(o.x.buf, my); break; - case VOp::ADD: want(o.x.buf, my); want(o.z.buf, my); break; - case VOp::D2S: want(o.x.buf, (my + 1) / 2); break; - default: return -1; - } - } - int64_t h = 0; - for (size_t i = (size_t)band_from; i < ops.size(); ++i) { - const VOp& o = ops[i]; - for (const VImg* v : { &o.x, &o.z }) - if (v->buf && is_whole(v->buf)) { - if (v->lvl != 0) return -1; - h = std::max(h, get(v->buf)); - } - } - return h; - } -}; - -inline void Vae::issue(RadCtx* c, int64_t H0, int64_t W0, const RadOperand& cu, - const void* input, size_t from, size_t to, int64_t row0) const { - auto ptr = [&](const VImg& v) -> const void* { - if (!v.buf) return input; - const char* p = (const char*)rad_buf_ptr(c, v.buf); - return row0 && is_whole(v.buf) ? p + row0 * W0 * v.ch * (int64_t)sizeof(uint16_t) : p; - }; - auto view = [&](const VImg& v, int64_t* H, int64_t* W) { - *H = side(H0, v.lvl, down); - *W = side(W0, v.lvl, down); - return RAD_P_T2(ptr(v), RAD_BF16, *H, *W * v.ch); - }; - auto rows = [&](const VImg& v, int64_t cols) { - const int64_t H = side(H0, v.lvl, down), W = side(W0, v.lvl, down); - return RAD_P_T2(ptr(v), RAD_BF16, H * W * v.ch / cols, cols); - }; - for (size_t i = from; i < to && i < ops.size(); ++i) { - const VOp& o = ops[i]; - int64_t Hx, Wx, Hy, Wy; - switch (o.kind) { - case VOp::CONV: { - const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy); - RAD_ISSUE_N(c, o.op, Hy * Wy, x, RAD_W(o.w), RAD_W(o.b), y); - break; - } - case VOp::NORM: { - const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); - RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), RAD_W(o.w), rows(o.y, o.y.ch)); - break; - } - case VOp::ADD: { - const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); - RAD_ISSUE_N(c, o.op, H * W, rows(o.x, o.x.ch), rows(o.z, o.z.ch), rows(o.y, o.y.ch)); - break; - } - case VOp::D2S: - case VOp::S2D: { - const RadOperand x = view(o.x, &Hx, &Wx), y = view(o.y, &Hy, &Wy); - RAD_ISSUE_N(c, o.op, Hy * Wy, x, y); - break; - } - case VOp::ATTN: { - /* q, k and v are column slices of the qkv rows, at its 3C pitch. */ - const int64_t H = side(H0, o.x.lvl, down), W = side(W0, o.x.lvl, down); - const int64_t C = o.y.ch, n = H * W; - RAD_ISSUE_N(c, o.op, n, bcol(o.x.buf, 0, C, n), bcol(o.x.buf, C, C, n), - bcol(o.x.buf, 2 * C, C, n), cu, brows(o.y.buf, n)); - break; - } - } - } -} /* ================================================================== the model */ struct TeLayer { diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index d3bf0fa8..236f2c4c 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -940,7 +941,8 @@ int Builder::decl_name_map(const RadNameMap* m) { return RAD_E_INVAL; } if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM && - m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA) { + m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA && + m->mode != RAD_MAP_TAP) { err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode); return RAD_E_INVAL; } @@ -951,9 +953,9 @@ int Builder::decl_name_map(const RadNameMap* m) { : "the magnitude and the direction", m->n_src); return RAD_E_INVAL; } - if (m->mode == RAD_MAP_TRANSPOSE && m->n_src != 1) { - err(RAD_E_INVAL, "name map for '%s': a transpose map names one source, not %d", - m->declared, m->n_src); + if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP) && m->n_src != 1) { + err(RAD_E_INVAL, "name map for '%s': a %s map names one source, not %d", m->declared, + m->mode == RAD_MAP_TAP ? "tap" : "transpose", m->n_src); return RAD_E_INVAL; } @@ -1192,16 +1194,27 @@ int Builder::declare_generator(const RadGeneratorDecl* d) { : prog_.is_audio_generator() ? "an audio generator" : "a video generator"); return RAD_E_STATE; } - if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID) { + if (d->layout != RAD_GEN_LAYOUT_JOINT_GRID && d->layout != RAD_GEN_LAYOUT_JOINT_STEP) { err(RAD_E_INVAL, "declare_generator '%s': layout %d is not one this engine builds", nm, (int)d->layout); return RAD_E_INVAL; } + const bool joint = d->layout == RAD_GEN_LAYOUT_JOINT_STEP; auto has = [](const char* t, const char* what) { return t && std::strstr(t, what); }; - if (!has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") || - !has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) { - err(RAD_E_INVAL, "declare_generator '%s': tmpl_text needs {prompt}, tmpl_edit {images} and " - "{prompt}, and tmpl_image {image}, where the picture's tokens go", nm); + if (joint ? !has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") + : !has(d->tmpl_text, "{prompt}") || !has(d->tmpl_edit, "{prompt}") || + !has(d->tmpl_edit, "{images}") || !has(d->tmpl_image, "{image}")) { + err(RAD_E_INVAL, "declare_generator '%s': tmpl_text and tmpl_edit need {prompt}, and " + "with the pictures in the prompt tmpl_edit needs {images} and tmpl_image " + "{image}, where the picture's tokens go", nm); + return RAD_E_INVAL; + } + if (joint && (d->cond_rows <= 0 || !(d->rope_hw_scale > 0) || d->pad_multiple < 0 || + (d->pad_multiple > 0 && d->pad_token < 0))) { + err(RAD_E_INVAL, "declare_generator '%s': the joint layout needs cond_rows, a positive " + "rope_hw_scale and, with padding, a pad token (cond_rows %lld, scale %g, " + "pad %d to a multiple of %d)", nm, (long long)d->cond_rows, + d->rope_hw_scale, (int)d->pad_token, (int)d->pad_multiple); return RAD_E_INVAL; } if (d->latent_channels <= 0 || d->latent_scale <= 0 || d->size_multiple <= 0 || @@ -1220,7 +1233,8 @@ int Builder::declare_generator(const RadGeneratorDecl* d) { return RAD_E_INVAL; } if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) || - (d->n_sigmas == 0 && d->default_steps <= 0) || !(d->default_cfg >= 1.0) || + (d->n_sigmas == 0 && d->default_steps <= 0) || + !(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0)) || (d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) || (!d->dyn_shift && !(d->shift > 0)) || d->shift_terminal < 0 || d->shift_terminal >= 1) { err(RAD_E_INVAL, "declare_generator '%s': the sampler is incomplete (%d fixed sigmas, %lld " @@ -1255,17 +1269,19 @@ int Builder::declare_generator(const RadGeneratorDecl* d) { g.name = nm; g.tmpl_text = d->tmpl_text; g.tmpl_edit = d->tmpl_edit; - g.tmpl_image = d->tmpl_image; + g.tmpl_image = d->tmpl_image ? d->tmpl_image : ""; g.tmpl_image_sep = d->tmpl_image_sep ? d->tmpl_image_sep : ""; g.drop_prefix = d->drop_prefix ? d->drop_prefix : ""; g.tmpl_transparent = d->tmpl_transparent ? d->tmpl_transparent : ""; + g.has_default_negative = d->default_negative != nullptr; + g.default_negative = d->default_negative ? d->default_negative : ""; g.sigmas.assign(d->sigmas, d->sigmas + d->n_sigmas); prog_.generator = *d; /* The Program is moved after declare, which would invalidate pointers into gen_str, so the * decl's string fields are cleared; read them only through gen_str. */ RadGeneratorDecl& c = prog_.generator; c.name = c.tmpl_text = c.tmpl_edit = c.tmpl_image = c.tmpl_image_sep = nullptr; - c.drop_prefix = c.tmpl_transparent = nullptr; + c.drop_prefix = c.tmpl_transparent = c.default_negative = nullptr; c.sigmas = nullptr; return RAD_OK; } @@ -1461,22 +1477,78 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) { (long long)d->audio_latent_channels); return RAD_E_INVAL; } - if (d->default_steps <= 0 || d->max_steps < d->default_steps || !(d->shift_video > 0.0) || - !(d->shift_audio > 0.0) || d->max_lanes <= 0) { + /* Form 1 (LTX-2's FlowMatchEulerDiscrete) steps both modalities the same sigmas and reads + * no per-modality shift. */ + const bool shifts = d->sched_kind == 1 || (d->shift_video > 0.0 && d->shift_audio > 0.0); + if (d->default_steps <= 0 || d->max_steps < d->default_steps || !shifts || d->max_lanes <= 0) { err(RAD_E_INVAL, "declare_video_generator '%s': the sampler is incomplete (%lld steps by " "default, %lld at most, shifts %g and %g, %lld lanes)", nm, (long long)d->default_steps, (long long)d->max_steps, d->shift_video, d->shift_audio, (long long)d->max_lanes); return RAD_E_INVAL; } - if (d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) || - (d->n_rungs > 0 && (d->default_steps != d->n_rungs + 1 || d->max_steps != d->n_rungs + 1))) { - err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %d grid " - "points, which default_steps and max_steps must both be (%lld, %lld)", nm, - (int)d->n_rungs, (int)d->n_rungs + 1, (long long)d->default_steps, + /* Form 0 counts grid points, form 1 evaluations. */ + const int64_t rung_steps = d->sched_kind == 1 ? d->n_rungs : d->n_rungs + 1; + if (d->sched_kind < 0 || d->sched_kind > 1 || d->n_rungs < 0 || (d->n_rungs > 0 && !d->rungs) || + (d->n_rungs > 0 && (d->default_steps != rung_steps || d->max_steps != rung_steps))) { + err(RAD_E_INVAL, "declare_video_generator '%s': a trained schedule of %d rungs runs %lld " + "steps, which default_steps and max_steps must both be (%lld, %lld)", nm, + (int)d->n_rungs, (long long)rung_steps, (long long)d->default_steps, (long long)d->max_steps); return RAD_E_INVAL; } + if (d->sched_kind == 1 && d->dyn_shift && + (!(d->max_seq > d->base_seq) || !std::isfinite(d->base_shift) || + !std::isfinite(d->max_shift))) { + err(RAD_E_INVAL, "declare_video_generator '%s': the dynamic shift runs from %lld tokens " + "(%g) to %lld (%g); the second length must be the larger", nm, + (long long)d->base_seq, d->base_shift, (long long)d->max_seq, d->max_shift); + return RAD_E_INVAL; + } + if (!(d->shift_terminal >= 0.0 && d->shift_terminal < 1.0)) { + err(RAD_E_INVAL, "declare_video_generator '%s': shift_terminal %g is outside [0, 1)", nm, + d->shift_terminal); + return RAD_E_INVAL; + } + if (d->n_refine_rungs < 0 || (d->n_refine_rungs > 0 && (!d->refine_rungs || + d->sched_kind != 1 || d->n_rungs == 0 || !(d->upscale_max > 1.0)))) { + err(RAD_E_INVAL, "declare_video_generator '%s': refinement rungs need a trained schedule of " + "form 1 and a latent upscaler", nm); + return RAD_E_INVAL; + } + for (int i = 0; i < d->n_refine_rungs; ++i) + if (!(d->refine_rungs[i] > 0.0 && d->refine_rungs[i] <= 1.0) || + (i > 0 && !(d->refine_rungs[i] < d->refine_rungs[i - 1]))) { + err(RAD_E_INVAL, "declare_video_generator '%s': refinement rung %d (%g) is outside " + "(0, 1] or not below the one before it", nm, i, d->refine_rungs[i]); + return RAD_E_INVAL; + } + if (d->step_text_rows < 0 || d->step_text_rows > d->max_text * 64 || d->image_crf < 0 || + d->image_crf > 51 || (d->image_cond != 0 && d->image_cond != 1) || + (d->guidance != 0 && d->guidance != 1)) { + err(RAD_E_INVAL, "declare_video_generator '%s': step_text_rows %lld, image_cond %d, " + "image_crf %d (0..51) or guidance %d is out of range", nm, + (long long)d->step_text_rows, (int)d->image_cond, (int)d->image_crf, (int)d->guidance); + return RAD_E_INVAL; + } + if (d->text_left_pad < 0 || (d->text_left_pad > 0 && d->text_left_pad < d->max_text) || + d->audio_streams < 0 || + (d->upscale_exact && (!(d->upscale_max > 1.0) || + d->upscale_max != std::floor(d->upscale_max)))) { + err(RAD_E_INVAL, "declare_video_generator '%s': text_left_pad %lld must hold the longest " + "prompt (%lld), audio_streams %d may not be negative, and an exact " + "upscaler's factor (%g) is a whole number above 1", nm, + (long long)d->text_left_pad, (long long)d->max_text, (int)d->audio_streams, + d->upscale_max); + return RAD_E_INVAL; + } + if (d->guidance) + for (int i = 0; i < 8; ++i) + if (!std::isfinite(d->guidance_default[i]) || d->guidance_default[i] < 0.0) { + err(RAD_E_INVAL, "declare_video_generator '%s': default guidance term %d (%g) must " + "be finite and not negative", nm, i, d->guidance_default[i]); + return RAD_E_INVAL; + } for (int i = 0; i < d->n_rungs; ++i) if (!(d->rungs[i] > 0.0 && d->rungs[i] <= 1.0) || (i > 0 && !(d->rungs[i] < d->rungs[i - 1]))) { @@ -1486,9 +1558,13 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) { } /* An upscaler needs a schedule it can split: one evaluation at the small size at least, and * `upscale_refine` of them after it by default. */ - const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs : d->default_steps - 1; + const int64_t def_evals = d->n_rungs > 0 ? d->n_rungs + : d->sched_kind == 1 ? d->default_steps : d->default_steps - 1; + const bool own_refine = d->n_refine_rungs > 0; if (d->upscale_max != 0.0 && - (!(d->upscale_max > 1.0) || d->upscale_refine < 1 || d->upscale_refine >= def_evals)) { + (!(d->upscale_max > 1.0) || + (!own_refine && (d->upscale_refine < 1 || d->upscale_refine >= def_evals)) || + (own_refine && d->upscale_refine != d->n_refine_rungs))) { err(RAD_E_INVAL, "declare_video_generator '%s': a latent upscaler of factor %g at most, " "refining %d evaluations of %lld by default; the factor must be above 1 " "and the refinement 1 to %lld", nm, d->upscale_max, (int)d->upscale_refine, @@ -1521,15 +1597,52 @@ int Builder::declare_video_generator(const RadVideoGenDecl* d) { if (!buf_ok(d->frames_out, RAD_U8, chunk_px, "frames_out") || !buf_ok(d->audio_out, RAD_F32, max_samples * d->audio_channels, "audio_out")) return RAD_E_INVAL; + if (d->duration_out != RAD_NULL_HANDLE) { + if (!buf_ok(d->duration_out, RAD_F32, 1, "duration_out")) return RAD_E_INVAL; + if (!(d->duration_min > 0.0 && d->duration_max > d->duration_min) || + !std::isfinite(d->duration_max) || + (d->duration_dtype != RAD_F32 && d->duration_dtype != RAD_BF16)) { + err(RAD_E_INVAL, "declare_video_generator '%s': a length head clamps to " + "[%g, %g] seconds in dtype %u; the bounds must be positive, finite " + "and in order, the dtype f32 or bf16", nm, d->duration_min, + d->duration_max, (unsigned)d->duration_dtype); + return RAD_E_INVAL; + } + } prog_.vgen_str.name = nm; prog_.vgen_str.tmpl = d->tmpl; prog_.vgen_str.rungs.assign(d->rungs, d->rungs + d->n_rungs); + prog_.vgen_str.refine_rungs.assign(d->refine_rungs, d->refine_rungs + d->n_refine_rungs); + prog_.vgen_str.default_negative = d->default_negative ? d->default_negative : ""; + prog_.vgen_str.decoders.clear(); + prog_.vgen_str.decoder_max_area.clear(); + for (const char* s = d->decoders; s && *s;) { + while (*s == ' ') ++s; + const char* e = s; + while (*e && *e != ' ') ++e; + if (e > s) prog_.vgen_str.decoders.emplace_back(s, e); + s = e; + } + for (size_t i = 0; i < prog_.vgen_str.decoders.size(); ++i) { + const int64_t a = d->decoder_max_area ? d->decoder_max_area[i] : 0; + if (a < 0 || a > d->max_area) { + err(RAD_E_INVAL, "declare_video_generator '%s': decoder '%s' makes frames of %lld pixels " + "at most, outside 0..max_area", nm, + prog_.vgen_str.decoders[i].c_str(), (long long)a); + return RAD_E_INVAL; + } + prog_.vgen_str.decoder_max_area.push_back(a > 0 ? a : d->max_area); + } prog_.video_gen = *d; /* As for the other generators: the Program is moved after declare; strings and the rungs live * in vgen_str. */ prog_.video_gen.name = nullptr; prog_.video_gen.tmpl = nullptr; prog_.video_gen.rungs = nullptr; + prog_.video_gen.refine_rungs = nullptr; + prog_.video_gen.default_negative = nullptr; + prog_.video_gen.decoders = nullptr; + prog_.video_gen.decoder_max_area = nullptr; return RAD_OK; } diff --git a/core/config.cpp b/core/config.cpp index c3eeb23e..56c2f91a 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -73,7 +73,7 @@ static const Flag g_flags[] = { { "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" }, { "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n" "context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n" - "also K in 6 (0.69); both Qwen3.8-27B" }, + "also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" }, { "--host-pool-mib", "N", "pinned host tier" }, { "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n" " pins its host memory at startup (default 4096)" }, diff --git a/core/engine.cpp b/core/engine.cpp index c2625599..1b15d259 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -8,6 +8,7 @@ #include "gen/video_driver.h" #include "kld.h" #include "mm/processor.h" +#include "mm/media.h" #include "build/startup.h" #include "build/rad_build.h" @@ -2375,8 +2376,11 @@ int Engine::run_server() { in.size_multiple = gd.size_multiple; in.pixel_channels = gd.pixel_channels; in.max_tokens = gd.max_tokens; - /* Edits need the conditioning network to read pictures. */ - in.max_refs = mm_proc ? gd.max_refs : 0; + /* Edits need the conditioning network to read pictures, unless only the generator's + * own encoder reads them. */ + in.refs_encoder_only = gd.layout == RAD_GEN_LAYOUT_JOINT_STEP; + in.max_refs = mm_proc || in.refs_encoder_only ? gd.max_refs : 0; + in.ref_shrink_only = gd.ref_shrink_only != 0; in.ref_area = gd.ref_area; in.default_width = gd.default_width; in.default_height = gd.default_height; @@ -2386,6 +2390,9 @@ int Engine::run_server() { in.fixed_schedule = !pg.gen_str.sigmas.empty(); in.fixed_steps = (int64_t)pg.gen_str.sigmas.size(); in.default_cfg = gd.default_cfg; + in.cfg_original = gd.cfg_original != 0; + in.has_default_negative = pg.gen_str.has_default_negative; + in.default_negative = pg.gen_str.default_negative; image_bridge.drv = img_gen_; image_bridge.proc = mm_proc.get(); d.images = &image_bridge; @@ -2497,6 +2504,19 @@ int Engine::run_server() { in.fixed_steps = vd.n_rungs > 0; in.upscale_max = vd.upscale_max; in.upscale_refine = vd.upscale_refine; + in.step_evals = vd.sched_kind == 1; + in.guidance = vd.guidance != 0; + for (int i = 0; i < 8; ++i) in.guidance_default[i] = vd.guidance_default[i]; + in.default_negative = pg.vgen_str.default_negative; + in.image_cond = vd.image_cond != 0; + in.image_crf = vd.image_crf; + in.length_head = vd.duration_out != RAD_NULL_HANDLE; + in.decoders = pg.vgen_str.decoders; + in.decoder_max_area = pg.vgen_str.decoder_max_area; + if (in.image_cond && in.image_crf > 0 && !mm::h264_roundtrip_available()) + RAD_WARN("video: '%s' prepares a first frame with an H.264 round trip at crf %d, which " + "needs libx264; this build's libavcodec has none, so input_reference is " + "refused", in.name.c_str(), (int)in.image_crf); in.max_lanes = vd.max_lanes; video_bridge.drv = vid_gen_; d.videos = &video_bridge; @@ -2555,6 +2575,12 @@ int Engine::run_server() { RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn " "thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ", mapped.c_str()); + /* What a request naming no effort gets, which a client cannot see: Qwen3.8's template + * renders xhigh into a system prompt (#113). */ + const std::string& dflt = srv.template_default_effort(); + if (cfg_.reasoning_effort.empty() && !dflt.empty()) + RAD_INFO("chat: a request naming no reasoning_effort renders as '%s', the " + "template's own default (--reasoning-effort sets another)", dflt.c_str()); } else if (!mapped.empty()) { RAD_INFO("chat: reasoning_effort mapped: %s", mapped.c_str()); } diff --git a/core/engine_probe.cpp b/core/engine_probe.cpp index bba87b21..1d7861ee 100644 --- a/core/engine_probe.cpp +++ b/core/engine_probe.cpp @@ -162,6 +162,10 @@ static bool dump_at(Ctx& ctx, int step, const char* phase, const std::string& na return true; } +/* A buffer is read where it lives after the pass, and the arena shares a transient's bytes with + * every buffer whose lifetime does not overlap it. So a dump after a drafter's context pass shows + * a tap buffer (dflash_src) already overwritten by a later one in that pass (df_c), and only the + * step loop's dump, after the trunk, shows the taps as written. A PERSIST buffer is never shared. */ void dump_buffers(Ctx& ctx, int step, const char* phase) { if ((int)log_level() < (int)Log::Trace) return; static const char* const names = std::getenv("RADIANCE_DUMP_BUF"); diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index aa81c61f..800c549d 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -56,6 +56,25 @@ void MetaOwn::finish() { * path, and typed fields are read from `text_config.X`, falling back to `X`, so a plugin finds * `vision_config.depth` under that name either way. */ +/* An array's scalars appended to `s` space-separated, nested arrays flattened row-major (a + * vocoder's per-resnet dilations, [[1, 3, 5], [1, 3, 5]], read as "1 3 5 1 3 5"); false for an + * array holding an object or a null. */ +static bool join_scalars(const nlohmann::json& v, std::string* s) { + for (const auto& e : v) { + if (e.is_array()) { + if (!join_scalars(e, s)) return false; + continue; + } + if (!s->empty()) *s += ' '; + if (e.is_number_integer()) *s += fmt("%lld", (long long)e.get()); + else if (e.is_number()) *s += fmt("%.17g", e.get()); + else if (e.is_string()) *s += e.get(); + else if (e.is_boolean()) *s += e.get() ? "1" : "0"; + else return false; + } + return true; +} + static void flatten_json(const nlohmann::json& j, const std::string& prefix, MetaOwn* out) { for (auto it = j.begin(); it != j.end(); ++it) { const std::string key = prefix.empty() ? it.key() : prefix + "." + it.key(); @@ -74,19 +93,10 @@ static void flatten_json(const nlohmann::json& j, const std::string& prefix, Met else if (v.is_string()) out->kv(key, v.get()); else if (v.is_array()) { /* An array of scalars becomes a space-separated string (mrope_section "11 11 10", - * layer_types "linear_attention full_attention ..."). Arrays of objects are - * skipped. */ + * layer_types "linear_attention full_attention ..."), nested arrays row-major. + * Arrays of objects are skipped. */ std::string s; - bool ok = true; - for (const auto& e : v) { - if (!s.empty()) s += ' '; - if (e.is_number_integer()) s += fmt("%lld", (long long)e.get()); - else if (e.is_number()) s += fmt("%.17g", e.get()); - else if (e.is_string()) s += e.get(); - else if (e.is_boolean()) s += e.get() ? "1" : "0"; - else { ok = false; break; } - } - if (ok) out->kv(key, s); + if (join_scalars(v, &s)) out->kv(key, s); } } } @@ -590,7 +600,9 @@ int Checkpoint::open_diffusers() { RAD_TRY(meta_merge_json_file(dir_ + "/" + sc + "/scheduler_config.json", sc, true, &meta_)); } - for (const char* sub : { "processor", "tokenizer" }) { + /* The tokenizer's own folder, or the text encoder's when the release keeps it there (FLUX.3 + * [klein]'s modular pipeline points its tokenizer at text_encoder/). */ + for (const char* sub : { "processor", "tokenizer", "text_encoder" }) { const std::string d = dir_ + "/" + sub; if (!path_exists(d + "/tokenizer.json")) continue; tok_dir_ = d; @@ -1552,9 +1564,9 @@ static int resolve_wnorm(Checkpoint& ck, const RadNameMap& m, bool optional, Ckp return RAD_OK; } -/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]) and RAD_MAP_EMA (src[0] the embedding - * sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), computed in - * f32 into `derived`. */ +/* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]), RAD_MAP_EMA (src[0] the embedding + * sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)) and + * RAD_MAP_TAP (one index of one dimension of src[0]), computed in f32 into `derived`. */ static int resolve_derived(Checkpoint& ck, const std::vector& maps, bool optional, CkptWeight* out, std::string* why) { auto refuse = [&](int rc, std::string msg) { @@ -1618,7 +1630,30 @@ static int resolve_derived(Checkpoint& ck, const std::vector& return refuse(RAD_E_FORMAT, "'" + a->name + "' cannot be read as f32"); out->rank = (uint32_t)rank; for (size_t i = 0; i < rank; ++i) out->shape[i] = a->shape[i]; - if (ema) { + if (m.mode == RAD_MAP_TAP) { + const int d = m.concat_dim; + if (d < 0 || (size_t)d >= rank || rank < 3) + return refuse(RAD_E_SHAPE, "'" + a->name + "' has rank " + std::to_string(rank) + + "; a tap of dimension " + std::to_string(d) + + " leaves no matrix"); + const int64_t k = a->shape[(size_t)d]; + const int64_t t = m.src_index[0] < 0 ? k + m.src_index[0] : m.src_index[0]; + if (t < 0 || t >= k) + return refuse(RAD_E_SHAPE, "tap " + std::to_string(m.src_index[0]) + " of '" + + a->name + "' dimension " + std::to_string(d) + " of " + + std::to_string(k)); + int64_t outer = 1, inner = 1; + for (int i = 0; i < d; ++i) outer *= a->shape[(size_t)i]; + for (size_t i = (size_t)d + 1; i < rank; ++i) inner *= a->shape[i]; + out->derived.resize((size_t)(outer * inner)); + for (int64_t o = 0; o < outer; ++o) + std::memcpy(&out->derived[(size_t)(o * inner)], &src[(size_t)((o * k + t) * inner)], + (size_t)inner * sizeof(float)); + out->rank = (uint32_t)(rank - 1); + for (size_t i = (size_t)d; i + 1 < rank; ++i) out->shape[i] = a->shape[i + 1]; + out->why = "it is tap " + std::to_string(t) + " of '" + a->name + "' dimension " + + std::to_string(d) + ", at convert -- a recipe rule stores it"; + } else if (ema) { const int64_t bins = a->shape[0], per = n / bins; int64_t un = 1; for (int64_t x : u->shape) un *= x; @@ -1673,7 +1708,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b if (maps.empty()) return refuse(RAD_E_NOTFOUND, "the name map has no entry for it"); if (maps.front()->mode == RAD_MAP_WNORM) return resolve_wnorm(ck, *maps.front(), optional, out, why); - if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA) + if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA || + maps.front()->mode == RAD_MAP_TAP) return resolve_derived(ck, maps, optional, out, why); struct Src1 { const char* name; int index; int64_t rows; }; std::vector srcs; diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index 500194b9..c4d09ab0 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -24,6 +24,7 @@ int64_t ref_tokens_max(const RadGeneratorDecl& d) { struct Sizes { int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0; + bool joint = false; }; Sizes sizes_of(const Program& prog, int64_t block_size) { @@ -34,7 +35,10 @@ Sizes sizes_of(const Program& prog, int64_t block_size) { z.EP = prog.encoder.modalities ? prog.ctx.max_enc_patches : 0; z.PD = prog.encoder.modalities ? prog.encoder.patch_dim : 0; z.R = d.max_refs; - z.P = z.T + z.R * ref_tokens_max(d); + z.joint = d.layout == RAD_GEN_LAYOUT_JOINT_STEP; + /* The longest conditioning: in the joint layout, the declared bound (its rows ride in the + * step, which the step size bounds anyway). */ + z.P = z.joint ? std::min(d.cond_rows, z.T) : z.T + z.R * ref_tokens_max(d); const int64_t s2 = d.latent_scale * d.latent_scale; z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2; z.NT = d.max_tokens; @@ -47,6 +51,7 @@ Sizes sizes_of(const Program& prog, int64_t block_size) { int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) { const int64_t I = 4, H = 2; const int64_t rope_rows = std::max(z.P, z.T); + const int64_t J = z.joint ? 1 : 0; /* the joint layout's regions, empty otherwise */ const int64_t want[][2] = { { 0, z.T * I }, /* R_TOK */ { 0, z.T * I }, /* R_POS */ @@ -56,7 +61,7 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) { { 0, z.EP * z.PD * H }, /* R_ENCPIX */ { 0, 4 * z.EP * I }, /* R_ENCCRD */ { 0, (z.R + 2) * I }, /* R_ENCCU */ - { 0, z.P * I }, /* R_SRC */ + { 0, rope_rows * I }, /* R_SRC: a COND's rows, or a joint DENOISE's */ { 0, 3 * rope_rows * I }, /* R_GROPE */ { 0, (12 * z.R + 24) * I }, /* R_SEG: offsets; per segment a {0, length} pair and a start; per picture a {0, tokens} pair */ { 0, z.P * I }, /* R_SLOT */ @@ -71,6 +76,15 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) { { 0, 2 * z.S * 4 }, /* R_SEED */ { 0, z.S * z.NB * I }, /* R_BT */ { 0, z.S * I }, /* R_USED */ + { 0, J * 4 * rope_rows * 4 }, /* R_ROPEF */ + { 0, J * (z.S + 1) * I }, /* R_ICU */ + { 0, J * z.T * I }, /* R_IROWS */ + { 0, J * (3 * z.S + 1) * I }, /* R_MCU */ + { 0, J * 2 * I }, /* R_VCU */ + { 0, J * z.T * I }, /* R_MROWS */ + { 0, J * z.T * I }, /* R_MSRC */ + { 0, J * 3 * (z.S + 1) * I }, /* R_MCCU */ + { 0, J * 4 * z.T * 4 }, /* R_MROPE */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { @@ -84,8 +98,10 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) { } /* namespace */ int64_t Driver::device_bytes(const Program& prog) { - if (!prog.is_generator() || prog.kv_groups.size() < 2) return 0; - const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size); + if (!prog.is_generator()) return 0; + const bool joint = prog.generator.layout == RAD_GEN_LAYOUT_JOINT_STEP; + if (!joint && prog.kv_groups.size() < 2) return 0; + const Sizes z = sizes_of(prog, joint ? 0 : prog.kv_groups[1].block_size); int64_t b[R_N][2]; return carve(z, prog.generator.pixel_channels, b, R_N); } @@ -97,16 +113,26 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector& fixed_ = prog.gen_str.sigmas; kv_ = kv; ranks_ = ranks; - /* Exactly one paged full-attention KV group, holding the conditioning. Group handles start at - * 1 (group 0 is the null handle); the KV manager and a batch both index by handle. */ - if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL || - prog.kv_groups[1].block_size <= 0) { + /* Exactly one paged full-attention KV group, holding the conditioning; none in the joint + * layout, where the conditioning rides in the steps. Group handles start at 1 (group 0 is the + * null handle); the KV manager and a batch both index by handle. */ + if (joint()) { + if (prog.kv_groups.size() > 1) { + RAD_ERR("image generator: the joint layout keeps its conditioning in the plugin's " + "state, and the program declares %zu KV group(s)", prog.kv_groups.size() - 1); + return RAD_E_UNSUPPORTED; + } + kv_group_ = 0; + block_size_ = 0; + } else if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL || + prog.kv_groups[1].block_size <= 0) { RAD_ERR("image generator: the program declares %zu KV group(s); the driver stages exactly " "one full-attention group, the conditioning's", prog.kv_groups.size() - 1); return RAD_E_UNSUPPORTED; + } else { + kv_group_ = 1; + block_size_ = prog.kv_groups[1].block_size; } - kv_group_ = 1; - block_size_ = prog.kv_groups[1].block_size; const Sizes z = sizes_of(prog, block_size_); max_tok_ = z.T; max_seqs_ = z.S; @@ -181,9 +207,9 @@ int Driver::submit(std::unique_ptr r, std::string* why) { " latent tokens (" + std::to_string(d.max_tokens * d.latent_scale * d.latent_scale) + " pixels)"); if (tokens * nb > max_tok_) - return no("an image of this size with guidance needs " + std::to_string(tokens * nb) + - " rows a step and a step carries " + std::to_string(max_tok_) + - " (--max-num-batched-tokens)"); + return no("an image of this size" + std::string(nb > 1 ? " with guidance" : "") + + " needs " + std::to_string(tokens * nb) + " rows a step and a step carries " + + std::to_string(max_tok_) + " (--max-num-batched-tokens)"); if (r->n < 1 || r->n > d.max_lanes) return no("n must be 1.." + std::to_string(d.max_lanes)); if ((int64_t)r->refs.size() > d.max_refs) @@ -293,22 +319,36 @@ int Driver::admit_locked() { for (const Pixels& p : r.refs) j.ref_hw.push_back({ (int32_t)(p.h / decl_.latent_scale), (int32_t)(p.w / decl_.latent_scale) }); + int64_t step_rows = 0; for (int b = 0; b < j.n_branch; ++b) { std::string why; - const int s = build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw, - &j.cond[b].lay, &why); + const int s = joint() + ? build_joint_layout(b ? r.neg : r.pos, decl_.pad_multiple, + decl_.rope_hw_scale, decl_.rope_text_l != 0, j.ref_hw, + &j.cond[b].lay, &why) + : build_layout(b ? r.neg : r.pos, decl_.slot_rows, j.ref_hw, &j.cond[b].lay, + &why); if (s < 0) { fail_locked(j, s, why); break; } if (j.cond[b].lay.rows > max_rows_) { fail_locked(j, RAD_E_INVAL, "the conditioning is " + - std::to_string(j.cond[b].lay.rows) + " rows; the driver stages " + + std::to_string(j.cond[b].lay.rows) + " rows (the prompt" + + std::string(r.refs.empty() ? "" : " and its pictures") + + "); this model conditions on at most " + std::to_string(max_rows_)); break; } + step_rows += entry_rows(j, b); } if (j.failed) continue; + if (step_rows > max_tok_) { + fail_locked(j, RAD_E_INVAL, "an image with its conditioning needs " + + std::to_string(step_rows) + " rows a step and a step carries " + + std::to_string(max_tok_) + " (--max-num-batched-tokens)"); + continue; + } } bool ok = true; - for (int b = 0; b < j.n_branch && ok; ++b) { + for (int b = 0; b < j.n_branch && ok && !joint(); ++b) { Cond& c = j.cond[b]; if (c.have_kv) continue; if (!kv_->can_ever_fit(c.lay.rows)) { @@ -337,8 +377,14 @@ int Driver::admit_locked() { const int32_t n_steps = (int32_t)j.sigmas.size() - 1; for (int b = 0; b < j.n_branch; ++b) { Cond& c = j.cond[b]; - c.rope_img.assign((size_t)(3 * j.tokens), 0); - image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens); + if (joint()) { + c.rope_img_f.assign((size_t)(4 * j.tokens), 0.0f); + grid_rope_f(decl_.rope_hw_scale, 0.0f, j.h_lat, j.w_lat, c.rope_img_f.data(), + j.tokens); + } else { + c.rope_img.assign((size_t)(3 * j.tokens), 0); + image_rope(c.lay.next_pos, j.h_lat, j.w_lat, c.rope_img.data(), j.tokens); + } } for (int32_t i = 0; i < r.n; ++i) { const int32_t l = free_lanes_.back(); @@ -413,8 +459,8 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste K.seqused = dptr(ri, R_USED); K.block_size = block_size_; K.max_blocks = max_blocks_; - B.n_kv_groups = 1; - B.kv = &K; + B.n_kv_groups = joint() ? 0 : 1; + B.kv = joint() ? nullptr : &K; B.gen_b = &G; G.src = dptr(ri, R_SRC); G.rope = dptr(ri, R_GROPE); @@ -431,6 +477,20 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste G.lane_dh = hptr(R_LANE); G.flags = dptr(ri, R_FLAGS); G.seed = dptr(ri, R_SEED); + /* The joint layout's fields, which only the passes that use them set. */ + G.branch = 0; + G.n_pad = 0; + G.valid_cu = nullptr; + G.n_img = 0; + G.img_cu = nullptr; + G.img_rows = nullptr; + G.mode_cu = nullptr; + G.rope_f = nullptr; + G.mode_rows = nullptr; + G.mode_src = nullptr; + G.mode_ccu = nullptr; + G.n_mode_h = nullptr; + G.mode_rope_f = nullptr; } } @@ -482,7 +542,8 @@ const RadBatch* Driver::next(int step) { for (int32_t l : j.lanes) { const Lane& ln = lanes_[(size_t)l]; if (ln.finished || ln.final_due || ln.preview_due || ln.step >= n_steps) continue; - const int64_t need = j.tokens * j.n_branch; + int64_t need = 0; + for (int b = 0; b < j.n_branch; ++b) need += entry_rows(j, b); if (rows + need > max_tok_ || entries + j.n_branch > max_seqs_) break; rows += need; entries += j.n_branch; @@ -503,15 +564,19 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { const Request& r = *j.req; const Branch& br = branch ? r.neg : r.pos; const Cond& c = j.cond[branch]; - const int64_t T = (int64_t)br.tokens.size(), P = c.lay.rows; + /* The joint layout's padding tokens follow the prompt's; each sits at position 1 and sees + * only the prompt (`valid_cu`), as a masked padding token does in the reference. */ + const int64_t T_valid = (int64_t)br.tokens.size(); + const int64_t T = T_valid + (joint() ? c.lay.n_pad : 0), P = c.lay.rows; int32_t* tok = hptr(R_TOK); int32_t* pos = hptr(R_POS); int32_t* rope = hptr(R_ROPE); - std::memcpy(tok, br.tokens.data(), (size_t)T * 4); - for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i; + std::memcpy(tok, br.tokens.data(), (size_t)T_valid * 4); + for (int64_t i = T_valid; i < T; ++i) tok[i] = decl_.pad_token; + for (int64_t i = 0; i < T; ++i) pos[i] = i < T_valid ? (int32_t)i : 1; for (int64_t i = 0; i < T; ++i) { - int32_t p3[3] = { (int32_t)i, (int32_t)i, (int32_t)i }; + int32_t p3[3] = { pos[i], pos[i], pos[i] }; if (br.media) br.media->rope.at(i, p3); rope[i] = p3[0]; rope[T + i] = p3[1]; @@ -571,7 +636,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { std::memcpy(segp, c.lay.seg.data(), (size_t)(nsg + 1) * 4); for (int64_t s = 0; s < nsg; ++s) { const int32_t a = c.lay.seg[(size_t)s], len = c.lay.seg[(size_t)s + 1] - a; - for (int cc = 0; cc < 3; ++cc) + /* The joint layout's positions are f32, staged whole below. */ + for (int cc = 0; cc < 3 && !joint(); ++cc) std::memcpy(grope + 3 * (int64_t)a + cc * (int64_t)len, &c.lay.rope[(size_t)(cc * P + a)], (size_t)len * 4); segp[nsg + 1 + 2 * s] = 0; @@ -579,21 +645,31 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { segp[nsg + 1 + 2 * nsg + s] = a; } reg_[R_SRC].used = P * 4; - reg_[R_GROPE].used = 3 * P * 4; + reg_[R_GROPE].used = joint() ? 0 : 3 * P * 4; reg_[R_SEG].used = (4 * nsg + 1) * 4; - const std::vector& bt = kv_->block_table(c.seq, kv_group_); - int32_t* slot = hptr(R_SLOT); - for (int64_t p = 0; p < P; ++p) { - const int64_t bi = p / block_size_; - slot[p] = bi < (int64_t)bt.size() ? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_) - : -1; + static const std::vector no_bt; + const std::vector& bt = joint() ? no_bt : kv_->block_table(c.seq, kv_group_); + if (joint()) { + std::memcpy(hptr(R_ROPEF), c.lay.rope_f.data(), (size_t)(4 * P) * 4); + reg_[R_ROPEF].used = 4 * P * 4; + int32_t* vcu = hptr(R_VCU); + vcu[0] = 0; + vcu[1] = (int32_t)T_valid; + reg_[R_VCU].used = 2 * 4; + } else { + int32_t* slot = hptr(R_SLOT); + for (int64_t p = 0; p < P; ++p) { + const int64_t bi = p / block_size_; + slot[p] = bi < (int64_t)bt.size() + ? (int32_t)(bt[(size_t)bi] * block_size_ + p % block_size_) : -1; + } + reg_[R_SLOT].used = P * 4; + int32_t* btab = hptr(R_BT); + for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i]; + reg_[R_BT].used = (int64_t)bt.size() * 4; + hptr(R_USED)[0] = (int32_t)P; + reg_[R_USED].used = 4; } - reg_[R_SLOT].used = P * 4; - int32_t* btab = hptr(R_BT); - for (size_t i = 0; i < bt.size(); ++i) btab[i] = bt[i]; - reg_[R_BT].used = (int64_t)bt.size() * 4; - hptr(R_USED)[0] = (int32_t)P; - reg_[R_USED].used = 4; /* Pictures again for the generator's own encoder, plus the inpainting source when masked. * Only the positive conditioning's pass writes the lanes. */ @@ -632,7 +708,8 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { * for the life of the pass. */ host_bidi_ = c.lay.bidi; host_px_ = pxh; - host_lanes_ = inp ? j.lanes : std::vector{}; + /* The joint layout's conditioning goes to every lane of the request. */ + host_lanes_ = inp || joint() ? j.lanes : std::vector{}; /* The lanes on the device too: an op copies the inpainting latent and mask into each. */ if (!host_lanes_.empty()) { std::memcpy(hptr(R_LANE), host_lanes_.data(), host_lanes_.size() * 4); @@ -681,6 +758,16 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { G.n_lane = (int64_t)host_lanes_.size(); G.lane_h = host_lanes_.data(); G.lane = G.n_lane ? dptr(ri, R_LANE) : nullptr; + if (joint()) { + B.n_kv_groups = 0; + B.kv = nullptr; + G.slot_mapping = nullptr; + G.branch = branch; + G.n_pad = c.lay.n_pad; + G.valid_cu = dptr(ri, R_VCU); + G.rope = nullptr; + G.rope_f = dptr(ri, R_ROPEF); + } } pass_.kind = RAD_GEN_PASS_COND; pass_.job = j.id; @@ -699,15 +786,28 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step for (int b = 0; b < j->n_branch; ++b) es.push_back({ j, l, b }); } const int64_t S = (int64_t)es.size(); - int64_t n_tok = 0; + int64_t n_tok = 0, n_img = 0; int32_t max_q = 0, max_ctx = 0; int64_t pitch = 1; for (const E& e : es) { - n_tok += e.j->tokens; - max_q = std::max(max_q, (int32_t)e.j->tokens); + const int64_t rows = entry_rows(*e.j, e.branch); + n_tok += rows; + n_img += e.j->tokens; + max_q = std::max(max_q, (int32_t)rows); max_ctx = std::max(max_ctx, (int32_t)e.j->cond[e.branch].lay.rows); - pitch = std::max(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, kv_group_).size()); + if (!joint()) + pitch = std::max(pitch, (int64_t)kv_->block_table(e.j->cond[e.branch].seq, + kv_group_).size()); } + /* The joint layout's per-row arrays: each row's source, the compact image order's bounds and + * rows, each entry's three modes, and the f32 positions. */ + int32_t* src = hptr(R_SRC); + int32_t* icu = hptr(R_ICU); + int32_t* irows = hptr(R_IROWS); + int32_t* mcu = hptr(R_MCU); + float* ropef = hptr(R_ROPEF); + int64_t img = 0; + if (joint()) icu[0] = 0; int32_t* cu = hptr(R_CU); int32_t* pos = hptr(R_POS); int32_t* tok = hptr(R_TOK); @@ -731,9 +831,37 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step const Lane& ln = lanes_[(size_t)e.lane]; const Cond& c = j.cond[e.branch]; const int64_t N = j.tokens; - for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; } - for (int cc = 0; cc < 3; ++cc) - std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4); + if (joint()) { + /* [conditioning | image]: the conditioning's rows from the plugin's copy at this lane + * and branch, the image's from the compact order. */ + const int64_t P = c.lay.rows; + const int64_t base = (2 * (int64_t)e.lane + e.branch) * decl_.cond_rows; + for (int64_t k = 0; k < P; ++k) { + src[row + k] = (int32_t)(base + k); + pos[row + k] = (int32_t)k; + tok[row + k] = 0; + } + for (int cc = 0; cc < 4; ++cc) + std::memcpy(ropef + cc * n_tok + row, c.lay.rope_f.data() + cc * P, (size_t)P * 4); + mcu[3 * i] = (int32_t)row; + mcu[3 * i + 1] = (int32_t)(row + c.lay.text); + mcu[3 * i + 2] = (int32_t)(row + P); + row += P; + for (int64_t k = 0; k < N; ++k) { + src[row + k] = (int32_t)(-(1 + img + k)); + irows[img + k] = (int32_t)(row + k); + pos[row + k] = (int32_t)k; + tok[row + k] = 0; + } + for (int cc = 0; cc < 4; ++cc) + std::memcpy(ropef + cc * n_tok + row, c.rope_img_f.data() + cc * N, (size_t)N * 4); + img += N; + icu[i + 1] = (int32_t)img; + } else { + for (int64_t k = 0; k < N; ++k) { pos[row + k] = (int32_t)k; tok[row + k] = 0; } + for (int cc = 0; cc < 3; ++cc) + std::memcpy(grope + cc * n_tok + row, c.rope_img.data() + cc * N, (size_t)N * 4); + } row += N; cu[i + 1] = (int32_t)row; sig[i] = j.sigmas[(size_t)ln.step]; @@ -758,6 +886,7 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step flags[i] = f; seed[2 * i] = (uint32_t)(ln.seed & 0xffffffffu); seed[2 * i + 1] = (uint32_t)(ln.seed >> 32); + if (joint()) continue; const std::vector& bt = kv_->block_table(c.seq, kv_group_); for (int64_t b = 0; b < pitch; ++b) btab[i * pitch + b] = b < (int64_t)bt.size() ? bt[(size_t)b] : -1; @@ -765,12 +894,46 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step } reg_[R_CU].used = (S + 1) * 4; reg_[R_POS].used = reg_[R_TOK].used = n_tok * 4; - reg_[R_GROPE].used = 3 * n_tok * 4; + if (joint()) { + mcu[3 * S] = (int32_t)n_tok; + /* The mode-major order: every entry's text, then pictures, then image. */ + int32_t* mrows = hptr(R_MROWS); + int32_t* msrc = hptr(R_MSRC); + int32_t* mccu = hptr(R_MCCU); + float* mrope = hptr(R_MROPE); + int64_t k = 0; + for (int mode = 0; mode < 3; ++mode) { + const int64_t k0 = k; + int64_t nm = 0; + for (int64_t i = 0; i < S; ++i) nm += mcu[3 * i + mode + 1] - mcu[3 * i + mode]; + for (int64_t i = 0; i < S; ++i) { + mccu[mode * (S + 1) + i] = (int32_t)(k - k0); + for (int32_t r = mcu[3 * i + mode]; r < mcu[3 * i + mode + 1]; ++r, ++k) { + mrows[k] = r; + msrc[k] = src[r]; + for (int cc = 0; cc < 4; ++cc) + mrope[4 * k0 + cc * nm + (k - k0)] = ropef[cc * n_tok + r]; + } + } + mccu[mode * (S + 1) + S] = (int32_t)(k - k0); + host_nmode_[mode] = k - k0; + } + reg_[R_MROWS].used = reg_[R_MSRC].used = n_tok * 4; + reg_[R_MCCU].used = 3 * (S + 1) * 4; + reg_[R_MROPE].used = 4 * n_tok * 4; + reg_[R_SRC].used = n_tok * 4; + reg_[R_IROWS].used = n_img * 4; + reg_[R_ICU].used = (S + 1) * 4; + reg_[R_MCU].used = (3 * S + 1) * 4; + reg_[R_ROPEF].used = 4 * n_tok * 4; + } else { + reg_[R_GROPE].used = 3 * n_tok * 4; + } reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4; reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4; reg_[R_SEED].used = 2 * S * 4; - reg_[R_BT].used = S * pitch * 4; - reg_[R_USED].used = S * 4; + reg_[R_BT].used = joint() ? 0 : S * pitch * 4; + reg_[R_USED].used = joint() ? 0 : S * 4; if (upload() < 0) return nullptr; finish_batches(n_tok, S, max_q, step); for (size_t rr = 0; rr < ranks_.size(); ++rr) { @@ -789,8 +952,22 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step G.inpaint = 0; G.n_lane = 0; G.lane_h = nullptr; - G.rope = dptr(ri, R_GROPE); + G.rope = joint() ? nullptr : dptr(ri, R_GROPE); G.lane_dh = hptr(R_LANE); + if (joint()) { + G.src = dptr(ri, R_SRC); + G.n_img = n_img; + G.img_cu = dptr(ri, R_ICU); + G.img_rows = dptr(ri, R_IROWS); + G.mode_cu = dptr(ri, R_MCU); + G.rope_f = dptr(ri, R_ROPEF); + G.slot_mapping = nullptr; + G.mode_rows = dptr(ri, R_MROWS); + G.mode_src = dptr(ri, R_MSRC); + G.mode_ccu = dptr(ri, R_MCCU); + G.n_mode_h = host_nmode_; + G.mode_rope_f = dptr(ri, R_MROPE); + } } pass_.kind = RAD_GEN_PASS_DENOISE; return &out_[0]; diff --git a/core/gen/driver.h b/core/gen/driver.h index 79c51fff..6bd715d6 100644 --- a/core/gen/driver.h +++ b/core/gen/driver.h @@ -75,6 +75,7 @@ private: bool have_kv = false; bool encoded = false; std::vector rope_img; /* [3, image tokens]: the image's rows at this sequence */ + std::vector rope_img_f; /* JOINT_STEP: [4, image tokens] */ }; struct Job { uint64_t id = 0; @@ -117,7 +118,7 @@ private: struct Region { int64_t off = 0, bytes = 0, used = 0; }; enum { R_TOK, R_POS, R_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE, R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED, - R_BT, R_USED, R_N }; + R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE, R_N }; int layout_regions(); template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } @@ -133,6 +134,13 @@ private: void fail_locked(Job& j, int status, const std::string& why); Job* job_locked(uint64_t id); + /* The JOINT_STEP layout: the conditioning rides in every denoising entry, and no KV. */ + bool joint() const { return decl_.layout == RAD_GEN_LAYOUT_JOINT_STEP; } + /* An entry's rows in a denoising pass. */ + int64_t entry_rows(const Job& j, int branch) const { + return j.tokens + (joint() ? j.cond[branch].lay.rows : 0); + } + const RadBatch* build_cond(Job& j, int branch, int step); const RadBatch* build_denoise(const std::vector& lanes, int step); const RadBatch* build_decode(int32_t lane, bool preview, int step); @@ -162,6 +170,7 @@ private: Pass pass_; /* Host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */ std::vector host_bidi_, host_px_, host_lanes_; + int64_t host_nmode_[3] = { 0, 0, 0 }; mutable std::mutex mu_; std::deque> jobs_; /* arrival order */ diff --git a/core/gen/gen.cpp b/core/gen/gen.cpp index 8116f29f..89e7eb2b 100644 --- a/core/gen/gen.cpp +++ b/core/gen/gen.cpp @@ -106,6 +106,67 @@ void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_to } } +void grid_rope_f(double hw_scale, float l, int32_t h, int32_t w, float* planes, int64_t n_total) { + const float s = (float)hw_scale; + int64_t k = 0; + for (int32_t r = 0; r < h; ++r) + for (int32_t c = 0; c < w; ++c, ++k) { + planes[k] = 0.0f; + planes[n_total + k] = s * (float)r; + planes[2 * n_total + k] = s * (float)c; + planes[3 * n_total + k] = l; + } +} + +int build_joint_layout(const Branch& b, int32_t pad_multiple, double hw_scale, bool text_l, + const std::vector>& ref_hw, Layout* out, + std::string* why) { + *out = Layout{}; + const int64_t T = (int64_t)b.tokens.size(); + if (b.n_drop < 0 || b.n_drop >= T) { + if (why) *why = "the conditioning prompt is no longer than its fixed prefix"; + return RAD_E_INVAL; + } + if (b.media) { + if (why) *why = "the joint layout reads no pictures in the prompt"; + return RAD_E_INVAL; + } + const int64_t text = T - b.n_drop; + const int64_t padded = pad_multiple > 0 ? (text + pad_multiple - 1) / pad_multiple * pad_multiple + : text; + int64_t refs = 0; + for (const auto& hw : ref_hw) refs += (int64_t)hw.first * hw.second; + const int64_t rows = padded + refs; + out->rows = rows; + out->text = padded; + out->n_pad = (int32_t)(padded - text); + out->src.resize((size_t)rows); + out->rope_f.assign((size_t)(4 * rows), 0.0f); + for (int64_t i = 0; i < padded; ++i) { + out->src[(size_t)i] = (int32_t)(b.n_drop + i); + if (text_l) out->rope_f[(size_t)(3 * rows + i)] = (float)i; + } + out->seg.push_back(0); + out->bidi.push_back(0); + int64_t row = padded, lat = 0; + for (size_t k = 0; k < ref_hw.size(); ++k) { + const int32_t h = ref_hw[k].first, w = ref_hw[k].second; + const int64_t n = (int64_t)h * w; + std::vector pl((size_t)(4 * n)); + grid_rope_f(hw_scale, -(float)(1 + k), h, w, pl.data(), n); + for (int cc = 0; cc < 4; ++cc) + std::memcpy(&out->rope_f[(size_t)(cc * rows + row)], &pl[(size_t)(cc * n)], + (size_t)n * sizeof(float)); + for (int64_t i = 0; i < n; ++i) out->src[(size_t)(row + i)] = (int32_t)(-(1 + lat + i)); + out->seg.push_back((int32_t)row); + out->bidi.push_back(1); + row += n; + lat += n; + } + out->seg.push_back((int32_t)rows); + return RAD_OK; +} + int build_layout(const Branch& b, int64_t slot_rows, const std::vector>& ref_hw, Layout* out, std::string* why) { diff --git a/core/gen/gen.h b/core/gen/gen.h index 9a7d2980..6ad9af96 100644 --- a/core/gen/gen.h +++ b/core/gen/gen.h @@ -129,6 +129,11 @@ struct Layout { std::vector seg; /* [n_seg + 1] */ std::vector bidi; /* [n_seg] */ int32_t next_pos = 0; /* the rotary count after the last row: the image's frame */ + /* JOINT_STEP only: the text's rows (padding included), the padding rows among them, and the + * f32 positions, [4, rows] component-major (`rope` is then empty). */ + int64_t text = 0; + int32_t n_pad = 0; + std::vector rope_f; }; /* `ref_hw` is each reference's latent grid (h, w), in media order. RAD_E_INVAL with `why` when the * prompt does not start with its drop prefix or a picture's slots do not tile its latent grid. */ @@ -137,5 +142,16 @@ int build_layout(const Branch& b, int64_t slot_rows, const std::vector>& ref_hw, Layout* out, + std::string* why); +/* The f32 positions (0, s h, s w, l) of an h x w grid: [4, h * w] component-major. */ +void grid_rope_f(double hw_scale, float l, int32_t h, int32_t w, float* planes, int64_t n_total); + } /* namespace gen */ } /* namespace rad */ diff --git a/core/gen/video.h b/core/gen/video.h index efd4928b..eb0daf14 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -10,6 +10,7 @@ #include "rad_core.h" #include +#include #include #include #include @@ -22,12 +23,13 @@ namespace gen { /* One thing a request has made. */ struct VideoEvent { - enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3 }; + enum Kind { STEP = 1, AUDIO = 2, FRAMES = 3, LENGTH = 4 }; int kind = 0; int32_t steps_done = 0; /* STEP: denoising steps finished */ /* AUDIO: the whole soundtrack, interleaved, in [-1, 1]. */ std::vector samples; - /* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. */ + /* FRAMES: frames [first, first + n) of the video, each [height, width, 3] u8 RGB. LENGTH: + * the `n` frames the model chose for a request that named no length, before any step. */ int32_t first = 0, n = 0; std::vector rgb; }; @@ -49,7 +51,8 @@ public: std::atomic cancel{false}; /* What the request makes, written by the driver at submit: the frames and their size, the - * steps, and the soundtrack's rate and channels. */ + * steps, and the soundtrack's rate and channels. A request whose length the model predicts + * has its `frames`, `steps` and `rows` rewritten once, before its LENGTH event. */ int32_t frames = 0, width = 0, height = 0, steps = 0; int64_t sample_rate = 0, channels = 0; double fps = 0.0; @@ -81,6 +84,17 @@ struct VideoRequest { double upscale = 0.0; int32_t refine = 0; uint64_t seed = 0; + /* Guidance (RadVideoGenDecl::guidance): the eight terms, NaN for the model's default, and the + * negative prompt, rendered and tokenised; `has_neg` false for the model's default. */ + double guidance[8] = { NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN }; + std::vector neg_tokens; + bool has_neg = false; + /* A first frame (RadVideoGenDecl::image_cond): [height, width, 3] u8 RGB at the size the + * first evaluations run at (video_small_size under upscaling, else the video's), already + * prepared as the model's pipeline prepares it; empty for none. */ + std::vector image; + /* The decoder (RadVideoGenDecl::decoders) by its index; 0 the model's default. */ + int32_t decoder = 0; std::shared_ptr ticket; }; @@ -98,14 +112,18 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, void video_small_size(const RadVideoGenDecl& d, int32_t width, int32_t height, double factor, int32_t* small_w, int32_t* small_h); -/* The two schedules a request of `steps` grid points runs (RadVideoGenDecl, "The sampler"): each - * the f32 sigmas, last 0, and the model evaluations it takes, the shorter of the two. With a - * trained schedule any other step count than n_rungs + 1 gives no steps. */ +/* The two schedules a request of `steps` runs (RadVideoGenDecl, "The sampler": grid points under + * form 0, evaluations under form 1): each the f32 sigmas, last 0, and the model evaluations it + * takes, the shorter of the two. With a trained schedule any other step count than the declared + * one gives no steps. `video_tokens` are the video's latent tokens, which form 1's dynamic shift + * reads. With `refine` (form 1 and refinement rungs) the rungs are followed by the refinement + * rungs instead of a 0, the evaluations their sum. */ struct VideoSchedule { std::vector sig_v, sig_a; int32_t steps = 0; }; -VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps); +VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens = 0, + bool refine = false); } /* namespace gen */ } /* namespace rad */ diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 08f28d25..e702188c 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -2,6 +2,7 @@ * waits on, and a request's shape and schedule (video.h). */ #include "video_driver.h" #include "rad_internal.h" +#include "rad_plugin.h" #include #include @@ -75,7 +76,7 @@ VideoShape video_shape(const RadVideoGenDecl& d, int32_t width, int32_t height, if (r2 > den || (r2 == den && (q & 1))) ++q; s.n_audio = (int32_t)q; s.video_rows = (int64_t)s.lat_frames * (s.lat_h / d.patch) * (s.lat_w / d.patch); - s.audio_rows = d.audio_channels * (int64_t)s.n_audio; + s.audio_rows = (d.audio_streams > 0 ? d.audio_streams : d.audio_channels) * (int64_t)s.n_audio; return s; } @@ -120,8 +121,47 @@ static std::vector rung_sigmas(double shift, const double* rungs, int32_t return s; } -VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps) { +/* Form 1 (RadVideoGenDecl::sched_kind): FlowMatchEulerDiscreteScheduler.set_timesteps with + * LTX-2's sigmas. numpy's linspace in f64 (i * step + start, the last exactly the stop) taken to + * f32; the shift and the terminal stretch in f32, as numpy computes on an f32 array with Python + * scalars. */ +static std::vector flow_sigmas(const RadVideoGenDecl& d, int32_t n, int64_t tokens) { + std::vector s((size_t)n); + const double stop = 1.0 / n, step = n > 1 ? (stop - 1.0) / (n - 1) : 0.0; + for (int32_t i = 0; i < n; ++i) s[(size_t)i] = (float)(i == n - 1 && n > 1 ? stop : i * step + 1.0); + if (d.dyn_shift) { + const double m = (d.max_shift - d.base_shift) / (double)(d.max_seq - d.base_seq); + const double mu = (double)tokens * m + (d.base_shift - m * (double)d.base_seq); + const float e = (float)std::exp(mu); + for (float& v : s) v = e / (e + (1.0f / v - 1.0f)); + } + if (d.shift_terminal > 0.0) { + const float sf = (1.0f - s.back()) / (float)(1.0 - d.shift_terminal); + for (float& v : s) v = 1.0f - (1.0f - v) / sf; + } + s.push_back(0.0f); + return s; +} + +VideoSchedule video_schedule(const RadVideoGenDecl& d, int32_t steps, int64_t video_tokens, + bool refine) { VideoSchedule v; + if (d.sched_kind == 1) { + if (d.n_rungs > 0) { + if (steps != d.n_rungs) return v; + for (int32_t i = 0; i < d.n_rungs; ++i) v.sig_v.push_back((float)d.rungs[i]); + if (refine) + for (int32_t i = 0; i < d.n_refine_rungs; ++i) + v.sig_v.push_back((float)d.refine_rungs[i]); + v.sig_v.push_back(0.0f); + } else { + if (steps < 1) return v; + v.sig_v = flow_sigmas(d, steps, video_tokens); + } + v.sig_a = v.sig_v; + v.steps = (int32_t)v.sig_v.size() - 1; + return v; + } if (d.n_rungs > 0) { if (steps != d.n_rungs + 1) return v; v.sig_v = rung_sigmas(d.shift_video, d.rungs, d.n_rungs); @@ -146,10 +186,12 @@ int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } /* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the * allocation and the VRAM budget. */ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], int n) { + /* A guided model's VCOND carries the negative prompt after the positive. */ + const int64_t prompts = d.guidance ? 2 : 1; const int64_t want[] = { - d.max_text * 4, /* R_TOK */ - d.max_text * 4, /* R_POS */ - 2 * 4, /* R_CU */ + prompts * d.max_text * 4, /* R_TOK */ + prompts * d.max_text * 4, /* R_POS */ + 3 * 4, /* R_CU */ 3 * max_tok * 4, /* R_ROPE: a step's rotary positions */ RAD_VGEOM_N * 4, /* R_GEOM */ 6 * 4, /* R_SCHED */ @@ -161,6 +203,8 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], in 4 * 4, /* R_SEG */ 4 * 4, /* R_LAT */ 4, /* R_UP */ + d.image_cond ? d.max_area * 3 * 2 : 0, /* R_IMG: a first frame, bf16 */ + 8 * 4, /* R_GUIDE */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { @@ -206,9 +250,17 @@ int VideoDriver::init(const Program& prog, PositionsFn positions, "video generator must", name_.c_str()); return RAD_E_UNSUPPORTED; } - if (max_tok_ < decl_.max_text) { - RAD_ERR("video generator '%s': a pass carries %lld rows and a prompt may be %lld tokens", - name_.c_str(), (long long)max_tok_, (long long)decl_.max_text); + decoder_names_ = prog.vgen_str.decoders; + decoder_area_ = prog.vgen_str.decoder_max_area; + refine_rungs_ = prog.vgen_str.refine_rungs; + decl_.refine_rungs = refine_rungs_.empty() ? nullptr : refine_rungs_.data(); + default_negative_ = prog.vgen_str.default_negative; + decl_.default_negative = default_negative_.c_str(); + const int64_t prompts = decl_.guidance ? 2 : 1; + if (max_tok_ < prompts * decl_.max_text) { + RAD_ERR("video generator '%s': a pass carries %lld rows and %s may be %lld tokens", + name_.c_str(), (long long)max_tok_, prompts == 2 ? "a prompt and its negative" : + "a prompt", (long long)(prompts * decl_.max_text)); return RAD_E_UNSUPPORTED; } int64_t b[R_N][2]; @@ -222,7 +274,8 @@ int VideoDriver::init(const Program& prog, PositionsFn positions, host_ = static_cast(rad_dev_alloc(bytes_, RAD_MEM_HOST_PINNED)); frames_host_ = static_cast(rad_dev_alloc(frames_bytes_, RAD_MEM_HOST_PINNED)); audio_host_ = static_cast(rad_dev_alloc(audio_bytes_, RAD_MEM_HOST_PINNED)); - if (!host_ || !frames_host_ || !audio_host_) { + duration_host_ = static_cast(rad_dev_alloc(64, RAD_MEM_HOST_PINNED)); + if (!host_ || !frames_host_ || !audio_host_ || !duration_host_) { RAD_ERR("video generator: no pinned host memory for the pass staging and outputs (%lld + " "%lld + %lld bytes)", (long long)bytes_, (long long)frames_bytes_, (long long)audio_bytes_); @@ -258,12 +311,157 @@ void VideoDriver::fini() { if (host_) rad_dev_free(host_, RAD_MEM_HOST_PINNED); if (frames_host_) rad_dev_free(frames_host_, RAD_MEM_HOST_PINNED); if (audio_host_) rad_dev_free(audio_host_, RAD_MEM_HOST_PINNED); + if (duration_host_) rad_dev_free(duration_host_, RAD_MEM_HOST_PINNED); + duration_host_ = nullptr; host_ = nullptr; frames_host_ = nullptr; audio_host_ = nullptr; } /* ================================================================== requests */ +/* A length head's prediction (RadVideoGenDecl::duration_out) in chunks: diffusers' + * LTX2DurationHead.predict_num_frames on the chunk grid -- the seconds clamped to the declared + * bounds, rounded to frames, floored to the grid and lifted one chunk when that falls under the + * minimum -- then held to min_chunks..max_chunks. `note` says what was clamped. */ +int32_t VideoDriver::predicted_chunks(double log_seconds, std::string* note) const { + const RadVideoGenDecl& d = decl_; + const double fps = (double)d.fps_num / (double)d.fps_den; + float e = std::exp((float)log_seconds); + if (d.duration_dtype == RAD_BF16) e = rad_bf16_to_f32(rad_f32_to_bf16(e)); + const double sec = e; + auto round_even = [](double v) { return (int64_t)std::nearbyint(v); }; + const int64_t lo = std::max(1, round_even(d.duration_min * fps)); + const int64_t hi = round_even(d.duration_max * fps); + const int64_t want = std::isfinite(sec) ? round_even(sec * fps) : hi; + const int64_t frames = std::max(lo, std::min(want, hi)); + int64_t n = std::max(0, (frames - d.frames_tail) / d.frames_per_chunk); + if (d.frames_per_chunk * n + d.frames_tail < lo && + d.frames_per_chunk * (n + 1) + d.frames_tail <= hi) + ++n; + std::string what = fmt(": %.3f s predicted", sec); + if (!(sec >= d.duration_min && sec <= d.duration_max)) + what += fmt(", held to %g..%g s", d.duration_min, d.duration_max); + if (n < d.min_chunks || n > d.max_chunks) { + n = std::max(d.min_chunks, std::min(n, d.max_chunks)); + what += fmt(", within the %lld..%lld frames this model makes", + (long long)(d.frames_per_chunk * d.min_chunks + d.frames_tail), + (long long)(d.frames_per_chunk * d.max_chunks + d.frames_tail)); + } + if (note) *note = what; + return (int32_t)n; +} + +/* The request's shape at `chunks` long: its geometry, rows and positions, its schedule, the + * upscale's split and what its ticket says it makes. Run at submit, and again for a request whose + * length the model predicts once its VCOND pass has written the prediction. */ +int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps, + std::string* why) { + const RadVideoGenDecl& d = decl_; + auto no = [&](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + const int64_t T = (int64_t)r.tokens.size(); + const VideoShape s = video_shape(d, r.width, r.height, chunks); + j.geom.n_text = (int32_t)(d.step_text_rows > 0 ? d.step_text_rows : T); + j.geom.frames = s.frames; + j.geom.lat_frames = s.lat_frames; + j.geom.lat_h = s.lat_h; + j.geom.lat_w = s.lat_w; + j.geom.n_audio = s.n_audio; + j.rows = j.geom.n_text + s.audio_rows + s.video_rows; + if (j.rows > max_tok_) + return no("a step of this video is " + std::to_string(j.rows) + " rows and a pass " + "carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video"); + const int64_t nr = positions_(RAD_VPOS_STEP, &j.geom, nullptr, 0); + const int64_t nd = positions_(RAD_VPOS_DECODE, &j.geom, nullptr, 0); + if (nr != j.rows || nd <= 0 || nd > max_tok_) + return no("the model lays this video out in " + std::to_string(nr) + " step rows and " + + std::to_string(nd) + " decoder rows, which this server cannot run"); + j.dec_rows = nd; + j.pos.assign((size_t)(3 * nr), 0.0f); + if (positions_(RAD_VPOS_STEP, &j.geom, j.pos.data(), nr) != nr) + return no("the model could not lay this video out"); + /* The schedule follows the upscale's split, which needs the small size first. */ + const bool upscaling = r.upscale > 1.0; + const bool own_refine = upscaling && d.n_refine_rungs > 0; + int64_t first_tokens = s.video_rows; + if (upscaling) { + int32_t sw = 0, sh = 0; + video_small_size(d, r.width, r.height, r.upscale, &sw, &sh); + first_tokens = video_shape(d, sw, sh, chunks).video_rows; + } + j.sched = video_schedule(d, steps, first_tokens, own_refine); + if (j.sched.steps < 1) return no("the schedule has no steps"); + int32_t first_w = r.width, first_h = r.height; + if (upscaling) { + if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler"); + if (d.upscale_exact) { + const int64_t m = (int64_t)std::llround(d.size_multiple * d.upscale_max); + if (r.upscale != d.upscale_max || r.width % m || r.height % m) + return no("this model's latent upscaler enlarges by exactly " + + fmt("%g", d.upscale_max) + ": latent_upscale must be that, and both " + "sides multiples of " + std::to_string(m)); + } + if (r.upscale > d.upscale_max) + return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model"); + int32_t sw = 0, sh = 0; + video_small_size(d, r.width, r.height, r.upscale, &sw, &sh); + if (sw == r.width && sh == r.height) + return no("latent_upscale " + fmt("%g", r.upscale) + " leaves " + + std::to_string(r.width) + "x" + std::to_string(r.height) + " as it is: " + "the small size is each side over the factor, rounded to a multiple of " + + std::to_string(d.size_multiple)); + const int32_t evals = j.sched.steps; + int32_t refine = r.refine; + if (own_refine) { + if (refine != 0 && refine != d.n_refine_rungs) + return no("upscale_refine_steps must be " + std::to_string(d.n_refine_rungs) + + ": this model refines the upscaled video over the schedule it was " + "trained on"); + refine = d.n_refine_rungs; + } + if (refine == 0) refine = std::min(d.upscale_refine, evals - 1); + if (refine < 1 || refine >= evals) + return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the " + "schedule takes " + std::to_string(evals) + " evaluations and the small " + "size at least one of them"); + const VideoShape ss = video_shape(d, sw, sh, chunks); + j.geom_small = j.geom; + j.geom_small.lat_h = ss.lat_h; + j.geom_small.lat_w = ss.lat_w; + j.rows_small = j.geom.n_text + ss.audio_rows + ss.video_rows; + const int64_t ns = positions_(RAD_VPOS_STEP, &j.geom_small, nullptr, 0); + if (ns != j.rows_small) + return no("the model lays the small size " + std::to_string(sw) + "x" + + std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which " + "this server cannot run"); + j.pos_small.assign((size_t)(3 * ns), 0.0f); + if (positions_(RAD_VPOS_STEP, &j.geom_small, j.pos_small.data(), ns) != ns) + return no("the model could not lay the small size out"); + j.split = evals - refine; + j.factor = (float)(((double)r.width / sw + (double)r.height / sh) / 2.0); + r.ticket->small_width = sw; + r.ticket->small_height = sh; + r.ticket->refine = refine; + first_w = sw; + first_h = sh; + } + if (!r.image.empty()) { + if (!d.image_cond) return no("this model cannot start from a picture"); + if (r.image.size() != (size_t)first_w * first_h * 3) + return no("the first frame is not " + std::to_string(first_w) + "x" + + std::to_string(first_h) + " RGB"); + } + j.n_chunks = chunks; + j.n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate); + VideoTicket& t = *r.ticket; + t.frames = s.frames; + t.steps = j.sched.steps; + t.rows = j.rows; + return RAD_OK; +} + int VideoDriver::submit(std::unique_ptr r, std::string* why) { if (!r || !r->ticket) return RAD_E_INVAL; const RadVideoGenDecl& d = decl_; @@ -275,7 +473,7 @@ int VideoDriver::submit(std::unique_ptr r, std::string* why) { if (T < 1 || T > d.max_text) return no("the prompt is " + std::to_string(T) + " tokens; this model takes 1.." + std::to_string(d.max_text)); - if (r->chunks < d.min_chunks || r->chunks > d.max_chunks) + if (r->chunks != 0 && (r->chunks < d.min_chunks || r->chunks > d.max_chunks)) return no("the length must be " + std::to_string(d.min_chunks) + ".." + std::to_string(d.max_chunks) + " chunks"); const int64_t W = r->width, H = r->height; @@ -287,87 +485,53 @@ int VideoDriver::submit(std::unique_ptr r, std::string* why) { " pixels, the long side at most " + std::to_string(d.max_aspect) + " times the short"); const int32_t steps = r->steps > 0 ? r->steps : (int32_t)d.default_steps; - if (d.n_rungs > 0 && steps != d.n_rungs + 1) - return no("num_inference_steps must be " + std::to_string(d.n_rungs + 1) + ": this model " + const bool evals = d.sched_kind == 1; /* form 1 counts evaluations, form 0 grid points */ + const int32_t rung_steps = evals ? d.n_rungs : d.n_rungs + 1; + if (d.n_rungs > 0 && steps != rung_steps) + return no("num_inference_steps must be " + std::to_string(rung_steps) + ": this model " "runs the schedule it was trained on, " + std::to_string(d.n_rungs) + " evaluations"); - if (steps < 2 || steps > d.max_steps) - return no("num_inference_steps must be 2.." + std::to_string(d.max_steps) + " (sigma grid " - "points, the last one 0)"); + if (steps < (evals ? 1 : 2) || steps > d.max_steps) + return no("num_inference_steps must be " + std::to_string(evals ? 1 : 2) + ".." + + std::to_string(d.max_steps) + (evals ? " (model evaluations)" : + " (sigma grid points, the last one 0)")); auto j = std::make_unique(); - const VideoShape s = video_shape(d, r->width, r->height, r->chunks); - j->geom.n_text = (int32_t)T; - j->geom.frames = s.frames; - j->geom.lat_frames = s.lat_frames; - j->geom.lat_h = s.lat_h; - j->geom.lat_w = s.lat_w; - j->geom.n_audio = s.n_audio; - j->rows = T + s.audio_rows + s.video_rows; - if (j->rows > max_tok_) - return no("a step of this video is " + std::to_string(j->rows) + " rows and a pass " - "carries " + std::to_string(max_tok_) + "; ask for a shorter or smaller video"); - const int64_t nr = positions_(RAD_VPOS_STEP, &j->geom, nullptr, 0); - const int64_t nd = positions_(RAD_VPOS_DECODE, &j->geom, nullptr, 0); - if (nr != j->rows || nd <= 0 || nd > max_tok_) - return no("the model lays this video out in " + std::to_string(nr) + " step rows and " + - std::to_string(nd) + " decoder rows, which this server cannot run"); - j->dec_rows = nd; - j->pos.assign((size_t)(3 * nr), 0.0f); - if (positions_(RAD_VPOS_STEP, &j->geom, j->pos.data(), nr) != nr) - return no("the model could not lay this video out"); - j->sched = video_schedule(d, steps); - if (j->sched.steps < 1) return no("the schedule has no steps"); - if (r->upscale > 1.0) { - if (!(d.upscale_max > 1.0)) return no("this model has no latent upscaler"); - if (r->upscale > d.upscale_max) - return no("latent_upscale is at most " + fmt("%g", d.upscale_max) + " for this model"); - int32_t sw = 0, sh = 0; - video_small_size(d, r->width, r->height, r->upscale, &sw, &sh); - if (sw == r->width && sh == r->height) - return no("latent_upscale " + fmt("%g", r->upscale) + " leaves " + - std::to_string(r->width) + "x" + std::to_string(r->height) + " as it is: " - "the small size is each side over the factor, rounded to a multiple of " + - std::to_string(d.size_multiple)); - const int32_t evals = j->sched.steps; - int32_t refine = r->refine; - if (refine == 0) refine = std::min(d.upscale_refine, evals - 1); - if (refine < 1 || refine >= evals) - return no("upscale_refine_steps must be 1.." + std::to_string(evals - 1) + ": the " - "schedule takes " + std::to_string(evals) + " evaluations and the small " - "size at least one of them"); - const VideoShape ss = video_shape(d, sw, sh, r->chunks); - j->geom_small = j->geom; - j->geom_small.lat_h = ss.lat_h; - j->geom_small.lat_w = ss.lat_w; - j->rows_small = T + ss.audio_rows + ss.video_rows; - const int64_t ns = positions_(RAD_VPOS_STEP, &j->geom_small, nullptr, 0); - if (ns != j->rows_small) - return no("the model lays the small size " + std::to_string(sw) + "x" + - std::to_string(sh) + " out in " + std::to_string(ns) + " step rows, which " - "this server cannot run"); - j->pos_small.assign((size_t)(3 * ns), 0.0f); - if (positions_(RAD_VPOS_STEP, &j->geom_small, j->pos_small.data(), ns) != ns) - return no("the model could not lay the small size out"); - j->split = evals - refine; - j->factor = (float)(((double)r->width / sw + (double)r->height / sh) / 2.0); - r->ticket->small_width = sw; - r->ticket->small_height = sh; - r->ticket->refine = refine; + /* Guidance: the request's terms over the model's defaults; a negative prompt only when a + * scale asks for the unconditional branch. */ + bool named = r->has_neg; + for (int i = 0; i < 8; ++i) { + named = named || !std::isnan(r->guidance[i]); + j->guidance[i] = (float)(std::isnan(r->guidance[i]) ? d.guidance_default[i] : r->guidance[i]); + if (!(j->guidance[i] >= 0.0f) || !std::isfinite(j->guidance[i])) + return no("guidance terms must be finite and not negative"); } - j->n_chunks = r->chunks; - j->n_samples = (int64_t)s.n_audio * (d.sample_rate / d.audio_rate); + if (!d.guidance && named) + return no("this model takes no guidance or negative prompt"); + j->n_neg = 0; + if (d.guidance && (j->guidance[0] != 1.0f || j->guidance[4] != 1.0f)) { + const int64_t N = (int64_t)r->neg_tokens.size(); + if (N < 1 || N > d.max_text) + return no("the negative prompt is " + std::to_string(N) + " tokens; this model takes " + "1.." + std::to_string(d.max_text)); + j->n_neg = (int32_t)N; + } + if (r->decoder < 0 || (r->decoder > 0 && (size_t)r->decoder >= decoder_area_.size())) + return no("this model has no decoder " + std::to_string(r->decoder)); + if (r->decoder > 0 && W * H > decoder_area_[(size_t)r->decoder]) + return no("the " + decoder_names_[(size_t)r->decoder] + " decoder makes frames of " + + std::to_string(decoder_area_[(size_t)r->decoder]) + " pixels at most"); + j->auto_len = r->chunks == 0 && d.duration_out != RAD_NULL_HANDLE; + const int32_t chunks = r->chunks == 0 ? (int32_t)d.default_chunks : r->chunks; + if (shape_job(*j, *r, chunks, steps, why) < 0) return RAD_E_INVAL; VideoTicket& t = *r->ticket; - t.frames = s.frames; t.width = r->width; t.height = r->height; - t.steps = j->sched.steps; t.sample_rate = d.sample_rate; t.channels = d.audio_channels; t.fps = (double)d.fps_num / (double)d.fps_den; t.in_tokens = T; - t.rows = j->rows; t.t_submit_ns = (int64_t)rad_mono_ns(); std::lock_guard lk(mu_); if (closed_) { @@ -472,8 +636,16 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, b.lat_frames, b.lat_h / p, b.lat_w / p }; std::memcpy(g + RAD_VGEOM_UP_SRC, up, sizeof up); } + g[RAD_VGEOM_AUDIO_VOL] = g0.n_audio; + g[RAD_VGEOM_AUDIO_VOL + 1] = 1; + g[RAD_VGEOM_AUDIO_VOL + 2] = 1; + const int32_t ppf = (int32_t)((g0.lat_h / decl_.patch) * (g0.lat_w / decl_.patch)); + g[RAD_VGEOM_FIRST_CU] = 0; + g[RAD_VGEOM_FIRST_CU + 1] = ppf; + g[RAD_VGEOM_FIRST_CU + 2] = ppf * g0.lat_frames; reg_[R_GEOM].used = RAD_VGEOM_N * 4; - const int64_t audio_rows = decl_.audio_channels * (int64_t)g0.n_audio; + const int64_t audio_rows = + (decl_.audio_streams > 0 ? decl_.audio_streams : decl_.audio_channels) * (int64_t)g0.n_audio; const int64_t video_rows = rows - g0.n_text - audio_rows; *hptr(R_LANE) = j.lane; *hptr(R_FIRST) = j.step == 0; @@ -487,6 +659,8 @@ void VideoDriver::stage_geom(const Job& j, const RadVideoGeom& g0, int64_t rows, lat[1] = (int32_t)video_rows; lat[2] = 0; lat[3] = (int32_t)audio_rows; + std::memcpy(hptr(R_GUIDE), j.guidance, sizeof j.guidance); + reg_[R_GUIDE].used = sizeof j.guidance; reg_[R_LANE].used = 4; reg_[R_FIRST].used = 4; reg_[R_SEG].used = 4 * 4; @@ -529,6 +703,10 @@ void VideoDriver::base_batches(const Job& j, const RadVideoGeom& g, int64_t n_to V.dec_rows = j.dec_rows; V.n_samples = j.n_samples; V.upscale = dptr(ri, R_UP); + V.guidance_h = j.guidance; + V.guidance = dptr(ri, R_GUIDE); + V.has_image = !j.req->image.empty(); + V.decoder = j.req->decoder; B.vgen_b = &V; } } @@ -581,30 +759,54 @@ const RadBatch* VideoDriver::batch_for(int rank) const { const RadBatch* VideoDriver::build_cond(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; - const int64_t T = j.geom.n_text; + /* The prompt, then the negative prompt when the request is guided against one, each its own + * sequence from position 0. */ + const int64_t T = (int64_t)j.req->tokens.size(), N = j.n_neg; int32_t* tok = hptr(R_TOK); int32_t* pos = hptr(R_POS); std::memcpy(tok, j.req->tokens.data(), (size_t)T * 4); - for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)i; + if (N > 0) std::memcpy(tok + T, j.req->neg_tokens.data(), (size_t)N * 4); + /* A left-padded encoder's prompt ends at text_left_pad - 1. */ + const int64_t lp = decl_.text_left_pad; + for (int64_t i = 0; i < T; ++i) pos[i] = (int32_t)(lp > 0 ? lp - T + i : i); + for (int64_t i = 0; i < N; ++i) pos[T + i] = (int32_t)(lp > 0 ? lp - N + i : i); int32_t* cu = hptr(R_CU); cu[0] = 0; cu[1] = (int32_t)T; + cu[2] = (int32_t)(T + N); + /* The first frame as the reference's image processor hands it to the VAE: x / 255 * 2 - 1 in + * f32, then bf16. */ + const std::vector& img = j.req->image; + if (!img.empty()) { + uint16_t* px = hptr(R_IMG); + for (size_t i = 0; i < img.size(); ++i) + px[i] = rad_f32_to_bf16(2.0f * ((float)img[i] / 255.0f) - 1.0f); + reg_[R_IMG].used = (int64_t)img.size() * 2; + } float* tv = hptr(R_TV); float* ta = hptr(R_TA); for (int32_t i = 0; i < j.sched.steps; ++i) { tv[i] = 1.0f - j.sched.sig_v[(size_t)i]; ta[i] = 1.0f - j.sched.sig_a[(size_t)i]; } - reg_[R_TOK].used = T * 4; - reg_[R_POS].used = T * 4; - reg_[R_CU].used = 2 * 4; + reg_[R_TOK].used = (T + N) * 4; + reg_[R_POS].used = (T + N) * 4; + reg_[R_CU].used = (N > 0 ? 3 : 2) * 4; reg_[R_TV].used = j.sched.steps * 4; reg_[R_TA].used = j.sched.steps * 4; const RadVideoGeom& g = small_now(j) ? j.geom_small : j.geom; stage_geom(j, g, small_now(j) ? j.rows_small : j.rows, 0); if (upload() < 0) return nullptr; - base_batches(j, g, T, step); - for (auto& B : out_) B.gen = RAD_GEN_PASS_VCOND; + base_batches(j, g, T + N, step); + for (size_t r = 0; r < out_.size(); ++r) { + RadBatch& B = out_[r]; + B.gen = RAD_GEN_PASS_VCOND; + B.n_seq = N > 0 ? 2 : 1; + B.max_q_len = B.max_q_len_prefill = (int32_t)std::max(T, N); + vout_[r].n_neg = (int32_t)N; + if (!img.empty()) vout_[r].image = dptr((int)r, R_IMG); + } + if (j.auto_len) rb_.assign(1, Readback{ decl_.duration_out, 4, duration_host_ }); pass_.kind = RAD_GEN_PASS_VCOND; pass_.job = j.id; return &out_[0]; @@ -691,6 +893,7 @@ const RadBatch* VideoDriver::build_audio(Job& j, int step) { const RadBatch* VideoDriver::build_chunk(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; stage_geom(j, j.geom, j.rows, j.chunk); + stage_seed(j); /* a decoder that denoises draws from the request's seed */ if (upload() < 0) return nullptr; base_batches(j, j.geom, j.dec_rows, step); const bool last = j.chunk == j.n_chunks - 1; @@ -715,6 +918,26 @@ int VideoDriver::done() { case RAD_GEN_PASS_VCOND: j->cond_done = true; j->req->ticket->t_cond_ns = now; + if (j->auto_len) { + j->auto_len = false; + std::string note, why; + int32_t n = predicted_chunks((double)duration_host_[0], ¬e); + /* Shaped as at submit, which passed at default_chunks; a longer video than a pass + * can carry is shortened until it fits. */ + const int32_t steps = j->req->steps > 0 ? j->req->steps : (int32_t)decl_.default_steps; + const int32_t at_submit = j->n_chunks; + while (n > at_submit && shape_job(*j, *j->req, n, steps, &why) < 0) --n; + if (n <= at_submit && shape_job(*j, *j->req, n, steps, &why) < 0) { + fail_locked(*j, RAD_E_INVAL, why); + break; + } + RAD_INFO("video: the model gives the prompt %d frames (%.2f s)%s", j->geom.frames, + (double)j->geom.frames * decl_.fps_den / decl_.fps_num, note.c_str()); + VideoEvent e; + e.kind = VideoEvent::LENGTH; + e.n = j->geom.frames; + j->req->ticket->push(std::move(e)); + } break; case RAD_GEN_PASS_VSTEP: { ++j->step; diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index c1dd0da6..2962d229 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -6,7 +6,8 @@ * threads through `submit()` and leave through their VideoTicket. * * A request holds a lane from admission to its last chunk. Its geometry, schedule and rotary - * positions are fixed at submit, so nothing is computed between passes but the staging. + * positions are fixed at submit, so nothing is computed between passes but the staging; a request + * whose length the model predicts is shaped again once, after its VCOND pass. * * Pass priority, one pass at a time: * @@ -76,6 +77,13 @@ private: std::vector pos_small; float factor = 0.0f; bool upscaled = false; + /* Guidance resolved against the model's defaults (RadVideoGenBatch::guidance_h) and the + * negative prompt's tokens the VCOND pass carries (0: none). */ + float guidance[8] = {}; + int32_t n_neg = 0; + /* The request named no length and the model predicts one (RadVideoGenDecl::duration_out): + * shaped at default_chunks until its VCOND pass is done. */ + bool auto_len = false; int32_t lane = -1; bool admitted = false; bool cond_done = false; @@ -96,7 +104,7 @@ private: /* Staging regions: their offsets in the host span and every rank's slab. */ struct Region { int64_t off = 0, bytes = 0, used = 0; }; enum { R_TOK, R_POS, R_CU, R_ROPE, R_GEOM, R_SCHED, R_TV, R_TA, R_SEED, R_LANE, R_FIRST, - R_SEG, R_LAT, R_UP, R_N }; + R_SEG, R_LAT, R_UP, R_IMG, R_GUIDE, R_N }; template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } template T* dptr(int rank, int r) const { @@ -105,6 +113,8 @@ private: int upload(); /* The geometry and rows of the job's next step: the small ones before its upscale. */ bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; } + int shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps, std::string* why); + int32_t predicted_chunks(double log_seconds, std::string* note) const; void base_batches(const Job& j, const RadVideoGeom& g, int64_t n_tok, int step); void stage_geom(const Job& j, const RadVideoGeom& g, int64_t rows, int32_t chunk); void stage_sched(const Job& j, int32_t i, bool to_clean); @@ -123,6 +133,10 @@ private: RadVideoGenDecl decl_{}; std::vector rungs_; /* decl_.rungs points here */ + std::vector refine_rungs_; /* decl_.refine_rungs */ + std::string default_negative_; + std::vector decoder_names_; /* RadVideoGenDecl::decoders */ + std::vector decoder_area_; /* each one's largest frame */ std::string name_; PositionsFn positions_ = nullptr; int64_t max_tok_ = 0; @@ -136,6 +150,7 @@ private: int64_t frames_bytes_ = 0; float* audio_host_ = nullptr; int64_t audio_bytes_ = 0; + float* duration_host_ = nullptr; /* duration_out's readback, f32 [1] */ std::vector rb_; std::vector out_; /* one per rank */ diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index 179e9e86..820e1abb 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -774,10 +774,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa /* Evict the least recently used snapshot, where a use is its reservation or a lookup * resuming from it, and never one handed out or reserved this step (its admission * restores from the slot ahead of the step; the save lands in it after). A tip gets - * no protection beyond its recency: sessions - * are request ids, and a client that rewrites its last message leaves one tip per - * turn that no later turn reaches, while the anchor every turn resumes from is used - * each turn. */ + * no protection beyond its recency: sessions are request ids, and a client that + * rewrites its last message leaves one tip per turn that no later turn reaches, while + * the anchor every turn resumes from is used each turn. */ const Ckpt* victim = nullptr; for (const auto& kvp : ck_by_prefix_) { if (handed(kvp.first) || reserved(kvp.first)) continue; diff --git a/core/mm/imaging.cpp b/core/mm/imaging.cpp index 585e6438..fb8e2943 100644 --- a/core/mm/imaging.cpp +++ b/core/mm/imaging.cpp @@ -22,6 +22,12 @@ double sinc(double x) { double lanczos(double x) { return (-3.0 <= x && x < 3.0) ? sinc(x) * sinc(x / 3.0) : 0.0; } +/* PIL's BILINEAR filter: a triangle of support 1. */ +double triangle(double x) { + if (x < 0.0) x = -x; + return x < 1.0 ? 1.0 - x : 0.0; +} + /* One axis: for each output index its first input index, its tap count, and `ksize` fixed-point * coefficients. */ struct Axis { @@ -30,11 +36,11 @@ struct Axis { std::vector kk; /* [out, ksize] */ }; -Axis coeffs(int in_size, int out_size) { +Axis coeffs(int in_size, int out_size, bool bilinear) { Axis a; const double scale = (double)in_size / (double)out_size; double filterscale = scale < 1.0 ? 1.0 : scale; - const double support = 3.0 * filterscale; + const double support = (bilinear ? 1.0 : 3.0) * filterscale; a.ksize = (int)std::ceil(support) * 2 + 1; a.bounds.assign((size_t)out_size * 2, 0); a.kk.assign((size_t)out_size * a.ksize, 0); @@ -50,7 +56,8 @@ Axis coeffs(int in_size, int out_size) { xmax -= xmin; int x = 0; for (; x < xmax; ++x) { - const double w = lanczos((x + xmin - center + 0.5) * ss); + const double t = (x + xmin - center + 0.5) * ss; + const double w = bilinear ? triangle(t) : lanczos(t); k[(size_t)x] = w; ww += w; } @@ -80,7 +87,17 @@ inline unsigned muldiv255(unsigned a, unsigned b) { } /* namespace */ +static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinear, FrameRGBA* out); + void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) { + resize_rgba(src, w, h, false, out); +} + +void resize_bilinear_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out) { + resize_rgba(src, w, h, true, out); +} + +static void resize_rgba(const FrameRGBA& src, int32_t w, int32_t h, bool bilinear, FrameRGBA* out) { const int iw = src.w, ih = src.h; /* Image.resize returns a copy at the same size. The premultiplied round trip below is not * lossless where alpha is below 255. */ @@ -96,7 +113,7 @@ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* pre[i * 4 + 3] = (uint8_t)al; } const bool horiz = w != iw, vert = h != ih; - const Axis ax = coeffs(iw, w), ay = coeffs(ih, h); + const Axis ax = coeffs(iw, w, bilinear), ay = coeffs(ih, h, bilinear); /* the rows the vertical pass reads */ const int y_first = ay.bounds[0]; const int y_last = ay.bounds[(size_t)(h - 1) * 2] + ay.bounds[(size_t)(h - 1) * 2 + 1]; diff --git a/core/mm/imaging.h b/core/mm/imaging.h index 637f0e13..5457ace6 100644 --- a/core/mm/imaging.h +++ b/core/mm/imaging.h @@ -18,6 +18,8 @@ namespace mm { /* `src` resized to w x h. */ void resize_lanczos_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out); +/* The same with PIL's BILINEAR filter (a triangle of support 1, widened when shrinking). */ +void resize_bilinear_rgba(const FrameRGBA& src, int32_t w, int32_t h, FrameRGBA* out); /* `src` over an opaque white ground. */ void composite_white(const FrameRGBA& src, Frame* out); diff --git a/core/mm/media.cpp b/core/mm/media.cpp index 7ba705cd..8eb1e048 100644 --- a/core/mm/media.cpp +++ b/core/mm/media.cpp @@ -46,6 +46,8 @@ int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*, std::string* why) { return no_decoder(why); } +int h264_roundtrip(const Frame&, int32_t, Frame*, std::string* why) { return no_decoder(why); } +bool h264_roundtrip_available() { return false; } int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector*, std::string* why) { return no_decoder(why); @@ -677,6 +679,113 @@ int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_sample return RAD_OK; } +bool h264_roundtrip_available() { + return avcodec_find_encoder_by_name("libx264") && avcodec_find_decoder(AV_CODEC_ID_H264); +} + +/* PyAV's single-frame round trip: VideoFrame.from_ndarray(rgb24).reformat("yuv420p") (plain + * SWS_BILINEAR, BT.601 coefficients, limited-range output), libx264 with the given crf, then the + * decoded frame's to_ndarray("rgb24"), which to_rgb reproduces. */ +int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why) { + std::string w; + if (!why) why = &w; + const int W = in.w & ~1, H = in.h & ~1; + if (W <= 0 || H <= 0) { *why = "the picture is smaller than 2x2"; return RAD_E_INVAL; } + const AVCodec* enc = avcodec_find_encoder_by_name("libx264"); + const AVCodec* dcd = avcodec_find_decoder(AV_CODEC_ID_H264); + if (!enc || !dcd) { *why = "this libavcodec has no libx264 encoder or H.264 decoder"; return RAD_E_UNSUPPORTED; } + AVCodecContext* ec = avcodec_alloc_context3(enc); + AVCodecContext* dc = avcodec_alloc_context3(dcd); + AVFrame* yuv = av_frame_alloc(); + AVFrame* dec = av_frame_alloc(); + AVPacket* pkt = av_packet_alloc(); + SwsContext* sws = nullptr; + int st = RAD_OK; + auto fail = [&](const char* what, int e) { + *why = std::string(what) + (e < 0 ? " (" + averr(e) + ")" : std::string()); + st = e == AVERROR(ENOMEM) ? RAD_E_NOMEM : RAD_E_INVAL; + }; + bool got = false; + if (!ec || !dc || !yuv || !dec || !pkt) { + *why = "out of memory"; + st = RAD_E_NOMEM; + } else { + ec->width = W; + ec->height = H; + ec->pix_fmt = AV_PIX_FMT_YUV420P; + ec->time_base = AVRational{ 1, 1 }; + ec->framerate = AVRational{ 1, 1 }; + /* PyAV's codec defaults: as many threads as the machine has, splitting each frame into + * that many slices, which shapes the bitstream. */ + ec->thread_count = 0; + ec->thread_type = FF_THREAD_SLICE; + av_opt_set(ec->priv_data, "preset", "veryfast", 0); + av_opt_set(ec->priv_data, "crf", std::to_string(crf).c_str(), 0); + int e = avcodec_open2(ec, enc, nullptr); + if (e < 0) fail("opening libx264", e); + if (st == RAD_OK && (e = avcodec_open2(dc, dcd, nullptr)) < 0) fail("opening the H.264 decoder", e); + if (st == RAD_OK) { + yuv->format = AV_PIX_FMT_YUV420P; + yuv->width = W; + yuv->height = H; + if ((e = av_frame_get_buffer(yuv, 0)) < 0) fail("allocating a frame", e); + } + if (st == RAD_OK) { + sws = sws_getContext(W, H, AV_PIX_FMT_RGB24, W, H, AV_PIX_FMT_YUV420P, SWS_BILINEAR, + nullptr, nullptr, nullptr); + if (!sws) fail("no RGB to yuv420p conversion", 0); + } + if (st == RAD_OK) { + /* The source rows into a padded RGB frame: the scaler reads whole vectors past a tight + * row's end. */ + AVFrame* rgb = av_frame_alloc(); + if (!rgb) fail("out of memory", AVERROR(ENOMEM)); + else { + rgb->format = AV_PIX_FMT_RGB24; + rgb->width = W; + rgb->height = H; + if ((e = av_frame_get_buffer(rgb, 0)) < 0) fail("allocating a frame", e); + else { + for (int y = 0; y < H; ++y) + std::memcpy(rgb->data[0] + (ptrdiff_t)y * rgb->linesize[0], + in.rgb.data() + (size_t)y * in.w * 3, (size_t)W * 3); + if (sws_scale(sws, rgb->data, rgb->linesize, 0, H, yuv->data, yuv->linesize) != H) + fail("colour conversion failed", 0); + } + av_frame_free(&rgb); + } + } + /* Encode the frame and flush; every packet goes straight to the decoder. */ + for (int pass = 0; st == RAD_OK && pass < 2; ++pass) { + yuv->pts = 0; + if ((e = avcodec_send_frame(ec, pass == 0 ? yuv : nullptr)) < 0) { fail("encoding", e); break; } + while (st == RAD_OK && (e = avcodec_receive_packet(ec, pkt)) >= 0) { + if ((e = avcodec_send_packet(dc, pkt)) < 0) fail("decoding", e); + av_packet_unref(pkt); + } + if (st == RAD_OK && e != AVERROR(EAGAIN) && e != AVERROR_EOF) fail("encoding", e); + } + if (st == RAD_OK) avcodec_send_packet(dc, nullptr); + while (st == RAD_OK && (e = avcodec_receive_frame(dc, dec)) >= 0) { + if (!got) { + SwsContext* back = nullptr; + st = to_rgb(dec, &back, out, why); + sws_freeContext(back); + got = st == RAD_OK; + } + av_frame_unref(dec); + } + if (st == RAD_OK && !got) fail("the round trip decoded to no frame", 0); + } + sws_freeContext(sws); + av_packet_free(&pkt); + av_frame_free(&yuv); + av_frame_free(&dec); + avcodec_free_context(&ec); + avcodec_free_context(&dc); + return st; +} + #endif /* RAD_HAVE_FFMPEG */ } /* namespace mm */ diff --git a/core/mm/media.h b/core/mm/media.h index 8473accb..27ef41c6 100644 --- a/core/mm/media.h +++ b/core/mm/media.h @@ -77,5 +77,13 @@ int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* use int decode_audio(const uint8_t* data, size_t n, int32_t rate, int64_t max_samples, std::vector* out, std::string* why); +/* `in` encoded as a one-frame H.264 stream at constant quality `crf` (libx264, preset veryfast, + * yuv420p) and decoded back, as a video model's reference pipeline does to a conditioning + * picture so it carries the compression of the footage the model was trained on. An odd width + * or height loses its last column or row first. Needs libx264. */ +int h264_roundtrip(const Frame& in, int32_t crf, Frame* out, std::string* why); +/* Whether this build can run h264_roundtrip: its libavcodec has libx264. */ +bool h264_roundtrip_available(); + } /* namespace mm */ } /* namespace rad */ diff --git a/core/rad_core.h b/core/rad_core.h index a0dab54a..c552cf73 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -376,7 +376,8 @@ public: RadGeneratorDecl generator{}; struct GenStrings { std::string name, tmpl_text, tmpl_edit, tmpl_image, tmpl_image_sep, drop_prefix, - tmpl_transparent; + tmpl_transparent, default_negative; + bool has_default_negative = false; std::vector sigmas; } gen_str; bool is_generator() const { return generator.layout != 0; } @@ -392,6 +393,11 @@ public: struct VideoGenStrings { std::string name, tmpl; std::vector rungs; /* RadVideoGenDecl::rungs; the declaration's pointer is null */ + std::vector refine_rungs; + std::string default_negative; + /* RadVideoGenDecl::decoders, one name each, and their largest frames (0: max_area). */ + std::vector decoders; + std::vector decoder_max_area; } vgen_str; bool is_video_generator() const { return video_gen.max_lanes != 0; } /* Driven by passes, not token steps: any generator. */ @@ -740,8 +746,9 @@ struct Config { /* --kv-cache-dtype bf16|fp8|fp8_v4|k6_v4. fp8 is an E4M3 cache with per-(sequence, head) * descales; it halves the per-token cost, most of the KV pool at production context. fp8_v4 * keeps K as E4M3 and V as int4 in groups of 32, k6_v4 also K as int6 (RadBuildCtx::kv_quant), - * served only where the plugin says so. Each changes the model's output slightly, so it is explicit and bf16 is the - * default. No "auto": it would always resolve to bf16 and only add another name. */ + * served only where the plugin says so. Each changes the model's output slightly, so it is + * explicit and bf16 is the default. No "auto": it would always resolve to bf16 and only add + * another name. */ std::string kv_cache_dtype = "bf16"; int64_t host_pool_mib = 0; int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index abc5443f..da0d20ce 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -113,8 +113,15 @@ int Ctx::prepare() { RAD_TRY(bind_routing()); RAD_TRY(bind_profiling()); /* Recorded passes need a recording backend, and are off whenever every issue must be seen: - * per-op profile, oracle. */ - tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_; + * per-op profile, oracle, and a calibration tap. A `gram_accum` sums across passes while its + * plugin counts the rows it has summed in step and writes the Grams once a token target is + * reached; a played pass reissues the accumulation without calling step, so the files would + * hold more rows than their header says and be written late. */ + const bool taps = std::any_of(program_->ops.begin(), program_->ops.end(), + [](const OpInfo& o) { return o.op == "gram_accum"; }); + tape_on_ = record_passes_ && tape_supported() && !profiling_ && !oracle_ && !taps; + if (taps && record_passes_ && tape_supported() && rank_ == 0) + RAD_INFO("recorded passes: off, the program accumulates calibration Grams (gram_accum)"); return RAD_OK; } diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 9ef3a898..66daed98 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -205,6 +205,8 @@ public: /* ---------------------------------------------------------- run-phase queries */ const RadBatch* batch() const { return batch_; } int rank() const { return rank_; } + /* Whether repeated passes are recorded and played back (prepare() says when they are not). */ + bool records_passes() const { return tape_on_; } int world_size() const { return world_size_; } RadStream stream() const { return stream_; } Program* program() const { return program_; } diff --git a/core/sched/metrics.h b/core/sched/metrics.h index ce0218ed..801cec72 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -51,19 +51,10 @@ struct SchedMetrics { int64_t step_ns = 0; int64_t step_ns_decode = 0; - /* The single-sequence decode floor, nanoseconds; 0 until a window of eligible steps fills. - * A min over WINDOW MEANS of single-sequence decode steps (see DecodeFloor), not over raw - * brackets -- a raw min latches a degenerate bracket forever. Single-sequence on purpose: a - * decode step at eight sequences is a different measurement, so keying the floor to one row - * keeps a batch arriving from being misread as drift. Scheduler::step_finished feeds DecodeFloor. */ + /* The single-sequence decode floor and the most recent window, nanoseconds: both window means + * of single-sequence decode steps (DecodeFloor), 0 until a gated window completes. A decode + * step at more sequences is a different measurement and does not count. */ int64_t step_ns_decode_best = 0; - - /* The most recent completed window mean of single-sequence decode steps, nanoseconds; 0 until - * the first gated window completes. The advisory's OTHER side: best() is how fast the engine - * has ever been, recent() is how fast it is now, and both are window means of the same stream - * at the same size -- so they cannot disagree by order statistics the way the engine's floor - * disagreed with the browser's per-poll min (7.7% phantom drift on a flat lane, 2026-10-18). - * Scheduler::step_finished records it. */ int64_t step_ns_decode_recent = 0; /* Per KV group. `name` points into the Program, which outlives any scrape. */ @@ -147,84 +138,55 @@ struct SchedMetrics { }; -/* Estimator for the single-sequence decode floor (SchedMetrics::step_ns_decode_best). - * - * A min over RAW step brackets is unbounded below: a decode step issued ahead behind a step with - * long host work (a prefill chunk, or a decode step that saves a KV checkpoint) has its forward - * pass finished before its own bracket opens, so the bracket holds only readback and commit -- - * about a millisecond, no GPU work. A min latches that degenerate on the first occurrence and - * never recovers. Measured live 2026-10-18: floor 1.34 ms against a 15.70 ms mean, after which - * the dashboard's restart advice read "heavily drifted, pays back fast" on a healthy engine -- - * a systematically wrong advisory, worse than none, because it recommends a restart that cannot - * help. - * - * The fix mirrors the construction the dashboard already proves clean on this lane: a min over - * WINDOW MEANS, not over raw samples. Each full window of single-sequence decode steps - * contributes one mean; a degenerate is diluted by the honest steps sharing its window, so the - * floor tracks the real floor. Two biases on that floor partially cancel: a window MEAN sits - * above the true floor (it averages, so it cannot reach a lone fast step), while min-over-windows - * picks the window with the most degenerates and pulls back down. A simulation of the live lane - * (real ~15.9 ms, true floor ~14.4 ms, degenerate ~1.34 ms) puts the estimate at 14.3 ms median - * at the observed ~1.4% degenerate rate, worst case ~13.6 ms -- within a few percent of the true - * floor, and never the 12x latch of the raw min. The residual can sit slightly BELOW the true - * floor (a degenerate-heavy window), which mildly OVER-reports drift; it is bounded and small, - * not the unbounded latch. kWindow is a structural count of samples to average, not a magic - * threshold a real step could fall below. Scheduler::step_finished feeds it one update per - * single-sequence decode step. */ +/* Estimator for the single-sequence decode floor (SchedMetrics::step_ns_decode_best): a min over + * window means, not over raw step brackets. A decode step issued ahead behind a step with long + * host work (a prefill chunk, a KV checkpoint save) has its forward pass finished before its own + * bracket opens, so the bracket holds only readback and commit, about a tenth of a real step; a + * raw min would latch that forever. Such brackets are rejected before they enter a window, and the + * window mean dilutes what remains. */ struct DecodeFloor { - /* Single-sequence decode steps averaged into one floor candidate. 32 approximates the number - * of decode steps the dashboard's 500 ms poll spans at this lane's step time, so the engine - * floor and the page's own c1 floor are computed over comparable windows. */ + /* Steps averaged into one floor candidate: about what the dashboard's 500 ms poll spans at a + * single-sequence step, so the engine's floor and the page's are over comparable windows. */ static constexpr int kWindow = 32; + static constexpr int64_t kHorizon = 8 * kWindow; void update(int64_t ns) { - /* Reject degenerate brackets BEFORE they enter a window. A decode step issued ahead behind - * a long host commit (a prefill chunk, or a KV checkpoint every 256 tokens) brackets at - * ~9% of a real step; real single-sequence steps bracket at ~96%. The populations are ~10x - * apart, so any threshold between them separates them -- 0.5 is the midpoint of that gap, - * not a value tuned to one distribution. Filtering at the STEP level is essential: at the - * observed ~1.4% rate a degenerate dilutes inside a 32-step window to a mean of ~0.91x, - * which no window-level threshold would catch, and a min over hundreds of windows then - * reliably lands on a degenerate-heavy window ~10% below the true floor. - * No rejection until a window's worth of samples has been accepted, so the running mean is - * never bootstrapped from a degenerate. */ - if (accepted_ >= kWindow && ns * 2 < mean_) return; - ++accepted_; - mean_ += (ns - mean_) / (double)accepted_; + /* A degenerate bracket is ~0.09 of a real step and a real one ~0.96 of the mean, so half + * the reference separates them. The reference is a running mean over every step, the + * rejected ones included, with a horizon of kHorizon steps: degenerates are rare enough to + * barely move it, and when the real step gets faster (a slow warm-up, a shorter context) + * it follows instead of rejecting every later step. No rejection until a window's worth + * of samples has been seen. */ + ++seen_; + mean_ += (ns - mean_) / (double)(seen_ < kHorizon ? seen_ : kHorizon); + if (seen_ > kWindow && ns * 2 < mean_) return; sum_ += ns; if (++count_ < kWindow) return; const int64_t mean = sum_ / count_; - /* The FIRST window is recorded by neither side. The rejection gate needs a window's worth - * of accepted samples before it can judge one, so the first window is by construction - * un-gated and can carry degenerates; recording it would let the floor latch a value the - * engine can no longer reach -- the same artifact the gate exists to remove, smuggled in - * through bootstrap. Measured: at a 5% degenerate rate the un-gated first window put the - * floor ~2% below the true floor and it stuck there forever. */ + /* The first window ran before the gate could judge and may carry degenerates, so it is + * recorded by neither side. */ if (warmed_) { if (best_ == 0 || mean < best_) best_ = mean; - recent_ = mean; /* most recent completed window, same size as best_ */ + recent_ = mean; } warmed_ = true; sum_ = 0; count_ = 0; } - /* The floor: the fastest window mean ever seen. A restart is priced against this. */ + /* The fastest window mean seen. */ int64_t best() const { return best_; } - /* The CURRENT speed: the most recent completed window mean, from the SAME stream and window - * size as best(). The advisory compares best() against recent() -- both window means of one - * population -- so the two sides cannot disagree by order statistics the way the engine's - * floor disagreed with the browser's per-poll min (a 7.7% phantom gap on a flat lane, - * 2026-10-18). 0 until the first window completes; the page must not divide by it. */ + /* The most recent completed window mean, from the same stream and window size as best(); + * 0 until the first gated window completes. */ int64_t recent() const { return recent_; } private: - int64_t sum_ = 0; - int count_ = 0; /* samples in the window being accumulated */ - int64_t best_ = 0; - int64_t recent_ = 0; - bool warmed_ = 0; /* false until one window has completed (the un-gated bootstrap) */ - int64_t accepted_ = 0; /* samples accepted across all windows (rejection gate's support) */ - double mean_ = 0.0; /* running mean of ACCEPTED steps -- the rejection reference */ + int64_t sum_ = 0; + int count_ = 0; /* samples in the window being accumulated */ + int64_t best_ = 0; + int64_t recent_ = 0; + bool warmed_ = false; /* one window has completed */ + int64_t seen_ = 0; /* samples seen, rejected ones included */ + double mean_ = 0.0; /* the rejection reference */ }; } /* namespace rad */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index ffb88f74..b2fac3e8 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -1599,7 +1599,10 @@ const RadBatch* Scheduler::step() { /* ------------------------------------------------------------------ media */ bool Scheduler::prefill_continues() const { std::lock_guard lk(mu_); - if (stage_rows_ <= 0) return false; + /* Only the step being released has a plan to read. Between a commit and the next step (an + * encoder pass is prepared there) `plan_` is the committed step's, whose requests in_step() no + * longer holds: a cancel and reap may have released one (#127). */ + if (stage_rows_ <= 0 || !step_open_) return false; /* The next step is held to decode rows (--prefill-interleave): experts staged for a chunk now * would be dropped by that step. */ if (interleave_left_ > 0) return false; @@ -2010,13 +2013,8 @@ void Scheduler::step_finished() { m_.step_ns += ns; if (plan_.phase == RAD_PHASE_DECODE) { m_.step_ns_decode += ns; - /* The single-sequence floor, keyed to the concurrency of THIS step (plan_.n_seq_decode is - * the row count that was just timed, not a later snapshot). A mixed step is excluded by the - * phase gate even when it carries one decode row: its lone row shares the step with a - * prefill chunk and is not the mechanical floor. The estimator is a min over WINDOW MEANS, - * not raw brackets: a decode step issued ahead behind a long host commit has no GPU work - * in its bracket, and a raw min latches that degenerate forever; averaging a window of - * single-row steps first dilutes it. See rad::DecodeFloor. */ + /* The single-sequence floor over the step just timed (rad::DecodeFloor). A mixed step + * never counts: its decode row shares the step with a prefill chunk. */ if (plan_.n_seq_decode == 1) { decode_floor_.update(ns); m_.step_ns_decode_best = decode_floor_.best(); diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 803aab0e..06aa8711 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -604,9 +604,7 @@ private: * covered, both decayed with the same time constant, so their ratio is tokens over time. */ double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0; bool step_open_ = false; - /* Estimator for the single-sequence decode floor (see rad::DecodeFloor). Replaces a raw min - * over step brackets, which latched a degenerate bracket forever (live defect 2026-10-18: - * 1.16 ms against a 15.55 ms mean). step_finished feeds it each single-sequence decode step. */ + /* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */ DecodeFloor decode_floor_; /* arrival; mu_ held */ diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 68ef685b..eb52ea51 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -125,10 +125,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) { o["model"] = opt_.model_id; o["version"] = opt_.version; o["uptime_s"] = unix_now() - started_at_; - /* How long this process took to come up, measured on this machine. Raw figure: a restart's - * real cost, for whoever is deciding whether one is worth it. 0 before the server listens. - * The page no longer consumes it -- see the note on the decode-step detail line for why the - * payback arithmetic that used to live there was removed. */ + /* Seconds this process took to come up, the cost of a restart; 0 before the server listens. */ o["startup_s"] = startup_s_; o["in_flight"] = in_flight_.load(std::memory_order_relaxed); o["queue_cap"] = queue_depth_; @@ -1363,31 +1360,18 @@ for (const k of METRICS) { * is for is the variation, and the number above it already states the level -- scaled from zero * every steady state is a flat line on the floor. No variation draws down the middle. * - * THE ENDS OF THAT RANGE ARE PERCENTILES, not the extremes. On a min/max axis one rare spike - * owns the whole box and the typical variation is squeezed into a couple of pixels: measured over - * real /stats samples, prefill sits at zero on a third of polls and spikes past 4,000 on the rest, - * which leaves its middle band 0.1px of the 15px available -- a flat line for a metric that is - * anything but. Taking the 5th and 95th percentiles and clamping to them gives the ordinary - * movement the height it was being denied (the same samples' middle band rises 1.2x to 3.9x - * depending on the metric). The cost is stated rather than hidden: a spike beyond the 95th now - * draws pinned to the top of the box instead of towering over the line, so the box shows how the - * metric has been behaving and not how bad its worst poll was. The number above still carries the - * level, and the detail line still carries the extremes. - * - * THE INSET IS ONE UNIT, not two and three. The stroke is 1.25 units wide, so a half-unit of - * clearance keeps it off the edge of the box; the extra it used to leave was a fifth of the - * height spent on nothing, and on a 17px box that is the difference between a line that moves - * and one that merely shifts. */ + * The ends of the range are the 5th and 95th percentiles, not the extremes: on a min/max axis one + * rare spike owns the box and the typical variation is squeezed into a pixel. A spike past the + * 95th draws pinned to the top; the number above carries the level and the detail line the + * extremes. The stroke is 1.25 units wide, so a one-unit inset keeps it off the edge. */ function spark(key, vals) { const s = M[key], w = 200, h = 22; if (vals.length < 3) { s.line.setAttribute("d", ""); return; } const q = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.floor(p * (sorted.length - 1)))]; const sorted = [...vals].sort((a, b) => a - b); let lo = q(sorted, 0.05), hi = q(sorted, 0.95); - /* WHEN THE PERCENTILES COLLAPSE, fall back to the extremes. If nine tenths of the window holds - * one value, the 5th and 95th land on it and carry nothing -- and a metric that is constant - * apart from rare spikes has those spikes as its ONLY news, so pinning them outside the axis - * would draw a flat line where the old axis at least showed them. */ + /* A window that is one value apart from rare spikes puts both percentiles on that value; the + * extremes then serve, so the spikes still show. */ if (!(hi > lo)) { lo = sorted[0]; hi = sorted[sorted.length - 1]; } const span = hi - lo; const dx = w / (vals.length - 1); @@ -1686,35 +1670,16 @@ function renderRequests(list, poolTokens) { let prev = null, prevAt = 0, bars = [], devs = [], layerBars = []; let lastStepMs = null, lastTps = null; -/* THE SINGLE-STREAM FLOOR and the engine's most recent window, shown as two numbers and - * interpreted by nobody. The engine records the fastest single-sequence decode window it has - * measured (step_ns_decode_best) and its most recent one (step_ns_decode_recent); the page states - * both and draws no conclusion. Neither is asked of a human: a typed ruler goes stale and - * mis-advises silently, and a browser meter sees only the steps taken while this tab is open. On - * an engine too old to emit the floor, the page falls back to the fastest single-stream step this - * tab has seen. - * - * THERE IS DELIBERATELY NO RESTART ADVICE HERE, and it was not never-built -- it was built, - * deployed, measured, and removed the same day (2026-10-18). It compared the floor against the - * recent window, called the gap drift, and priced a payback from startup_s. The gap is not drift. - * On a HEALTHY shared lane the floor sat flat at 14.79 ms while the recent window moved between - * 15.2 and 16.5 ms -- 3% to 11% -- tracking what else the lane was doing: it froze when the lane - * went idle and ROSE on a fresh short request, so it was neither context length nor engine age. - * The payback formula assumes a restart's improvement is permanent, so acting on it pays the 49 s - * bringup and re-drifts within minutes; the line was telling the operator to restart every 12-19 - * minutes forever, for a gain that was never there. What best-vs-recent actually measures is the - * distance between the lane's most favorable moment and its typical one. - * - * A verdict could go back here IF someone first observes the thing none of today's data shows: - * step time rising with ENGINE AGE and STAYING up. Every excursion seen so far was load. The - * full chain, including the estimator that survives this, is in patches/CHANGELOG-SOURCE.md. */ +/* The single-stream floor and the engine's most recent window, shown as two numbers with no + * verdict. The engine records the fastest single-sequence decode window it has measured + * (step_ns_decode_best) and its most recent one (step_ns_decode_recent). Their gap is not engine + * drift: on a healthy lane the recent window moves 3-11% above a flat floor with whatever else the + * lane is doing, so a restart priced against it would not pay back. Until the engine's first + * window completes, the fastest single-stream step this tab has seen stands in. */ let c1hist = []; const C1CAP = 7200; /* an hour at 2 polls/s of single-stream samples */ -let bestEver = 0; /* the best engine floor ever seen here, across restarts */ -try { bestEver = parseFloat(localStorage.getItem("radiance.c1best")) || 0; } catch (e) {} const bestAt = {}; /* fastest step seen at each concurrency, this process */ - function update(s, dt) { $("ver").textContent = s.version + " · up " + dur(s.uptime_s); @@ -1734,35 +1699,21 @@ function update(s, dt) { M.step.u.textContent = st.u; setMetric("step", lastStepMs, st.n); - /* THE FLOOR, single-stream on both sides of the engine's own measurement. The floor is a - * single-sequence window, so the engine keys it to one row deliberately: a decode step at eight - * sequences is a different measurement, and reading it against a single-sequence floor would - * report a batch arriving as a slowdown. */ + /* Single-stream steps only: the floor is a single-sequence window, and a batched step read + * against it would report a batch arriving as a slowdown. */ if (s.running === 1 && stepMs != null) { c1hist.push(stepMs); if (c1hist.length > C1CAP) c1hist.shift(); } const engBestMs = s.step_ns_decode_best > 0 ? s.step_ns_decode_best / 1e6 : 0; const engRecentMs = s.step_ns_decode_recent > 0 ? s.step_ns_decode_recent / 1e6 : 0; - if (engBestMs > 0 && (bestEver === 0 || engBestMs < bestEver)) { - bestEver = engBestMs; - try { localStorage.setItem("radiance.c1best", String(bestEver)); } catch (e) {} - } const floorMs = engBestMs > 0 ? engBestMs : (c1hist.length ? Math.min(...c1hist) : 0); - /* The two engine figures, stated plainly. Painted every poll: without a verdict there is - * nothing for a fast repaint to make unactionable, and `recent` only moves when a window of 32 - * single-sequence steps completes anyway. */ let det = ""; if (floorMs > 0) { det = "best " + floorMs.toFixed(2) + "ms"; if (engRecentMs > 0) det += " · recent " + engRecentMs.toFixed(2) + "ms"; } - /* THE STEP AS A PERCENTAGE OF THE FASTEST THIS PROCESS HAS DONE AT THIS CONCURRENCY: ~99% is the fastest the lane has done, anything slower a percentage of it. Keyed by - * concurrency on purpose: a c8 step read against the single-stream floor would report the batch - * arriving as a slowdown -- the mistake that took the old drift line out. Raw ratio, no - * threshold, no colour: the number is the statement. Capped at ~99 (shown with a tilde): `now` is a ~500 ms poll mean while - * `best` is a 32-step window mean, so a fast stretch shorter than a window can read faster than the - * recorded floor. That is "at your best", not a new record -- the engine only ratchets the floor on a - * completed 32-step window, and a sub-window blip is not one. The cap is 99, not 100: a 500 ms window that briefly beats the - * floor is not a sustained record, and 100% would claim a floor the window cannot confirm -- it - * would read as a bug. ~99% says "at your best" without overclaiming. */ + /* The step as a percentage of the fastest at this concurrency (`@cN` above one). `now` is a + * ~500 ms poll mean and `best` a 32-step window mean, so a short fast stretch can beat the + * floor; the figure is capped at 99 and shown as ~99, "at the best", rather than claiming a + * record the window cannot confirm. */ if (s.running > 0 && lastStepMs != null) { const k = s.running; if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs; diff --git a/core/server/iface.h b/core/server/iface.h index ac1d9968..e492463a 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -127,11 +127,8 @@ struct SchedMetrics { * a decode step regardless of load. */ int64_t step_ns = 0; int64_t step_ns_decode = 0; - /* The fastest single-sequence decode step this process has measured, nanoseconds; 0 until one - * runs. The dashboard reads this instead of asking a human to type a ruler (see the same field - * on rad::SchedMetrics, where it is recorded). */ + /* The single-sequence decode floor and most recent window (rad::SchedMetrics). */ int64_t step_ns_decode_best = 0; - /* The most recent completed single-sequence decode window mean; see SchedMetrics. */ int64_t step_ns_decode_recent = 0; }; @@ -589,7 +586,19 @@ struct ImageGenInfo { /* The model samples on a schedule of its own and takes no step count (a distilled model). */ bool fixed_schedule = false; int64_t fixed_steps = 0; + /* Guidance in the model card's terms: with `cfg_original` the scale s means cond + s (cond - + * uncond), off at 0, and the core runs s + 1; otherwise uncond + s (cond - uncond), off at 1. */ double default_cfg = 1.0; + bool cfg_original = false; + /* The negative prompt a guided request gets when it names none; without one it must. */ + bool has_default_negative = false; + std::string default_negative; + /* The pictures are not read by the conditioning network: they go to the generator's own + * encoder only (RAD_GEN_LAYOUT_JOINT_STEP). */ + bool refs_encoder_only = false; + /* A reference picture is shrunk to `ref_area` only when larger, then centre-cropped to the + * size multiple; otherwise resized to `ref_area` at its aspect. */ + bool ref_shrink_only = false; }; class IImageGen { @@ -650,6 +659,22 @@ struct VideoGenInfo { /* A latent upscaler: the largest factor (0: none) and the full-size evaluations by default. */ double upscale_max = 0.0; int64_t upscale_refine = 0; + /* `steps` counts model evaluations rather than sigma grid points (RadVideoGenDecl form 1). */ + bool step_evals = false; + /* Guidance (RadVideoGenDecl::guidance): the terms a request may name, their defaults and the + * negative prompt a guided request gets when it names none. */ + bool guidance = false; + double guidance_default[8] = {}; + std::string default_negative; + /* Image to video: a first frame is taken, after an H.264 round trip at image_crf when > 0. */ + bool image_cond = false; + int32_t image_crf = 0; + /* A length head: a request that names no length gets the one the model predicts. */ + bool length_head = false; + /* The decoders a request may name, the default first, and each one's largest frame in pixels + * (RadVideoGenDecl::decoders); empty for a model with one. */ + std::vector decoders; + std::vector decoder_max_area; }; class IVideoGen { diff --git a/core/server/images.cpp b/core/server/images.cpp index 8d953c5f..f8c888ab 100644 --- a/core/server/images.cpp +++ b/core/server/images.cpp @@ -9,8 +9,10 @@ * repainted where the mask is transparent; the rest is restored exactly after decoding. * * Extensions, under vLLM-Omni's names: `seed`, `negative_prompt` with `true_cfg_scale` - * (guidance), `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule - * (distilled) model accepts only its own step count. + * (guidance, in the model card's terms; `guidance_scale` is the same field under diffusers' name), + * `num_inference_steps`, and `width` / `height` instead of `size`. A fixed-schedule (distilled) + * model accepts only its own step count. A model whose card guides by default does so with its + * own negative prompt unless the request names one or turns guidance off. * * Refused: `response_format: url`, since no image is stored to serve later; only b64_json. * @@ -77,7 +79,7 @@ json form_value(const std::string& key, const std::string& v) { if (e && *e == 0 && !v.empty()) return json(x); return json(v); } - if (key == "true_cfg_scale") { + if (key == "true_cfg_scale" || key == "guidance_scale") { char* e = nullptr; const double x = std::strtod(v.c_str(), &e); if (e && *e == 0 && !v.empty()) return json(x); @@ -107,18 +109,34 @@ std::string replace_all(std::string s, const std::string& what, const std::strin } /* A picture as the generator's encoder reads it: each channel u -> 2 * (u / 255) - 1 in f32, then - * bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). */ -gen::Pixels to_pixels(const mm::FrameRGBA& f) { + * bf16 (VaeImageProcessor's preprocess, cast to the VAE's dtype). An RGB model reads the colour + * channels and not the alpha, as PIL's convert("RGB") drops it. */ +gen::Pixels to_pixels(const mm::FrameRGBA& f, int ch) { gen::Pixels p; p.w = f.w; p.h = f.h; - p.ch = 4; - p.bf16.resize(f.rgba.size()); - for (size_t i = 0; i < f.rgba.size(); ++i) - p.bf16[i] = rad_f32_to_bf16(2.0f * ((float)f.rgba[i] / 255.0f) - 1.0f); + p.ch = ch; + p.bf16.resize((size_t)f.w * f.h * ch); + for (size_t px = 0; px < (size_t)f.w * f.h; ++px) + for (int c = 0; c < ch; ++c) + p.bf16[px * ch + c] = + rad_f32_to_bf16(2.0f * ((float)f.rgba[px * 4 + c] / 255.0f) - 1.0f); return p; } +/* The centred w x h window of a picture (diffusers' resize_mode "crop" after its resize). */ +mm::FrameRGBA crop_centre(const mm::FrameRGBA& f, int32_t w, int32_t h) { + mm::FrameRGBA o; + o.w = w; + o.h = h; + o.rgba.resize((size_t)w * h * 4); + const int32_t x0 = (f.w - w) / 2, y0 = (f.h - h) / 2; + for (int32_t y = 0; y < h; ++y) + std::memcpy(&o.rgba[(size_t)y * w * 4], &f.rgba[((size_t)(y0 + y) * f.w + x0) * 4], + (size_t)w * 4); + return o; +} + /* The decoded RGBA flattened on white (no alpha), for a jpeg or an opaque background. */ std::vector on_white(const std::vector& rgba, int32_t w, int32_t h) { mm::FrameRGBA f; @@ -216,6 +234,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { "prompt", "model", "n", "size", "quality", "background", "output_format", "output_compression", "response_format", "stream", "partial_images", "moderation", "style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale", + "guidance_scale", "num_inference_steps", "width", "height", }; for (auto it = body.begin(); it != body.end(); ++it) { @@ -274,6 +293,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { if (r.background == "transparent" && r.format == "jpeg") return error_response(err_bad("background", "jpeg has no transparency; ask for png or " "webp"), req.peer); + if (r.background == "transparent" && info.pixel_channels < 4) + return error_response(err_bad("background", "this model makes opaque images"), req.peer); if (num("output_compression", 0, 100, &v) < 0) return error_response(err_bad("output_compression", "expected an integer in 0..100"), req.peer); @@ -323,21 +344,35 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { } if (str("negative_prompt", &r.negative) < 0) return error_response(err_bad("negative_prompt", "expected a string"), req.peer); - if (body.contains("true_cfg_scale") && !body["true_cfg_scale"].is_null()) { - if (!body["true_cfg_scale"].is_number()) - return error_response(err_bad("true_cfg_scale", "expected a number"), req.peer); - r.cfg = body["true_cfg_scale"].get(); - if (!(r.cfg >= 1.0 && r.cfg <= 30.0)) - return error_response(err_bad("true_cfg_scale", "expected a number in 1..30"), - req.peer); + /* The scale in the model card's terms: off at 0 for a card that states it as + * cond + s (cond - uncond), at 1 for uncond + s (cond - uncond). */ + const double cfg_off = info.cfg_original ? 0.0 : 1.0; + const char* cfg_key = body.contains("guidance_scale") && !body["guidance_scale"].is_null() + ? "guidance_scale" : "true_cfg_scale"; + const bool cfg_given = body.contains(cfg_key) && !body[cfg_key].is_null(); + if (cfg_given && body.contains("true_cfg_scale") && body.contains("guidance_scale") && + !body["true_cfg_scale"].is_null()) + return error_response(err_bad("guidance_scale", "true_cfg_scale and guidance_scale are " + "the same field; name one"), req.peer); + r.cfg = info.default_cfg; + if (cfg_given) { + if (!body[cfg_key].is_number()) + return error_response(err_bad(cfg_key, "expected a number"), req.peer); + r.cfg = body[cfg_key].get(); + if (!(r.cfg >= cfg_off && r.cfg <= 30.0)) + return error_response(err_bad(cfg_key, "expected a number in " + + std::string(cfg_off > 0 ? "1" : "0") + + "..30"), req.peer); } - /* Guidance needs a scale above one and a negative prompt (empty becomes " "), as in the - * reference pipeline. */ - r.has_neg = r.cfg > 1.0 && body.contains("negative_prompt"); - if (r.has_neg && r.negative.empty()) r.negative = " "; - if (r.cfg > 1.0 && !r.has_neg) - return error_response(err_bad("true_cfg_scale", "guidance needs a negative_prompt"), - req.peer); + /* Guidance needs a scale past its off value and a negative prompt: the request's (empty + * becomes " ", as in the reference pipeline), or the model's own. */ + const bool guided = r.cfg > cfg_off; + const bool named_neg = body.contains("negative_prompt") && !body["negative_prompt"].is_null(); + r.has_neg = guided && (named_neg || info.has_default_negative); + if (r.has_neg && !named_neg) r.negative = info.default_negative; + else if (r.has_neg && r.negative.empty()) r.negative = " "; + if (guided && !r.has_neg) + return error_response(err_bad(cfg_key, "guidance needs a negative_prompt"), req.peer); /* ---- the pictures */ if (edit) { @@ -372,7 +407,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { * image generated without transparency has only decoder noise in its alpha. */ if (r.background == "auto") { bool alpha = false; - if (r.format != "jpeg") + if (r.format != "jpeg" && info.pixel_channels >= 4) for (const mm::FrameRGBA& f : r.images) for (size_t i = 3; i < f.rgba.size() && !alpha; i += 4) alpha = f.rgba[i] < kTransparentBelow; @@ -437,17 +472,40 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { g->steps = r.steps; g->seed = r.seed; g->previews = r.previews; - g->cfg = (float)r.cfg; + /* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is + * that at s + 1. */ + g->cfg = (float)(info.cfg_original ? r.cfg + 1.0 : r.cfg); g->has_neg = r.has_neg; g->ticket = std::make_shared(); std::vector> items; + const int pch = (int)info.pixel_channels; for (const mm::FrameRGBA& f : r.images) { int32_t rw = 0, rh = 0; - dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh); mm::FrameRGBA rs; - mm::resize_lanczos_rgba(f, rw, rh, &rs); - g->refs.push_back(to_pixels(rs)); + if (info.ref_shrink_only) { + /* Shrunk to the reference area only when larger, then cut to the size multiple. */ + const double area = (double)f.w * f.h; + if (area > (double)info.ref_area) { + const double k = std::sqrt((double)info.ref_area / area); + rw = std::max(1, (int32_t)(f.w * k)); + rh = std::max(1, (int32_t)(f.h * k)); + mm::resize_lanczos_rgba(f, rw, rh, &rs); + } else { + rs = f; + } + const int32_t cw = rs.w / mult * mult, ch = rs.h / mult * mult; + if (cw <= 0 || ch <= 0) + return error_response(err_bad("image", "a picture must be at least " + + std::to_string(mult) + " pixels a side"), + req.peer); + if (cw != rs.w || ch != rs.h) rs = crop_centre(rs, cw, ch); + } else { + dims_for((double)info.ref_area, (double)f.w / (double)f.h, mult, &rw, &rh); + mm::resize_lanczos_rgba(f, rw, rh, &rs); + } + g->refs.push_back(to_pixels(rs, pch)); + if (info.refs_encoder_only) continue; mm::Frame rgb; mm::composite_white(rs, &rgb); std::shared_ptr it; @@ -465,7 +523,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { mm::resize_lanczos_rgba(r.images[0], r.w, r.h, &src); mm::resize_lanczos_rgba(r.mask, r.w, r.h, &msk); g->inpaint = true; - g->inp_src = to_pixels(src); + g->inp_src = to_pixels(src, pch); const int32_t lw = r.w / (int32_t)ls, lh = r.h / (int32_t)ls; g->inp_mask.assign((size_t)lw * lh, 0.0f); keep_px.assign((size_t)r.w * r.h, 0); @@ -567,12 +625,15 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { auto encode = [fmt, comp, keep_px, src_px, flatten](gen::Image& im, std::string* b64, std::string* why) -> int { std::vector& px = im.px; + const size_t ch = (size_t)im.ch; if (!keep_px.empty() && !im.preview) for (size_t i = 0; i < keep_px.size(); ++i) - if (keep_px[i]) std::memcpy(&px[i * 4], &src_px[i * 4], 4); + if (keep_px[i]) std::memcpy(&px[i * ch], &src_px[i * 4], ch); std::vector file; int s; - if (flatten) { + if (ch == 3) { + s = mm::encode_image(px.data(), im.w, im.h, 3, fmt, comp, &file, why); + } else if (flatten) { const std::vector rgb = on_white(px, im.w, im.h); s = mm::encode_image(rgb.data(), im.w, im.h, 3, fmt, comp, &file, why); } else { diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 692368e4..85477067 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace rad { @@ -3854,9 +3855,17 @@ json message_item(const std::string& id, const std::string& text, const char* st { "content", text.empty() && std::strcmp(status, "in_progress") == 0 ? json::array() : json::array({ text_part(text) }) } }; } -json call_item(const ToolCall& tc, const char* status) { - return json{ { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id }, - { "name", tc.name }, { "arguments", tc.arguments }, { "status", status } }; +/* A call to a flattened namespace tool reports its namespace and its own name apart, as the + * Responses API's function_call item does. */ +json call_item(const OaiRequest& r, const ToolCall& tc, const char* status) { + json it = { { "id", fc_id(tc.id) }, { "type", "function_call" }, { "call_id", tc.id }, + { "name", tc.name }, { "arguments", tc.arguments }, { "status", status } }; + auto ns = r.tool_namespace.find(tc.name); + if (ns != r.tool_namespace.end()) { + it["namespace"] = ns->second.first; + it["name"] = ns->second.second; + } + return it; } /* The response object, around its output items, with the request fields it echoes. */ @@ -3880,7 +3889,8 @@ json response_object(const OaiRequest& r, const char* status, const json& output } /* namespace */ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat, - std::string* echo, ApiError* err) { + std::string* echo, ApiError* err, + std::map>* ns) { json b; RAD_TRY(parse_request_object(body, lim, &b, err)); auto prev = b.find("previous_response_id"); @@ -3983,11 +3993,14 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string } msgs.push_back(json{ { "role", role }, { "content", parts } }); } else if (type == "function_call") { - std::string id, name, args = "{}"; + std::string id, name, args = "{}", space; if (!member_str(item, "call_id", "input[].call_id", &id, err) || !member_str(item, "name", "input[].name", &name, err) || - !member_str(item, "arguments", "input[].arguments", &args, err)) + !member_str(item, "arguments", "input[].arguments", &args, err) || + !member_str(item, "namespace", "input[].namespace", &space, err)) return RAD_E_INVAL; + /* A namespaced call, under the name its tool was flattened to below. */ + if (!space.empty()) name = space + "__" + name; json call = { { "id", id }, { "type", "function" }, { "function", { { "name", name }, { "arguments", args } } } }; json* prev = last_assistant(); @@ -4040,34 +4053,78 @@ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string } o["messages"] = std::move(msgs); - /* Function tools only. Built-in tools (web search, file search, computer use) and freeform - * custom tools have no chat-completions counterpart and are left out. */ + /* Function tools, and the function tools a namespace groups (Codex sends every MCP server's + * tools that way), flattened to "__": the chat path has one flat list, and + * the reply's function_call items report the two apart again (OaiRequest::tool_namespace). + * Built-in tools (web search, file search, computer use) and freeform custom tools have no + * chat-completions counterpart and are left out. */ json echo_tools = json::array(); auto tit = b.find("tools"); if (tit != b.end() && tit->is_array()) { json tools = json::array(); + std::set names; + auto add = [&](const json& t, const std::string& space) -> int { + std::string name; + if (!member_str(t, "name", space.empty() ? "tools[].name" : "tools[].tools[].name", + &name, err)) + return RAD_E_INVAL; + const std::string flat = space.empty() ? name : space + "__" + name; + if (!names.insert(flat).second) { + *err = err_bad("tools", "two tools are named \"" + flat + "\" (a namespace's tools " + "are offered to the model as __)"); + return RAD_E_INVAL; + } + json fn = { { "name", flat }, + { "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } }; + if (t.contains("description")) fn["description"] = t.at("description"); + tools.push_back(json{ { "type", "function" }, { "function", fn } }); + if (!space.empty() && ns) (*ns)[flat] = { space, name }; + return RAD_OK; + }; for (const json& t : *tit) { - if (str_or(t, "type") != "function") { + const std::string type = str_or(t, "type"); + if (type == "namespace") { + std::string space; + if (!member_str(t, "name", "tools[].name", &space, err)) return RAD_E_INVAL; + if (space.empty()) { + *err = err_bad("tools[].name", "a namespace needs a name"); + return RAD_E_INVAL; + } + auto inner = t.find("tools"); + if (inner == t.end() || !inner->is_array()) { + *err = err_bad("tools[].tools", "a namespace holds an array of tools"); + return RAD_E_INVAL; + } + for (const json& f : *inner) { + if (str_or(f, "type") != "function") { + RAD_DEBUG("responses: tool of type \"%s\" in namespace \"%s\" left out: " + "no chat equivalent", str_or(f, "type", "?").c_str(), + space.c_str()); + continue; + } + RAD_TRY(add(f, space)); + } + echo_tools.push_back(t); + continue; + } + if (type != "function") { RAD_DEBUG("responses: tool of type \"%s\" left out: no chat equivalent", str_or(t, "type", "?").c_str()); continue; } - std::string name; - if (!member_str(t, "name", "tools[].name", &name, err)) return RAD_E_INVAL; - json fn = { { "name", name }, - { "parameters", t.contains("parameters") ? t.at("parameters") : json::object() } }; - if (t.contains("description")) fn["description"] = t.at("description"); - tools.push_back(json{ { "type", "function" }, { "function", fn } }); + RAD_TRY(add(t, "")); echo_tools.push_back(t); } if (!tools.empty()) o["tools"] = std::move(tools); } auto tc = b.find("tool_choice"); if (tc != b.end() && !tc->is_null()) { - std::string type = "auto", name; + std::string type = "auto", name, space; if (tc->is_object() && (!member_str(*tc, "type", "tool_choice.type", &type, err) || - !member_str(*tc, "name", "tool_choice.name", &name, err))) + !member_str(*tc, "name", "tool_choice.name", &name, err) || + !member_str(*tc, "namespace", "tool_choice.namespace", &space, err))) return RAD_E_INVAL; + if (!space.empty()) name = space + "__" + name; if (!tc->is_object()) o["tool_choice"] = *tc; else if (type == "function") o["tool_choice"] = json{ { "type", "function" }, { "function", { { "name", name } } } }; @@ -4119,7 +4176,7 @@ std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageO out.push_back(reasoning_item(random_id("rs_"), c.msg.reasoning, "completed")); if (!c.msg.content.empty()) out.push_back(message_item(random_id("msg_"), c.msg.content, "completed")); - for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(tc, "completed")); + for (const ToolCall& tc : c.msg.tool_calls) out.push_back(call_item(r, tc, "completed")); const bool cut = c.finish == Finish::Length; return response_object(r, cut ? "incomplete" : "completed", out, &u, cut ? "max_output_tokens" : nullptr).dump(); @@ -4175,7 +4232,7 @@ void ResponsesStream::open(std::string& out, Item k, size_t call) { const ToolCall& tc = last_.tool_calls[call]; item_id_ = fc_id(tc.id); event(out, "response.output_item.added", - json{ { "output_index", at }, { "item", call_item(tc, "in_progress") } }); + json{ { "output_index", at }, { "item", call_item(*r_, tc, "in_progress") } }); } } @@ -4207,7 +4264,7 @@ void ResponsesStream::close(std::string& out) { const bool cut = finished_ && last_.open_call && call_ + 1 == last_.tool_calls.size(); event(out, "response.function_call_arguments.done", json{ { "item_id", item_id_ }, { "output_index", at }, { "arguments", tc.arguments } }); - item = call_item(tc, cut ? "incomplete" : "completed"); + item = call_item(*r_, tc, cut ? "incomplete" : "completed"); } event(out, "response.output_item.done", json{ { "output_index", at }, { "item", item } }); items_.push_back(std::move(item)); diff --git a/core/server/oai.h b/core/server/oai.h index 4ea77023..ffbf5538 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -109,6 +109,10 @@ struct OaiRequest { /* The Responses API request fields its response object echoes (instructions, tools, * tool_choice, text, reasoning, ...), as a JSON object; "" for the other shapes. */ std::string echo_json; + /* The Responses API's namespaced function tools, flattened for the chat path: the flattened + * name ("__") to its namespace and name, which a function_call item reports + * apart. Empty for the other shapes. */ + std::map> tool_namespace; /* llama-server's native /completion: the generated token ids beside the text. */ bool return_tokens = false; /* The reasoning block's closer when the reply starts inside the block, else "": the stop @@ -499,9 +503,11 @@ std::string anthropic_error_body(const ApiError& e); /* OpenAI's Responses API, translated into the equivalent chat request like Anthropic's. `*echo` * holds the request fields the response object repeats. previous_response_id needs server-side * storage and is refused; non-function tool types have no chat equivalent and are dropped, as - * llama-server does. */ + * llama-server does. A namespace's function tools are flattened to "__", and + * `*ns` (when given) maps each flattened name back for the reply's function_call items. */ int responses_to_chat(const std::string& body, const OaiLimits& lim, std::string* chat, - std::string* echo, ApiError* err); + std::string* echo, ApiError* err, + std::map>* ns = nullptr); std::string responses_body(const OaiRequest& r, const ChoiceOut& c, const UsageOut& u); /* Anthropic's stop_reason for a finish and the stop string that caused it. */ diff --git a/core/server/server.cpp b/core/server/server.cpp index d7719961..d72dc82d 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -170,7 +170,12 @@ void Server::register_routes() { router_.post("/v1/responses", [this](const HttpRequest& q) { return handle_responses(q); }); router_.post("/responses", [this](const HttpRequest& q) { return handle_responses(q); }); auto responses_tokens = [this](const HttpRequest& q) { - return count_tokens(q, responses_to_chat, ApiShape::OpenAI, "response.input_tokens"); + return count_tokens(q, + [](const std::string& b, const OaiLimits& l, std::string* c, + std::string* ec, ApiError* e) { + return responses_to_chat(b, l, c, ec, e); + }, + ApiShape::OpenAI, "response.input_tokens"); }; router_.post("/v1/responses/input_tokens", responses_tokens); router_.post("/responses/input_tokens", responses_tokens); @@ -210,9 +215,7 @@ static const int64_t kSpareWorkers = 64; void Server::note_ready(uint64_t begin_ns) { if (begin_ns == 0) return; const uint64_t now = rad_mono_ns(); - /* Only a start in the past is a duration. A stamp that arrives out of order is ignored rather - * than written as zero: a zero cost would price every restart as free in any payback formula - * that divides by it. */ + /* A stamp that is not in the past leaves the figure unset rather than writing a zero. */ if (now <= begin_ns) return; startup_s_ = (int64_t)((now - begin_ns) / 1000000000ull); } @@ -264,20 +267,32 @@ std::vector Server::probe_reasoning_efforts() { l.default_reasoning_effort.clear(); l.reasoning_effort_map.clear(); l.probe = true; - auto takes = [&](const std::string& effort) { + template_default_effort_.clear(); + auto render = [&](const std::string& effort, std::string* text) { std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1)"; if (!effort.empty()) body += R"(,"reasoning_effort":)" + json(effort).dump(); body += "}"; OaiRequest r; ApiError e; - return parse_chat_request(body, odeps_, l, &r, &e) >= 0; + if (parse_chat_request(body, odeps_, l, &r, &e) < 0) return false; + if (text) *text = r.prompts.empty() ? std::string() : r.prompts[0].text; + return true; }; /* A render that fails without an effort says nothing about efforts; one that takes a * nonsense word takes every word. */ - if (!takes("") || takes("radiance-probe-not-a-level")) return {}; - std::vector set; - for (const char* w : { "low", "medium", "high", "xhigh", "max" }) - if (takes(w)) set.push_back(w); + std::string plain; + if (!render("", &plain) || render("radiance-probe-not-a-level", nullptr)) return {}; + std::vector set, same; + for (const char* w : { "low", "medium", "high", "xhigh", "max" }) { + std::string text; + if (!render(w, &text)) continue; + set.push_back(w); + if (text == plain) same.push_back(w); + } + /* The level a request naming none gets: the one level whose render is the same. A template may + * spend it in a system prompt the client never sees (#113: Qwen3.8's is xhigh). Several, or + * none, say nothing. */ + if (same.size() == 1) template_default_effort_ = same[0]; lim_.reasoning_efforts = set; return set; } @@ -1548,10 +1563,12 @@ HttpResponse Server::handle_responses(const HttpRequest& req) { std::string chat, echo; ApiError err; OaiRequest r; - if (responses_to_chat(req.body, lim_, &chat, &echo, &err) < 0 || + std::map> ns; + if (responses_to_chat(req.body, lim_, &chat, &echo, &err, &ns) < 0 || parse_chat_request(chat, odeps_, lim_, &r, &err) < 0) return error_response(err, req.peer); r.shape = ApiShape::Responses; + r.tool_namespace = std::move(ns); r.id = random_id("resp_"); r.echo_json = std::move(echo); return serve(req, r); diff --git a/core/server/server.h b/core/server/server.h index 12360f1f..f1cded21 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -181,6 +181,9 @@ public: * also takes a nonsense word it takes any word, and the result is empty. Used to refuse words * outside the set and for /server_info; called once, before run(). */ std::vector probe_reasoning_efforts(); + /* The effort the template applies to a request that names none, found by the probe above as + * the one whose render is the same; "" when none matches or the probe found no set. */ + const std::string& template_default_effort() const { return template_default_effort_; } /* Renders each --reasoning-effort-map target as a request's effort. Empty when the template * takes all of them; otherwise the first refusal, naming the target. */ std::string check_reasoning_effort_map() const; @@ -198,6 +201,7 @@ public: void note_ready(uint64_t begin_ns); private: + std::string template_default_effort_; struct Generation; struct TranscriptionJob; /* speech.cpp */ struct RealtimeSession; /* realtime.cpp */ @@ -357,8 +361,8 @@ private: std::atomic speech_sessions_{0}; std::atomic stopping_{false}; int64_t started_at_ = 0; - /* Seconds from the top of Engine::start() to the moment the server began listening -- the - * cost of a restart, measured on this machine rather than guessed. 0 until note_ready(). */ + /* Seconds from the top of Engine::start() to the moment the server began listening; 0 until + * note_ready(). */ int64_t startup_s_ = 0; /* Sinks whose HTTP side is gone but whose engine side may still be mid-step. Held until the diff --git a/core/server/videos.cpp b/core/server/videos.cpp index 94f48633..b1de899f 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -15,8 +15,19 @@ * (`w:h`) instead lays the model's own canvas over that ratio: the short edge (the model's, or * `short_edge`), the area capped at the model's largest, both sides rounded to the multiple. * A video's length is a whole number of the model's chunks: `seconds` is rounded up to the next. - * Nothing that conditions on media is served: `input_reference` and non-empty `conditions` are - * refused. + * A model with a length head (LTX-2.5's duration head) chooses the length of a request that names + * none, or says `"seconds": "auto"`; the video object reports it once chosen. A model with more + * than one decoder takes `decoder`, one of their names (LTX-2.5: `vae`, the default, or + * `diffusion`). + * A model that can start from a picture takes OpenAI's `input_reference`, a file in the form or a + * data URL (a string or {image_url}) in JSON, as the video's first frame, prepared as the model's + * pipeline prepares it: an H.264 round trip at the model's quality, then a bilinear resize to the + * size the first steps run at. Non-empty `conditions` are refused. + * + * A guided model takes `negative_prompt` and its guidance terms, each the model's default when + * absent: `guidance_scale`, `stg_scale`, `modality_scale` and `guidance_rescale` for the video, + * the same with `audio_` in front for the soundtrack. A scale of 1 turns that modality's + * unconditional branch off; the negative prompt is the model's own unless named. * * A model with a latent upscaler also takes `latent_upscale`, a factor from 1 to its largest: the * first steps run at `size` divided by it and the latent is enlarged to `size` for the last @@ -31,6 +42,7 @@ #include "oai.h" #include "gen/video.h" +#include "mm/imaging.h" #include "mm/media.h" #include "mm/mp4.h" #include "rad_internal.h" @@ -40,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -66,12 +79,24 @@ struct Server::VideoJob { double upscale = 0.0; int32_t refine = 0; std::string upscale_from; + /* A guided model's terms as resolved against its defaults, the negative prompt when a scale + * used it, and whether the video started from a picture. */ + bool guided = false; + double guidance[8] = {}; + std::string negative; + bool has_negative = false; + bool from_image = false; + std::string decoder; /* a decoder the request named other than the default */ int32_t w = 0, h = 0; bool worker_done = false; /* its thread has nothing left to do but return */ }; namespace { +/* The largest picture `input_reference` may decode to, which bounds the memory a request can make + * the server allocate before the resize. */ +constexpr int64_t kMaxRefPixels = (int64_t)1 << 26; + std::string new_video_id() { static const char* hex = "0123456789abcdef"; std::random_device rd; @@ -130,11 +155,15 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { /* JSON, or a form whose fields are strings (OpenAI's clients send the create call as a form, * since it may carry a file). */ json body = json::object(); + std::vector ref_bytes; + bool has_ref = false; if (!req.form.empty()) { for (const FormPart& p : req.form) { - if (p.name == "input_reference") - return error_response(err_unsupported("input_reference", "this server makes video " - "from text only"), req.peer); + if (p.name == "input_reference" && !p.filename.empty()) { + ref_bytes.assign(p.data.begin(), p.data.end()); + has_ref = true; + continue; + } if (!p.filename.empty()) return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"), req.peer); @@ -154,6 +183,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { static const char* kKnown[] = { "model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps", "task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", + "negative_prompt", "decoder", + /* RadVideoGenBatch::guidance_h's order */ + "guidance_scale", "stg_scale", "modality_scale", "guidance_rescale", + "audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; @@ -178,12 +211,33 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { body["prompt"].get().find_first_not_of(" \t\r\n") == std::string::npos) return bad("prompt", "the prompt is required, as a non-empty string"); const std::string prompt = body["prompt"].get(); - if (has(body, "input_reference")) - return error_response(err_unsupported("input_reference", "this server makes video from " + if (has(body, "input_reference")) { + /* JSON: a data URL, as a string or an image_url object. */ + const json& v = body["input_reference"]; + std::string u; + if (v.is_string()) u = v.get(); + else if (v.is_object() && v.contains("image_url") && v["image_url"].is_string()) + u = v["image_url"].get(); + else if (v.is_object() && v.contains("image_url") && v["image_url"].is_object() && + v["image_url"].contains("url") && v["image_url"]["url"].is_string()) + u = v["image_url"]["url"].get(); + else + return bad("input_reference", "a picture is a file, a data: URL, or an object with an " + "image_url"); + ApiError err; + if (decode_media_url(u, "input_reference", &ref_bytes, &err) < 0) + return error_response(err, req.peer); + has_ref = true; + } + if (has_ref && !info.image_cond) + return error_response(err_unsupported("input_reference", "this model makes video from " "text only"), req.peer); - if (has(body, "task") && (!body["task"].is_string() || body["task"].get() != "t2va")) { - ApiError e = err_unsupported("task", "this server makes video from text: t2va"); - e.supported = { "t2va" }; + const std::string task_want = has_ref ? "i2va" : "t2va"; + if (has(body, "task") && (!body["task"].is_string() || + body["task"].get() != task_want)) { + ApiError e = err_unsupported("task", has_ref ? "a video from a picture is i2va" + : "this request makes video from text: t2va"); + e.supported = { task_want }; return error_response(e, req.peer); } if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty())) @@ -250,7 +304,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { const bool has_sec = has(body, "seconds"), has_dur = has(target, "duration_seconds"); if (has_sec && has_dur) return bad("seconds", "give seconds or target's duration_seconds, not both"); - if (has_sec || has_dur) { + /* A model with a length head chooses the length of a request that names none, or `auto`. */ + const bool auto_len = info.length_head && + (!(has_sec || has_dur) || + (has_sec && body["seconds"].is_string() && body["seconds"].get() == "auto")); + if (auto_len) { + chunks = 0; + } else if (has_sec || has_dur) { double sec = 0; if (!number(has_sec ? body["seconds"] : target["duration_seconds"], &sec) || !(sec > 0)) return bad(has_sec ? "seconds" : "target", "the length is a positive number of seconds"); @@ -263,26 +323,81 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { "this model makes " + rad::fmt("%.2f", min_s) + " to " + rad::fmt("%.2f", max_s) + " seconds"); } - const int64_t frames = info.frames_per_chunk * chunks + info.frames_tail; + /* The length the job reports until the model has chosen one. */ + const int64_t frames = + info.frames_per_chunk * (chunks > 0 ? chunks : info.default_chunks) + info.frames_tail; std::unique_ptr r = std::make_unique(); r->width = (int32_t)W; r->height = (int32_t)H; r->chunks = (int32_t)chunks; + /* ---- the decoder, by name, the model's first when absent */ + std::string decoder; + if (has(body, "decoder")) { + if (!body["decoder"].is_string()) + return bad("decoder", "the decoder is a name"); + decoder = body["decoder"].get(); + std::string names; + int32_t idx = -1; + for (size_t i = 0; i < info.decoders.size(); ++i) { + names += (i ? ", " : "") + info.decoders[i]; + if (info.decoders[i] == decoder) idx = (int32_t)i; + } + if (idx < 0) + return bad("decoder", info.decoders.empty() + ? std::string("this model has one decoder and takes no name") + : "this model decodes with " + names); + if (W * H > info.decoder_max_area[(size_t)idx]) + return bad("decoder", "the " + decoder + " decoder makes frames of " + + std::to_string(info.decoder_max_area[(size_t)idx]) + + " pixels at most"); + r->decoder = idx; + if (idx == 0) decoder.clear(); + } if (has(body, "num_inference_steps")) { double v = 0; + const char* unit = info.step_evals ? " model evaluations" + : " sigma grid points, the last one 0"; + const int64_t lo = info.step_evals ? 1 : 2; if (info.fixed_steps && (!number(body["num_inference_steps"], &v) || v != (double)info.max_steps)) return bad("num_inference_steps", "this model runs the schedule it was trained on: " + - std::to_string(info.max_steps) + " sigma grid points, the last one 0"); - if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < 2 || + std::to_string(info.max_steps) + unit); + if (!number(body["num_inference_steps"], &v) || v != std::floor(v) || v < lo || v > (double)info.max_steps) - return bad("num_inference_steps", "expected an integer in 2.." + - std::to_string(info.max_steps) + - " (sigma grid points, the last one 0)"); + return bad("num_inference_steps", "expected an integer in " + std::to_string(lo) + + ".." + std::to_string(info.max_steps) + " (" + + (unit + 1) + ")"); r->steps = (int32_t)v; } + /* ---- guidance */ + static const char* kGuide[8] = { + "guidance_scale", "stg_scale", "modality_scale", "guidance_rescale", + "audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale", + }; + for (int i = 0; i < 8; ++i) { + if (!has(body, kGuide[i])) continue; + if (!info.guidance) + return error_response(err_unsupported(kGuide[i], "this model takes no guidance"), + req.peer); + double v = 0; + const bool rescale = i % 4 == 3; + if (!number(body[kGuide[i]], &v) || !(v >= 0.0) || v > (rescale ? 1.0 : 100.0)) + return bad(kGuide[i], rescale ? "expected a number from 0 to 1" + : "expected a number from 0 to 100"); + r->guidance[i] = v; + } + std::string negative = info.default_negative; + if (has(body, "negative_prompt")) { + if (!info.guidance) + return error_response(err_unsupported("negative_prompt", "this model takes no " + "guidance"), req.peer); + if (!body["negative_prompt"].is_string()) + return bad("negative_prompt", "expected a string"); + negative = body["negative_prompt"].get(); + r->has_neg = true; + } if (has(body, "latent_upscale")) { double v = 0; if (!(info.upscale_max > 0.0)) @@ -320,18 +435,65 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { static const std::string kSlot = "{prompt}"; const std::string& t = info.tmpl; const size_t p = t.find(kSlot); - auto put = [&](const std::string& s, bool special) { - if (s.empty()) return; - const auto ids = deps_.tok->encode(s, false, special); - r->tokens.insert(r->tokens.end(), ids.begin(), ids.end()); + auto render = [&](const std::string& text, std::vector* out) { + auto put = [&](const std::string& s, bool special) { + if (s.empty()) return; + const auto ids = deps_.tok->encode(s, false, special); + out->insert(out->end(), ids.begin(), ids.end()); + }; + put(t.substr(0, p), true); + put(text, false); + put(t.substr(p + kSlot.size()), true); }; - put(t.substr(0, p), true); - put(prompt, false); - put(t.substr(p + kSlot.size()), true); + render(prompt, &r->tokens); if ((int64_t)r->tokens.size() > info.max_text) return bad("prompt", "the prompt is " + std::to_string(r->tokens.size()) + " tokens; this model takes at most " + std::to_string(info.max_text)); + if (info.guidance) { + render(negative, &r->neg_tokens); + if ((int64_t)r->neg_tokens.size() > info.max_text) + return bad("negative_prompt", "the negative prompt is " + + std::to_string(r->neg_tokens.size()) + + " tokens; this model takes at most " + + std::to_string(info.max_text)); + } + } + + /* ---- the first frame, at the size the first steps run at */ + if (has_ref) { + int32_t fw = r->width, fh = r->height; + if (r->upscale > 1.0) { + RadVideoGenDecl geo{}; /* video_small_size reads the size multiple only */ + geo.size_multiple = info.size_multiple; + gen::video_small_size(geo, r->width, r->height, r->upscale, &fw, &fh); + } + mm::Frame f; + std::string why; + if (mm::decode_image(ref_bytes.data(), ref_bytes.size(), kMaxRefPixels, &f, &why) < 0) + return bad("input_reference", "the picture could not be read: " + why); + if (info.image_crf > 0) { + mm::Frame rt; + const int e = mm::h264_roundtrip(f, info.image_crf, &rt, &why); + if (e < 0) { + ApiError err = err_bad("input_reference", "the picture could not be prepared: " + why); + if (e != RAD_E_INVAL) { err.status = 503; err.type = "server_error"; } + return error_response(err, req.peer); + } + f = std::move(rt); + } + mm::FrameRGBA a, sized; + a.w = f.w; + a.h = f.h; + a.rgba.resize((size_t)f.w * f.h * 4); + for (size_t i = 0, n = (size_t)f.w * f.h; i < n; ++i) { + std::memcpy(&a.rgba[4 * i], &f.rgb[3 * i], 3); + a.rgba[4 * i + 3] = 255; + } + mm::resize_bilinear_rgba(a, fw, fh, &sized); + r->image.resize((size_t)fw * fh * 3); + for (size_t i = 0, n = (size_t)fw * fh; i < n; ++i) + std::memcpy(&r->image[3 * i], &sized.rgba[4 * i], 3); } /* ---- admitted and queued: the job holds its place until its file is written */ @@ -340,7 +502,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { j->id = new_video_id(); j->model = opt_.model_id; j->prompt = prompt; - j->seconds = rad::fmt("%.2f", (double)frames / fps); + j->seconds = auto_len ? std::string("auto") : rad::fmt("%.2f", (double)frames / fps); j->size = std::to_string(W) + "x" + std::to_string(H); j->created_at = unix_now(); j->seed = r->seed; @@ -348,6 +510,13 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { r->ticket = j->ticket; const int64_t n_tok = (int64_t)r->tokens.size(); const int32_t steps = r->steps; + j->guided = info.guidance; + for (int i = 0; i < 8; ++i) + j->guidance[i] = std::isnan(r->guidance[i]) ? info.guidance_default[i] : r->guidance[i]; + j->has_negative = info.guidance && (j->guidance[0] != 1.0 || j->guidance[4] != 1.0); + if (j->has_negative) j->negative = negative; + j->from_image = !r->image.empty(); + j->decoder = decoder; const double upscale = r->upscale; { std::string w; @@ -365,8 +534,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { j->refine = tk.refine; j->upscale_from = std::to_string(tk.small_width) + "x" + std::to_string(tk.small_height); } - RAD_INFO("video %s: %s, %lld frames (%s s), %lld prompt tokens, %d steps%s, seed=%llu", - j->id.c_str(), j->size.c_str(), (long long)frames, j->seconds.c_str(), + RAD_INFO("video %s: %s, %s, %lld prompt tokens, %d steps%s, seed=%llu", + j->id.c_str(), j->size.c_str(), + auto_len ? "the length the model chooses" + : rad::fmt("%lld frames (%s s)", (long long)frames, j->seconds.c_str()).c_str(), (long long)n_tok, steps > 0 ? steps : (int)tk.steps, tk.refine > 0 ? rad::fmt(" (the first %d at %dx%d, upscaled for the last %d)", (int)(tk.steps - tk.refine), (int)tk.small_width, @@ -406,6 +577,9 @@ void Server::video_work(std::shared_ptr j) { std::lock_guard lk(videos_m_); j->status = "in_progress"; j->progress = t.steps > 0 ? (int)(90LL * e.steps_done / t.steps) : 0; + } else if (e.kind == gen::VideoEvent::LENGTH) { + std::lock_guard lk(videos_m_); + j->seconds = rad::fmt("%.2f", (double)e.n * info.fps_den / info.fps_num); } else if (e.kind == gen::VideoEvent::AUDIO) { if (t.channels > 0) st = mp4.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why); @@ -530,6 +704,17 @@ json Server::video_json(const VideoJob& j) { o["upscale_refine_steps"] = j.refine; o["upscale_from"] = j.upscale_from; } + if (j.guided) { + static const char* kGuide[8] = { + "guidance_scale", "stg_scale", "modality_scale", "guidance_rescale", + "audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", + "audio_guidance_rescale", + }; + for (int i = 0; i < 8; ++i) o[kGuide[i]] = j.guidance[i]; + if (j.has_negative) o["negative_prompt"] = j.negative; + } + if (j.from_image) o["input_reference"] = true; + if (!j.decoder.empty()) o["decoder"] = j.decoder; o["remixed_from_video_id"] = nullptr; if (j.failed) { json e; diff --git a/core/text/chat.cpp b/core/text/chat.cpp index 2986dc5e..076b3820 100644 --- a/core/text/chat.cpp +++ b/core/text/chat.cpp @@ -10,6 +10,7 @@ #include #include +#include #include namespace rad { @@ -130,6 +131,54 @@ static size_t json_depth(const ojson& root) { return deepest; } +/* The conversation with every system message merged, in order, into one at its head, or false + * when that is the conversation already (none, or one leading) or a system message carries more + * than text. The Chat Completions API places no constraint on system messages, while many + * templates raise unless there is exactly one, first (#137). */ +static bool lead_system(const ojson& messages, ojson* out) { + if (!messages.is_array()) return false; + std::string text; + size_t n_sys = 0; + bool first = false; + for (size_t i = 0; i < messages.size(); ++i) { + const ojson& m = messages[i]; + if (!m.is_object() || m.value("role", "") != "system") continue; + if (i == 0) first = true; + std::string t; + const auto c = m.find("content"); + if (c != m.end() && c->is_string()) { + t = c->get(); + } else if (c != m.end() && c->is_array()) { + for (const ojson& part : *c) { + if (!part.is_object() || part.value("type", "") != "text" || + !part.contains("text") || !part.at("text").is_string()) + return false; + t += part.at("text").get(); + } + } else if (c != m.end() && !c->is_null()) { + return false; + } + if (n_sys++ && !text.empty() && !t.empty()) text += "\n\n"; + text += t; + } + if (n_sys == 0 || (n_sys == 1 && first)) return false; + *out = ojson::array(); + out->push_back(ojson{ { "role", "system" }, { "content", text } }); + for (const ojson& m : messages) + if (!m.is_object() || m.value("role", "") != "system") out->push_back(m); + return true; +} + +/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence + * about parser generation, which the render's failure is not. */ +static std::string template_words(const char* what) { + static const char kWrap[] = "Unable to generate parser for this template. Automatic parser " + "generation failed: "; + std::string w = what ? what : ""; + if (w.compare(0, sizeof kWrap - 1, kWrap) == 0) w.erase(0, sizeof kWrap - 1); + return w; +} + int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt, ChatPrompt* out) const { if (!ready()) { @@ -190,9 +239,32 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt try { p = common_chat_templates_apply(impl_->tmpls.get(), in); } catch (const std::exception& e) { - if (!opt.quiet) RAD_ERR("chat: template refused the request: %s", e.what()); - out->error = e.what(); - return RAD_E_UNSUPPORTED; + /* A template that takes one system message, first, refuses a conversation that has + * another or has it later, which the API allows: it is rendered once more with them + * merged into one at the head. Anything else the template refuses is the request's. */ + ojson merged; + bool served = false; + if (lead_system(messages, &merged)) { + try { + in.messages = common_chat_msgs_parse_oaicompat(merged); + p = common_chat_templates_apply(impl_->tmpls.get(), in); + served = true; + static std::atomic said{ false }; + if (!opt.quiet && !said.exchange(true)) + RAD_WARN("chat: the model's chat template refuses system messages after the " + "first (%s); such a conversation is rendered with its system " + "messages merged, in order, into one at the head. Said once.", + template_words(e.what()).c_str()); + } catch (const std::exception&) { + } + } + if (!served) { + const std::string w = template_words(e.what()); + if (!opt.quiet) RAD_WARN("chat: the model's chat template refused the request: %s", + w.c_str()); + out->error = "the model's chat template refused this conversation: " + w; + return RAD_E_INVAL; + } } out->prompt = std::move(p.prompt); diff --git a/core/util/rad_util.cpp b/core/util/rad_util.cpp index 76fbdf8b..bef28516 100644 --- a/core/util/rad_util.cpp +++ b/core/util/rad_util.cpp @@ -72,11 +72,22 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) { const char* base = std::strrchr(file, '/'); base = base ? base + 1 : file; - char msg[4096]; - va_list ap; + /* A line longer than the stack buffer is formatted again in full: a trace row of many values + * (RADIANCE_DUMP_HEAD) was cut at 4 KiB without a mark (#113). */ + char buf[4096]; + std::string big; + va_list ap, ap2; va_start(ap, fmt); - vsnprintf(msg, sizeof msg, fmt, ap); + va_copy(ap2, ap); + const int n = vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + if (n >= (int)sizeof buf) { + big.resize((size_t)n + 1); + vsnprintf(big.data(), big.size(), fmt, ap2); + big.resize((size_t)n); + } + va_end(ap2); + const char* msg = big.empty() ? buf : big.c_str(); const char* col = level_colour(l); const char* rst = col[0] ? "\033[0m" : ""; diff --git a/data/recipes/flux-3-klein-fp8.recipe b/data/recipes/flux-3-klein-fp8.recipe new file mode 100644 index 00000000..a44c6cfc --- /dev/null +++ b/data/recipes/flux-3-klein-fp8.recipe @@ -0,0 +1,24 @@ +# flux-3-klein-fp8.recipe -- FLUX.3 [klein] (or its base) with block-scaled fp8 linears. +# +# rad-convert --recipe data/recipes/flux-3-klein-fp8.recipe \ +# -o flux-3-klein-fp8.rad +# +# Every linear of the text encoder's language model and of the DiT's early and joint blocks +# becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over activations +# quantised the same way. What stays bf16 is read once a pass or less: the embedding table, the +# embedders, the timestep MLPs, the modulations, the output layer and the VAE. The language +# model's layers past its last tap (32 of 36) are not carried. + +te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.mode.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.mode.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.mode.*.ffn_in.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.mode.*.ffn_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.single.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.single.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.single.*.ffn_in.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.single.*.ffn_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +vae.* cast dtype=bf16 diff --git a/data/recipes/krea-2-bf16.recipe b/data/recipes/krea-2-bf16.recipe new file mode 100644 index 00000000..a6657048 --- /dev/null +++ b/data/recipes/krea-2-bf16.recipe @@ -0,0 +1,23 @@ +# krea-2-bf16.recipe -- Krea 2 (Raw or Turbo) at bf16. +# +# rad-convert --recipe data/recipes/krea-2-bf16.recipe \ +# -o krea-2-bf16.rad +# +# Every linear stays as the release holds it (bf16). The language model's layers past its last tap +# (35 of 36) are not carried. The first matching rule decides. + +# The release stores its norms, modulation tables, embedders, projector and output layer f32. +# diffusers keeps every norm f32 and runs the rest bf16. Here the text fusion's norms, the q/k norms +# and txt_in's norm stay f32; the DiT's norm1, norm2 and final norm are bf16, the fused modulation +# kernel's operand, with the rest. +fuse.*.norm1.weight cast dtype=f32 +fuse.*.norm2.weight cast dtype=f32 +fuse.*.q_norm.weight cast dtype=f32 +fuse.*.k_norm.weight cast dtype=f32 +dit.blk.*.q_norm.weight cast dtype=f32 +dit.blk.*.k_norm.weight cast dtype=f32 +txt.norm.weight cast dtype=f32 +fuse.* cast dtype=bf16 +txt.* cast dtype=bf16 +dit.* cast dtype=bf16 +vae.* cast dtype=bf16 diff --git a/data/recipes/krea-2-fp8.recipe b/data/recipes/krea-2-fp8.recipe new file mode 100644 index 00000000..330219e4 --- /dev/null +++ b/data/recipes/krea-2-fp8.recipe @@ -0,0 +1,41 @@ +# krea-2-fp8.recipe -- Krea 2 (Raw or Turbo) with block-scaled fp8 linears. +# +# rad-convert --recipe data/recipes/krea-2-fp8.recipe \ +# -o krea-2-fp8.rad +# +# Every linear of the text encoder's language model, of the text fusion's blocks and of the DiT's +# 28 blocks becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over +# activations quantised the same way. What stays bf16 is read once a pass or less: the embedding +# table, txt_in, img_in, the timestep MLP and modulation, the blocks' tables, the final layer and +# the VAE. The language model's layers past its last tap (35 of 36) are not carried. + +te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +fuse.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +fuse.*.attn_gate.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +fuse.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +fuse.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +fuse.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_gate.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The release stores its norms, modulation tables, embedders, projector and output layer f32. +# diffusers keeps every norm f32 and runs the rest bf16. Here the text fusion's norms, the q/k norms +# and txt_in's norm stay f32; the DiT's norm1, norm2 and final norm are bf16, the fused modulation +# kernel's operand, with the rest. +fuse.*.norm1.weight cast dtype=f32 +fuse.*.norm2.weight cast dtype=f32 +fuse.*.q_norm.weight cast dtype=f32 +fuse.*.k_norm.weight cast dtype=f32 +dit.blk.*.q_norm.weight cast dtype=f32 +dit.blk.*.k_norm.weight cast dtype=f32 +txt.norm.weight cast dtype=f32 +fuse.* cast dtype=bf16 +txt.* cast dtype=bf16 +dit.* cast dtype=bf16 +vae.* cast dtype=bf16 diff --git a/data/recipes/ltx-2.5-bf16.recipe b/data/recipes/ltx-2.5-bf16.recipe new file mode 100644 index 00000000..27eb7ba2 --- /dev/null +++ b/data/recipes/ltx-2.5-bf16.recipe @@ -0,0 +1,14 @@ +# ltx-2.5-bf16.recipe -- LTX-2.5 (the base or the distilled DiT) at the checkpoint's precision. +# +# rad-convert --recipe data/recipes/ltx-2.5-bf16.recipe \ +# -o ltx-2.5-bf16.rad +# +# The text encoder, the connectors, the DiT, both VAEs and the latent upsampler are kept bf16. The +# vocoders run in f32 and a pipeline saved in bf16 holds them bf16, so they are cast here, once; the +# spectrogram bases stay bf16. + +voc.conv_* cast dtype=f32 +voc.upsamplers.* cast dtype=f32 +voc.resnets.* cast dtype=f32 +voc.act_out.* cast dtype=f32 +bwe.* cast dtype=f32 diff --git a/data/recipes/ltx-2.5-fp8.recipe b/data/recipes/ltx-2.5-fp8.recipe new file mode 100644 index 00000000..74d96867 --- /dev/null +++ b/data/recipes/ltx-2.5-fp8.recipe @@ -0,0 +1,37 @@ +# ltx-2.5-fp8.recipe -- LTX-2.5 (the base or the distilled DiT) with block-scaled fp8 linears. +# +# rad-convert --recipe data/recipes/ltx-2.5-fp8.recipe \ +# -o ltx-2.5-fp8.rad +# +# Every linear of the text encoder (Gemma 4), of the two connectors and of the DiT's 48 blocks +# becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over activations +# quantised the same way; the biases stay bf16 and are added after. What stays bf16 is small or +# read once a step: the attention gates' logits, the q and k norms, the patch projections, the +# timestep MLPs and the tables, the connectors' registers, both VAEs and the latent upsampler. +# The vocoders are cast to f32, which their convolutions and anti-aliased activations run in +# (a pipeline saved in bf16 holds them bf16); the spectrogram bases stay bf16. + +te.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +conn.*.proj.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +conn.*.blk.*.qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +conn.*.blk.*.out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +conn.*.blk.*.ff_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +conn.*.blk.*.ff_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.kv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ff_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.ff_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.audio_ff_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.audio_ff_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +voc.conv_* cast dtype=f32 +voc.upsamplers.* cast dtype=f32 +voc.resnets.* cast dtype=f32 +voc.act_out.* cast dtype=f32 +bwe.* cast dtype=f32 diff --git a/deploy/compose/flux-3-klein.yaml b/deploy/compose/flux-3-klein.yaml new file mode 100644 index 00000000..b3214063 --- /dev/null +++ b/deploy/compose/flux-3-klein.yaml @@ -0,0 +1,15 @@ +# FLUX.3 [klein] (black-forest-labs/flux-3-image-klein) as block fp8: text to image and edits from up +# to ten reference pictures on OpenAI's /v1/images/generations and /v1/images/edits, on one card, +# RADIANCE_GPU in .env (default 0). For the base model, point --model at flux-3-klein-base-fp8.rad. +# The FLUX Kommunity License (non-commercial use) applies. +name: radiance-flux-3-klein +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-flux-3-klein + environment: + ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}" + command: > + --model /models/flux-3-klein-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 diff --git a/deploy/compose/krea-2-raw.yaml b/deploy/compose/krea-2-raw.yaml new file mode 100644 index 00000000..f65e554a --- /dev/null +++ b/deploy/compose/krea-2-raw.yaml @@ -0,0 +1,14 @@ +# Krea 2 Raw (krea/Krea-2-Raw) as block fp8: text to image on OpenAI's /v1/images/generations, on one +# card, RADIANCE_GPU in .env (default 0). The Krea 2 Community License and Krea's acceptable use +# policy apply. +name: radiance-krea-2-raw +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-krea-2-raw + environment: + ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}" + command: > + --model /models/krea-2-raw-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 diff --git a/deploy/compose/krea-2-turbo.yaml b/deploy/compose/krea-2-turbo.yaml new file mode 100644 index 00000000..87b6f3cc --- /dev/null +++ b/deploy/compose/krea-2-turbo.yaml @@ -0,0 +1,14 @@ +# Krea 2 Turbo (krea/Krea-2-Turbo) as block fp8: text to image on OpenAI's /v1/images/generations, +# on one card, RADIANCE_GPU in .env (default 0). +# The Krea 2 Community License and Krea's acceptable use policy apply. +name: radiance-krea-2-turbo +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-krea-2-turbo + environment: + ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}" + command: > + --model /models/krea-2-turbo-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 diff --git a/deploy/compose/ltx-2.5.yaml b/deploy/compose/ltx-2.5.yaml new file mode 100644 index 00000000..0c737922 --- /dev/null +++ b/deploy/compose/ltx-2.5.yaml @@ -0,0 +1,15 @@ +# LTX-2.5 (Lightricks/LTX-2.5-Diffusers), distilled, as block fp8: video with its stereo soundtrack +# from text or from text and a first frame, on OpenAI's /v1/videos, on one card, RADIANCE_GPU in +# .env (default 0). The text encoder is read from pinned host memory (--vision-tower-placement ram). +# For the base model, point --model at ltx-2.5-fp8.rad. The LTX-2.x Community License applies. +name: radiance-ltx-2.5 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ltx-2.5 + environment: + ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}" + command: > + --model /models/ltx-2.5-distilled-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 --vision-tower-placement ram diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index bda1b0ce..dadd297e 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -21,10 +21,14 @@ plugin claims. | `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) | | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 | | `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 | +| `arch/krea2` | `krea2` | *(empty)* | Krea 2 Raw and Turbo, an image generator: Qwen3-VL-4B's tapped layers through a text-fusion transformer, a 12.9B single-stream DiT and Wan 2.1's VAE, from the diffusers pipeline directory; bf16 or block fp8 | +| `arch/flux3` | `flux3` | *(empty)* | FLUX.3 [klein] and its base, an image generator and editor: Qwen3-VL-4B's tapped layers, a 5.6B three-mode DiT over the text, up to ten reference pictures and the image, FLUX.2's VAE; bf16 or block fp8 | +| `arch/flux3distilled` | `flux3distilled` | *(empty)* | the same plugin under the name FLUX.3 [klein]'s step-distilled release gives itself (`Flux3DistilledModularPipeline`; its base is a `Flux3ModularPipeline`) | | `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text | | `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 | | `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card | | `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`) | +| `arch/ltx2` | `ltx2` | *(empty)* | LTX-2.5 (base and distilled), a video with its stereo soundtrack from text or from text and a first frame: Gemma 4's language model and two text connectors, the duration head, a dual-stream audio-video DiT with four-way guidance, the causal video VAE (tiled past the default canvas) or the diffusion decoder, the audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; bf16 or block fp8, one card | The traps below are readings that are wrong without any error: the model produces fluent output. @@ -195,7 +199,7 @@ Three groups, which is why hybrid KV groups are first-class: | group | kind | geometry | |---|---|---| -| full attention | `RAD_KV_FULL` | 16 layers, head_dim 256, 4 KV heads; block size from the resolved kernel. `--kv-cache-dtype fp8_v4` / `k6_v4` (`qwen35_fp8` only) declare it at head_dim 200 / 176, the bytes of a token's quantised row over two (docs/OPS.md) | +| full attention | `RAD_KV_FULL` | 16 layers, head_dim 256, 4 KV heads; block size from the resolved kernel. `--kv-cache-dtype fp8_v4` / `k6_v4` (`qwen35_fp8`; `qwen4exp_fp8` too) declare it at head_dim 200 / 176, the bytes of a token's quantised row over two (docs/OPS.md) | | GDN recurrent state | `RAD_KV_LINEAR` | 48 layers, 48 states of 128 x 128 | | GDN conv state | `RAD_KV_CONV` | 48 layers, 2*16 + 48 = 80 heads x 128 = 10240 channels, a rolling `conv_width - 1 + n_spec` window | @@ -301,6 +305,11 @@ plugin reads each weight's encoding from the container and declares the op that - bf16: every norm gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not a whole scale block), the router, `shared_expert_gate` and `embed_tokens`. +**The attention cache takes `--kv-cache-dtype fp8_v4` or `k6_v4`.** The QSA layers' cache (and the +MTP head's layer, which shares it) is then declared at head_dim 200 or 176, a token's quantised row +over two, and read by the gqa12 rows (gqa6 with 4-token pages at four ranks) of those layouts +(docs/OPS.md). The indexer's key cache and tail keep their widths. + `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` is the served choice: four-bit codebook experts with ten protected experts left bf16, int8 block linears and lm_head, E4M3 mixing and MTP fc matrices, and the n-gram table at one fixed E4M3 scale. @@ -488,26 +497,25 @@ and 8. - The indexer is replicated whole. - The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact. - The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each - connection's mHC projection of 24 x 16384) are replicated. From a pass of - `RADIANCE_GLM_TP_SPLIT_ROWS` rows (default 256; 0 never), each rank computes a disjoint part + connection's mHC projection of 24 x 16384) are replicated. From a pass of 256 rows + (`kGlmTpSplitRows`, `arch/common/rad_tp_split.h`), each rank computes a disjoint part with the replicated kernel and an `all_gather` joins the parts, so every value is bit-identical: the router and the head gates split their output columns, the mHC projection its 16384-wide input into eight 2048-column chunks, whose partials `mhc_pre_finish` completes on every rank. Below the threshold, as in decode, the collective costs more than it saves. -**MoE decode fusions.** Three, each byte-identical to the launches it replaces, on unless its -variable is `0`; any value but `0` or `1` refuses the start. +**MoE decode fusions.** Three, each byte-identical to the launches it replaces, declared +wherever a loaded library serves the fused op (the separate launches otherwise): -| variable | one launch for | where it applies | +| fusion | one launch for | where it applies | |---|---|---| -| `RADIANCE_GLM_ROUTER_FUSE` | `router_sigmoid_topk`, `moe_scatter` and the shared gate's `fill`: `router_sigmoid_topk_scatter` | passes of up to 128 rows (`M * top_k` <= 1024, one workgroup's sort); 84 launches fewer a trunk decode step, 2 a draft pass | -| `RADIANCE_GLM_SWIGLU_QUANT` | `swiglu_clamped` and `quant_act_fp8`: `swiglu_clamped_quant_fp8` | the routed and shared arms and the three dense layers; 87 fewer a trunk step, 2 a draft pass | -| `RADIANCE_GLM_GATHER_INVERSE` | none: the sort writes each slot's row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) instead of searching `sorted` | every MoE pass | +| router | `router_sigmoid_topk`, `moe_scatter` and the shared gate's `fill`: `router_sigmoid_topk_scatter` | passes of up to 128 rows (`M * top_k` <= 1024, one workgroup's sort); 84 launches fewer a trunk decode step, 2 a draft pass | +| SwiGLU | `swiglu_clamped` and `quant_act_fp8`: `swiglu_clamped_quant_fp8` | the routed and shared arms and the three dense layers; 87 fewer a trunk step, 2 a draft pass | +| gather inverse | none: the sort writes each slot's row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) instead of searching `sorted` | every MoE pass | -With all three at `0` the graph and the launches are those -`glm53_without_fusion_switches_is_the_pinned_graph_and_steps` pins. Paired on the eight R9700s -below, greedy text at a fixed draft depth of 3 is identical with and without them, and eight -agent streams decode 456 tok/s against 452, one 144 against 140. +`glm53_moe_decode_fusions_replace_their_launches_where_they_fit` counts the launches. Paired on +the eight R9700s below, greedy text at a fixed draft depth of 3 is identical with and without +them, and eight agent streams decode 456 tok/s against 452, one 144 against 140. **Measured** on eight R9700s (gfx1201, 32 GB; four on PCIe Gen5 x16, four on Gen5 x8) at TP8 with the flags of `deploy/compose/glm53-flash.yaml` (32768 tokens of context, eight sequences, MTP with @@ -870,6 +878,96 @@ its 8 steps. --- +# `krea2`: Krea 2 Raw and Turbo, an image generator + +`arch/krea2` declares a generator in the core's JOINT_STEP layout: the conditioning pass leaves +each lane's text rows (after the text fusion and `txt_in`) in its store, and every denoising step +runs them with the image, since every row is modulated by the step's timestep and nothing can be +cached as keys. Served on `/v1/images/generations` ([GUIDE §5.6](GUIDE.md)); it takes no reference +pictures, so `/v1/images/edits` answers 501. + +``` +text Qwen3-VL-4B's language model over the prompt in Qwen-Image's template, the template's + system turn dropped; TWELVE taps, hidden_states[2, 5, .., 35] (the outputs of layers 1, + 4, .., 34) before any final norm; the layers past the last tap are not converted +fusion two blocks attending across a token's twelve taps (twelve consecutive rows), a learned + Linear(12, 1) over them (mix_rows), two blocks attending across the tokens, txt_in +DiT 28 single-stream blocks over [text | image]; gqa 48 query heads to 12, a sigmoid output + gate, q and k RMS-normed, three-axis rotary (text at the origin, an image token at + (0, row, column)); six modulation rows a block = ONE timestep projection shared by all + blocks + each block's learned table (table_add), gates without tanh +norms every RMS norm zero-centred: the gain is 1 + w, in f32 +VAE Qwen-Image's (Wan 2.1's causal 3-D convolutions on one frame), 16 channels at 8x; a token + is 2 x 2 latents (64 values), 16 pixels a side +schedule Raw: 28 steps, the resolution-shifted schedule of its scheduler config, guidance 4.5 in + the card's terms against an empty negative prompt; Turbo: 8 steps at a fixed shift + (mu 1.15), no guidance. Raw or Turbo is read from the pipeline and scheduler config +``` + +Traps: + +- **Guidance is in the card's terms**: `cond + s (cond - uncond)`, which the core runs as + `uncond + (s + 1)(cond - uncond)` (RadGenDecl::cfg_original). Read as diffusers' usual + `uncond + s (...)` the picture is under-guided by one. +- **The taps are layer outputs, not inputs.** `hidden_states[i]` is the output of layer i - 1; + an off-by-one shifts all twelve and gives a plausible, wrong picture. +- **The text rows are a token's twelve taps, then the tokens.** The first two fusion blocks attend + within a token (twelve rows), the last two across tokens; swapping the order of the rows swaps + which attention sees what. + +Against diffusers' pipeline in bf16 on a tiny random-weight pipeline of the same layout (256x256, +from the same latents, mean absolute difference in 8-bit levels): Turbo 0.6, Raw guided 2.2 in an +all-bf16 container. Block fp8 moves the random model's Raw picture by 8.5 levels, which is the +quantisation's: the container's codes decoded to bf16 on the host give the same picture. + +--- + +# `flux3`: FLUX.3 [klein] and its base, an image generator and editor + +`arch/flux3` declares a JOINT_STEP generator over three modes: the text, the reference pictures' +latents and the image. The conditioning pass leaves each lane's text rows (after +`context_embedder`) and reference rows (VAE-encoded by the generator's own encoder and embedded) in +its store; every step runs the three modes' early blocks and then the joint blocks. Served on +`/v1/images/generations` and `/v1/images/edits` with up to ten reference pictures. + +``` +text Qwen3-VL-4B-Instruct's language model over the prompt in its chat template, right-padded + to a multiple of 80 tokens; the padding takes part (each padding token at position 1, + attending to the prompt alone: attn_cross with valid_cu); EIGHT taps hidden_states[4, 8, + .., 32] side by side, 20480 values a token, through context_embedder +DiT parallel blocks, h += gate (attn(n) + mlp(n)), n a LayerNorm without affine times + (1 + scale) plus shift; 5 early blocks a mode, each mode on its own, then 28 joint blocks + over [text | pictures | image] an entry; each mode its own modulation (text and pictures + at t = 0, the image at the step's), separately for the early and the joint blocks +rotary four axes (t, h, w, l): text along l, the image at (0, h/2, w/2, 0), reference k at + l = -(1 + k) +flow map the step-distilled release adds the embedding of the time the step goes TO to every + mode's timestep embedding (transformer config flow_map) +VAE FLUX.2's: 32 channels at 8x, GroupNorm(32) and a single-head mid-block attention; a token + is 2 x 2 latents (128 values), normalised by the VAE's BatchNorm running statistics + (chan_stats with var 1: sqrt(running_var + eps)) +schedule [klein]: 16 steps, no guidance; base: 50 steps, guidance 3.5 against an empty negative + prompt; both a constant shift of 6.93 +refs at most ten, each shrunk (never enlarged) to 1024 x 1024 pixels of area +``` + +Traps: + +- **The padding is part of the prompt.** The pipeline pads to a multiple of 80 and the padding + tokens' states reach the DiT; dropping them, or letting them attend to each other, changes every + text row the image attends to. +- **GroupNorm over 128 channels in 32 groups** is four channels a group, which group_norm runs at + 4-channel chunks; a kernel that needs 8 refuses the VAE. +- **The prompt upsampler is not run.** diffusers' modular pipeline can rewrite the prompt with a + separate LLM first; radiance reads the prompt as given, as the pipeline does with that block + removed. + +Against diffusers' modular pipeline in bf16 on a tiny random-weight pipeline of the same layout +(256x256, from the same latents, mean absolute difference in 8-bit levels, GPU): [klein] 1.17, the +base guided 2.30, an edit with one reference picture 1.16. + +--- + # `qwen3asr`: speech to text `model_type: qwen3_asr` (`Qwen3ASRForConditionalGeneration`), served from the checkpoint as it @@ -1207,3 +1305,97 @@ output denormalised, folded back into patch rows (patch_fold), then the video The node runs the network on whole clips here (its temporal chunking is off in the example workflows); every rank runs it whole, its weights in VRAM on each. + +--- + +# `ltx2`: LTX-2.5, video with sound + +`arch/ltx2` declares a video generator (`rad_declare_video_generator`, schedule form 1) on the +passes of `core/gen/video_driver.h`: VCOND once per request (the text encoder over the prompt and +the negative prompt, the connectors into the lane's text rows, the first frame encoded for image to +video), VSTEP once per evaluation, VDECODE and ADECODE once per video, VUPSCALE between the two +stages of the distilled recipe. Served on `/v1/videos` ([GUIDE §5.16](GUIDE.md)), one card, bf16 or +block fp8. The checkpoint is the diffusers `LTX2Pipeline` directory, with `latent_upsampler/`, +`duration_head/` and `diffusion_decoder/` read when they are there. + +``` +text Gemma 4's language model over "{prompt}" (no template), LEFT-padded to 1024 + rows; every layer's output is kept (the embeddings, each layer's but the last, the final + norm of the last), each RMS-normed per layer and flattened channel-major per token. + Gemma 4 scores q.k at scale 1: the q and k norms' gains carry the 1/sqrt(head_dim) +connector per modality a projection of that stack to its width (video 4096, audio 2048), the + 1024 rows past the prompt's tokens filled from 128 learnable registers, eight + bidirectional blocks with a split rotary over the row index +DiT 48 dual-stream blocks: video 4096 (32 x 128) over 1 x 1 patches of 128 channels (32 + pixels a latent, 8 frames a latent frame + the first), audio 2048 (32 x 64) over 25 + latents a second (8 channels x 16 mel bins); a block's video stream runs self-attention, + cross-attention to its text, attention to the soundtrack and a feed-forward, the + soundtrack's the same against the video; every attention gated per head + (2 sigmoid(logit)), q and k RMS-normed across all heads; per-block tables + the step's + timestep projection (table_add), the cross-modal ones shift-first +rotary split over (t, y, x) at the patches' MIDPOINTS for the video, the time midpoint for the + audio (rope_split, max 20 2048 2048 and 20) +guidance up to four evaluations a step -- the prompt, the negative prompt, the prompt with block + 28's self-attentions bypassed (STG), the prompt without the cross-modal attentions -- + combined on the clean estimates with a rescale (ltx_guide); base defaults video + (cfg 3, stg 1, modality 3, rescale 0.7), audio (7, 1, 3, 0.7); distilled: one, unguided +VAE causal 3-D decoder, four up blocks of residual blocks with depth-to-space and + PerChannelRMSNorm (pixel_norm div), 4 x 4 pixel patches out; a frame larger than + 960 x 544 in diffusers' tiles (16 latents every 14: tile_grid, tile_crop, a tile store, + tile_stitch's blends to bytes), a smaller one whole; its encoder takes the first frame + for image to video +ddec the diffusion decoder, a request's `decoder` "diffusion": the latent with its last frame + twice more (NATTEN's border needs them), stages of 4 6 4 2 neighbourhood-attention blocks + (2048 1024 512 512 wide, windows 3x7x7 3x7x7 3x5x5 3x5x5, pre-norm, a 3-D gptj rotary + over the voxel coordinates in 8 12 12 pairs, SwiGLU 4x) with pixel-shuffle upsamples + (1x2x2, 2x1x1, 2x2x2, 2x2x2); the first three over the whole video, then per tile of the + feature grid (_tile_intervals: 96 cells every 88, 40 every 28) the fourth and one x0 step + at timestep 1 from the seed's noise (stream 2 + the tile) over 4 x 4 pixel patches: 8 + diffusion blocks of 256 (11x11x11 windows) conditioned on the fourth stage's output, the + norms modulated by the timestep's shared table plus each block's own, each attending a + head at a time (one head's q|k|v is a quarter of all four's); tile_stitch blends the + tiles' overlaps into the frames +audio a causal 2-D decoder to a stereo log-mel spectrogram at 16 kHz, a BigVGAN vocoder to 16 + kHz, a bandwidth extender (its own vocoder over the waveform's log-mel spectrogram plus a + sinc-resampled skip, bwe_up) to 48 kHz; the vocoders in f32 +length the duration head (VCOND, when the container has it): each connector's prompt rows + projected to 256 with a modality embedding, one learned query over all 2048 (four heads + of 64, no mask), a tanh-GELU MLP to ln(seconds) -- read back by the core, which shapes a + request that named no length from it (RadVideoGenDecl::duration_out) +schedule base: 30 steps of FlowMatchEuler, exponential dynamic shift 0.95..2.05 over 1024..4096 + tokens, shift_terminal 0.1; distilled: its 8 trained sigmas (1.0 .. 0.421875), and with + the upsampler the two-stage recipe -- the 8 at half size, the latent upsampler, both + latents re-noised to 0.909375 with stream 1 of their seeds (flow_renoise), the stage-2 + sigmas 0.909375, 0.725, 0.421875 at the full size +``` + +Traps: + +- **The noise is radiance's.** The video's latent is stream 0 of the seed in packed (f, y, x) + order; the soundtrack's the seed with its top bit flipped; the second stage's re-noise is stream + 1 of each. Parity against diffusers means handing it the same tensors: the latents, and for the + first-frame pipeline and the re-noise its `randn_tensor` patched to return them. +- **A distilled schedule is read as given.** diffusers stretches explicit sigmas to a scheduler + config's `shift_terminal`; a distilled pipeline whose scheduler config kept the base model's 0.1 + would run different sigmas there, and the plugin runs the trained ones. +- **The vocoder's dilations are nested lists** (`[[1, 3, 5], ...]`); the metadata reader flattens + them row-major. Dropped, every resnet runs at dilation 1 and the soundtrack is noise. +- **The first frame goes through H.264 at CRF 18 before the encoder**, as the pipeline does for + LTX-2.5 (33 for the Gemma 3 generations). In the two-stage recipe the first frame of the + UPSCALED latent is the one kept clean, as diffusers' image pipeline keeps it, not a re-encode + at the full size. +- **A tile's crop reads the latent after earlier tiles have decoded.** The buffer planner orders + liveness by declaration, which has one crop before the decoder; the latent is a persistent buffer + so the decoder's scratch cannot take its memory between tiles. Before that, every tile but the + first decoded garbage and the first one partly. +- **The MP4 is not a parity instrument.** H.264 at CRF 18 in yuv420p moves a random-weight + model's frames by about 40 levels on its own; compare the frames before encoding (the op + oracle's patch_pix8 output). + +Against diffusers' pipelines in bf16 on a tiny random-weight pipeline of the same layout (256x256, +17 frames, from the same latents), the first frame's row sums agree to within 0.2% at 2 unguided +and 4 guided steps, for image to video, single-stage distilled and the distilled two-stage recipe +with and without a first frame; diffusers on CUDA and on the CPU differ from each other by up to 0.1%. +On an R9700 (libr4d) the same five renders land within 0.15% of diffusers' CUDA rows, every op +agreeing with its host reference under the op oracle. Block fp8 moves the random model's rows by +0.2 to 0.4% (the card's fp8a8 GEMMs, the CPU's fp8 codes widened to bf16). diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 9df15ae7..99f58bb1 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -130,19 +130,26 @@ the cards the engine runs on. | `flashnext-tp1.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | The same on one card: a 42 GiB pinned host pool for the experts that do not fit, 4096-token prefill steps, 4 sequences | | `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server | | `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 | +| `ornith-1.5-35b-a3b.yaml` | `ornith-1.5-35b-a3b-fp8.rad` | Ornith-1.5-35B-A3B, FP8, MTP, vision | | `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower | | `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower | | `qwen3.8-27b-paro.yaml` | `qwen3.8-27b-paro-int4.rad` | Qwen3.8-27B ParoQuant int4 (learned rotations) with its DFlash2 drafter and vision tower, on one card; the int5 and MXFP4 containers serve from it too | | `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 | | `gemma4-31b-w4a8.yaml` | `gemma4-31b-w4a8.rad` | Gemma 4 31B, int4 trunk with int8 activations, its assistant head as the MTP drafter, vision tower | +| `gemma4-31b-heretic-ara-w4a8.yaml` | `gemma4-31b-heretic-ara-w4a8.rad` | The same for Gemma 4 31B heretic-ara (refusals removed) | +| `translategemma-27b.yaml` | `translategemma-27b-mxfp4-gptq.rad` | TranslateGemma 27B MXFP4 with its chat template (`gemma3.jinja`) | +| `glm53-flash.yaml` | `glm53-flash-mxfp4.rad` | GLM-5.3-Flash, MXFP4 experts and block-FP8 attention, on eight cards | | `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter | | `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter | | `embeddinggemma2.yaml` | `embeddinggemma2-bf16.rad` | EmbeddingGemma 2 in bf16: text, image, video and audio embeddings on one card (`RADIANCE_GPU`) | | `qwen-image-2.1.yaml` | `qwen-image-2.1-fp8.rad` | Qwen-Image 2.1 as block fp8 on two cards: OpenAI's images API, generation and edits | | `qwen-image-2.1-turbo.yaml` | `qwen-image-2.1-turbo-fp8.rad` | Qwen-Image 2.1 Turbo, the same in 8 steps | +| `krea-2-turbo.yaml`, `krea-2-raw.yaml` | `krea-2-turbo-fp8.rad`, `krea-2-raw-fp8.rad` | Krea 2 Turbo and Raw as block fp8: text to image on one card (`RADIANCE_GPU`) | +| `flux-3-klein.yaml` | `flux-3-klein-fp8.rad` | FLUX.3 [klein] as block fp8: generation and edits on one card (`RADIANCE_GPU`); the base container serves the same way | | `qwen3-asr-1.7b.yaml` | `Qwen3-ASR-1.7B-hf/` (the checkpoint) | Qwen3-ASR 1.7B: `/v1/audio/transcriptions` and live `/v1/realtime`, on one card (`RADIANCE_GPU`) | | `minimax-h3.yaml` | `minimax-h3-fp8.rad` | MiniMax-H3 as block fp8: video with its stereo soundtrack on `/v1/videos`, two cards and about 39 GiB of pinned host memory | | `fasth3.yaml` | `fasth3-8-step-v2-fp8.rad` | FastVideo's FastH3 8-Step V2, the same in eight steps | +| `ltx-2.5.yaml` | `ltx-2.5-distilled-fp8.rad` | LTX-2.5 distilled as block fp8: video with its stereo soundtrack on `/v1/videos`, one card (`RADIANCE_GPU`), the text encoder in pinned host memory; the base container serves the same way | | `minimax-music3.yaml` | `minimax-music3-bf16.rad` | MiniMax-Music3 in bf16: songs from lyrics and a description on `/v1/audio/speech` | | `breeze-tts2.yaml` | `breeze-tts2-bf16.rad` | Breeze-TTS-2 in bf16: speech on `/v1/audio/speech` and live over `/v1/audio/speech/stream`, on one card (`RADIANCE_GPU`) | @@ -163,7 +170,7 @@ docker compose -f flashnext.yaml down # stop ``` Every model listens on the same port and most take both cards (`flashnext-tp1.yaml`, -`qwen3.8-27b-paro.yaml` and `embeddinggemma2.yaml` take one), so run one at a time: `down` one -before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and +`qwen3.8-27b-paro.yaml` and the files that read `RADIANCE_GPU` take one, `glm53-flash.yaml` +eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and the dashboard page answer without the API key, and the health check fetches `/health` with busybox's `wget`. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index d3b45689..cad2fee6 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -276,9 +276,13 @@ and runs. | `lfm2_bf16` | LiquidAI LFM2 and LFM2-VL in bf16, including d1 (§5.13) | | `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) | | `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) | +| `krea2` | Krea 2 Raw and Turbo, an image model from text (§5.6) | +| `flux3`, `flux3distilled` | FLUX.3 [klein] and its base, an image model that also edits (§5.6); one plugin under the two names the releases give themselves | | `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) | | `minimaxmusic3` | MiniMax-Music3, songs from a description and lyrics (§5.15) | | `breeze` | Breeze-TTS-2, speech from text and an optional description of the voice (§5.15) | +| `minimaxh3` | MiniMax-H3 and FastH3, video with its stereo soundtrack from text (§5.16) | +| `ltx2` | LTX-2.5, video with its stereo soundtrack from text or a first frame (§5.16) | **4. Falling back to the reference library is fatal.** If any op resolves to `libref`, the engine refuses to start and names the ops, because serving from it is orders of magnitude slower with nothing @@ -393,6 +397,27 @@ rad-convert /srv/models/Qwen/Qwen-Image-2.1 -o qwen-image-2.1-fp8.rad \ rad-convert /srv/models/Qwen/Qwen-Image-2.1-Turbo -o qwen-image-2.1-turbo-fp8.rad \ --recipe data/recipes/qwen-image-2.1-fp8.recipe +# Krea 2 Raw or Turbo, and FLUX.3 [klein] or its base, image models (§5.6): the diffusers pipeline +# directory; fp8 blocks for the text encoder and the DiT. Krea 2 takes a recipe either way (or +# krea-2-bf16.recipe), since the release stores its embedders and modulations f32 +rad-convert /srv/models/krea/Krea-2-Turbo -o krea-2-turbo-fp8.rad \ + --recipe data/recipes/krea-2-fp8.recipe +rad-convert /srv/models/black-forest-labs/flux-3-image-klein -o flux-3-klein-fp8.rad \ + --recipe data/recipes/flux-3-klein-fp8.recipe + +# LTX-2.5, video with sound (§5.16): the diffusers pipeline directory, latent_upsampler/ included +# for the distilled release's two-stage recipe; fp8 blocks for the text encoder, the connectors and +# the DiT, or bf16 (both recipes keep the vocoders f32, which they run in) +rad-convert /srv/models/Lightricks/LTX-2.5-Diffusers -o ltx-2.5-fp8.rad \ + --recipe data/recipes/ltx-2.5-fp8.recipe +# Its full (SFT) DiT, transformer_full/, is guided and takes the base schedule back: a folder whose +# transformer/ links to it, and the scheduler's shifting turned on as the release's README does +mkdir ltx-2.5-full && ln -s /srv/models/Lightricks/LTX-2.5-Diffusers/* ltx-2.5-full/ +rm ltx-2.5-full/transformer ltx-2.5-full/transformer_full +ln -s /srv/models/Lightricks/LTX-2.5-Diffusers/transformer_full ltx-2.5-full/transformer +rad-convert ltx-2.5-full -o ltx-2.5-full-fp8.rad --recipe data/recipes/ltx-2.5-fp8.recipe \ + --set scheduler.use_dynamic_shifting=1 --set scheduler.shift_terminal=0.1 + # MiniMax-Music3, songs (§5.15): the diffusers pipeline directory is the checkpoint (language model, # depth decoder, condition encoder, DiT, vocoder, tokenizer); bf16 throughout (21 GB, one card or two) rad-convert /srv/models/MiniMaxAI/MiniMax-Music3 -o minimax-music3-bf16.rad \ @@ -729,9 +754,10 @@ are first-seen, so steps wait on the drive. `ram` copies the table into host mem so a step has no host work. `vram` puts all of it on every card. `ram` needs the table's size free after the pinned host pools and the prefix cache's host tier, with `--host-headroom-mib` to spare (default 4 GiB), under every memory cgroup the process sits in, and refuses the start otherwise. -`auto` takes the first of `vram`, `ram` and `disk` that holds the table. Without a device kernel for the gather (no libr4d) the table is -read on the host: `vram` is refused, and `ram` is a copy in locked huge pages, which also needs a -memlock limit that large (`--ulimit memlock=-1` in Docker, `LimitMEMLOCK=infinity` under systemd). +`auto` takes the first of `vram`, `ram` and `disk` that holds the table. Without a device kernel +for the gather (no libr4d) the table is read on the host: `vram` is refused, and `ram` is a copy in +locked huge pages, which also needs a memlock limit that large (`--ulimit memlock=-1` in Docker, +`LimitMEMLOCK=infinity` under systemd). **`--weights-disk-tier`** serves a model larger than the card and the host pool together, with every step paced by the drive. A routed expert that fits neither lives only in the container. Before each @@ -792,8 +818,10 @@ widths. `fp8_v4` and `k6_v4` narrow the trunk's attention cache further, in groups of 32 dimensions with an f16 scale each: `fp8_v4` keeps K in E4M3 and stores V as int4, `k6_v4` stores K as int6 too. A token then costs 25/32 or 22/32 of what fp8 costs, and a drafter's cache stays fp8. libr4d has their -kernels for Qwen3.8-27B's attention (head_dim 256, gqa 6), so the plugin offers them there and the -server refuses them, naming the plugin, anywhere else. On two R9700s at the serve flags of +kernels for Qwen3.8-27B's attention (head_dim 256, gqa 6) and Qwen3.8-Flash-Next's (head_dim 256, +gqa 12 over 4-token pages, gqa 6 a rank at four ranks), so `qwen35_fp8` and `qwen4exp_fp8` offer +them there and the server refuses them, naming the plugin, anywhere else. Flash-Next's QSA indexer +keeps its own key cache, so its share of a token does not shrink. On two R9700s at the serve flags of `qwen3.8-27b-mxfp4.yaml` with `--max-num-batched-tokens 2048` and 12 GiB a card left to another engine, against the bf16 model on 17 long log-analysis documents (60 368 scored positions): @@ -1229,6 +1257,13 @@ radiance --model m.rad --chat-template-kwargs @template-vars.json startup with the template's message. - `/tokenize` renders `messages` with the same variables. +**System messages.** Many templates raise unless a conversation has one system message, first; the +Chat Completions API allows any number anywhere. A conversation the template refuses that has a +system message after the first message, or more than one, is rendered again with its system +messages merged, in order and separated by a blank line, into one at the head; the first such +request logs a warning. Anything else a template refuses is a 400 on `messages` in the template's +own words. + **`--reasoning-effort`** is the default for chat requests that set none, passed to the chat template verbatim, so the legal set is the template's. Qwen3.8 takes `xhigh|medium|low` and defaults to `xhigh`, which on a short task can spend the whole token budget inside `` and return empty @@ -1345,7 +1380,7 @@ still verified by the adapter, so output is exact and only the acceptance rate c | flag | default | | |---|---|---| | `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card | -| `--kv-cache-dtype T` | bf16 | `bf16`, `fp8`, or on Qwen3.8-27B `fp8_v4` or `k6_v4` (§4.4) | +| `--kv-cache-dtype T` | bf16 | `bf16`, `fp8`, or on Qwen3.8-27B and Qwen3.8-Flash-Next `fp8_v4` or `k6_v4` (§4.4) | | `--host-pool-mib N` | 0 | pinned host tier (weights) | | `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3) | | `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card (§4.3) | @@ -1721,7 +1756,7 @@ becomes up to 280 tokens by default (`--image-tokens`, or a request's `image_tok `document`, `Retrieval-query`, `STS`, ...) and applies to text and content-part inputs; a model that states a default prompt applies it when the request names none. -**An image model** (Qwen-Image 2.1 or 2.1-Turbo) serves OpenAI's images API only; completions, chat +**An image model** (Qwen-Image 2.1 or 2.1-Turbo, Krea 2, FLUX.3 [klein]) serves OpenAI's images API only; completions, chat and embeddings answer 501. OpenAI images clients (Open WebUI, the OpenAI SDKs) work unchanged; the picture always comes back in the response. The engine sizes the step, batch and context for an image model itself (`--max-num-batched-tokens` and `--max-model-len` from the model's largest pass, @@ -1785,6 +1820,15 @@ area (its latent rows replace its vision tokens). One card holds the fp8 contain container. A request the cache can never hold is a 400 naming the rows it needed. The models are under Qwen's research license, non-commercial. +**Krea 2 and FLUX.3 [klein]** take the same fields with their own defaults. Both make RGB pictures +(`background: transparent` is a 400), 1024x1024 by default, sides rounded down to multiples of 16, +up to 2048x2048 (16384 latent tokens). Krea 2 Raw runs 28 steps at guidance 4.5 against an empty +negative prompt and Turbo 8 steps unguided; Krea 2 reads only text, so `/v1/images/edits` answers +501. FLUX.3 [klein] runs 16 steps unguided and its base 50 at guidance 3.5; both edit from up to ten +pictures, each shrunk to 1024x1024 of area when larger. The guidance scale is `guidance_scale` or +`true_cfg_scale` (one of them), in the model card's terms. FLUX.3's pipeline can rewrite a prompt +with a separate language model first; radiance reads the prompt as given. + ### 5.7 Request fields | field | notes | @@ -1912,8 +1956,12 @@ llama-server (`chat_template_kwargs`, `top_k`, ...). The answer is a response ob stream with every event's `output_index`, `content_index` and `sequence_number`, opening with `response.created` and `response.in_progress` at once, as OpenAI's and vLLM's do: they report the response object, not output. A reply cut at -`max_output_tokens` is `incomplete`. Function tools are offered to the model; built-in tools (web -search, file search, computer use) and freeform custom tools are left out, as in llama-server. +`max_output_tokens` is `incomplete`. Function tools are offered to the model, and so are the +function tools a `namespace` groups (Codex sends every MCP server's tools that way), named +`__`: the reply's `function_call` item carries `namespace` and `name` apart, and a +`function_call` input item or a `tool_choice` naming a namespace is joined back the same way. Two +tools that would share a name are refused. Built-in tools (web search, file search, computer use) +and freeform custom tools are left out, as in llama-server. Responses are not stored, so `previous_response_id` is refused: send the conversation as `input`. What a response object cannot carry is refused: `n` other than 1, and logprobs (`include` naming `message.output_text.logprobs`, `top_logprobs`, `logprobs`, `n_probs`), which @@ -2362,7 +2410,7 @@ and the session goes on. ### 5.16 Video: `/v1/videos` -A video generation model (MiniMax-H3) answers OpenAI's video jobs: `POST /v1/videos` queues a video +A video generation model (MiniMax-H3, LTX-2.5) answers OpenAI's video jobs: `POST /v1/videos` queues a video with its stereo soundtrack and answers at once with the video object; `GET /v1/videos/{id}` reports its `status` (`queued`, `in_progress`, `completed`, `failed`) and `progress` (0 to 100); `GET /v1/videos/{id}/content` downloads the MP4 once it is completed (`?variant=thumbnail` gives the @@ -2427,6 +2475,54 @@ The MP4 holds H.264 video (yuv420p, BT.709) and AAC audio at 32 kHz stereo. A fi for an hour (`expires_at`), at most 32 of them. MiniMax-H3's license excludes use in the EU, the UK, the Republic of Korea and the USA without a separate license from MiniMax. +**LTX-2.5** takes the same jobs with its own limits, and starts from a picture as well as from text: + +```sh +radiance --model ltx-2.5-fp8.rad --vision-tower-placement ram + +# image to video: the picture is the first frame (a file in the form, or a data: URL in JSON) +curl -s http://localhost:8000/v1/videos -F 'prompt=the fox turns and runs into the trees' \ + -F 'size=768x512' -F 'seconds=5' -F 'input_reference=@fox.png' +``` + +- **`prompt`** is read as written (no template), at most 1024 tokens; **`negative_prompt`** is + what guidance steers away from, empty by default. +- **`seconds`** is rounded up to steps of 8 frames at 24 a second, from 17 frames (0.71 s) to 161 + (6.7 s). Left out (or `"auto"`), the release's duration head chooses the length the prompt + implies, as diffusers does when `num_frames` is omitted: its prediction held to 1 to 20 seconds, + rounded to frames and down to the 8-frame steps, then to the 161 frames this server makes. The + video object says `"seconds": "auto"` until the prompt is read, then the length chosen. A + container without the head makes 121 frames (5.04 s). **`size`**: both sides multiples of 32 from 256, at most + 1920 x 1088 pixels of area, at most 3:1; 960x544 by default, the release's own. A step carries at + most 121 frames at 1920x1088 (a longer video at that size is refused). Up to 960 x 544 of area + the VAE decodes each frame whole, as the pipeline does by default; a larger frame is decoded in + diffusers' tiles (`vae.enable_tiling()`: 512 pixels every 448) and blended where they overlap, + as the release's two-stage README does at 1920x1088. +- **`input_reference`** is the first frame, resized and cropped to `size` and put through H.264 + at CRF 18 first, as the model was trained. +- **`decoder`** picks how the latents become frames: `vae` (the default, the convolutional VAE that + diffusers' LTX2Pipeline decodes with) or `diffusion`, the release's diffusion decoder (the + README's "Decode with the diffusion decoder"): four stages of neighborhood-attention blocks, then + one denoising step from noise over 4 x 4 pixel patches, run in its own tiles (768 pixels every + 704, 80 frames every 56) as diffusers' `enable_tiling()` runs it. It draws its noise from the + request's seed, so a seed repeats its video. Frames of at most 960 x 544 of area. +- The base model runs 30 steps (`num_inference_steps`, at most 64), each up to four evaluations: + **`guidance_scale`** against the negative prompt, **`stg_scale`** against the model with block + 28's self-attentions bypassed, **`modality_scale`** against the model without its cross-modal + attentions, and **`guidance_rescale`**, by default 3, 1, 3 and 0.7 for the video. The + soundtrack's own four are the same fields prefixed `audio_` (7, 1, 3, 0.7). A scale of 1 (0 for + `stg_scale`) drops its evaluation, so `{"guidance_scale": 1, "stg_scale": 0, "modality_scale": + 1, ...}` runs one evaluation a step. +- The distilled release runs its 8 trained steps unguided, and only those; with its latent + upsampler in the container, **`latent_upscale`** 2 (sides multiples of 64) runs them at half the + size, enlarges the clean latent, re-noises it and refines at the full size in 3 more. `size` is + the output's: the release's README recipe is `"size": "1920x1088", "latent_upscale": 2` (its first + stage at 960x544). + +The MP4's soundtrack is 48 kHz stereo. LTX-2.5 runs on one card; `--tp` above 1 is refused. Its +Gemma 4 text encoder (13 GiB in fp8) does not fit a 32 GB card beside the DiT: serve it with +`--vision-tower-placement ram`, which keeps it in pinned host memory and reads it once a prompt. + ## 6. Operation ### 6.1 The dashboard @@ -2464,18 +2560,13 @@ take twice as long as its neighbour — so nothing is compared until 32 have bee averaged. A single slow step moves neither figure. The percentage, `now X% of best`, is the page's own live window read against the -floor. `now` is the mean of the steps that completed in the last poll (~500 ms); -the figure is that mean as a fraction of `best`, so ~99% is the fastest the lane -has done and anything slower reads a percentage of it (a step at 80% of the -floor's speed reads "80% of best"). It is capped at ~99, shown with a tilde: `now` is a ~500 ms mean -while `best` is a 32-step window mean, so a fast stretch shorter than a window can -read faster than the recorded floor. That is "at your best", not a new record — -the engine only lowers `best` on a completed 32-step window, and a sub-window blip -is not one. The cap is 99 rather than 100 because a 500 ms window that briefly beats the floor is -not a sustained record; 100% would claim a floor the window cannot confirm and would read as a -bug, while ~99% says "at your best" without overclaiming. At higher concurrency the figure is keyed to that concurrency (`@c8`) -and read against the fastest step seen at that concurrency, because a batched step -is a different measurement and would report a batch arriving as a slowdown. +floor: the mean of the steps that completed in the last poll (~500 ms) as a +fraction of `best`, so a step at 80% of the floor's speed reads "80% of best". A +fast stretch shorter than a window can beat the 32-step floor without being a new +record, so the figure is capped and the fastest reads `~99%`. At higher +concurrency it is keyed to that concurrency (`@c8`) and read against the fastest +step seen there, because a batched step is a different measurement and would +report a batch arriving as a slowdown. The gap between them is normal, and it is not degradation. `best` is the most favorable moment the lane has hit; `recent` is what it is doing now. On a healthy @@ -2657,7 +2748,7 @@ is the part of a log to paste into an issue. Its sections: warning is also printed as a `W` line of its own. ``` -I STARTUP REPORT -- radiance 1.8.1 +I STARTUP REPORT -- radiance 1.9.0 I CONFIGURATION -- every option, the value in force, and where it came from I --model /models/flashnext.rad [command line] I --tp 2 [command line] @@ -2754,8 +2845,6 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_CALIB_DIR` | where an engine run writes calibration data for a recipe's `gptq calib=DIR` | | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | | `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | -| `RADIANCE_GLM_TP_SPLIT_ROWS` | `arch/glm5next` under tensor parallelism: the pass height from which the router, the index head gates and the mHC projection split their f32 work over the ranks and gather it, bit-identical to the replicated form (default 256; `0` or a value that does not parse never splits) | -| `RADIANCE_GLM_ROUTER_FUSE`, `RADIANCE_GLM_SWIGLU_QUANT`, `RADIANCE_GLM_GATHER_INVERSE` | `arch/glm5next`'s MoE decode fusions, each byte-identical to the launches it replaces: unset, empty or `1` on, `0` off, any other value refuses the start. For comparing, not for deployment (docs/ARCHITECTURES.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) | diff --git a/docs/OPS.md b/docs/OPS.md index 2fe30b51..94348275 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -373,7 +373,7 @@ kernels with its chunk-sum order, so the pair is byte-identical to `mhc_pre` (`r and two from 32, where the weight rows are 16-byte and the residual rows 8-byte aligned; the finish forms the 4x4 mixing on one wave and collapses the row over the workgroup; `mhc_post` at `hc` 4 writes eight columns of every stream a thread on 16-byte rows. Every form gives the bytes -of the scalar kernels it replaces. +of the scalar kernels that serve the rows it cannot read. ### Gemma 4's audio tower @@ -518,7 +518,7 @@ form by `M`, `N` and `K`; on rows that are not 16-byte aligned it takes the 16x6 are byte-identical (`tests/r4d_emu/test_fp8f32.cpp`). The grouped row takes equal-width parity tables (`N_odd = N`, `K_odd = K`), token or sorted activations, and stacked planes or pointer tables, and runs expert-major: a block per (column span, expert) takes every row of its expert, -each element keeping the row-tile form's sequence. +each element keeping the 16x64 tile's sequence. **`group` has different meanings in this table.** A kernel that reads it the other way is wrong, not slow. `libref/ref_quant.cpp` is the definition. @@ -772,6 +772,8 @@ bytes). |---|---|---| | `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` | | `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt `cu_div`/opt `block`/opt `window_right`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` | +| `attn_cross` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `cu_seqlens`, `cu_k` → `out` | +| `attn_na3d` | `M`(range) `head_dim` `kt` `kh` `kw` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `geom` → `out` | | `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` | | `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout | | `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` | @@ -801,6 +803,24 @@ with `window_right = r + 1` (non-causal only: key `j` visible when `i - j < wind `[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read at its row pitch, so a tower's `[q|k|v]` row needs no copy. +**`attn_cross`** is `attn_dense` with each entry's keys a run of their own: entry `s`'s queries +are rows `[cu_seqlens[s], cu_seqlens[s+1])` of `q`, its keys and values rows `[cu_k[s], cu_k[s+1])` +of `k` and `v`, and with `causal` a query sees key `j` of its run when `j <= i`, both counted from +their run's start. A query that sees no key is zero. It is a video's rows reading their prompt +(cross attention), and a padded prompt whose padding rows see only the prompt (`cu_k` the +prompt's rows, `cu_seqlens` the prompt and its padding: every padding row sees every prompt row +and none of the padding, as a masked padding token does in the reference). + +**`attn_na3d`** is 3-D neighborhood attention, NATTEN's `na3d` (LTX-2.5's diffusion decoder). The +rows of `q`, `k`, `v` and `out` are the voxels of the volume `geom` = `(T, H, W)` (i32 on the +device), `(t, i, j)` row-major, each `[rows, heads head_dim]` at its own row pitch (column slices of +a fused projection). A query sees the keys of a `kt x kh x kw` window, each extent at most its axis, +centred on it and shifted inward at the border: along an axis of `L` and window `n` it starts at +`clamp(c - n / 2, 0, L - n)`, so it always holds `n` keys. Per head, in f32: each score the dot over +`d` ascending times `scale` (default `1 / sqrt(head_dim)`), the window's keys in raster order, the +softmax as `attn_cross` takes it, the output rounded to its dtype. Rows past `T H W` are not +written. libr4d serves `head_dim` 64. + **`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a softcap. Query row `i` of a segment sees key rows `j` of the same segment with `0 <= i - j <= left` (`right` must be 0). Per head, `qf = q * (head_dim^-0.5 / ln 2) * softplus(pds)` @@ -918,8 +938,11 @@ The group is declared at `RAD_F8E4M3` with head_dim the row's bytes / 2, so the as it does for fp8, and the cache operand's last extent is the row. The ops take the model's head_dim. libr4d's rows are `kv_store_fp8v4` / `kv_store_k6v4`, `qk_norm_rope_gate_kv_store_fp8v4` / `_k6v4` (byte-identical to the prologue and the store, as at -the other widths), and `attn_prefill_h256_gqa6_{fp8v4,k6v4}` and `attn_decode_h256_gqa6_{fp8v4,k6v4}`, -which widen the codes to f16 in a tile's staging. `r4d_selftest` holds the stores to an exactly +the other widths), `attn_prefill_h256_gqa6_{fp8v4,k6v4}` and `attn_decode_h256_gqa6_{fp8v4,k6v4}`, +which widen the codes to f16 in a tile's staging, and the same kernels at Qwen3.8-Flash-Next's +ratios over 4-token pages: `attn_{prefill,decode,decode_gq}_h256_gqa12_{fp8v4,k6v4}` and +`attn_{prefill,decode,decode_gq}_h256_gqa6_bs4_{fp8v4,k6v4}`, the `decode_gq` rows with the output +gate and quantiser in the split-KV merge. `r4d_selftest` holds the stores to an exactly representable set and the attention rows to its inline oracle. ### `qk_norm_rope_gate` (device-only) @@ -976,6 +999,9 @@ says which (`libref/ref_gen.cpp`). | `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | | `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `dtype` | `t` → `y` | | `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` | +| `table_add` | `M`(range) `n` `L` `dtype` | `x`, `t`w → `y` | +| `mix_rows` | `M`(range) `n` `k` `dtype` | `x`, `w`w → `y` | +| `chan_stats` | `M`(range) `n` `mode` `var`/opt `eps`:f64/opt `dtype` | `x`, `mean`w, `s`w → `y` | | `lane_gather` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `cu_seqlens` → `y` | | `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout | | `randn_lanes` | `M`(range) `n` `stride` `dtype` | `flags`, `seed`, `lane`, `cu_seqlens`, `dst`:inout | @@ -1007,8 +1033,20 @@ source into every listed lane (a repainted picture's latent into each of its ima store would round it, so the bytes are the three ops'. - `timestep_embed`: `[cos | sin]` of `t' * f_i`, `f_i = exp(-ln(max_period) * i / (n/2))` in f32, `t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)`, the value - diffusers' pipeline hands its transformer. `t` is f32 `[M]`. + diffusers' pipeline hands its transformer; with `round` 2, `t' = scale * bf16(t)` (a pipeline + that hands the transformer `t` in bf16 and scales it inside, Krea 2's); with `round` 3, + `t' = bf16(scale * bf16(t))` (the scaling also in bf16, FLUX's). `t` is f32 `[M]`. - `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source. +- `table_add`: `y[r, l n + c] = x[r, c] + t[l, c]` for each of `L` rows of the weight `t` `[L, n]`, + the sum f32 and rounded once: a modulation shared by every block plus each block's own learned + table (Krea 2, LTX-2), every block's rows in one launch, read at `l n` of each `y` row. +- `chan_stats`: a latent through per-channel statistics a VAE keeps as weights, `mean` and `s` + `[n]`: `std` is `s`, or with `var` 1 `sqrt(s + eps)` (a BatchNorm's running variance, FLUX's VAE), + each statistic rounded to `y`'s dtype as the reference casts it; `mode` `denorm` is + `y = rd(rd(x std) + mean)` and `norm` is `y = rd(rd(x - mean) / std)`. +- `mix_rows`: `y[r, c] = sum_i w[i] x[r k + i, c]` over `i < k`, f32 in ascending `i` and rounded + once: a `Linear(k, 1)` across `k` consecutive rows (Krea 2's text fusion folds a token's twelve + tapped encoder layers, laid out as consecutive rows, into one). - `randn_lanes`: for entries whose `flags` carry 1, the lane's rows become the entry's seed's standard-normal stream (`abi/rad_philox.h`), element `(k, c)` the stream's `k * n + c`. `seed` is `[n_seq, 2]` u32, low word first. @@ -1025,7 +1063,8 @@ shapes: an image's size belongs to a request, and a parameter is fixed at declar - `conv2d_nhwc`: `w` is PyTorch's `[cout, cin, k, k]` (a kernel may store it permuted through its layout hook), `b` `[cout]`; `up` 2 reads the input upsampled 2x nearest-neighbour; `pad` `same` is `k/2` zeros a side, `down` is none above and left and one below and right - (`ZeroPad2d((0,1,0,1))` before a stride-2 conv). f32 accumulation, the bias added, one rounding. + (`ZeroPad2d((0,1,0,1))` before a stride-2 conv), `causal` is `k - 1` rows above, none below and + `k/2` columns a side (causal along the rows: LTX-2's audio VAE). f32 accumulation, the bias added, one rounding. - `l2norm_chan`: each pixel's channels to unit L2 (eps 1e-12), times `sqrt(n)`, times `gamma` (three roundings), then `act` `none` or `silu`. - `chan_affine`: `mul` and `add` are space-separated lists of `n` values, each rounded to bf16; @@ -1090,6 +1129,7 @@ libref function says which (`libref/ref_audio.cpp`). | `interleave2` | `M`(range) `dtype` | `a`, `b` → `y` | | `iota` | `M`(range) `start` `step` `period`/opt | → `y` | | `cu_repeat` | `M`(range) `mult` | `len` → `y` | +| `int_affine` | `M`(range) `src` `mul` `add` | `x` → `y` | **Frames.** A lane is one piece; a frame is one step of its language model, whose branches (the conditional first, then the unconditional) are consecutive rows, `rep` of them a lane. @@ -1120,7 +1160,10 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a `status[lane] >= 0` (frame 0 only moves past the prompt; a negative status ended the piece). - `iota`: `y[i] = start + i * step`, or `start + (i % period) * step` with `period` (the positions of equal sequences laid end to end). `cu_repeat`: `y[j] = j * len[0] * mult`, the bounds of equal - sequences whose length lives on the device. + sequences whose length lives on the device. `int_affine`: + `y[j] = (src[j] < 0 ? 0 : x[src[j]]) mul[j] + add[j]` over three lists of integers of one length + (`src` -1 a constant): the shapes and bounds a model derives from a pass's device geometry, such + as a decoder's volume at each of its scales. **Windows.** The denoiser runs over windows of frames, each entry of a window step a lane's latent in a state buffer `stride` rows a lane (`lat_cu` bounds each entry's rows, `win_lane` names its @@ -1194,8 +1237,8 @@ bf16 tensor and keeps f32 where it computes in f32; the libref function says whi | op | params | operands | |---|---|---| -| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `z` | -| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `w`w, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | +| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `z` | +| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? | | `flow_x0_step` | `M`(range) `n` `dtype` | `v`, `t`, `sigma`, `sigma_next`, `x`:inout | | `patch_unfold` | `M`(range) `C` `pt` `ph` `pw` `mul` `add` `dtype` | `x`, `geom` → `y` | | `vtile_gather` | `M`(range) `n` `tile` `overlap` `frames` `period` `n_reg` `dtype` | `x`, `reg`w, `geom` → `y` | @@ -1211,7 +1254,14 @@ reads its entry's rows of `s` and `g`. stored `x`), `n2 = bf16(n1 w)`, `m = bf16(n2 bf16(1 + scale[e]))`, `z = bf16(m + shift[e])`. `s` is `[n_seq, >= 2n]` at its own row pitch, `shift = s[e, 0:n]` and `scale = s[e, n:2n]` (a column slice of the modulation table); `g` is `[n_seq, >= n]` at its own pitch; `w` is `[n]`. - The residual rounds to `x`'s dtype and the norm chain to `z`'s. + The residual rounds to `x`'s dtype and the norm chain to `z`'s. `wadd` is added to the gain in + f32 (a zero-centred norm's `1 + w`), and with `norm_once` 1 the norm and its gain round together, + `n2 = bf16(x rsqrt(mean(x^2) + eps) (w + wadd))`, as an f32 RMS norm with a gain stores its + output (Krea 2's). `norm` `layer` (default `rms`) is a LayerNorm instead: `x` centred by its + mean (an f32 sum in ascending order) and `rsqrt` of the centred values' biased variance plus + `eps`. Without `w` the norm has no gain and rounds once, `n2 = bf16((x - mean) rsqrt(var + + eps))` (FLUX.3's LayerNorm without an affine). `norm` `none` takes no norm and no gain, + `n2 = x`, and refuses `w` (LTX-2's text keys and values, modulated as they are). - `rms_mod_quant_fp8` is `rms_mod` with the norm chain in bf16, then `quant_act_fp8` of that bf16 row per `group` as `ln_mod_quant_fp8` takes it; `z` written when bound. - `flow_x0_step` is MiniMax-H3's sampler step over a lane's rows, all f32, each product and sum @@ -1376,7 +1426,7 @@ pass starts from. Each op rounds once into its output (`libref/ref_video.cpp`). | op | params | operands | |---|---|---| -| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` | `x`, `w`w, `b`w, `geom`, `res`? → `y` | +| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` `tpad`/opt `tpre`/opt | `x`, `w`w, `b`w, `geom`, `res`? → `y` | | `group_norm` | `M`(range) `n` `groups` `eps`:f64 `act` `dtype` | `x`, `w`w, `b`w, `mod`?, `stats`:inout → `y` | | `tconv_dw` | `M`(range) `n` `k` `dtype` | `x`, `w`w, `b`w, `geom` → `y` | | `resize_bilinear` | `M`(range) `n` `dtype` | `x`, `geom` → `y` | @@ -1395,7 +1445,10 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t `y[(t,i,j), o] = rd(f32(sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw] x[(t+dt-kt/2, i+kh-k/2, j+kw-k/2), ci]) + b[o])`, terms outside the volume zero, f32 accumulation in an order of the implementation's (libref: the taps in `(dt, kh, kw)` order, each tap's - channels ascending). With `res`, `y = rd(rd(acc + b) + res)`: the convolution's output rounded, + channels ascending). `tpad` (optional) pads the frames instead with `replicate` (the edge frame + repeated, `kt/2` a side) or `causal` (the first frame repeated `kt - 1` times in front, nothing + after; with `tpre` that many more copies in front, and y then has `T + tpre` frames): LTX-2's + decoder and encoder. With `res`, `y = rd(rd(acc + b) + res)`: the convolution's output rounded, then the residual added and rounded, as a block's `skip(x) + h` in bf16. `res` may be the same memory as `y` (the residual added in place); `x` never aliases `y`. x, y, res and w bf16 (also f32), b bf16 or f32. MiniMax-H3: `k` = `kt` = 3, `(cin, cout)` `(24, 512)`, `(512, 512)`, @@ -1437,6 +1490,134 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t first, `stream` the parameter. `x` f32 `[M, n]` at its row pitch. MiniMax-H3: `n` 96 (the video's patch rows) and 32 (the soundtrack's), `stream` 1. +## LTX-2 + +The ops LTX-2's audio-video transformer adds (`libref/ref_ltx.cpp`): its rotary over fractional +coordinates, the per-head gate on every attention's output, and the sampler step that combines a +step's guidance passes in the clean-estimate space. Each rounds where the reference rounds +(diffusers' `transformer_ltx2.py` and `pipeline_ltx2.py`): the transformer in bf16, the rotary, +guidance and sampler in f32. + +| op | params | operands | +|---|---|---| +| `rope_split` | `M`(range) `n_head` `head_dim` `dim` `n_dims` `theta`:f64 `max` `head0`/opt `dtype` | `x`:inout, `positions` | +| `head_gate` | `M`(range) `n_head` `head_dim` `dtype` | `g`, `x`:inout | +| `ltx_guide` | `M`(range) `n` `dtype` | `vc`, `vu`?, `vs`?, `vm`?, `scales`, `sched`, `stats`:inout, `x`:inout | +| `pixel_norm` | `M`(range) `n` `eps`:f64 `form` `act`/opt `ileave`/opt `dtype` `mult`:f64/opt | `x` → `y` | +| `d2s3d` | `M`(range) `C` `st` `sh` `sw` `drop`/opt `dtype` | `x`, `geom` → `y` | +| `s2d3d` | `M`(range) `C` `st` `sh` `sw` `tpre`/opt `group`/opt `mode` `add`/opt `dtype` | `x`, `geom`, `y`:inout | +| `pix_patch` | `M`(range) `p` `C` `order`/opt `dtype` | `x` → `y` | +| `patch_pix8` | `M`(range) `p` `C` `order`/opt `dtype` | `x` → `y` | +| `stft_logmel` | `M`(range) `hop` `nfft` `n_mel` `ch` `dtype` | `x`, `basis`w, `mel`w → `y` | +| `bwe_up` | `M`(range) `ratio` `ch` `dtype` | `x`, `res` → `y` | +| `vol_index` | `M`(range) | `geom` → `y` | +| `tile_grid` | `M`(range) `tile` `stride` `rule`/opt `min`/opt `tile_t`/opt `stride_t`/opt `min_t`/opt `tail`/opt | `geom` → `y` | +| `tile_crop` | `M`(range) `C` `dtype` | `x`, `geom`, `box` → `y` | +| `tile_stitch` | `M`(range) `tile` `stride` `rule`/opt `min`/opt `tile_t`/opt `stride_t`/opt `min_t`/opt `scale` `scale_t`/opt `p` `C` `order`/opt `dtype` | `x`, `geom`, `first` → `y` | + +- `rope_split` is LTX2AudioVideoRotaryPosEmbed's "split" rotary. Over the full width `dim` of all + heads there are `P = dim / 2` pairs: the first `pad = P - steps n_dims` are not rotated, and the + rest are a frequency ladder `freq[k] = f32(theta^linspace(0, 1, steps)[k] pi / 2)` (f64 before + the cast, torch's linspace), `steps = P / n_dims`, its pairs interleaving the coordinates: pair + `pad + k n_dims + d` turns by coordinate `d` at `freq[k]`. A coordinate `c` gives the angle + `a = f32(f32(2 f32(c / max[d])) - 1) freq[k]`, `max` a list of `n_dims` values. Head `h` owns + pairs `[h hd/2, (h+1) hd/2)` and turns its halves against each other, + `o1 = f32(f32(x1 cos a) - f32(x2 sin a))`, `o2 = f32(f32(x2 cos a) + f32(x1 sin a))`, rounded to + `x`'s dtype. `head0` is the first head the operand holds (a rank's share). `positions` is + `[n_dims, M]`, f32 or integer, at its own strides. LTX-2.5: the video's self-attention `dim` + 4096, `n_dims` 3, `max` `20 2048 2048` (two padded pairs); the soundtrack's and both cross + attentions' `dim` 2048, `n_dims` 1, `max` `20`; the text connectors' `max` 4096 over the row + index. +- `head_gate`: `x = rd(x rd(2 rd(sigmoid(g))))` for each head's `head_dim` values, `g` + `[M, >= n_head]` the head's logit (the gated attention's `to_gate_logits`), each operand at its + own row pitch. +- `ltx_guide` is one sampler step over a modality's latent `x` (f32 `[M, n]`, all of it: the + rescale's deviations are over every value) from its guidance passes' velocities (`[M, n]`, read + as f32), all in f32: + + x0_p = f32(x - f32(v_p sigma)) each pass p + g = x0_c [+ f32(f32(gs - 1) f32(x0_c - x0_u))] [+ f32(stg f32(x0_c - x0_s))] + [+ f32(f32(ms - 1) f32(x0_c - x0_m))] left to right + r > 0: g = f32(f32(r f32(g f32(std(x0_c) / std(g)))) + f32(f32(1 - r) g)) + v = f32(f32(x - g) / sigma), x = f32(x + f32(f32(sigma_next - sigma) v)) + + A bracketed term is taken when its pass is bound and its coefficient is not zero. `std` is the + unbiased deviation over all `M n` values, accumulated in f64. `scales` is f32 `[4]` + `(gs, stg, ms, r)` and `sched` f32 `[2]` `(sigma, sigma_next)`, both read on the device; `stats` + is f32 of at least 8200 values, the implementation's scratch. + +Its VAE, audio VAE and vocoder run in bf16 tensors, and these ops round where those tensors are +stored (`rd`, the output's dtype unless said). + +- `pixel_norm` is an RMS norm over each row's `n` values: `m = rd(sum rd(x^2) / n)` (f32 sum in + ascending order), then `form` `rsqrt` `z = rd(x rd(1 / sqrt(rd(m + eps))))` or `div` + `z = rd(x / rd(sqrt(rd(m + eps))))`, with `act` silu `z = rd(z / (1 + exp(-z)))`, and with + `mult` `z = rd(z mult)` (the connectors' scale to the DiT's width). The VAE's + PerChannelRMSNorm and the audio VAE's PixelNorm are the div form (with the SiLU after them + fused); the text connectors' per-layer norm is the rsqrt form, whose output `ileave` L + interleaves: x's row `t L + l` goes to columns `c L + l` of y's row `t`, as the reference + flattens `[C, layers]`. +- `d2s3d` and `s2d3d` resample voxel rows (`geom` = x's `(T, H, W)`, i32 on the device), the + packed channel of `(c, a, b, d)` being `((c st + a) sh + b) sw + d` (a the frame offset, b the + row's, d the column's). `d2s3d` is the upsampler's depth to space, + `y[(t st + a - drop, i sh + b, j sw + d), c] = x[(t, i, j), packed]`, the first `drop` frames + dropped (by default `st - 1`, the causal mapping; 0 keeps them, as a decoder's tile that does not + start the video does). `s2d3d` is the downsampler's space to depth over the volume with `tpre` leading + frames prepended (frames `0 .. tpre - 1` again): `mode` copy writes the packed row, `mean` + averages each run of `group` packed channels (f32 sum, divided, one rounding); with `add` 1 + `y = rd(y + v)`. `M` is x's rows. +- `pix_patch` and `patch_pix8` are the patchifier both ways over dense 2-D operands whose shapes + give the sizes: a `p x p` patch of `C` channels is one row of `C p p` values, channel `c`'s + `(ph, pw)` at `c p p + pw p + ph` (`order` wh, LTX-2's) or `c p p + ph p + pw` (hw). + `pix_patch` takes an image `[H, W C]` to `[H / p, (W / p) C p p]`; `patch_pix8` takes patch rows + `[R, w C p p]` to RGB bytes `[R p, w p C]` by `to_rgba8`'s rule, + `round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1))`, rd x's dtype. +- `vol_index` writes a volume's voxel coordinates, the rotary positions of attention over it: + `geom` = `(T, H, W)`, `y` i32 `[3, n]` component-major at its own row pitch, voxel + `m = (t H + i) W + j`'s `(t, i, j)` at column `m`, for `m < min(n, T H W)`. +- `tile_grid`, `tile_crop` and `tile_stitch` run a decoder in tiles as diffusers does: LTX-2's VAE + (`tiled_decode`, `rule` `stride`, the default) and LTX-2.5's diffusion decoder + (`_tile_intervals`, `rule` `intervals`). Along an axis of `L` cells a tile starts at every + multiple of `stride` below `L`; under `intervals` an axis of `tile` cells or fewer is one tile, and + while more than one start is left and the last leaves fewer than `min` cells (default 1) that + start is dropped. A tile but the last is `min(tile, L - start)` long, the last runs to `L`. The + same cut with `tile_t`, `stride_t` and `min_t` makes time bands (without `tile_t`, one band of + every frame); tiles are raster-ordered over (time band, row band, column band). `tile_grid` + writes the tiles of the grid `geom` = `(T, H, W)` to `y` i32 `[M, 8]`, row k + `(t, h, w, t0, y0, x0, k, count)`, the last time band `tail` cells longer than its cut (frames a + decoder carries past `T`); rows past the count are zero. A row's `(t, h, w)` is a decoder's volume + operand and its first six entries `tile_crop`'s `box`: `tile_crop` copies the box + `y[(a, i, j)] = x[(t0 + a, y0 + i, x0 + j)]` out of the volume `x` (`geom` its `(T, H, W)`). + `tile_stitch` takes every tile's decoder output back to back in tile order: a cell is `scale` + patches of `p x p` pixels a side and `scale_t` frames (default 1), the video's first cell one + frame, so tile `(kt, i, j)` with cells `[t0, t1)` in time holds `scale_t (t1 - t0)` frames (less + `scale_t - 1` when `t0` is 0) of `(h scale) x (w scale)` rows of patches (`pix_patch`'s columns). + `geom` is the grid the tiles cut, `first` the first frame `y` holds, and `y` RGB bytes + `[n (H scale p), (W scale p) C]`. A frame is the time band whose kept frames hold it (a band but + the last keeps `stride_t scale_t`, the first `scale_t - 1` fewer), a pixel `(Y, X)` the tile + `(Y / s, X / s)` of that band, `s = stride scale p`, the last band of an axis keeping the rest. + With every product and sum rounded to `x`'s dtype and + `mix(a, b, k, e) = rd(rd(a f32(1 - k / e)) + rd(b f32(k / e)))`, a band's picture is diffusers' + in-place `blend_v` with the tile above and then `blend_h` with the tile to the left over + `min(their extents, (tile - stride) scale p)` pixels, the neighbours read as their own blends + left them (libref/ref_ltx.cpp writes the four-tile corner out), and a frame of a band within + `min(their frames, (tile_t - stride_t) scale_t)` of its start is `blend_t` of the band before and + this one; the byte is `patch_pix8`'s. +- `stft_logmel` is each channel's causal log-mel spectrogram (the bandwidth extender's MelSTFT): + `x [S, ch]`, `basis [2F, 1, nfft]` (the windowed DFT, real then imaginary rows, + `F = nfft / 2 + 1`), `mel [n_mel, F]`; frame `t` reads samples `t hop + j - (nfft - hop)`, zero + before the start; `s_k = rd(sum_j basis[k, j] x)`, + `mag_k = rd(sqrt(rd(rd(re_k^2) + rd(im_k^2))))`, + `y[t, h n_mel + m] = rd(log(max(rd(sum_k mel[m, k] mag_k), rd(1e-5))))`; y is `[S / hop, ch n_mel]`. +- `bwe_up` is the extender's output: x `[S, ch]` raised `ratio` times by its Hann-windowed sinc + resampler (width `w = ceil(6 / 0.99)`, `2 w ratio + 1` taps + `rd(sinc(u) cos^2(clamp(u, -6, 6) pi / 12) 0.99 / ratio)` with `u = f32(n / ratio - w) 0.99`, + the input's edges replicated), `up = rd(ratio rd(sum taps x))`, then + `y = clamp(rd(res + up), -1, 1)`; rd is x's dtype, y f32 or x's dtype. + +The VAEs' convolutions are `conv3d_ndhwc` with `tpad` and the audio VAE's `conv2d_nhwc` with +`pad` causal. + ## Mixture of experts | op | params | operands | @@ -1582,9 +1763,9 @@ with `route_scale` 2.5. libr4d's `router_sigmoid_topk_f32` takes up to 512 experts and `top_k` up to 32, f32 logits, bias and weights, i32 ids, pitched rows, `M` up to 65535. It selects in one wave per row: each lane holds its experts as order-preserving keys (`-0` as `+0`, ties to the lower expert), and round `j` -takes the largest key below round `j-1`'s winner. A row without NaN ranks gives the bytes of the -serial scan. A NaN rank is never selected, and a row with fewer than `top_k` other ranks names -expert 0 in its empty slots, weighted by expert 0's `p`. +takes the largest key below round `j-1`'s winner. A row without NaN ranks gives the bytes of a +serial scan with a strict `>`. A NaN rank is never selected, and a row with fewer than `top_k` +other ranks names expert 0 in its empty slots, weighted by expert 0's `p`. **`router_sigmoid_topk_scatter`** (device-only) is `router_sigmoid_topk` and `moe_scatter` over its `ids` in one launch, and with `gate` `[M, 1]` also the `fill` of an ungated shared arm's gate with @@ -1621,8 +1802,10 @@ at this dtype. The form follows the routed rows. The expert-major form, a block expert) that reads each expert slice once, takes up to 511 rows, and at GLM's TP8 slices (288 experts, top 8) gate_up up to 768 and down up to 6143. At those slices the wide prefill form (P64: jobs of 32 or 64 rows of one expert) takes gate_up from 769 rows and down from 5760, ahead of the -expert-major band. Elsewhere the row-group forms serve. Every form gives the bytes of the -arithmetic-decode row-group form (`tests/r4d_emu/test_moemx.cpp`). +expert-major band. At GLM's TP4 slices the GLM prefill form (jobs of 32 rows of one expert, its +loads a stage ahead) takes from 512 rows; elsewhere the row groups (16 sorted rows a block) serve. +Every form gives the bytes of one per-element sequence, restated on the host by +`tests/r4d_emu/test_moemx.cpp`. **`moe_gemm_q_mod4`** is the same GEMM over four classes by the expert's number mod 4. `w`/`w_scale` hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting to `N`, `K`); @@ -1730,12 +1913,12 @@ at most 32 tokens. `mode=prefill` commits its final state and sets the count to scratch slot replays nothing. libr4d's `kda_update_k128_v128_bf16` takes `head_k = head_v = 128`, 1 to 65535 heads, bf16 -activations, f32 `A_log`, `dt_bias` and state, both modes and both state forms. A wave holds one, -two or four value rows of a head (four by default, the next token's operands loaded while the -current one reduces) and runs the sequence's tokens in order; every form gives the bytes of the -one-row kernel (`tests/r4d_emu/test_kda.cpp`). Under `anchor`, `verify` replays the accepted prefix -in a separate dispatch before the window, so no value row overwrites factors another is still -reading. A sequence whose window or slots are out of bounds is skipped on the device, not refused. +activations, f32 `A_log`, `dt_bias` and state, both modes and both state forms. A wave holds four +value rows of a head, loads the next token's operands while the current one reduces and runs the +sequence's tokens in order (held to libref by `r4d_selftest` and `tests/r4d_emu/test_kda.cpp`). +Under `anchor`, `verify` replays the accepted prefix in a separate dispatch before the window, so +no value row overwrites factors another is still reading. A sequence whose window or slots are +out of bounds is skipped on the device, not refused. **Speculative rollback is part of the schema** (`spec.md` §10). The recurrent state and the conv window have already absorbed rejected tokens, so the state cache is a rolling window of @@ -2495,11 +2678,10 @@ it as bf16 high and low parts with f32 accumulation. At a multiple of 16 a tile one query; otherwise it pairs eight heads of two neighbouring queries, loading a key once where both tables name the page, so GLM-5.3's 8 heads a rank fill the tile. The pairing walks the union of the two tables, so each chunk runs once, for tables of up to 520 entries; past that it pairs -by table position, with a second pass where the two differ. -`RADIANCE_MLA_MATRIX_MAX_M` lowers the matrix row's `M` bound (65535 by default); past it the -wave row, `mla_attn_bf16`, serves: a wave per head with an online softmax. Both split a short -batch's history across workgroups and merge the f32 partials before narrowing, into the fixed -scratch their hooks reserve; without scratch they compute unsplit. +by table position, with a second pass where the two differ. Other head counts take the wave row, +`mla_attn_bf16`: a wave per head with an online softmax. Both split a short batch's history across +workgroups and merge the f32 partials before narrowing, into the fixed scratch their hooks +reserve; without scratch they compute unsplit. `mla_project` moves a query into the latent and a latent result out of it, through the bf16 weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows. @@ -2512,8 +2694,8 @@ per-head width. Its rows are head-major, so a tensor-parallel slice of whole hea libr4d's `mla_project_bf16` serves `head_dim` 256 and `latent_dim` 512, up to 64 heads, pitched tensors. It takes up to eight rows a thread (`absorb`) or a wave (`expand`), loading each weight -element once for them, with every row's sum in the one-row kernels' order, so all forms give the -same bytes. +element once for them, with every row's sum in the same order whatever the group, so a row's bytes +do not depend on the batch. ## Draft heads diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index 10e80c3a..3da5c89b 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -54,6 +54,7 @@ set(AVX_KERNEL_SRC avx_gen.cpp avx_gen_attn.cpp avx_video.cpp + avx_ltx.cpp avx_vsa.cpp avx_audio.cpp ) diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index 6ac77d3b..1441048b 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.cpp @@ -1646,3 +1646,181 @@ AVX_KERNEL(qsa_block_key) { } return RAD_OK; } + +/* ------------------------------------------------------------------ attn_cross */ +/* attn_dense with each entry's keys a run of their own (`cu_k`), libref's attn_cross: causal + * counts from each run's start, and a query that sees no key is zero. The same tiled online + * softmax as attn_dense's portable path. */ +AVX_KERNEL(attn_cross) { + if (!rad_args_have(a, 6)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *cuk = &a->t[4]; + const RadTensor *o = &a->t[5]; + const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0); + const int64_t gqa = p_int(a, "gqa", 1); + const int causal = (int)p_int(a, "causal", 0); + if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE; + if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED; + const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2] + : (q->rank == 2 ? q->shape[1] / head_dim : 1); + const int64_t kv_heads = q_heads / gqa; + if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1; + if (n_seq <= 0 || numel(cuk) < n_seq + 1) return RAD_E_SHAPE; + const int64_t total_q = numel(q) / (q_heads * head_dim); + const int64_t total_k = numel(k) / (kv_heads * head_dim); + if (total_q <= 0 || ldi(cu, offlin(cu, n_seq)) <= ldi(cu, offlin(cu, 0))) return RAD_E_SHAPE; /* zero rows */ + if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE; + for (int64_t s = 0; s < n_seq; ++s) + if (ldi(cu, offlin(cu, s + 1)) < ldi(cu, offlin(cu, s)) || + ldi(cuk, offlin(cuk, s + 1)) < ldi(cuk, offlin(cuk, s)) || + ldi(cu, offlin(cu, s + 1)) > total_q || ldi(cuk, offlin(cuk, s + 1)) > total_k) + return RAD_E_SHAPE; + + 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 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 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 = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); + + AVX_PARALLEL_FOR_IF(n_seq * q_heads >= 2) + for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) { + const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa; + const int64_t b0 = ldi(cu, offlin(cu, s)), b1 = ldi(cu, offlin(cu, s + 1)); + const int64_t k0 = ldi(cuk, offlin(cuk, s)), k1 = ldi(cuk, offlin(cuk, s + 1)); + float* frame = (float*)scratch_f32((size_t)(4 * head_dim + AVX_KV_TILE) + 16); + float* qbuf = frame; + float* kbuf = frame + head_dim; + float* vbuf = frame + 2 * head_dim; + float* acc = frame + 3 * head_dim; + float* sbuf = frame + 4 * head_dim; + int64_t vbase[AVX_KV_TILE]; + for (int64_t i = b0; i < b1; ++i) { + const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs; + const int64_t jend = causal ? std::min(k1, k0 + (i - b0) + 1) : k1; + const float* qv = head_f32(q, qb, q_ds, head_dim, 1.0f, qbuf); + for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; + float m = -INFINITY, l = 0.0f; + int ntile = 0; + auto flush = [&]() { + if (ntile == 0) return; + float tmax = sbuf[0]; + for (int t = 1; t < ntile; ++t) if (sbuf[t] > tmax) tmax = sbuf[t]; + if (tmax > m) { + const float r = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax); + if (r != 1.0f) { + for (int64_t d = 0; d < head_dim; ++d) acc[d] *= r; + l *= r; + } + m = tmax; + } + for (int t = 0; t < ntile; ++t) sbuf[t] = sc_exp(sbuf[t] - m); + for (int t = 0; t < ntile; ++t) { + const float w = sbuf[t]; + l += w; + axpy(acc, head_f32(v, vbase[t], v_ds, head_dim, 1.0f, vbuf), w, head_dim); + } + ntile = 0; + }; + for (int64_t j = k0; j < jend; ++j) { + const float* kvr = head_f32(k, j * k_rs + kh * k_hs, k_ds, head_dim, 1.0f, kbuf); + sbuf[ntile] = dotf(qv, kvr, head_dim) * scale; + vbase[ntile] = j * v_rs + kh * v_hs; + if (++ntile == AVX_KV_TILE) flush(); + } + flush(); + if (m == -INFINITY) { + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f); + continue; + } + const float inv = l > 0.0f ? 1.0f / l : 0.0f; + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv); + } + } + return RAD_OK; +} + +/* attn_na3d: libref's neighborhood attention (libref/ref_attn.cpp), the window's keys through + * attn_cross's online softmax. */ +AVX_KERNEL(attn_na3d) { + if (!rad_args_have(a, 5)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *G = &a->t[3], *o = &a->t[4]; + const int64_t head_dim = p_int(a, "head_dim", 0); + const int64_t kt = p_int(a, "kt", 0), kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0); + if (head_dim <= 0 || kt <= 0 || kh <= 0 || kw <= 0 || numel(G) < 3 || q->rank != 2) + return RAD_E_SHAPE; + if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED; + const int64_t heads = q->shape[1] / head_dim; + const int64_t T = ldi(G, offlin(G, 0)), H = ldi(G, offlin(G, 1)), W = ldi(G, offlin(G, 2)); + if (heads <= 0 || q->shape[1] % head_dim || T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; + const int64_t N = std::min(q->shape[0], T * H * W); + if (N <= 0 || numel(k) < N * heads * head_dim || numel(v) < N * heads * head_dim || + numel(o) < N * heads * head_dim) + return RAD_E_SHAPE; + const int64_t nt = std::min(kt, T), nh = std::min(kh, H), nw = std::min(kw, W); + const int64_t q_ds = q->stride[1], q_rs = row_stride(q, heads * head_dim); + const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1, k_rs = row_stride(k, heads * head_dim); + const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1, v_rs = row_stride(v, heads * head_dim); + const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1, o_rs = row_stride(o, heads * head_dim); + const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); + auto start = [](int64_t c, int64_t n, int64_t L) { + return std::min(std::max(c - n / 2, 0), L - n); + }; + AVX_PARALLEL_FOR_IF(N * heads >= 2) + for (int64_t rh = 0; rh < N * heads; ++rh) { + const int64_t r = rh / heads, h = rh % heads; + const int64_t t = r / (H * W), i = (r / W) % H, j = r % W; + const int64_t t0 = start(t, nt, T), i0 = start(i, nh, H), j0 = start(j, nw, W); + float* frame = (float*)scratch_f32((size_t)(4 * head_dim + AVX_KV_TILE) + 16); + float* qbuf = frame; + float* kbuf = frame + head_dim; + float* vbuf = frame + 2 * head_dim; + float* acc = frame + 3 * head_dim; + float* sbuf = frame + 4 * head_dim; + int64_t vbase[AVX_KV_TILE]; + const int64_t ob = r * o_rs + h * head_dim * o_ds; + const float* qv = head_f32(q, r * q_rs + h * head_dim * q_ds, q_ds, head_dim, 1.0f, qbuf); + for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; + float m = -INFINITY, l = 0.0f; + int ntile = 0; + auto flush = [&]() { + if (ntile == 0) return; + float tmax = sbuf[0]; + for (int u = 1; u < ntile; ++u) if (sbuf[u] > tmax) tmax = sbuf[u]; + if (tmax > m) { + const float rr = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax); + if (rr != 1.0f) { + for (int64_t d = 0; d < head_dim; ++d) acc[d] *= rr; + l *= rr; + } + m = tmax; + } + for (int u = 0; u < ntile; ++u) sbuf[u] = sc_exp(sbuf[u] - m); + for (int u = 0; u < ntile; ++u) { + l += sbuf[u]; + axpy(acc, head_f32(v, vbase[u], v_ds, head_dim, 1.0f, vbuf), sbuf[u], head_dim); + } + ntile = 0; + }; + for (int64_t a1 = t0; a1 < t0 + nt; ++a1) + for (int64_t b1 = i0; b1 < i0 + nh; ++b1) + for (int64_t c1 = j0; c1 < j0 + nw; ++c1) { + const int64_t key = (a1 * H + b1) * W + c1; + const float* kr = head_f32(k, key * k_rs + h * head_dim * k_ds, k_ds, head_dim, 1.0f, kbuf); + sbuf[ntile] = dotf(qv, kr, head_dim) * scale; + vbase[ntile] = key * v_rs + h * head_dim * v_ds; + if (++ntile == AVX_KV_TILE) flush(); + } + flush(); + const float inv = l > 0.0f ? 1.0f / l : 0.0f; + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv); + } + return RAD_OK; +} diff --git a/libavx/avx_audio.cpp b/libavx/avx_audio.cpp index a25e7582..99e16e1a 100644 --- a/libavx/avx_audio.cpp +++ b/libavx/avx_audio.cpp @@ -1094,6 +1094,37 @@ AVX_KERNEL(iota) { return RAD_OK; } +/* ------------------------------------------------------------------ int_affine */ +/* y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists. */ +static int avx_parse_ints(const char* s, int64_t* v, int cap) { + int n = 0; + while (s && *s) { + char* e = nullptr; + const long long x = std::strtoll(s, &e, 10); + if (e == s) break; + if (n == cap) return -1; + v[n++] = x; + s = e; + } + return n; +} + +AVX_KERNEL(int_affine) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + int64_t src[16], mul[16], add[16]; + const int n = avx_parse_ints(p_str(a, "src", ""), src, 16); + if (n <= 0 || avx_parse_ints(p_str(a, "mul", ""), mul, 16) != n || + avx_parse_ints(p_str(a, "add", ""), add, 16) != n || numel(Y) < n) + return RAD_E_SHAPE; + for (int j = 0; j < n; ++j) { + if (src[j] >= numel(X)) return RAD_E_SHAPE; + const int64_t v = src[j] < 0 ? 0 : at(X, src[j]); + st_int_dt(Y->dtype, Y->data, offlin(Y, j), v * mul[j] + add[j]); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ cu_repeat */ /* y[j] = j * len[0] * mult over y's elements: the bounds of equal sequences. */ AVX_KERNEL(cu_repeat) { diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 39f51551..67460da9 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -359,6 +359,17 @@ std::vector build_cases() { add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 1), HI("causal", 0), HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24), HI("block", 7) }); + /* Cross attention: each entry's keys a run of their own, both sides of `causal`. */ + for (const char* dt : { "f32", "bf16" }) + for (int causal : { 0, 1 }) + add("attn_cross", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2), + HI("causal", causal), HS("dtype", dt), HF("scale", 0.125) }); + /* Neighborhood attention: a 4 x 4 x 4 volume (the description's), windows narrower and as wide + * as its axes. */ + for (const char* dt : { "f32", "bf16" }) + for (int kw : { 3, 4 }) + add("attn_na3d", { HI("M", 64), HI("head_dim", 64), HI("kt", 3), HI("kh", 3), + HI("kw", kw), HS("dtype", dt) }); for (const char* dt : { "f32", "bf16" }) add("seg_sinusoid", { HI("M", 30), HI("n", 64), HI("period", 13), HS("dtype", dt) }); /* Gemma 4's audio attention: left 12, over segments longer than the window. */ @@ -698,10 +709,16 @@ std::vector build_cases() { EB(7, 645, dt[0] == 'f' ? 4 : 2, 3)); add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt), HS("act", "none") }, EB(7, 645, dt[0] == 'f' ? 4 : 2, 3)); + add("table_add", { HI("M", 3), HI("n", 645), HI("L", 5), HS("dtype", dt) }); + add("mix_rows", { HI("M", 7), HI("n", 645), HI("k", 12), HS("dtype", dt) }); + for (const char* mode : { "denorm", "norm" }) + for (int var : { 0, 1 }) + add("chan_stats", { HI("M", 7), HI("n", 645), HS("mode", mode), HI("var", var), + HF("eps", 1e-4), HS("dtype", dt) }); for (int gated : { 1, 0 }) add("ln_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128), HI("gated", gated), HS("dtype", dt) }); - for (int round : { 1, 0 }) + for (int round : { 3, 2, 1, 0 }) add("timestep_embed", { HI("M", 3), HI("n", 256), HF("scale", 1000.0), HF("max_period", 10000.0), HI("round", round), HS("dtype", dt) }); @@ -776,6 +793,17 @@ std::vector build_cases() { HS("dtype", dt) }); add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-5), HI("group", 128), HI("gated", gated), HS("dtype", dt) }); + /* A zero-centred gain (1 + w), the norm and gain rounded once (Krea 2's). */ + add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-5), HI("gated", gated), + HS("dtype", dt), HF("wadd", 1.0), HI("norm_once", 1) }); + add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-5), HI("group", 128), + HI("gated", gated), HS("dtype", dt), HF("wadd", 1.0), + HI("norm_once", 1) }); + /* A LayerNorm without a gain (FLUX's). */ + add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-6), HI("gated", gated), + HS("dtype", dt), HS("norm", "layer") }); + add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128), + HI("gated", gated), HS("dtype", dt), HS("norm", "layer") }); } add("flow_x0_step", { HI("M", 9), HI("n", 645), HS("dtype", dt) }); for (int pt : { 1, 4 }) @@ -833,6 +861,37 @@ std::vector build_cases() { add("flow_renoise", { HI("M", 9), HI("n", 96), HI("stream", 1), HS("dtype", "f32") }); add("flow_renoise", { HI("M", 5), HI("n", 645), HI("stream", 7), HS("dtype", "f32") }); + /* LTX-2: the video's 3-axis rotary (two padded pairs, a rank's second head), the cross + * attentions' 1-axis one, the per-head gate and the guided step. */ + for (const char* dt : { "f32", "bf16" }) { + add("rope_split", { HI("M", 7), HI("n_head", 3), HI("head_dim", 128), HI("dim", 4096), + HI("n_dims", 3), HF("theta", 10000.0), HS("max", "20 2048 2048"), + HI("head0", 1), HS("dtype", dt) }); + add("rope_split", { HI("M", 5), HI("n_head", 4), HI("head_dim", 64), HI("dim", 256), + HI("n_dims", 1), HF("theta", 10000.0), HS("max", "20"), + HS("dtype", dt) }); + add("head_gate", { HI("M", 7), HI("n_head", 5), HI("head_dim", 64), HS("dtype", dt) }); + add("ltx_guide", { HI("M", 9), HI("n", 128), HS("dtype", dt) }); + add("pixel_norm", { HI("M", 26), HI("n", 96), HF("eps", 1e-6), HS("form", "rsqrt"), + HI("ileave", 13), HF("mult", 3.7), HS("dtype", dt) }); + add("pixel_norm", { HI("M", 7), HI("n", 256), HF("eps", 1e-8), HS("form", "div"), + HS("act", "silu"), HS("dtype", dt) }); + add("d2s3d", { HI("M", 27), HI("C", 5), HI("st", 2), HI("sh", 2), HI("sw", 2), + HS("dtype", dt) }); + add("s2d3d", { HI("M", 27), HI("C", 4), HI("st", 2), HI("sh", 1), HI("sw", 1), + HI("tpre", 1), HS("mode", "copy"), HS("dtype", dt) }); + add("s2d3d", { HI("M", 64), HI("C", 6), HI("st", 2), HI("sh", 2), HI("sw", 2), + HI("group", 4), HS("mode", "mean"), HI("add", 1), HS("dtype", dt) }); + add("pix_patch", { HI("M", 12), HI("p", 4), HI("C", 3), HS("dtype", dt) }); + add("patch_pix8", { HI("M", 12), HI("p", 4), HI("C", 3), HS("dtype", dt) }); + add("stft_logmel", { HI("M", 6), HI("hop", 80), HI("nfft", 512), HI("n_mel", 64), + HI("ch", 2), HS("dtype", dt) }); + add("bwe_up", { HI("M", 600), HI("ratio", 3), HI("ch", 2), HS("dtype", dt) }); + add("tile_crop", { HI("M", 125), HI("C", 7), HS("dtype", dt) }); + add("tile_stitch", { HI("M", 4000), HI("tile", 4), HI("stride", 3), HI("scale", 2), + HI("p", 4), HI("C", 3), HS("dtype", dt) }); + } + /* Video sparse attention over the cubes libref describes: a 3 x 3 x 3 grid in boxes of 2 * after two dense segments of as many rows (P 8, V 8; sparsity 0.8 keeps 2), with and without * the coarse operands; and MiniMax-H3's boxes of 4 at patch 2 over a 10 x 5 x 5 grid after @@ -967,9 +1026,13 @@ std::vector build_cases() { add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1), HI("skip", 1) }); add("iota", { HI("M", 645), HI("start", 3), HI("step", 2) }); + add("tile_grid", { HI("M", 9), HI("tile", 16), HI("stride", 14) }); + add("vol_index", { HI("M", 125) }); add("iota", { HI("M", 7), HI("start", -5), HI("step", 1) }); add("cu_repeat", { HI("M", 5), HI("mult", 3) }); add("cu_repeat", { HI("M", 9), HI("mult", 1) }); + add("int_affine", { HI("M", 4), HS("src", "0 -1 2 1"), HS("mul", "2 0 8 4"), + HS("add", "-1 7 -7 -3") }); /* ================================================================== speed-only, at model size * diff --git a/libavx/avx_gen.cpp b/libavx/avx_gen.cpp index 608e1df2..f49025db 100644 --- a/libavx/avx_gen.cpp +++ b/libavx/avx_gen.cpp @@ -325,21 +325,27 @@ AVX_KERNEL(ln_mod_quant_fp8) { /* Both forms: with `gated` the branch added through the gate row (no tanh) and the residual stored * in x's dtype; then n1 = rd(x rsqrt(mean(x^2) + eps)), n2 = rd(n1 w), m = rd(n2 rd(1 + scale)), * z = rd(m + shift), rd the norm chain's dtype (z's for rms_mod, bf16 for the quantised form, - * libref's rule). The sum of squares is the vector reduction, held to the tolerance table; every + * libref's rule); `norm` none takes n2 = x. The sum of squares is the vector reduction, held to the tolerance table; every * rounding is a pass through the stored dtype, so the rest is libref's arithmetic. The per-entry * rows (1 + scale rounded, the shift and the gate) and the gain are built once a launch. */ static int rms_mod_run(const RadArgs* a, bool quant) { if (a->n_t < (quant ? 9 : 7)) return RAD_E_INVAL; - const RadTensor *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2], *W = &a->t[3]; + const RadTensor *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2]; + const RadTensor* W = rad_arg_in(a, 3); const RadTensor *cu = &a->t[4], *X = &a->t[5]; const RadTensor *Q = quant ? &a->t[6] : nullptr, *SC = quant ? &a->t[7] : nullptr; const RadTensor* Z = quant ? rad_arg_in(a, 8) : &a->t[6]; const int64_t n = p_int(a, "n", 0), grp = quant ? p_int(a, "group", 0) : 1; const bool gated = p_int(a, "gated", 0) != 0; const float eps = p_f32(a, "eps", 1e-6f); + const float wadd = p_f32(a, "wadd", 0.0f); + const bool once = p_int(a, "norm_once", 0) != 0; + const char* nk = p_str(a, "norm", "rms"); + const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0; + if ((!layer && !none && std::strcmp(nk, "rms") != 0) || (none && W)) return RAD_E_INVAL; if (n <= 0 || grp <= 0 || n % grp || (gated && (!Yv || !G))) return RAD_E_SHAPE; const int64_t rows = rows_of(quant ? Q : Z, n), n_seq = numel(cu) - 1, ngrp = n / grp; - if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || numel(W) < n || + if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || (W && numel(W) < n) || numel(S) < n_seq * 2 * n) return RAD_E_SHAPE; if (gated && (rows_of(Yv, n) < rows || numel(G) < n_seq * n)) return RAD_E_SHAPE; @@ -359,7 +365,8 @@ static int rms_mod_run(const RadArgs* a, bool quant) { row[n + i] = ldt(S, e * s_rs + i * s_cs); if (gated) row[2 * n + i] = ldt(G, e * g_rs + i * g_cs); } - for (int64_t i = 0; i < n; ++i) tabs[n_seq * tw + i] = ldt(W, i * laststride(W)); + for (int64_t i = 0; i < n; ++i) + tabs[n_seq * tw + i] = W ? ldt(W, i * laststride(W)) + wadd : 1.0f; } const float* wrow = tabs + n_seq * tw; @@ -380,13 +387,23 @@ static int rms_mod_run(const RadArgs* a, bool quant) { } else { std::memcpy(v, xv, (size_t)n * sizeof(float)); } - const float rs = 1.0f / std::sqrt(row_sumsq(v, n) / (float)n + eps); + if (layer) { + /* Centred first, the mean an f32 sum in ascending order (libref's). */ + float mu = 0.0f; + for (int64_t k = 0; k < n; ++k) mu += v[k]; + mu /= (float)n; + for (int64_t k = 0; k < n; ++k) v[k] -= mu; + } + /* `none`: no norm, the residual as it is (libref's n2 = x). */ + const float rs = none ? 1.0f : 1.0f / std::sqrt(row_sumsq(v, n) / (float)n + eps); const vf vr = vf_set1(rs); int64_t i = 0; for (; i + VF_N <= n; i += VF_N) vf_storeu(o + i, vf_mul(vf_loadu(v + i), vr)); for (; i < n; ++i) o[i] = v[i] * rs; - narrow_row(dt, o, n, tmp); - mul_rows(o, wrow, n); + if (W) { + if (!once) narrow_row(dt, o, n, tmp); + mul_rows(o, wrow, n); + } narrow_row(dt, o, n, tmp); mul_rows(o, ent, n); narrow_row(dt, o, n, tmp); @@ -424,7 +441,9 @@ AVX_KERNEL(timestep_embed) { for (int64_t i = 0; i < h; ++i) f[i] = sc_exp(coef * (float)i / (float)h); for (int64_t m = 0; m < rows; ++m) { const float tv = ldt(T, offlin(T, m)); - const float tt = round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale) + const float tt = round == 3 ? narrow1(RAD_BF16, scale * narrow1(RAD_BF16, tv)) + : round == 2 ? scale * narrow1(RAD_BF16, tv) + : round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale) : scale * tv; for (int64_t i = 0; i < h; ++i) { const float arg = tt * f[i]; @@ -553,14 +572,15 @@ AVX_KERNEL(randn_lanes) { * x' = bf16(x + bf16(bf16(sigma_next - sigma) * v')) * * flag 4 writes x - sigma v' to the lane's preview, and flag 2 restores the kept region, - * x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise)). libref requires every - * operand, the optional three included. Every entry is checked before any lane is written. */ + * x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise)). inp, mask and preview are + * optional, as in libref: an entry whose flags need one that is absent is refused. Every entry is + * checked before any lane is written. */ AVX_KERNEL(flow_euler) { - if (!rad_args_have(a, 13)) return RAD_E_INVAL; + if (!rad_args_have(a, 9) || !rad_arg_in(a, 11)) return RAD_E_INVAL; const RadTensor *V = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *cfg = &a->t[3]; const RadTensor *pair = &a->t[4], *lane = &a->t[5], *fl = &a->t[6], *seed = &a->t[7]; - const RadTensor *cu = &a->t[8], *inp = &a->t[9], *mask = &a->t[10], *st = &a->t[11]; - const RadTensor* pv = &a->t[12]; + const RadTensor *cu = &a->t[8], *inp = rad_arg_in(a, 9), *mask = rad_arg_in(a, 10); + const RadTensor *st = &a->t[11], *pv = rad_arg_in(a, 12); const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); if (n <= 0 || stride <= 0) return RAD_E_SHAPE; const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), v_rows = rows_of(V, n); @@ -576,6 +596,8 @@ AVX_KERNEL(flow_euler) { if (len > 0 && (b0 < 0 || b0 + len > v_rows)) return RAD_E_SHAPE; if (pr >= 0 && len > 0 && (cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > v_rows)) return RAD_E_SHAPE; + const int64_t f = ldi(fl, offlin(fl, e)); + if (((f & kInpaint) && (!inp || !mask)) || ((f & kPreview) && !pv)) return RAD_E_INVAL; } const uint32_t dt = st->dtype; for (int64_t e = 0; e < n_seq; ++e) { @@ -776,8 +798,11 @@ AVX_KERNEL(conv2d_nhwc) { const int64_t Ho = Y->shape[0], Wo = Y->shape[1] / cout; if (Hin <= 0 || Win <= 0 || Ho <= 0 || Wo <= 0) return RAD_E_SHAPE; const int64_t Hv = Hin * up, Wv = Win * up; - const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2; - if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo) + /* `causal` pads k - 1 rows above and none below (libref's). */ + const bool causal = pad && !std::strcmp(pad, "causal"); + const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2; + const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2; + if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo) return RAD_E_SHAPE; if (numel(W) < cout * cin * k * k || numel(B) < cout) return RAD_E_SHAPE; const int64_t xr = X->stride[0], yr = Y->stride[0]; @@ -855,7 +880,7 @@ AVX_KERNEL(conv2d_nhwc) { for (int64_t kh = 0; kh < k; ++kh) { const int64_t iy = oy * stride + kh - pt; for (int64_t kw = 0; kw < k; ++kw) { - const int64_t ix = ox * stride + kw - pt; + const int64_t ix = ox * stride + kw - pl; char* d = dst + (size_t)((kh * k + kw) * cin) * ael; if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) { std::memset(d, 0, (size_t)cin * ael); @@ -1186,3 +1211,85 @@ AVX_KERNEL(scatter_add_rows) { for (int64_t m = 0; m < M; ++m) add_row(m); return RAD_OK; } + +/* ------------------------------------------------------------------ table_add */ +/* libref's table_add: y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once to y's dtype. */ +AVX_KERNEL(table_add) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *T = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0), L = p_int(a, "L", 0); + if (n <= 0 || L <= 0 || numel(T) < L * n) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, L * n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(rows * L * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(3 * n + 64)); + float *xs = buf, *ts = buf + n + 16, *p = ts + n + 16; + const float* xv = in_row(X, rowoff(X, r, n), n, xs); + for (int64_t l = 0; l < L; ++l) { + const float* tv = in_row(T, l * n * laststride(T), n, ts); + for (int64_t c = 0; c < n; ++c) p[c] = xv[c] + tv[c]; + out_row(Y, rowoff(Y, r, L * n) + l * n * laststride(Y), n, p); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ mix_rows */ +/* libref's mix_rows: y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once. */ +AVX_KERNEL(mix_rows) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0); + if (n <= 0 || k <= 0 || numel(W) < k) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows * k) return RAD_E_SHAPE; + std::vector w((size_t)k); + for (int64_t i = 0; i < k; ++i) w[(size_t)i] = ldt(W, i * laststride(W)); + AVX_PARALLEL_FOR_IF(rows * n * k >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(2 * n + 64)); + float *xs = buf, *acc = buf + n + 16; + for (int64_t c = 0; c < n; ++c) acc[c] = 0.0f; + for (int64_t i = 0; i < k; ++i) { + const float* xv = in_row(X, rowoff(X, r * k + i, n), n, xs); + for (int64_t c = 0; c < n; ++c) acc[c] += w[(size_t)i] * xv[c]; + } + out_row(Y, rowoff(Y, r, n), n, acc); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ chan_stats */ +/* libref's chan_stats: per-channel statistics held as weights, every step rounded as libref. */ +AVX_KERNEL(chan_stats) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Mn = &a->t[1], *Sd = &a->t[2], *Y = &a->t[3]; + const int64_t n = p_int(a, "n", 0); + const bool var = p_int(a, "var", 0) != 0; + const float eps = p_f32(a, "eps", 0.0f); + const char* mode = p_str(a, "mode", "denorm"); + const bool norm = std::strcmp(mode, "norm") == 0; + if (!norm && std::strcmp(mode, "denorm") != 0) return RAD_E_INVAL; + if (n <= 0 || numel(Mn) < n || numel(Sd) < n) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const uint32_t dt = Y->dtype; + std::vector mu((size_t)n), sd((size_t)n); + for (int64_t c = 0; c < n; ++c) { + mu[(size_t)c] = narrow1(dt, ldt(Mn, c * laststride(Mn))); + const float v = ldt(Sd, c * laststride(Sd)); + sd[(size_t)c] = narrow1(dt, var ? std::sqrt(v + eps) : v); + } + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* buf = scratch_f32((size_t)(2 * n + 32)); + float *xs = buf, *o = buf + n + 16; + const float* xv = in_row(X, rowoff(X, r, n), n, xs); + for (int64_t c = 0; c < n; ++c) + o[c] = norm ? narrow1(dt, narrow1(dt, xv[c] - mu[(size_t)c]) / sd[(size_t)c]) + : narrow1(dt, narrow1(dt, xv[c] * sd[(size_t)c]) + mu[(size_t)c]); + out_row(Y, rowoff(Y, r, n), n, o); + } + return RAD_OK; +} diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 2081c01c..e5b14941 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -100,7 +100,7 @@ int avx_par_force(int threads); X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \ X(lora_shrink) X(lora_expand) \ /* ---- attention */ \ - X(attn_paged) X(attn_dense) X(kv_store) X(rope) \ + X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(rope) \ X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \ X(qsa_score) X(qsa_select) X(qsa_tail_store) X(qsa_work) \ /* ---- mixture of experts */ \ @@ -123,12 +123,17 @@ int avx_par_force(int threads); X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \ X(attn_vsa) X(conv3d_ndhwc) X(group_norm) X(tconv_dw) \ X(resize_bilinear) X(patch_fold) X(flow_renoise) \ + /* ---- LTX-2 */ \ + X(rope_split) X(head_gate) X(ltx_guide) X(pixel_norm) \ + X(d2s3d) X(s2d3d) X(pix_patch) X(patch_pix8) \ + X(stft_logmel) X(bwe_up) X(tile_grid) X(tile_crop) \ + X(tile_stitch) X(vol_index) \ /* ---- audio generation */ \ X(conv1d) X(conv_t1d) X(snake) X(cfg_topk_sample) \ X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \ X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \ X(win_finish) X(chan_split) X(interleave2) X(iota) \ - X(cu_repeat) X(snake_aa) \ + X(cu_repeat) X(snake_aa) X(int_affine) \ /* ---- sampling, and the drafter's token walk */ \ X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \ X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \ diff --git a/libavx/avx_ltx.cpp b/libavx/avx_ltx.cpp new file mode 100644 index 00000000..6bc35149 --- /dev/null +++ b/libavx/avx_ltx.cpp @@ -0,0 +1,604 @@ +/* avx_ltx.cpp -- LTX-2's ops (docs/OPS.md, "LTX-2"): its rotary over fractional coordinates, the + * per-head attention gate, the guided sampler step, its VAE's norm, resampling and patches, and its + * vocoder's spectrogram and resampler. libref's arithmetic, element by element + * (libref/ref_ltx.cpp states the roundings): LTX-2 is a GPU model, and these run on the CPU only + * where a whole model does, so they are written for agreement rather than speed. + */ +#include "avx_vec.h" +#include "avx_common.h" + +#include +#include +#include +#include + +using namespace avx; + +namespace { + +/* A product the compiler may not fuse into the add after it (libavx builds with + * -ffp-contract=fast; libref rounds the product first). */ +inline float keep(float x) { __asm__("" : "+x"(x)); return x; } + +double linspace01(int64_t i, int64_t steps) { + if (steps <= 1) return 0.0; + const double step = 1.0 / (double)(steps - 1); + return i < steps / 2 ? step * (double)i : 1.0 - step * (double)(steps - 1 - i); +} + +int parse_floats(const char* s, std::vector* out) { + out->clear(); + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + out->push_back((float)v); + s = end; + } + return (int)out->size(); +} + +inline int64_t at_i(const RadTensor* t, int64_t i) { + return (int64_t)ld_elem(t->data, t->dtype, i * laststride(t)); +} + +float pos_at(const RadTensor* p, int64_t d, int64_t r) { + const int64_t off = p->rank >= 2 ? d * p->stride[0] + r * p->stride[1] : r * laststride(p); + return ldt(p, off); +} + +} /* namespace */ + +/* ------------------------------------------------------------------ rope_split */ +AVX_KERNEL(rope_split) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *P = &a->t[1]; + const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0); + const int64_t dim = p_int(a, "dim", 0), nd = p_int(a, "n_dims", 0), h0 = p_int(a, "head0", 0); + const double theta = (double)p_f32(a, "theta", 10000.0f); + std::vector mx; + if (nh <= 0 || hd <= 0 || (hd & 1) || nd <= 0 || dim < (h0 + nh) * hd || + parse_floats(p_str(a, "max", ""), &mx) != (int)nd) + return RAD_E_SHAPE; + const int64_t P2 = dim / 2, steps = P2 / nd, pad = P2 - steps * nd, half = hd / 2; + const int64_t rows = rows_of(X, nh * hd); + if (rows <= 0 || P->rank < 1) return RAD_E_SHAPE; + std::vector freq((size_t)steps); + for (int64_t k = 0; k < steps; ++k) + freq[(size_t)k] = (float)(std::pow(theta, linspace01(k, steps)) * M_PI / 2.0); + const int64_t xs = laststride(X); + AVX_PARALLEL_FOR_IF(rows * nh * hd >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, nh * hd); + for (int64_t h = 0; h < nh; ++h) + for (int64_t i = 0; i < half; ++i) { + const int64_t p = (h0 + h) * half + i; + if (p < pad) continue; + const int64_t j = p - pad, d = j % nd, k = j / nd; + const float g = pos_at(P, d, r) / mx[(size_t)d]; + const float ang = (2.0f * g - 1.0f) * freq[(size_t)k]; + const float c = (float)std::cos((double)ang), s = (float)std::sin((double)ang); + const int64_t o1 = xb + (h * hd + i) * xs, o2 = xb + (h * hd + half + i) * xs; + const float x1 = ldt(X, o1), x2 = ldt(X, o2); + st_elem(X->data, X->dtype, o1, keep(x1 * c) - keep(x2 * s)); + st_elem(X->data, X->dtype, o2, keep(x2 * c) + keep(x1 * s)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ head_gate */ +AVX_KERNEL(head_gate) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *G = &a->t[0], *X = &a->t[1]; + const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0); + if (nh <= 0 || hd <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(X, nh * hd); + if (rows <= 0 || rows_of(G, nh) < rows) return RAD_E_SHAPE; + const int64_t xs = laststride(X), gs = laststride(G); + AVX_PARALLEL_FOR_IF(rows * nh * hd >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, nh * hd), gb = rowoff(G, r, nh); + for (int64_t h = 0; h < nh; ++h) { + const float lg = ldt(G, gb + h * gs); + const float sg = narrow1(G->dtype, 1.0f / (1.0f + std::exp(-lg))); + const float gate = narrow1(X->dtype, 2.0f * sg); + for (int64_t i = 0; i < hd; ++i) { + const int64_t o = xb + (h * hd + i) * xs; + st_elem(X->data, X->dtype, o, ldt(X, o) * gate); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ ltx_guide */ +AVX_KERNEL(ltx_guide) { + if (a->n_t < 8) return RAD_E_INVAL; + const RadTensor *Vc = &a->t[0], *Vu = rad_arg_in(a, 1), *Vs = rad_arg_in(a, 2); + const RadTensor *Vm = rad_arg_in(a, 3), *Sc = &a->t[4], *Sh = &a->t[5], *X = &a->t[7]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || numel(Sc) < 4 || numel(Sh) < 2) return RAD_E_SHAPE; + const int64_t rows = rows_of(X, n); + if (rows <= 0 || rows_of(Vc, n) < rows || (Vu && rows_of(Vu, n) < rows) || + (Vs && rows_of(Vs, n) < rows) || (Vm && rows_of(Vm, n) < rows)) + return RAD_E_SHAPE; + const int64_t ss = laststride(Sc); + const float gs = ldt(Sc, 0), stg = ldt(Sc, ss), ms = ldt(Sc, 2 * ss), rr = ldt(Sc, 3 * ss); + const float sig = ldt(Sh, 0), sig_n = ldt(Sh, laststride(Sh)); + const bool use_u = Vu && gs != 1.0f, use_s = Vs && stg != 0.0f, use_m = Vm && ms != 1.0f; + const float cu = gs - 1.0f, cm = ms - 1.0f; + const int64_t N = rows * n; + std::vector x0c((size_t)N), g((size_t)N); + auto x0 = [&](const RadTensor* V, int64_t r, int64_t c, float x) { + return x - keep(ldt(V, rowoff(V, r, n) + c * laststride(V)) * sig); + }; + AVX_PARALLEL_FOR_IF(N >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = 0; c < n; ++c) { + const float x = ldt(X, rowoff(X, r, n) + c * laststride(X)); + const float xc = x0(Vc, r, c, x); + float v = xc; + if (use_u) v = v + keep(cu * (xc - x0(Vu, r, c, x))); + if (use_s) v = v + keep(stg * (xc - x0(Vs, r, c, x))); + if (use_m) v = v + keep(cm * (xc - x0(Vm, r, c, x))); + x0c[(size_t)(r * n + c)] = xc; + g[(size_t)(r * n + c)] = v; + } + float fac = 1.0f, kept = 1.0f; + if (rr > 0.0f) { + auto stdev = [&](const std::vector& v) { + double m = 0.0; + for (float e : v) m += e; + m /= (double)N; + double sq = 0.0; + for (float e : v) sq += ((double)e - m) * ((double)e - m); + return (float)std::sqrt(sq / (double)(N > 1 ? N - 1 : 1)); + }; + fac = stdev(x0c) / stdev(g); + kept = (float)(1.0 - (double)rr); + } + const float dt = sig_n - sig; + AVX_PARALLEL_FOR_IF(N >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = 0; c < n; ++c) { + float v = g[(size_t)(r * n + c)]; + if (rr > 0.0f) v = keep(rr * keep(v * fac)) + keep(kept * v); + const int64_t o = rowoff(X, r, n) + c * laststride(X); + const float x = ldt(X, o); + const float vel = (x - v) / sig; + st_elem(X->data, X->dtype, o, x + keep(dt * vel)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ pixel_norm */ +AVX_KERNEL(pixel_norm) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0), L = p_int(a, "ileave", 1); + const float eps = p_f32(a, "eps", 1e-6f), mult = p_f32(a, "mult", 1.0f); + const char* fs = p_str(a, "form", "rsqrt"); + const char* as = p_str(a, "act", "none"); + const int form = !std::strcmp(fs, "rsqrt") ? 0 : !std::strcmp(fs, "div") ? 1 : -1; + const int act = !std::strcmp(as, "none") ? 0 : !std::strcmp(as, "silu") ? 1 : -1; + if (form < 0 || act < 0 || n <= 0 || L <= 0) return RAD_E_INVAL; + const int64_t rows = rows_of(Y, n * L) * L; + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const uint32_t dt = Y->dtype; + const int64_t xs = laststride(X), ys = laststride(Y); + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r / L, n * L), l = r % L; + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) { + const float v = ldt(X, xb + i * xs); + ss += narrow1(dt, v * v); + } + const float v = narrow1(dt, narrow1(dt, ss / (float)n) + eps); + const float sc = form == 0 ? narrow1(dt, 1.0f / std::sqrt(v)) : narrow1(dt, std::sqrt(v)); + for (int64_t i = 0; i < n; ++i) { + const float x = ldt(X, xb + i * xs); + float z = narrow1(dt, form == 0 ? x * sc : x / sc); + if (act == 1) z = narrow1(dt, z / (1.0f + std::exp(-z))); + if (mult != 1.0f) z = narrow1(dt, z * mult); + st_elem(Y->data, dt, yb + (i * L + l) * ys, z); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ d2s3d */ +AVX_KERNEL(d2s3d) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1); + const int64_t sw = p_int(a, "sw", 1), drop = p_int(a, "drop", st - 1); + if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || drop < 0 || drop >= st || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), P = st * sh * sw; + const int64_t To = T * st - drop, Ho = H * sh, Wo = W * sw; + if (T <= 0 || H <= 0 || W <= 0 || rows_of(X, C * P) < T * H * W || + rows_of(Y, C) < To * Ho * Wo) + return RAD_E_SHAPE; + const int64_t xs = laststride(X), ys = laststride(Y); + AVX_PARALLEL_FOR_IF(To * Ho * Wo * C >= AVX_PAR_MIN) + for (int64_t r = 0; r < To * Ho * Wo; ++r) { + const int64_t tt = r / (Ho * Wo) + drop, ii = (r / Wo) % Ho, jj = r % Wo; + const int64_t t = tt / st, aa = tt % st, i = ii / sh, b = ii % sh, j = jj / sw, d = jj % sw; + const int64_t xb = rowoff(X, (t * H + i) * W + j, C * P), yb = rowoff(Y, r, C); + for (int64_t c = 0; c < C; ++c) + st_elem(Y->data, Y->dtype, yb + c * ys, + ldt(X, xb + (((c * st + aa) * sh + b) * sw + d) * xs)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ s2d3d */ +AVX_KERNEL(s2d3d) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1); + const int64_t sw = p_int(a, "sw", 1), tpre = p_int(a, "tpre", 0), grp = p_int(a, "group", 1); + const bool add = p_int(a, "add", 0) != 0; + const char* ms = p_str(a, "mode", "copy"); + const int mode = !std::strcmp(ms, "copy") ? 0 : !std::strcmp(ms, "mean") ? 1 : -1; + if (mode < 0) return RAD_E_INVAL; + if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || grp <= 0 || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), P = C * st * sh * sw; + const int64_t Tv = T + tpre; + if (T <= 0 || Tv % st || H % sh || W % sw || (mode == 1 && P % grp)) return RAD_E_SHAPE; + const int64_t To = Tv / st, Ho = H / sh, Wo = W / sw, Co = mode == 1 ? P / grp : P; + if (rows_of(X, C) < T * H * W || rows_of(Y, Co) < To * Ho * Wo) return RAD_E_SHAPE; + const int64_t xs = laststride(X), ys = laststride(Y); + const uint32_t dt = Y->dtype; + AVX_PARALLEL_FOR_IF(To * Ho * Wo * P >= AVX_PAR_MIN) + for (int64_t r = 0; r < To * Ho * Wo; ++r) { + const int64_t t = r / (Ho * Wo), i = (r / Wo) % Ho, j = r % Wo; + const int64_t yb = rowoff(Y, r, Co); + auto val = [&](int64_t q) { + const int64_t d = q % sw, b = (q / sw) % sh, aa = (q / (sw * sh)) % st; + const int64_t c = q / (sw * sh * st); + const int64_t v = t * st + aa, tr = v < tpre ? v : v - tpre; + return ldt(X, rowoff(X, (tr * H + i * sh + b) * W + j * sw + d, C) + c * xs); + }; + for (int64_t o = 0; o < Co; ++o) { + float v; + if (mode == 0) { + v = val(o); + } else { + float s = 0.0f; + for (int64_t q = o * grp; q < (o + 1) * grp; ++q) s += val(q); + v = narrow1(dt, s / (float)grp); + } + const int64_t oy = yb + o * ys; + st_elem(Y->data, dt, oy, add ? narrow1(dt, ldt(Y, oy)) + narrow1(dt, v) : v); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ pix_patch / patch_pix8 */ +static inline int64_t patch_col(int64_t c, int64_t ph, int64_t pw, int64_t p, bool wh) { + return c * p * p + (wh ? pw * p + ph : ph * p + pw); +} + +AVX_KERNEL(pix_patch) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0); + const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0; + if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || X->shape[1] % C) return RAD_E_SHAPE; + const int64_t H = X->shape[0], W = X->shape[1] / C; + if (H <= 0 || W <= 0 || H % p || W % p || Y->shape[0] != H / p || + Y->shape[1] != (W / p) * C * p * p) + return RAD_E_SHAPE; + const int64_t xr = X->stride[0], yr = Y->stride[0]; + AVX_PARALLEL_FOR_IF(H * W * C >= AVX_PAR_MIN) + for (int64_t y = 0; y < H; ++y) + for (int64_t x = 0; x < W; ++x) + for (int64_t c = 0; c < C; ++c) + st_elem(Y->data, Y->dtype, + (y / p) * yr + (x / p) * C * p * p + patch_col(c, y % p, x % p, p, wh), + ldt(X, y * xr + x * C + c)); + return RAD_OK; +} + +AVX_KERNEL(patch_pix8) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0); + const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0; + if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || Y->dtype != RAD_U8 || + X->shape[1] % (C * p * p)) + return RAD_E_SHAPE; + const int64_t R = X->shape[0], w = X->shape[1] / (C * p * p); + if (R <= 0 || w <= 0 || Y->shape[0] != R * p || Y->shape[1] != w * p * C) return RAD_E_SHAPE; + const int64_t xr = X->stride[0], yr = Y->stride[0]; + const uint32_t dt = X->dtype; + uint8_t* yb = (uint8_t*)Y->data; + AVX_PARALLEL_FOR_IF(R * p * w * p * C >= AVX_PAR_MIN) + for (int64_t y = 0; y < R * p; ++y) + for (int64_t x = 0; x < w * p; ++x) + for (int64_t c = 0; c < C; ++c) { + const float v = ldt(X, (y / p) * xr + (x / p) * C * p * p + + patch_col(c, y % p, x % p, p, wh)); + const float cl = std::min(std::max(v, -1.0f), 1.0f); + float u = narrow1(dt, narrow1(dt, cl / 2.0f) + 0.5f); + u = std::min(std::max(u, 0.0f), 1.0f); + yb[y * yr + x * C + c] = (uint8_t)std::nearbyint(u * 255.0f); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vol_index */ +AVX_KERNEL(vol_index) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *G = &a->t[0], *Y = &a->t[1]; + if (numel(G) < 3 || Y->rank != 2 || Y->shape[0] != 3) return RAD_E_SHAPE; + const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), n = Y->shape[1]; + if (T <= 0 || H <= 0 || W <= 0 || n <= 0) return RAD_E_SHAPE; + const int64_t m1 = std::min(n, T * H * W); + for (int64_t m = 0; m < m1; ++m) { + const int64_t v[3] = { m / (H * W), (m / W) % H, m % W }; + for (int64_t c = 0; c < 3; ++c) + st_int_dt(Y->dtype, Y->data, c * Y->stride[0] + m * Y->stride[1], v[c]); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ tile_grid / tile_crop / tile_stitch */ +/* diffusers' tiled decodes: libref/ref_ltx.cpp states the cuts and the blends. */ +namespace { +struct TileCut { + int64_t tile = 1, stride = 1, min = 1; + bool intervals = false; + int64_t count(int64_t L) const { + if (intervals && L <= tile) return 1; + int64_t n = (L + stride - 1) / stride; + while (intervals && n > 1 && L - (n - 1) * stride < min) --n; + return n; + } + int64_t len(int64_t L, int64_t k) const { + return k == count(L) - 1 ? L - k * stride : std::min(tile, L - k * stride); + } +}; + +bool tile_cuts(const RadArgs* a, TileCut* s, TileCut* t) { + static const char* const kRules[] = { "stride", "intervals" }; + const int rule = p_enum(a, "rule", kRules, 2, 0); + s->tile = p_int(a, "tile", 0); + s->stride = p_int(a, "stride", 0); + s->min = p_int(a, "min", 1); + s->intervals = rule == 1; + t->tile = p_int(a, "tile_t", 1 << 30); + t->stride = p_int(a, "stride_t", 1 << 30); + t->min = p_int(a, "min_t", 1); + t->intervals = rule == 1; + return rule >= 0 && s->tile > 0 && s->stride > 0 && s->stride <= s->tile && s->min > 0 && + t->tile > 0 && t->stride > 0 && t->stride <= t->tile && t->min > 0; +} + +} /* namespace */ + +AVX_KERNEL(tile_grid) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *G = &a->t[0], *Y = &a->t[1]; + TileCut cs, ct; + const int64_t n = numel(Y) / 8, tail = p_int(a, "tail", 0); + if (!tile_cuts(a, &cs, &ct) || tail < 0 || n <= 0 || numel(G) < 3) return RAD_E_SHAPE; + const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2); + if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; + const int64_t nt = ct.count(T), ni = cs.count(H), nj = cs.count(W), count = nt * ni * nj; + for (int64_t k = 0; k < n; ++k) { + int64_t row[8] = {}; + if (k < count) { + const int64_t kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj; + const int64_t v[8] = { ct.len(T, kt) + (kt == nt - 1 ? tail : 0), cs.len(H, i), + cs.len(W, j), kt * ct.stride, i * cs.stride, j * cs.stride, k, + count }; + std::memcpy(row, v, sizeof row); + } + for (int64_t e = 0; e < 8; ++e) st_int_dt(Y->dtype, Y->data, offlin(Y, k * 8 + e), row[e]); + } + return RAD_OK; +} + +AVX_KERNEL(tile_crop) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *B = &a->t[2], *Y = &a->t[3]; + const int64_t C = p_int(a, "C", 0); + if (C <= 0 || numel(G) < 3 || numel(B) < 6) return RAD_E_SHAPE; + const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2); + const int64_t t = at_i(B, 0), h = at_i(B, 1), w = at_i(B, 2); + const int64_t t0 = at_i(B, 3), y0 = at_i(B, 4), x0 = at_i(B, 5); + if (t <= 0 || h <= 0 || w <= 0 || t0 < 0 || y0 < 0 || x0 < 0 || t0 + t > T || y0 + h > H || + x0 + w > W || rows_of(X, C) < T * H * W || rows_of(Y, C) < t * h * w) + return RAD_E_SHAPE; + const int64_t xs = laststride(X), ys = laststride(Y); + AVX_PARALLEL_FOR_IF(t * h * w * C >= AVX_PAR_MIN) + for (int64_t r = 0; r < t * h * w; ++r) { + const int64_t f = r / (h * w), i = (r / w) % h, j = r % w; + const int64_t xb = rowoff(X, ((t0 + f) * H + y0 + i) * W + x0 + j, C), yb = rowoff(Y, r, C); + for (int64_t c = 0; c < C; ++c) st_elem(Y->data, Y->dtype, yb + c * ys, ldt(X, xb + c * xs)); + } + return RAD_OK; +} + +namespace { +struct TileStore { + TileCut cs, ct; + int64_t T, H, W, sc, st, nt, ni, nj, hsum, wsum; + TileStore(const TileCut& s, const TileCut& t, int64_t T_, int64_t H_, int64_t W_, int64_t sc_, + int64_t st_) + : cs(s), ct(t), T(T_), H(H_), W(W_), sc(sc_), st(st_), nt(t.count(T_)), ni(s.count(H_)), + nj(s.count(W_)), hsum(0), wsum(0) { + for (int64_t i = 0; i < ni; ++i) hsum += cs.len(H, i); + for (int64_t j = 0; j < nj; ++j) wsum += cs.len(W, j); + } + int64_t frames(int64_t kt) const { + return st * ct.len(T, kt) - (kt == 0 ? st - 1 : 0); + } + int64_t offset(int64_t kt, int64_t i, int64_t j) const { + int64_t before = 0; + for (int64_t q = 0; q < kt; ++q) before += frames(q); + int64_t left = 0, above = 0; + for (int64_t q = 0; q < j; ++q) left += cs.len(W, q); + for (int64_t q = 0; q < i; ++q) above += cs.len(H, q); + return sc * sc * (before * hsum * wsum + frames(kt) * (above * wsum + cs.len(H, i) * left)); + } + int64_t rows() const { return offset(nt, 0, 0); } +}; +} /* namespace */ + +AVX_KERNEL(tile_stitch) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Fst = &a->t[2], *Y = &a->t[3]; + TileCut cs, ct; + const int64_t sc = p_int(a, "scale", 0), st = p_int(a, "scale_t", 1); + const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0); + const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0; + if (!tile_cuts(a, &cs, &ct) || sc <= 0 || st <= 0 || p <= 0 || C <= 0 || numel(G) < 3 || + numel(Fst) < 1 || Y->dtype != RAD_U8 || Y->rank != 2) + return RAD_E_SHAPE; + const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), f0 = at_i(Fst, 0); + const int64_t Hpx = H * sc * p, Wpx = W * sc * p, P = C * p * p; + if (T <= 0 || H <= 0 || W <= 0 || Y->shape[1] != Wpx * C || Y->shape[0] % Hpx) return RAD_E_SHAPE; + const int64_t nf = Y->shape[0] / Hpx; + const TileStore ts(cs, ct, T, H, W, sc, st); + if (nf <= 0 || f0 < 0 || f0 + nf > st * T - (st - 1) || rows_of(X, P) < ts.rows()) + return RAD_E_SHAPE; + const int64_t s = cs.stride * sc * p, E = (cs.tile - cs.stride) * sc * p; + const int64_t Et = (ct.tile - ct.stride) * st, xs = laststride(X); + const uint32_t dt = X->dtype; + auto R = [&](int64_t kt, int64_t i, int64_t j, int64_t f, int64_t yy, int64_t xx, int64_t c) { + const int64_t wp = cs.len(W, j) * sc, hp = cs.len(H, i) * sc; + const int64_t row = ts.offset(kt, i, j) + (f * hp + yy / p) * wp + xx / p; + return ldt(X, rowoff(X, row, P) + patch_col(c, yy % p, xx % p, p, wh) * xs); + }; + auto mix = [&](float va, float vb, int64_t k, int64_t e) { + const float wa = (float)(1.0 - (double)k / (double)e), wb = (float)((double)k / (double)e); + return narrow1(dt, narrow1(dt, keep(va * wa)) + narrow1(dt, keep(vb * wb))); + }; + auto S = [&](int64_t kt, int64_t f, int64_t Yp, int64_t Xp, int64_t c) { + const int64_t i = std::min(Yp / s, ts.ni - 1), ly = Yp - i * s; + const int64_t j = std::min(Xp / s, ts.nj - 1), lx = Xp - j * s; + const int64_t ha = i > 0 ? cs.len(H, i - 1) * sc * p : 0; + const int64_t ev = i > 0 ? std::min(std::min(ha, cs.len(H, i) * sc * p), E) : 0; + const int64_t wl = j > 0 ? cs.len(W, j - 1) * sc * p : 0; + const int64_t eh = j > 0 ? std::min(std::min(wl, cs.len(W, j) * sc * p), E) : 0; + const bool vb = i > 0 && ly < ev, hb = j > 0 && lx < eh; + float V = R(kt, i, j, f, ly, lx, c); + if (vb) { + const int64_t ya = ha - ev + ly; + float A = R(kt, i - 1, j, f, ya, lx, c); + if (hb) A = mix(R(kt, i - 1, j - 1, f, ya, wl - eh + lx, c), A, lx, eh); + V = mix(A, V, ly, ev); + } + if (hb) { + float L = R(kt, i, j - 1, f, ly, wl - eh + lx, c); + if (vb) L = mix(R(kt, i - 1, j - 1, f, ha - ev + ly, wl - eh + lx, c), L, ly, ev); + V = mix(L, V, lx, eh); + } + return V; + }; + uint8_t* yb = (uint8_t*)Y->data; + const int64_t yr = Y->stride[0], band = ct.stride * st; + AVX_PARALLEL_FOR_IF(nf * Hpx * Wpx * C >= AVX_PAR_MIN) + for (int64_t r = 0; r < nf * Hpx; ++r) { + const int64_t n = f0 + r / Hpx, Yp = r % Hpx; + const int64_t kt = std::min((n + st - 1) / band, ts.nt - 1); + const int64_t f = n - (kt == 0 ? 0 : kt * band - (st - 1)); + const int64_t et = kt > 0 ? std::min(std::min(ts.frames(kt - 1), ts.frames(kt)), Et) : 0; + for (int64_t Xp = 0; Xp < Wpx; ++Xp) + for (int64_t c = 0; c < C; ++c) { + float v = S(kt, f, Yp, Xp, c); + if (kt > 0 && f < et) v = mix(S(kt - 1, ts.frames(kt - 1) - et + f, Yp, Xp, c), v, f, et); + const float cl = std::min(std::max(v, -1.0f), 1.0f); + float u = narrow1(dt, narrow1(dt, cl / 2.0f) + 0.5f); + u = std::min(std::max(u, 0.0f), 1.0f); + yb[r * yr + Xp * C + c] = (uint8_t)std::nearbyint(u * 255.0f); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ stft_logmel */ +AVX_KERNEL(stft_logmel) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *B = &a->t[1], *Mb = &a->t[2], *Y = &a->t[3]; + const int64_t hop = p_int(a, "hop", 0), nfft = p_int(a, "nfft", 0), nm = p_int(a, "n_mel", 0); + const int64_t ch = p_int(a, "ch", 0); + if (hop <= 0 || nfft < hop || nm <= 0 || ch <= 0) return RAD_E_SHAPE; + const int64_t F = nfft / 2 + 1, S = rows_of(X, ch), frames = rows_of(Y, ch * nm); + if (S <= 0 || frames <= 0 || frames * hop > S || numel(B) < 2 * F * nfft || numel(Mb) < nm * F) + return RAD_E_SHAPE; + const uint32_t dt = Y->dtype; + const int64_t pad = nfft - hop, xs = laststride(X), ys = laststride(Y); + const float floor_v = narrow1(dt, 1e-5f); + AVX_PARALLEL_FOR_IF(frames * ch * F * nfft >= AVX_PAR_MIN) + for (int64_t t = 0; t < frames; ++t) + for (int64_t h = 0; h < ch; ++h) { + std::vector mag((size_t)F); + for (int64_t k = 0; k < F; ++k) { + float re = 0.0f, im = 0.0f; + for (int64_t j = 0; j < nfft; ++j) { + const int64_t s = t * hop + j - pad; + if (s < 0) continue; + const float v = ldt(X, rowoff(X, s, ch) + h * xs); + re += keep(ldt(B, k * nfft + j) * v); + im += keep(ldt(B, (F + k) * nfft + j) * v); + } + re = narrow1(dt, re); + im = narrow1(dt, im); + mag[(size_t)k] = narrow1(dt, std::sqrt(narrow1(dt, narrow1(dt, re * re) + + narrow1(dt, im * im)))); + } + const int64_t yb = rowoff(Y, t, ch * nm); + for (int64_t m = 0; m < nm; ++m) { + float s = 0.0f; + for (int64_t k = 0; k < F; ++k) s += keep(ldt(Mb, m * F + k) * mag[(size_t)k]); + const float mel = std::max(narrow1(dt, s), floor_v); + st_elem(Y->data, dt, yb + (h * nm + m) * ys, std::log(mel)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ bwe_up */ +AVX_KERNEL(bwe_up) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Rz = &a->t[1], *Y = &a->t[2]; + const int64_t r = p_int(a, "ratio", 0), ch = p_int(a, "ch", 0); + if (r <= 0 || ch <= 0) return RAD_E_SHAPE; + const int64_t S = rows_of(X, ch), O = rows_of(Y, ch); + if (S <= 0 || O <= 0 || O > S * r || rows_of(Rz, ch) < O) return RAD_E_SHAPE; + const uint32_t dt = X->dtype; + const int64_t w = (int64_t)std::ceil(6.0 / 0.99), K = 2 * w * r + 1, off = 2 * w * r; + std::vector f((size_t)K); + for (int64_t n = 0; n < K; ++n) { + const float u = keep(keep((float)n / (float)r - (float)w) * 0.99f); + const float uc = std::min(std::max(u, -6.0f), 6.0f); + const float cw = std::cos(keep(keep(uc * (float)M_PI) / 6.0f) / 2.0f); + const float pu = keep((float)M_PI * u); + const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu; + f[(size_t)n] = narrow1(dt, keep(keep(sinc * keep(cw * cw)) * 0.99f) / (float)r); + } + const int64_t xs = laststride(X), rs = laststride(Rz), ys = laststride(Y); + AVX_PARALLEL_FOR_IF(O * ch * K >= AVX_PAR_MIN) + for (int64_t o = 0; o < O; ++o) + for (int64_t h = 0; h < ch; ++h) { + const int64_t u = o + off; + float acc = 0.0f; + for (int64_t k = u % r; k < K; k += r) { + const int64_t i = (u - k) / r; + const int64_t s = std::min(std::max(i - w, 0), S - 1); + acc += keep(f[(size_t)k] * ldt(X, rowoff(X, s, ch) + h * xs)); + } + const float up = narrow1(dt, (float)r * narrow1(dt, acc)); + const float v = narrow1(dt, ldt(Rz, rowoff(Rz, o, ch) + h * rs) + up); + st_elem(Y->data, Y->dtype, rowoff(Y, o, ch) + h * ys, std::min(std::max(v, -1.0f), 1.0f)); + } + return RAD_OK; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 3d70387a..602ac0c6 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -297,6 +297,13 @@ static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_IN P_INTO("window_right") }; static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") }; +static const RadParamSpec pAttnCross[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"), + P_INT("causal"), P_STR("dtype"), P_F64O("scale") }; +static const RadOperandSpec oAttnCross[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), + OPD("cu_k"), OUT("out") }; +static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("kt"), P_INT("kh"), + P_INT("kw"), P_STR("dtype"), P_F64O("scale") }; +static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") }; static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), P_INT("block_size"), P_STR("kv_dtype"), @@ -504,6 +511,13 @@ static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") }; /* ---- image generation --------------------------------------------------------------------- */ static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") }; +static const RadParamSpec pTableAdd[] = { P_INT("M"), P_INT("n"), P_INT("L"), P_STR("dtype") }; +static const RadOperandSpec oTableAdd[] = { OPD("x"), WGT("t"), OUT("y") }; +static const RadParamSpec pMixRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") }; +static const RadParamSpec pChanStats[] = { P_INT("M"), P_INT("n"), P_STR("mode"), P_INTO("var"), + P_F64O("eps"), P_STR("dtype") }; +static const RadOperandSpec oChanStats[] = { OPD("x"), WGT("mean"), WGT("s"), OUT("y") }; +static const RadOperandSpec oMixRows[] = { OPD("x"), WGT("w"), OUT("y") }; static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") }; static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), @@ -511,12 +525,14 @@ static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"), - P_STR("dtype") }; -static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"), + P_STR("dtype"), P_F64O("wadd"), + P_INTO("norm_once"), P_STRO("norm") }; +static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"), OPD("cu_seqlens"), INOUT("x"), OUT("z") }; static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), - P_INT("gated"), P_STR("dtype") }; -static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"), + P_INT("gated"), P_STR("dtype"), P_F64O("wadd"), + P_INTO("norm_once"), P_STRO("norm") }; +static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"), OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"), @@ -590,7 +606,8 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se /* ---- the latent upscaler (avx_video.cpp), as libref declares it; patch_fold takes * patch_unfold's parameters and operands ------------------------------------------------------ */ static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), - P_INT("kt"), P_STR("dtype") }; + P_INT("kt"), P_STR("dtype"), P_STRO("tpad"), + P_INTO("tpre") }; static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"), OPD_O("res"), OUT("y") }; static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"), @@ -604,6 +621,52 @@ static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stre P_STR("dtype") }; static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") }; +/* ---- LTX-2 (avx_ltx.cpp) */ +static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"), + P_INT("dim"), P_INT("n_dims"), P_F64("theta"), + P_STR("max"), P_INTO("head0"), P_STR("dtype") }; +static const RadOperandSpec oRopeSplit[] = { INOUT("x"), OPD("positions") }; +static const RadParamSpec pHeadGate[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"), + P_STR("dtype") }; +static const RadOperandSpec oHeadGate[] = { OPD("g"), INOUT("x") }; +static const RadParamSpec pLtxGuide[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oLtxGuide[] = { OPD("vc"), OPD_O("vu"), OPD_O("vs"), OPD_O("vm"), + OPD("scales"), OPD("sched"), INOUT("stats"), + INOUT("x") }; +static const RadParamSpec pPixelNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("form"), + P_STRO("act"), P_INTO("ileave"), P_STR("dtype"), + P_F64O("mult") }; +static const RadOperandSpec oPixelNorm[] = { OPD("x"), OUT("y") }; +static const RadParamSpec pD2s3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"), + P_INTO("drop"), P_STR("dtype") }; +static const RadOperandSpec oD2s3d[] = { OPD("x"), OPD("geom"), OUT("y") }; +static const RadParamSpec pS2d3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"), + P_INTO("tpre"), P_INTO("group"), P_STR("mode"), + P_INTO("add"), P_STR("dtype") }; +static const RadOperandSpec oS2d3d[] = { OPD("x"), OPD("geom"), INOUT("y") }; +static const RadParamSpec pPixPatch[] = { P_INT("M"), P_INT("p"), P_INT("C"), P_STRO("order"), + P_STR("dtype") }; +static const RadOperandSpec oPixPatch[] = { OPD("x"), OUT("y") }; +static const RadParamSpec pVolIndex[] = { P_INT("M") }; +static const RadOperandSpec oVolIndex[] = { OPD("geom"), OUT("y") }; +static const RadParamSpec pTileGrid[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), P_STRO("rule"), + P_INTO("min"), P_INTO("tile_t"), P_INTO("stride_t"), + P_INTO("min_t"), P_INTO("tail") }; +static const RadOperandSpec oTileGrid[] = { OPD("geom"), OUT("y") }; +static const RadParamSpec pTileCrop[] = { P_INT("M"), P_INT("C"), P_STR("dtype") }; +static const RadOperandSpec oTileCrop[] = { OPD("x"), OPD("geom"), OPD("box"), OUT("y") }; +static const RadParamSpec pTileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), + P_STRO("rule"), P_INTO("min"), P_INTO("tile_t"), + P_INTO("stride_t"), P_INTO("min_t"), P_INT("scale"), + P_INTO("scale_t"), P_INT("p"), P_INT("C"), + P_STRO("order"), P_STR("dtype") }; +static const RadOperandSpec oTileStitch[] = { OPD("x"), OPD("geom"), OPD("first"), OUT("y") }; +static const RadParamSpec pStftMel[] = { P_INT("M"), P_INT("hop"), P_INT("nfft"), P_INT("n_mel"), + P_INT("ch"), P_STR("dtype") }; +static const RadOperandSpec oStftMel[] = { OPD("x"), WGT("basis"), WGT("mel"), OUT("y") }; +static const RadParamSpec pBweUp[] = { P_INT("M"), P_INT("ratio"), P_INT("ch"), P_STR("dtype") }; +static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") }; + /* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */ static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("dil"), P_STRO("act"), P_STR("dtype"), @@ -664,6 +727,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"), static const RadOperandSpec oIota[] = { OUT("y") }; static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") }; static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") }; +static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") }; +static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") }; /* ---- vocabulary edges --------------------------------------------------------------------- */ static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), @@ -881,6 +946,11 @@ static const RadOpSchema kSchemas[] = { { "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "dense varlen attention over cu_seqlens; a non-causal window may reach further right " "(`window_right`)." }, +{ "attn_cross", ARR(pAttnCross), ARR(oAttnCross), + "attn_dense with each entry's keys a run of their own (cu_k); causal counts from each run's " + "start." }, +{ "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d), + "3-D neighborhood attention over a volume, libref's window and arithmetic." }, { "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." }, { "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." }, { "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey), @@ -949,6 +1019,13 @@ static const RadOpSchema kSchemas[] = { { "ln_mod", ARR(pLnMod), ARR(oLnMod), "y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a gainless layer norm and the row's entry's " "modulation row of `s` ([n_seq, >= n] at its own pitch)." }, +{ "table_add", ARR(pTableAdd), ARR(oTableAdd), + "y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once." }, +{ "chan_stats", ARR(pChanStats), ARR(oChanStats), + "per-channel statistics held as weights: denorm rd(rd(x std) + mean), norm rd(rd(x - mean) / " + "std)." }, +{ "mix_rows", ARR(pMixRows), ARR(oMixRows), + "y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once." }, { "gate_add", ARR(pGateAdd), ARR(oGateAdd), "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), or with `act` none the gate g itself, bit for bit " "libref's." }, @@ -1032,6 +1109,29 @@ static const RadOpSchema kSchemas[] = { { "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise), "x = f32(f32(1 - s) x) + f32(s z), z the (seed, stream) normal stream at k n + c, bit for bit " "libref's." }, +{ "rope_split", ARR(pRopeSplit), ARR(oRopeSplit), + "LTX-2's split rotary over fractional coordinates, libref's arithmetic element by element." }, +{ "head_gate", ARR(pHeadGate), ARR(oHeadGate), + "x = rd(x rd(2 rd(sigmoid(g)))) per head, libref's." }, +{ "ltx_guide", ARR(pLtxGuide), ARR(oLtxGuide), + "LTX-2's guided sampler step in f32, libref's arithmetic with the deviations in f64." }, +{ "pixel_norm", ARR(pPixelNorm), ARR(oPixelNorm), + "an RMS norm over each row as bf16 tensors compute it, every step rounded; rsqrt or div form, " + "optionally silu, `ileave` interleaving the output; libref's." }, +{ "d2s3d", ARR(pD2s3d), ARR(oD2s3d), "depth to space over voxel rows, libref's copy." }, +{ "s2d3d", ARR(pS2d3d), ARR(oS2d3d), + "space to depth over voxel rows, a copy or the mean of each group, libref's." }, +{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch), "an image to patch rows, libref's copy." }, +{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch), "patch rows to RGB bytes, libref's rule." }, +{ "vol_index", ARR(pVolIndex), ARR(oVolIndex), "a volume's voxel coordinates, libref's." }, +{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid), "a tiled decode's boxes, libref's cut." }, +{ "tile_crop", ARR(pTileCrop), ARR(oTileCrop), "a tile out of a volume, libref's copy." }, +{ "tile_stitch", ARR(pTileStitch), ARR(oTileStitch), + "decoded tiles blended to RGB bytes, libref's blends and rounding." }, +{ "stft_logmel", ARR(pStftMel), ARR(oStftMel), + "each channel's causal log-mel spectrogram, libref's roundings." }, +{ "bwe_up", ARR(pBweUp), ARR(oBweUp), + "a Hann-windowed sinc resampler plus a residual, clamped, libref's roundings." }, { "conv1d", ARR(pConv1d), ARR(oConv1d), "a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost, PyTorch's " "[cout, cin, k] weight, dilation `dil`, centred or (`causal`) all on the left, zeros outside " @@ -1073,6 +1173,8 @@ static const RadOpSchema kSchemas[] = { { "interleave2", ARR(pInterleave), ARR(oInterleave2), "two streams interleaved, y [rows, 2]." }, { "iota", ARR(pIota), ARR(oIota), "y[i] = start + i * step." }, { "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "y[j] = j * len[0] * mult." }, +{ "int_affine", ARR(pIntAffine), ARR(oIntAffine), + "y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists." }, { "embed_lookup", ARR(pEmbedM), ARR(oEmbed), "embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." }, { "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ), @@ -1382,6 +1484,11 @@ ROW("avx_attn_paged", "attn_paged", "attn", cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(attn_paged)), SIMPLE("avx_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT, L(attn_dense)), +SIMPLE("avx_attn_cross", "attn_cross", "attn", + "dense varlen attention, keys bounded apart from the queries (cu_k)", DT_FLOAT, + L(attn_cross)), +SIMPLE("avx_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT, + L(attn_na3d)), ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY, cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store)), SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)), @@ -1458,6 +1565,12 @@ SIMPLE("avx_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + an entry' DT_FLOAT, L(ln_mod)), SIMPLE("avx_gate_add", "gate_add", "elem", "x += act(gate row) * y, act tanh or none", DT_FLOAT, L(gate_add)), +SIMPLE("avx_table_add", "table_add", "elem", "a row plus each of L table rows", DT_FLOAT, + L(table_add)), +SIMPLE("avx_mix_rows", "mix_rows", "elem", "a weighted sum of k consecutive rows", DT_FLOAT, + L(mix_rows)), +SIMPLE("avx_chan_stats", "chan_stats", "elem", "per-channel statistics held as weights", + DT_FLOAT, L(chan_stats)), SIMPLE("avx_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm", "gated residual, adaptive norm and the E4M3 quantiser in one pass", "float in, fp8_e4m3 out, f32 scale, bf16 z", L(ln_mod_quant_fp8)), @@ -1526,6 +1639,27 @@ SIMPLE("avx_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch r L(patch_fold)), SIMPLE("avx_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma", DT_FLOAT, L(flow_renoise)), +SIMPLE("avx_rope_split", "rope_split", "elem", "LTX-2's split rotary over coordinates", DT_FLOAT, + L(rope_split)), +SIMPLE("avx_head_gate", "head_gate", "elem", "each head times 2 sigmoid of its logit", DT_FLOAT, + L(head_gate)), +SIMPLE("avx_ltx_guide", "ltx_guide", "elem", "LTX-2's guided sampler step", DT_FLOAT, + L(ltx_guide)), +SIMPLE("avx_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors compute it", DT_FLOAT, + L(pixel_norm)), +SIMPLE("avx_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, L(d2s3d)), +SIMPLE("avx_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, L(s2d3d)), +SIMPLE("avx_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, L(pix_patch)), +SIMPLE("avx_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, L(patch_pix8)), +SIMPLE("avx_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, L(vol_index)), +SIMPLE("avx_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, L(tile_grid)), +SIMPLE("avx_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, L(tile_crop)), +SIMPLE("avx_tile_stitch", "tile_stitch", "elem", "decoded tiles blended to RGB bytes", DT_FLOAT, + L(tile_stitch)), +SIMPLE("avx_stft_logmel", "stft_logmel", "elem", "a causal log-mel spectrogram", DT_FLOAT, + L(stft_logmel)), +SIMPLE("avx_bwe_up", "bwe_up", "elem", "a sinc-resampled waveform plus a residual, clamped", + DT_FLOAT, L(bwe_up)), SIMPLE("avx_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, as GEMMs over patch rows", DT_FLOAT, L(conv1d)), @@ -1560,6 +1694,8 @@ SIMPLE("avx_interleave2", "interleave2", "elem", "two streams interleaved", DT_A L(interleave2)), SIMPLE("avx_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, L(iota)), SIMPLE("avx_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, L(cu_repeat)), +SIMPLE("avx_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY, + L(int_affine)), SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)), /* Its layout hook only validates: the table is read as stored and other encodings are refused diff --git a/libavx/avx_video.cpp b/libavx/avx_video.cpp index 431fe8c1..9aebb8fe 100644 --- a/libavx/avx_video.cpp +++ b/libavx/avx_video.cpp @@ -458,14 +458,21 @@ AVX_KERNEL(conv3d_ndhwc) { const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *G = &a->t[3]; const RadTensor *R = rad_arg_in(a, 4), *Y = &a->t[5]; const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0); - const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0); - if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(G) < 3) + const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0), tpre = p_int(a, "tpre", 0); + /* The frames' padding (libref's): zero, the edge frame repeated, or causal with `tpre` more + * copies of the first frame in front (T + tpre frames out). */ + const char* tps = p_str(a, "tpad", "zero"); + const int tpad = !std::strcmp(tps, "zero") ? 0 : !std::strcmp(tps, "replicate") ? 1 + : !std::strcmp(tps, "causal") ? 2 : -1; + if (tpad < 0 || (tpre && tpad != 2)) return RAD_E_INVAL; + if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || tpre < 0 || + numel(G) < 3) return RAD_E_SHAPE; const int64_t T = at(G, 0), H = at(G, 1), Wd = at(G, 2); if (T <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE; - const int64_t rows = T * H * Wd, taps = kt * k * k, KK = taps * cin; - if (rows_of(Y, cout) < rows || rows_of(X, cin) < rows || (R && rows_of(R, cout) < rows) || - numel(W) < cout * KK || numel(B) < cout) + const int64_t rows = (T + tpre) * H * Wd, taps = kt * k * k, KK = taps * cin; + if (rows_of(Y, cout) < rows || rows_of(X, cin) < T * H * Wd || + (R && rows_of(R, cout) < rows) || numel(W) < cout * KK || numel(B) < cout) return RAD_E_SHAPE; static thread_local std::vector wbuf, pbuf; static thread_local std::vector ybuf; @@ -505,7 +512,10 @@ AVX_KERNEL(conv3d_ndhwc) { for (int64_t dz = 0; dz < kt; ++dz) for (int64_t kh = 0; kh < k; ++kh) for (int64_t kw = 0; kw < k; ++kw, d += (size_t)cin * ael) { - const int64_t tz = t + dz - pz, iy = i + kh - ps, ix = j + kw - ps; + int64_t tz = t + dz - pz; + if (tpad == 1) tz = std::min(std::max(tz, 0), T - 1); + else if (tpad == 2) tz = std::max(t + dz - (kt - 1) - tpre, 0); + const int64_t iy = i + kh - ps, ix = j + kw - ps; if (tz < 0 || tz >= T || iy < 0 || iy >= H || ix < 0 || ix >= Wd) { std::memset(d, 0, (size_t)cin * ael); continue; diff --git a/libquant/lq_gptq.cpp b/libquant/lq_gptq.cpp index af4ce4bf..81edadd3 100644 --- a/libquant/lq_gptq.cpp +++ b/libquant/lq_gptq.cpp @@ -136,16 +136,14 @@ bool chol_upper_loop(std::vector& a, int64_t k) { return true; } +#ifdef RAD_LQ_LAPACK /* LAPACK where OpenBLAS was found; RAD_LQ_LAPACK=0 takes the loops instead, the reference the * LAPACK path is checked against (quant_algo_test). */ bool use_lapack() { -#ifdef RAD_LQ_LAPACK const char* e = std::getenv("RAD_LQ_LAPACK"); return !(e && e[0] == '0'); -#else - return false; -#endif } +#endif bool chol_lower(std::vector& a, int64_t k) { #ifdef RAD_LQ_LAPACK @@ -168,7 +166,7 @@ bool chol_upper(std::vector& a, int64_t k) { return chol_upper_loop(a, k); } -/* Layer factors kept at once (RAD_LQ_FACTOR_CACHE_ALL: every one). */ +/* Layer factors kept at once. */ constexpr size_t kFactors = 4; struct Cache { @@ -222,10 +220,9 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d * once, and a 21504-wide factor is 1.85 GB in f32 (every one kept OOM-killed * TranslateGemma 27B's conversion at layer 25). A MoE layer's experts run in parallel * and alternate between its gate_up and down stems, so one kept factor would be - * recomputed over and over. RAD_LQ_FACTOR_CACHE_ALL keeps every one. */ - static const bool all = std::getenv("RAD_LQ_FACTOR_CACHE_ALL") != nullptr; + * recomputed over and over. */ if (layer && !c.f.count(key)) { - while (!all && c.order.size() >= kFactors) { + while (c.order.size() >= kFactors) { c.f.erase(c.order.front()); c.order.pop_front(); } diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 351dca26..e8ccd9ad 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -81,6 +81,7 @@ set(R4D_UNITS # decoder's patch unfold, tiles, stitch and rotary positions, and the soundtrack decoder's # alias-free SnakeBeta. "r4d_video|" + "r4d_ltx|" # A video latent upscaler: the 3x3x3 convolution as an implicit GEMM over voxel rows, the group # norm, the temporal depthwise convolution, the per-frame bilinear resize, the patch fold and the # re-noise. diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 141b1b85..aa4c8509 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -869,6 +869,7 @@ int r4d_binary_bf16(long a, long b, long y, int M, int n, int op, int a_ld, int b_ld, int y_ld, long stream); int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream); int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream); +int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long stream); // y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The gate is the first half, the order rad-convert // fuses gate_proj and up_proj in. int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream); diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 1f348c96..7a76627a 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -362,9 +362,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, * fill a card while their twins wait behind the other engine's kernel on the peer card, which * waits for a slot on the full card. Not capped: the hyper-connection gathers of the MoE paths * (r4d_ar_gather_hc_write without its inverse scratch, r4d_ar_hc_write_wht6), whose LDS table - * needs a minimum block count, which may exceed the ceiling (dense models do not use them). Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B) - * hung within a minute of concurrent prefill; MES then failed to evict the queues and the - * failed reset froze the host. Capped in both engines so that their spinners together cannot + * needs a minimum block count, which may exceed the ceiling (dense models do not use them). + * Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B) hung within a minute of + * concurrent prefill; MES then failed to evict the queues and the failed reset froze the + * host. Capped in both engines so that their spinners together cannot * fill a card, the cycle cannot close. The flag and counter arrays keep their full size (maxb); * only the launch counts shrink, and each element's sum is the same. Unset, nothing changes. */ if (const char* e = std::getenv("R4D_AR_MAX_BLOCKS")) { diff --git a/libr4d/r4d_attn_dense_bf16.hip b/libr4d/r4d_attn_dense_bf16.hip index 6ef0329e..25799f63 100644 --- a/libr4d/r4d_attn_dense_bf16.hip +++ b/libr4d/r4d_attn_dense_bf16.hip @@ -1,8 +1,9 @@ // R4D dense attention, varlen over cu_seqlens segments, grouped-query: an encoder's, non-causal with // an optional two-sided window, i - j < window behind and j - i < wright ahead (wright is // `window_right`, or `window` for the symmetric |i - j| < window), or causal with an optional -// window behind (a codec's sliding layers). bf16 in and out, f16 operands, f32 accumulate. Head -// widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row. +// window behind (a codec's sliding layers, a text encoder's prompt). bf16 in and out, f16 +// operands, f32 accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair +// is a row. // // Core from the vision kernel (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32 // column-distributed accumulator gives each lane one query row, softmax state is lane-private, and @@ -39,7 +40,8 @@ __global__ __launch_bounds__(NQB * GQA * DSPLIT * 32) void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, const uint16_t* __restrict__ gv, uint16_t* __restrict__ go, const int* __restrict__ cu, float scale, int window, int wright, - int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld) + int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld, + int krep) { typedef DT16<1> D; typedef D::frag frag16; @@ -73,8 +75,9 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re const int dp = warp % DSPLIT; const int g = (warp / DSPLIT) % GQA; const int qbi = warp / (DSPLIT * GQA); - const int kvh = blockIdx.y, seq = blockIdx.z; - const int hq = kvh * GQA + g; + // blockIdx.y is a group of GQA query heads; krep groups read one KV head. + const int kvh = blockIdx.y / krep, seq = blockIdx.z; + const int hq = blockIdx.y * GQA + g; const int s0 = cu[seq] / cdiv, slen = cu[seq + 1] / cdiv - s0; const int q0 = blockIdx.x * BQ; @@ -301,21 +304,25 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re // ---- launch ---------------------------------------------------------------------------------- // One instantiation per (head_dim, gqa), at a workgroup shape picked for it: // h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads) -// h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB) -// h256 gqa4: 4 query blocks x 4 heads, tiles of 32 (LDS: 37 KiB) -// h512 gqa4: 2 query blocks x 4 heads x 2 head halves, tiles of 16 (LDS: 57 KiB) +// h256 gqa2, 4, 8: 8, 4, 2 query blocks x the heads, tiles of 32 (LDS: 37 KiB) +// h512 gqa2, 4, 8: 4, 2, 1 query blocks x the heads x 2 head halves, tiles of 16 (LDS: 57 KiB) +// The LDS holds one K/V tile, so the query heads a workgroup carries change its waves, not it. +// A wider group (16 query heads a KV head and up, any multiple of 8) runs as krep workgroups of +// eight heads each over the same KV head: 16 heads in one would need 32 waves and, at h512, more +// than 64 KiB of LDS. template static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o, const void* cu, int num_seqs, int max_seqlen, int n_head_kv, float scale, int window, int wright, int block, int cdiv, - int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s) + int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s, + int krep = 1) { constexpr int BQ = NQB * 16; - dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv, num_seqs); + dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv * krep, num_seqs); hipLaunchKernelGGL((r4d_attn_dense_kernel), grid, dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k, (const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, wright, - block, cdiv, causal, q_ld, k_ld, v_ld, o_ld); + block, cdiv, causal, q_ld, k_ld, v_ld, o_ld, krep); const hipError_t e = hipGetLastError(); return e == hipSuccess ? 0 : -100 - (int)e; } @@ -338,27 +345,34 @@ extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v, return -4; if (num_seqs <= 0 || max_seqlen <= 0) return 0; if (wright == 0) wright = window; - const int gqa = n_head / n_head_kv; + int gqa = n_head / n_head_kv, krep = 1; + if (gqa > 8 && gqa % 8 == 0) krep = gqa / 8, gqa = 8; hipStream_t s = (hipStream_t)stream; if (head_dim == 64 && gqa == 1) return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, n_head_kv, scale, window, wright, block, cdiv, causal, q_ld, k_ld, v_ld, o_ld, s); - if (head_dim == 256 && gqa == 2) - return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs, - max_seqlen, n_head_kv, scale, window, - wright, block, cdiv, causal, q_ld, k_ld, - v_ld, o_ld, s); - if (head_dim == 256 && gqa == 4) - return r4d_attn_dense_launch<256, 4, 4, 1, 32>(q, k, v, o, cu_seqlens, num_seqs, - max_seqlen, n_head_kv, scale, window, - wright, block, cdiv, causal, q_ld, k_ld, - v_ld, o_ld, s); - if (head_dim == 512 && gqa == 4) - return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs, - max_seqlen, n_head_kv, scale, window, - wright, block, cdiv, causal, q_ld, k_ld, - v_ld, o_ld, s); +#define R4D_DENSE(HD, G, NQB, DS, T) \ + return r4d_attn_dense_launch(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, \ + n_head_kv, scale, window, wright, block, \ + cdiv, causal, q_ld, k_ld, v_ld, o_ld, s, krep) + if (head_dim == 256) { + switch (gqa) { + case 2: R4D_DENSE(256, 2, 8, 1, 32); + case 4: R4D_DENSE(256, 4, 4, 1, 32); + case 8: R4D_DENSE(256, 8, 2, 1, 32); + default: return -1; + } + } + if (head_dim == 512) { + switch (gqa) { + case 2: R4D_DENSE(512, 2, 4, 2, 16); + case 4: R4D_DENSE(512, 4, 2, 2, 16); + case 8: R4D_DENSE(512, 8, 1, 2, 16); + default: return -1; + } + } +#undef R4D_DENSE return -1; } diff --git a/libr4d/r4d_attn_gen.hip b/libr4d/r4d_attn_gen.hip index 025043fd..6599bf9b 100644 --- a/libr4d/r4d_attn_gen.hip +++ b/libr4d/r4d_attn_gen.hip @@ -69,7 +69,8 @@ __global__ __launch_bounds__(NQB * GQA * 32) void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk, const int8_t* __restrict__ gk8, const float* __restrict__ gks, const uint16_t* __restrict__ gv, uint16_t* __restrict__ go, - const int* __restrict__ cu, int num_seqs, const int* __restrict__ used, + const int* __restrict__ cu, const int* __restrict__ cuk, int num_seqs, + const int* __restrict__ used, const int* __restrict__ bt, int bt_pitch, const uint16_t* __restrict__ kvc, int kv_heads, float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld, @@ -137,7 +138,10 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr if (slen <= 0 || q0 >= slen) return; const int qlast = min(q0 + BQ, slen) - 1; const int P = used ? used[seq] : 0; - const int ke = causal ? qlast + 1 : slen; // own keys any query here can see + // Own keys: beside the queries, or (`cuk`, attn_cross) a run of their own; a query sees key j + // of its run, counted from the run's start, when j <= its own row with `causal`. + const int ks0 = cuk ? cuk[seq] : s0, klen = cuk ? cuk[seq + 1] - ks0 : slen; + const int ke = causal ? min(qlast + 1, klen) : klen; // own keys any query here can see const float mul = scale * 1.44269504089f; const int qpos = q0 + qbi * 16 + c; @@ -193,12 +197,12 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr // The K row of key `kk` of the current source; its V row is `vrow`. auto krow = [&](bool pre, int kk) -> const uint16_t* { - if (!pre) return kbase + (long)(s0 + kk) * k_ld; + if (!pre) return kbase + (long)(ks0 + kk) * k_ld; const int blk = btrow[kk / BS]; return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD); }; auto vrow = [&](bool pre, int kk) -> const uint16_t* { - if (!pre) return vbase + (long)(s0 + kk) * v_ld; + if (!pre) return vbase + (long)(ks0 + kk) * v_ld; const int blk = btrow[kk / BS]; return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD) + HD; }; @@ -222,12 +226,12 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr if ((TILE * K8G) % NTHR == 0 || i < TILE * K8G) { const int key = i / K8G, gg = i % K8G; const int kk = (k0 + key < klim) ? k0 + key : klim - 1; - kr[p] = *(const uint4*)(gk8 + (long)(s0 + kk) * k8_ld + (long)kvh * HD + gg * 16); + kr[p] = *(const uint4*)(gk8 + (long)(ks0 + kk) * k8_ld + (long)kvh * HD + gg * 16); } } if (tid < TILE) { const int kk = (k0 + tid < klim) ? k0 + tid : klim - 1; - ksr = gks[(long)(s0 + kk) * ks_ld + kvh]; + ksr = gks[(long)(ks0 + kk) * ks_ld + kvh]; } } else { #pragma unroll @@ -243,7 +247,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr if constexpr (PV8) { const int kk0 = k0 + (lgi / DG8) * 8 + vj; const int kk = (kk0 < klim) ? kk0 : klim - 1; - const uint8_t* v8 = (const uint8_t*)gv + (long)(s0 + kk) * v_ld + (long)kvh * HD; + const uint8_t* v8 = (const uint8_t*)gv + (long)(ks0 + kk) * v_ld + (long)kvh * HD; vr[0] = __builtin_bit_cast(uint4, load_tr_b128(v8 + (lgi % DG8) * 16)); } else { #pragma unroll @@ -597,7 +601,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr template static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, const float* ks, - const void* v, void* o, const int* cu, + const void* v, void* o, const int* cu, const int* cuk, const int* used, const int* bt, int bt_pitch, const void* kvc, int num_seqs, int max_q, int n_head_kv, float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld, int v_ld, int o_ld, @@ -609,14 +613,15 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons hipLaunchKernelGGL((r4d_attn_ps_kernel), grid, dim3(NQB * GQA * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks, - (const uint16_t*)v, (uint16_t*)o, cu, num_seqs, used, bt, bt_pitch, + (const uint16_t*)v, (uint16_t*)o, cu, cuk, num_seqs, used, bt, bt_pitch, (const uint16_t*)kvc, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs); const hipError_t e = hipGetLastError(); return e == hipSuccess ? 0 : -100 - (int)e; } -/* head_dim 128 at gqa 1, 2, 4 and 8. Null `used`/`bt`/`kvc` means no prefix (the dense form). +/* head_dim 128 at gqa 1, 2, 4 and 8, and 64 (an audio stream's heads) without a prefix or the + * int8 and fp8 forms. Null `used`/`bt`/`kvc` means no prefix (the dense form). * `max_q` is the total query rows over all sequences and bounds the flat grid. Non-null `k8` * selects the int8 Q.K form (own-key codes, `k8_ld` bytes per row; a scale per (row, head) in * `ks`, `ks_ld` floats per row), gqa 1 only. Non-null `vs` selects the fp8 P.V form (`v` as E4M3 @@ -626,16 +631,34 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float const int* used, const int* bt, int bt_pitch, const void* kvc, int num_seqs, int max_q, int n_head, int n_head_kv, int head_dim, float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld, - int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr) + int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr, + const int* cuk = nullptr) { if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2; if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3; if (k8 && ((k8_ld & 15) || ((uintptr_t)k8 & 15) || !ks)) return -3; if (num_seqs <= 0 || max_q <= 0) return 0; const int gqa = n_head / n_head_kv; + if (head_dim == 64) { + if (k8 || vs || used || bt || kvc) return -1; +#define R4D_PS64(G, NQB) \ + return r4d_attn_ps_launch<64, G, NQB, 64, false, false>(q, k, k8, ks, v, o, cu, cuk, used, \ + bt, bt_pitch, kvc, num_seqs, \ + max_q, n_head_kv, scale, causal, \ + q_ld, k_ld, k8_ld, ks_ld, v_ld, \ + o_ld, nullptr, s) + switch (gqa) { + case 1: R4D_PS64(1, 16); + case 2: R4D_PS64(2, 4); + case 4: R4D_PS64(4, 2); + case 8: R4D_PS64(8, 1); + default: return -1; + } +#undef R4D_PS64 + } if (head_dim != 128) return -1; #define R4D_PS(G, NQB, T, I8) \ - return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, used, bt, \ + return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, cuk, used, bt, \ bt_pitch, kvc, num_seqs, max_q, \ n_head_kv, scale, causal, q_ld, k_ld, \ k8_ld, ks_ld, v_ld, o_ld, nullptr, s) @@ -646,10 +669,10 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float if (gqa != 1 || used || bt || kvc || (v_ld & 15) || ((uintptr_t)v & 15)) return -1; if (k8) return r4d_attn_ps_launch<128, 1, 16, 64, true, true>( - q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, + q, k, k8, ks, v, o, cu, cuk, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s); return r4d_attn_ps_launch<128, 1, 16, 64, false, true>( - q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale, + q, k, k8, ks, v, o, cu, cuk, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s); } if (k8) { @@ -791,8 +814,44 @@ extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) { return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE); } -// ============================================================== wide heads (attn_dense, h768 / h1152) -// Image decoder mid-block attention: one head up to 1152 wide over every latent pixel (16384 rows +/* attn_cross at head_dim 64 or 128: the dense kernel with each entry's keys a run of their own + * (`cu_k`), causal counting from each run's start. */ +extern "C" int r4d_rad_attn_cross(const RadArgs* a, RadStream s) { + const RadTensor* q = r4d_opt(a, 0); + const RadTensor* k = r4d_opt(a, 1); + const RadTensor* v = r4d_opt(a, 2); + const RadTensor* cu = r4d_opt(a, 3); + const RadTensor* ck = r4d_opt(a, 4); + const RadTensor* o = r4d_opt(a, 5); + if (!q || !k || !v || !cu || !ck || !o) return R4D_NO(RAD_E_INVAL); + if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2 || !r4d_contig(ck) || + r4d_numel(ck) < cu->shape[0]) + return R4D_NO(RAD_E_SHAPE); + const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1); + if ((hd != 64 && hd != 128) || gqa <= 0) return R4D_NO(RAD_E_SHAPE); + long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0; + long long to = 0, ho = 0, o_ld = 0; + if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) || + !r4d_head_rows(k, hd, &tk, &hk, &k_ld) || + !r4d_head_rows(v, hd, &tv, &hv, &v_ld) || + !r4d_head_rows(o, hd, &to, &ho, &o_ld)) + return R4D_NO(RAD_E_STRIDE); + if (hk != hv || ho != nh || hk * gqa != nh || tk != tv || to < total) return R4D_NO(RAD_E_SHAPE); + const int num_seqs = (int)(cu->shape[0] - 1); + const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd)); + const int e = r4d_attn_ps(q->data, k->data, nullptr, nullptr, v->data, o->data, + (const int*)cu->data, nullptr, nullptr, 0, nullptr, num_seqs, + (int)total, (int)nh, (int)hk, (int)hd, scale, + (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, 0, 0, + (int)v_ld, (int)o_ld, (hipStream_t)s, nullptr, + (const int*)ck->data); + if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE); + if (e == 0) return RAD_OK; + return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE); +} + +// ============================================================== wide heads (attn_dense, h384 .. h1152) +// Image decoder mid-block attention: one head 384 to 1152 wide over every latent pixel (16384 rows // at 2048 x 2048). A lane cannot hold a 1152-wide output row (576 accumulator VGPRs), so the head // is split across the workgroup's eight waves: a wave owns HD/8 dims of the 16-query block. // @@ -945,7 +1004,8 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) { if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL); if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE); const long long hd = r4d_geti_or(a, "head_dim", 0); - if ((hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 || r4d_geti_or(a, "causal", 0) != 0 || + if ((hd != 384 && hd != 512 && hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 || + r4d_geti_or(a, "causal", 0) != 0 || r4d_geti_or(a, "window", 0) != 0 || r4d_geti_or(a, "block", 0) != 0 || r4d_geti_or(a, "cu_div", 1) != 1) return R4D_NO(RAD_E_UNSUPPORTED); @@ -967,8 +1027,10 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) { (const uint16_t*)q->data, (const uint16_t*)k->data, \ (const uint16_t*)v->data, (uint16_t*)o->data, (const int*)cu->data, \ num_seqs, scale, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld) - if (hd == 768) R4D_WIDE(768); - else R4D_WIDE(1152); + if (hd == 384) R4D_WIDE(384); + else if (hd == 512) R4D_WIDE(512); + else if (hd == 768) R4D_WIDE(768); + else R4D_WIDE(1152); #undef R4D_WIDE return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } diff --git a/libr4d/r4d_attn_paged_gqa8.hip b/libr4d/r4d_attn_paged_gqa8.hip index 15eb6c03..ab6bbb27 100644 --- a/libr4d/r4d_attn_paged_gqa8.hip +++ b/libr4d/r4d_attn_paged_gqa8.hip @@ -54,6 +54,12 @@ using std::max; #ifndef R4D_ATTN_H256 #define R4D_ATTN_H256 1 #endif +/* The fp8_v4 and k6_v4 caches at head_dim 256 (RadBuildCtx::kv_quant), off unless the including + * unit serves a model whose plugin offers them: Qwen3.8-Flash-Next's QSA layers (gqa12, and gqa6 + * at four ranks). The kernels are the h256/gqa6 templates' O_V4 / O_K6 forms. */ +#ifndef R4D_ATTN_V4 +#define R4D_ATTN_V4 0 +#endif #define GQ_JOIN_(a, b, c) a##b##c #define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c) #define GQ_SYM(pre, suf) GQ_JOIN(pre, R4D_ATTN_GQA, suf) @@ -99,10 +105,11 @@ extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) { return r4d_decode_scratch(a, r4d_decode_splits(a, G8_D_TILE), G8_D_OPT); } -template +template /* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168 * bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the - * combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). */ + * combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). `XOPT` adds + * option bits to the attention kernel's (O_V4, O_K6: the cache layout). */ static int g8_decode_launch(const R4DArgs* a, RadStream stream, const R4DGateQuant* gq = nullptr) { int emit_rc = RAD_OK; @@ -115,12 +122,14 @@ static int g8_decode_launch(const R4DArgs* a, RadStream stream, #define G8_LAUNCH(NW) \ emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel), \ + G8_BLOCK_SIZE, KVP, G8_D_OPT | XOPT>), \ dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, *a, splits) - /* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. */ + /* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. A v4 + * cache stages V widened (the kernel drops O_V8 under O_V4). */ if (nw == 1) emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<1, G8_D_TILE, HEAD_DIM, G8_GQA, - G8_BLOCK_SIZE, KVP, G8_D_OPT | O_V8>), + G8_BLOCK_SIZE, KVP, + G8_D_OPT | O_V8 | XOPT>), dim3(splits, a->kv_heads, a->num_seqs), dim3(32), 0, *a, splits); else if (nw == 2) G8_LAUNCH(2); else if (nw == 3) G8_LAUNCH(3); @@ -227,7 +236,9 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad * parameters and no tensors, so parameters come first and tensors are the fallback (see the * h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs, because * S * floor(128 / (kv_heads * S)) is not monotone in S. */ -static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) { +/* `row` is a token's bytes in a (block, head) page, 0 for the 16-bit and E4M3 caches' 2 * head_dim + * (fill_paged_row). */ +static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = 0) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); @@ -254,7 +265,7 @@ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) { } return worst; } - const int rc = fill_paged(a, &r, head_dim); + const int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim); if (rc != RAD_OK) return rc; r.splits = sp; return GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r); @@ -271,10 +282,10 @@ extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h128_gqa, _scratch)(const RadArgs* } #endif -static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim) { +static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim, long long row = 0) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); - const int rc = fill_paged(a, r, head_dim); + const int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim); if (rc != RAD_OK) return rc; r->splits = sp; const int64_t need = GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(r); @@ -380,3 +391,39 @@ extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _bf16)(const RadArgs* a, Rad return g8_decode_launch<128, 1>(&r, s); } #endif + +#if R4D_ATTN_H256 && R4D_ATTN_V4 +/* ---- the fp8_v4 cache (a token's row 25 * 256 / 16 = 400 bytes: E4M3 K, int4 V, f16 scales) and + * the k6_v4 cache (352 bytes: int6 K, int4 V), prefill, decode and decode with the gate and + * quantiser in the merge. */ +#define G8_V4_ENTRIES(TAG, ROWB, XOPT) \ +extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _##TAG)(const RadArgs* a, RadStream s) { \ + R4DArgs r; \ + const int rc = fill_paged_row(a, &r, 256, ROWB); \ + if (rc != RAD_OK) return rc; \ + return g8_prefill_launch<256, G8_P_OPT_256 | (XOPT), 0>(&r, (hipStream_t)s); \ +} \ +extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h256_gqa, _##TAG##_scratch)(const RadArgs* a) { \ + return g8_decode_scratch(a, 256, ROWB); \ +} \ +extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _##TAG)(const RadArgs* a, \ + RadStream stream) { \ + R4DArgs r; \ + const int rc = g8_decode_common(a, &r, 256, ROWB); \ + if (rc != RAD_OK) return rc; \ + return g8_decode_launch<256, 0, (XOPT)>(&r, stream); \ +} \ +extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _##TAG)(const RadArgs* a, \ + RadStream stream) { \ + R4DArgs r; \ + const int rc = g8_decode_common(a, &r, 256, ROWB); \ + if (rc != RAD_OK) return rc; \ + R4DGateQuant gq{}; \ + const int gc = g8_gate_quant_args(a, r, &gq); \ + if (gc != RAD_OK) return gc; \ + return g8_decode_launch<256, 0, (XOPT)>(&r, stream, &gq); \ +} +G8_V4_ENTRIES(fp8v4, 400, O_V4) +G8_V4_ENTRIES(k6v4, 352, O_V4 | O_K6) +#undef G8_V4_ENTRIES +#endif diff --git a/libr4d/r4d_attn_paged_h256_gqa12.hip b/libr4d/r4d_attn_paged_h256_gqa12.hip index 971a915c..f589e125 100644 --- a/libr4d/r4d_attn_paged_h256_gqa12.hip +++ b/libr4d/r4d_attn_paged_h256_gqa12.hip @@ -17,5 +17,7 @@ // pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16 here // would refuse at issue rather than at declare. #define G8_BLOCK_SIZE 4 +// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers. +#define R4D_ATTN_V4 1 #include "r4d_attn_paged_gqa8.hip" diff --git a/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip b/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip index 6330c1bd..2394aad6 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6_bs4.hip @@ -19,5 +19,7 @@ // the pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16 // here would refuse at issue rather than at declare. #define G8_BLOCK_SIZE 4 +// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers. +#define R4D_ATTN_V4 1 #include "r4d_attn_paged_gqa8.hip" diff --git a/libr4d/r4d_audio.hip b/libr4d/r4d_audio.hip index 8bf20db2..1cf06249 100644 --- a/libr4d/r4d_audio.hip +++ b/libr4d/r4d_audio.hip @@ -16,6 +16,7 @@ #include "rad_philox.h" #include +#include #include namespace { @@ -970,6 +971,17 @@ __global__ __launch_bounds__(kT) void iota_kernel(int* __restrict__ y, int n, in if (i < n) y[i] = start + (period > 0 ? i % period : i) * step; } +// y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j], the lists by value. +constexpr int kAffMax = 16; +struct IntAffine { int src[kAffMax], mul[kAffMax], add[kAffMax]; }; + +__global__ __launch_bounds__(kAffMax) void int_affine_kernel(const int* __restrict__ x, + int* __restrict__ y, IntAffine p, + int n) { + const int j = threadIdx.x; + if (j < n) y[j] = (p.src[j] < 0 ? 0 : x[p.src[j]]) * p.mul[j] + p.add[j]; +} + __global__ __launch_bounds__(kT) void cu_repeat_kernel(const int* __restrict__ len, int* __restrict__ y, int n, int mult) { const int j = blockIdx.x * kT + threadIdx.x; @@ -1597,6 +1609,38 @@ extern "C" int r4d_rad_iota(const RadArgs* a, RadStream s) { return st_of(hipGetLastError()); } +namespace { +int parse_ints(const char* s, int* v, int cap) { + int n = 0; + while (s && *s) { + char* e = nullptr; + const long x = std::strtol(s, &e, 10); + if (e == s) break; + if (n == cap) return -1; + v[n++] = (int)x; + s = e; + } + return n; +} +} // namespace + +extern "C" int r4d_rad_int_affine(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_i32(x) || !is_i32(y)) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(x) || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE); + IntAffine p{}; + const int n = parse_ints(r4d_gets(a, "src"), p.src, kAffMax); + if (n <= 0 || parse_ints(r4d_gets(a, "mul"), p.mul, kAffMax) != n || + parse_ints(r4d_gets(a, "add"), p.add, kAffMax) != n || r4d_numel(y) < n) + return R4D_NO(RAD_E_SHAPE); + for (int j = 0; j < n; ++j) + if (p.src[j] >= r4d_numel(x)) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(int_affine_kernel, dim3(1), dim3(kAffMax), 0, (hipStream_t)s, + (const int*)x->data, (int*)y->data, p, n); + return st_of(hipGetLastError()); +} + extern "C" int r4d_rad_cu_repeat(const RadArgs* a, RadStream s) { const RadTensor *len = r4d_opt(a, 0), *y = r4d_opt(a, 1); if (!len || !y) return R4D_NO(RAD_E_INVAL); diff --git a/libr4d/r4d_fp8_f32scale.hip b/libr4d/r4d_fp8_f32scale.hip index fe947940..b961814d 100644 --- a/libr4d/r4d_fp8_f32scale.hip +++ b/libr4d/r4d_fp8_f32scale.hip @@ -1,6 +1,7 @@ /* Canonical E4M3 weights with exact F32 block scales: native FP8 WMMA and F32 scale folding, no - * checkpoint scale narrowing. The grouped form and the legacy dense form compute one 16x64 output - * tile a block; the dense decode and prefill forms below them produce the same bytes faster. */ + * checkpoint scale narrowing. The legacy dense form computes one 16x64 output tile a block; the + * dense decode and prefill forms below it produce the same bytes faster, and the grouped form runs + * expert-major over the same per-element sequence. */ #include #include "r4d_args.h" #include "r4d_emit.h" @@ -8,108 +9,75 @@ #include "r4d_fp8_wmma.h" #include "r4d_launch.h" #include -#include #include -#include #include namespace { struct Meta { long ar, asr, yr, wr, sr, wstep[2], sstep[2]; - int T, N, K, experts, topk, sorted_a, tile; + int T, N, K, experts, topk, sorted_a; }; __device__ const uint8_t* entry(const void* p, long step, int e) { return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e]; } -template -__global__ void fp8_f32scale(const uint8_t* a, const float* as, const void* w0, const void* s0, - const void* w1, const void* s1, const int* sorted, const int* offsets, +/* The legacy dense form: a block per 16 rows by 64 columns, the operands staged through LDS a + * dword at a time, so it serves any row pitch and alignment. */ +__global__ void fp8_f32scale(const uint8_t* a, const float* as, const uint8_t* w, const float* ws, uint16_t* y, Meta m) { const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, n0 = blockIdx.x * 64; __shared__ uint8_t qa[16 * 136], wb[64 * 136]; __shared__ int source[16]; - int first = (int)blockIdx.y * (Grouped ? m.tile : 16); - const int limit = min(first + (Grouped ? m.tile : 16), m.T); - while (first < limit) { - int expert = 0, end = limit; - if constexpr (Grouped) { - // Tile sorted rows rather than launching every expert, most of which are empty - // during native MTP decode. Split a tile at each expert boundary. - if (sorted[first] < 0 || offsets[m.experts] <= first) { - for (int c = tid; c < 64; c += 128) - if (n0 + c < m.N) y[(long)first * m.yr + n0 + c] = 0; - ++first; - continue; + const int first = (int)blockIdx.y * 16, end = min(first + 16, m.T); + if (tid < 16) { + const int r = first + tid; + source[tid] = r < end ? r : -1; + } + __syncthreads(); + auto acc = r4d_fp8::acc_zero(); + for (int k0 = 0; k0 < m.K; k0 += 128) { + for (int j = tid; j < 16 * 32; j += 128) { + const int r = j / 32, c = (j % 32) * 4, src = source[r]; + uint32_t v = 0; + if (src >= 0) { + const auto* p = a + (long)src * m.ar + k0 + c; + v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | + ((uint32_t)p[3] << 24); } - int lo = 0, hi = m.experts; - while (lo + 1 < hi) { - const int mid = (lo + hi) / 2; - if (offsets[mid] <= first) - lo = mid; - else - hi = mid; - } - expert = lo; - end = min(limit, offsets[expert + 1]); - if (end <= first) return; + *(uint32_t*)(qa + r * 136 + c) = v; } - const int parity = Grouped ? expert & 1 : 0, e = Grouped ? expert / 2 : 0; - const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e); - const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e); - if (tid < 16) { - const int r = first + tid; - const int flat = Grouped && r < end ? sorted[r] : r; - source[tid] = r < end && flat >= 0 ? (Grouped && !m.sorted_a ? flat / m.topk : r) : -1; + for (int j = tid; j < 64 * 32; j += 128) { + const int r = j / 32, c = (j % 32) * 4; + const auto* p = w + (long)(n0 + r) * m.wr + k0 + c; + *(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | + ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); } __syncthreads(); - auto acc = r4d_fp8::acc_zero(); - for (int k0 = 0; k0 < m.K; k0 += 128) { - for (int j = tid; j < 16 * 32; j += 128) { - const int r = j / 32, c = (j % 32) * 4, src = source[r]; - uint32_t v = 0; - if (src >= 0) { - const auto* p = a + (long)src * m.ar + k0 + c; - v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | - ((uint32_t)p[3] << 24); - } - *(uint32_t*)(qa + r * 136 + c) = v; - } - for (int j = tid; j < 64 * 32; j += 128) { - const int r = j / 32, c = (j % 32) * 4; - const auto* p = w + (long)(n0 + r) * m.wr + k0 + c; - *(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | - ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); - } - __syncthreads(); - auto raw = r4d_fp8::acc_zero(); + auto raw = r4d_fp8::acc_zero(); #pragma unroll - for (int k = 0; k < 128; k += 16) - raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane), - r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw); - const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128]; -#pragma unroll - for (int j = 0; j < 8; ++j) { - const int src = source[(lane >> 4) * 8 + j]; - const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0; - acc[j] += raw[j] * scale; - } - __syncthreads(); - } + for (int k = 0; k < 128; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane), + r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw); + const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128]; #pragma unroll for (int j = 0; j < 8; ++j) { - const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15); - if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]); + const int src = source[(lane >> 4) * 8 + j]; + const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0; + acc[j] += raw[j] * scale; } __syncthreads(); - first = end; + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15); + if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]); } } /* The grouped form expert-major: a block per (column span, expert) takes every row of its * expert in 16-row tiles, so an expert slice is read from memory once however its rows fall in - * the sorted order (the row tiles above re-read it once per tile its run spans). Each element - * keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as raw * - * (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K in - * stages of StageK, as one stage sequence with the next stage loaded into registers while the + * the sorted order (16-row tiles of the sorted order read it once per tile its run spans). Each + * element keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as + * raw * (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K + * in stages of StageK, as one stage sequence with the next stage loaded into registers while the * current one computes from LDS. Block row `experts` zeroes the dropped rows past * offsets[experts]. */ typedef unsigned f8_u4 __attribute__((ext_vector_type(4))); @@ -237,15 +205,15 @@ __global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, co } // Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same // eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's -// row segment, which the old kernel copied through LDS unchanged), then acc += raw * (a_scale * +// row segment, which the legacy form copies through LDS unchanged), then acc += raw * (a_scale * // w_scale) in ascending block order. A WMMA output depends only on its own A row, B column and // C, so which rows and columns share a tile does not change it. // Decode: one wave C adjacent 16-column tiles, S waves of a block on S consecutive K blocks at // once, the fragments loaded straight from global memory; R row tiles share each weight fragment // and C column tiles each activation fragment. Each wave scales its own partial products (the -// a_scale x w_scale product and the multiply are the old fold's own two roundings) into LDS; then -// every wave folds a share of the outputs, adding the round's products in block order to the +// a_scale x w_scale product and the multiply are the legacy fold's own two roundings) into LDS; +// then every wave folds a share of the outputs, adding the round's products in block order to the // output's running sum, which lives in LDS between rounds. The block's activation scales are // staged in LDS when they fit (`stage`). template @@ -338,7 +306,7 @@ __global__ void fp8_f32scale_decode(const uint8_t* a, const float* as, const uin } } -// Prefill: the old kernel's 64-column block and LDS layout over R row tiles, so a staged weight +// Prefill: the legacy form's 64-column block and LDS layout over R row tiles, so a staged weight // block serves R*16 rows instead of 16, staged with 16-byte loads and the next K block loaded // into registers while the current one is multiplied. template @@ -413,54 +381,18 @@ __global__ void __launch_bounds__(128) } } -// The dense form. RADIANCE_FP8F32_FORM names "legacy", "rows1"/"rows2"/"rows4" (row tiles a -// block) or "decode", optionally "decodeRxS" or "decodeRxSxC" (R row tiles, S waves a block, C -// column tiles a wave); otherwise the rule at the end of dense_form. The forms are byte-identical; -// the choice is speed only. +// The dense form: a decode form (`decode`, C column tiles a wave, S waves a block) or the row +// tiles (R of 16 rows a block), by the rule at the end of dense_form. The forms are +// byte-identical; the choice is speed only. struct Form { - int kind = 0, r = 0, s = 0, c = 1; -}; // kind 0 legacy, 1 decode, 2 rows + bool decode = false; + int r = 1, s = 1, c = 1; +}; constexpr int kLdsCap = 64 * 1024; long decode_lds(int R, int S, int C, long KB, bool stage) { return ((long)S * R * C * 8 * 32 + (long)R * C * 8 * 32 + (stage ? (long)R * 16 * KB : 0)) * 4; } -// Row tiles a decode block shares a weight fragment over (at most three: four need 192 registers -// and spill), then waves a block: doubled while the grid stays under 1024 waves, the K blocks last -// and the exchange fits the LDS. -Form decode_plan(long N, long K, long T) { - Form f; - f.kind = 1; - const long tiles = (T + 15) / 16, kb = K / 128; - f.r = (int)(tiles >= 3 ? 3 : tiles); - const long blocks = (N / 16) * ((tiles + f.r - 1) / f.r); - f.s = 1; - while (f.s < 32 && f.s * 2 <= kb && blocks * f.s < 1024 && - decode_lds(f.r, f.s * 2, 1, kb, false) <= kLdsCap) - f.s *= 2; - return f; -} Form dense_form(long N, long K, long T) { - if (const char* e = std::getenv("RADIANCE_FP8F32_FORM")) { - if (!std::strcmp(e, "legacy")) return Form{}; - if (!std::strncmp(e, "rows", 4)) { - Form f; - f.kind = 2; - f.r = e[4] == '1' ? 1 : e[4] == '2' ? 2 : 4; - return f; - } - if (!std::strncmp(e, "decode", 6)) { - Form f = decode_plan(N, K, T); - int r = 0, s = 0, c = 1; - const int n = std::sscanf(e + 6, "%dx%dx%d", &r, &s, &c); - if (n >= 2 && r >= 1 && r <= 3 && s >= 1 && s <= 32 && (s & (s - 1)) == 0 && - (c == 1 || c == 2 || c == 4) && !(r == 3 && c == 4)) { - f.r = r; - f.s = s; - f.c = c; - } - return f; - } - } // Measured on gfx1201 (r4d_selftest --perfq, cold) at GLM's six shapes: decode1x8 up to 16 // rows; from 17 to 64 two column tiles a wave (decode1x8x2) lead by 5 to 15 %, except at N 512 // (too few column tiles, 1x8 stays) and N 4096 over K 1536, where the 16-row tile wins; from 65 @@ -472,14 +404,12 @@ Form dense_form(long N, long K, long T) { const bool rows = T > 128 || (T > 64 && K <= 2048) || (T > 16 && T <= 64 && K <= 1536 && N >= 4096); if (!rows) { - f.kind = 1; - f.r = 1; + f.decode = true; f.c = T > 16 && T <= 64 && N > 512 ? 2 : 1; f.s = 8; while (f.s > 1 && f.s > kb) f.s /= 2; return f; } - f.kind = 2; f.r = T > 64 && N >= 4096 ? 2 : 1; return f; } @@ -494,35 +424,28 @@ int dense_fast(RadStream stream, const RadTensor& x, const RadTensor& xs, const const RadTensor& ws, const RadTensor& y, const Meta& m, bool* done) { *done = false; const Form f = dense_form(m.N, m.K, m.T); - if (!f.kind || m.wr % 16 || m.ar % 16 || + if (m.wr % 16 || m.ar % 16 || (reinterpret_cast(x.data) | reinterpret_cast(w.data)) % 16) return RAD_OK; const uint8_t *xa = (const uint8_t*)x.data, *wa = (const uint8_t*)w.data; const float *xsa = (const float*)xs.data, *wsa = (const float*)ws.data; uint16_t* ya = (uint16_t*)y.data; - if (f.kind == 1) { + if (f.decode) { const long kb = m.K / 128; - const int stage = decode_lds(f.r, f.s, f.c, kb, true) <= kLdsCap; - const long lds = decode_lds(f.r, f.s, f.c, kb, stage); + const int stage = decode_lds(1, f.s, f.c, kb, true) <= kLdsCap; + const long lds = decode_lds(1, f.s, f.c, kb, stage); if (lds > kLdsCap || m.N % (16 * f.c)) return RAD_OK; *done = true; - const dim3 grid(m.N / (16 * f.c), (unsigned)(((m.T + 15) / 16 + f.r - 1) / f.r)), - block(32 * f.s); -#define F32S_DECODE(R_, C_) \ - if (f.r == R_ && f.c == C_) \ - return R4D_EMIT(stream, (fp8_f32scale_decode), grid, block, (uint32_t)lds, xa, \ - xsa, wa, wsa, ya, m, stage); - F32S_DECODE(1, 1) - F32S_DECODE(2, 1) F32S_DECODE(3, 1) F32S_DECODE(1, 2) F32S_DECODE(2, 2) F32S_DECODE(3, 2) - F32S_DECODE(1, 4) F32S_DECODE(2, 4) -#undef F32S_DECODE - * done = false; - return RAD_OK; + const dim3 grid(m.N / (16 * f.c), (unsigned)((m.T + 15) / 16)), block(32 * f.s); + if (f.c == 2) + return R4D_EMIT(stream, (fp8_f32scale_decode<1, 2>), grid, block, (uint32_t)lds, xa, + xsa, wa, wsa, ya, m, stage); + return R4D_EMIT(stream, (fp8_f32scale_decode<1, 1>), grid, block, (uint32_t)lds, xa, xsa, + wa, wsa, ya, m, stage); } *done = true; - if (f.r == 1) return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m); if (f.r == 2) return emit_rows<2>(stream, xa, xsa, wa, wsa, ya, m); - return emit_rows<4>(stream, xa, xsa, wa, wsa, ya, m); + return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m); } int body(const RadArgs* a, RadStream stream, bool grouped) { if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL; @@ -539,7 +462,7 @@ int body(const RadArgs* a, RadStream stream, bool grouped) { y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 || y.shape[0] < 1 || y.shape[0] > INT_MAX) return RAD_E_SHAPE; - const int rank = grouped ? 3 : 2; + const uint32_t rank = grouped ? 3 : 2; if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K || ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 || ws.stride[rank - 1] != 1) @@ -553,75 +476,46 @@ int body(const RadArgs* a, RadStream stream, bool grouped) { m.T = (int)y.shape[0]; m.N = N; m.K = K; - const void *w1 = nullptr, *s1 = nullptr; - const int *sorted = nullptr, *offsets = nullptr; - if (grouped) { - m.experts = r4d_geti_or(a, "n_expert", 0); - m.topk = r4d_geti_or(a, "top_k", 0); - const char* order = r4d_gets(a, "a_order"); - m.sorted_a = order && !std::strcmp(order, "sorted"); - const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5]; - if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N || - r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 || - wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K || - so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr || - so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 || - off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 || - off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data || - !so.data || !st.data || !off.data) - return RAD_E_SHAPE; - m.wstep[0] = w.stride[0]; - m.wstep[1] = wo.stride[0]; - m.sstep[0] = ws.stride[0] * 4; - m.sstep[1] = so.stride[0] * 4; - if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE; - w1 = wo.data; - s1 = so.data; - sorted = (const int*)st.data; - offsets = (const int*)off.data; - } else { + if (!grouped) { if (x.shape[0] != m.T) return RAD_E_SHAPE; - m.wstep[0] = N * m.wr; - m.sstep[0] = (N / 128) * m.sr * 4; bool done = false; const int rc = dense_fast(stream, x, xs, w, ws, y, m, &done); if (done || rc < 0) return rc; + return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0, + (const uint8_t*)x.data, (const float*)xs.data, (const uint8_t*)w.data, + (const float*)ws.data, (uint16_t*)y.data, m); } - m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16; - if (grouped) { - /* The expert-major form at every routed-row count unless the environment bounds or - * refuses it (RADIANCE_FP8F32_DECODE_EXPERTS 0 or 1, ..._MAX_T). Measured at GLM's TP8 - * slices: a long K (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and - * under 128 routed rows four tiles a block on top; at down's K of 256 every variant - * reads within a few percent of the bandwidth, so it keeps 128 over four tiles. Stage - * and tiles can be pinned, for the microbenchmark. */ - auto env_long = [](const char* name, long dflt) { - const char* v = std::getenv(name); - return v && *v ? std::strtol(v, nullptr, 10) : dflt; - }; - const char* force = std::getenv("RADIANCE_FP8F32_DECODE_EXPERTS"); - const long max_t = env_long("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1); - if (force ? force[0] == '1' : max_t < 0 || m.T <= max_t) { - const long stage = env_long("RADIANCE_FP8F32_EXPERTS_STAGE_K", K <= 256 ? 128 : 256); - const long tiles = - env_long("RADIANCE_FP8F32_EXPERTS_COLTILES", K <= 256 || m.T < 128 ? 4 : 1); + m.experts = r4d_geti_or(a, "n_expert", 0); + m.topk = r4d_geti_or(a, "top_k", 0); + const char* order = r4d_gets(a, "a_order"); + m.sorted_a = order && !std::strcmp(order, "sorted"); + const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5]; + if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N || + r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 || + wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K || + so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr || + so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 || + off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 || + off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data || + !so.data || !st.data || !off.data) + return RAD_E_SHAPE; + m.wstep[0] = w.stride[0]; + m.wstep[1] = wo.stride[0]; + m.sstep[0] = ws.stride[0] * 4; + m.sstep[1] = so.stride[0] * 4; + if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE; + /* The expert-major form at every routed-row count. Measured at GLM's TP8 slices: a long K + * (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and under 128 routed rows + * four tiles a block on top; at down's K of 256 every variant reads within a few percent of + * the bandwidth, so it keeps 128 over four tiles. */ #define F8_EXPERTS(SK, C) \ R4D_EMIT(stream, (fp8_f32scale_experts), \ dim3((N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), 0, \ - (const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, \ - offsets, (uint16_t*)y.data, m) - if (stage == 256) return tiles == 4 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1); - return tiles == 4 ? F8_EXPERTS(128, 4) : F8_EXPERTS(128, 1); + (const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data, so.data, \ + (const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m) + if (K > 256) return m.T < 128 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1); + return F8_EXPERTS(128, 4); #undef F8_EXPERTS - } - } - if (grouped) - return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + m.tile - 1) / m.tile), - dim3(128), 0, (const uint8_t*)x.data, (const float*)xs.data, w.data, - ws.data, w1, s1, sorted, offsets, (uint16_t*)y.data, m); - return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0, - (const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, - offsets, (uint16_t*)y.data, m); } int dense(const RadArgs* a, RadStream stream) { return body(a, stream, false); } int grouped(const RadArgs* a, RadStream stream) { return body(a, stream, true); } diff --git a/libr4d/r4d_gen.hip b/libr4d/r4d_gen.hip index 73cbfd21..97a4cfde 100644 --- a/libr4d/r4d_gen.hip +++ b/libr4d/r4d_gen.hip @@ -116,6 +116,62 @@ __global__ __launch_bounds__(kT) void gate_add_kernel( } } +// ---------------------------------------------------------------------------- table_add +// y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once: one workgroup a (row, table row). +__global__ __launch_bounds__(kT) void table_add_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ t, uint16_t* __restrict__ y, + int n, int L, int x_ld, int y_ld) { + const int r = blockIdx.x / L, l = blockIdx.x % L; + for (int i = threadIdx.x * 8; i < n; i += kT * 8) { + float a[8], b[8]; + ld8(x + (size_t)r * x_ld + i, a); + ld8(t + (size_t)l * n + i, b); + #pragma unroll + for (int j = 0; j < 8; ++j) a[j] += b[j]; + st8(y + (size_t)r * y_ld + (size_t)l * n + i, a); + } +} + +// ---------------------------------------------------------------------------- mix_rows +// y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once: one workgroup a row. +__global__ __launch_bounds__(kT) void mix_rows_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, uint16_t* __restrict__ y, + int n, int k, int x_ld, int y_ld) { + const int r = blockIdx.x; + for (int i = threadIdx.x * 8; i < n; i += kT * 8) { + float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0}, v[8]; + for (int q = 0; q < k; ++q) { + const float wq = bf2f(w[q]); + ld8(x + (size_t)(r * k + q) * x_ld + i, v); + #pragma unroll + for (int j = 0; j < 8; ++j) acc[j] += wq * v[j]; + } + st8(y + (size_t)r * y_ld + i, acc); + } +} + +// ---------------------------------------------------------------------------- chan_stats +// The statistics are rounded on the host side of each thread (cheap: n reads), every step as +// libref rounds it. +__global__ __launch_bounds__(kT) void chan_stats_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ mean, + const uint16_t* __restrict__ sv, uint16_t* __restrict__ y, int n, int x_ld, int y_ld, + int var, float eps, int norm) { + const int r = blockIdx.x; + for (int i = threadIdx.x * 8; i < n; i += kT * 8) { + float a[8], mu[8], sd[8]; + ld8(x + (size_t)r * x_ld + i, a); + ld8(mean + i, mu); + ld8(sv + i, sd); + #pragma unroll + for (int j = 0; j < 8; ++j) { + const float s = var ? bfr(sqrtf(sd[j] + eps)) : sd[j]; + a[j] = norm ? bfr(bfr(a[j] - mu[j]) / s) : bfr(bfr(a[j] * s) + mu[j]); + } + st8(y + (size_t)r * y_ld + i, a); + } +} + // ---------------------------------------------------------------------------- ln_mod_quant_fp8 // gate_add, ln_mod and quant_act_fp8 in one pass over the row: the DiT block's norm in front of // every quantised linear, with the previous branch's gated residual folded in. Three passes over a @@ -207,7 +263,8 @@ __global__ __launch_bounds__(kT) void timestep_kernel( int round, int y_ld) { const int m = blockIdx.x; const float tv = t[m]; - const float tt = round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv; + const float tt = round == 3 ? bfr(scale * bfr(tv)) : round == 2 ? scale * bfr(tv) + : round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv; for (int i = threadIdx.x; i < h; i += kT) { const float f = expf(coef * (float)i / (float)h); const float arg = tt * f; @@ -339,6 +396,25 @@ __device__ __forceinline__ float ca_rd(const float*, float v) { return v; } __device__ __forceinline__ void ca_st(uint16_t* p, int64_t i, float v) { p[i] = f32_to_bf16(v); } __device__ __forceinline__ void ca_st(float* p, int64_t i, float v) { p[i] = v; } +// The element-wise form, any of x, the statistics (TW) and y in bf16 or f32: a latent kept in +// f32, or rows whose pitch the 8-wide kernel cannot take (an encoder's mean channels beside its +// log-variance). Each step rounds to y's dtype as the reference stores it; the explicit _rn +// intrinsics keep the compiler from contracting x s + mean into one fused multiply-add. +template +__global__ __launch_bounds__(kT) void chan_stats_any_kernel( + const TX* __restrict__ x, const TW* __restrict__ mean, const TW* __restrict__ sv, + TY* __restrict__ y, int n, int x_ld, int y_ld, int var, float eps, int norm) { + const int r = blockIdx.x; + for (int i = threadIdx.x; i < n; i += kT) { + const float mu = ca_rd(y, ca_ld(mean, (size_t)i)), v = ca_ld(sv, (size_t)i); + const float sd = ca_rd(y, var ? __fsqrt_rn(__fadd_rn(v, eps)) : v); + const float a = ca_ld(x, (size_t)r * x_ld + i); + ca_st(y, (int64_t)r * y_ld + i, + norm ? ca_rd(y, __fdiv_rn(ca_rd(y, __fsub_rn(a, mu)), sd)) + : ca_rd(y, __fadd_rn(ca_rd(y, __fmul_rn(a, sd)), mu))); + } +} + template __global__ __launch_bounds__(kT) void chan_affine_kernel( const T* __restrict__ x, T* __restrict__ y, int64_t total, int n, int x_ld, int inv, int rnd, @@ -467,7 +543,7 @@ template __global__ __launch_bounds__(256) void conv_igemm_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo, - int cout, int k, int stride, int up, int pt, int x_ld, int y_ld, int Mpx, int K) { + int cout, int k, int stride, int up, int pt, int pl, int x_ld, int y_ld, int Mpx, int K) { constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16; constexpr int CPR = CV_BK / 8; constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256; @@ -512,7 +588,7 @@ __global__ __launch_bounds__(256) void conv_igemm_kernel( auto loadA = [&](int i) -> r4d_u32x4 { if (!a_ok[i] || a_t[i] >= kk2) return zero; const int kh = a_t[i] / kq, kw = a_t[i] - kh * kq; - const int iy = a_oy[i] * stride + kh - pt, ix = a_ox[i] * stride + kw - pt; + const int iy = a_oy[i] * stride + kh - pt, ix = a_ox[i] * stride + kw - pl; if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) return zero; /* Both are non-negative here, so a halving is a shift. */ const int sy = UP == 1 ? iy : UP == 2 ? (iy >> 1) : iy / up; @@ -600,7 +676,7 @@ __global__ __launch_bounds__(256) void conv_igemm_kernel( __global__ __launch_bounds__(kT) void conv_direct_kernel( const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo, - int cout, int k, int stride, int up, int pt, int x_ld, int y_ld, int64_t total) { + int cout, int k, int stride, int up, int pt, int pl, int x_ld, int y_ld, int64_t total) { const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x; if (t >= total) return; const int co = (int)(t % cout); @@ -612,7 +688,7 @@ __global__ __launch_bounds__(kT) void conv_direct_kernel( const int iy = oy * stride + kh - pt; if (iy < 0 || iy >= Hv) continue; for (int kw = 0; kw < k; ++kw) { - const int ix = ox * stride + kw - pt; + const int ix = ox * stride + kw - pl; if (ix < 0 || ix >= Wv) continue; const uint16_t* xp = x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin; const uint16_t* wp = w + (size_t)co * K + (size_t)(kh * k + kw) * cin; @@ -637,9 +713,10 @@ inline bool rows8(const RadTensor* t, long long n, long long* rows, long long* l } // A dense [H, W * c] image operand. -inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W) { +inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W, + bool pitched = false) { if (!t || t->rank != 2 || c <= 0 || t->shape[1] % c || t->stride[1] != 1 || - t->stride[0] != t->shape[1]) + (pitched ? t->stride[0] < t->shape[1] : t->stride[0] != t->shape[1])) return false; *H = t->shape[0]; *W = t->shape[1] / c; @@ -752,6 +829,87 @@ extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) { return st_of(hipGetLastError()); } +extern "C" int r4d_rad_table_add(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *t = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !t || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(t) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), L = r4d_geti_or(a, "L", 0); + long long rx = 0, xl = 0, ry = 0, yl = 0; + if (L <= 0 || !rows8(x, n, &rx, &xl) || !rows8(y, n * L, &ry, &yl) || !r4d_contig(t) || + ((uintptr_t)t->data & 15)) + return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx < ry || r4d_numel(t) < L * n) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(table_add_kernel, dim3((unsigned)(ry * L)), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (const uint16_t*)t->data, (uint16_t*)y->data, + (int)n, (int)L, (int)xl, (int)yl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_mix_rows(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !w || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(w) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0); + long long rx = 0, xl = 0, ry = 0, yl = 0; + if (k <= 0 || !rows8(x, n, &rx, &xl) || !rows8(y, n, &ry, &yl) || !r4d_contig(w)) + return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx < ry * k || r4d_numel(w) < k) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(mix_rows_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (const uint16_t*)w->data, (uint16_t*)y->data, + (int)n, (int)k, (int)xl, (int)yl); + return st_of(hipGetLastError()); +} + +template +static int chan_stats_any(const RadTensor* x, const RadTensor* mn, const RadTensor* sv, + const RadTensor* y, long long rows, long long n, long long xl, + long long yl, int var, float eps, int norm, RadStream s) { + hipLaunchKernelGGL((chan_stats_any_kernel), dim3((unsigned)rows), dim3(kT), 0, + (hipStream_t)s, (const TX*)x->data, (const TW*)mn->data, + (const TW*)sv->data, (TY*)y->data, (int)n, (int)xl, (int)yl, var, eps, + norm); + return st_of(hipGetLastError()); +} + +/* Both rows: bf16 (chan_stats_bf16, eight channels a thread when every row and statistic is + * 16-byte aligned, element-wise otherwise) and f32 (chan_stats_f32: x and y f32 over bf16 or f32 + * statistics, a latent kept in f32 before a bf16 network reads it). */ +extern "C" int r4d_rad_chan_stats(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *mn = r4d_opt(a, 1), *sv = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !mn || !sv || !y) return R4D_NO(RAD_E_INVAL); + const long long n = r4d_geti_or(a, "n", 0); + const char* mode = r4d_gets(a, "mode"); + const int norm = mode && !std::strcmp(mode, "norm"); + if (!mode || (!norm && std::strcmp(mode, "denorm"))) return R4D_NO(RAD_E_INVAL); + auto bf_f32 = [](const RadTensor* t) { return is_bf16(t) || t->dtype == RAD_F32; }; + if (!bf_f32(x) || !bf_f32(y) || !bf_f32(mn) || mn->dtype != sv->dtype || x->dtype != y->dtype) + return R4D_NO(RAD_E_DTYPE); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + const int var = (int)r4d_geti_or(a, "var", 0); + const float eps = (float)r4d_getf(a, "eps", 0.0); + long long rx = 0, xl = 0, ry = 0, yl = 0; + if (is_bf16(x) && is_bf16(mn) && rows8(x, n, &rx, &xl) && rows8(y, n, &ry, &yl) && + r4d_contig(mn) && r4d_contig(sv) && !((uintptr_t)mn->data & 15) && + !((uintptr_t)sv->data & 15)) { + if (ry <= 0 || rx < ry || r4d_numel(mn) < n || r4d_numel(sv) < n) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(chan_stats_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)x->data, (const uint16_t*)mn->data, + (const uint16_t*)sv->data, (uint16_t*)y->data, (int)n, (int)xl, (int)yl, + var, eps, norm); + return st_of(hipGetLastError()); + } + xl = r4d_rows_pitch(x, n, &rx); + yl = r4d_rows_pitch(y, n, &ry); + if (xl < 0 || yl < 0 || !r4d_contig(mn) || !r4d_contig(sv)) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx < ry || r4d_numel(mn) < n || r4d_numel(sv) < n) return R4D_NO(RAD_E_SHAPE); + const bool f = x->dtype == RAD_F32, wf = mn->dtype == RAD_F32; +#define R4D_CS(TX, TW) chan_stats_any(x, mn, sv, y, ry, n, xl, yl, var, eps, norm, s) + if (f) return wf ? R4D_CS(float, float) : R4D_CS(float, uint16_t); + return wf ? R4D_CS(uint16_t, float) : R4D_CS(uint16_t, uint16_t); +#undef R4D_CS +} + /* Both rows: a bf16 embedding (timestep_embed_bf16) or an f32 one (timestep_embed_f32, a timestep * MLP kept in f32). */ extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) { @@ -957,13 +1115,19 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) { const long long up = r4d_geti_or(a, "up", 1); const char* pad = r4d_gets(a, "pad"); const bool down = pad && !std::strcmp(pad, "down"); - if (pad && !down && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL); + const bool causal = pad && !std::strcmp(pad, "causal"); + if (pad && !down && !causal && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL); if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return R4D_NO(RAD_E_SHAPE); long long Hin = 0, Win = 0, Ho = 0, Wo = 0; - if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo)) return R4D_NO(RAD_E_SHAPE); + /* y may be a column slice of wider rows (a channel written into its own columns): both kernels + * store at its row pitch. */ + if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo, true)) + return R4D_NO(RAD_E_SHAPE); const long long Hv = Hin * up, Wv = Win * up; - const long long pt = down ? 0 : k / 2, pb = down ? 1 : k / 2; - if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo) + /* Rows padded above `pt` and below `pb`, columns `pl` left and `pr` right. */ + const long long pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2; + const long long pl = down ? 0 : k / 2, pr = down ? 1 : k / 2; + if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo) return R4D_NO(RAD_E_SHAPE); const long long K = k * k * cin; if (r4d_numel(w) < cout * K || r4d_numel(b) < cout) return R4D_NO(RAD_E_SHAPE); @@ -977,7 +1141,7 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) { (const uint16_t*)x->data, (const uint16_t*)w->data, (const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, (int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, - (int)x->stride[0], (int)y->stride[0], (int64_t)total); + (int)pl, (int)x->stride[0], (int)y->stride[0], (int64_t)total); return st_of(hipGetLastError()); } // 128 pixels a block, and the widest channel tile (192, 128, then 64) that leaves under a third @@ -995,7 +1159,7 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) { (unsigned)((cout + 4 * TC * 16 - 1) / (4 * TC * 16))), \ dim3(256), 0, st, (const uint16_t*)x->data, (const uint16_t*)w->data, \ (const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \ - (int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, \ + (int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, (int)pl, \ (int)x->stride[0], (int)y->stride[0], (int)Mpx, (int)K) /* The decoder's two kernel sizes at its two sampling rates, and the generic form for the rest. */ #define R4D_CONV_K(TP, TC) \ diff --git a/libr4d/r4d_glm.hip b/libr4d/r4d_glm.hip index b8324b27..6cd8560c 100644 --- a/libr4d/r4d_glm.hip +++ b/libr4d/r4d_glm.hip @@ -5,9 +5,6 @@ #include "r4d_moe_sort.h" #include #include -#include -#include -#include namespace { __global__ void gemm_nt_f32_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, @@ -71,31 +68,6 @@ __global__ void __launch_bounds__(128) if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c]; } -// The tile forms, by rows x columns per wave. RADIANCE_F32_GEMM_TILE names one ("8x4") or -// "legacy"; unset or unknown picks by M. All forms are byte-identical, so the choice is speed only. -struct F32Tile { - int r, c; -}; -constexpr F32Tile kF32Tiles[] = { { 1, 1 }, { 2, 1 }, { 4, 1 }, { 8, 1 }, { 4, 2 }, - { 8, 2 }, { 4, 4 }, { 8, 4 }, { 16, 2 }, { 16, 4 } }; -F32Tile f32_tile(long rows, long n) { - if (const char* e = std::getenv("RADIANCE_F32_GEMM_TILE")) { - if (!std::strcmp(e, "legacy")) return { 0, 0 }; - int r = 0, c = 0; - if (std::sscanf(e, "%dx%d", &r, &c) == 2) - for (const F32Tile& t : kF32Tiles) - if (t.r == r && t.c == c) return t; - } - // Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096. 16x4 gains - // 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every width. A - // projection of a few columns has too few waves for wide tiles at any M. - if (n <= 8) return { 4, 1 }; - if (rows <= 1) return { 0, 0 }; - if (rows <= 2) return { 2, 1 }; - if (rows < 16) return { 4, 1 }; - if (rows < 64) return { 4, 4 }; - return { 8, 4 }; -} template int gemm_f32_tile(RadStream stream, const RadTensor& x, const RadTensor& w, const RadTensor& y, long n, long k) { @@ -117,52 +89,28 @@ int gemm_f32_body(const RadArgs* a, RadStream stream) { w.stride[1] != 1 || y.stride[1] != 1 || x.stride[0] < k || w.stride[0] < k || y.stride[0] < n) return RAD_E_SHAPE; - const F32Tile t = f32_tile(x.shape[0], n); -#define R4D_F32_TILE(R, C) \ - if (t.r == R && t.c == C) return gemm_f32_tile(stream, x, w, y, n, k); - R4D_F32_TILE(1, 1) - R4D_F32_TILE(2, 1) R4D_F32_TILE(4, 1) R4D_F32_TILE(8, 1) R4D_F32_TILE(4, 2) R4D_F32_TILE(8, 2) - R4D_F32_TILE(4, 4) R4D_F32_TILE(8, 4) R4D_F32_TILE(16, 2) R4D_F32_TILE(16, 4) -#undef R4D_F32_TILE - return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0, - (const uint16_t*)x.data, (const float*)w.data, (float*)y.data, - x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k); + /* The tile form, rows x columns per wave, by M; all forms are byte-identical, so the choice is + * speed only. Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096. + * 16x4 gains 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every + * width. A projection of a few columns has too few waves for wide tiles at any M. */ + const long rows = x.shape[0]; + if (n <= 8) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k); + if (rows <= 1) + return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0, + (const uint16_t*)x.data, (const float*)w.data, (float*)y.data, + x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k); + if (rows <= 2) return gemm_f32_tile<2, 1>(stream, x, w, y, n, k); + if (rows < 16) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k); + if (rows < 64) return gemm_f32_tile<4, 4>(stream, x, w, y, n, k); + return gemm_f32_tile<8, 4>(stream, x, w, y, n, k); } -__global__ void router_sigmoid_kernel(const float* logits, const float* bias, int* ids, - float* weights, long lp, long bp, long ip, long wp, int ne, - int k, int norm, float factor) { - __shared__ float probabilities[512], ranking[512]; - const int r = blockIdx.x; - for (int e = threadIdx.x; e < ne; e += 256) { - const float p = 1.0f / (1.0f + expf(-logits[(long)r * lp + e])); - probabilities[e] = p; - ranking[e] = p + bias[(long)e * bp]; - } - __syncthreads(); - if (threadIdx.x) return; - int index[32]; - float chosen[32], total = 0; - for (int j = 0; j < k; ++j) { - int best = 0; - for (int e = 1; e < ne; ++e) - if (ranking[e] > ranking[best]) best = e; - index[j] = best; - chosen[j] = probabilities[best]; - total += chosen[j]; - ranking[best] = -INFINITY; - } - const float mult = norm ? factor / (total + 1e-20f) : factor; - for (int j = 0; j < k; ++j) { - ids[(long)r * ip + j] = index[j]; - weights[(long)r * wp + j] = chosen[j] * mult; - } -} -// The scan above in one wave per row. Lane l holds experts l, l+32, ... as 64-bit keys: the -// rank's order-preserving bits (-0 folded to +0) over ~e, so equal ranks order as the scan's strict -// `>` does, to the lower expert. Round j takes the largest key below round j-1's winner and parks -// it on lane j (top_k <= 32). Probabilities, `total` in round order, `mult` and the weights are -// the scan's expressions, so a finite row gives the same bytes. A NaN rank is never selected here, -// while the scan takes expert 0 first when its rank is NaN. +// router_sigmoid_topk in one wave per row: p = sigmoid(logit), the top_k largest ranks p + bias +// in descending order, equal ranks to the lower expert, as a serial scan with a strict `>` takes +// them. Lane l holds experts l, l+32, ... as 64-bit keys: the rank's order-preserving bits (-0 +// folded to +0) over ~e, so equal ranks order to the lower expert. Round j takes the largest key +// below round j-1's winner and parks it on lane j (top_k <= 32). `total` sums the selected p in +// round order, mult = norm ? factor / (total + 1e-20) : factor, and a weight is p * mult. A NaN +// rank is never selected. // OWN is a template bound because the keys are registers; a lane-derived trip count would index // them divergently, which gfx12 lowers to a v_movrels loop. __device__ __forceinline__ unsigned long long router_rank_key(float rank, int e) { @@ -283,12 +231,6 @@ int router_body(const RadArgs* a, RadStream stream) { bias.stride[0] < 1) return RAD_E_SHAPE; const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0); - const char* select = std::getenv("RADIANCE_ROUTER_SELECT"); - if (select && !std::strcmp(select, "old")) - return R4D_EMIT(stream, router_sigmoid_kernel, dim3(lg.shape[0]), dim3(256), 0, - (const float*)lg.data, (const float*)bias.data, (int*)ids.data, - (float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], - (int)ne, (int)k, norm, factor); const dim3 grid((unsigned)((lg.shape[0] + 3) / 4)); if (ne <= 9 * 32) return R4D_EMIT(stream, router_sigmoid_wave_kernel<9>, grid, dim3(128), 0, diff --git a/libr4d/r4d_kda.hip b/libr4d/r4d_kda.hip index fdbcd799..baba52f2 100644 --- a/libr4d/r4d_kda.hip +++ b/libr4d/r4d_kda.hip @@ -1,6 +1,5 @@ /* Exact recurrent baseline for GLM KDA, including speculative candidate snapshots. - * One wave owns one, two or four value rows and keeps each row's 128-wide state in four - * registers per lane. + * One wave owns four value rows and keeps each row's 128-wide state in four registers per lane. * Prefill uses the same recurrence and commits only its final state. */ #include #include "r4d_args.h" @@ -26,29 +25,16 @@ struct KdaJob : KdaMeta { const int *idx, *cu, *accepted, *init; }; -__device__ float sum(float v) { - for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32); - return __shfl(v, 0, 32); -} -/* r4d_wave_sum adds the same partners in the same order as sum() does for lane 0, and every - * other lane forms the same additions with the operands swapped, so all lanes hold lane 0's bits - * without the broadcast. */ -template -__device__ __forceinline__ float wave_total(float v) { - if constexpr (Dpp) - return r4d_wave_sum(v); - else - return sum(v); -} __device__ long factor_offset(long base, int logical, long pitch) { return base + (logical / 128) * pitch + (logical % 128); } /* Separate dispatch: all old factor reads finish before the next window overwrites them. */ -template __global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, const int* accepted, const int* init, KdaMeta m) { const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, seq = blockIdx.z; + /* A sequence without tokens this step leaves its slots as they are. */ + if (cu[(long)seq * m.cs0] == cu[(long)(seq + 1) * m.cs0]) return; const int anchor = idx[(long)seq * m.is0], scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1]; if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch) @@ -80,123 +66,17 @@ __global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, c } const float delta = state[factor_offset(fb, f + 384, m.ss2)] * - (state[factor_offset(fb, f + 128 + e, m.ss2)] - wave_total(prediction)); + (state[factor_offset(fb, f + 128 + e, m.ss2)] - r4d_wave_sum(prediction)); #pragma unroll for (int d = 0; d < 4; ++d) s[d] += delta * k[d]; } #pragma unroll for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d]; } -__global__ void kda_update_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v, - const uint16_t* g, const uint16_t* beta, const float* alog, - const float* bias, float* state_ptr, uint16_t* out, - const int* idx, const int* cu, const int* accepted_ptr, - const int* init, KdaMeta meta) { - KdaJob j{}; - static_cast(j) = meta; - j.input[0] = q; - j.input[1] = k; - j.input[2] = v; - j.input[3] = g; - j.input[4] = beta; - j.alog = alog; - j.bias = bias; - j.state = state_ptr; - j.out = out; - j.idx = idx; - j.cu = cu; - j.accepted = accepted_ptr; - j.init = init; - const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5); - const int head = blockIdx.y, seq = blockIdx.z; - const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0]; - const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1; - if (begin < 0 || end < begin || end > j.tokens || accepted < 1 || - accepted > (j.anchor ? 32 : j.width) || - (j.verify && end - begin > (j.anchor ? 32 : j.width))) - return; - const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1]; - if (read >= j.slots) return; - if (read < 0) { - if (!lane) - for (int t = begin; t < end; ++t) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = 0; - return; - } - const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0; - const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0; - if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return; - const long fb = (long)scratch * j.ss0 + (long)head * j.ss1; - const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2; - float state[4]; -#pragma unroll - for (int d = 0; d < 4; ++d) state[d] = initialized ? j.state[initial + lane + 32 * d] : 0; - const float gain = expf(j.alog[head]); - for (int t = begin; t < end; ++t) { - float q[4], k[4], decay[4], sq = 0, sk = 0; -#pragma unroll - for (int d = 0; d < 4; ++d) { - const int channel = lane + d * 32; - q[d] = bf16_to_f32(j.input[0][(long)t * j.row[0] + (long)head * j.head[0] + channel]); - k[d] = bf16_to_f32(j.input[1][(long)t * j.row[1] + (long)head * j.head[1] + channel]); - sq += q[d] * q[d]; - sk += k[d] * k[d]; - const float raw = - bf16_to_f32(j.input[3][(long)t * j.row[3] + (long)head * j.head[3] + channel]); - decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + j.bias[head * 128 + channel])))); - } - const float qi = j.scale * rsqrtf(sum(sq) + j.eps), ki = rsqrtf(sum(sk) + j.eps); - const float beta = - 1.0f / - (1.0f + expf(-bf16_to_f32(j.input[4][(long)t * j.row[4] + (long)head * j.head[4]]))); - float predicted = 0; -#pragma unroll - for (int d = 0; d < 4; ++d) { - q[d] *= qi; - k[d] *= ki; - state[d] *= decay[d]; - predicted += state[d] * k[d]; - } - predicted = sum(predicted); - const float value = - bf16_to_f32(j.input[2][(long)t * j.row[2] + (long)head * j.head[2] + e]); - if (j.anchor && j.verify) { - const int f = 1 + (t - begin) * 385; - if (e == 0) { -#pragma unroll - for (int d = 0; d < 4; ++d) { - const int c = lane + 32 * d; - j.state[factor_offset(fb, f + c, j.ss2)] = k[d]; - j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d]; - } - if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = beta; - } - if (!lane) j.state[factor_offset(fb, f + 128 + e, j.ss2)] = value; - } - const float delta = beta * (value - predicted); - float result = 0; -#pragma unroll - for (int d = 0; d < 4; ++d) { - state[d] += delta * k[d]; - result += state[d] * q[d]; - } - result = sum(result); - if (!lane) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = f32_to_bf16(result); - if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) { - const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1]; - if (write >= 0 && write < j.slots) { - const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2; -#pragma unroll - for (int d = 0; d < 4; ++d) j.state[target + lane + 32 * d] = state[d]; - } - } - } - if (j.anchor && e == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f; -} -/* kda_update_kernel with R value rows a wave: the loads, norms and decay exponentials, which do - * not depend on the state, are formed once for R rows, and the rows' reductions interleave. Each - * row's arithmetic is kda_update_kernel's in its order, so the bytes match (selftest --perfkda). - * With Prefetch the next token's operands are loaded while this one is reduced. */ -template +/* R value rows a wave: the loads, norms and decay exponentials, which do not depend on the state, + * are formed once for R rows, and the rows' reductions interleave. The next token's operands are + * loaded while this one is reduced. */ +template __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v, const uint16_t* g, const uint16_t* beta, const float* alog, const float* bias, float* state_ptr, uint16_t* out, const int* idx, @@ -222,7 +102,7 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint const int head = blockIdx.y, seq = blockIdx.z; const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0]; const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1; - if (begin < 0 || end < begin || end > j.tokens || accepted < 1 || + if (begin < 0 || end <= begin || end > j.tokens || accepted < 1 || accepted > (j.anchor ? 32 : j.width) || (j.verify && end - begin > (j.anchor ? 32 : j.width))) return; @@ -269,14 +149,11 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r); }; Token cur; - if (Prefetch && begin < end) fetch(begin, cur); + if (begin < end) fetch(begin, cur); for (int t = begin; t < end; ++t) { - [[maybe_unused]] Token next; + Token next; /* The last token loads itself again rather than a row past `end`. */ - if constexpr (Prefetch) - fetch(t + 1 < end ? t + 1 : t, next); - else - fetch(t, cur); + fetch(t + 1 < end ? t + 1 : t, next); float qv[4], kv[4], decay[4], sq = 0, sk = 0; #pragma unroll for (int d = 0; d < 4; ++d) { @@ -355,7 +232,7 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d]; } } - if constexpr (Prefetch) cur = next; + cur = next; } if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f; } @@ -448,44 +325,18 @@ int body(const RadArgs* a, RadStream stream) { j.init = (const int*)init->data; j.hs0 = init->stride[0]; } - /* RADIANCE_KDA_FORM=old is the one-row kernel on shuffle sums, the reference the selftest - * holds every form to byte for byte; RADIANCE_KDA_ROWS (1, 2 or 4 value rows a wave) and - * RADIANCE_KDA_PREFETCH=0 pin the other form's variants for the microbenchmark. */ - const char* kform = std::getenv("RADIANCE_KDA_FORM"); - const bool old = kform && !std::strcmp(kform, "old"); const unsigned seqs = (unsigned)(cu.shape[0] - 1); if (j.anchor && j.verify) { const int rc = - old ? R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), - 0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast(j)) - : R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), - 0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast(j)); + R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0, j.state, + j.idx, j.cu, j.accepted, j.init, static_cast(j)); if (rc != RAD_OK) return rc; } - if (old) - return R4D_EMIT(stream, kda_update_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0, - j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], j.alog, j.bias, - j.state, j.out, j.idx, j.cu, j.accepted, j.init, static_cast(j)); - const char* rows_env = std::getenv("RADIANCE_KDA_ROWS"); - const long rows = rows_env && *rows_env ? std::strtol(rows_env, nullptr, 10) : 4; - const char* prefetch_env = std::getenv("RADIANCE_KDA_PREFETCH"); - const bool prefetch = !prefetch_env || prefetch_env[0] != '0'; -#define KDA_ROWS(RR, PF) \ - return R4D_EMIT(stream, (kda_rows_kernel), dim3(32 / RR, (unsigned)H, seqs), \ - dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], \ - j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init, \ - static_cast(j)) - if (rows == 1) { - if (prefetch) KDA_ROWS(1, true); - KDA_ROWS(1, false); - } - if (rows == 2) { - if (prefetch) KDA_ROWS(2, true); - KDA_ROWS(2, false); - } - if (prefetch) KDA_ROWS(4, true); - KDA_ROWS(4, false); -#undef KDA_ROWS + constexpr int kRows = 4; + return R4D_EMIT(stream, (kda_rows_kernel), dim3(32 / kRows, (unsigned)H, seqs), + dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], + j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init, + static_cast(j)); } } extern "C" int r4d_rad_kda_update(const RadArgs* a, RadStream stream) { return body(a, stream); } diff --git a/libr4d/r4d_ltx.hip b/libr4d/r4d_ltx.hip new file mode 100644 index 00000000..9633beab --- /dev/null +++ b/libr4d/r4d_ltx.hip @@ -0,0 +1,1091 @@ +// R4D -- LTX-2's ops (docs/OPS.md, "LTX-2"): its rotary over fractional coordinates, the per-head +// attention gate and the guided sampler step. +// +// Each kernel rounds where its libref function does (libref/ref_ltx.cpp). The rotary's angles take +// the device's sincosf, within two units in the last place of libref's correctly rounded cos and +// sin; the guided step's deviations are f64 block sums in a fixed order, so it is deterministic. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_gdn_wmma.h" + +#include +#include +#include +#include + +namespace { + +constexpr int kT = 256; + +__device__ __forceinline__ float bfr(float v) { return bf2f(f32_to_bf16(v)); } + +// A value stored to an operand of dtype `bf`: bf16 when set, else f32. +__device__ __forceinline__ float ldx(const void* p, size_t i, bool bf) { + return bf ? bf2f(((const uint16_t*)p)[i]) : ((const float*)p)[i]; +} +__device__ __forceinline__ void stx(void* p, size_t i, float v, bool bf) { + if (bf) ((uint16_t*)p)[i] = f32_to_bf16(v); + else ((float*)p)[i] = v; +} + +// ---------------------------------------------------------------------------- rope_split +// One workgroup a (head, run of kRopeRows rows): the head's half-width pairs across the threads, +// their frequency and axis worked out once into LDS (f64 pow, as libref), then the rows. +constexpr int kRopeRows = 64; +constexpr int kMaxDims = 4; + +__global__ __launch_bounds__(kT) void rope_split_kernel( + void* __restrict__ x, const void* __restrict__ pos, int rows, int nh, int hd, int head0, + int nd, int steps, int pad, double theta, float m0, float m1, float m2, float m3, long long x_ld, + long long p_ld, long long p_cs, bool xbf, bool pint) { + __shared__ float freq[256]; + __shared__ int axis[256]; + const int half = hd / 2, h = blockIdx.y, r0 = blockIdx.x * kRopeRows; + if ((int)threadIdx.x < half) { + const int p = (head0 + h) * half + (int)threadIdx.x; + if (p < pad) { + axis[threadIdx.x] = -1; + freq[threadIdx.x] = 0.0f; + } else { + const int j = p - pad, k = j / nd; + axis[threadIdx.x] = j % nd; + double l = 0.0; + if (steps > 1) { + const double st = 1.0 / (double)(steps - 1); + l = k < steps / 2 ? st * (double)k : 1.0 - st * (double)(steps - 1 - k); + } + freq[threadIdx.x] = (float)(pow(theta, l) * M_PI / 2.0); + } + } + __syncthreads(); + const float mx[kMaxDims] = { m0, m1, m2, m3 }; + const int per = kT / half; // rows a pass of the workgroup covers + const int i = (int)threadIdx.x % half, rr = (int)threadIdx.x / half; + if (rr >= per) return; + const int d = axis[i]; + if (d < 0) return; // cos 1, sin 0: the value as it is + const float f = freq[i]; + for (int r = r0 + rr; r < min(r0 + kRopeRows, rows); r += per) { + const long long pi = (long long)d * p_cs + (long long)r * p_ld; + const float c0 = pint ? (float)((const int*)pos)[pi] : ((const float*)pos)[pi]; + const float g = c0 / mx[d]; + const float ang = (2.0f * g - 1.0f) * f; + float s, c; + sincosf(ang, &s, &c); + const size_t o1 = (size_t)r * x_ld + (size_t)h * hd + i, o2 = o1 + half; + const float x1 = ldx(x, o1, xbf), x2 = ldx(x, o2, xbf); + const float a1 = x1 * c, b1 = x2 * s, a2 = x2 * c, b2 = x1 * s; + stx(x, o1, a1 - b1, xbf); + stx(x, o2, a2 + b2, xbf); + } +} + +// ---------------------------------------------------------------------------- head_gate +// x = rd(x rd(2 rd(sigmoid(g)))): a thread an element. +__global__ __launch_bounds__(kT) void head_gate_kernel( + void* __restrict__ x, const uint16_t* __restrict__ g, long long total, int width, int hd, + long long x_ld, long long g_ld, bool xbf) { + const long long e = (long long)blockIdx.x * kT + threadIdx.x; + if (e >= total) return; + const long long r = e / width; + const int col = (int)(e % width), h = col / hd; + const float sg = bfr(1.0f / (1.0f + expf(-bf2f(g[r * g_ld + h])))); + const float gate = xbf ? bfr(2.0f * sg) : 2.0f * sg; + const size_t o = (size_t)r * x_ld + col; + stx(x, o, ldx(x, o, xbf) * gate, xbf); +} + +// ---------------------------------------------------------------------------- ltx_guide +// Two launches. The first, when the rescale is on (read off `scales` on the device), sums x0_c, +// x0_c^2, g and g^2 in f64 a workgroup a part into `stats`; the second reduces the parts (each +// workgroup the same sums in the same order), then recomputes g from the passes, rescales it, and +// takes the Euler step in place. +constexpr int kGuideParts = 1024; + +struct GuideIn { + const void* vc; const void* vu; const void* vs; const void* vm; + long long lc, lu, ls, lm; // row pitches + bool bc, bu, bs, bm; // bf16 +}; + +__device__ __forceinline__ float guide_g(const GuideIn& v, long long r, int c, float x, float sig, + float cu, float stg, float cm, bool uu, bool us, bool um, + float* x0c) { + const float xc = x - ldx(v.vc, (size_t)(r * v.lc + c), v.bc) * sig; + float g = xc; + if (uu) g = g + cu * (xc - (x - ldx(v.vu, (size_t)(r * v.lu + c), v.bu) * sig)); + if (us) g = g + stg * (xc - (x - ldx(v.vs, (size_t)(r * v.ls + c), v.bs) * sig)); + if (um) g = g + cm * (xc - (x - ldx(v.vm, (size_t)(r * v.lm + c), v.bm) * sig)); + *x0c = xc; + return g; +} + +__global__ __launch_bounds__(kT) void ltx_guide_sum_kernel( + GuideIn v, const float* __restrict__ x, const float* __restrict__ sc, + const float* __restrict__ sh, double* __restrict__ parts, long long rows, int n, long long x_ld) { + __shared__ double red[4][kT]; + const float gs = sc[0], stg = sc[1], ms = sc[2], rr = sc[3], sig = sh[0]; + const bool uu = v.vu && gs != 1.0f, us = v.vs && stg != 0.0f, um = v.vm && ms != 1.0f; + double a[4] = { 0, 0, 0, 0 }; + if (rr > 0.0f) { + const long long total = rows * n; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < total; + e += (long long)gridDim.x * kT) { + const long long r = e / n; + const int c = (int)(e % n); + float xc; + const float g = guide_g(v, r, c, x[r * x_ld + c], sig, gs - 1.0f, stg, ms - 1.0f, uu, us, + um, &xc); + a[0] += xc; + a[1] += (double)xc * xc; + a[2] += g; + a[3] += (double)g * g; + } + } + for (int k = 0; k < 4; ++k) red[k][threadIdx.x] = a[k]; + __syncthreads(); + for (int s = kT / 2; s > 0; s >>= 1) { + if ((int)threadIdx.x < s) + for (int k = 0; k < 4; ++k) red[k][threadIdx.x] += red[k][threadIdx.x + s]; + __syncthreads(); + } + if (threadIdx.x < 4) parts[(size_t)blockIdx.x * 4 + threadIdx.x] = red[threadIdx.x][0]; +} + +__global__ __launch_bounds__(kT) void ltx_guide_step_kernel( + GuideIn v, float* __restrict__ x, const float* __restrict__ sc, const float* __restrict__ sh, + const double* __restrict__ parts, int n_parts, long long rows, int n, long long x_ld) { + __shared__ double red[4][kT]; + __shared__ float fac_s; + const float gs = sc[0], stg = sc[1], ms = sc[2], rr = sc[3], sig = sh[0], sn = sh[1]; + const bool uu = v.vu && gs != 1.0f, us = v.vs && stg != 0.0f, um = v.vm && ms != 1.0f; + float fac = 1.0f; + if (rr > 0.0f) { + double a[4] = { 0, 0, 0, 0 }; + for (int p = threadIdx.x; p < n_parts; p += kT) + for (int k = 0; k < 4; ++k) a[k] += parts[(size_t)p * 4 + k]; + for (int k = 0; k < 4; ++k) red[k][threadIdx.x] = a[k]; + __syncthreads(); + for (int s = kT / 2; s > 0; s >>= 1) { + if ((int)threadIdx.x < s) + for (int k = 0; k < 4; ++k) red[k][threadIdx.x] += red[k][threadIdx.x + s]; + __syncthreads(); + } + if (threadIdx.x == 0) { + const double N = (double)(rows * n), dof = N > 1.0 ? N - 1.0 : 1.0; + const double vc = (red[1][0] - red[0][0] * red[0][0] / N) / dof; + const double vg = (red[3][0] - red[2][0] * red[2][0] / N) / dof; + fac_s = (float)sqrt(vc > 0.0 ? vc : 0.0) / (float)sqrt(vg > 0.0 ? vg : 0.0); + } + __syncthreads(); + fac = fac_s; + } + const float kept = (float)(1.0 - (double)rr), dt = sn - sig; + const long long total = rows * n; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < total; + e += (long long)gridDim.x * kT) { + const long long r = e / n; + const int c = (int)(e % n); + float* xp = x + r * x_ld + c; + const float xv = *xp; + float xc; + float g = guide_g(v, r, c, xv, sig, gs - 1.0f, stg, ms - 1.0f, uu, us, um, &xc); + if (rr > 0.0f) g = rr * (g * fac) + kept * g; + const float vel = (xv - g) / sig; + *xp = xv + dt * vel; + } +} + +// ---------------------------------------------------------------------------- pixel_norm +// A wave a row, eight rows a workgroup: the lanes' strided sums of rd(x^2) reduced by the wave +// (a different f32 order from libref's ascending one), then the row scaled. `ileave` L sends +// row t L + l to columns c L + l of y's row t. +__device__ __forceinline__ float rdx(float v, bool bf) { return bf ? bfr(v) : v; } + +__global__ __launch_bounds__(kT) void pixel_norm_kernel( + const void* __restrict__ x, void* __restrict__ y, long long rows, int n, int L, float eps, + float mult, long long x_ld, long long y_ld, bool xbf, bool ybf, bool divf, bool silu) { + const long long r = (long long)blockIdx.x * (kT / 32) + (threadIdx.x >> 5); + if (r >= rows) return; + const int lane = threadIdx.x & 31; + const size_t xb = (size_t)r * x_ld; + float ss = 0.0f; + for (int i = lane; i < n; i += 32) { + const float v = ldx(x, xb + i, xbf); + ss += rdx(v * v, ybf); + } + for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor(ss, o, 32); + const float v = rdx(rdx(ss / (float)n, ybf) + eps, ybf); + const float s = divf ? rdx(sqrtf(v), ybf) : rdx(1.0f / sqrtf(v), ybf); + const size_t yb = (size_t)(r / L) * y_ld + (size_t)(r % L); + for (int i = lane; i < n; i += 32) { + const float xv = ldx(x, xb + i, xbf); + float z = rdx(divf ? xv / s : xv * s, ybf); + if (silu) z = rdx(z / (1.0f + expf(-z)), ybf); + if (mult != 1.0f) z = rdx(z * mult, ybf); + stx(y, yb + (size_t)i * L, z, ybf); + } +} + +// ---------------------------------------------------------------------------- d2s3d / s2d3d +// Copies over voxel rows, a thread an output value; the volume is read off `geom` on the device, +// and rows past it (or past the `rows` the output holds) are left alone. +__global__ __launch_bounds__(kT) void d2s3d_kernel( + const void* __restrict__ x, void* __restrict__ y, const int* __restrict__ geom, long long rows, + int C, int st, int sh, int sw, int drop, long long x_ld, long long y_ld, bool xbf, bool ybf) { + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0) return; + const long long Ho = (long long)H * sh, Wo = (long long)W * sw; + const long long To = (long long)T * st - drop; + const long long n = min(rows, To * Ho * Wo) * C; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long r = e / C; + const int c = (int)(e % C); + const long long tt = r / (Ho * Wo) + drop, ii = (r / Wo) % Ho, jj = r % Wo; + const long long t = tt / st, i = ii / sh, j = jj / sw; + const int aa = (int)(tt % st), b = (int)(ii % sh), d = (int)(jj % sw); + const long long xr = (t * H + i) * W + j; + stx(y, (size_t)(r * y_ld + c), + ldx(x, (size_t)(xr * x_ld + ((c * st + aa) * sh + b) * sw + d), xbf), ybf); + } +} + +__global__ __launch_bounds__(kT) void s2d3d_kernel( + const void* __restrict__ x, void* __restrict__ y, const int* __restrict__ geom, long long rows, + int C, int st, int sh, int sw, int tpre, int grp, int Co, long long x_ld, long long y_ld, + bool xbf, bool ybf, bool mean, bool add) { + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0 || (T + tpre) % st || H % sh || W % sw) return; + const long long Ho = H / sh, Wo = W / sw, To = (T + tpre) / st; + const long long n = min(rows, To * Ho * Wo) * Co; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long r = e / Co; + const int o = (int)(e % Co); + const long long t = r / (Ho * Wo), i = (r / Wo) % Ho, j = r % Wo; + auto val = [&](int q) { + const int d = q % sw, b = (q / sw) % sh, aa = (q / (sw * sh)) % st; + const int c = q / (sw * sh * st); + const long long v = t * st + aa, tr = v < tpre ? v : v - tpre; + return ldx(x, (size_t)(((tr * H + i * sh + b) * W + j * sw + d) * x_ld + c), xbf); + }; + float v; + if (!mean) { + v = val(o); + } else { + float s = 0.0f; + for (int q = o * grp; q < (o + 1) * grp; ++q) s += val(q); + v = rdx(s / (float)grp, ybf); + } + const size_t oy = (size_t)(r * y_ld + o); + stx(y, oy, add ? ldx(y, oy, ybf) + rdx(v, ybf) : v, ybf); + } +} + +// ---------------------------------------------------------------------------- pix_patch / patch_pix8 +__device__ __forceinline__ int patch_col(int c, int ph, int pw, int p, bool wh) { + return c * p * p + (wh ? pw * p + ph : ph * p + pw); +} + +// A thread an image value. +__global__ __launch_bounds__(kT) void pix_patch_kernel( + const void* __restrict__ x, void* __restrict__ y, int H, int W, int C, int p, bool wh, + long long x_ld, long long y_ld, bool xbf, bool ybf) { + const long long n = (long long)H * W * C; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const int c = (int)(e % C); + const long long px = e / C; + const int yy = (int)(px / W), xx = (int)(px % W); + stx(y, (size_t)((yy / p) * y_ld + (long long)(xx / p) * C * p * p + + patch_col(c, yy % p, xx % p, p, wh)), + ldx(x, (size_t)(yy * x_ld + (long long)xx * C + c), xbf), ybf); + } +} + +// A thread an output byte. +__global__ __launch_bounds__(kT) void patch_pix8_kernel( + const void* __restrict__ x, uint8_t* __restrict__ y, long long R, int w, int C, int p, bool wh, + long long x_ld, long long y_ld, bool xbf) { + const long long Wp = (long long)w * p * C, n = R * p * Wp; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long yy = e / Wp; + const int rem = (int)(e % Wp), xx = rem / C, c = rem % C; + const float v = ldx(x, (size_t)((yy / p) * x_ld + (long long)(xx / p) * C * p * p + + patch_col(c, (int)(yy % p), xx % p, p, wh)), xbf); + const float cl = fminf(fmaxf(v, -1.0f), 1.0f); + const float u = fminf(fmaxf(rdx(rdx(cl / 2.0f, xbf) + 0.5f, xbf), 0.0f), 1.0f); + y[yy * y_ld + xx * C + c] = (uint8_t)rintf(u * 255.0f); + } +} + +// ---------------------------------------------------------------------------- attn_na3d +// 3-D neighborhood attention (libref/ref_attn.cpp states it): a thread a (query, head), its query +// in registers, the window's keys streamed from memory -- neighbouring queries share all but a +// slice of their windows, so the caches serve most reads -- in libref's two passes, the maximum +// and then the exponentials' sum and the weighted values. +template +__global__ __launch_bounds__(kT) void attn_na3d_kernel( + const void* __restrict__ q, const void* __restrict__ k, const void* __restrict__ v, + const int* __restrict__ geom, void* __restrict__ o, long long rows, int kt, int kh, int kw, + float scale, long long q_ld, long long k_ld, long long v_ld, long long o_ld, bool qbf, bool kbf, + bool vbf, bool obf) { + const int h = blockIdx.y; + const long long r = (long long)blockIdx.x * kT + threadIdx.x; + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0 || r >= min(rows, (long long)T * H * W)) return; + const int nt = min(kt, T), nh = min(kh, H), nw = min(kw, W); + const int t = (int)(r / ((long long)H * W)), i = (int)((r / W) % H), j = (int)(r % W); + const int t0 = min(max(t - nt / 2, 0), T - nt), i0 = min(max(i - nh / 2, 0), H - nh); + const int j0 = min(max(j - nw / 2, 0), W - nw); + float qv[HD]; + for (int d = 0; d < HD; ++d) qv[d] = ldx(q, (size_t)(r * q_ld + h * HD + d), qbf); + auto score = [&](long long key) { + float dot = 0.0f; + const size_t kb = (size_t)(key * k_ld + h * HD); + for (int d = 0; d < HD; ++d) dot = __fadd_rn(dot, __fmul_rn(qv[d], ldx(k, kb + d, kbf))); + return dot * scale; + }; + float mx = -INFINITY; + for (int a1 = t0; a1 < t0 + nt; ++a1) + for (int b1 = i0; b1 < i0 + nh; ++b1) { + const long long base = ((long long)a1 * H + b1) * W; + for (int c1 = j0; c1 < j0 + nw; ++c1) mx = fmaxf(mx, score(base + c1)); + } + float acc[HD]; + for (int d = 0; d < HD; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int a1 = t0; a1 < t0 + nt; ++a1) + for (int b1 = i0; b1 < i0 + nh; ++b1) { + const long long base = ((long long)a1 * H + b1) * W; + for (int c1 = j0; c1 < j0 + nw; ++c1) { + const float w = expf(score(base + c1) - mx); + sum += w; + const size_t vb = (size_t)((base + c1) * v_ld + h * HD); + for (int d = 0; d < HD; ++d) acc[d] = fmaf(w, ldx(v, vb + d, vbf), acc[d]); + } + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int d = 0; d < HD; ++d) stx(o, (size_t)(r * o_ld + h * HD + d), acc[d] * inv, obf); +} + +// The same over bf16 operands, each row read 8 values at a time (16-byte loads: the rows sit at +// multiples of 8 values and the heads at multiples of 64). +__device__ __forceinline__ void bf16x8(const uint16_t* __restrict__ p, float* f) { + const uint4 u = *(const uint4*)p; + const uint32_t w[4] = { u.x, u.y, u.z, u.w }; + for (int i = 0; i < 4; ++i) { + f[2 * i] = __uint_as_float(w[i] << 16); + f[2 * i + 1] = __uint_as_float(w[i] & 0xffff0000u); + } +} + +template +__global__ __launch_bounds__(kT) void attn_na3d_bf16_kernel( + const uint16_t* __restrict__ q, const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, + const int* __restrict__ geom, uint16_t* __restrict__ o, long long rows, int kt, int kh, int kw, + float scale, long long q_ld, long long k_ld, long long v_ld, long long o_ld) { + const int h = blockIdx.y; + const long long r = (long long)blockIdx.x * kT + threadIdx.x; + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0 || r >= min(rows, (long long)T * H * W)) return; + const int nt = min(kt, T), nh = min(kh, H), nw = min(kw, W); + const int t = (int)(r / ((long long)H * W)), i = (int)((r / W) % H), j = (int)(r % W); + const int t0 = min(max(t - nt / 2, 0), T - nt), i0 = min(max(i - nh / 2, 0), H - nh); + const int j0 = min(max(j - nw / 2, 0), W - nw); + float qv[HD]; + for (int d = 0; d < HD; d += 8) bf16x8(q + r * q_ld + h * HD + d, qv + d); + auto score = [&](long long key) { + const uint16_t* kr = k + key * k_ld + h * HD; + float dot = 0.0f; + for (int d = 0; d < HD; d += 8) { + float kk[8]; + bf16x8(kr + d, kk); + for (int e = 0; e < 8; ++e) dot = fmaf(qv[d + e], kk[e], dot); + } + return dot * scale; + }; + float mx = -INFINITY; + for (int a1 = t0; a1 < t0 + nt; ++a1) + for (int b1 = i0; b1 < i0 + nh; ++b1) { + const long long base = ((long long)a1 * H + b1) * W; + for (int c1 = j0; c1 < j0 + nw; ++c1) mx = fmaxf(mx, score(base + c1)); + } + float acc[HD]; + for (int d = 0; d < HD; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int a1 = t0; a1 < t0 + nt; ++a1) + for (int b1 = i0; b1 < i0 + nh; ++b1) { + const long long base = ((long long)a1 * H + b1) * W; + for (int c1 = j0; c1 < j0 + nw; ++c1) { + const float w = expf(score(base + c1) - mx); + sum += w; + const uint16_t* vr = v + (base + c1) * v_ld + h * HD; + for (int d = 0; d < HD; d += 8) { + float vv[8]; + bf16x8(vr + d, vv); + for (int e = 0; e < 8; ++e) acc[d + e] = fmaf(w, vv[e], acc[d + e]); + } + } + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int d = 0; d < HD; ++d) o[r * o_ld + h * HD + d] = f32_to_bf16(acc[d] * inv); +} + +// ---------------------------------------------------------------------------- vol_index +// A thread a voxel's three coordinates. +__global__ __launch_bounds__(kT) void vol_index_kernel(const int* __restrict__ geom, + int* __restrict__ y, long long n, + long long y_ld) { + const int T = geom[0], H = geom[1], W = geom[2]; + if (T <= 0 || H <= 0 || W <= 0) return; + const long long m1 = min(n, (long long)T * H * W); + for (long long m = (long long)blockIdx.x * kT + threadIdx.x; m < m1; + m += (long long)gridDim.x * kT) { + y[m] = (int)(m / ((long long)H * W)); + y[y_ld + m] = (int)((m / W) % H); + y[2 * y_ld + m] = (int)(m % W); + } +} + +// ---------------------------------------------------------------------------- tile_grid / tile_crop / tile_stitch +// diffusers' tiled decodes (libref/ref_ltx.cpp states the cuts and the blends): the boxes, a +// tile's voxels out of a volume, the tiles blended to bytes. The volumes are read off the device. +struct TileCutD { + int tile, stride, least; + bool intervals; + __device__ int count(int L) const { + if (intervals && L <= tile) return 1; + int n = (L + stride - 1) / stride; + while (intervals && n > 1 && L - (n - 1) * stride < least) --n; + return n; + } + __device__ int len(int L, int k) const { + return k == count(L) - 1 ? L - k * stride : min(tile, L - k * stride); + } +}; + +// A thread a row of the box table. +__global__ __launch_bounds__(kT) void tile_grid_kernel(const int* __restrict__ geom, + int* __restrict__ y, int n, TileCutD cs, + TileCutD ct, int tail) { + const int k = blockIdx.x * kT + threadIdx.x; + if (k >= n) return; + const int T = geom[0], H = geom[1], W = geom[2]; + int row[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + if (T > 0 && H > 0 && W > 0) { + const int nt = ct.count(T), ni = cs.count(H), nj = cs.count(W), count = nt * ni * nj; + if (k < count) { + const int kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj; + row[0] = ct.len(T, kt) + (kt == nt - 1 ? tail : 0); + row[1] = cs.len(H, i); + row[2] = cs.len(W, j); + row[3] = kt * ct.stride; + row[4] = i * cs.stride; + row[5] = j * cs.stride; + row[6] = k; + row[7] = count; + } + } + for (int e = 0; e < 8; ++e) y[(long long)k * 8 + e] = row[e]; +} + +// A thread an output value; rows past the box's voxels (or the `rows` y holds) are left alone. +__global__ __launch_bounds__(kT) void tile_crop_kernel( + const void* __restrict__ x, void* __restrict__ y, const int* __restrict__ geom, + const int* __restrict__ box, long long rows, int C, long long x_ld, long long y_ld, bool xbf, + bool ybf) { + const int T = geom[0], H = geom[1], W = geom[2]; + const int t = box[0], h = box[1], w = box[2], t0 = box[3], y0 = box[4], x0 = box[5]; + if (t <= 0 || h <= 0 || w <= 0 || t0 < 0 || y0 < 0 || x0 < 0 || t0 + t > T || y0 + h > H || + x0 + w > W) + return; + const long long n = min(rows, (long long)t * h * w) * C; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long r = e / C; + const int c = (int)(e % C); + const long long f = r / ((long long)h * w), i = (r / w) % h, j = r % w; + const long long xr = ((t0 + f) * H + y0 + i) * W + x0 + j; + stx(y, (size_t)(r * y_ld + c), ldx(x, (size_t)(xr * x_ld + c), xbf), ybf); + } +} + +// The tile store's layout: time bands of every tile back to back. +struct TileStoreD { + TileCutD cs, ct; + int T, H, W, sc, st; + __device__ int frames(int kt) const { return st * ct.len(T, kt) - (kt == 0 ? st - 1 : 0); } + __device__ long long offset(int kt, int i, int j) const { + const int nj = cs.count(W), ni = cs.count(H); + long long hsum = 0, wsum = 0, left = 0, above = 0, before = 0; + for (int q = 0; q < nj; ++q) { + const int b = cs.len(W, q); + wsum += b; + if (q < j) left += b; + } + for (int q = 0; q < ni; ++q) { + const int b = cs.len(H, q); + hsum += b; + if (q < i) above += b; + } + for (int q = 0; q < kt; ++q) before += frames(q); + return (long long)sc * sc * + (before * hsum * wsum + (long long)frames(kt) * (above * wsum + (long long)cs.len(H, i) * left)); + } +}; + +// A thread an output byte: up to eight tiles' values, the blends in libref's order and roundings. +__global__ __launch_bounds__(kT) void tile_stitch_kernel( + const void* __restrict__ x, uint8_t* __restrict__ y, const int* __restrict__ geom, + const int* __restrict__ first, long long y_rows, long long y_cols, TileCutD cs, TileCutD ct, + int sc, int st, int p, int C, bool wh, long long x_ld, long long y_ld, bool xbf) { + const int T = geom[0], H = geom[1], W = geom[2], f0 = first[0]; + const long long Hpx = (long long)H * sc * p, Wpx = (long long)W * sc * p; + if (T <= 0 || H <= 0 || W <= 0 || y_cols != Wpx * C || y_rows % Hpx) return; + const long long nf = y_rows / Hpx; + if (f0 < 0 || f0 + nf > (long long)st * T - (st - 1)) return; + const TileStoreD ts{ cs, ct, T, H, W, sc, st }; + const int nt = ct.count(T), ni = cs.count(H), nj = cs.count(W); + const long long s = (long long)cs.stride * sc * p, E = (long long)(cs.tile - cs.stride) * sc * p; + const long long Et = (long long)(ct.tile - ct.stride) * st, band = (long long)ct.stride * st; + const long long n = y_rows * y_cols; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long r = e / y_cols; + const int rem = (int)(e % y_cols), Xp = rem / C, c = rem % C; + const long long nfr = f0 + r / Hpx, Yp = r % Hpx; + const int kt = (int)min((nfr + st - 1) / band, (long long)nt - 1); + const int f = (int)(nfr - (kt == 0 ? 0 : kt * band - (st - 1))); + auto R = [&](int bk, int ti, int tj, int fr, int yy, int xx) { + const long long wp = (long long)cs.len(W, tj) * sc, hp = (long long)cs.len(H, ti) * sc; + const long long row = ts.offset(bk, ti, tj) + ((long long)fr * hp + yy / p) * wp + xx / p; + return ldx(x, (size_t)(row * x_ld + patch_col(c, yy % p, xx % p, p, wh)), xbf); + }; + auto mix = [&](float va, float vb, int k, int ext) { + const float wa = (float)(1.0 - (double)k / (double)ext); + const float wb = (float)((double)k / (double)ext); + return rdx(rdx(__fmul_rn(va, wa), xbf) + rdx(__fmul_rn(vb, wb), xbf), xbf); + }; + const int i = (int)min(Yp / s, (long long)ni - 1), j = (int)min((long long)Xp / s, (long long)nj - 1); + const int ly = (int)(Yp - i * s), lx = (int)(Xp - j * s); + const int ha = i > 0 ? cs.len(H, i - 1) * sc * p : 0; + const int ev = i > 0 ? (int)min(min((long long)ha, (long long)cs.len(H, i) * sc * p), E) : 0; + const int wl = j > 0 ? cs.len(W, j - 1) * sc * p : 0; + const int eh = j > 0 ? (int)min(min((long long)wl, (long long)cs.len(W, j) * sc * p), E) : 0; + const bool vb = i > 0 && ly < ev, hb = j > 0 && lx < eh; + auto S = [&](int bk, int fr) { + float V = R(bk, i, j, fr, ly, lx); + if (vb) { + const int ya = ha - ev + ly; + float A = R(bk, i - 1, j, fr, ya, lx); + if (hb) A = mix(R(bk, i - 1, j - 1, fr, ya, wl - eh + lx), A, lx, eh); + V = mix(A, V, ly, ev); + } + if (hb) { + float L = R(bk, i, j - 1, fr, ly, wl - eh + lx); + if (vb) L = mix(R(bk, i - 1, j - 1, fr, ha - ev + ly, wl - eh + lx), L, ly, ev); + V = mix(L, V, lx, eh); + } + return V; + }; + float v = S(kt, f); + if (kt > 0) { + const int et = (int)min(min((long long)ts.frames(kt - 1), (long long)ts.frames(kt)), Et); + if (f < et) v = mix(S(kt - 1, ts.frames(kt - 1) - et + f), v, f, et); + } + const float cl = fminf(fmaxf(v, -1.0f), 1.0f); + const float u = fminf(fmaxf(rdx(rdx(cl / 2.0f, xbf) + 0.5f, xbf), 0.0f), 1.0f); + y[r * y_ld + (long long)Xp * C + c] = (uint8_t)rintf(u * 255.0f); + } +} + +// ---------------------------------------------------------------------------- stft_logmel +// A workgroup a (frame, channel): the frame's samples into LDS, a thread a frequency bin's real +// and imaginary sums (ascending, as libref), the magnitudes into LDS, then a thread a mel bin. +constexpr int kStftMaxN = 4096; + +__global__ __launch_bounds__(kT) void stft_logmel_kernel( + const void* __restrict__ x, const void* __restrict__ basis, const void* __restrict__ melb, + void* __restrict__ y, int frames, int ch, int hop, int nfft, int nm, long long x_ld, + long long y_ld, bool xbf, bool bbf, bool mbf, bool ybf) { + __shared__ float sx[kStftMaxN]; + __shared__ float mag[kStftMaxN / 2 + 1]; + const int t = blockIdx.x, h = blockIdx.y, F = nfft / 2 + 1, pad = nfft - hop; + for (int j = threadIdx.x; j < nfft; j += kT) { + const long long s = (long long)t * hop + j - pad; + sx[j] = s < 0 ? 0.0f : ldx(x, (size_t)(s * x_ld + h), xbf); + } + __syncthreads(); + for (int k = threadIdx.x; k < F; k += kT) { + float re = 0.0f, im = 0.0f; + const size_t br = (size_t)k * nfft, bi = (size_t)(F + k) * nfft; + for (int j = 0; j < nfft; ++j) { + re += ldx(basis, br + j, bbf) * sx[j]; + im += ldx(basis, bi + j, bbf) * sx[j]; + } + re = rdx(re, ybf); + im = rdx(im, ybf); + mag[k] = rdx(sqrtf(rdx(rdx(re * re, ybf) + rdx(im * im, ybf), ybf)), ybf); + } + __syncthreads(); + const float fl = rdx(1e-5f, ybf); + for (int m = threadIdx.x; m < nm; m += kT) { + float s = 0.0f; + for (int k = 0; k < F; ++k) s += ldx(melb, (size_t)m * F + k, mbf) * mag[k]; + stx(y, (size_t)((long long)t * y_ld + (long long)h * nm + m), logf(fmaxf(rdx(s, ybf), fl)), + ybf); + } +} + +// ---------------------------------------------------------------------------- bwe_up +// A thread an output value; the resampler's taps are worked out on the host as libref does and +// passed by value. +// Taps for ratios up to 4 (2 w r + 1 = 57): the filter is passed by value, and the backend's +// kernel-argument slot is 768 bytes. +constexpr int kBweTaps = 64; +struct BweTaps { float f[kBweTaps]; }; + +__global__ __launch_bounds__(kT) void bwe_up_kernel( + const void* __restrict__ x, const void* __restrict__ res, void* __restrict__ y, BweTaps f, + long long S, long long O, int ch, int r, int w, int K, long long x_ld, long long r_ld, + long long y_ld, bool xbf, bool rbf, bool ybf) { + const long long n = O * ch; + for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n; + e += (long long)gridDim.x * kT) { + const long long o = e / ch; + const int h = (int)(e % ch); + const long long u = o + 2ll * w * r; + float acc = 0.0f; + for (int k = (int)(u % r); k < K; k += r) { + const long long i = (u - k) / r; + const long long s = min(max(i - w, 0ll), S - 1); + acc += f.f[k] * ldx(x, (size_t)(s * x_ld + h), xbf); + } + const float up = rdx((float)r * rdx(acc, xbf), xbf); + const float v = rdx(ldx(res, (size_t)(o * r_ld + h), rbf) + up, xbf); + stx(y, (size_t)(o * y_ld + h), fminf(fmaxf(v, -1.0f), 1.0f), ybf); + } +} + +inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } +inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; } +inline bool is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; } +inline bool is_bf_or_f32(const RadTensor* t) { return is_bf16(t) || is_f32(t); } + +int parse_floats(const char* s, float* out, int max) { + int n = 0; + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + if (n == max) return max + 1; + out[n++] = (float)v; + s = end; + } + return n; +} + +} // namespace + +// ============================================================== the plugin ABI entry points + +extern "C" int r4d_rad_rope_split(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *p = r4d_opt(a, 1); + if (!x || !p) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !(p->dtype == RAD_F32 || p->dtype == RAD_I32)) + return R4D_NO(RAD_E_DTYPE); + const long long nh = r4d_geti_or(a, "n_head", 0), hd = r4d_geti_or(a, "head_dim", 0); + const long long dim = r4d_geti_or(a, "dim", 0), nd = r4d_geti_or(a, "n_dims", 0); + const long long h0 = r4d_geti_or(a, "head0", 0); + float mx[kMaxDims] = { 1, 1, 1, 1 }; + if (nh <= 0 || hd <= 0 || (hd & 1) || hd / 2 > 256 || (kT % (hd / 2)) || nd <= 0 || + nd > kMaxDims || dim < (h0 + nh) * hd || + parse_floats(r4d_gets(a, "max"), mx, kMaxDims) != (int)nd) + return R4D_NO(RAD_E_SHAPE); + long long rows = 0; + const long long xl = r4d_rows_pitch(x, nh * hd, &rows); + if (xl < 0) return R4D_NO(RAD_E_STRIDE); + if (rows <= 0) return R4D_NO(RAD_E_SHAPE); + // positions [n_dims, M] at its strides, or [M]. + long long pl = 1, pc = 0; + if (p->rank >= 2) { + pc = p->stride[0]; + pl = p->stride[1]; + if (p->shape[0] < nd || p->shape[1] < rows) return R4D_NO(RAD_E_SHAPE); + } else { + pl = p->rank ? p->stride[0] : 1; + if (nd != 1 || r4d_numel(p) < rows) return R4D_NO(RAD_E_SHAPE); + } + const long long P2 = dim / 2, steps = P2 / nd, pad = P2 - steps * nd; + dim3 grid((unsigned)((rows + kRopeRows - 1) / kRopeRows), (unsigned)nh); + hipLaunchKernelGGL(rope_split_kernel, grid, dim3(kT), 0, (hipStream_t)s, x->data, p->data, + (int)rows, (int)nh, (int)hd, (int)h0, (int)nd, (int)steps, (int)pad, + r4d_getf(a, "theta", 10000.0), mx[0], mx[1], mx[2], mx[3], xl, pl, pc, + is_bf16(x), p->dtype == RAD_I32); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_head_gate(const RadArgs* a, RadStream s) { + const RadTensor *g = r4d_opt(a, 0), *x = r4d_opt(a, 1); + if (!g || !x) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(g) || !is_bf_or_f32(x)) return R4D_NO(RAD_E_DTYPE); + const long long nh = r4d_geti_or(a, "n_head", 0), hd = r4d_geti_or(a, "head_dim", 0); + if (nh <= 0 || hd <= 0) return R4D_NO(RAD_E_SHAPE); + long long rows = 0, rg = 0; + const long long xl = r4d_rows_pitch(x, nh * hd, &rows), gl = r4d_rows_pitch(g, nh, &rg); + if (xl < 0 || gl < 0) return R4D_NO(RAD_E_STRIDE); + if (rows <= 0 || rg < rows) return R4D_NO(RAD_E_SHAPE); + const long long total = rows * nh * hd; + hipLaunchKernelGGL(head_gate_kernel, dim3((unsigned)((total + kT - 1) / kT)), dim3(kT), 0, + (hipStream_t)s, x->data, (const uint16_t*)g->data, total, (int)(nh * hd), + (int)hd, xl, gl, is_bf16(x)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_ltx_guide(const RadArgs* a, RadStream s) { + const RadTensor *vc = r4d_opt(a, 0), *vu = r4d_opt(a, 1), *vs = r4d_opt(a, 2); + const RadTensor *vm = r4d_opt(a, 3), *sc = r4d_opt(a, 4), *sh = r4d_opt(a, 5); + const RadTensor *st = r4d_opt(a, 6), *x = r4d_opt(a, 7); + if (!vc || !sc || !sh || !st || !x) return R4D_NO(RAD_E_INVAL); + if (!is_f32(x) || !is_f32(sc) || !is_f32(sh) || !is_f32(st)) return R4D_NO(RAD_E_DTYPE); + for (const RadTensor* v : { vc, vu, vs, vm }) + if (v && !is_bf_or_f32(v)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rows = 0; + const long long xl = r4d_rows_pitch(x, n, &rows); + if (xl < 0) return R4D_NO(RAD_E_STRIDE); + if (n <= 0 || rows <= 0 || r4d_numel(sc) < 4 || r4d_numel(sh) < 2 || + r4d_numel(st) < 2 * 4 * kGuideParts || !r4d_contig(sc) || !r4d_contig(sh) || + ((uintptr_t)st->data & 7)) + return R4D_NO(RAD_E_SHAPE); + GuideIn in{}; + const RadTensor* vv[4] = { vc, vu, vs, vm }; + const void** dst[4] = { &in.vc, &in.vu, &in.vs, &in.vm }; + long long* ld[4] = { &in.lc, &in.lu, &in.ls, &in.lm }; + bool* bf[4] = { &in.bc, &in.bu, &in.bs, &in.bm }; + for (int i = 0; i < 4; ++i) { + *dst[i] = nullptr; + if (!vv[i]) continue; + long long rv = 0; + const long long l = r4d_rows_pitch(vv[i], n, &rv); + if (l < 0) return R4D_NO(RAD_E_STRIDE); + if (rv < rows) return R4D_NO(RAD_E_SHAPE); + *dst[i] = vv[i]->data; + *ld[i] = l; + *bf[i] = is_bf16(vv[i]); + } + const long long total = rows * n; + const int parts = (int)std::min(kGuideParts, (total + kT - 1) / kT); + double* pd = (double*)st->data; + hipLaunchKernelGGL(ltx_guide_sum_kernel, dim3((unsigned)parts), dim3(kT), 0, (hipStream_t)s, + in, (const float*)x->data, (const float*)sc->data, (const float*)sh->data, + pd, rows, (int)n, xl); + hipLaunchKernelGGL(ltx_guide_step_kernel, dim3((unsigned)parts), dim3(kT), 0, (hipStream_t)s, + in, (float*)x->data, (const float*)sc->data, (const float*)sh->data, pd, + parts, rows, (int)n, xl); + return st_of(hipGetLastError()); +} + +namespace { + +// Workgroups for a grid-stride loop over n values. +inline unsigned grid_for(long long n) { + return (unsigned)std::max(1ll, std::min((n + kT - 1) / kT, 1ll << 20)); +} + +// A dense 2-D operand: its rows, columns and row pitch, or false. +inline bool dense2(const RadTensor* t, long long* rows, long long* cols, long long* ld) { + if (!t || t->rank != 2 || t->stride[1] != 1 || t->shape[0] <= 0 || t->shape[1] <= 0) + return false; + *rows = t->shape[0]; + *cols = t->shape[1]; + *ld = t->stride[0]; + return true; +} + +// `order`: wh (the default, LTX-2's) or hw; -1 for anything else. +inline int patch_order(const RadArgs* a) { + const char* o = r4d_gets(a, "order"); + if (!o || !*o || !std::strcmp(o, "wh")) return 1; + return std::strcmp(o, "hw") ? -1 : 0; +} + +} // namespace + +extern "C" int r4d_rad_pixel_norm(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), L = r4d_geti_or(a, "ileave", 1); + const char *form = r4d_gets(a, "form"), *act = r4d_gets(a, "act"); + const bool divf = form && !std::strcmp(form, "div"); + const bool silu = act && !std::strcmp(act, "silu"); + if ((form && *form && !divf && std::strcmp(form, "rsqrt")) || + (act && *act && !silu && std::strcmp(act, "none"))) + return R4D_NO(RAD_E_INVAL); + if (n <= 0 || L <= 0) return R4D_NO(RAD_E_SHAPE); + long long ry = 0, rx = 0; + const long long yl = r4d_rows_pitch(y, n * L, &ry), xl = r4d_rows_pitch(x, n, &rx); + if (yl < 0 || xl < 0) return R4D_NO(RAD_E_STRIDE); + const long long rows = ry * L; + if (rows <= 0 || rx < rows) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(pixel_norm_kernel, dim3((unsigned)((rows + kT / 32 - 1) / (kT / 32))), + dim3(kT), 0, (hipStream_t)s, x->data, y->data, rows, (int)n, (int)L, + (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "mult", 1.0), xl, yl, + is_bf16(x), is_bf16(y), divf, silu); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_d2s3d(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !g || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(y) || g->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "C", 0), st = r4d_geti_or(a, "st", 1); + const long long sh = r4d_geti_or(a, "sh", 1), sw = r4d_geti_or(a, "sw", 1); + const long long drop = r4d_geti_or(a, "drop", st - 1); + if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || drop < 0 || drop >= st || r4d_numel(g) < 3 || + !r4d_contig(g)) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, C * st * sh * sw, &rx), yl = r4d_rows_pitch(y, C, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || ry <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(d2s3d_kernel, dim3(grid_for(ry * C)), dim3(kT), 0, (hipStream_t)s, x->data, + y->data, (const int*)g->data, ry, (int)C, (int)st, (int)sh, (int)sw, (int)drop, + xl, yl, is_bf16(x), is_bf16(y)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_s2d3d(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !g || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(y) || g->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "C", 0), st = r4d_geti_or(a, "st", 1); + const long long sh = r4d_geti_or(a, "sh", 1), sw = r4d_geti_or(a, "sw", 1); + const long long tpre = r4d_geti_or(a, "tpre", 0), grp = r4d_geti_or(a, "group", 1); + const char* mode = r4d_gets(a, "mode"); + const bool mean = mode && !std::strcmp(mode, "mean"); + if (mode && *mode && !mean && std::strcmp(mode, "copy")) return R4D_NO(RAD_E_INVAL); + const long long P = C * st * sh * sw; + if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || grp <= 0 || (mean && P % grp) || + r4d_numel(g) < 3 || !r4d_contig(g)) + return R4D_NO(RAD_E_SHAPE); + const long long Co = mean ? P / grp : P; + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, C, &rx), yl = r4d_rows_pitch(y, Co, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || ry <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(s2d3d_kernel, dim3(grid_for(ry * Co)), dim3(kT), 0, (hipStream_t)s, x->data, + y->data, (const int*)g->data, ry, (int)C, (int)st, (int)sh, (int)sw, + (int)tpre, (int)grp, (int)Co, xl, yl, is_bf16(x), is_bf16(y), mean, + r4d_geti_or(a, "add", 0) != 0); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_pix_patch(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long p = r4d_geti_or(a, "p", 0), C = r4d_geti_or(a, "C", 0); + const int wh = patch_order(a); + if (wh < 0) return R4D_NO(RAD_E_INVAL); + long long H = 0, WC = 0, xl = 0, Ry = 0, Cy = 0, yl = 0; + if (!dense2(x, &H, &WC, &xl) || !dense2(y, &Ry, &Cy, &yl)) return R4D_NO(RAD_E_SHAPE); + if (p <= 0 || C <= 0 || WC % C) return R4D_NO(RAD_E_SHAPE); + const long long W = WC / C; + if (H % p || W % p || Ry != H / p || Cy != (W / p) * C * p * p) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(pix_patch_kernel, dim3(grid_for(H * W * C)), dim3(kT), 0, (hipStream_t)s, + x->data, y->data, (int)H, (int)W, (int)C, (int)p, wh == 1, xl, yl, + is_bf16(x), is_bf16(y)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_patch_pix8(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || y->dtype != RAD_U8) return R4D_NO(RAD_E_DTYPE); + const long long p = r4d_geti_or(a, "p", 0), C = r4d_geti_or(a, "C", 0); + const int wh = patch_order(a); + if (wh < 0) return R4D_NO(RAD_E_INVAL); + long long R = 0, Cx = 0, xl = 0, Ry = 0, Cy = 0, yl = 0; + if (!dense2(x, &R, &Cx, &xl) || !dense2(y, &Ry, &Cy, &yl)) return R4D_NO(RAD_E_SHAPE); + if (p <= 0 || C <= 0 || Cx % (C * p * p)) return R4D_NO(RAD_E_SHAPE); + const long long w = Cx / (C * p * p); + if (Ry != R * p || Cy != w * p * C) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(patch_pix8_kernel, dim3(grid_for(Ry * Cy)), dim3(kT), 0, (hipStream_t)s, + x->data, (uint8_t*)y->data, R, (int)w, (int)C, (int)p, wh == 1, xl, yl, + is_bf16(x)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_attn_na3d(const RadArgs* a, RadStream s) { + const RadTensor *q = r4d_opt(a, 0), *k = r4d_opt(a, 1), *v = r4d_opt(a, 2), *g = r4d_opt(a, 3); + const RadTensor* o = r4d_opt(a, 4); + if (!q || !k || !v || !g || !o) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(q) || !is_bf_or_f32(k) || !is_bf_or_f32(v) || !is_bf_or_f32(o) || + g->dtype != RAD_I32) + return R4D_NO(RAD_E_DTYPE); + const long long hd = r4d_geti_or(a, "head_dim", 0), kt = r4d_geti_or(a, "kt", 0); + const long long kh = r4d_geti_or(a, "kh", 0), kw = r4d_geti_or(a, "kw", 0); + if (hd != 64 || kt <= 0 || kh <= 0 || kw <= 0 || r4d_numel(g) < 3 || !r4d_contig(g) || + q->rank != 2 || q->shape[1] % hd) + return R4D_NO(RAD_E_SHAPE); + const long long heads = q->shape[1] / hd, D = heads * hd; + long long rq = 0, rk = 0, rv = 0, ro = 0; + const long long ql = r4d_rows_pitch(q, D, &rq), kl = r4d_rows_pitch(k, D, &rk); + const long long vl = r4d_rows_pitch(v, D, &rv), ol = r4d_rows_pitch(o, D, &ro); + if (ql < 0 || kl < 0 || vl < 0 || ol < 0) return R4D_NO(RAD_E_STRIDE); + if (rq <= 0 || rk < rq || rv < rq || ro < rq) return R4D_NO(RAD_E_SHAPE); + const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd)); + const dim3 grid((unsigned)((rq + kT - 1) / kT), (unsigned)heads); + if (is_bf16(q) && is_bf16(k) && is_bf16(v) && is_bf16(o) && ql % 8 == 0 && kl % 8 == 0 && + vl % 8 == 0 && ((uintptr_t)q->data | (uintptr_t)k->data | (uintptr_t)v->data) % 16 == 0) { + hipLaunchKernelGGL(attn_na3d_bf16_kernel<64>, grid, dim3(kT), 0, (hipStream_t)s, + (const uint16_t*)q->data, (const uint16_t*)k->data, + (const uint16_t*)v->data, (const int*)g->data, (uint16_t*)o->data, rq, + (int)kt, (int)kh, (int)kw, scale, ql, kl, vl, ol); + return st_of(hipGetLastError()); + } + hipLaunchKernelGGL(attn_na3d_kernel<64>, grid, dim3(kT), 0, (hipStream_t)s, q->data, k->data, + v->data, (const int*)g->data, o->data, rq, (int)kt, (int)kh, (int)kw, scale, + ql, kl, vl, ol, is_bf16(q), is_bf16(k), is_bf16(v), is_bf16(o)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_vol_index(const RadArgs* a, RadStream s) { + const RadTensor *g = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!g || !y) return R4D_NO(RAD_E_INVAL); + if (g->dtype != RAD_I32 || y->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + if (r4d_numel(g) < 3 || !r4d_contig(g) || y->rank != 2 || y->shape[0] != 3 || + y->shape[1] <= 0 || y->stride[1] != 1) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(vol_index_kernel, dim3(grid_for(y->shape[1])), dim3(kT), 0, (hipStream_t)s, + (const int*)g->data, (int*)y->data, (long long)y->shape[1], + (long long)y->stride[0]); + return st_of(hipGetLastError()); +} + +// The cuts a tile op's parameters name (libref's tile_cuts); false when one is out of range. +static bool tile_cuts_d(const RadArgs* a, TileCutD* s, TileCutD* t) { + const char* rs = r4d_gets(a, "rule"); + const char* rule = rs ? rs : "stride"; + const bool iv = std::strcmp(rule, "intervals") == 0; + if (!iv && std::strcmp(rule, "stride") != 0) return false; + *s = TileCutD{ (int)r4d_geti_or(a, "tile", 0), (int)r4d_geti_or(a, "stride", 0), + (int)r4d_geti_or(a, "min", 1), iv }; + *t = TileCutD{ (int)r4d_geti_or(a, "tile_t", 1 << 30), (int)r4d_geti_or(a, "stride_t", 1 << 30), + (int)r4d_geti_or(a, "min_t", 1), iv }; + return s->tile > 0 && s->stride > 0 && s->stride <= s->tile && s->least > 0 && t->tile > 0 && + t->stride > 0 && t->stride <= t->tile && t->least > 0; +} + +extern "C" int r4d_rad_tile_grid(const RadArgs* a, RadStream s) { + const RadTensor *g = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!g || !y) return R4D_NO(RAD_E_INVAL); + if (g->dtype != RAD_I32 || y->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + TileCutD cs, ct; + const long long n = r4d_numel(y) / 8, tail = r4d_geti_or(a, "tail", 0); + if (!tile_cuts_d(a, &cs, &ct) || tail < 0 || n <= 0 || r4d_numel(g) < 3 || !r4d_contig(g) || + !r4d_contig(y)) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(tile_grid_kernel, dim3((unsigned)((n + kT - 1) / kT)), dim3(kT), 0, + (hipStream_t)s, (const int*)g->data, (int*)y->data, (int)n, cs, ct, (int)tail); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_tile_crop(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *b = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !g || !b || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(y) || g->dtype != RAD_I32 || b->dtype != RAD_I32) + return R4D_NO(RAD_E_DTYPE); + const long long C = r4d_geti_or(a, "C", 0); + if (C <= 0 || r4d_numel(g) < 3 || r4d_numel(b) < 6 || !r4d_contig(g) || !r4d_contig(b)) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, C, &rx), yl = r4d_rows_pitch(y, C, &ry); + if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (rx <= 0 || ry <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(tile_crop_kernel, dim3(grid_for(ry * C)), dim3(kT), 0, (hipStream_t)s, + x->data, y->data, (const int*)g->data, (const int*)b->data, ry, (int)C, xl, + yl, is_bf16(x), is_bf16(y)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_tile_stitch(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *f = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !g || !f || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || g->dtype != RAD_I32 || f->dtype != RAD_I32 || y->dtype != RAD_U8) + return R4D_NO(RAD_E_DTYPE); + TileCutD cs, ct; + const long long sc = r4d_geti_or(a, "scale", 0), st = r4d_geti_or(a, "scale_t", 1); + const long long p = r4d_geti_or(a, "p", 0), C = r4d_geti_or(a, "C", 0); + const int wh = patch_order(a); + if (wh < 0) return R4D_NO(RAD_E_INVAL); + if (!tile_cuts_d(a, &cs, &ct) || sc <= 0 || st <= 0 || p <= 0 || C <= 0 || + r4d_numel(g) < 3 || r4d_numel(f) < 1 || !r4d_contig(g) || !r4d_contig(f)) + return R4D_NO(RAD_E_SHAPE); + long long rx = 0, Cx = 0, xl = 0, ry = 0, Cy = 0, yl = 0; + if (!dense2(x, &rx, &Cx, &xl) || !dense2(y, &ry, &Cy, &yl)) return R4D_NO(RAD_E_SHAPE); + if (Cx != C * p * p || ry <= 0 || Cy <= 0) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(tile_stitch_kernel, dim3(grid_for(ry * Cy)), dim3(kT), 0, (hipStream_t)s, + x->data, (uint8_t*)y->data, (const int*)g->data, (const int*)f->data, ry, Cy, + cs, ct, (int)sc, (int)st, (int)p, (int)C, wh == 1, xl, yl, is_bf16(x)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_stft_logmel(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *b = r4d_opt(a, 1), *m = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !b || !m || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(b) || !is_bf_or_f32(m) || !is_bf_or_f32(y)) + return R4D_NO(RAD_E_DTYPE); + const long long hop = r4d_geti_or(a, "hop", 0), nfft = r4d_geti_or(a, "nfft", 0); + const long long nm = r4d_geti_or(a, "n_mel", 0), ch = r4d_geti_or(a, "ch", 0); + if (hop <= 0 || nfft < hop || nfft > kStftMaxN || nm <= 0 || ch <= 0) + return R4D_NO(RAD_E_SHAPE); + const long long F = nfft / 2 + 1; + long long S = 0, frames = 0; + const long long xl = r4d_rows_pitch(x, ch, &S), yl = r4d_rows_pitch(y, ch * nm, &frames); + if (xl < 0 || yl < 0 || !r4d_contig(b) || !r4d_contig(m)) return R4D_NO(RAD_E_STRIDE); + if (S <= 0 || frames <= 0 || frames * hop > S || frames > INT32_MAX || + r4d_numel(b) < 2 * F * nfft || r4d_numel(m) < nm * F) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(stft_logmel_kernel, dim3((unsigned)frames, (unsigned)ch), dim3(kT), 0, + (hipStream_t)s, x->data, b->data, m->data, y->data, (int)frames, (int)ch, + (int)hop, (int)nfft, (int)nm, xl, yl, is_bf16(x), is_bf16(b), is_bf16(m), + is_bf16(y)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_bwe_up(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *rz = r4d_opt(a, 1), *y = r4d_opt(a, 2); + if (!x || !rz || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf_or_f32(x) || !is_bf_or_f32(rz) || !is_bf_or_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long r = r4d_geti_or(a, "ratio", 0), ch = r4d_geti_or(a, "ch", 0); + const int w = (int)std::ceil(6.0 / 0.99); + const long long K = 2ll * w * r + 1; + if (r <= 0 || ch <= 0 || K > kBweTaps) return R4D_NO(RAD_E_SHAPE); + long long S = 0, O = 0, Rr = 0; + const long long xl = r4d_rows_pitch(x, ch, &S), yl = r4d_rows_pitch(y, ch, &O); + const long long rl = r4d_rows_pitch(rz, ch, &Rr); + if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE); + if (S <= 0 || O <= 0 || O > S * r || Rr < O) return R4D_NO(RAD_E_SHAPE); + // libref's taps: f32 arithmetic as torch builds the filter, rounded to x's dtype. + BweTaps f{}; + for (long long n = 0; n < K; ++n) { + const float u = ((float)n / (float)r - (float)w) * 0.99f; + const float uc = std::min(std::max(u, -6.0f), 6.0f); + const float cw = std::cos(uc * (float)M_PI / 6.0f / 2.0f); + const float pu = (float)M_PI * u; + const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu; + const float v = sinc * (cw * cw) * 0.99f / (float)r; + f.f[n] = is_bf16(x) ? rad_bf16_to_f32(rad_f32_to_bf16(v)) : v; + } + hipLaunchKernelGGL(bwe_up_kernel, dim3(grid_for(O * ch)), dim3(kT), 0, (hipStream_t)s, + x->data, rz->data, y->data, f, S, O, (int)ch, (int)r, w, (int)K, xl, rl, yl, + is_bf16(x), is_bf16(rz), is_bf16(y)); + return st_of(hipGetLastError()); +} diff --git a/libr4d/r4d_mhc.hip b/libr4d/r4d_mhc.hip index 53a2b8ea..a92d039f 100644 --- a/libr4d/r4d_mhc.hip +++ b/libr4d/r4d_mhc.hip @@ -67,41 +67,8 @@ __global__ void mhc_partial_kernel(const uint16_t* h, const float* fn, Out out, } } -// Prefill reuses each F32 mixing weight across four BF16 token rows. -// Each row keeps the same accumulation and reduction order as the scalar-row path. -template -__global__ void mhc_partial_rows4_kernel(const uint16_t* h, const float* fn, Out out, int width, - int mix, int chunk0, long hp, long fp, long rows) { - __shared__ float sums[4][4]; - const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; - const int j = blockIdx.y, chunk = chunk0 + blockIdx.x; - const long first = (long)blockIdx.z * 4; - float sum[4] = { 0, 0, 0, 0 }; - for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) { - const float weight = j == mix ? 0 : fn[(long)j * fp + i]; -#pragma unroll - for (int r = 0; r < 4; ++r) - if (first + r < rows) { - const float v = bf16_to_f32(h[(first + r) * hp + i]); - sum[r] += v * (j == mix ? v : weight); - } - } -#pragma unroll - for (int r = 0; r < 4; ++r) { - sum[r] = warp_sum(sum[r]); - if (!lane) sums[r][wave] = sum[r]; - } - __syncthreads(); - if (!tid) - for (int r = 0; r < 4; ++r) - if (first + r < rows) { - *out.at(first + r, j, chunk) = sums[r][0] + sums[r][1] + sums[r][2] + sums[r][3]; - if (j == mix) out.pad(first + r, mix, chunk); - } -} - -// Reuse each input across four coefficients and each weight across four rows. -// All per-output K accumulation and reduction orders match the rows4 path. +// Prefill reuses each input across four coefficients and each F32 mixing weight across four BF16 +// token rows. Every output keeps mhc_partial_kernel's accumulation and reduction order. template __global__ void mhc_partial_rows4_coeff4_kernel(const uint16_t* h, const float* fn, Out out, int width, int mix, int chunk0, long hp, long fp, @@ -246,17 +213,18 @@ __global__ __launch_bounds__(128) void mhc_partial_vec_kernel(const uint16_t* h, } } -template +// The geometries without the chunk split: one workgroup a row projects the residual itself from +// `fn`, then mixes and collapses it. __global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* scale, const float* base, uint16_t* x, float* post, float* comb, int n, int hc, int iterations, float eps, float heps, long hp, long fp, - long xp, long pp, long cp, int chunks, In in) { + long xp, long pp, long cp) { __shared__ float sums[8], inverse, coefficients[80], pre[8], c[64]; const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; const long r = blockIdx.x; const int width = hc * n, mix = hc * (hc + 2); float ss = 0; - for (int i = tid; !chunks && i < width; i += 256) { + for (int i = tid; i < width; i += 256) { const float v = bf16_to_f32(h[r * hp + i]); ss += v * v; } @@ -265,20 +233,14 @@ __global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* __syncthreads(); if (!tid) { float s = 0; - if (chunks) - for (int i = 0; i < chunks; ++i) s += *in.at(r, mix, i); - else - for (int i = 0; i < 8; ++i) s += sums[i]; + for (int i = 0; i < 8; ++i) s += sums[i]; inverse = rsqrtf(s / (float)width + eps); } __syncthreads(); for (int j = wave; j < mix; j += 8) { float dot = 0; - if (chunks) - for (int i = lane; i < chunks; i += 32) dot += *in.at(r, j, i); - else - for (int i = lane; i < width; i += 32) - dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i]; + for (int i = lane; i < width; i += 32) + dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i]; dot = warp_sum(dot); if (!lane) coefficients[j] = dot * inverse; } @@ -319,7 +281,7 @@ __global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* for (int j = 0; j < hc * hc; ++j) comb[r * cp + j] = c[j]; } __syncthreads(); - if (VecX && mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return; + if (mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return; for (int i = tid; i < n; i += 256) { float v = 0; for (int j = 0; j < hc; ++j) v += pre[j] * bf16_to_f32(h[r * hp + j * n + i]); @@ -383,29 +345,8 @@ __device__ __forceinline__ float glm_warp_mix(int lane, long row, const float* s if (lane < 16) comb[row * cp + lane] = value; return pre; } -template -__global__ void mhc_pre_glm_warp_kernel(const uint16_t* h, const float* scale, const float* base, - uint16_t* x, float* post, float* comb, int iterations, - float eps, float heps, long hp, long xp, long pp, long cp, - In in) { - const int lane = threadIdx.x; - const long row = blockIdx.x; - const float pre = - glm_warp_mix(lane, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in); - const float p0 = __shfl(pre, 0, 32), p1 = __shfl(pre, 1, 32), p2 = __shfl(pre, 2, 32), - p3 = __shfl(pre, 3, 32); - for (int i = lane; i < 4096; i += 32) { - float v = 0; - v += p0 * bf16_to_f32(h[row * hp + i]); - v += p1 * bf16_to_f32(h[row * hp + 4096 + i]); - v += p2 * bf16_to_f32(h[row * hp + 8192 + i]); - v += p3 * bf16_to_f32(h[row * hp + 12288 + i]); - x[row * xp + i] = f32_to_bf16(v); - } -} - -// The warp kernel's mix on wave 0, then the collapsed read over the whole block: one wave writing -// 4096 columns a row was most of a decode step's mhc_pre. +// glm_warp_mix on wave 0, then the collapsed read over the whole block: one wave writing 4096 +// columns a row would be most of a decode step's mhc_pre. template __global__ __launch_bounds__(256) void mhc_pre_glm_wide_kernel( const uint16_t* h, const float* scale, const float* base, uint16_t* x, float* post, float* comb, @@ -516,23 +457,15 @@ constexpr int kChunkCols = 2048, kPartStride = 28; template int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out out, int n, int hc, int chunk0, int count, long rows) { - const char* rows4 = std::getenv("RADIANCE_MHC_PREFILL_ROWS4"); - const char* coeff4 = std::getenv("RADIANCE_MHC_PREFILL_COEFF4"); - /* From 2 rows the four-slot form (RADIANCE_MHC_PARTIAL_VEC 0 off, 1 at every row count; - * RADIANCE_MHC_PARTIAL_ROWS 1, 2 or 4 pins its rows a wave), on 16-byte weight and 8-byte - * residual rows; GLM's 2048-column chunks only. Measured cold on gfx1201 at GLM's shape: - * one row a wave leads up to 16 rows (13 us against the old 20 to 36), two rows from 48 - * (20 against 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave - * trail two at every count. */ - const char* vec = std::getenv("RADIANCE_MHC_PARTIAL_VEC"); + /* From 2 rows the four-slot form, on 16-byte weight and 8-byte residual rows; GLM's + * 2048-column chunks only. Measured cold on gfx1201 at GLM's shape: one row a wave leads up + * to 16 rows (13 us against 20 to 36 for the one-slot kernels), two rows from 48 (20 against + * 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave trail two at + * every count. */ const bool vec_aligned = ((uintptr_t)fn.data & 15) == 0 && fn.stride[0] % 4 == 0 && ((uintptr_t)h.data & 7) == 0 && h.stride[0] % 4 == 0 && hc * n % kChunkCols == 0; - if (vec_aligned && (vec ? vec[0] == '1' : rows >= 2)) { - const char* pin_rows = std::getenv("RADIANCE_MHC_PARTIAL_ROWS"); - const long R = pin_rows && *pin_rows ? std::strtol(pin_rows, nullptr, 10) - : rows >= 32 ? 2 - : 1; + if (vec_aligned && rows >= 2) { const int mix = hc * (hc + 2), groups = (mix + 4) / 4; #define MHC_VEC(RR) \ do { \ @@ -542,25 +475,18 @@ int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out (const float*)fn.data, out, mix, chunk0, count, (long)h.stride[0], \ (long)fn.stride[0], rows, items); \ } while (0) - if (R == 4) MHC_VEC(4); - if (R == 2) MHC_VEC(2); + if (rows >= 32) MHC_VEC(2); MHC_VEC(1); #undef MHC_VEC } - const char* rows4_min = std::getenv("RADIANCE_MHC_ROWS4_MIN"); - const bool use_rows4 = - (!rows4 || rows4[0] == '1') && - rows >= (rows4_min && *rows4_min ? std::strtol(rows4_min, nullptr, 10) : 32); - if (use_rows4 && (!coeff4 || coeff4[0] == '1')) + /* Otherwise four rows and four coefficients a block from 32 rows, one row and one coefficient + * below. */ + constexpr long kRows4Min = 32; + if (rows >= kRows4Min) return R4D_EMIT(stream, (mhc_partial_rows4_coeff4_kernel), dim3(count, (hc * (hc + 2) + 4) / 4, (unsigned)((rows + 3) / 4)), dim3(128), 0, (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2), chunk0, (long)h.stride[0], (long)fn.stride[0], rows); - if (use_rows4) - return R4D_EMIT(stream, (mhc_partial_rows4_kernel), - dim3(count, hc * (hc + 2) + 1, (unsigned)((rows + 3) / 4)), dim3(128), 0, - (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2), - chunk0, (long)h.stride[0], (long)fn.stride[0], rows); return R4D_EMIT(stream, (mhc_partial_kernel), dim3(count, hc * (hc + 2) + 1, (unsigned)rows), dim3(128), 0, (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2), @@ -571,39 +497,19 @@ int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out template int emit_finish(RadStream stream, const RadTensor& h, const float* fn, long fp, const RadTensor& s, const RadTensor& b, const RadTensor& x, const RadTensor& p, const RadTensor& c, - int n, int hc, int iters, float eps, float heps, long rows, int chunks, bool split, - In in) { - const char* warp = std::getenv("RADIANCE_MHC_PREFILL_WARP"); + int n, int hc, int iters, float eps, float heps, long rows, bool split, In in) { /* The warp mix at every row count: byte-identical to the scalar one and a quarter of its time - * at one to six rows. RADIANCE_MHC_FINISH, for the microbenchmark: `old` the one-wave finish - * from 32 rows and the scalar mix and read below, `scalar` that mix with the wide read. */ - const char* form = std::getenv("RADIANCE_MHC_FINISH"); - const bool old = form && !std::strcmp(form, "old"); - const bool warp_mix = split && (warp ? warp[0] == '1' : true) && - (old ? rows >= 32 : !(form && !std::strcmp(form, "scalar"))); - if (warp_mix && old) - return R4D_EMIT(stream, (mhc_pre_glm_warp_kernel), dim3((unsigned)rows), dim3(32), 0, - (const uint16_t*)h.data, (const float*)s.data, (const float*)b.data, - (uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps, - (long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], - in); - if (warp_mix) + * at one to six rows. */ + if (split) return R4D_EMIT(stream, (mhc_pre_glm_wide_kernel), dim3((unsigned)rows), dim3(256), 0, (const uint16_t*)h.data, (const float*)s.data, (const float*)b.data, (uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps, (long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], in); - if (old) - return R4D_EMIT(stream, (mhc_pre_kernel), dim3((unsigned)rows), dim3(256), 0, - (const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data, - (uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps, - (long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], - (long)c.stride[0], split ? chunks : 0, in); - return R4D_EMIT(stream, (mhc_pre_kernel), dim3((unsigned)rows), dim3(256), 0, + return R4D_EMIT(stream, mhc_pre_kernel, dim3((unsigned)rows), dim3(256), 0, (const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data, (uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps, - (long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], - split ? chunks : 0, in); + (long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0]); } bool coefficients(const RadArgs* a, long* iters, float* eps, float* heps) { *iters = r4d_geti_or(a, "iterations", 0); @@ -640,7 +546,7 @@ int pre_body(const RadArgs* a, RadStream stream) { if (rc < 0) return rc; } return emit_finish(stream, h, (const float*)fn.data, (long)fn.stride[0], s, b, x, p, c, n, hc, - (int)iters, eps, heps, rows, chunks, split, in); + (int)iters, eps, heps, rows, split, in); } int partial_body(const RadArgs* a, RadStream stream) { if (!a || a->n_t < 3) return RAD_E_INVAL; @@ -676,7 +582,7 @@ int finish_body(const RadArgs* a, RadStream stream) { return RAD_E_SHAPE; const Dense in{ (float*)part.data, (long)part.stride[0], kPartStride, 0 }; return emit_finish(stream, h, nullptr, 0, s, b, x, p, c, n, hc, (int)iters, eps, heps, rows, - chunks, true, in); + true, in); } int post_body(const RadArgs* a, RadStream stream) { if (!a || a->n_t < 5) return RAD_E_INVAL; @@ -689,12 +595,10 @@ int post_body(const RadArgs* a, RadStream stream) { !matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc) || !matrix(o, RAD_BF16, rows, hc * n) || o.data == h.data) return RAD_E_SHAPE; - /* RADIANCE_MHC_POST_VEC=0 keeps the per-output kernel, for the microbenchmark. */ - const char* vec = std::getenv("RADIANCE_MHC_POST_VEC"); const auto aligned = [](const RadTensor& t) { return ((uintptr_t)t.data & 15) == 0 && t.stride[0] % 8 == 0; }; - if ((!vec || vec[0] == '1') && hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o)) + if (hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o)) return R4D_EMIT(stream, mhc_post_vec_kernel, dim3((n / 8 + 255) / 256, (unsigned)rows), dim3(256), 0, (const uint16_t*)x.data, (const uint16_t*)h.data, (const float*)p.data, (const float*)c.data, (uint16_t*)o.data, n, diff --git a/libr4d/r4d_mla.hip b/libr4d/r4d_mla.hip index 710c1a35..58f93126 100644 --- a/libr4d/r4d_mla.hip +++ b/libr4d/r4d_mla.hip @@ -19,31 +19,11 @@ struct ProjectMeta { long xr, xh, wp, yr, yh; int rows, heads; }; -/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. */ -__global__ void project_absorb(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { - const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r = blockIdx.z; - if (col >= 512) return; - float sum = 0; - for (int j = 0; j < 256; ++j) - sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]), - bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]), sum); - y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum); -} -__global__ void project_expand(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { - const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, - r = blockIdx.z; - float sum = 0; - for (int j = lane; j < 512; j += 32) - sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]), - bf16_to_f32(w[((long)head * 512 + 256 + col) * m.wp + j]), sum); -#pragma unroll - for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32); - if (!lane) y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum); -} -/* project_absorb and project_expand with R rows a thread (absorb) or a wave (expand): each weight - * element is loaded once for R rows. Every row's sum runs over j in the same order, and - * r4d_xor_sum<32> exchanges as the shuffle loop does, so the bytes match the one-row kernels. - * A tail group past the last row reads that row again and stores nothing for it. */ +/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. R rows + * a thread (absorb) or a wave (expand): each weight element is loaded once for R rows. Every row's + * sum runs over j in the same order whatever R is (expand: each lane's share in ascending j, then + * r4d_xor_sum<32>), so a row's bytes do not depend on the batch it is in. A tail group past the + * last row reads that row again and stores nothing for it. */ template __global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { @@ -122,24 +102,11 @@ int project_body(const RadArgs* a, RadStream stream) { return RAD_E_SHAPE; const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0], y.stride[1], (int)x.shape[0], (int)h }; - /* RADIANCE_MLA_PROJECT: `old` the one-row kernels on shuffle sums, the reference the selftest - * holds the row forms to byte for byte; 1, 2, 4 or 8 pins the rows a thread (absorb) or a - * wave (expand). */ - const char* form = std::getenv("RADIANCE_MLA_PROJECT"); const auto* xp = (const uint16_t*)x.data; const auto* wp = (const uint16_t*)w.data; auto* yp = (uint16_t*)y.data; - if (form && !std::strcmp(form, "old")) { - if (absorb) - return R4D_EMIT(stream, project_absorb, dim3(4, h, m.rows), dim3(128), 0, xp, wp, yp, - m); - return R4D_EMIT(stream, project_expand, dim3(64, h, m.rows), dim3(128), 0, xp, wp, yp, m); - } - const long R = form && *form ? std::strtol(form, nullptr, 10) - : m.rows >= 8 ? 8 - : m.rows >= 4 ? 4 - : m.rows >= 2 ? 2 - : 1; + /* The largest of 8, 4, 2 and 1 rows a group that the batch fills. */ + const int R = m.rows >= 8 ? 8 : m.rows >= 4 ? 4 : m.rows >= 2 ? 2 : 1; #define MLA_PROJECT_ROWS(RR) \ do { \ const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \ @@ -639,10 +606,9 @@ int body(const RadArgs* a, RadStream stream) { // Vectors need every cache row on a sixteen-byte boundary. const bool wide = g_mla_matrix_form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) && !(kv.stride[2] % 8); - /* RADIANCE_MLA_PAIR=pos keeps the positional pairing, for comparison; the union's LDS lists - * hold a table of at most kUnionBlocks entries. */ - const char* pairing = std::getenv("RADIANCE_MLA_PAIR"); - const bool by_page = !(pairing && !std::strcmp(pairing, "pos")) && bt.shape[1] <= kUnionBlocks; + /* The union's LDS lists hold a table of at most kUnionBlocks entries; a wider table takes the + * positional pairing. */ + const bool by_page = bt.shape[1] <= kUnionBlocks; const bool stats = MATRIX && env_on("RADIANCE_MLA_CONFLICT_STATS"); Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2], bt.stride[0], bt.stride[1], len.stride[0], o.stride[0], diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index aa48c382..084a76e6 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -837,9 +837,11 @@ extern "C" int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld // y[m, i] = v over an [M, n] extent with a row pitch, for a rank with nothing to compute whose // downstream reader (an all-reduce, a residual) still needs a defined buffer. A memset cannot // handle the pitch or a two-byte value. -__global__ __launch_bounds__(kThreads) void fill_kernel(uint16_t* __restrict__ y, uint32_t n, - uint32_t y_ld, uint16_t v) { - uint16_t* __restrict__ yr = y + (size_t)blockIdx.x * y_ld; +// T is the element's bits: uint16_t for bf16, uint32_t for f32. +template +__global__ __launch_bounds__(kThreads) void fill_kernel(T* __restrict__ y, uint32_t n, + uint32_t y_ld, T v) { + T* __restrict__ yr = y + (size_t)blockIdx.x * y_ld; for (uint32_t i = threadIdx.x; i < n; i += kThreads) yr[i] = v; } @@ -854,8 +856,20 @@ extern "C" int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long s if (!y) return -1; if (M <= 0 || n <= 0) return -2; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(fill_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, - (uint16_t*)y, (uint32_t)n, (uint32_t)y_ld, f32_to_bf16_host(value)); + hipLaunchKernelGGL(fill_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + (hipStream_t)stream, (uint16_t*)y, (uint32_t)n, (uint32_t)y_ld, + f32_to_bf16_host(value)); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long stream) { + if (!y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!y_ld) y_ld = n; + uint32_t bits; + std::memcpy(&bits, &value, sizeof bits); + hipLaunchKernelGGL(fill_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + (hipStream_t)stream, (uint32_t*)y, (uint32_t)n, (uint32_t)y_ld, bits); return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -1306,8 +1320,10 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) { const RadTensor* x = r4d_opt(a, CS_X); const RadTensor* y = r4d_opt(a, CS_Y); if (!x || !y) return R4D_NO(RAD_E_INVAL); - R4D_NEED(dt_bf16(x)); - R4D_NEED(dt_bf16(y)); + /* A copy at the dtype both sides share: bf16, or f32 (a latent kept aside and put back). */ + if (x->dtype != y->dtype || (x->dtype != RAD_BF16 && x->dtype != RAD_F32)) + return R4D_NO(RAD_E_DTYPE); + const long long es = x->dtype == RAD_F32 ? 4 : 2; const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); @@ -1319,7 +1335,7 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) { * while the source holds the live rows, so the source need only have at least as many. */ if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE); - return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * 2, x_ld * 2, n * 2, M, + return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * es, x_ld * es, n * es, M, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; } @@ -1566,7 +1582,7 @@ extern "C" int r4d_rad_sigmoid(const RadArgs* a, RadStream s) { extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) { const RadTensor* y = r4d_opt(a, 0); if (!y) return R4D_NO(RAD_E_INVAL); - R4D_NEED(dt_bf16(y)); + if (y->dtype != RAD_BF16 && y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); if (n <= 0) return R4D_NO(RAD_E_SHAPE); long long M = 0; @@ -1574,8 +1590,9 @@ extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) { if (y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0) return R4D_NO(RAD_E_SHAPE); const double v = r4d_getf(a, "value", 0.0); - return r4d_fill_bf16(r4d_addr(y), (int)M, (int)n, (int)y_ld, (float)v, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + const int e = (y->dtype == RAD_F32 ? r4d_fill_f32 : r4d_fill_bf16)( + r4d_addr(y), (int)M, (int)n, (int)y_ld, (float)v, (long)(uintptr_t)s); + return e == 0 ? RAD_OK : RAD_E_DEVICE; } /* ------------------------------------------------------------------ logit_softcap */ diff --git a/libr4d/r4d_moe_mxfp4.hip b/libr4d/r4d_moe_mxfp4.hip index ad22b3b5..4217fd53 100644 --- a/libr4d/r4d_moe_mxfp4.hip +++ b/libr4d/r4d_moe_mxfp4.hip @@ -10,14 +10,14 @@ #include "r4d_mxfp4.h" #include #include -#include +#include namespace { struct MxMeta { long wstep[2], sstep[2]; int wrow[2], srow[2], n[2], k[2]; long ar, asr, yr; - int T, Arows, N, K, experts, topk, sorted_a, tile, parts, aligned_jobs; + int T, Arows, N, K, experts, topk, sorted_a, parts; int stage_out, out16; }; __device__ const uint8_t* entry(const void* base, long step, int e) { @@ -26,96 +26,43 @@ __device__ const uint8_t* entry(const void* base, long step, int e) { /* E2M1 values are exactly representable in E4M3. Stage those codes directly, * use FP8 WMMA, and fold each 32-wide E8M0 scale into the F32 accumulator. * No persistent expansion or checkpoint relayout is needed. */ -// Four independent bytes: magnitudes >=2 map to (m+12)*4; 0/1 map to 0/48. -// Expand each magnitude-test bit into a byte mask without cross-byte carries. -__device__ __forceinline__ uint32_t fp4x4(uint32_t n) { - const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u; - const uint32_t mask = (flag << 5) - (flag >> 3); - return ((((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) | - ((n & 0x08080808u) << 4)); -} -/* Eight codes of a packed word to their E4M3 bytes in k order. The table form (r4d_mxfp4.h, v_perm - * on the magnitude) gives the same bytes in about a third of the instructions; the arithmetic form - * stays reachable (RADIANCE_MXFP4_LUT=0) as the bytewise reference. */ -template +/* Eight codes of a packed word to their E4M3 bytes in k order, by table (r4d_mxfp4.h, v_perm on + * the magnitude): the bytes of the bytewise arithmetic decode in about a third of the + * instructions. */ __device__ __forceinline__ uint2 mx_codes8(uint32_t packed) { - if constexpr (Lut) { - uint32_t lo, hi; - r4d_mxfp4_unpack8_exact(packed, &lo, &hi); - return uint2{ lo, hi }; - } else { - const uint32_t low = fp4x4(packed & 0x0f0f0f0fu), high = fp4x4((packed >> 4) & 0x0f0f0f0fu); - return uint2{ __byte_perm(low, high, 0x5140), __byte_perm(low, high, 0x7362) }; - } + uint32_t lo, hi; + r4d_mxfp4_unpack8_exact(packed, &lo, &hi); + return uint2{ lo, hi }; } -template +/* The row-group form: a one-wave block per (16 columns, 16 sorted rows), the rows split at each + * expert boundary. */ __global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { - __shared__ __align__(16) uint8_t aa[16 * RowTiles * 136], bb[16 * ColTiles * 136]; - const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, - col0 = blockIdx.x * (16 * ColTiles); - constexpr int JobRows = 16 * RowTiles, Threads = 32 * ColTiles * RowTiles; - const int wave_col = ColTiles == 1 ? 0 : wave % ColTiles, - wave_row = RowTiles == 1 ? 0 : wave / ColTiles; - int first = blockIdx.y * m.tile; - int group_end = min((int)(blockIdx.y + 1) * m.tile, m.T), job_expert = 0; - if (m.aligned_jobs) { - // Expert e begins at job floor(offset[e]/JobRows)+e. The extra job per expert - // bounds padding without a prefix-sum pass; every live job owns one row tile - // of one expert, so hot experts still spread across independent CTAs. - const int job = blockIdx.y, tail = offset[m.experts] / JobRows + m.experts; - if (job >= tail) { - const int r0 = offset[m.experts] + (job - tail) * JobRows; - for (int r = r0; r < min(r0 + JobRows, m.T); ++r) - if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)r * m.yr + col0 + tid] = 0; - return; + __shared__ __align__(16) uint8_t aa[16 * 136], bb[16 * 136]; + const int tid = threadIdx.x, lane = tid & 31, col0 = blockIdx.x * 16; + const int first = blockIdx.y * 16, group_end = min((int)(blockIdx.y + 1) * 16, m.T); + for (int start = first; start < group_end;) { + if (sorted[start] < 0 || offset[m.experts] <= start) { + if (tid < 16 && col0 + tid < m.N) y[(long)start * m.yr + col0 + tid] = 0; + ++start; + continue; } int lo = 0, hi = m.experts; while (lo + 1 < hi) { const int mid = (lo + hi) / 2; - if (offset[mid] / JobRows + mid <= job) + if (offset[mid] <= start) lo = mid; else hi = mid; } - job_expert = lo; - first = offset[lo] + (job - (offset[lo] / JobRows + lo)) * JobRows; - group_end = min(first + JobRows, offset[lo + 1]); - } - for (int start = first; start < group_end;) { - if (sorted[start] < 0 || offset[m.experts] <= start) { - if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)start * m.yr + col0 + tid] = 0; - ++start; - continue; - } - int lo = m.aligned_jobs ? job_expert : 0, hi = m.experts; - if (!m.aligned_jobs) - while (lo + 1 < hi) { - const int mid = (lo + hi) / 2; - if (offset[mid] <= start) - lo = mid; - else - hi = mid; - } const int cls = lo & 1, end = min(group_end, offset[lo + 1]); if (end <= start) return; const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2); const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2); auto total = r4d_fp8::acc_zero(); - // Routing is invariant across K; each activation scale covers all four groups. - int sources[8]; - if constexpr (CachedRows) { -#pragma unroll - for (int row = 0; row < 8; ++row) { - const int r = start + wave_row * 16 + (lane >> 4) * 8 + row; - const int flat = r < end ? sorted[r] : -1; - const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; - sources[row] = ar >= 0 && ar < m.Arows ? ar : -1; - } - } for (int kb = 0; kb < m.k[cls]; kb += 128) { - for (int j = tid; j < 16 * RowTiles * 16; j += Threads) { + for (int j = tid; j < 16 * 16; j += 32) { const int r = j / 16, d = (j % 16) * 8; const int ar = start + r < end && sorted[start + r] >= 0 ? (m.sorted_a ? start + r : sorted[start + r] / m.topk) @@ -124,56 +71,40 @@ __global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const vo if (ar >= 0 && ar < m.Arows) __builtin_memcpy(&av, a + (long)ar * m.ar + kb + d, 8); *reinterpret_cast(aa + r * 136 + d) = av; } - for (int j = tid; j < 16 * ColTiles * 16; j += Threads) { + for (int j = tid; j < 16 * 16; j += 32) { const int r = j / 16, d = (j % 16) * 8; const int n = col0 + r, part = n / (m.N / m.parts), within = n % (m.N / m.parts); const int wn = part * (m.n[cls] / m.parts) + within; uint32_t packed = 0; if (n < m.N && within < m.n[cls] / m.parts) __builtin_memcpy(&packed, w + (long)wn * m.wrow[cls] + (kb + d) / 2, 4); - *reinterpret_cast(bb + r * 136 + d) = mx_codes8(packed); + *reinterpret_cast(bb + r * 136 + d) = mx_codes8(packed); } __syncthreads(); - if (start + wave_row * 16 < end) { - const int n = col0 + wave_col * 16 + (lane & 15), part = n / (m.N / m.parts), - within = n % (m.N / m.parts); - const int wn = part * (m.n[cls] / m.parts) + within; - const bool valid = n < m.N && within < m.n[cls] / m.parts; - float activation[8]; - if constexpr (CachedRows) { + const int n = col0 + (lane & 15), part = n / (m.N / m.parts), + within = n % (m.N / m.parts); + const int wn = part * (m.n[cls] / m.parts) + within; + const bool valid = n < m.N && within < m.n[cls] / m.parts; #pragma unroll - for (int row = 0; row < 8; ++row) - activation[row] = - sources[row] >= 0 ? as[(long)sources[row] * m.asr + kb / 128] : 0; - } + for (int group = 0; group < 4; ++group) { + const int exp = valid ? ws[(long)wn * m.srow[cls] + kb / 32 + group] : 127; + auto raw = r4d_fp8::acc_zero(); #pragma unroll - for (int group = 0; group < 4; ++group) { - const int exp = valid ? ws[(long)wn * m.srow[cls] + kb / 32 + group] : 127; - auto raw = r4d_fp8::acc_zero(); + for (int k = group * 32; k < (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, 0, k, lane), + r4d_fp8::frag<128>(bb, 0, k, lane), raw); + // E8M0 maps directly to the F32 exponent field; code zero is 2^-127, + // a representable subnormal, and code 255 is NaN. + const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? ((uint32_t)exp << 23) + : 0x00400000u); #pragma unroll - for (int k = group * 32; k < (group + 1) * 32; k += 16) - raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, wave_row * 16, k, lane), - r4d_fp8::frag<128>(bb, wave_col * 16, k, lane), raw); - // E8M0 maps directly to the F32 exponent field; code zero is 2^-127, - // a representable subnormal, and code 255 is NaN. - const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u - : exp ? ((uint32_t)exp << 23) - : 0x00400000u); -#pragma unroll - for (int row = 0; row < 8; ++row) { - if constexpr (CachedRows) { - if (sources[row] >= 0) total[row] += raw[row] * activation[row] * scale; - } else { - const int r = start + wave_row * 16 + (lane >> 4) * 8 + row; - if (r < end) { - const int ar = sorted[r] < 0 ? -1 - : m.sorted_a ? r - : sorted[r] / m.topk; - if (ar >= 0 && ar < m.Arows) - total[row] += - raw[row] * as[(long)ar * m.asr + kb / 128] * scale; - } - } + for (int row = 0; row < 8; ++row) { + const int r = start + (lane >> 4) * 8 + row; + if (r < end) { + const int ar = sorted[r] < 0 ? -1 : m.sorted_a ? r : sorted[r] / m.topk; + if (ar >= 0 && ar < m.Arows) + total[row] += raw[row] * as[(long)ar * m.asr + kb / 128] * scale; } } } @@ -181,8 +112,7 @@ __global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const vo } #pragma unroll for (int row = 0; row < 8; ++row) { - const int r = start + wave_row * 16 + (lane >> 4) * 8 + row, - n = col0 + wave_col * 16 + (lane & 15); + const int r = start + (lane >> 4) * 8 + row, n = col0 + (lane & 15); if (r < end && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]); } start = end; @@ -201,18 +131,20 @@ __device__ __forceinline__ r4d_u32x4 mx_ldg16(const uint8_t* p) { __device__ __forceinline__ uint32_t mx_ldg4(const uint8_t* p) { return *(const __attribute__((address_space(1))) mx_g4*)p; } -/* The TP8 prefill form (M32N64, aligned jobs, cached rows) with its loads a stage ahead. A job's - * row table resolves into LDS once; the next 128 of K (activation bytes, weight codes, an exponent - * dword a column, the activation scales) is loaded into registers while the current stage computes - * from LDS. The form above waits on three dependent latencies a stage: the routing entry, the - * activation row it names, and the exponent bytes it reads after the barrier. A job begins at its - * first row even when that slot is dropped; rows are independent, so the bytes are the same. +/* The GLM prefill form: jobs of 32 rows of one expert by 64 columns, eight waves, with its loads a + * stage ahead. Expert e begins at job floor(offset[e]/32)+e: the extra job per expert bounds the + * padding without a prefix-sum pass, and every live job owns one row tile of one expert, so hot + * experts still spread across independent blocks. A job's row table resolves into LDS once; the + * next 128 of K (activation bytes, weight codes, an exponent dword a column, the activation + * scales) is loaded into registers while the current stage computes from LDS, where a form that + * loads after the barrier waits on three dependent latencies a stage: the routing entry, the + * activation row it names, and the exponent bytes. A job begins at its first row even when that + * slot is dropped; rows are independent, so the bytes are the same. * The exponents are decoded once, at staging; the fold carries no row predicate, the epilogue * writes a dropped row's zero instead. * One stage ahead only: a deeper prefetch measured slower on the expert-major forms. The barriers * order LDS only (lds_barrier), so the prefetch stays in flight across them and L0 keeps the * activation rows the next column block reads. */ -template __global__ __launch_bounds__(256) R4D_WAVES(16) void moe_mxfp4_prefill_kernel(const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, const void* s1, @@ -285,7 +217,7 @@ __global__ __launch_bounds__(256) *reinterpret_cast(aa + arow * P + ad) = ra; #pragma unroll for (int t = 0; t < 4; ++t) - *reinterpret_cast(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8(rw[t]); + *reinterpret_cast(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8(rw[t]); if (tid < BN) { // E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable // subnormal, and code 255 is NaN. @@ -351,13 +283,8 @@ __global__ __launch_bounds__(256) * fresh WMMA pair from zero, folded as (raw * activation scale) * E8M0 scale and added, two * roundings and an add (the unit is built -ffp-contract=off). The tiles of a wave are separate * accumulators, so no element sees another order. `stage_out` writes the output through LDS in - * 16-byte rows instead of a lane's 2-byte column stores. - * - * DB (streamed A only): two LDS stages, one barrier a stage. The next stage is stored into the - * other buffer after the current one computes, which every wave last read before the previous - * barrier; the single-buffer order needs a second barrier before it may overwrite the stage it - * computes from. Same bytes in LDS, same per-element sequence. */ -template + * 16-byte rows instead of a lane's 2-byte column stores. */ +template struct MxP64 { static constexpr int Threads = 256, WR = BM / 16, WC = 8 / WR, TC = BN / (16 * WC), KB = StageK / 128; @@ -366,28 +293,27 @@ struct MxP64 { static constexpr int TPA = Threads / BM, ACh = StageK / 16 / TPA, RCh = KR / 16 / TPA; static constexpr int TPW = Threads / BN, WCh = StageK / 32 / TPW, SAK = Resident ? KR / 128 : KB; - static constexpr int NB = DB ? 2 : 1, BB = NB * BN * PB > BM *PO ? NB * BN * PB : BM * PO; - static constexpr int Lds = NB * (BM * PA + 16 * KB * BN + 4 * SAK * BM) + BB + 4 * BM; + static constexpr int BB = BN * PB > BM * PO ? BN * PB : BM * PO; + static constexpr int Lds = BM * PA + 16 * KB * BN + 4 * SAK * BM + BB + 4 * BM; // The waves a SIMD the LDS admits (128 KiB a WGP, a block's eight waves over four SIMDs): // stating it keeps the compiler from trading the stage registers for waves it cannot get. static constexpr int Waves = 2 * (131072 / Lds > 8 ? 8 : 131072 / Lds); }; -template +template __global__ __launch_bounds__(256) - R4D_WAVES((MxP64::Waves)) void moe_mxfp4_p64_kernel( + R4D_WAVES((MxP64::Waves)) void moe_mxfp4_p64_kernel( const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { - using G = MxP64; + using G = MxP64; constexpr int Threads = G::Threads, WC = G::WC, TC = G::TC, KB = G::KB, AK = G::AK, PA = G::PA, PB = G::PB; constexpr int PO = G::PO, TPA = G::TPA, TPW = G::TPW, SAK = G::SAK; static_assert(BM % 16 == 0 && 8 % G::WR == 0 && TC >= 1 && TC * 16 * WC == BN && (Resident || CT == 1) && G::ACh >= 1 && G::WCh >= 1 && BN * KB <= Threads && - BM * SAK <= Threads && !(DB && Resident) && G::Lds <= 65536, + BM * SAK <= Threads && G::Lds <= 65536, "stage chunks must divide evenly over the block, in 64 KiB of LDS"); - constexpr int NB = G::NB; - __shared__ __align__(16) uint8_t aa[NB * BM * PA], bb[G::BB]; - __shared__ __align__(16) float ss[NB * 4 * KB * BN], sa[NB * SAK * BM]; + __shared__ __align__(16) uint8_t aa[BM * PA], bb[G::BB]; + __shared__ __align__(16) float ss[4 * KB * BN], sa[SAK * BM]; __shared__ int src[BM]; const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, wave_row = wave / WC, wave_col = wave % WC; @@ -479,20 +405,19 @@ __global__ __launch_bounds__(256) re = 0x7f7f7f7fu; if (evalid && k0 + ekb * 128 < kc) re = mx_ldg4(ep + (k0 + ekb * 128) / 32); }; - auto store = [&](int b) { + auto store = [&]() { if constexpr (!Resident) { #pragma unroll for (int i = 0; i < G::ACh; ++i) - *reinterpret_cast(aa + b * BM * PA + arow * PA + (a0 + i * TPA) * 16) = - ra[i]; - if (tid < BM * KB) sa[b * SAK * BM + tid] = rsa; + *reinterpret_cast(aa + arow * PA + (a0 + i * TPA) * 16) = ra[i]; + if (tid < BM * KB) sa[tid] = rsa; } #pragma unroll for (int i = 0; i < G::WCh; ++i) { #pragma unroll for (int t = 0; t < 4; ++t) - *reinterpret_cast(bb + b * BN * PB + wcol * PB + (w0c + i * TPW) * 32 + - 8 * t) = mx_codes8(rw[i][t]); + *reinterpret_cast(bb + wcol * PB + (w0c + i * TPW) * 32 + 8 * t) = + mx_codes8(rw[i][t]); } if (tid < BN * KB) { // E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable @@ -500,7 +425,7 @@ __global__ __launch_bounds__(256) #pragma unroll for (int g = 0; g < 4; ++g) { const uint32_t exp = (re >> (8 * g)) & 0xffu; - ss[b * 4 * KB * BN + (ekb * 4 + g) * BN + ecol] = + ss[(ekb * 4 + g) * BN + ecol] = __uint_as_float(exp == 255 ? 0x7fc00000u : exp ? (exp << 23) : 0x00400000u); @@ -510,32 +435,30 @@ __global__ __launch_bounds__(256) r4d_fp8::f8v total[TC]; #pragma unroll for (int t = 0; t < TC; ++t) total[t] = r4d_fp8::acc_zero(); - auto compute = [&](int s, int b) { + auto compute = [&](int s) { const int k0 = (s % ksn) * StageK; - const uint8_t *ab = aa + b * BM * PA, *bp = bb + b * BN * PB; - const float* sp = ss + b * 4 * KB * BN; #pragma unroll for (int kb = 0; kb < KB; ++kb) { if (k0 + kb * 128 >= kc) break; - const float* sar = sa + b * SAK * BM + (Resident ? k0 / 128 + kb : kb) * BM + rowbase; + const float* sar = sa + (Resident ? k0 / 128 + kb : kb) * BM + rowbase; float activation[8]; #pragma unroll for (int row = 0; row < 8; ++row) activation[row] = sar[row]; const int ka = (Resident ? k0 : 0) + kb * 128; #pragma unroll for (int group = 0; group < 4; ++group) { - const auto fa0 = r4d_fp8::frag(ab, wave_row * 16, ka + group * 32, lane); - const auto fa1 = r4d_fp8::frag(ab, wave_row * 16, ka + group * 32 + 16, lane); + const auto fa0 = r4d_fp8::frag(aa, wave_row * 16, ka + group * 32, lane); + const auto fa1 = r4d_fp8::frag(aa, wave_row * 16, ka + group * 32 + 16, lane); #pragma unroll for (int t = 0; t < TC; ++t) { auto raw = r4d_fp8::mma( - fa0, r4d_fp8::frag(bp, colw + t * 16, kb * 128 + group * 32, lane), + fa0, r4d_fp8::frag(bb, colw + t * 16, kb * 128 + group * 32, lane), r4d_fp8::acc_zero()); raw = r4d_fp8::mma( fa1, - r4d_fp8::frag(bp, colw + t * 16, kb * 128 + group * 32 + 16, lane), + r4d_fp8::frag(bb, colw + t * 16, kb * 128 + group * 32 + 16, lane), raw); - const float scale = sp[(kb * 4 + group) * BN + colw + t * 16 + (lane & 15)]; + const float scale = ss[(kb * 4 + group) * BN + colw + t * 16 + (lane & 15)]; // A dropped row folds zeros (or NaN under a code-255 scale) and is written as 0. #pragma unroll for (int row = 0; row < 8; ++row) @@ -586,21 +509,11 @@ __global__ __launch_bounds__(256) } }; load(0); - if constexpr (DB) { - store(0); - lds_barrier(); - } for (int s = 0; s < S; ++s) { - if constexpr (DB) { - if (s + 1 < S) load(s + 1); - if (live) compute(s, s & 1); - if (s + 1 < S) store((s + 1) & 1); - } else { - store(0); - lds_barrier(); - if (s + 1 < S) load(s + 1); - if (live) compute(s, 0); - } + store(); + lds_barrier(); + if (s + 1 < S) load(s + 1); + if (live) compute(s); lds_barrier(); if (s % ksn == ksn - 1) { epilogue(colb + (s / ksn) * BN); @@ -620,7 +533,7 @@ __global__ __launch_bounds__(256) * A stage of StageK of K is loaded into registers while the previous one computes from LDS; at * gate_up's K of 4096 the 256 stage measured fastest. Block row `experts` zeroes the dropped rows * past offset[experts]. */ -template +template __global__ __launch_bounds__(32 * Waves) void moe_mxfp4_expert_kernel( const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { @@ -715,7 +628,7 @@ __global__ __launch_bounds__(32 * Waves) void moe_mxfp4_expert_kernel( const uint32_t q[4] = { rw[i].x, rw[i].y, rw[i].z, rw[i].w }; #pragma unroll for (int t = 0; t < 4; ++t) - *reinterpret_cast(bb + c * P + 2 * d + 8 * t) = mx_codes8(q[t]); + *reinterpret_cast(bb + c * P + 2 * d + 8 * t) = mx_codes8(q[t]); } #pragma unroll for (int i = 0; i < SChunks; ++i) { @@ -777,7 +690,7 @@ struct MxStage { uint32_t s[SChunks]; float sa; }; -template +template __global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel( const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { @@ -870,8 +783,7 @@ __global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel( d = (j % (StageK / 32)) * 16; #pragma unroll for (int t = 0; t < 4; ++t) - *reinterpret_cast(bb + c * P + 2 * d + 8 * t) = - mx_codes8(R.w[i][t]); + *reinterpret_cast(bb + c * P + 2 * d + 8 * t) = mx_codes8(R.w[i][t]); } #pragma unroll for (int i = 0; i < St::SChunks; ++i) { @@ -993,78 +905,24 @@ int body(const RadArgs* a, RadStream stream) { m.ar = aq->stride[0]; m.asr = as->stride[0]; m.yr = y->stride[0]; - m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16; // Validated GLM projections at TP4 and TP8: retain the small/decode path and other models. const bool glm_prefill = ne == 288 && top == 8 && nn[0] == nn[1] && kk[0] == kk[1] && ((parts == 2 && (nn[0] == 1024 || nn[0] == 512) && kk[0] == 4096) || (parts == 1 && nn[0] == 4096 && (kk[0] == 512 || kk[0] == 256))); - auto enabled = [&](const char* name) { - const char* v = std::getenv(name); - return v ? v[0] == '1' : glm_prefill; - }; - /* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted - * rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form - * overtakes it, down up to 6143 rows (at 8192 the pipelined prefill form reads the slice - * 2.2 times less often and wins by a quarter). Other shapes keep the decode band. The environment - * moves the bounds, forces either side (RADIANCE_MXFP4_DECODE_EXPERTS 0 or 1) and pins stage - * and tiles, for the microbenchmark. */ - const char* lut_env = std::getenv("RADIANCE_MXFP4_LUT"); - const bool lut = lut_env ? lut_env[0] == '1' : true; - auto env_long = [](const char* name, long dflt) { - const char* v = std::getenv(name); - return v && *v ? std::strtol(v, nullptr, 10) : dflt; - }; - const long max_t = - env_long(m.sorted_a ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN" - : "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP", - glm_prefill && (nn[0] == 512 || kk[0] == 256) ? (m.sorted_a ? 6143 : 768) : 511); - const char* experts_env = std::getenv("RADIANCE_MXFP4_DECODE_EXPERTS"); + const bool tp8 = glm_prefill && (nn[0] == 512 || kk[0] == 256); /* The P64 form from a routed-row bound per projection, ahead of the expert-major band (its * down bound overlaps it): gate_up from 769 rows, where the prefill forms begin, down from - * 20 rows an expert at GLM's 288. Default at GLM's TP8 slices only, the measured ones - * (RADIANCE_MXFP4_PREFILL_P64=0 keeps the TP8 prefill form of stage 1, which also takes a grid - * P64 cannot address). The - * tile follows the rows an expert, measured at the TP8 slices (perfmx, cold): down BM32 BN64 - * K128 over four column tiles up to 3072 tokens (2048: 647 against 831 us), above BM64 BN128 - * K128 x4 with the LDS output (4096: 1101 against 1607); gate_up BM32 BN64 K256 up to 1536 - * tokens (768: 563 against 660), BM64 BN64 K256 up to 3072 (2048: 941 against 995), above - * BM64 BN128 K128 with the LDS output (4096: 1715 against 1915). BM, BN, stage, column tiles, - * the LDS output, the double buffer and the three row bounds move with the environment, and a - * forced expert-major form (DECODE_EXPERTS=1) keeps precedence. */ - const char* p64_env = std::getenv("RADIANCE_MXFP4_PREFILL_P64"); - const bool resident = m.K <= 256; - long dbm = 32, dbn = 64, dsk = 128, dout = 0; - if (resident) { - if (m.T >= env_long("RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", 24576)) { - dbm = 64; - dbn = 128; - dout = 1; - } - } else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BM64", 12288)) - dsk = 256; - else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BN128", 24576)) { - dbm = 64; - dsk = 256; - } else { - dbm = 64; - dbn = 128; - dout = 1; - } - const long bm = env_long("RADIANCE_MXFP4_PREFILL_P64_BM", dbm) == 32 ? 32 : 64; - const bool tp8 = glm_prefill && (nn[0] == 512 || kk[0] == 256); - if ((p64_env ? p64_env[0] == '1' : tp8) && !(experts_env && experts_env[0] == '1') && - m.T >= env_long(m.sorted_a ? "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN" - : "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - m.sorted_a ? 5760 : 769) && - (m.T + bm - 1) / bm + m.experts <= 65535) { - const long bn = env_long("RADIANCE_MXFP4_PREFILL_P64_BN", dbn) == 64 ? 64 : 128; - const long sk = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", dsk) == 256 ? 256 : 128; - const long ct = resident && env_long("RADIANCE_MXFP4_PREFILL_P64_COLTILES", 4) != 1 ? 4 : 1; - m.stage_out = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", dout) == 1; - // The double buffer exists where two stages fit in 64 KiB of LDS: every 128 stage, and - // the 256 stage at BM32 BN64. - const bool db = !resident && env_long("RADIANCE_MXFP4_PREFILL_P64_DB", 0) == 1 && - (sk == 128 || (bm == 32 && bn == 64)); + * 20 rows an expert at GLM's 288. At GLM's TP8 slices only, the measured ones; a grid P64 + * cannot address takes the forms below. The tile follows the rows an expert, measured at the + * TP8 slices (perfmx, cold): down BM32 BN64 K128 over four column tiles up to 3072 tokens + * (2048: 647 against 831 us), above BM64 BN128 K128 x4 with the LDS output (4096: 1101 + * against 1607); gate_up BM32 BN64 K256 up to 1536 tokens (768: 563 against 660), BM64 BN64 + * K256 up to 3072 (2048: 941 against 995), above BM64 BN128 K128 with the LDS output (4096: + * 1715 against 1915). */ + const bool resident = m.K <= 256, wide = m.T >= 24576; + const long bm = wide || (!resident && m.T >= 12288) ? 64 : 32; + if (tp8 && m.T >= (m.sorted_a ? 5760 : 769) && (m.T + bm - 1) / bm + m.experts <= 65535) { + m.stage_out = wide; m.out16 = (reinterpret_cast(y->data) & 15) == 0 && m.yr % 8 == 0; const long jobs = (m.T + bm - 1) / bm + m.experts; #define MX_P64(BM, BN, SK, CT, R) \ @@ -1072,85 +930,40 @@ int body(const RadArgs* a, RadStream stream) { dim3(((long)m.N + BN * CT - 1) / (BN * CT), jobs), dim3(256), 0, \ (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \ s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) -#define MX_P64D(BM, BN, SK) \ - R4D_EMIT(stream, (moe_mxfp4_p64_kernel), \ - dim3(((long)m.N + BN - 1) / BN, jobs), dim3(256), 0, (const uint8_t*)aq->data, \ - (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, s[1]->data, \ - (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) - if (db) { - if (sk == 256) return MX_P64D(32, 64, 256); - if (bm == 32) return bn == 64 ? MX_P64D(32, 64, 128) : MX_P64D(32, 128, 128); - return bn == 64 ? MX_P64D(64, 64, 128) : MX_P64D(64, 128, 128); - } -#undef MX_P64D -#define MX_P64_SK(BM, BN, CT, R) \ - return sk == 256 ? MX_P64(BM, BN, 256, CT, R) : MX_P64(BM, BN, 128, CT, R); -#define MX_P64_BN(BM, CT, R) \ - if (bn == 64) { MX_P64_SK(BM, 64, CT, R) } \ - MX_P64_SK(BM, 128, CT, R) -#define MX_P64_BM(CT, R) \ - if (bm == 32) { MX_P64_BN(32, CT, R) } \ - MX_P64_BN(64, CT, R) - if (!resident) { MX_P64_BM(1, false) } - if (ct == 1) { MX_P64_BM(1, true) } - MX_P64_BM(4, true) -#undef MX_P64_BM -#undef MX_P64_BN -#undef MX_P64_SK + if (resident) return wide ? MX_P64(64, 128, 128, 4, true) : MX_P64(32, 64, 128, 4, true); + if (wide) return MX_P64(64, 128, 128, 1, false); + return bm == 64 ? MX_P64(64, 64, 256, 1, false) : MX_P64(32, 64, 256, 1, false); #undef MX_P64 } - if (experts_env ? experts_env[0] == '1' : max_t < 0 || m.T <= max_t) { - const long stage = env_long("RADIANCE_MXFP4_EXPERTS_STAGE_K", m.K <= 256 ? 128 : 256); - const long tiles = env_long("RADIANCE_MXFP4_EXPERTS_COLTILES", m.K <= 256 ? 4 : 1); + /* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted + * rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form + * overtakes it, down up to 6143 rows (at 8192 the pipelined prefill form reads the slice + * 2.2 times less often and wins by a quarter). Other shapes keep the decode band. A K of 256 + * takes 128 stages over four column tiles, a longer K the 256 stage over one. */ + if (m.T <= (tp8 ? (m.sorted_a ? 6143 : 768) : 511)) { #define MX_EXPERTS(KERNEL, C) \ R4D_EMIT(stream, KERNEL, dim3(((long)m.N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), \ 0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \ w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \ (uint16_t*)y->data, m) -#define MX_EXPERTS_LUT(L) \ - if (stage == 128) \ - return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 4, L>), 4) \ - : MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 1, L>), 1); \ - return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<256, 4, L>), 4) \ - : MX_EXPERTS((moe_mxfp4_expert_kernel<4, 256, L>), 1); - if (lut) { MX_EXPERTS_LUT(true) } - MX_EXPERTS_LUT(false) -#undef MX_EXPERTS_LUT + if (m.K <= 256) return MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 4>), 4); + return MX_EXPERTS((moe_mxfp4_expert_kernel<4, 256>), 1); #undef MX_EXPERTS } - m.aligned_jobs = enabled("RADIANCE_MXFP4_ALIGNED_JOBS") && m.T >= 512; - const bool wide = enabled("RADIANCE_MXFP4_PREFILL_N32") && m.T >= 512; - const bool tall = wide && m.aligned_jobs && enabled("RADIANCE_MXFP4_PREFILL_M32"); - const int job_rows = tall ? 32 : 16; - const int jobs = - m.aligned_jobs ? (m.T + job_rows - 1) / job_rows + m.experts : (m.T + m.tile - 1) / m.tile; + /* From 512 routed rows (past the expert-major band) the GLM prefill form at GLM's slices, in + * jobs of 32 rows of one expert; elsewhere the row groups, 16 sorted rows a block. */ + const bool pipe = glm_prefill && m.T >= 512; + const int jobs = pipe ? (m.T + 31) / 32 + m.experts : (m.T + 15) / 16; if (jobs > 65535) return RAD_E_SHAPE; -#define MX_EMIT(CT, RT, CACHE, L) \ - R4D_EMIT(stream, (moe_mxfp4_fp8_kernel), \ - dim3(((long)m.N + 16 * CT - 1) / (16 * CT), jobs), dim3(32 * CT * RT), 0, \ - (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \ - s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) -#define MX_PIPE(L) \ - R4D_EMIT(stream, (moe_mxfp4_prefill_kernel), dim3(((long)m.N + 63) / 64, jobs), dim3(256), \ - 0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \ - w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \ - (uint16_t*)y->data, m) - const char* cached = std::getenv("RADIANCE_MXFP4_PREFILL_CACHE_ROWS"); - const bool pipe = enabled("RADIANCE_MXFP4_PREFILL_PIPE"); -#define MX_EMIT_LUT(L) \ - if (tall && enabled("RADIANCE_MXFP4_PREFILL_N64")) { \ - if (cached ? cached[0] == '1' : glm_prefill) \ - return pipe ? MX_PIPE(L) : MX_EMIT(4, 2, true, L); \ - return MX_EMIT(4, 2, false, L); \ - } \ - if (tall) return MX_EMIT(2, 2, false, L); \ - if (wide) return MX_EMIT(2, 1, false, L); \ - return MX_EMIT(1, 1, false, L); - if (lut) { MX_EMIT_LUT(true) } - MX_EMIT_LUT(false) -#undef MX_EMIT_LUT -#undef MX_PIPE -#undef MX_EMIT + if (pipe) + return R4D_EMIT(stream, moe_mxfp4_prefill_kernel, dim3(((long)m.N + 63) / 64, jobs), + dim3(256), 0, (const uint8_t*)aq->data, (const float*)as->data, + w[0]->data, s[0]->data, w[1]->data, s[1]->data, (const int*)sorted->data, + (const int*)off->data, (uint16_t*)y->data, m); + return R4D_EMIT(stream, moe_mxfp4_fp8_kernel, dim3(((long)m.N + 15) / 16, jobs), dim3(32), 0, + (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, + w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, + (uint16_t*)y->data, m); } } extern "C" int r4d_rad_moe_mxfp4(const RadArgs* a, RadStream stream) { return body(a, stream); } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 7db0f3a9..6b74b26f 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -164,6 +164,10 @@ int r4d_rad_seg_sinusoid (const RadArgs*, RadStream); * (an image decoder's mid block). */ int r4d_rad_attn_prefix_self (const RadArgs*, RadStream); int r4d_rad_attn_dense_h128 (const RadArgs*, RadStream); +int r4d_rad_attn_cross (const RadArgs*, RadStream); +int r4d_rad_table_add (const RadArgs*, RadStream); +int r4d_rad_mix_rows (const RadArgs*, RadStream); +int r4d_rad_chan_stats (const RadArgs*, RadStream); int r4d_rad_attn_dense_wide (const RadArgs*, RadStream); /* The image generator's other ops (r4d_gen.hip). */ int r4d_rad_ln_mod (const RadArgs*, RadStream); @@ -204,6 +208,7 @@ int r4d_rad_interleave2 (const RadArgs*, RadStream); int r4d_rad_attn_dense_small_h256 (const RadArgs*, RadStream); int r4d_rad_iota (const RadArgs*, RadStream); int r4d_rad_cu_repeat (const RadArgs*, RadStream); +int r4d_rad_int_affine (const RadArgs*, RadStream); /* r4d_video.hip */ int r4d_rad_rms_mod (const RadArgs*, RadStream); int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream); @@ -221,6 +226,21 @@ int r4d_rad_tconv_dw (const RadArgs*, RadStream); int r4d_rad_resize_bilinear (const RadArgs*, RadStream); int r4d_rad_patch_fold (const RadArgs*, RadStream); int r4d_rad_flow_renoise (const RadArgs*, RadStream); +int r4d_rad_rope_split (const RadArgs*, RadStream); +int r4d_rad_head_gate (const RadArgs*, RadStream); +int r4d_rad_ltx_guide (const RadArgs*, RadStream); +int r4d_rad_pixel_norm (const RadArgs*, RadStream); +int r4d_rad_d2s3d (const RadArgs*, RadStream); +int r4d_rad_s2d3d (const RadArgs*, RadStream); +int r4d_rad_pix_patch (const RadArgs*, RadStream); +int r4d_rad_patch_pix8 (const RadArgs*, RadStream); +int r4d_rad_vol_index (const RadArgs*, RadStream); +int r4d_rad_attn_na3d (const RadArgs*, RadStream); +int r4d_rad_tile_grid (const RadArgs*, RadStream); +int r4d_rad_tile_crop (const RadArgs*, RadStream); +int r4d_rad_tile_stitch (const RadArgs*, RadStream); +int r4d_rad_stft_logmel (const RadArgs*, RadStream); +int r4d_rad_bwe_up (const RadArgs*, RadStream); /* r4d_vsa.hip: video sparse attention's selection (scratch for the tile means) and attention. */ int r4d_rad_vsa_select (const RadArgs*, RadStream); int64_t r4d_rad_vsa_select_scratch (const RadArgs*); @@ -280,6 +300,24 @@ int64_t r4d_rad_attn_decode_h256_gqa6_scratch(const RadArgs*); * kernel; see attn_decode_gq_h256_gqa6_fp8kv. */ int r4d_rad_attn_decode_gq_h256_gqa6_fp8(const RadArgs*, RadStream); int r4d_rad_attn_decode_gq_h256_gqa6_bf16(const RadArgs*, RadStream); +/* The fp8_v4 and k6_v4 caches on both: prefill, decode, and decode with the gate and quantiser in + * the merge (R4D_ATTN_V4 in r4d_attn_paged_gqa8.hip). */ +int r4d_rad_attn_prefill_h256_gqa12_fp8v4(const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa12_fp8v4(const RadArgs*, RadStream); +int r4d_rad_attn_decode_gq_h256_gqa12_fp8v4(const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch(const RadArgs*); +int r4d_rad_attn_prefill_h256_gqa12_k6v4(const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa12_k6v4(const RadArgs*, RadStream); +int r4d_rad_attn_decode_gq_h256_gqa12_k6v4(const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h256_gqa12_k6v4_scratch(const RadArgs*); +int r4d_rad_attn_prefill_h256_gqa6_fp8v4(const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa6_fp8v4(const RadArgs*, RadStream); +int r4d_rad_attn_decode_gq_h256_gqa6_fp8v4(const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch(const RadArgs*); +int r4d_rad_attn_prefill_h256_gqa6_k6v4(const RadArgs*, RadStream); +int r4d_rad_attn_decode_h256_gqa6_k6v4(const RadArgs*, RadStream); +int r4d_rad_attn_decode_gq_h256_gqa6_k6v4(const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h256_gqa6_k6v4_scratch(const RadArgs*); /* -- gated delta net (r4d_gdn_*.hip) -- */ int r4d_rad_gdn_chunk_scan (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index a4d7038a..4cd29805 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -188,6 +188,23 @@ static const RadOperandSpec oAttnDense[] = { { "cu_seqlens", RAD_OPD_IN, 0 }, { "out", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pAttnCross[] = { + P_INT("M"), P_INT("head_dim"), P_INT("gqa"), P_INT("causal"), P_STR("dtype"), + P_F64O("scale"), +}; +static const RadOperandSpec oAttnCross[] = { + { "q", RAD_OPD_IN, 0 }, + { "k", RAD_OPD_IN, 0 }, + { "v", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "cu_k", RAD_OPD_IN, 0 }, + { "out", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("kt"), P_INT("kh"), + P_INT("kw"), P_STR("dtype"), P_F64O("scale") }; +static const RadOperandSpec oAttnNa3d[] = { { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, + { "v", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, + { "out", RAD_OPD_OUT, 0 } }; /* Not docs/OPS.md's `qk_norm_rope` (qkv in place, `theta`): this kernel splits a packed [q|gate] * projection per head, writes q, k and the gate to three destinations, and takes a precomputed @@ -2257,6 +2274,20 @@ static const RadOperandSpec oLnModQ[] = { { "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 }, }; /* `act` is the gate's activation, "tanh" (the default) or "none". */ +static const RadParamSpec pTableAdd[] = { P_INT("M"), P_INT("n"), P_INT("L"), P_STR("dtype") }; +static const RadOperandSpec oTableAdd[] = { + { "x", RAD_OPD_IN, 0 }, { "t", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pMixRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") }; +static const RadParamSpec pChanStats[] = { P_INT("M"), P_INT("n"), P_STR("mode"), P_INTO("var"), + P_F64O("eps"), P_STR("dtype") }; +static const RadOperandSpec oChanStats[] = { + { "x", RAD_OPD_IN, 0 }, { "mean", RAD_OPD_WEIGHT, 0 }, { "s", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec oMixRows[] = { + { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oGateAdd[] = { { "y", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, @@ -2408,6 +2439,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"), static const RadOperandSpec oIota[] = { { "y", RAD_OPD_OUT, 0 } }; static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") }; static const RadOperandSpec oCuRepeat[] = { { "len", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") }; +static const RadOperandSpec oIntAffine[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; static const RadParamSpec pSnakeAa[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("k"), P_INTO("log"), P_STR("dtype") }; static const RadOperandSpec oSnakeAa[] = { @@ -2419,17 +2452,19 @@ static const RadOperandSpec oSnakeAa[] = { /* ---- video generation (r4d_video.hip); the same specs as libref's (ref_registry.cpp). `geom` is * the request's latent geometry, i32 on the device. */ static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"), - P_STR("dtype") }; + P_STR("dtype"), P_F64O("wadd"), + P_INTO("norm_once"), P_STRO("norm") }; static const RadOperandSpec oRmsMod[] = { { "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, + { "w", RAD_OPD_WEIGHT, 1 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, { "z", RAD_OPD_OUT, 0 }, }; static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), - P_INT("gated"), P_STR("dtype") }; + P_INT("gated"), P_STR("dtype"), P_F64O("wadd"), + P_INTO("norm_once"), P_STRO("norm") }; static const RadOperandSpec oRmsModQ[] = { { "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 }, - { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, + { "w", RAD_OPD_WEIGHT, 1 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 }, }; static const RadOperandSpec oFlowX0[] = { @@ -2464,7 +2499,8 @@ static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } }; /* ---- a video latent upscaler (r4d_upscaler.hip); the same specs as libref's. `geom` is the * request's volume, i32 on the device; patch_fold takes patch_unfold's specs. */ static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), - P_INT("kt"), P_STR("dtype") }; + P_INT("kt"), P_STR("dtype"), P_STRO("tpad"), + P_INTO("tpre") }; static const RadOperandSpec oConv3d[] = { { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, { "geom", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, @@ -2489,6 +2525,64 @@ static const RadOperandSpec oFlowRenoise[] = { { "sigma", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, }; +/* ---- LTX-2 (r4d_ltx.hip); the same specs as libref's. */ +static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"), + P_INT("dim"), P_INT("n_dims"), P_F64("theta"), + P_STR("max"), P_INTO("head0"), P_STR("dtype") }; +static const RadOperandSpec oRopeSplit[] = { + { "x", RAD_OPD_INOUT, 0 }, { "positions", RAD_OPD_IN, 0 }, +}; +static const RadParamSpec pHeadGate[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"), + P_STR("dtype") }; +static const RadOperandSpec oHeadGate[] = { { "g", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 } }; +static const RadParamSpec pLtxGuide[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oLtxGuide[] = { + { "vc", RAD_OPD_IN, 0 }, { "vu", RAD_OPD_IN, 1 }, { "vs", RAD_OPD_IN, 1 }, + { "vm", RAD_OPD_IN, 1 }, { "scales", RAD_OPD_IN, 0 }, { "sched", RAD_OPD_IN, 0 }, + { "stats", RAD_OPD_INOUT, 0 }, { "x", RAD_OPD_INOUT, 0 }, +}; +/* LTX-2's VAE, audio VAE and vocoder (r4d_ltx.hip); `geom` is x's volume, i32 on the device. */ +static const RadParamSpec pPixelNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("form"), + P_STRO("act"), P_INTO("ileave"), P_STR("dtype"), + P_F64O("mult") }; +static const RadOperandSpec oPixelNorm[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pD2s3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), + P_INT("sw"), P_INTO("drop"), P_STR("dtype") }; +static const RadOperandSpec oD2s3d[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pS2d3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), + P_INT("sw"), P_INTO("tpre"), P_INTO("group"), + P_STR("mode"), P_INTO("add"), P_STR("dtype") }; +static const RadOperandSpec oS2d3d[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_INOUT, 0 } }; +static const RadParamSpec pPixPatch[] = { P_INT("M"), P_INT("p"), P_INT("C"), P_STRO("order"), + P_STR("dtype") }; +static const RadOperandSpec oPixPatch[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pVolIndex[] = { P_INT("M") }; +static const RadOperandSpec oVolIndex[] = { { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pTileGrid[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), P_STRO("rule"), + P_INTO("min"), P_INTO("tile_t"), P_INTO("stride_t"), + P_INTO("min_t"), P_INTO("tail") }; +static const RadOperandSpec oTileGrid[] = { { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pTileCrop[] = { P_INT("M"), P_INT("C"), P_STR("dtype") }; +static const RadOperandSpec oTileCrop[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, + { "box", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pTileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), + P_STRO("rule"), P_INTO("min"), P_INTO("tile_t"), + P_INTO("stride_t"), P_INTO("min_t"), P_INT("scale"), + P_INTO("scale_t"), P_INT("p"), P_INT("C"), + P_STRO("order"), P_STR("dtype") }; +static const RadOperandSpec oTileStitch[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, + { "first", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pStftMel[] = { P_INT("M"), P_INT("hop"), P_INT("nfft"), P_INT("n_mel"), + P_INT("ch"), P_STR("dtype") }; +static const RadOperandSpec oStftMel[] = { { "x", RAD_OPD_IN, 0 }, { "basis", RAD_OPD_WEIGHT, 0 }, + { "mel", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pBweUp[] = { P_INT("M"), P_INT("ratio"), P_INT("ch"), P_STR("dtype") }; +static const RadOperandSpec oBweUp[] = { { "x", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; + /* ---- video sparse attention (r4d_vsa.hip); the same specs as libref's. `segs` cuts the packed * rows into dense segments and the video grid, `geom` is the request's latent geometry; `sel` is * vsa_select's output and attn_vsa's input. `v` of vsa_select is read only for `coarse`. */ @@ -2761,6 +2855,12 @@ static const RadOpSchema kSchemas[] = { "dense attention over cu_seqlens segments (rows cu/cu_div), with attn_paged's window " "rule over a segment's positions and optional blocks of `block` rows that attend " "within themselves."), + SCHEMA("attn_cross", pAttnCross, oAttnCross, + "attn_dense with each entry's keys a run of their own: queries rows [cu[s], cu[s+1]), " + "keys and values rows [cu_k[s], cu_k[s+1]); `causal` counts from each run's start."), + SCHEMA("attn_na3d", pAttnNa3d, oAttnNa3d, + "3-D neighborhood attention over the voxels of geom = (T, H, W): each query sees the " + "kt x kh x kw window centred on it, shifted inward at the border."), SCHEMA("qk_norm_rope_gate", pQkNormRopeGate, oQkNormRopeGate, "split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate " "copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a " @@ -3137,6 +3237,14 @@ static const RadOpSchema kSchemas[] = { SCHEMA("ln_mod_quant_fp8", pLnModQ, oLnModQ, "gated 1: x = bf16(x + bf16(bf16(tanh(g[seq])) * y)) first; then z = ln_mod(x) and " "(q, scale) = quant_act_fp8(z, group), z written when bound."), + SCHEMA("table_add", pTableAdd, oTableAdd, + "y[r, l n + c] = x[r, c] + t[l, c]: a shared modulation row plus each of L learned rows, " + "f32 sum rounded once."), + SCHEMA("chan_stats", pChanStats, oChanStats, + "a latent through per-channel statistics held as weights: denorm rd(rd(x std) + mean), " + "norm rd(rd(x - mean) / std); std is s, or sqrt(s + eps) with var 1."), + SCHEMA("mix_rows", pMixRows, oMixRows, + "y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows."), SCHEMA("gate_add", pGateAdd, oGateAdd, "x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate; " "with `act` none the gate is g itself, x = bf16(x + bf16(g[seq] * y))."), @@ -3205,6 +3313,8 @@ static const RadOpSchema kSchemas[] = { SCHEMA("interleave2", pInterleave, oInterleave2, "two streams interleaved."), SCHEMA("iota", pIota, oIota, "y[i] = start + i * step."), SCHEMA("cu_repeat", pCuRepeat, oCuRepeat, "bounds of equal sequences, y[j] = j * len[0] * mult."), + SCHEMA("int_affine", pIntAffine, oIntAffine, + "y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists."), SCHEMA("snake_aa", pSnakeAa, oSnakeAa, "BigVGAN's alias-free SnakeBeta over each sequence, f32: replicate-padded, upsampled " "`ratio` times by `f_up`, SnakeBeta, filtered by `f_down` at stride `ratio`."), @@ -3247,6 +3357,44 @@ static const RadOpSchema kSchemas[] = { SCHEMA("flow_renoise", pFlowRenoise, oFlowRenoise, "x = (1 - sigma) x + sigma z, z the (seed, stream) normal stream at element k n + c, " "each step one f32 rounding."), + SCHEMA("rope_split", pRopeSplit, oRopeSplit, + "LTX-2's split rotary over fractional coordinates: the pairs of all heads on one " + "ladder, the first `pad` unrotated, the axes interleaved; each head's halves turned " + "against each other in f32."), + SCHEMA("head_gate", pHeadGate, oHeadGate, + "x = rd(x rd(2 rd(sigmoid(g)))) for each head's values."), + SCHEMA("ltx_guide", pLtxGuide, oLtxGuide, + "LTX-2's sampler step: the passes' clean estimates combined (CFG, STG, modality), an " + "optional rescale by the deviations' ratio, the velocity back and the Euler step, f32."), + SCHEMA("pixel_norm", pPixelNorm, oPixelNorm, + "an RMS norm over each row's n values as bf16 tensors compute it, every step rounded " + "to y's dtype; rsqrt or div form, optionally silu; `ileave` L writes x's row t L + l " + "to columns c L + l of y's row t."), + SCHEMA("d2s3d", pD2s3d, oD2s3d, + "depth to space over voxel rows, the first st - 1 frames dropped."), + SCHEMA("s2d3d", pS2d3d, oS2d3d, + "space to depth over voxel rows, `tpre` leading frames prepended: a packed row each " + "box (copy) or each `group` packed channels averaged (mean); `add` adds into y."), + SCHEMA("pix_patch", pPixPatch, oPixPatch, + "an image [H, W C] to patch rows [H/p, (W/p) C p p], order wh or hw."), + SCHEMA("patch_pix8", pPixPatch, oPixPatch, + "patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule."), + SCHEMA("vol_index", pVolIndex, oVolIndex, + "a volume's voxel coordinates (t, i, j), component-major."), + SCHEMA("tile_grid", pTileGrid, oTileGrid, + "the tiles of a grid as diffusers cuts them (rule stride or intervals), in space and " + "optionally time, one row (t, h, w, t0, y0, x0, k, count) a tile."), + SCHEMA("tile_crop", pTileCrop, oTileCrop, + "one tile's voxels out of a volume, box (t, h, w, t0, y0, x0)."), + SCHEMA("tile_stitch", pTileStitch, oTileStitch, + "decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h, then blend_t " + "across time bands, each tile kept to its stride, patch_pix8's bytes."), + SCHEMA("stft_logmel", pStftMel, oStftMel, + "each channel's causal log-mel spectrogram from a windowed DFT basis and a mel " + "filterbank, every stored tensor rounded to y's dtype."), + SCHEMA("bwe_up", pBweUp, oBweUp, + "y = clamp(rd(res + up(x)), -1, 1), x raised `ratio` times by a Hann-windowed sinc " + "resampler."), SCHEMA("vsa_select", pVsa, oVsaSelect, "video sparse attention's selection over tiles of at most 64 rows (dense segments in " "chunks, the video grid in tile_t x tile_h x tile_w boxes): f32 tile means of q and k, " @@ -3504,6 +3652,60 @@ static const RadConstraint cAttnDecodeGqH256G6Bs4Bf16[] = { C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), C_EQ("group", 128), C_IN("act", "sigmoid"), }; +/* The fp8_v4 and k6_v4 caches on the QSA layers' two ratios (r4d_attn_paged_gqa8.hip's + * R4D_ATTN_V4): the fp8 rows' constraints at those kv_dtype values. */ +static const RadConstraint cAttnPrefillH256G12Fp8v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"), +}; +static const RadConstraint cAttnDecodeH256G12Fp8v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"), +}; +static const RadConstraint cAttnDecodeGqH256G12Fp8v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"), + C_EQ("group", 128), C_IN("act", "sigmoid"), +}; +static const RadConstraint cAttnPrefillH256G12K6v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"), +}; +static const RadConstraint cAttnDecodeH256G12K6v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"), +}; +static const RadConstraint cAttnDecodeGqH256G12K6v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"), + C_EQ("group", 128), C_IN("act", "sigmoid"), +}; +static const RadConstraint cAttnPrefillH256G6Bs4Fp8v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"), +}; +static const RadConstraint cAttnDecodeH256G6Bs4Fp8v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"), +}; +static const RadConstraint cAttnDecodeGqH256G6Bs4Fp8v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"), + C_EQ("group", 128), C_IN("act", "sigmoid"), +}; +static const RadConstraint cAttnPrefillH256G6Bs4K6v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"), +}; +static const RadConstraint cAttnDecodeH256G6Bs4K6v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"), +}; +static const RadConstraint cAttnDecodeGqH256G6Bs4K6v4[] = { + C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4), + C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"), + C_EQ("group", 128), C_IN("act", "sigmoid"), +}; static const RadConstraint cAttnPrefillH128G8Fp8[] = { C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), @@ -3571,6 +3773,9 @@ static const RadConstraint cAttnLocalRel[] = { }; /* `cast` widening bf16 -> f32: an exact conversion, the form a pooled embedding leaves the * device in. */ +static const RadConstraint cCastF32[] = { + C_IN("from", "f32"), C_IN("to", "f32"), +}; static const RadConstraint cCastWiden[] = { C_IN("from", "bf16"), C_IN("to", "f32"), }; @@ -3584,20 +3789,30 @@ static const RadConstraint cCastF16[] = { static const RadConstraint cCastNarrow[] = { C_IN("from", "f32"), C_IN("to", "bf16"), }; -/* The encoder's dense attention: bidirectional, any window, at the (head_dim, gqa) pairs - * r4d_attn_dense_bf16.hip compiles. */ +/* Dense attention at the (head_dim, gqa) pairs r4d_attn_dense_bf16.hip compiles: an encoder's, + * bidirectional with any window, or a text encoder's causal prompt. gqa 1 at 256 and 512 is + * attn_dense_small_h256's and the wide kernel's. */ /* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */ static const RadConstraint cAttnDenseH64[] = { C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"), }; static const RadConstraint cAttnDenseH256G2[] = { - C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("causal", 0), C_IN("dtype", "bf16"), + C_EQ("head_dim", 256), C_EQ("gqa", 2), C_IN("dtype", "bf16"), }; static const RadConstraint cAttnDenseH256G4[] = { - C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"), + C_EQ("head_dim", 256), C_EQ("gqa", 4), C_IN("dtype", "bf16"), +}; +static const RadConstraint cAttnDenseH256G8[] = { + C_EQ("head_dim", 256), C_DIV("gqa", 8), C_IN("dtype", "bf16"), +}; +static const RadConstraint cAttnDenseH512G2[] = { + C_EQ("head_dim", 512), C_EQ("gqa", 2), C_IN("dtype", "bf16"), }; static const RadConstraint cAttnDenseH512G4[] = { - C_EQ("head_dim", 512), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"), + C_EQ("head_dim", 512), C_EQ("gqa", 4), C_IN("dtype", "bf16"), +}; +static const RadConstraint cAttnDenseH512G8[] = { + C_EQ("head_dim", 512), C_DIV("gqa", 8), C_IN("dtype", "bf16"), }; /* A head in a wave's registers with a rotary pair in one lane: head_dim a multiple of 32 up to * 1024. The shim refuses a rotary_dim whose half is not a multiple of 32 (neox) by name. */ @@ -3871,16 +4086,9 @@ static const RadConstraint cMlaProject[] = { C_GE("M", 1), /* The matrix row outranks the wave row (mla_attn_bf16) at every M, the pairing walking the union * of both rows' pages: measured cold on gfx1201 (r4d_selftest --perfmla), a 2048-row chunk * with DSA tables (fill topk:16) takes 7.1 ms against 12.4 ms on the wave row and 13.0 ms on the - * positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms. - * RADIANCE_MLA_MATRIX_MAX_M lowers the bound, read once as the table loads; 0 is never. */ -static long long mla_matrix_max_m() { - const char* e = std::getenv("RADIANCE_MLA_MATRIX_MAX_M"); - char* end = nullptr; - const long long v = e && *e ? std::strtoll(e, &end, 10) : -1; - return end && !*end && v >= 0 ? (v < 65535 ? v : 65535) : 65535; -} + * positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms. */ static const RadConstraint cMlaMatrix[] = { C_GE("M", 1), - C_LE("M", mla_matrix_max_m()), + C_LE("M", 65535), C_EQ("latent_dim", 512), C_GE("heads", 8), C_LE("heads", 64), @@ -4605,6 +4813,16 @@ static const RadConstraint cAttnPrefixSelf[] = { static const RadConstraint cAttnDenseH128[] = { C_EQ("head_dim", 128), C_LE("gqa", 8), C_IN("dtype", "bf16"), }; +static const RadConstraint cAttnCrossH64[] = { + C_EQ("head_dim", 64), C_LE("gqa", 8), C_IN("dtype", "bf16"), +}; +static const RadConstraint cAttnNa3d[] = { C_EQ("head_dim", 64), C_IN("dtype", "bf16 f32") }; +static const RadConstraint cAttnDenseH384[] = { + C_EQ("head_dim", 384), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), +}; +static const RadConstraint cAttnDenseH512[] = { + C_EQ("head_dim", 512), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), +}; static const RadConstraint cAttnDenseH768[] = { C_EQ("head_dim", 768), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"), }; @@ -4729,6 +4947,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_cast, nullptr, nullptr, nullptr, r4d_shape_cast }, +{ "cast_f32_f32", "cast", "elem", + "y = x, f32 to f32 -- a strided row copy through libr4d's 2D copy", + "any M and n; both row pitches are read off the operands", + "f32 in, f32 out, byte-for-byte", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cCastF32), NOTUNE, + nullptr, nullptr, r4d_rad_cast, nullptr, nullptr, nullptr, + r4d_shape_cast }, + { "cast_bf16_f32", "cast", "elem", "y = x, bf16 widened to f32", "any M and n; both row pitches are read off the operands", @@ -5013,6 +5240,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_fill, nullptr, nullptr, nullptr, r4d_shape_fill }, +{ "fill_f32", "fill", "elem", + "constant fill, a row a workgroup", + "any M, n; a row pitch is honoured", + "f32 out, the value exactly", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_fill, nullptr, nullptr, nullptr, + r4d_shape_fill }, + { "sigmoid_bf16", "sigmoid", "elem", "logistic sigmoid, grid-strided over the whole extent", "any extent; contiguous in and out", @@ -5791,6 +6027,129 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant }, +/* The fp8_v4 and k6_v4 caches on Flash-Next's QSA layers: gqa12 at one and two ranks, gqa6 with + * 4-token pages at four. A token's row is 400 bytes (E4M3 K, int4 V, f16 group scales) or 352 + * (int6 K, int4 V); the layouts are RAD_KVQ_*'s (abi/rad_builder.h). */ +{ "attn_prefill_h256_gqa12_fp8v4", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 256, 12 queries per kv head, paged block 4, varlen", + "bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH256G12Fp8v4), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa12_fp8v4, nullptr, nullptr, nullptr, + nullptr }, + +{ "attn_decode_h256_gqa12_fp8v4", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", + "head_dim 256, 12 queries per kv head, paged block 4, q_len*gqa <= 64, no window", + "bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256G12Fp8v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_fp8v4, r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch, + nullptr, nullptr, + nullptr }, + +{ "attn_decode_gq_h256_gqa12_fp8v4", "attn_paged_gate_quant", "attn", + "paged split-KV decode attention with the output gate and the fp8 quantiser in the merge", + "attn_decode_h256_gqa12_fp8v4's geometry; gate_quant_fp8 over the merged (token, head) rows: " + "sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned", + "bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeGqH256G12Fp8v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa12_fp8v4, r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch, + nullptr, nullptr, + nullptr, nullptr, r4d_fuse_attn_paged_gate_quant }, + +{ "attn_prefill_h256_gqa12_k6v4", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 256, 12 queries per kv head, paged block 4, varlen", + "bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH256G12K6v4), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa12_k6v4, nullptr, nullptr, nullptr, + nullptr }, + +{ "attn_decode_h256_gqa12_k6v4", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", + "head_dim 256, 12 queries per kv head, paged block 4, q_len*gqa <= 64, no window", + "bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256G12K6v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_k6v4, r4d_rad_attn_decode_h256_gqa12_k6v4_scratch, + nullptr, nullptr, + nullptr }, + +{ "attn_decode_gq_h256_gqa12_k6v4", "attn_paged_gate_quant", "attn", + "paged split-KV decode attention with the output gate and the fp8 quantiser in the merge", + "attn_decode_h256_gqa12_k6v4's geometry; gate_quant_fp8 over the merged (token, head) rows: " + "sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned", + "bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeGqH256G12K6v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa12_k6v4, r4d_rad_attn_decode_h256_gqa12_k6v4_scratch, + nullptr, nullptr, + nullptr, nullptr, r4d_fuse_attn_paged_gate_quant }, + +{ "attn_prefill_h256_gqa6_bs4_fp8v4", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 256, 6 queries per kv head, paged block 4, varlen", + "bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH256G6Bs4Fp8v4), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa6_fp8v4, nullptr, nullptr, nullptr, + nullptr }, + +{ "attn_decode_h256_gqa6_bs4_fp8v4", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", + "head_dim 256, 6 queries per kv head, paged block 4, q_len*gqa <= 64, no window", + "bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256G6Bs4Fp8v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_fp8v4, r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch, + nullptr, nullptr, + nullptr }, + +{ "attn_decode_gq_h256_gqa6_bs4_fp8v4", "attn_paged_gate_quant", "attn", + "paged split-KV decode attention with the output gate and the fp8 quantiser in the merge", + "attn_decode_h256_gqa6_bs4_fp8v4's geometry; gate_quant_fp8 over the merged (token, head) rows: " + "sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned", + "bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeGqH256G6Bs4Fp8v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa6_fp8v4, r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch, + nullptr, nullptr, + nullptr, nullptr, r4d_fuse_attn_paged_gate_quant }, + +{ "attn_prefill_h256_gqa6_bs4_k6v4", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 256, 6 queries per kv head, paged block 4, varlen", + "bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH256G6Bs4K6v4), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa6_k6v4, nullptr, nullptr, nullptr, + nullptr }, + +{ "attn_decode_h256_gqa6_bs4_k6v4", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", + "head_dim 256, 6 queries per kv head, paged block 4, q_len*gqa <= 64, no window", + "bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256G6Bs4K6v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_k6v4, r4d_rad_attn_decode_h256_gqa6_k6v4_scratch, + nullptr, nullptr, + nullptr }, + +{ "attn_decode_gq_h256_gqa6_bs4_k6v4", "attn_paged_gate_quant", "attn", + "paged split-KV decode attention with the output gate and the fp8 quantiser in the merge", + "attn_decode_h256_gqa6_bs4_k6v4's geometry; gate_quant_fp8 over the merged (token, head) rows: " + "sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned", + "bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeGqH256G6Bs4K6v4), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa6_k6v4, r4d_rad_attn_decode_h256_gqa6_k6v4_scratch, + nullptr, nullptr, + nullptr, nullptr, r4d_fuse_attn_paged_gate_quant }, + { "attn_prefill_h128_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 128, 8 queries per kv head, paged block 16, varlen", @@ -5887,7 +6246,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_attn_dense }, { "attn_dense_h256_gqa2_bf16", "attn_dense", "attn", - "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", + "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or " + "causal with an optional window behind", "head_dim 256, two query heads a KV head in one workgroup, the key range cut to the window", "bf16 query / key / value / out, f16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -5895,21 +6255,52 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_attn_dense }, { "attn_dense_h256_gqa4_bf16", "attn_dense", "attn", - "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", + "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or " + "causal with an optional window behind", "head_dim 256, four query heads a KV head in one workgroup, the key range cut to the window", "bf16 query / key / value / out, f16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnDenseH256G4), NOTUNE, nullptr, nullptr, r4d_rad_attn_dense }, +{ "attn_dense_h256_gqa8_bf16", "attn_dense", "attn", + "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or " + "causal with an optional window behind", + "head_dim 256, eight query heads a KV head in one workgroup (a multiple of eight as several), " + "the key range cut to the window", + "bf16 query / key / value / out, f16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH256G8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense }, + +{ "attn_dense_h512_gqa2_bf16", "attn_dense", "attn", + "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or " + "causal with an optional window behind", + "head_dim 512 split across two waves, two query heads a KV head in one workgroup", + "bf16 query / key / value / out, f16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH512G2), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense }, + { "attn_dense_h512_gqa4_bf16", "attn_dense", "attn", - "dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window", + "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or " + "causal with an optional window behind", "head_dim 512 split across two waves, four query heads a KV head in one workgroup", "bf16 query / key / value / out, f16 operands, fp32 accumulate", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cAttnDenseH512G4), NOTUNE, nullptr, nullptr, r4d_rad_attn_dense }, +{ "attn_dense_h512_gqa8_bf16", "attn_dense", "attn", + "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or " + "causal with an optional window behind", + "head_dim 512 split across two waves, eight query heads a KV head in one workgroup (a " + "multiple of eight as several workgroups)", + "bf16 query / key / value / out, f16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH512G8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense }, + /* -------------------------------------------------------------------------- gated delta net */ { "gdn_chunk_scan_k128_v128_c64_bf16", "gdn_chunk_scan", "gdn", "gated delta net chunked scan: WY recompute, state recurrence and output in one kernel", @@ -7496,6 +7887,46 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnDenseH128), NOTUNE, nullptr, nullptr, r4d_rad_attn_dense_h128 }, +{ "attn_cross_h128_bf16", "attn_cross", "attn", + "dense varlen attention with the keys bounded apart from the queries (cross attention)", + "head_dim 128, 1/2/4/8 query heads a KV head; attn_dense_h128's kernel", + "bf16 query / key / value / out, bf16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH128), NOTUNE, + nullptr, nullptr, r4d_rad_attn_cross }, + +{ "attn_cross_h64_bf16", "attn_cross", "attn", + "dense varlen attention with the keys bounded apart from the queries (cross attention)", + "head_dim 64, 1/2/4/8 query heads a KV head; attn_dense_h128's kernel at 64", + "bf16 query / key / value / out, bf16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnCrossH64), NOTUNE, + nullptr, nullptr, r4d_rad_attn_cross }, + +{ "attn_na3d_h64", "attn_na3d", "attn", + "3-D neighborhood attention: a thread a (query, head), the window's keys streamed through the " + "caches, libref's two passes", + "head_dim 64, any window, row pitches honoured", "bf16 or f32 q / k / v / out, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnNa3d), NOTUNE, + nullptr, nullptr, r4d_rad_attn_na3d }, + +{ "attn_dense_h384_bf16", "attn_dense", "attn", + "one 384-wide head over every row of a segment: an image encoder's mid-block attention", + "head_dim 384 split across eight waves, 16 queries a workgroup", + "bf16 query / key / value / out, bf16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH384), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense_wide }, + +{ "attn_dense_h512_bf16", "attn_dense", "attn", + "one 512-wide head over every row of a segment: an image encoder's mid-block attention", + "head_dim 512 split across eight waves, 16 queries a workgroup", + "bf16 query / key / value / out, bf16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH512), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense_wide }, + { "attn_dense_h768_bf16", "attn_dense", "attn", "one 768-wide head over every row of a segment: an image encoder's mid-block attention", "head_dim 768 split across eight waves, 16 queries a workgroup", @@ -7527,6 +7958,38 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGenRows8), NOTUNE, nullptr, nullptr, r4d_rad_ln_mod }, +{ "table_add_bf16", "table_add", "elem", + "a shared modulation row plus each block's learned table row, every block in one launch", + "any M, row pitches honoured; n a multiple of 8", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_table_add }, + +{ "chan_stats_bf16", "chan_stats", "elem", + "a VAE latent through its per-channel statistics (running mean and variance, or mean and std)", + "any M, row pitches honoured; n a multiple of 8", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_chan_stats }, + +{ "chan_stats_f32", "chan_stats", "elem", + "a latent kept in f32 through its VAE's per-channel statistics", + "any M, row pitches honoured", + "f32 x and y, bf16 or f32 statistics, every step rounded to f32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_chan_stats }, + +{ "mix_rows_bf16", "mix_rows", "elem", + "a learned weighted sum of k consecutive rows (a Linear(k, 1) over a stacked axis)", + "any M, row pitches honoured; n a multiple of 8", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenRows8), NOTUNE, + nullptr, nullptr, r4d_rad_mix_rows }, + { "gate_add_bf16", "gate_add", "elem", "x += tanh(gate row) * y, the reference's three roundings; with `act` none the gate as it is", "any M, row pitches honoured", @@ -7809,6 +8272,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, 0, NOTUNE, nullptr, nullptr, r4d_rad_cu_repeat }, +{ "int_affine", "int_affine", "elem", + "integers derived from device geometry: one wave, the lists by value", "up to 16 values", + "i32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_int_affine }, + { "attn_dense_small_h256_bf16", "attn_dense", "attn", "dense attention over short sequences, causal or not: a depth decoder's frame positions", "head_dim 256, one query head a key head, sequences of at most 32 rows, a workgroup a (sequence, " @@ -7958,6 +8428,103 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGenF32), NOTUNE, nullptr, nullptr, r4d_rad_flow_renoise }, + +{ "rope_split", "rope_split", "elem", + "LTX-2's rotary: a workgroup a (head, 64 rows), the head's ladder in LDS, sincosf a pair", + "any M, row pitches honoured; head_dim / 2 dividing 256; up to four axes", + "bf16 or f32 x, f32 or i32 positions", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_rope_split }, + +{ "head_gate", "head_gate", "elem", + "each head times 2 sigmoid of its logit: a thread a value", + "any M, row pitches honoured", "bf16 logits, bf16 or f32 x", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_head_gate }, + +{ "ltx_guide", "ltx_guide", "elem", + "LTX-2's guided step: f64 deviation sums in up to 1024 parts, then the step in place", + "any M and n, row pitches honoured", "f32 latent, bf16 or f32 velocities", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_ltx_guide }, + +{ "pixel_norm", "pixel_norm", "norm", + "an RMS norm as bf16 tensors compute it: a wave a row, its sum of squares a wave reduction", + "any M and n, row pitches honoured", "bf16 or f32 x and y", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_pixel_norm }, + +{ "d2s3d", "d2s3d", "elem", + "depth to space over voxel rows: a thread a value, the volume off the device", + "any C and factors, row pitches honoured", "bf16 or f32 x and y, i32 geom", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_d2s3d }, + +{ "s2d3d", "s2d3d", "elem", + "space to depth over voxel rows, copy or group mean, optionally added: a thread a value", + "any C and factors, row pitches honoured", "bf16 or f32 x and y, i32 geom", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_s2d3d }, + +{ "pix_patch", "pix_patch", "elem", + "an image to patch rows: a thread a value", + "dense 2-D operands, row pitches honoured", "bf16 or f32 x and y", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_pix_patch }, + +{ "patch_pix8", "patch_pix8", "elem", + "patch rows to RGB bytes: a thread a byte", + "dense 2-D operands, row pitches honoured", "bf16 or f32 x, u8 y", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_patch_pix8 }, + +{ "vol_index", "vol_index", "elem", + "a volume's voxel coordinates: a thread a voxel", "i32, a dense [3, n]", "i32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_vol_index }, + +{ "tile_grid", "tile_grid", "elem", + "a tiled decode's boxes off a device volume: a thread a row", "contiguous i32", "i32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + nullptr, 0, NOTUNE, + nullptr, nullptr, r4d_rad_tile_grid }, + +{ "tile_crop", "tile_crop", "elem", + "a tile's voxels out of a volume: a thread a value, the box read on the device", + "row pitches honoured", "bf16 or f32 x and y, i32 geom and box", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_tile_crop }, + +{ "tile_stitch", "tile_stitch", "elem", + "decoded tiles blended to RGB bytes: a thread a byte, up to four tiles read", + "dense 2-D operands, row pitches honoured", "bf16 or f32 x, u8 y, i32 geom and first", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_tile_stitch }, + +{ "stft_logmel", "stft_logmel", "elem", + "a causal log-mel spectrogram: a workgroup a (frame, channel), the frame in LDS", + "nfft up to 4096, row pitches honoured", "bf16 or f32 operands", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_stft_logmel }, + +{ "bwe_up", "bwe_up", "elem", + "a sinc-resampled waveform plus a residual, clamped: a thread a value, the taps by value", + "ratio up to 9, row pitches honoured", "bf16 or f32 operands", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenAnyFloat), NOTUNE, + nullptr, nullptr, r4d_rad_bwe_up }, }; /* ================================================================================== the exports */ diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 3844acbd..1e7e0e69 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -944,11 +944,12 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8 * compare the bf16 output against the oracle above. A negative control corrupts part of the * reference and requires the comparison to fail. */ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa, - int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64) { + int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64, + int64_t bs = 16) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); if (!r) { ok(name, false, "row absent"); return; } - const int64_t seqs = 1, kv_heads = 2, bs = 16; + const int64_t seqs = 1, kv_heads = 2; const int64_t q_heads = kv_heads * gqa; const int64_t max_blocks = (ctx + bs - 1) / bs; /* a ctx past a whole block: a partial last one */ const int64_t total_q = seqs * q_len; @@ -2671,9 +2672,12 @@ static void rowtopk_shard_case(const Plugin& pl) { * zero scale group and a scale of 1. The E4M3 cache is random bytes except NaN codes, the bf16 one * random finite values, and the descales are not 1. * - * `i8` runs both at int8 codes (the operand an int8 out projection reads), with the same claim. */ -static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = false) { - const std::string kvs = bf16 ? "bf16kv" : "fp8kv"; + * `i8` runs both at int8 codes (the operand an int8 out projection reads), with the same claim. + * `kvq` 1 or 2 runs them over an fp8_v4 or k6_v4 cache instead of the E4M3 one: random codes with + * finite f16 group scales. */ +static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = false, + int kvq = 0) { + const std::string kvs = bf16 ? "bf16kv" : kvq == 1 ? "fp8v4" : kvq == 2 ? "k6v4" : "fp8kv"; const std::string fold = "attn_decode_gq_h256_gqa12_" + kvs; const std::string pair = "attn_decode_h256_gqa12_" + kvs; if (!sel(fold.c_str())) return; @@ -2701,7 +2705,10 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = std::vector hq((size_t)(S * nq * hd)), hqg((size_t)(S * nq * 2 * hd)); for (auto& x : hq) x = h_to_bf16(rnd(2.0f)); for (auto& x : hqg) x = h_to_bf16(rnd(6.0f)); - const size_t cbytes = (size_t)(nb * nkv * bs * 2 * hd) * (bf16 ? 2 : 1); + /* A token's row in a page: 2 * head_dim elements, or the v4 layouts' 25 / 22 * head_dim / 16 + * bytes (RadBuildCtx::kv_quant). */ + const int64_t rowb = kvq == 2 ? 22 * hd / 16 : kvq == 1 ? 25 * hd / 16 : 2 * hd; + const size_t cbytes = (size_t)(nb * nkv * bs * rowb) * (bf16 ? 2 : 1); std::vector hc(cbytes); if (bf16) { for (size_t i = 0; i + 1 < cbytes; i += 2) { @@ -2713,6 +2720,18 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = x = (uint8_t)(rnd(128.0f) + 128.0f); if ((x & 0x7f) == 0x7f) x ^= 1; /* E4M3's NaN codes */ } + /* The group scales: K's (k6_v4) and V's, finite and positive. */ + const int64_t vs = kvq == 2 ? hd * 21 / 16 : hd * 3 / 2, ks = hd * 5 / 4; + if (kvq) + for (size_t r0 = 0; r0 < cbytes; r0 += (size_t)rowb) + for (int64_t g = 0; g < hd / 32; ++g) { + const _Float16 v = (_Float16)(0.03125f * (1.0f + (rnd(1.0f) + 1.0f) * 2.0f)); + std::memcpy(&hc[r0 + (size_t)(vs + g * 2)], &v, 2); + if (kvq == 2) { + const _Float16 k = (_Float16)(0.0078125f * (1.0f + (rnd(1.0f) + 1.0f) * 2.0f)); + std::memcpy(&hc[r0 + (size_t)(ks + g * 2)], &k, 2); + } + } } std::vector hds((size_t)(S * nkv)); for (auto& x : hds) x = 0.75f + 0.5f * (rnd(1.0f) + 1.0f) * 0.5f; @@ -2741,7 +2760,7 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = auto attn_ops = [&](void* out) { return std::vector{ T(d_q, RAD_BF16, { S, nq, hd }), - T(d_c, bf16 ? RAD_BF16 : RAD_F8E4M3, { nb, nkv, bs, 2 * hd }), + T(d_c, bf16 ? RAD_BF16 : RAD_F8E4M3, { nb, nkv, bs, rowb }), TI32({ S, maxb }, table), TI32({ S }, used), T(d_kd, RAD_F32, { S, nkv }), @@ -2752,7 +2771,7 @@ static void attn_gq_fold_case(const Plugin& pl, int64_t S, bool bf16, bool i8 = std::vector pa = { PI("q_len", 1), PI("head_dim", hd), PI("gqa", nq / nkv), PI("block_size", bs), PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), - PS("kv_dtype", bf16 ? "bf16" : "fp8_e4m3"), + PS("kv_dtype", bf16 ? "bf16" : kvq == 1 ? "fp8_v4" : kvq == 2 ? "k6_v4" : "fp8_e4m3"), PI("n_head", nq), PI("max_seqs", S), PI("max_ctx", maxb * bs), }; @@ -6807,6 +6826,1186 @@ void snake_aa_cases(const Plugin& pl) { } /* namespace vid */ +/* ================================================================== the joint image generators + * Krea 2's and FLUX.3's ops: table_add, mix_rows, chan_stats, attn_cross, rms_mod's zero-centred + * and LayerNorm forms, timestep_embed's bf16 roundings and the wide attention at 384 and 512, each + * against the host's arithmetic in libref's order. */ +namespace g3 { + +using namespace au; + +/* y[r, l n + c] = x[r, c] + t[l, c]: exact, x at a wider pitch, y a column slice. */ +void table_add_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "table_add_bf16"); + if (!r) { ok("table_add_bf16", false, "row absent"); return; } + const int64_t M = 3, n = 6144 * 6, L = 1, xld = n + 64, yld = 28 * n; + std::vector x = randv((size_t)(M * xld), 1.0f), t = randv((size_t)(L * n), 0.5f); + for (float& v : x) v = bfr(v); + for (float& v : t) v = bfr(v); + RadTensor tx = T(up_bf16(x), RAD_BF16, { M, n }); + tx.stride[0] = xld; + void* dy = dalloc((size_t)(M * yld) * 2); + RadTensor ty = T((char*)dy + 5 * n * 2, RAD_BF16, { M, L * n }); + ty.stride[0] = yld; + const int rc = launch(r, { tx, T(up_bf16(t), RAD_BF16, { L, n }), ty }, + { PI("M", M), PI("n", n), PI("L", L), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("table_add_bf16", false, "rc " + std::to_string(rc)); return; } + const std::vector all = down_bf16(dy, (size_t)(M * yld)); + int64_t bad = 0; + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) + bad += all[(size_t)(row * yld + 5 * n + c)] != bfr(x[(size_t)(row * xld + c)] + t[(size_t)c]); + ok("table_add_bf16 one block's table into its columns, exact", bad == 0, + fmt("%lld values differ", (long long)bad)); +} + +/* y[r, c] = sum_i w[i] x[r k + i, c], twelve taps of 2560. */ +void mix_rows_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "mix_rows_bf16"); + if (!r) { ok("mix_rows_bf16", false, "row absent"); return; } + const int64_t M = 37, n = 2560, k = 12; + std::vector x = randv((size_t)(M * k * n), 1.0f), w = randv((size_t)k, 0.3f); + for (float& v : x) v = bfr(v); + for (float& v : w) v = bfr(v); + void* dy = dalloc((size_t)(M * n) * 2); + const int rc = launch(r, { T(up_bf16(x), RAD_BF16, { M * k, n }), T(up_bf16(w), RAD_BF16, { k }), + T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PI("k", k), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("mix_rows_bf16", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + float acc = 0.0f; + for (int64_t i = 0; i < k; ++i) acc += w[(size_t)i] * x[(size_t)((row * k + i) * n + c)]; + want[(size_t)(row * n + c)] = bfr(acc); + } + check("mix_rows_bf16 twelve taps", down_bf16(dy, want.size()), want, 8e-3); +} + +/* Both modes, a deviation and a variance (FLUX's BatchNorm, eps 1e-4). */ +void chan_stats_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "chan_stats_bf16"); + if (!r) { ok("chan_stats_bf16", false, "row absent"); return; } + const int64_t M = 33, n = 128; + for (const bool norm : { false, true }) + for (const int var : { 0, 1 }) { + std::vector x = randv((size_t)(M * n), 2.0f), mu = randv((size_t)n, 0.5f); + std::vector sv((size_t)n); + for (int64_t c = 0; c < n; ++c) sv[(size_t)c] = bfr(0.3f + 0.02f * (float)c); + for (float& v : x) v = bfr(v); + for (float& v : mu) v = bfr(v); + void* dy = dalloc((size_t)(M * n) * 2); + const int rc = launch(r, { T(up_bf16(x), RAD_BF16, { M, n }), + T(up_bf16(mu), RAD_BF16, { n }), + T(up_bf16(sv), RAD_BF16, { n }), T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("mode", norm ? "norm" : "denorm"), + PI("var", var), PF("eps", 1e-4), PS("dtype", "bf16") }); + const std::string nm = fmt("chan_stats_bf16 %s var %d", norm ? "norm" : "denorm", var); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + const float sd = var ? bfr(std::sqrt(sv[(size_t)c] + 1e-4f)) : sv[(size_t)c]; + const float xv = x[(size_t)(row * n + c)]; + want[(size_t)(row * n + c)] = norm ? bfr(bfr(xv - mu[(size_t)c]) / sd) + : bfr(bfr(xv * sd) + mu[(size_t)c]); + } + check(nm, down_bf16(dy, want.size()), want, 8e-3); + } +} + +/* The f32 form over bf16 and f32 statistics: exact against the host's f32 steps. */ +void chan_stats_f32_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "chan_stats_f32"); + if (!r) { ok("chan_stats_f32", false, "row absent"); return; } + const int64_t M = 19, n = 128; + for (const bool wf32 : { false, true }) + for (const bool norm : { false, true }) + for (const int var : { 0, 1 }) { + std::vector x = randv((size_t)(M * n), 2.0f), mu = randv((size_t)n, 0.5f); + std::vector sv((size_t)n); + for (int64_t c = 0; c < n; ++c) sv[(size_t)c] = 0.3f + 0.0137f * (float)c; + if (!wf32) { + for (float& v : mu) v = bfr(v); + for (float& v : sv) v = bfr(v); + } + void* dy = dalloc((size_t)(M * n) * 4); + const uint32_t wd = wf32 ? RAD_F32 : RAD_BF16; + const int rc = launch(r, { T(up_f32(x), RAD_F32, { M, n }), + T(wf32 ? up_f32(mu) : up_bf16(mu), wd, { n }), + T(wf32 ? up_f32(sv) : up_bf16(sv), wd, { n }), + T(dy, RAD_F32, { M, n }) }, + { PI("M", M), PI("n", n), PS("mode", norm ? "norm" : "denorm"), + PI("var", var), PF("eps", 1e-4), PS("dtype", "f32") }); + const std::string nm = fmt("chan_stats_f32 %s stats %s var %d", norm ? "norm" : "denorm", + wf32 ? "f32" : "bf16", var); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + volatile float e = sv[(size_t)c] + 1e-4f; + const float sd = var ? std::sqrt((float)e) : sv[(size_t)c]; + const float xv = x[(size_t)(row * n + c)]; + volatile float t = norm ? xv - mu[(size_t)c] : xv * sd; + want[(size_t)(row * n + c)] = norm ? (float)t / sd : (float)t + mu[(size_t)c]; + } + /* f32 against f32 (rel() would round the answer to bf16 first): each error over + * the size of the terms it came from, |x s| + |mean| or |x - mean| / s, since a + * result near zero is a cancellation. The device's square root may sit an ulp from + * the host's. */ + const std::vector got = down_f32(dy, want.size()); + double worst = 0; + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < n; ++c) { + const size_t e = (size_t)(row * n + c); + const double sd = var ? std::sqrt((double)sv[(size_t)c] + 1e-4) : sv[(size_t)c]; + const double xv = x[e], m = mu[(size_t)c]; + const double size = norm ? (std::fabs(xv) + std::fabs(m)) / sd + : std::fabs(xv * sd) + std::fabs(m); + worst = std::max(worst, std::fabs((double)got[e] - want[e]) / + std::max(1e-30, size)); + } + ok(fmt("%s (max error over the terms %.3g, bound 5e-7)", nm.c_str(), worst).c_str(), + worst <= 5e-7); + } +} + +/* Host attention over q rows [q0, q1) against key rows [k0, k1), causal on relative indices. */ +static void host_attn(const std::vector& q, const std::vector& k, + const std::vector& v, int64_t qld, int64_t kld, int64_t nh, + int64_t nkv, int64_t hd, int64_t q0, int64_t q1, int64_t k0, int64_t k1, + bool causal, std::vector* out) { + const float sc = 1.0f / std::sqrt((float)hd); + for (int64_t i = q0; i < q1; ++i) + for (int64_t h = 0; h < nh; ++h) { + const int64_t kh = h / (nh / nkv); + const int64_t je = causal ? std::min(k1, k0 + (i - q0) + 1) : k1; + std::vector s; + double mx = -1e30; + for (int64_t j = k0; j < je; ++j) { + double d = 0; + for (int64_t t = 0; t < hd; ++t) + d += (double)q[(size_t)(i * qld + h * hd + t)] * k[(size_t)(j * kld + kh * hd + t)]; + s.push_back(d * sc); + mx = std::max(mx, s.back()); + } + double sum = 0; + for (double& e : s) { e = std::exp(e - mx); sum += e; } + for (int64_t t = 0; t < hd; ++t) { + double a = 0; + for (int64_t j = k0; j < je; ++j) + a += s[(size_t)(j - k0)] * v[(size_t)(j * kld + kh * hd + t)]; + (*out)[(size_t)(i * nh * hd + h * hd + t)] = s.empty() ? 0.0f : (float)(a / sum); + } + } +} + +/* Two entries, queries and keys of different counts, at gqa 1 and 4, causal and not. */ +void attn_cross_cases(const Plugin& pl, int64_t hd) { + const std::string row = fmt("attn_cross_h%lld_bf16", (long long)hd); + const RadKernelInfo* r = find(pl, row.c_str()); + if (!r) { ok(row.c_str(), false, "row absent"); return; } + for (const int64_t gqa : { 1, 4 }) + for (const int causal : { 0, 1 }) { + const int64_t nkv = 2, nh = nkv * gqa, Q = 150, K = 211; + const std::vector cuq = { 0, 70, 150 }, cuk = { 0, 123, 211 }; + std::vector q = randv((size_t)(Q * nh * hd), 1.0f); + std::vector k = randv((size_t)(K * nkv * hd), 1.0f), v = randv((size_t)(K * nkv * hd), 1.0f); + for (float& x : q) x = bfr(x); + for (float& x : k) x = bfr(x); + for (float& x : v) x = bfr(x); + void* dout = dalloc((size_t)(Q * nh * hd) * 2); + const int rc = launch(r, { T(up_bf16(q), RAD_BF16, { Q, nh * hd }), + T(up_bf16(k), RAD_BF16, { K, nkv * hd }), + T(up_bf16(v), RAD_BF16, { K, nkv * hd }), + T(up_i32(cuq), RAD_I32, { 3 }), T(up_i32(cuk), RAD_I32, { 3 }), + T(dout, RAD_BF16, { Q, nh * hd }) }, + { PI("M", Q), PI("head_dim", hd), PI("gqa", gqa), + PI("causal", causal), PS("dtype", "bf16") }); + const std::string nm = fmt("%s gqa %lld causal %d", row.c_str(), (long long)gqa, causal); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(Q * nh * hd)); + for (int e = 0; e < 2; ++e) + host_attn(q, k, v, nh * hd, nkv * hd, nh, nkv, hd, cuq[(size_t)e], cuq[(size_t)e + 1], + cuk[(size_t)e], cuk[(size_t)e + 1], causal != 0, &want); + check(nm, down_bf16(dout, want.size()), want, 2e-2); + } +} + +/* attn_dense at the grouped h256 and h512 rows, causal and not, over two segments: a text + * encoder's prompt (Gemma 4's sliding and global layers). */ +void attn_dense_gqa_cases(const Plugin& pl) { + for (const int64_t hd : { 256, 512 }) + for (const int64_t gqa : { 2, 4, 8, 16 }) { + /* 16 query heads a KV head run on the gqa-8 row, two workgroups a KV head. */ + const std::string row = fmt("attn_dense_h%lld_gqa%lld_bf16", (long long)hd, + (long long)std::min(gqa, 8)); + const RadKernelInfo* r = find(pl, row.c_str()); + if (!r) { ok(row.c_str(), false, "row absent"); continue; } + for (const int causal : { 0, 1 }) { + const int64_t nkv = 2, nh = nkv * gqa, total = 173; + const std::vector cu = { 0, 101, 173 }; + std::vector q = randv((size_t)(total * nh * hd), 1.0f); + std::vector k = randv((size_t)(total * nkv * hd), 1.0f); + std::vector v = randv((size_t)(total * nkv * hd), 1.0f); + for (float& x : q) x = bfr(x); + for (float& x : k) x = bfr(x); + for (float& x : v) x = bfr(x); + void* dout = dalloc((size_t)(total * nh * hd) * 2); + const int rc = launch(r, { T(up_bf16(q), RAD_BF16, { total, nh * hd }), + T(up_bf16(k), RAD_BF16, { total, nkv * hd }), + T(up_bf16(v), RAD_BF16, { total, nkv * hd }), + T(up_i32(cu), RAD_I32, { 3 }), + T(dout, RAD_BF16, { total, nh * hd }) }, + { PI("M", total), PI("head_dim", hd), PI("gqa", gqa), + PI("causal", causal), PS("dtype", "bf16"), + PI("max_seqlen", 101) }); + const std::string nm = fmt("%s gqa %lld causal %d", row.c_str(), (long long)gqa, + causal); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(total * nh * hd)); + for (int e = 0; e < 2; ++e) + host_attn(q, k, v, nh * hd, nkv * hd, nh, nkv, hd, cu[(size_t)e], + cu[(size_t)e + 1], cu[(size_t)e], cu[(size_t)e + 1], causal != 0, &want); + check(nm, down_bf16(dout, want.size()), want, 2e-2); + } + } +} + +/* One wide head over every pixel, 384 and 512. */ +void attn_wide_cases(const Plugin& pl) { + for (const int64_t hd : { 384, 512 }) { + const std::string row = fmt("attn_dense_h%lld_bf16", (long long)hd); + const RadKernelInfo* r = find(pl, row.c_str()); + if (!r) { ok(row.c_str(), false, "row absent"); continue; } + const int64_t N = 300; + const std::vector cu = { 0, (int32_t)N }; + std::vector qkv = randv((size_t)(N * 3 * hd), 1.0f); + for (float& x : qkv) x = bfr(x); + void* d = up_bf16(qkv); + auto col = [&](int c) { + RadTensor t = T((char*)d + c * hd * 2, RAD_BF16, { N, hd }); + t.stride[0] = 3 * hd; + return t; + }; + void* dout = dalloc((size_t)(N * hd) * 2); + const int rc = launch(r, { col(0), col(1), col(2), T(up_i32(cu), RAD_I32, { 2 }), + T(dout, RAD_BF16, { N, hd }) }, + { PI("M", N), PI("head_dim", hd), PI("gqa", 1), PI("causal", 0), + PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok(row.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector q((size_t)(N * hd)), k((size_t)(N * hd)), v((size_t)(N * hd)); + for (int64_t i = 0; i < N; ++i) + for (int64_t t = 0; t < hd; ++t) { + q[(size_t)(i * hd + t)] = qkv[(size_t)(i * 3 * hd + t)]; + k[(size_t)(i * hd + t)] = qkv[(size_t)(i * 3 * hd + hd + t)]; + v[(size_t)(i * hd + t)] = qkv[(size_t)(i * 3 * hd + 2 * hd + t)]; + } + std::vector want((size_t)(N * hd)); + host_attn(q, k, v, hd, hd, 1, 1, hd, 0, N, 0, N, false, &want); + check(row + " one head over 300 rows", down_bf16(dout, want.size()), want, 2e-2); + } +} + +/* rms_mod's zero-centred gain rounded once (Krea 2) and its gainless LayerNorm (FLUX), gated + * and not, plain and quantised. */ +void rms_mod_forms(const Plugin& pl) { + for (const bool quant : { false, true }) { + const char* name = quant ? "rms_mod_quant_fp8_bf16" : "rms_mod_bf16"; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); continue; } + const int64_t n = 3072, M = 7, segs = 3, pitch = 3 * n; + const std::vector cu = { 0, 2, 5, 7 }; + for (const bool layer : { false, true }) + for (const int gated : { 0, 1 }) { + std::vector x = randv((size_t)(M * n), 2.0f), y = randv((size_t)(M * n), 1.0f); + std::vector tab = randv((size_t)(segs * pitch), 0.5f), w = randv((size_t)n, 0.1f); + for (float& v : x) v = bfr(v + 0.7f); + for (float& v : y) v = bfr(v); + for (float& v : tab) v = bfr(v); + for (float& v : w) v = bfr(v); + void* dx = up_bf16(x); + void* dtab = up_bf16(tab); + RadTensor tg = T(dtab, RAD_BF16, { segs, n }); + tg.stride[0] = pitch; + RadTensor ts2 = T((char*)dtab + n * 2, RAD_BF16, { segs, 2 * n }); + ts2.stride[0] = pitch; + RadTensor ty = T(up_bf16(y), RAD_BF16, { M, n }); + if (!gated) { absent(ty); absent(tg); } + RadTensor tw = T(up_bf16(w), RAD_BF16, { n }); + if (layer) absent(tw); + void* dz = dalloc((size_t)(M * n) * 2); + void* dq = dalloc((size_t)(M * n)); + void* dqs = dalloc((size_t)(M * n / 128) * 4); + std::vector args = { ty, tg, ts2, tw, T(up_i32(cu), RAD_I32, { 4 }), + T(dx, RAD_BF16, { M, n }) }; + std::vector ps = { PI("M", M), PI("n", n), PF("eps", 1e-6), + PI("gated", gated), PS("dtype", "bf16") }; + if (layer) ps.push_back(PS("norm", "layer")); + else { ps.push_back(PF("wadd", 1.0)); ps.push_back(PI("norm_once", 1)); } + if (quant) { + args.push_back(T(dq, RAD_F8E4M3, { M, n })); + args.push_back(T(dqs, RAD_F32, { M, n / 128 })); + ps.push_back(PI("group", 128)); + } + args.push_back(T(dz, RAD_BF16, { M, n })); + const std::string nm = fmt("%s %s gated %d", name, layer ? "layer" : "zero-centred", + gated); + const int rc = launch(r, args, ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * n)); + for (int64_t row = 0; row < M; ++row) { + const int64_t e = seq_of(cu, row); + float* xv = x.data() + row * n; + if (gated) + for (int64_t i = 0; i < n; ++i) + xv[i] = bfr(xv[i] + bfr(tab[(size_t)(e * pitch + i)] * y[(size_t)(row * n + i)])); + float mu = 0.0f; + if (layer) { + for (int64_t i = 0; i < n; ++i) mu += xv[i]; + mu /= (float)n; + } + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) ss += (xv[i] - mu) * (xv[i] - mu); + const float rs = 1.0f / std::sqrt(ss / (float)n + 1e-6f); + for (int64_t i = 0; i < n; ++i) { + const float vv = xv[i] - mu; + const float n2 = layer ? bfr(vv * rs) : bfr(vv * rs * (w[(size_t)i] + 1.0f)); + const float sc = bfr(1.0f + tab[(size_t)(e * pitch + 2 * n + i)]); + want[(size_t)(row * n + i)] = bfr(bfr(n2 * sc) + tab[(size_t)(e * pitch + n + i)]); + } + } + check(nm + " norm", down_bf16(dz, want.size()), want, 4e-3); + if (quant) { + std::vector qb((size_t)(M * n)); + st_memcpy(qb.data(), dq, qb.size(), hipMemcpyDeviceToHost); + const std::vector qs = down_f32(dqs, (size_t)(M * n / 128)); + std::vector deq((size_t)(M * n)); + for (size_t i = 0; i < deq.size(); ++i) deq[i] = rad_fp8e4m3_to_f32(qb[i]) * qs[i / 128]; + check(nm + " codes", deq, want, 4e-2); + } + } + } +} + +/* timestep_embed's round 2 (1000 bf16(t)) and 3 (bf16(1000 bf16(t))): the angle from each. */ +void timestep_round_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "timestep_embed_bf16"); + if (!r) { ok("timestep_embed_bf16", false, "row absent"); return; } + const std::vector t = { 0.9876543f, 0.5f, 0.0123457f }; + for (const int round : { 2, 3 }) { + void* dy = dalloc((size_t)(3 * 256) * 2); + const int rc = launch(r, { T(up_f32(t), RAD_F32, { 3 }), T(dy, RAD_BF16, { 3, 256 }) }, + { PI("M", 3), PI("n", 256), PF("scale", 1000.0), + PF("max_period", 10000.0), PI("round", round), + PS("dtype", "bf16") }); + const std::string nm = fmt("timestep_embed_bf16 round %d", round); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want(3 * 256); + for (int m = 0; m < 3; ++m) { + const float tt = round == 3 ? bfr(1000.0f * bfr(t[(size_t)m])) : 1000.0f * bfr(t[(size_t)m]); + for (int i = 0; i < 128; ++i) { + const float f = std::exp(-std::log(10000.0f) * (float)i / 128.0f); + want[(size_t)(m * 256 + i)] = bfr(std::cos(tt * f)); + want[(size_t)(m * 256 + 128 + i)] = bfr(std::sin(tt * f)); + } + } + check(nm, down_bf16(dy, want.size()), want, 2e-2); + } +} + +} /* namespace g3 */ + +/* ================================================================== LTX-2 + * rope_split, head_gate and ltx_guide against the host's arithmetic in libref's order: the rotary's + * device sincosf within a few bf16 steps, the gate exact, the guided step's f64 deviations. */ +namespace ltx { + +using namespace au; + +static double lin01(int64_t i, int64_t steps) { + if (steps <= 1) return 0.0; + const double st = 1.0 / (double)(steps - 1); + return i < steps / 2 ? st * (double)i : 1.0 - st * (double)(steps - 1 - i); +} + +/* The video's 3-axis rotary over a rank's second and third heads of 4096 (two pairs padded), and + * a 1-axis one over 2048, each over a column slice of a fused [q | k | v] row. */ +void rope_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "rope_split"); + if (!r) { ok("rope_split", false, "row absent"); return; } + struct Case { int64_t nh, hd, dim, nd, h0; const char* mx; }; + for (const Case cs : { Case{ 2, 128, 4096, 3, 1, "20 2048 2048" }, + Case{ 32, 64, 2048, 1, 0, "20" } }) { + const int64_t M = 77, w = cs.nh * cs.hd, ld = 3 * w + 8; + std::vector x = randv((size_t)(M * ld), 1.0f); + for (float& v : x) v = bfr(v); + std::vector pos((size_t)(cs.nd * M)); + for (int64_t d = 0; d < cs.nd; ++d) + for (int64_t i = 0; i < M; ++i) + pos[(size_t)(d * M + i)] = d == 0 ? (float)i / 24.0f : (float)(32 * (i % 9) + 16); + void* dx = up_bf16(x); + RadTensor tx = T((char*)dx + w * 2, RAD_BF16, { M, w }); + tx.stride[0] = ld; + const int rc = launch(r, { tx, T(up_f32(pos), RAD_F32, { cs.nd, M }) }, + { PI("M", M), PI("n_head", cs.nh), PI("head_dim", cs.hd), + PI("dim", cs.dim), PI("n_dims", cs.nd), PF("theta", 10000.0), + PS("max", cs.mx), PI("head0", cs.h0), PS("dtype", "bf16") }); + const std::string nm = fmt("rope_split %lld axes over %lld", (long long)cs.nd, + (long long)cs.dim); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + float mx[3] = { 20.0f, 2048.0f, 2048.0f }; + const int64_t P2 = cs.dim / 2, steps = P2 / cs.nd, pad = P2 - steps * cs.nd, half = cs.hd / 2; + std::vector want((size_t)(M * w)), got((size_t)(M * w)); + const std::vector all = down_bf16(dx, (size_t)(M * ld)); + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < w; ++c) { + want[(size_t)(i * w + c)] = x[(size_t)(i * ld + w + c)]; + got[(size_t)(i * w + c)] = all[(size_t)(i * ld + w + c)]; + } + for (int64_t i = 0; i < M; ++i) + for (int64_t h = 0; h < cs.nh; ++h) + for (int64_t k = 0; k < half; ++k) { + const int64_t p = (cs.h0 + h) * half + k; + if (p < pad) continue; + const int64_t j = p - pad, d = j % cs.nd, f = j / cs.nd; + const float fr = (float)(std::pow(10000.0, lin01(f, steps)) * M_PI / 2.0); + const float g = pos[(size_t)(d * M + i)] / mx[d]; + const float ang = (2.0f * g - 1.0f) * fr; + const float co = (float)std::cos((double)ang), si = (float)std::sin((double)ang); + const float x1 = x[(size_t)(i * ld + w + h * cs.hd + k)]; + const float x2 = x[(size_t)(i * ld + w + h * cs.hd + half + k)]; + want[(size_t)(i * w + h * cs.hd + k)] = bfr(x1 * co - x2 * si); + want[(size_t)(i * w + h * cs.hd + half + k)] = bfr(x2 * co + x1 * si); + } + check(nm, got, want, 4e-3); + /* The columns either side of the slice are untouched. */ + int64_t moved = 0; + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < w; ++c) moved += all[(size_t)(i * ld + c)] != x[(size_t)(i * ld + c)]; + ok(fmt("%s leaves the neighbouring columns", nm.c_str()).c_str(), moved == 0); + } +} + +void gate_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "head_gate"); + if (!r) { ok("head_gate", false, "row absent"); return; } + const int64_t M = 53, nh = 32, hd = 128, gld = nh + 3; + std::vector x = randv((size_t)(M * nh * hd), 2.0f), g = randv((size_t)(M * gld), 3.0f); + for (float& v : x) v = bfr(v); + for (float& v : g) v = bfr(v); + void* dx = up_bf16(x); + RadTensor tg = T(up_bf16(g), RAD_BF16, { M, nh }); + tg.stride[0] = gld; + const int rc = launch(r, { tg, T(dx, RAD_BF16, { M, nh * hd }) }, + { PI("M", M), PI("n_head", nh), PI("head_dim", hd), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("head_gate", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * nh * hd)); + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < nh * hd; ++c) { + const float sg = bfr(1.0f / (1.0f + std::exp(-g[(size_t)(i * gld + c / hd)]))); + want[(size_t)(i * nh * hd + c)] = bfr(x[(size_t)(i * nh * hd + c)] * bfr(2.0f * sg)); + } + const std::vector got = down_bf16(dx, want.size()); + ok("head_gate 32 heads of 128, logits at a wider pitch", + differ(got, want) <= (int64_t)(want.size() / 1000), fmt("%lld differ", (long long)differ(got, want))); +} + +/* Every pass bound with the rescale on, then CFG alone: x after one step against the host's f64 + * deviations. */ +void guide_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "ltx_guide"); + if (!r) { ok("ltx_guide", false, "row absent"); return; } + const int64_t M = 3000, n = 128; + for (const bool full : { true, false }) { + std::vector x = randv((size_t)(M * n), 1.0f); + std::vector> v(4); + for (auto& e : v) { + e = randv((size_t)(M * n), 1.0f); + for (float& q : e) q = bfr(q); + } + const std::vector sc = full ? std::vector{ 3.0f, 1.0f, 3.0f, 0.7f } + : std::vector{ 7.0f, 0.0f, 1.0f, 0.0f }; + const std::vector sh = { 0.909375f, 0.725f }; + void* dx = up_f32(x); + void* st = dalloc((size_t)8200 * 4); + const int rc = launch(r, { T(up_bf16(v[0]), RAD_BF16, { M, n }), + T(up_bf16(v[1]), RAD_BF16, { M, n }), + full ? T(up_bf16(v[2]), RAD_BF16, { M, n }) : RadTensor{}, + full ? T(up_bf16(v[3]), RAD_BF16, { M, n }) : RadTensor{}, + T(up_f32(sc), RAD_F32, { 4 }), T(up_f32(sh), RAD_F32, { 2 }), + T(st, RAD_F32, { 8200 }), T(dx, RAD_F32, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + const std::string nm = full ? "ltx_guide every pass, rescaled" : "ltx_guide CFG alone"; + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const float sig = sh[0], dt = sh[1] - sh[0]; + std::vector x0c((size_t)(M * n)), g((size_t)(M * n)), want((size_t)(M * n)); + for (size_t e = 0; e < want.size(); ++e) { + const float xc = x[e] - v[0][e] * sig; + float gv = xc; + gv = gv + (sc[0] - 1.0f) * (xc - (x[e] - v[1][e] * sig)); + if (full) gv = gv + sc[1] * (xc - (x[e] - v[2][e] * sig)); + if (full) gv = gv + (sc[2] - 1.0f) * (xc - (x[e] - v[3][e] * sig)); + x0c[e] = xc; + g[e] = gv; + } + float fac = 1.0f; + if (sc[3] > 0.0f) { + auto sd = [&](const std::vector& a) { + double m = 0.0, q = 0.0; + for (float e : a) m += e; + m /= (double)a.size(); + for (float e : a) q += ((double)e - m) * ((double)e - m); + return (float)std::sqrt(q / (double)(a.size() - 1)); + }; + fac = sd(x0c) / sd(g); + } + const float kept = (float)(1.0 - (double)sc[3]); + for (size_t e = 0; e < want.size(); ++e) { + float gv = g[e]; + if (sc[3] > 0.0f) gv = sc[3] * (gv * fac) + kept * gv; + want[e] = x[e] + dt * ((x[e] - gv) / sig); + } + /* An f32 latent: compared in f32 (check() holds a bf16 answer). */ + const std::vector got = down_f32(dx, want.size()); + double e = 0.0, w2 = 0.0; + for (size_t i = 0; i < want.size(); ++i) { + e += ((double)got[i] - want[i]) * ((double)got[i] - want[i]); + w2 += (double)want[i] * want[i]; + } + const double rl = std::sqrt(e / w2); + ok(fmt("%s (rel_l2 %.3g, bound 1e-6)", nm.c_str(), rl).c_str(), rl <= 1e-6); + } +} + + +/* ---- LTX-2's VAE, audio VAE and vocoder ops, each against a host port of its libref function + * (libref/ref_ltx.cpp). Copies are compared bit for bit; sums the kernel orders differently to a + * relative L2. */ + +/* The div form with SiLU (the VAE's norm) at bf16, and the rsqrt form interleaving 4 layers and + * scaled (the connectors') at f32 in and bf16 out. */ +void pixel_norm_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "pixel_norm"); + if (!r) { ok("pixel_norm", false, "row absent"); return; } + struct Case { int64_t rows, n, L; bool div, silu, xf32; float eps, mult; }; + for (const Case c : { Case{ 333, 512, 1, true, true, false, 1e-8f, 1.0f }, + Case{ 4 * 37, 96, 4, false, false, true, 1e-6f, 2.75f } }) { + std::vector x = randv((size_t)(c.rows * c.n), 2.0f); + void* dx = c.xf32 ? up_f32(x) : up_bf16(x); + void* dy = dalloc((size_t)(c.rows * c.n) * 2); + std::vector ps = { PI("M", c.rows / c.L), PI("n", c.n), PF("eps", c.eps), + PS("form", c.div ? "div" : "rsqrt"), PS("dtype", "bf16") }; + if (c.silu) ps.push_back(PS("act", "silu")); + if (c.L > 1) ps.push_back(PI("ileave", c.L)); + if (c.mult != 1.0f) ps.push_back(PF("mult", c.mult)); + const int rc = launch(r, { T(dx, c.xf32 ? RAD_F32 : RAD_BF16, { c.rows, c.n }), + T(dy, RAD_BF16, { c.rows / c.L, c.n * c.L }) }, + ps); + const std::string nm = fmt("pixel_norm %s%s over %lld, %lld layers interleaved", + c.div ? "div" : "rsqrt", c.silu ? " silu" : "", (long long)c.n, + (long long)c.L); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(c.rows * c.n)); + for (int64_t q = 0; q < c.rows; ++q) { + float ss = 0.0f; + for (int64_t i = 0; i < c.n; ++i) { + const float v = x[(size_t)(q * c.n + i)]; + ss += bfr(v * v); + } + const float v = bfr(bfr(ss / (float)c.n) + c.eps); + const float s = c.div ? bfr(std::sqrt(v)) : bfr(1.0f / std::sqrt(v)); + for (int64_t i = 0; i < c.n; ++i) { + const float xv = x[(size_t)(q * c.n + i)]; + float z = bfr(c.div ? xv / s : xv * s); + if (c.silu) z = bfr(z / (1.0f + std::exp(-z))); + if (c.mult != 1.0f) z = bfr(z * c.mult); + want[(size_t)((q / c.L) * c.n * c.L + i * c.L + q % c.L)] = z; + } + } + check(nm, down_bf16(dy, want.size()), want, 4e-3); + } +} + +/* The upsampler's 2 x 2 x 2 and 1 x 2 x 2 depth to space; the downsampler's space to depth, copy + * with a frame prepended, and the residual's group mean added into y. */ +void resample_cases(const Plugin& pl) { + const RadKernelInfo* rd = find(pl, "d2s3d"); + const RadKernelInfo* rs = find(pl, "s2d3d"); + if (!rd || !rs) { ok("d2s3d / s2d3d", false, "row absent"); return; } + struct D { int64_t st, drop; }; + for (const D dd : { D{ 2, 1 }, D{ 1, 0 }, D{ 2, 0 } }) { + const int64_t st = dd.st, drop = dd.drop; + const int64_t T0 = 3, H = 5, W = 7, C = 24, P = st * 4; + const int64_t To = T0 * st - drop, M = To * H * 2 * W * 2; + std::vector x = randv((size_t)(T0 * H * W * C * P), 1.0f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)((M + 5) * C) * 2); + const int rc = launch(rd, { T(dx, RAD_BF16, { T0 * H * W, C * P }), + TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + T(dy, RAD_BF16, { M + 5, C }) }, + { PI("M", M), PI("C", C), PI("st", st), PI("sh", 2), PI("sw", 2), + PI("drop", drop), PS("dtype", "bf16") }); + const std::string nm = fmt("d2s3d %lld x 2 x 2, %lld dropped", (long long)st, (long long)drop); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * C)); + const int64_t Ho = H * 2, Wo = W * 2; + for (int64_t q = 0; q < M; ++q) { + const int64_t tt = q / (Ho * Wo) + drop, ii = (q / Wo) % Ho, jj = q % Wo; + const int64_t t = tt / st, aa = tt % st, i = ii / 2, b = ii % 2, j = jj / 2, d = jj % 2; + for (int64_t c = 0; c < C; ++c) + want[(size_t)(q * C + c)] = + x[(size_t)(((t * H + i) * W + j) * C * P + ((c * st + aa) * 2 + b) * 2 + d)]; + } + const std::vector got = down_bf16(dy, want.size()); + ok(nm.c_str(), differ(got, want) == 0, fmt("%lld differ", (long long)differ(got, want))); + } + struct S { int64_t tpre, group; bool mean, add; }; + for (const S c : { S{ 1, 1, false, false }, S{ 1, 4, true, true } }) { + const int64_t T0 = 5, H = 6, W = 4, C = 16, P = C * 8, Co = c.mean ? P / c.group : P; + const int64_t To = (T0 + c.tpre) / 2, M = To * (H / 2) * (W / 2); + std::vector x = randv((size_t)(T0 * H * W * C), 1.0f), y0 = randv((size_t)(M * Co), 1.0f); + void* dx = up_bf16(x); + void* dy = up_bf16(y0); + std::vector ps = { PI("M", T0 * H * W), PI("C", C), PI("st", 2), PI("sh", 2), + PI("sw", 2), PI("tpre", c.tpre), PI("group", c.group), + PS("mode", c.mean ? "mean" : "copy"), PI("add", c.add), + PS("dtype", "bf16") }; + const int rc = launch(rs, { T(dx, RAD_BF16, { T0 * H * W, C }), + TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + T(dy, RAD_BF16, { M, Co }) }, + ps); + const std::string nm = fmt("s2d3d %s, a frame prepended%s", c.mean ? "group mean" : "copy", + c.add ? ", added" : ""); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(M * Co)); + const int64_t Ho = H / 2, Wo = W / 2; + for (int64_t q = 0; q < M; ++q) { + const int64_t t = q / (Ho * Wo), i = (q / Wo) % Ho, j = q % Wo; + auto val = [&](int64_t p) { + const int64_t d = p % 2, b = (p / 2) % 2, aa = (p / 4) % 2, cc = p / 8; + const int64_t v = t * 2 + aa, tr = v < c.tpre ? v : v - c.tpre; + return x[(size_t)(((tr * H + i * 2 + b) * W + j * 2 + d) * C + cc)]; + }; + for (int64_t o = 0; o < Co; ++o) { + float v; + if (!c.mean) { + v = val(o); + } else { + float s = 0.0f; + for (int64_t p = o * c.group; p < (o + 1) * c.group; ++p) s += val(p); + v = bfr(s / (float)c.group); + } + want[(size_t)(q * Co + o)] = c.add ? bfr(y0[(size_t)(q * Co + o)] + v) : v; + } + } + const std::vector got = down_bf16(dy, want.size()); + ok(nm.c_str(), differ(got, want) == 0, fmt("%lld differ", (long long)differ(got, want))); + } +} + +/* An RGB image to 4 x 4 patches and back to bytes, both orders. */ +void patch_cases(const Plugin& pl) { + const RadKernelInfo* rp = find(pl, "pix_patch"); + const RadKernelInfo* r8 = find(pl, "patch_pix8"); + if (!rp || !r8) { ok("pix_patch / patch_pix8", false, "row absent"); return; } + for (const bool wh : { true, false }) { + const int64_t H = 24, W = 40, C = 3, p = 4, w = W / p, cols = w * C * p * p; + std::vector x = randv((size_t)(H * W * C), 1.2f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)(H / p * cols) * 2); + const std::vector ps = { PI("M", H / p), PI("p", p), PI("C", C), + PS("order", wh ? "wh" : "hw"), PS("dtype", "bf16") }; + int rc = launch(rp, { T(dx, RAD_BF16, { H, W * C }), T(dy, RAD_BF16, { H / p, cols }) }, ps); + const char* ord = wh ? "wh" : "hw"; + if (rc != RAD_OK) { ok(fmt("pix_patch %s", ord).c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(H / p * cols)); + auto col = [&](int64_t c, int64_t ph, int64_t pw) { + return c * p * p + (wh ? pw * p + ph : ph * p + pw); + }; + for (int64_t yy = 0; yy < H; ++yy) + for (int64_t xx = 0; xx < W; ++xx) + for (int64_t c = 0; c < C; ++c) + want[(size_t)((yy / p) * cols + (xx / p) * C * p * p + col(c, yy % p, xx % p))] = + x[(size_t)((yy * W + xx) * C + c)]; + const std::vector got = down_bf16(dy, want.size()); + ok(fmt("pix_patch %s", ord).c_str(), differ(got, want) == 0, + fmt("%lld differ", (long long)differ(got, want))); + void* d8 = dalloc((size_t)(H * W * C)); + RadTensor t8 = T(d8, RAD_U8, { H, W * C }); + rc = launch(r8, { T(dy, RAD_BF16, { H / p, cols }), t8 }, ps); + if (rc != RAD_OK) { ok(fmt("patch_pix8 %s", ord).c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector g8((size_t)(H * W * C)), w8(g8.size()); + st_memcpy(g8.data(), d8, g8.size(), hipMemcpyDeviceToHost); + for (size_t e = 0; e < w8.size(); ++e) { + const float cl = std::min(std::max(x[e], -1.0f), 1.0f); + const float u = std::min(std::max(bfr(bfr(cl / 2.0f) + 0.5f), 0.0f), 1.0f); + w8[e] = (uint8_t)std::nearbyint(u * 255.0f); + } + ok(fmt("patch_pix8 %s is pix_patch's inverse in bytes", ord).c_str(), differ(g8, w8) == 0, + fmt("%lld differ", (long long)differ(g8, w8))); + } +} + +/* diffusers' tiled decodes. The boxes of a 29 x 33 grid at tile 16, stride 14 (bands of 16, 15 + * and 1 rows, 16, 16 and 5 columns) and of the diffusion decoder's 61 x 68 x 100 grid under + * `intervals` (two time bands, the last 8 tail cells longer; one row band; a 12-column remnant + * merged); a 2 x 4 x 3 box out of a volume; and tiles stitched to bytes against a host + * transcription of the in-place blends (libref/ref_ltx.cpp): five frames over a 9 x 10 grid at + * tile 4, stride 3, and 9 cells of 2 frames in two time bands at tile 6, stride 4, rule + * `intervals`, its spatial remnant merged. */ +struct HostCut { + int64_t tile, stride, min; + bool iv; + int64_t count(int64_t L) const { + if (iv && L <= tile) return 1; + int64_t n = (L + stride - 1) / stride; + while (iv && n > 1 && L - (n - 1) * stride < min) --n; + return n; + } + int64_t len(int64_t L, int64_t k) const { + return k == count(L) - 1 ? L - k * stride : std::min(tile, L - k * stride); + } +}; + +/* Neighborhood attention against a host transcription: two heads of 64 over a 6 x 9 x 13 volume + * with the decoder's 3 x 5 x 5 window, and with its 11 x 11 x 11 one, which the 6 frames clamp. */ +void na3d_cases(const Plugin& pl) { + const RadKernelInfo* rn = find(pl, "attn_na3d_h64"); + if (!rn) { ok("attn_na3d", false, "row absent"); return; } + struct K { int64_t kt, kh, kw; }; + for (const K w : { K{ 3, 5, 5 }, K{ 11, 11, 11 } }) { + const int64_t T0 = 6, H = 9, W = 13, V = T0 * H * W, hd = 64, nhd = 2, D = nhd * hd; + std::vector q = randv((size_t)(V * D), 1.0f), k = randv((size_t)(V * D), 1.0f), + v = randv((size_t)(V * D), 1.0f); + for (auto* x : { &q, &k, &v }) + for (auto& e : *x) e = bfr(e); + void* dq = up_bf16(q); + void* dk = up_bf16(k); + void* dv = up_bf16(v); + void* dout = dalloc((size_t)(V * D) * 2); + const int rc = launch(rn, { T(dq, RAD_BF16, { V, D }), T(dk, RAD_BF16, { V, D }), + T(dv, RAD_BF16, { V, D }), + TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + T(dout, RAD_BF16, { V, D }) }, + { PI("M", V), PI("head_dim", hd), PI("kt", w.kt), PI("kh", w.kh), + PI("kw", w.kw), PS("dtype", "bf16") }); + const std::string nm = fmt("attn_na3d %lld x %lld x %lld over 6 x 9 x 13", (long long)w.kt, + (long long)w.kh, (long long)w.kw); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const int64_t nt = std::min(w.kt, T0), nh = std::min(w.kh, H), nw = std::min(w.kw, W); + auto start = [](int64_t c, int64_t n, int64_t L) { + return std::min(std::max(c - n / 2, 0), L - n); + }; + std::vector want((size_t)(V * D)); + for (int64_t r = 0; r < V; ++r) + for (int64_t h = 0; h < nhd; ++h) { + const int64_t t = r / (H * W), i = (r / W) % H, j = r % W; + const int64_t t0 = start(t, nt, T0), i0 = start(i, nh, H), j0 = start(j, nw, W); + std::vector sc; + std::vector keys; + double mx = -1e300; + for (int64_t a1 = t0; a1 < t0 + nt; ++a1) + for (int64_t b1 = i0; b1 < i0 + nh; ++b1) + for (int64_t c1 = j0; c1 < j0 + nw; ++c1) { + const int64_t key = (a1 * H + b1) * W + c1; + double d = 0; + for (int64_t e = 0; e < hd; ++e) + d += (double)q[(size_t)(r * D + h * hd + e)] * k[(size_t)(key * D + h * hd + e)]; + d /= 8.0; + sc.push_back(d); + keys.push_back(key); + mx = std::max(mx, d); + } + double sum = 0; + for (double& x : sc) { x = std::exp(x - mx); sum += x; } + for (int64_t e = 0; e < hd; ++e) { + double acc = 0; + for (size_t n = 0; n < keys.size(); ++n) acc += sc[n] * v[(size_t)(keys[n] * D + h * hd + e)]; + want[(size_t)(r * D + h * hd + e)] = (float)(acc / sum); + } + } + check(nm.c_str(), down_bf16(dout, want.size()), want, 8e-3); + } +} + +/* A 3 x 4 x 5 volume's voxel coordinates. */ +void vol_index_cases(const Plugin& pl) { + const RadKernelInfo* rv = find(pl, "vol_index"); + if (!rv) { ok("vol_index", false, "row absent"); return; } + const int64_t T0 = 3, H = 4, W = 5, n = T0 * H * W + 4; + void* dy = dalloc((size_t)(3 * n) * 4); + const int rcode = launch(rv, { TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + T(dy, RAD_I32, { 3, n }) }, + { PI("M", n) }); + if (rcode != RAD_OK) { ok("vol_index 3 x 4 x 5", false, "rc " + std::to_string(rcode)); return; } + std::vector got((size_t)(3 * n)); + st_memcpy(got.data(), dy, got.size() * 4, hipMemcpyDeviceToHost); + int64_t bad = 0; + for (int64_t m = 0; m < T0 * H * W; ++m) + bad += got[(size_t)m] != m / (H * W) || got[(size_t)(n + m)] != (m / W) % H || + got[(size_t)(2 * n + m)] != m % W; + ok("vol_index 3 x 4 x 5", bad == 0, fmt("%lld differ", (long long)bad)); +} + +void tile_cases(const Plugin& pl) { + const RadKernelInfo* rg = find(pl, "tile_grid"); + const RadKernelInfo* rc = find(pl, "tile_crop"); + const RadKernelInfo* rs = find(pl, "tile_stitch"); + if (!rg || !rc || !rs) { ok("tile_grid / tile_crop / tile_stitch", false, "row absent"); return; } + struct G { int32_t T, H, W; std::vector ps; HostCut cs, ct; int64_t tail, n; const char* nm; }; + const std::vector grids = { + { 3, 29, 33, { PI("M", 12), PI("tile", 16), PI("stride", 14) }, + { 16, 14, 1, false }, { 1 << 30, 1 << 30, 1, false }, 0, 12, "tile_grid 29 x 33" }, + { 61, 68, 100, { PI("M", 4), PI("tile", 96), PI("stride", 88), PS("rule", "intervals"), + PI("min", 13), PI("tile_t", 40), PI("stride_t", 28), PI("min_t", 6), + PI("tail", 8) }, + { 96, 88, 13, true }, { 40, 28, 6, true }, 8, 4, "tile_grid intervals 61 x 68 x 100" }, + }; + for (const G& g : grids) { + void* dy = dalloc((size_t)(g.n * 8) * 4); + const int rcode = launch(rg, { TI32({ 3 }, { g.T, g.H, g.W }), T(dy, RAD_I32, { g.n, 8 }) }, + g.ps); + if (rcode != RAD_OK) { ok(g.nm, false, "rc " + std::to_string(rcode)); continue; } + std::vector got((size_t)(g.n * 8)), want((size_t)(g.n * 8), 0); + st_memcpy(got.data(), dy, got.size() * 4, hipMemcpyDeviceToHost); + const int64_t nt = g.ct.count(g.T), ni = g.cs.count(g.H), nj = g.cs.count(g.W); + const int64_t count = nt * ni * nj; + for (int64_t k = 0; k < std::min(count, g.n); ++k) { + const int64_t kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj; + const int64_t v[8] = { g.ct.len(g.T, kt) + (kt == nt - 1 ? g.tail : 0), g.cs.len(g.H, i), + g.cs.len(g.W, j), kt * g.ct.stride, i * g.cs.stride, + j * g.cs.stride, k, count }; + for (int e = 0; e < 8; ++e) want[(size_t)(k * 8 + e)] = (int32_t)v[e]; + } + ok(g.nm, got == want, "rows differ"); + } + { + const int64_t T0 = 5, H = 7, W = 9, C = 6, t = 2, h = 4, w = 3, t0 = 2, y0 = 2, x0 = 5; + std::vector x = randv((size_t)(T0 * H * W * C), 1.0f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)((t * h * w + 3) * C) * 2); + const int rcode = launch(rc, { T(dx, RAD_BF16, { T0 * H * W, C }), + TI32({ 3 }, { (int32_t)T0, (int32_t)H, (int32_t)W }), + TI32({ 6 }, { (int32_t)t, (int32_t)h, (int32_t)w, (int32_t)t0, + (int32_t)y0, (int32_t)x0 }), + T(dy, RAD_BF16, { t * h * w + 3, C }) }, + { PI("M", t * h * w + 3), PI("C", C), PS("dtype", "bf16") }); + if (rcode != RAD_OK) { + ok("tile_crop 2 x 4 x 3 at (2, 2, 5)", false, "rc " + std::to_string(rcode)); + } else { + std::vector want((size_t)(t * h * w * C)); + for (int64_t r = 0; r < t * h * w; ++r) { + const int64_t f = r / (h * w), i = (r / w) % h, j = r % w; + for (int64_t c = 0; c < C; ++c) + want[(size_t)(r * C + c)] = + x[(size_t)((((t0 + f) * H + y0 + i) * W + x0 + j) * C + c)]; + } + const std::vector got = down_bf16(dy, want.size()); + ok("tile_crop 2 x 4 x 3 at (2, 2, 5)", differ(got, want) == 0, + fmt("%lld differ", (long long)differ(got, want))); + } + } + struct S { int64_t T, H, W; HostCut cs, ct; int64_t sc, st, f0, nf; bool wh; const char* rule; }; + const std::vector stitches = { + { 5, 9, 10, { 4, 3, 1, false }, { 1 << 30, 1 << 30, 1, false }, 2, 1, 1, 3, true, "stride" }, + { 5, 9, 10, { 4, 3, 1, false }, { 1 << 30, 1 << 30, 1, false }, 2, 1, 1, 3, false, "stride" }, + { 9, 7, 13, { 6, 4, 4, true }, { 6, 4, 2, true }, 2, 2, 0, 17, true, "intervals" }, + }; + for (const S& k : stitches) { + const int64_t p = 2, C = 3, P = C * p * p; + const int64_t nt = k.ct.count(k.T), ni = k.cs.count(k.H), nj = k.cs.count(k.W); + int64_t hs = 0, ws = 0; + for (int64_t i = 0; i < ni; ++i) hs += k.cs.len(k.H, i); + for (int64_t j = 0; j < nj; ++j) ws += k.cs.len(k.W, j); + auto frames = [&](int64_t kt) { return k.st * k.ct.len(k.T, kt) - (kt == 0 ? k.st - 1 : 0); }; + int64_t ftot = 0; + for (int64_t kt = 0; kt < nt; ++kt) ftot += frames(kt); + const int64_t rows = ftot * k.sc * k.sc * hs * ws; + std::vector x = randv((size_t)(rows * P), 1.3f); + for (auto& v : x) v = bfr(v); + auto offset = [&](int64_t kt, int64_t i, int64_t j) { + int64_t before = 0, left = 0, above = 0; + for (int64_t q = 0; q < kt; ++q) before += frames(q); + for (int64_t q = 0; q < j; ++q) left += k.cs.len(k.W, q); + for (int64_t q = 0; q < i; ++q) above += k.cs.len(k.H, q); + return k.sc * k.sc * (before * hs * ws + frames(kt) * (above * ws + k.cs.len(k.H, i) * left)); + }; + auto R = [&](int64_t kt, int64_t i, int64_t j, int64_t f, int64_t yy, int64_t xx, int64_t c) { + const int64_t wp = k.cs.len(k.W, j) * k.sc, hp = k.cs.len(k.H, i) * k.sc; + const int64_t row = offset(kt, i, j) + (f * hp + yy / p) * wp + xx / p; + const int64_t col = c * p * p + (k.wh ? (xx % p) * p + yy % p : (yy % p) * p + xx % p); + return x[(size_t)(row * P + col)]; + }; + auto mix = [&](float va, float vb, int64_t q, int64_t e) { + const float wa = (float)(1.0 - (double)q / (double)e), wb = (float)((double)q / (double)e); + return bfr(bfr(va * wa) + bfr(vb * wb)); + }; + const int64_t Hpx = k.H * k.sc * p, Wpx = k.W * k.sc * p, s = k.cs.stride * k.sc * p; + const int64_t E = (k.cs.tile - k.cs.stride) * k.sc * p, Et = (k.ct.tile - k.ct.stride) * k.st; + const int64_t band = k.ct.stride * k.st; + auto Sv = [&](int64_t kt, int64_t f, int64_t Yp, int64_t Xp, int64_t c) { + const int64_t i = std::min(Yp / s, ni - 1), ly = Yp - i * s; + const int64_t j = std::min(Xp / s, nj - 1), lx = Xp - j * s; + const int64_t ha = i > 0 ? k.cs.len(k.H, i - 1) * k.sc * p : 0; + const int64_t ev = i > 0 ? std::min(std::min(ha, k.cs.len(k.H, i) * k.sc * p), E) : 0; + const int64_t wl = j > 0 ? k.cs.len(k.W, j - 1) * k.sc * p : 0; + const int64_t eh = j > 0 ? std::min(std::min(wl, k.cs.len(k.W, j) * k.sc * p), E) : 0; + const bool vb = i > 0 && ly < ev, hb = j > 0 && lx < eh; + float V = R(kt, i, j, f, ly, lx, c); + if (vb) { + float A = R(kt, i - 1, j, f, ha - ev + ly, lx, c); + if (hb) A = mix(R(kt, i - 1, j - 1, f, ha - ev + ly, wl - eh + lx, c), A, lx, eh); + V = mix(A, V, ly, ev); + } + if (hb) { + float L = R(kt, i, j - 1, f, ly, wl - eh + lx, c); + if (vb) L = mix(R(kt, i - 1, j - 1, f, ha - ev + ly, wl - eh + lx, c), L, ly, ev); + V = mix(L, V, lx, eh); + } + return V; + }; + std::vector want((size_t)(k.nf * Hpx * Wpx * C)); + for (int64_t r = 0; r < k.nf * Hpx; ++r) { + const int64_t n = k.f0 + r / Hpx, Yp = r % Hpx; + const int64_t kt = std::min((n + k.st - 1) / band, nt - 1); + const int64_t f = n - (kt == 0 ? 0 : kt * band - (k.st - 1)); + const int64_t et = kt > 0 ? std::min(std::min(frames(kt - 1), frames(kt)), Et) : 0; + for (int64_t Xp = 0; Xp < Wpx; ++Xp) + for (int64_t c = 0; c < C; ++c) { + float v = Sv(kt, f, Yp, Xp, c); + if (kt > 0 && f < et) v = mix(Sv(kt - 1, frames(kt - 1) - et + f, Yp, Xp, c), v, f, et); + const float cl = std::min(std::max(v, -1.0f), 1.0f); + const float u = std::min(std::max(bfr(bfr(cl / 2.0f) + 0.5f), 0.0f), 1.0f); + want[(size_t)((r * Wpx + Xp) * C + c)] = (uint8_t)std::nearbyint(u * 255.0f); + } + } + void* dx = up_bf16(x); + void* dy = dalloc(want.size()); + std::vector ps = { PI("M", k.nf * Hpx), PI("tile", k.cs.tile), PI("stride", k.cs.stride), + PS("rule", k.rule), PI("min", k.cs.min), PI("scale", k.sc), + PI("scale_t", k.st), PI("p", p), PI("C", C), + PS("order", k.wh ? "wh" : "hw"), PS("dtype", "bf16") }; + if (nt > 1 || k.ct.tile < (1 << 30)) { + ps.push_back(PI("tile_t", k.ct.tile)); + ps.push_back(PI("stride_t", k.ct.stride)); + ps.push_back(PI("min_t", k.ct.min)); + } + const int rcode = launch(rs, { T(dx, RAD_BF16, { rows, P }), + TI32({ 3 }, { (int32_t)k.T, (int32_t)k.H, (int32_t)k.W }), + TI32({ 1 }, { (int32_t)k.f0 }), + T(dy, RAD_U8, { k.nf * Hpx, Wpx * C }) }, + ps); + const std::string nm = fmt("tile_stitch %s %lld x %lld x %lld %s, frames %lld..%lld", k.rule, + (long long)k.T, (long long)k.H, (long long)k.W, k.wh ? "wh" : "hw", + (long long)k.f0, (long long)(k.f0 + k.nf - 1)); + if (rcode != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rcode)); continue; } + std::vector got(want.size()); + st_memcpy(got.data(), dy, got.size(), hipMemcpyDeviceToHost); + ok(nm.c_str(), differ(got, want) == 0, fmt("%lld differ", (long long)differ(got, want))); + } +} + +/* The extender's MelSTFT shape (512-point DFT, hop 128, 64 mel bins) over two channels, bf16. */ +void stft_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "stft_logmel"); + if (!r) { ok("stft_logmel", false, "row absent"); return; } + const int64_t nfft = 512, hop = 128, nm = 64, ch = 2, F = nfft / 2 + 1, S = 37 * hop; + const int64_t frames = S / hop; + std::vector x = randv((size_t)(S * ch), 0.5f); + std::vector basis((size_t)(2 * F * nfft)), mel((size_t)(nm * F)); + for (int64_t k = 0; k < F; ++k) + for (int64_t j = 0; j < nfft; ++j) { + const double wnd = 0.5 - 0.5 * std::cos(2.0 * M_PI * (double)j / (double)nfft); + const double ang = -2.0 * M_PI * (double)(k * j) / (double)nfft; + basis[(size_t)(k * nfft + j)] = (float)(wnd * std::cos(ang)); + basis[(size_t)((F + k) * nfft + j)] = (float)(wnd * std::sin(ang)); + } + for (float& v : mel) v = std::fabs(rnd()) * 0.05f; + void* dx = up_bf16(x); + void* db = up_bf16(basis); + void* dm = up_bf16(mel); + void* dy = dalloc((size_t)(frames * ch * nm) * 2); + const int rc = launch(r, { T(dx, RAD_BF16, { S, ch }), T(db, RAD_BF16, { 2 * F, 1, nfft }), + T(dm, RAD_BF16, { nm, F }), T(dy, RAD_BF16, { frames, ch * nm }) }, + { PI("M", frames), PI("hop", hop), PI("nfft", nfft), PI("n_mel", nm), + PI("ch", ch), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("stft_logmel", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(frames * ch * nm)); + for (int64_t t = 0; t < frames; ++t) + for (int64_t h = 0; h < ch; ++h) { + std::vector mag((size_t)F); + for (int64_t k = 0; k < F; ++k) { + float re = 0.0f, im = 0.0f; + for (int64_t j = 0; j < nfft; ++j) { + const int64_t s = t * hop + j - (nfft - hop); + if (s < 0) continue; + re += basis[(size_t)(k * nfft + j)] * x[(size_t)(s * ch + h)]; + im += basis[(size_t)((F + k) * nfft + j)] * x[(size_t)(s * ch + h)]; + } + re = bfr(re); + im = bfr(im); + mag[(size_t)k] = bfr(std::sqrt(bfr(bfr(re * re) + bfr(im * im)))); + } + for (int64_t m = 0; m < nm; ++m) { + float s = 0.0f; + for (int64_t k = 0; k < F; ++k) s += mel[(size_t)(m * F + k)] * mag[(size_t)k]; + want[(size_t)(t * ch * nm + h * nm + m)] = std::log(std::max(bfr(s), bfr(1e-5f))); + } + } + check("stft_logmel 512-point, hop 128, 64 mel bins, 2 channels", down_bf16(dy, want.size()), + want, 5e-3); +} + +/* A decoder's volume at a scale and a constant, off a device geometry. */ +void int_affine_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "int_affine"); + if (!r) { ok("int_affine", false, "row absent"); return; } + RadTensor x = TI32({ 4 }, { 21, 16, 24, 30 }); + void* dy = dalloc(5 * 4); + const int rc = launch(r, { x, T(dy, RAD_I32, { 5 }) }, + { PI("M", 5), PS("src", "0 1 2 -1 3"), PS("mul", "8 2 2 0 4"), + PS("add", "-7 0 0 1 -3") }); + if (rc != RAD_OK) { ok("int_affine", false, "rc " + std::to_string(rc)); return; } + const std::vector got = down_i32(dy, 5); + ok("int_affine (8 F - 7, 2 h, 2 w, 1, 4 n - 3)", + got == std::vector({ 161, 32, 48, 1, 117 })); +} + +/* 16 kHz to 48 kHz over two channels, f32 out as the vocoder's waveform. */ +void bwe_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "bwe_up"); + if (!r) { ok("bwe_up", false, "row absent"); return; } + const int64_t S = 400, ch = 2, ratio = 3, O = S * ratio; + std::vector x = randv((size_t)(S * ch), 0.8f), res = randv((size_t)(O * ch), 0.5f); + void* dx = up_bf16(x); + void* dr = up_bf16(res); + void* dy = dalloc((size_t)(O * ch) * 4); + const int rc = launch(r, { T(dx, RAD_BF16, { S, ch }), T(dr, RAD_BF16, { O, ch }), + T(dy, RAD_F32, { O, ch }) }, + { PI("M", O), PI("ratio", ratio), PI("ch", ch), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("bwe_up", false, "rc " + std::to_string(rc)); return; } + const int64_t w = (int64_t)std::ceil(6.0 / 0.99), K = 2 * w * ratio + 1; + std::vector f((size_t)K); + for (int64_t n = 0; n < K; ++n) { + const float u = ((float)n / (float)ratio - (float)w) * 0.99f; + const float uc = std::min(std::max(u, -6.0f), 6.0f); + const float cw = std::cos(uc * (float)M_PI / 6.0f / 2.0f); + const float pu = (float)M_PI * u; + const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu; + f[(size_t)n] = bfr(sinc * (cw * cw) * 0.99f / (float)ratio); + } + std::vector want((size_t)(O * ch)); + for (int64_t o = 0; o < O; ++o) + for (int64_t h = 0; h < ch; ++h) { + const int64_t u = o + 2 * w * ratio; + float acc = 0.0f; + for (int64_t k = u % ratio; k < K; k += ratio) { + const int64_t s = std::min(std::max((u - k) / ratio - w, 0), S - 1); + acc += f[(size_t)k] * x[(size_t)(s * ch + h)]; + } + const float up = bfr((float)ratio * bfr(acc)); + const float v = bfr(res[(size_t)(o * ch + h)] + up); + want[(size_t)(o * ch + h)] = std::min(std::max(v, -1.0f), 1.0f); + } + check("bwe_up 3x over 2 channels, f32 out", down_f32(dy, want.size()), want, 4e-3); +} + +/* conv2d_nhwc's three paddings (same, down, causal) on the implicit GEMM, and causal on the direct + * kernel (the audio VAE's 2-channel input). */ +void conv2d_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "conv2d_nhwc_bf16"); + if (!r) { ok("conv2d_nhwc_bf16", false, "row absent"); return; } + struct Case { const char* pad; int64_t cin, cout, k, stride, H, W; }; + for (const Case c : { Case{ "same", 64, 96, 3, 1, 9, 13 }, Case{ "down", 32, 64, 3, 2, 10, 14 }, + Case{ "causal", 64, 128, 3, 1, 11, 8 }, + Case{ "causal", 2, 32, 3, 1, 12, 16 } }) { + const bool down = !std::strcmp(c.pad, "down"), causal = !std::strcmp(c.pad, "causal"); + const int64_t pt = down ? 0 : causal ? c.k - 1 : c.k / 2, pb = down ? 1 : causal ? 0 : c.k / 2; + const int64_t pl0 = down ? 0 : c.k / 2, pr = down ? 1 : c.k / 2; + const int64_t Ho = (c.H + pt + pb - c.k) / c.stride + 1, Wo = (c.W + pl0 + pr - c.k) / c.stride + 1; + const int64_t K = c.cin * c.k * c.k; + std::vector x = randv((size_t)(c.H * c.W * c.cin), 1.0f); + std::vector w = randv((size_t)(c.cout * K), 1.5f / std::sqrt((float)K)); + std::vector b = randv((size_t)c.cout, 0.3f); + for (float& e : w) e = bfr(e); + const std::vector ps = { PI("M", Ho), PI("cin", c.cin), PI("cout", c.cout), + PI("k", c.k), PI("stride", c.stride), PS("pad", c.pad), + PI("up", 1), PS("dtype", "bf16") }; + const std::string nm = fmt("conv2d_nhwc_bf16 pad %s, %lld -> %lld, stride %lld", c.pad, + (long long)c.cin, (long long)c.cout, (long long)c.stride); + void* dw = stored_weight(r, ps, w, c.cout, K, nm.c_str()); + void* dx = up_bf16(x); + void* db = up_bf16(b); + void* dy = dalloc((size_t)(Ho * Wo * c.cout) * 2); + const int rc = launch(r, { T(dx, RAD_BF16, { c.H, c.W * c.cin }), T(dw, RAD_BF16, { c.cout, K }), + T(db, RAD_BF16, { c.cout }), T(dy, RAD_BF16, { Ho, Wo * c.cout }) }, + ps); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + std::vector want((size_t)(Ho * Wo * c.cout)); + for (int64_t oy = 0; oy < Ho; ++oy) + for (int64_t ox = 0; ox < Wo; ++ox) + for (int64_t o = 0; o < c.cout; ++o) { + double acc = 0.0; + for (int64_t kh = 0; kh < c.k; ++kh) + for (int64_t kw = 0; kw < c.k; ++kw) { + const int64_t iy = oy * c.stride + kh - pt, ix = ox * c.stride + kw - pl0; + if (iy < 0 || iy >= c.H || ix < 0 || ix >= c.W) continue; + for (int64_t ci = 0; ci < c.cin; ++ci) + acc += (double)w[(size_t)(((o * c.cin + ci) * c.k + kh) * c.k + kw)] * + x[(size_t)((iy * c.W + ix) * c.cin + ci)]; + } + want[(size_t)((oy * Wo + ox) * c.cout + o)] = bfr((float)acc + b[(size_t)o]); + } + check(nm, down_bf16(dy, want.size()), want, 5e-3); + } + /* One output channel into the second half of wider rows (an audio decoder's conv_out writing + * a channel's mel bins into its own columns): the slice right, the other half untouched. */ + { + const int64_t cin = 128, H = 9, W = 16, k = 3, K = cin * k * k, P = 2 * W; + std::vector x = randv((size_t)(H * W * cin), 1.0f); + std::vector w = randv((size_t)K, 1.5f / std::sqrt((float)K)), b = { 0.25f }; + for (float& e : w) e = bfr(e); + const std::vector ps = { PI("M", H), PI("cin", cin), PI("cout", 1), PI("k", k), + PI("stride", 1), PS("pad", "causal"), PI("up", 1), + PS("dtype", "bf16") }; + const char* nm = "conv2d_nhwc_bf16 causal 128 -> 1 into a column slice"; + void* dw = stored_weight(r, ps, w, 1, K, nm); + std::vector pre((size_t)(H * P), -7.5f); + void* dy = up_bf16(pre); + RadTensor ty = T((uint16_t*)dy + W, RAD_BF16, { H, W }); + ty.stride[0] = P; + const int rc = launch(r, { T(up_bf16(x), RAD_BF16, { H, W * cin }), T(dw, RAD_BF16, { 1, K }), + T(up_bf16(b), RAD_BF16, { 1 }), ty }, + ps); + if (rc != RAD_OK) ok(nm, false, "rc " + std::to_string(rc)); + else { + const std::vector got = down_bf16(dy, (size_t)(H * P)); + std::vector want((size_t)(H * W)), sl((size_t)(H * W)); + bool kept = true; + for (int64_t oy = 0; oy < H; ++oy) + for (int64_t ox = 0; ox < W; ++ox) { + double acc = 0.0; + for (int64_t kh = 0; kh < k; ++kh) + for (int64_t kw = 0; kw < k; ++kw) { + const int64_t iy = oy + kh - (k - 1), ix = ox + kw - k / 2; + if (iy < 0 || ix < 0 || ix >= W) continue; + for (int64_t ci = 0; ci < cin; ++ci) + acc += (double)w[(size_t)((ci * k + kh) * k + kw)] * + x[(size_t)((iy * W + ix) * cin + ci)]; + } + want[(size_t)(oy * W + ox)] = bfr((float)acc + b[0]); + sl[(size_t)(oy * W + ox)] = got[(size_t)(oy * P + W + ox)]; + kept = kept && got[(size_t)(oy * P + ox)] == -7.5f; + } + check(nm, sl, want, 5e-3); + ok("conv2d_nhwc_bf16 leaves the columns outside the slice alone", kept); + } + } +} + +} /* namespace ltx */ + /* ---- a video latent upscaler's ops, at MiniMax-H3's shapes --------------------------------------- * * The upscaler runs a 37-frame clip at its 42 x 24 latent (the source) and at 84 x 48 (the @@ -6886,14 +8085,18 @@ std::vector conv_rows(const Vol& v, int64_t M, int64_t want) { /* libref's conv3d_ndhwc at output row r: the products (exact in f32) summed in f64, rounded to f32, * the bias added in f32 and rounded; with a residual, that plus the residual, rounded. `wt` is the - * weight tap-major, as the row stores it. */ + * weight tap-major, as the row stores it. `v` is the input's volume; `tpad` 1 replicates the edge + * frames, 2 is causal with `tpre` more first frames in front. */ void conv3d_row(const std::vector& x, int64_t cin, const std::vector& wt, const std::vector& b, const float* res, const Vol& v, int64_t cout, - int64_t r, float* out) { + int64_t r, float* out, int tpad = 0, int64_t tpre = 0) { const int64_t HW = v.H * v.W, t = r / HW, y = (r / v.W) % v.H, xx = r % v.W; std::vector acc((size_t)cout, 0.0); for (int64_t tap = 0; tap < 27; ++tap) { - const int64_t nt = t + tap / 9 - 1, ny = y + (tap / 3) % 3 - 1, nx = xx + tap % 3 - 1; + int64_t nt = t + tap / 9 - 1; + if (tpad == 1) nt = std::min(std::max(nt, 0), v.T - 1); + else if (tpad == 2) nt = std::max(nt - 1 - tpre, 0); + const int64_t ny = y + (tap / 3) % 3 - 1, nx = xx + tap % 3 - 1; if (nt < 0 || nt >= v.T || ny < 0 || ny >= v.H || nx < 0 || nx >= v.W) continue; const float* xr = &x[(size_t)((nt * HW + ny * v.W + nx) * cin)]; for (int64_t o = 0; o < cout; ++o) { @@ -6919,18 +8122,23 @@ struct ConvCase { int64_t xpad, ypad, yextra; /* pitch padding, output rows past the volume */ int64_t mshort; /* the M parameter this short of T H W: the volume's rows are written */ int64_t sample; /* rows checked besides the faces; 0 every row */ + int tpad = 0; /* 0 zero, 1 replicate, 2 causal frame padding */ + int64_t tpre = 0; /* causal: more first frames in front, as many more output frames */ }; void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { const Vol& v = c.v; - const int64_t vol = v.T * v.H * v.W, M = vol, K = 27 * c.cin; + const Vol vo{ v.T + c.tpre, v.H, v.W }; + const int64_t vol = v.T * v.H * v.W, M = vo.T * v.H * v.W, K = 27 * c.cin; const int64_t ldx = c.cin + c.xpad, ldy = c.cout + c.ypad, yrows = M + c.yextra; - const std::string nm = fmt("conv3d_ndhwc_bf16 %s: %lld -> %lld at %lld x %lld, %lld frames%s%s%s", + static const char* const kTpad[] = { "", ", replicate", ", causal" }; + const std::string nm = fmt("conv3d_ndhwc_bf16 %s: %lld -> %lld at %lld x %lld, %lld frames%s%s%s%s", c.what, (long long)c.cin, (long long)c.cout, (long long)v.H, (long long)v.W, (long long)v.T, c.res == 2 ? ", res in place" : c.res ? ", res" : "", c.bf32 ? ", f32 bias" : "", - c.xpad || c.ypad || c.yextra || c.mshort ? ", pitched" : ""); + c.xpad || c.ypad || c.yextra || c.mshort ? ", pitched" : "", + kTpad[c.tpad]); g_seed = 0xc03dull + (uint64_t)(c.cin * 131 + c.cout * 7 + v.T); std::vector x = randv((size_t)(vol * c.cin), 1.0f); std::vector w = randv((size_t)(c.cout * K), 1.5f / std::sqrt((float)K)); @@ -6945,6 +8153,8 @@ void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { wt[(size_t)((o * 27 + t) * c.cin + ci)] = w[(size_t)((o * c.cin + ci) * 27 + t)]; std::vector ps = { PI("M", M - c.mshort), PI("cin", c.cin), PI("cout", c.cout), PI("k", 3), PI("kt", 3), PS("dtype", "bf16") }; + if (c.tpad) ps.push_back(PS("tpad", c.tpad == 1 ? "replicate" : "causal")); + if (c.tpre) ps.push_back(PI("tpre", c.tpre)); void* dw = stored_weight(r, ps, w, c.cout, K, nm.c_str()); void* dx = up_rows(x, vol, c.cin, ldx, vol); std::vector bb = b; @@ -6969,7 +8179,7 @@ void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { const std::vector yb = down_u16(dy, (size_t)(yrows * ldy)); std::vector rows; if (c.sample) { - rows = conv_rows(v, M, c.sample); + rows = conv_rows(vo, M, c.sample); } else { for (int64_t i = 0; i < M; ++i) rows.push_back(i); } @@ -6977,7 +8187,7 @@ void conv3d_case(const RadKernelInfo* r, const ConvCase& c) { par_for((int64_t)rows.size(), [&](int64_t i) { const int64_t rr = rows[(size_t)i]; conv3d_row(x, c.cin, wt, b, c.res ? &res[(size_t)(rr * c.cout)] : nullptr, v, c.cout, rr, - &want[(size_t)i * c.cout]); + &want[(size_t)i * c.cout], c.tpad, c.tpre); for (int64_t o = 0; o < c.cout; ++o) got[(size_t)i * c.cout + o] = h_bf16(yb[(size_t)(rr * ldy + o)]); }); @@ -7005,6 +8215,12 @@ void conv3d_cases(const Plugin& pl) { ConvCase{ "one frame", Vol{ 1, 9, 13 }, 16, 24, 2, true, 0, 8, 2, 0, 0 }, ConvCase{ "one row", Vol{ 4, 1, 21 }, 8, 8, 0, false, 8, 0, 0, 0, 0 }, ConvCase{ "two tiles a tap", Vol{ 2, 11, 6 }, 128, 136, 2, false, 0, 0, 7, 0, 0 }, + /* LTX-2's VAE: the decoder's replicated frames, the encoder's causal ones (its + * 48-channel patchified input off the 64-channel tile), and the temporal + * downsampler's first frame prepended once more. */ + ConvCase{ "replicate", Vol{ 4, 6, 10 }, 128, 128, 2, false, 0, 0, 3, 0, 0, 1, 0 }, + ConvCase{ "causal", Vol{ 5, 7, 9 }, 48, 128, 0, false, 8, 0, 0, 0, 0, 2, 0 }, + ConvCase{ "causal, one more frame", Vol{ 3, 6, 6 }, 64, 64, 1, true, 0, 8, 4, 0, 0, 2, 1 }, }) conv3d_case(r, c); /* A 15 s clip at the target size: 411264 rows, the largest volume the model runs. */ @@ -7083,6 +8299,13 @@ void group_norm_cases(const Plugin& pl) { G{ "f32 in, bf16 out", 101, 512, 32, true, false, false, 0, false, false, -3.0f, 16 }, G{ "one row", 1, 512, 32, false, false, false, 1, true, false, 0.0f, 0 }, G{ "64 channels", 1000, 64, 8, false, true, false, 0, true, false, 0.0f, 8 }, + /* Groups of 4 channels (four-channel chunks): the FLUX.2 VAE's 128 channels in 32 + * groups at a 256 x 256 image, bf16 with SiLU, then f32 rows over a large mean. */ + G{ "4 channels a group", 256 * 256, 128, 32, false, false, false, 0, true, false, 0.0f, 0 }, + /* Groups of 2 channels (two-channel chunks): a 64-wide latent upsampler in 32 groups. */ + G{ "2 channels a group", 48 * 8 * 8, 64, 32, false, false, false, 0, true, false, 0.0f, 0 }, + G{ "2 channels a group, f32 rows", 777, 64, 32, true, true, true, 2, false, false, 5.0f, 8 }, + G{ "4 channels a group, f32", 777, 128, 32, true, true, true, 2, false, false, 20.0f, 8 }, }) { const int64_t M = g.M, n = g.n, ld = n + g.pad, rows = M + 2; const std::string nm = fmt("group_norm %s: %lld x %lld in %lld groups", g.what, @@ -12030,12 +13253,13 @@ static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blo st_memcpy(right, (char*)scratch + 128 + need, 128, hipMemcpyDeviceToHost); for (int i = 0; i < 128; ++i) guards = guards && left[i] == 0xa5 && right[i] == 0xa5; } - const char* pairing = std::getenv("RADIANCE_MLA_PAIR"); + /* Paired tiles walk the union of both tables up to 520 entries (kUnionBlocks), past it the + * tables position by position. */ + const bool positional = std::strstr(name, "matrix") && heads % 16 && blocks > 520; ok(fmt("MLA M=%lld heads=%lld blocks=%lld%s%s%s split/unsplit, max error %.8g", (long long)rows, (long long)heads, (long long)blocks, fill == MlaFill::topk ? fmt(" topk:%lld", (long long)swaps).c_str() : "", - form ? fmt(" pinned form %d", form).c_str() : "", - pairing && std::strstr(name, "matrix") ? fmt(" pairing %s", pairing).c_str() : "", + form ? fmt(" pinned form %d", form).c_str() : "", positional ? " positional pairing" : "", max_error) .c_str(), matches); @@ -12169,8 +13393,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, PI("blocks", blocks), PI("block_size", bs), PF("scale", 0.0625), PS("dtype", "bf16") }; std::vector base, rule; - auto run = [&](const char* name, int form, const char* label, bool positional = false) { - ScopedEnv pairing("RADIANCE_MLA_PAIR", positional ? "pos" : nullptr); + auto run = [&](const char* name, int form, const char* label) { const RadKernelInfo* r = find(pl, name); if (!r) { std::printf(" %-34s row absent\n", label); @@ -12235,28 +13458,15 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, ulp = std::max(ulp, std::abs(ord(got[i]) - ord(base[i]))); abs_err = std::max(abs_err, std::fabs(x - y)); } - /* The two key loads stage the same values: their outputs must agree to the bit. The - * pairings walk request r of a pair in the same order (equal at one split) and r+1 in - * another. */ - std::string same = + /* The two key loads stage the same values: their outputs must agree to the bit. */ + const std::string same = form == 1 && !rule.empty() ? (rule == got ? ", bit-identical to form 0" : ", DIFFERS from form 0") : ""; - if (positional && !rule.empty()) { - size_t differ[2] = { 0, 0 }; - float apart = 0; - for (size_t i = 0; i < got.size(); ++i) - if (got[i] != rule[i]) { - ++differ[(i / (size_t)(heads * D)) % 2]; - apart = std::max(apart, std::fabs(h_bf16(got[i]) - h_bf16(rule[i]))); - } - same = fmt(", vs union %zu/%zu values differ (r/r+1), max abs %.3g", differ[0], - differ[1], apart); - } std::snprintf(diff, sizeof diff, "%smax %d ulp, max abs %.3g%s", finite ? "" : "NONFINITE ", ulp, abs_err, same.c_str()); } - if (form == 0 && !positional) rule = got; + if (form == 0) rule = got; std::printf(" %-34s %10.2f us %7.2f TFLOP/s %s\n", label, us, flops / (us * 1e6), diff); if (form >= 0 && pl.mla_stats) { /* One more launch with the conflict counters on, outside the timing. */ @@ -12276,10 +13486,13 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, std::printf(" mla_attn_matrix_bf16 serves heads a multiple of 8 only\n"); return; } - if (heads % 16) { + /* Tables of up to 520 entries (kUnionBlocks) pair by their union, wider ones by position. */ + if (heads % 16 && blocks <= 520) { run("mla_attn_matrix_bf16", 0, "matrix paired, union, vector load"); run("mla_attn_matrix_bf16", 1, "matrix paired, union, element load"); - run("mla_attn_matrix_bf16", 0, "matrix paired, positional, vector", true); + } else if (heads % 16) { + run("mla_attn_matrix_bf16", 0, "matrix paired, positional, vector"); + run("mla_attn_matrix_bf16", 1, "matrix paired, positional, element"); } else { run("mla_attn_matrix_bf16", 0, "matrix 16 heads, vector load"); run("mla_attn_matrix_bf16", 1, "matrix 16 heads, element load"); @@ -12449,41 +13662,6 @@ static void kda_check(const Plugin& pl, const char* mode, bool cold, int accepte dlclose(ref); } -/* Saves the given switches on construction and restores them on destruction; pin() sets each - * to its value or, for nullptr, back to what the caller had. */ -struct EnvPins { - std::vector names; - std::vector saved; - std::vector had; - explicit EnvPins(std::initializer_list n) : names(n) { - for (const char* k : names) { - const char* v = std::getenv(k); - had.push_back(v != nullptr); - saved.push_back(v ? v : ""); - } - } - void pin(std::initializer_list values) { - size_t i = 0; - for (const char* v : values) { - if (v) - setenv(names[i], v, 1); - else if (had[i]) - setenv(names[i], saved[i].c_str(), 1); - else - unsetenv(names[i]); - ++i; - } - } - ~EnvPins() { - for (size_t i = 0; i < names.size(); ++i) { - if (had[i]) - setenv(names[i], saved[i].c_str(), 1); - else - unsetenv(names[i]); - } - } -}; - /* One launch, then a 200 ms warm-up and `iters` timed launches (st_time_us: --cold gives the * median of flushed launches). -1 when the row refuses the arguments. */ static double form_us(const RadKernelInfo* r, RadArgs* a, int iters) { @@ -12510,15 +13688,16 @@ static std::vector fetch_bytes(const void* d, size_t bytes) { return v; } -/* kda_update at GLM's TP8 shape (eight heads, 128 x 128 state per head), every form held byte for - * byte to the one-row kernel on shuffle sums (RADIANCE_KDA_FORM=old) over the output and the - * whole state buffer, the slots no sequence names included: prefill of M tokens as one sequence - * per candidate and as three anchored sequences (one cold, one unseated), and the verify step of - * eight sequences with up to six candidates, per candidate and anchored, the anchored one after a - * replay of the accepted prefix. `iters` below zero compares only, as a case. */ -static void kda_forms(const Plugin& pl, int64_t M, int iters) { +/* kda_update at GLM's TP8 shape (eight heads, 128 x 128 state per head): prefill of M tokens as + * one sequence per candidate and as three anchored sequences (one cold, one unseated), and the + * verify step of eight sequences with up to six candidates, per candidate and anchored, the + * anchored one after a replay of the accepted prefix. Timed, or with `iters` below zero held to + * libref over the output and the whole state buffer, the slots no sequence names included, as a + * case: the lane reductions sum in another order than libref's loops, so f32 state within + * 2e-5 + 2e-5 |x| and bf16 output within one rounding step. */ +static void kda_perf(const Plugin& pl, int64_t M, int iters) { const bool check = iters < 0; - if (iters == 0) iters = 50; + if (iters <= 0) iters = 50; if (M < 1 || M > 65535) { std::printf("--perfkda: 1 <= M <= 65535\n"); return; @@ -12528,6 +13707,23 @@ static void kda_forms(const Plugin& pl, int64_t M, int iters) { std::printf("--perfkda: row kda_update_k128_v128_bf16 absent\n"); return; } + const RadKernelInfo* oracle = nullptr; + void* ref = nullptr; + if (check && g_plugin) { + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + auto count = ref ? (int (*)(void))dlsym(ref, "rad_kernel_count") : nullptr; + auto at = ref ? (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at") : nullptr; + if (count && at) + for (int i = 0; i < count() && !oracle; ++i) + if (!std::strcmp(at(i)->op, "kda_update")) oracle = at(i); + } + if (check && !oracle) { + ok("KDA at GLM's TP8 shape", false, "reference operation unavailable"); + if (ref) dlclose(ref); + return; + } const int64_t H = 8, D = 128, slots = 64, tokens = std::max(M, 48); const size_t state_floats = (size_t)(slots * H * D * D); std::vector state0(state_floats), alog((size_t)H), bias((size_t)(H * D)); @@ -12628,20 +13824,6 @@ static void kda_forms(const Plugin& pl, int64_t M, int iters) { cases.push_back(c); } - EnvPins env({ "RADIANCE_KDA_FORM", "RADIANCE_KDA_ROWS", "RADIANCE_KDA_PREFETCH" }); - struct Form { - const char* what; - const char* form; - const char* rows; - const char* prefetch; - }; - const Form forms[] = { { "rule", nullptr, nullptr, nullptr }, - { "1 row a wave", "new", "1", "1" }, - { "2 rows a wave", "new", "2", "1" }, - { "4 rows a wave", "new", "4", "1" }, - { "1 row a wave, no prefetch", "new", "1", "0" }, - { "2 rows a wave, no prefetch", "new", "2", "0" }, - { "4 rows a wave, no prefetch", "new", "4", "0" } }; if (!check) std::printf("kda_update at GLM's TP8 shape (8 heads, 128 x 128), %s, %d launches\n", g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() @@ -12691,54 +13873,65 @@ static void kda_forms(const Plugin& pl, int64_t M, int iters) { a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - auto run = [&]() { - st_memcpy(d_state, start.data(), state_bytes, hipMemcpyHostToDevice); - st_memset(d_out, 0xff, out_bytes); - if (row->launch(&a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) - return false; - return true; - }; - auto outputs = [&]() { - std::vector o = fetch_bytes(d_out, out_bytes); - const std::vector s = fetch_bytes(d_state, state_bytes); - o.insert(o.end(), s.begin(), s.end()); - return o; - }; - env.pin({ "old", nullptr, nullptr }); - const bool ref_ok = run(); - const std::vector ref = outputs(); - if (check) - ok(fmt("KDA %s: old form served", c.what.c_str()).c_str(), ref_ok); - else - std::printf(" %s\n %-34s %8.1f us\n", c.what.c_str(), "old", - ref_ok ? form_us(row, &a, iters) : -1.0); - for (const Form& f : forms) { - env.pin({ f.form, f.rows, f.prefetch }); - const bool served = run(); - const bool same = served && outputs() == ref; - if (check) { - ok(fmt("KDA %s, %s: byte-identical to the old form", c.what.c_str(), f.what) - .c_str(), - ref_ok && same, served ? "" : "not served"); - continue; + st_memcpy(d_state, start.data(), state_bytes, hipMemcpyHostToDevice); + st_memset(d_out, 0xff, out_bytes); + if (check) { + std::vector want_out((size_t)(tokens * H * D), 0xffff); + std::vector want_state = start; + void* const host[13] = { in[0].data(), in[1].data(), in[2].data(), + in[3].data(), in[4].data(), alog.data(), + bias.data(), want_state.data(), c.idx.data(), + c.cu.data(), c.accepted.data(), c.init.data(), + want_out.data() }; + std::vector ht = t; + for (int i = 0; i < 13; ++i) ht[(size_t)i].data = host[i]; + RadArgs ha = a; + ha.t = ht.data(); + const bool served = oracle->launch(&ha, nullptr) == RAD_OK && + row->launch(&a, nullptr) == RAD_OK && + st_stream_sync(nullptr) == hipSuccess; + std::vector got_out(want_out.size()); + std::vector got_state(state_floats); + st_memcpy(got_out.data(), d_out, out_bytes, hipMemcpyDeviceToHost); + st_memcpy(got_state.data(), d_state, state_bytes, hipMemcpyDeviceToHost); + size_t bad = 0; + for (size_t i = 0; i < got_out.size(); ++i) { + if (got_out[i] == want_out[i]) continue; + const float x = h_bf16(got_out[i]), y = h_bf16(want_out[i]); + if (!std::isfinite(x) || !std::isfinite(y) || + std::fabs(x - y) > 0.008f + 0.008f * std::fabs(y)) { + if (bad < 4) std::printf(" out[%zu]: %.6g, libref %.6g\n", i, x, y); + ++bad; + } } - const double us = served ? form_us(row, &a, iters) : -1.0; - if (us < 0) - std::printf(" %-34s not served\n", f.what); - else - std::printf(" %-34s %8.1f us%s\n", f.what, us, - same ? " = old" : " DIFFERS from old"); + for (size_t i = 0; i < got_state.size(); ++i) { + if (got_state[i] == want_state[i]) continue; + if (!std::isfinite(got_state[i]) || + std::fabs(got_state[i] - want_state[i]) > 2e-5f + 2e-5f * std::fabs(want_state[i])) { + if (bad < 4) + std::printf(" state[%zu] (slot %zu): %.9g, libref %.9g, start %.9g\n", i, + i / (size_t)(H * D * D), got_state[i], want_state[i], start[i]); + ++bad; + } + } + ok(fmt("KDA %s: output and whole state at libref's (%zu outside)", c.what.c_str(), bad) + .c_str(), + served && !bad, served ? "" : "not served"); + continue; } + const double us = form_us(row, &a, iters); + if (us < 0) + std::printf(" %-44s not served\n", c.what.c_str()); + else + std::printf(" %-44s %8.1f us\n", c.what.c_str(), us); } + if (ref) dlclose(ref); } -/* mla_project at GLM's TP8 shape (eight heads, head_dim 256, latent 512) in both modes, every row - * form held byte for byte to the one-row kernels on shuffle sums (RADIANCE_MLA_PROJECT=old) over - * the whole pitched output, so a store past a row or into the pitch shows. M not a multiple of the - * rows a group checks the tail. `iters` below zero compares only, as a case. */ -static void project_forms(const Plugin& pl, int64_t M, int iters) { - const bool check = iters < 0; - if (iters == 0) iters = 100; +/* mla_project at GLM's TP8 shape (eight heads, head_dim 256, latent 512) in both modes, on pitched + * tensors, timed. mla_project_check holds the row to libref. */ +static void project_perf(const Plugin& pl, int64_t M, int iters) { + if (iters <= 0) iters = 100; if (M < 1 || M > 65535) { std::printf("--perfproject: 1 <= M <= 65535\n"); return; @@ -12758,14 +13951,11 @@ static void project_forms(const Plugin& pl, int64_t M, int iters) { return; } st_memcpy(d_w, w.data(), w.size() * 2, hipMemcpyHostToDevice); - EnvPins env({ "RADIANCE_MLA_PROJECT" }); - if (!check) - std::printf( - "mla_project at GLM's TP8 shape (8 heads, 256 <-> 512), M=%lld, %s, %d launches\n", - (long long)M, - g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() - : "warm (back to back, mean)", - iters); + std::printf("mla_project at GLM's TP8 shape (8 heads, 256 <-> 512), M=%lld, %s, %d launches\n", + (long long)M, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", + iters); for (const char* mode : { "absorb", "expand" }) { const bool absorb = !std::strcmp(mode, "absorb"); const int64_t xd = absorb ? 256 : 512, yd = absorb ? 512 : 256; @@ -12797,38 +13987,12 @@ static void project_forms(const Plugin& pl, int64_t M, int iters) { a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - const size_t y_bytes = (size_t)(M * yr * 2); - auto run = [&]() { - st_memset(d_y, 0xa5, y_bytes); - return row->launch(&a, nullptr) == RAD_OK && st_stream_sync(nullptr) == hipSuccess; - }; - env.pin({ "old" }); - const bool ref_ok = run(); - const std::vector ref = fetch_bytes(d_y, y_bytes); - if (check) - ok(fmt("MLA project %s M=%lld: old form served", mode, (long long)M).c_str(), ref_ok); + st_memset(d_y, 0xa5, (size_t)(M * yr * 2)); + const double us = form_us(row, &a, iters); + if (us < 0) + std::printf(" %-8s not served\n", mode); else - std::printf(" %s\n %-20s %8.1f us\n", mode, "old", - ref_ok ? form_us(row, &a, iters) : -1.0); - for (const char* f : { (const char*)nullptr, "1", "2", "4", "8" }) { - env.pin({ f }); - const bool served = run(); - const bool same = served && fetch_bytes(d_y, y_bytes) == ref; - const std::string what = f ? fmt("%s rows a group", f) : std::string("rule"); - if (check) { - ok(fmt("MLA project %s M=%lld, %s: byte-identical to the old form", mode, - (long long)M, what.c_str()) - .c_str(), - ref_ok && same, served ? "" : "not served"); - continue; - } - const double us = served ? form_us(row, &a, iters) : -1.0; - if (us < 0) - std::printf(" %-20s not served\n", what.c_str()); - else - std::printf(" %-20s %8.1f us%s\n", what.c_str(), us, - same ? " = old" : " DIFFERS from old"); - } + std::printf(" %-8s %8.1f us\n", mode, us); } } @@ -12939,7 +14103,7 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co } ok("MXFP4 expert storage allocation", memory_ok); if (!memory_ok) { - for (void* p : pinned) hipHostFree(p); + for (void* p : pinned) hip_ck(hipHostFree(p), "hipHostFree", __LINE__); dlclose(ref); return; } @@ -13009,27 +14173,9 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co 0.004f + 0.008f * std::fabs(want)); } } - const char* lut = std::getenv("RADIANCE_MXFP4_LUT"); - const char* pipe = std::getenv("RADIANCE_MXFP4_PREFILL_PIPE"); - auto env_or = [](const char* n, const char* d) { - const char* v = std::getenv(n); - return v ? v : d; - }; - const char* p64 = std::getenv("RADIANCE_MXFP4_PREFILL_P64"); - const std::string p64s = - !p64 ? std::string("rule") - : p64[0] == '1' - ? fmt("BM%s BN%s K%s x%s out%s db%s", env_or("RADIANCE_MXFP4_PREFILL_P64_BM", "rule"), - env_or("RADIANCE_MXFP4_PREFILL_P64_BN", "rule"), - env_or("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", "rule"), - env_or("RADIANCE_MXFP4_PREFILL_P64_COLTILES", "4"), - env_or("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", "rule"), - env_or("RADIANCE_MXFP4_PREFILL_P64_DB", "0")) - : std::string("off"); - ok(fmt("MXFP4 M=%d N=%d K=%d parts=%d pooled=%d %s exceptional=%d holes=%d lut=%s pipe=%s " - "p64=%s, pointer tables and dropped slots", - M, OUT, NK, parts, pooled, order, exceptional, holes, lut ? lut : "rule", - pipe ? pipe : "rule", p64s.c_str()) + ok(fmt("MXFP4 M=%d N=%d K=%d parts=%d pooled=%d %s exceptional=%d holes=%d experts=%d top=%d, " + "pointer tables and dropped slots", + M, OUT, NK, parts, pooled, order, exceptional, holes, NE, top) .c_str(), match); ok("MXFP4 grouped output red zones and pitch", guards); @@ -13047,7 +14193,7 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co ok("MXFP4 layout rejects a different scale group", row->layout(ps.data(), (int)ps.size(), 2, &enc, &selection, &plane, 1, &layout) == RAD_E_DTYPE); - for (void* p : pinned) hipHostFree(p); + for (void* p : pinned) hip_ck(hipHostFree(p), "hipHostFree", __LINE__); dlclose(ref); } @@ -13062,12 +14208,10 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co * the touched experts are the real traffic. Warm, a touched set under 64 MiB is cache-resident * after the first launch; --cold is the engine's case. * - * Forms are chosen by the RADIANCE_MXFP4_* environment, read at every launch. Their rule is - * mirrored here only to name the form and count the expert slices it streams: a (job, expert) - * pair reads the whole slice across the column blocks, so row groups re-read an expert once per - * group its run spans, and the expert-major decode form once per 16 of its rows. Every form must - * match the bytes of a pinned reference ("old": the TP8 prefill form with its stage prefetch from - * 512 routed rows, below that the rule), since each keeps one accumulation order per element. */ + * The form is the launcher's rule, mirrored here only to name it and count the expert slices it + * streams: a (job, expert) pair reads the whole slice across the column blocks, so row groups + * re-read an expert once per group its run spans, the expert-major decode form once per 16 of its + * rows, and the P64 and GLM prefill forms once per job. */ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_t top_k, bool f8 = false, const char* skew = nullptr) { if (iters <= 0) iters = 100; @@ -13177,125 +14321,8 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ : "warm (back to back, mean)", iters); - constexpr int kEnvs = 22; - static const char* const kEnvMx[kEnvs] = { "RADIANCE_MXFP4_DECODE_EXPERTS", - "RADIANCE_MXFP4_ALIGNED_JOBS", - "RADIANCE_MXFP4_PREFILL_N32", - "RADIANCE_MXFP4_PREFILL_M32", - "RADIANCE_MXFP4_PREFILL_N64", - "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", - "RADIANCE_MXFP4_EXPERTS_STAGE_K", - "RADIANCE_MXFP4_EXPERTS_COLTILES", - "RADIANCE_MXFP4_LUT", - "RADIANCE_MXFP4_PREFILL_PIPE", - "RADIANCE_MXFP4_PREFILL_P64", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", - "RADIANCE_MXFP4_PREFILL_P64_BM", - "RADIANCE_MXFP4_PREFILL_P64_BN", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", - "RADIANCE_MXFP4_PREFILL_P64_COLTILES", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", - "RADIANCE_MXFP4_PREFILL_P64_T_BM64", - "RADIANCE_MXFP4_PREFILL_P64_T_BN128", - "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", - "RADIANCE_MXFP4_PREFILL_P64_DB" }; - /* The F32-scale row has no prefill forms; its slots 1..5 and 8..21 name the MXFP4 switches, - * which it does not read. */ - static const char* const kEnvF8[kEnvs] = { "RADIANCE_FP8F32_DECODE_EXPERTS", - "RADIANCE_MXFP4_ALIGNED_JOBS", - "RADIANCE_MXFP4_PREFILL_N32", - "RADIANCE_MXFP4_PREFILL_M32", - "RADIANCE_MXFP4_PREFILL_N64", - "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", - "RADIANCE_FP8F32_EXPERTS_STAGE_K", - "RADIANCE_FP8F32_EXPERTS_COLTILES", - "RADIANCE_MXFP4_LUT", - "RADIANCE_MXFP4_PREFILL_PIPE", - "RADIANCE_MXFP4_PREFILL_P64", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", - "RADIANCE_MXFP4_PREFILL_P64_BM", - "RADIANCE_MXFP4_PREFILL_P64_BN", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", - "RADIANCE_MXFP4_PREFILL_P64_COLTILES", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", - "RADIANCE_MXFP4_PREFILL_P64_T_BM64", - "RADIANCE_MXFP4_PREFILL_P64_T_BN128", - "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", - "RADIANCE_MXFP4_PREFILL_P64_DB" }; - const char* const* const kEnv = f8 ? kEnvF8 : kEnvMx; - std::string saved[kEnvs]; - bool had[kEnvs]; - for (int i = 0; i < kEnvs; ++i) { - const char* v = std::getenv(kEnv[i]); - had[i] = v != nullptr; - if (v) saved[i] = v; - } - auto restore = [&]() { - for (int i = 0; i < kEnvs; ++i) { - if (had[i]) - setenv(kEnv[i], saved[i].c_str(), 1); - else - unsetenv(kEnv[i]); - } - }; - auto on = [](const char* n, bool dflt) { - const char* v = std::getenv(n); - return v ? v[0] == '1' : dflt; - }; - /* body()'s glm_prefill: the default of the prefill switches at GLM's projections. */ + /* body()'s glm_prefill: the measured GLM slices, at which the prefill forms serve. */ const bool glm = !f8 && E == 288 && top_k == 8; - auto num = [](const char* n, long dflt) { - const char* v = std::getenv(n); - return v && *v ? std::strtol(v, nullptr, 10) : dflt; - }; - /* env nullptr: the environment as given. Expert-major forms pin stage and column tiles; the - * prefill forms exist only from 512 routed rows. `lut` 0 or 1 pins the weight decode, `pipe` - * the TP8 prefill form's stage prefetch (-1: as given); the arithmetic decode without the - * prefetch is the bytewise reference of the others. `bm` > 0 pins the P64 form below its row - * bound at BM, BN, stage, column tiles (down only), LDS output and double buffer (gate_up - * only); every other pinned form pins P64 off. */ - struct Form { - const char* env; - int stage, tiles, lut, pipe = -1, bm = 0, bn = 0, sk = 0, ct = 0, out = 0, db = 0; - }; - std::vector forms = { { nullptr, 0, 0, -1 }, { "100000", 256, 1, -1 }, - { "100000", 256, 4, -1 }, { "100000", 128, 1, -1 }, - { "100000", 128, 4, -1 }, { "000000", 0, 0, -1 } }; - if (!f8) - for (int lut : { 0, 1 }) { - forms.push_back({ "100000", 256, 1, lut }); - forms.push_back({ "100000", 128, 4, lut }); - } - if (Tr >= 512 && !f8) { - for (const char* f : { "010000", "001000", "011000", "011100", "011110", "011111" }) - forms.push_back({ f, 0, 0, -1 }); - for (int pipe : { 0, 1 }) - for (int lut : { 0, 1 }) forms.push_back({ "011111", 0, 0, lut, pipe }); - } - const Form old = Tr >= 512 && !f8 ? Form{ "011111", 0, 0, 1, 1 } : Form{ nullptr, 0, 0, -1 }; - auto apply = [&](const Form& F) { - restore(); - if (!F.env) return; - for (int i = 0; i < 6; ++i) setenv(kEnv[i], F.env[i] == '1' ? "1" : "0", 1); - const int pinned[2] = { F.stage, F.tiles }; - for (int i = 0; i < 2; ++i) { - if (F.stage) - setenv(kEnv[6 + i], std::to_string(pinned[i]).c_str(), 1); - else - unsetenv(kEnv[6 + i]); - } - const int pinned2[2] = { F.lut, F.pipe }; - for (int i = 8; i < 10; ++i) - if (pinned2[i - 8] >= 0) setenv(kEnv[i], pinned2[i - 8] ? "1" : "0", 1); - setenv(kEnv[10], F.bm ? "1" : "0", 1); - if (F.bm) { - const int v[7] = { 0, 0, F.bm, F.bn, F.sk, F.ct, F.out }; - for (int i = 0; i < 7; ++i) setenv(kEnv[11 + i], std::to_string(v[i]).c_str(), 1); - setenv(kEnv[21], F.db ? "1" : "0", 1); - } - }; struct Proj { const char* name; @@ -13315,28 +14342,6 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ P.name, (long long)N, (long long)K, (long long)P.parts, P.srt ? "sorted" : "token", slice / 1048576.0, touched * slice / 1048576.0, E * slice / 1048576.0); - /* P64 over BM x BN x stage; at down's K (A resident) also over column tiles, and the LDS - * output at the default. */ - std::vector pf = forms; - if (Tr >= 512 && !f8) { - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - for (int sk2 : { 128, 256 }) - for (int ct : { 1, 4 }) { - if (ct == 1 && K > 256) continue; - pf.push_back({ "000000", 0, 0, -1, -1, bm, bn, sk2, ct, 0 }); - } - pf.push_back({ "000000", 0, 0, -1, -1, 64, 128, 128, 4, 1 }); - /* The double buffer where two stages fit in LDS (streamed A, gate_up). */ - if (K > 256) { - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - pf.push_back({ "000000", 0, 0, -1, -1, bm, bn, 128, 4, 0, 1 }); - pf.push_back({ "000000", 0, 0, -1, -1, 32, 64, 256, 4, 0, 1 }); - pf.push_back({ "000000", 0, 0, -1, -1, 64, 128, 128, 4, 1, 1 }); - } - } - std::vector av((size_t)(Ma * K)); for (size_t i = 0; i < av.size(); ++i) av[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i) % 33) - 16) / 4); @@ -13428,74 +14433,36 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ a.world_size = 1; const double flop = 2.0 * (double)Tr * (double)N * (double)K; const size_t ybytes = (size_t)(Tr * N) * 2; - std::vector reference(ybytes), got(ybytes); - apply(old); - st_memset(d_y, 0xff, ybytes); - bool have_old = r->launch(&a, nullptr) == RAD_OK && st_stream_sync(nullptr) == hipSuccess; - if (have_old) st_memcpy(reference.data(), d_y, ybytes, hipMemcpyDeviceToHost); - std::printf(" old: %s\n", - !have_old ? "not served, no byte comparison" - : old.env ? "TP8 prefill form, stage prefetch and table decode pinned" - : "the rule"); - for (size_t f = 0; f < pf.size(); ++f) { - apply(pf[f]); - const long max_t = f8 ? num("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1) - : num(P.srt ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN" - : "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP", - glm ? (P.srt ? 6143 : 768) : 511); - const char* forced = std::getenv(kEnv[0]); - const bool pwide = K > 256 ? Tr >= num(kEnv[19], 24576) : Tr >= num(kEnv[20], 24576); - const long dbm = pwide || (K > 256 && Tr >= num(kEnv[18], 12288)) ? 64 : 32; - const long dbn = pwide ? 128 : 64; - const long dsk = K > 256 && !pwide ? 256 : 128; - const long pbm = num(kEnv[13], dbm) == 32 ? 32 : 64, - pbn = num(kEnv[14], dbn) == 64 ? 64 : 128; - const long psk = num(kEnv[15], dsk) == 256 ? 256 : 128; - const bool p64 = !f8 && on(kEnv[10], glm) && !(forced && forced[0] == '1') && - Tr >= num(P.srt ? kEnv[12] : kEnv[11], P.srt ? 5760 : 769) && - (Tr + pbm - 1) / pbm + E <= 65535; - const bool expert = !p64 && on(kEnv[0], max_t < 0 || Tr <= max_t); - const long esk = num(kEnv[6], K <= 256 ? 128 : 256) == 128 ? 128 : 256; - const long et = num(kEnv[7], K <= 256 || (f8 && Tr < 128) ? 4 : 1) == 4 ? 4 : 1; - const bool aligned = !p64 && !expert && !f8 && on(kEnv[1], glm) && Tr >= 512; - const bool wide = !p64 && !expert && !f8 && on(kEnv[2], glm) && Tr >= 512; - const bool tall = wide && aligned && on(kEnv[3], glm), n64 = tall && on(kEnv[4], glm); - const bool cached = n64 && on(kEnv[5], glm), lut = f8 || p64 || on(kEnv[8], true); - const bool pipe = cached && on(kEnv[9], glm); - const long pct = K <= 256 && num(kEnv[16], 4) != 1 ? 4 : 1; - const bool pout = num(kEnv[17], pwide ? 1 : 0) == 1; - const bool pdb = - K > 256 && num(kEnv[21], 0) == 1 && (psk == 128 || (pbm == 32 && pbn == 64)); - const int64_t jr = p64 ? pbm : tall ? 32 : 16, tile = Tr < 32 ? 1 : Tr < 128 ? 4 : 16; + { + const bool pwide = Tr >= 24576; + const int64_t pbm = pwide || (K > 256 && Tr >= 12288) ? 64 : 32; + const bool p64 = + glm && Tr >= (P.srt ? 5760 : 769) && (Tr + pbm - 1) / pbm + E <= 65535; + const bool expert = !p64 && (f8 || Tr <= (glm ? (P.srt ? 6143 : 768) : 511)); + const bool pipe = !p64 && !expert && glm; + const int64_t jr = p64 ? pbm : pipe ? 32 : 16; int64_t streams = 0; - if (p64 || aligned || expert) + if (p64 || pipe || expert) for (int64_t e = 0; e < E; ++e) streams += (off[(size_t)(e + 1)] - off[(size_t)e] + jr - 1) / jr; else for (int64_t i = 0; i < Tr; ++i) - streams += i % tile == 0 || owner[(size_t)i] != owner[(size_t)(i - 1)]; + streams += i % 16 == 0 || owner[(size_t)i] != owner[(size_t)(i - 1)]; const std::string label = - std::string(pf[f].env ? "" : "rule: ") + - (p64 ? fmt("P64 BM%ld BN%ld K%ld", pbm, pbn, psk) + - (K <= 256 ? fmt(" x%ld, A resident", pct) : "") + - (pout ? ", LDS out" : "") + (pdb ? ", double buffer" : "") - : expert ? fmt("expert-major K%ld x%ld tiles", esk, et) - : std::string(n64 ? "M32N64" - : tall ? "M32N32" - : wide ? "M16N32" - : f8 ? "M16N64" - : "M16N16") + - (aligned ? " aligned jobs" - : fmt(" row groups of %lld", (long long)tile)) + - (cached ? ", cached rows" : "") + (pipe ? ", pipe" : "")) + - (lut ? "" : ", fp4x4"); + p64 ? fmt("P64 BM%lld BN%d K%d", (long long)pbm, pwide ? 128 : 64, + K > 256 && !pwide ? 256 : 128) + + (K <= 256 ? " x4, A resident" : "") + (pwide ? ", LDS out" : "") + : expert ? fmt("expert-major K%d x%d tiles", K <= 256 ? 128 : 256, + K <= 256 || (f8 && Tr < 128) ? 4 : 1) + : pipe ? std::string("GLM prefill form, jobs of 32 rows") + : std::string("row groups of 16"); st_memset(d_y, 0xff, ybytes); const int rc = r->launch(&a, nullptr); if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { std::printf(" %-46s rc=%d (not served)\n", label.c_str(), rc); + dfree_all(); continue; } - st_memcpy(got.data(), d_y, ybytes, hipMemcpyDeviceToHost); { hipEvent_t w0, w1; st_ev_create(&w0); @@ -13512,28 +14479,17 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ st_ev_destroy(w1); } const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); - if (f == 0) { - rule_us += us; - rule_bytes += touched * slice; - } - std::string same; - if (have_old) { - int64_t diff = 0; - for (size_t i = 0; i < ybytes; i += 2) - diff += std::memcmp(&got[i], &reference[i], 2) != 0; - same = diff ? fmt(" %lld elements differ from old", (long long)diff) : " = old"; - } - std::printf( - " %-46s %9.1f us %7.1f GB/s touched %5.2fx streamed %6.1f TFLOP/s%s\n", - label.c_str(), us, touched * slice / (us * 1e3), - touched ? (double)streams / (double)touched : 0.0, flop / (us * 1e6), same.c_str()); + rule_us += us; + rule_bytes += touched * slice; + std::printf(" %-46s %9.1f us %7.1f GB/s touched %5.2fx streamed %6.1f TFLOP/s\n", + label.c_str(), us, touched * slice / (us * 1e3), + touched ? (double)streams / (double)touched : 0.0, flop / (us * 1e6)); } - restore(); dfree_all(); } if (rule_us > 0) - std::printf(" the rule's forms, gate_up + down: %.1f us a layer, %.1f GB/s touched\n", - rule_us, rule_bytes / (rule_us * 1e3)); + std::printf(" gate_up + down: %.1f us a layer, %.1f GB/s touched\n", rule_us, + rule_bytes / (rule_us * 1e3)); } /* The gated residual's read at int8 codes. The same inputs run with the codes plane as E4M3 and @@ -13832,10 +14788,9 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool /* mHC's chunk-split read, as tensor parallelism issues it: every rank's mhc_pre_partial over its * chunks, the partials joined row by row as the row-interleaved all_gather lays them out (here on * the host), then mhc_pre_finish. The result must be byte-identical to mhc_pre on the same inputs, - * under each of mhc_pre's kernel switches, since both run the same projection and finishing - * kernels; the partial matrix's padding slots must be zero. */ -static void mhc_split_check(const Plugin& pl, int64_t rows, int world, const char* env, - const char* value) { + * since both run the same projection and finishing kernels; the partial matrix's padding slots + * must be zero. */ +static void mhc_split_check(const Plugin& pl, int64_t rows, int world) { const RadKernelInfo* pre = find(pl, "mhc_pre_bf16"); const RadKernelInfo* part_row = find(pl, "mhc_pre_partial_bf16"); const RadKernelInfo* fin = find(pl, "mhc_pre_finish_bf16"); @@ -13843,9 +14798,6 @@ static void mhc_split_check(const Plugin& pl, int64_t rows, int world, const cha if (!pre || !part_row || !fin) { ok(nm, false, "row absent"); return; } const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; const int64_t mine = total / world, hp = W + 6, xp = n + 2; - const char* saved = env ? std::getenv(env) : nullptr; - const std::string keep = saved ? saved : ""; - if (env) setenv(env, value, 1); std::vector hv((size_t)(rows * hp)); for (size_t i = 0; i < hv.size(); ++i) @@ -13929,22 +14881,21 @@ static void mhc_split_check(const Plugin& pl, int64_t rows, int world, const cha good = good && launch(fin, split, fp); const Out got = fetch(sx, sp, sc); const bool same = good && got.x == want.x && got.p == want.p && got.c == want.c; - ok(fmt("%s at M=%lld over %d ranks%s%s%s: byte-identical to mhc_pre", nm, (long long)rows, - world, env ? ", " : "", env ? env : "", env ? (std::string("=") + value).c_str() : "") + ok(fmt("%s at M=%lld over %d ranks: byte-identical to mhc_pre", nm, (long long)rows, world) .c_str(), same, good ? (got.x != want.x ? "x differs" : got.p != want.p ? "post differs" : got.c != want.c ? "comb differs" : "") : "launch failed"); ok(fmt("%s at M=%lld over %d ranks: zero padding", nm, (long long)rows, world).c_str(), padded); - if (env) { if (saved) setenv(env, keep.c_str(), 1); else unsetenv(env); } } /* mhc_pre and mhc_post at GLM's shape (n 4096, four streams, 2048-column chunks, 20 Sinkhorn - * rounds), every form timed and compared byte for byte with the old dispatch - * (RADIANCE_MHC_FINISH=old, RADIANCE_MHC_PARTIAL_VEC=0, the per-output mhc_post). - * The whole op, its partials alone (all eight chunks, and the one chunk a rank computes at TP8) - * and its finish alone over those partials. GB/s counts h and x (and mhc_post's output); the - * mixing weights (1.5 MiB) stay in L2. `iters` below zero runs each form once and reports only - * the comparisons, as a case. */ + * rounds), timed on 16-byte rows, where the vector forms run (four-slot partials, the finish's + * 16-byte collapse, the eight-column mhc_post), and compared byte for byte with the same operands + * on a residual pitched by two elements, where the scalar forms run (one slot a thread, four rows + * and four coefficients a block from 32 rows, the per-output mhc_post). The whole op, its partials + * alone (all eight chunks, and the one chunk a rank computes at TP8) and its finish alone over + * those partials. GB/s counts h and x (and mhc_post's output); the mixing weights (1.5 MiB) stay + * in L2. `iters` below zero runs each form once and reports only the comparisons, as a case. */ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { const bool check = iters < 0; if (iters == 0) iters = 200; @@ -13955,29 +14906,14 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { const RadKernelInfo* post = find(pl, "mhc_post_bf16"); if (!pre || !part || !fin || !post) { std::printf("--perfmhcpre: an mhc row is absent\n"); return; } const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; - static const char* const kEnv[5] = { "RADIANCE_MHC_FINISH", "RADIANCE_MHC_ROWS4_MIN", - "RADIANCE_MHC_POST_VEC", "RADIANCE_MHC_PARTIAL_VEC", - "RADIANCE_MHC_PARTIAL_ROWS" }; - std::string saved[5]; - bool had[5]; - for (int i = 0; i < 5; ++i) { - const char* v = std::getenv(kEnv[i]); - had[i] = v != nullptr; - if (v) saved[i] = v; - } - auto pin = [&](const char* finish, const char* rows4, const char* vec, - const char* pvec = nullptr, const char* prows = nullptr) { - const char* v[5] = { finish, rows4, vec, pvec, prows }; - for (int i = 0; i < 5; ++i) { - if (v[i]) setenv(kEnv[i], v[i], 1); - else if (had[i]) setenv(kEnv[i], saved[i].c_str(), 1); - else unsetenv(kEnv[i]); - } - }; + const int64_t pitched = W + 2; std::vector hv((size_t)(rows * W)), yv((size_t)(rows * n)); for (size_t i = 0; i < hv.size(); ++i) hv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 3u + 11u) % 2001) - 1000) / 1000); + std::vector hpv((size_t)(rows * pitched), 0); + for (int64_t r = 0; r < rows; ++r) + std::memcpy(&hpv[(size_t)(r * pitched)], &hv[(size_t)(r * W)], (size_t)W * 2); for (size_t i = 0; i < yv.size(); ++i) yv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 5u + 3u) % 2001) - 1000) / 500); std::vector fv((size_t)(mix * W)), sv = { 0.7f, 0.9f, 1.1f }, bv((size_t)mix); @@ -13985,6 +14921,7 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { fv[i] = (float)((int)(st_mix32((uint32_t)i + 77u) % 2001) - 1000) / 100000; for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)((int)(i % 7) - 3) * 0.25f; void* d_h = dalloc(hv.size() * 2); + void* d_hp = dalloc(hpv.size() * 2); void* d_y = dalloc(yv.size() * 2); void* d_f = dalloc(fv.size() * 4); void* d_s = dalloc(12); @@ -13995,11 +14932,13 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { void* d_part = dalloc((size_t)(rows * total * S * 4)); void* d_part1 = dalloc((size_t)(rows * S * 4)); void* d_out = dalloc((size_t)(rows * W * 2)); - if (!d_h || !d_y || !d_f || !d_s || !d_b || !d_x || !d_p || !d_c || !d_part || !d_part1 || !d_out) { + if (!d_h || !d_hp || !d_y || !d_f || !d_s || !d_b || !d_x || !d_p || !d_c || !d_part || !d_part1 || + !d_out) { std::printf("--perfmhcpre: alloc failed\n"); return; } st_memcpy(d_h, hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_hp, hpv.data(), hpv.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_y, yv.data(), yv.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_f, fv.data(), fv.size() * 4, hipMemcpyHostToDevice); st_memcpy(d_s, sv.data(), 12, hipMemcpyHostToDevice); @@ -14008,6 +14947,8 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { ts = T(d_s, RAD_F32, { 3 }), tb = T(d_b, RAD_F32, { mix }), tx = T(d_x, RAD_BF16, { rows, n }), tp = T(d_p, RAD_F32, { rows, hc }), tc = T(d_c, RAD_F32, { rows, hc * hc }); + RadTensor thp = T(d_hp, RAD_BF16, { rows, W }); + thp.stride[0] = pitched; std::vector coef = { PI("M", rows), PI("n", n), PI("hc", hc), PI("iterations", 20), PF("eps", 1e-6), PF("hc_eps", 1e-6), PI("chunk", 2048), PS("dtype", "bf16") }; @@ -14021,6 +14962,8 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { std::vector a_fin = { T(d_part, RAD_F32, { rows, total * S }), th, ts, tb, tx, tp, tc }; std::vector a_post = { T(d_y, RAD_BF16, { rows, n }), th, tp, tc, T(d_out, RAD_BF16, { rows, W }) }; + std::vector a_pre_p = a_pre, a_all_p = a_all, a_post_p = a_post; + a_pre_p[0] = a_all_p[0] = a_post_p[1] = thp; auto args = [](std::vector& t, std::vector& p) { RadArgs a{}; a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); @@ -14028,7 +14971,8 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { return a; }; RadArgs A_pre = args(a_pre, coef), A_all = args(a_all, p_all), A_one = args(a_one, p_one), - A_fin = args(a_fin, coef), A_post = args(a_post, coef); + A_fin = args(a_fin, coef), A_post = args(a_post, coef), A_pre_p = args(a_pre_p, coef), + A_all_p = args(a_all_p, p_all), A_post_p = args(a_post_p, coef); auto timed = [&](const RadKernelInfo* r, RadArgs* a) { if (r->launch(a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return -1.0; if (check) return 0.0; @@ -14068,7 +15012,7 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { auto line = [&](const char* what, double us, double bytes, const std::string& same) { if (check) { ok(fmt("%s at M=%lld%s", what, (long long)rows, - same.empty() ? " is served" : ": byte-identical to the old dispatch").c_str(), + same.empty() ? " is served" : ": byte-identical to the pitched rows").c_str(), us >= 0 && same.find("DIFFERS") == std::string::npos, us < 0 ? "not served" : ""); return; } @@ -14076,75 +15020,49 @@ static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { std::printf(" %-44s %8.1f us %7.1f GB/s%s\n", what, us, bytes / (us * 1e3), same.c_str()); }; auto cmp = [](const std::vector& a, const std::vector& b) { - return a == b ? std::string(" = old") : std::string(" DIFFERS from old"); + return a == b ? std::string(" = pitched") : std::string(" DIFFERS from pitched"); }; - pin("old", nullptr, "0", "0"); - const double us_old = timed(pre, &A_pre); + const size_t x_bytes = (size_t)(rows * n * 2), part_bytes = (size_t)(rows * total * S * 4), + out_bytes = (size_t)(rows * W * 2); + const double us_pre_p = timed(pre, &A_pre_p); const std::vector ref = outputs(); - line("mhc_pre, old dispatch", us_old, hx, ""); - struct Pv { const char* what; const char* finish; const char* rows4; const char* pvec; - const char* prows; }; - for (const Pv& v : { Pv{ "mhc_pre, rule", nullptr, nullptr, nullptr, nullptr }, - Pv{ "mhc_pre, finish: scalar mix, wide read", "scalar", nullptr, nullptr, nullptr }, - Pv{ "mhc_pre, old partials (rows4 from 32)", nullptr, nullptr, "0", nullptr }, - Pv{ "mhc_pre, four-slot partials, 1 row a wave", nullptr, nullptr, "1", "1" }, - Pv{ "mhc_pre, four-slot partials, 2 rows a wave", nullptr, nullptr, "1", "2" }, - Pv{ "mhc_pre, four-slot partials, 4 rows a wave", nullptr, nullptr, "1", "4" } }) { - pin(v.finish, v.rows4, nullptr, v.pvec, v.prows); - st_memset(d_x, 0xff, (size_t)(rows * n * 2)); - const double us = timed(pre, &A_pre); - line(v.what, us, hx, us < 0 ? "" : cmp(outputs(), ref)); - } - pin(nullptr, nullptr, nullptr, "0"); - if (part->launch(&A_all, nullptr) == RAD_OK) st_stream_sync(nullptr); - const std::vector part_ref = fetch(d_part, (size_t)(rows * total * S * 4)); - for (const Pv& v : { Pv{ "mhc_pre_partial, 8 chunks, old", nullptr, nullptr, "0", nullptr }, - Pv{ "mhc_pre_partial, 8 chunks, rule", nullptr, nullptr, nullptr, nullptr }, - Pv{ "mhc_pre_partial, 8 chunks, four-slot x1", nullptr, nullptr, "1", "1" }, - Pv{ "mhc_pre_partial, 8 chunks, four-slot x2", nullptr, nullptr, "1", "2" }, - Pv{ "mhc_pre_partial, 8 chunks, four-slot x4", nullptr, nullptr, "1", "4" }, - Pv{ "mhc_pre_partial, 8 chunks, rows4 at every M", nullptr, "1", "0", nullptr }, - Pv{ "mhc_pre_partial, 8 chunks, scalar-row", nullptr, "1000000", "0", nullptr } }) { - pin(nullptr, v.rows4, nullptr, v.pvec, v.prows); - st_memset(d_part, 0xff, (size_t)(rows * total * S * 4)); - const double us = timed(part, &A_all); - const bool is_ref = v.pvec && !std::strcmp(v.pvec, "0") && !v.rows4; - line(v.what, us, (double)rows * W * 2, us < 0 || is_ref ? std::string() - : cmp(fetch(d_part, (size_t)(rows * total * S * 4)), part_ref)); - } - pin(nullptr, nullptr, nullptr); + line("mhc_pre, pitched rows", us_pre_p, hx, ""); + st_memset(d_x, 0xff, x_bytes); + const double us_pre = timed(pre, &A_pre); + line("mhc_pre", us_pre, hx, us_pre < 0 ? "" : cmp(outputs(), ref)); + + st_memset(d_part, 0xff, part_bytes); + const double us_all_p = timed(part, &A_all_p); + const std::vector part_ref = fetch(d_part, part_bytes); + line("mhc_pre_partial, 8 chunks, pitched rows", us_all_p, (double)rows * W * 2, ""); + st_memset(d_part, 0xff, part_bytes); + const double us_all = timed(part, &A_all); + line("mhc_pre_partial, 8 chunks", us_all, (double)rows * W * 2, + us_all < 0 ? "" : cmp(fetch(d_part, part_bytes), part_ref)); line("mhc_pre_partial, 1 chunk (a TP8 rank's)", timed(part, &A_one), (double)rows * W * 2 / 8, ""); + if (part->launch(&A_all, nullptr) == RAD_OK) st_stream_sync(nullptr); - for (const Pv& v : { Pv{ "mhc_pre_finish, old", "old", nullptr, nullptr, nullptr }, - Pv{ "mhc_pre_finish, rule", nullptr, nullptr, nullptr, nullptr }, - Pv{ "mhc_pre_finish, scalar mix, wide read", "scalar", nullptr, nullptr, nullptr } }) { - pin(v.finish, nullptr, nullptr); - st_memset(d_x, 0xff, (size_t)(rows * n * 2)); - const double us = timed(fin, &A_fin); - line(v.what, us, hx, us < 0 ? "" : cmp(outputs(), ref)); - } + st_memset(d_x, 0xff, x_bytes); + const double us_fin = timed(fin, &A_fin); + line("mhc_pre_finish", us_fin, hx, us_fin < 0 ? "" : cmp(outputs(), ref)); + const double post_bytes = (double)rows * (2 * W + n) * 2; - pin(nullptr, nullptr, "0"); - const double us_post_old = timed(post, &A_post); - const std::vector post_ref = fetch(d_out, (size_t)(rows * W * 2)); - line("mhc_post, old", us_post_old, post_bytes, ""); - pin(nullptr, nullptr, nullptr); - st_memset(d_out, 0xff, (size_t)(rows * W * 2)); + const double us_post_p = timed(post, &A_post_p); + const std::vector post_ref = fetch(d_out, out_bytes); + line("mhc_post, pitched rows", us_post_p, post_bytes, ""); + st_memset(d_out, 0xff, out_bytes); const double us_post = timed(post, &A_post); - line("mhc_post, rule", us_post, post_bytes, - us_post < 0 ? "" : cmp(fetch(d_out, (size_t)(rows * W * 2)), post_ref)); - for (int i = 0; i < 5; ++i) { - if (had[i]) setenv(kEnv[i], saved[i].c_str(), 1); - else unsetenv(kEnv[i]); - } + line("mhc_post", us_post, post_bytes, + us_post < 0 ? "" : cmp(fetch(d_out, out_bytes), post_ref)); } -/* router_sigmoid_topk's wave-per-row select against the serial scan (RADIANCE_ROUTER_SELECT=old), - * byte for byte over ids and weights with their pitches filled, so an overrun or a missed slot - * shows. Logits, bias and outputs are pitched, the bias strided. `ties` puts logits on steps of - * 1/2 and the bias on steps of 1/8, so many experts share a rank and the lower-index rule - * decides. `iters` below zero compares only, as a case; otherwise both are timed. */ +/* router_sigmoid_topk's wave-per-row select against libref's: the ids exactly and the weights to + * a relative 1e-5 (the card's expf and the host's may differ in the last place), with the pitches + * filled, so an overrun or a missed slot shows. Logits, bias and outputs are pitched, the bias + * strided. `ties` puts logits on steps of 1/2 and the bias on steps of 1/8, so many experts share + * a rank and the lower-index rule decides. `iters` below zero compares only, as a case; otherwise + * the select is timed. */ static void router_select(const Plugin& pl, int64_t rows, int64_t ne, int64_t k, int norm, bool ties, int iters) { const bool check = iters < 0; @@ -14180,45 +15098,70 @@ static void router_select(const Plugin& pl, int64_t rows, int64_t ne, int64_t k, RadArgs a{}; a.t = ts.data(); a.n_t = 4; a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - const char* saved = std::getenv("RADIANCE_ROUTER_SELECT"); - const std::string keep = saved ? saved : ""; - auto run = [&](const char* form, std::vector* out, double* us) -> int { - if (form) setenv("RADIANCE_ROUTER_SELECT", form, 1); - else unsetenv("RADIANCE_ROUTER_SELECT"); - st_memset(d_i, 0xa5, (size_t)(rows * ip * 4)); - st_memset(d_w, 0xa5, (size_t)(rows * wp * 4)); - const int rc = r->launch(&a, nullptr); - if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : RAD_E_DEVICE; - out->resize((size_t)(rows * (ip + wp) * 4)); - st_memcpy(out->data(), d_i, (size_t)(rows * ip * 4), hipMemcpyDeviceToHost); - st_memcpy(out->data() + rows * ip * 4, d_w, (size_t)(rows * wp * 4), hipMemcpyDeviceToHost); - if (!check) *us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); - return (int)RAD_OK; - }; - std::vector old, got; - double us_old = 0, us_new = 0; - const int orc = run("old", &old, &us_old); - const int nrc = orc == RAD_OK ? run(nullptr, &got, &us_new) : orc; - if (saved) setenv("RADIANCE_ROUTER_SELECT", keep.c_str(), 1); - else unsetenv("RADIANCE_ROUTER_SELECT"); - const bool same = nrc == RAD_OK && got == old; - if (check) { - size_t first = 0; - if (nrc == RAD_OK && !same) while (first < got.size() && got[first] == old[first]) ++first; - ok(fmt("router_sigmoid_topk select at M=%lld n_expert=%lld top_k=%lld norm=%d%s: " - "byte-identical to the serial scan", (long long)rows, (long long)ne, (long long)k, - norm, ties ? ", tied ranks" : "").c_str(), same, - nrc != RAD_OK ? fmt("rc=%d", nrc) : same ? "" : fmt("first byte %zu", first)); + st_memset(d_i, 0xa5, (size_t)(rows * ip * 4)); + st_memset(d_w, 0xa5, (size_t)(rows * wp * 4)); + int rc = r->launch(&a, nullptr); + if (rc == RAD_OK && st_stream_sync(nullptr) != hipSuccess) rc = RAD_E_DEVICE; + if (!check) { + if (rc != RAD_OK) { std::printf("--perfrouter: launch failed (rc %d)\n", rc); return; } + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + std::printf("router_sigmoid_topk, M=%lld (n_expert %lld, top %lld, norm %d), %s, %d " + "launches\n", (long long)rows, (long long)ne, (long long)k, norm, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", iters); + std::printf(" %-28s %8.1f us\n", "wave per row", us); return; } - if (nrc != RAD_OK) { std::printf("--perfrouter: launch failed (rc %d)\n", nrc); return; } - std::printf("router_sigmoid_topk, M=%lld (n_expert %lld, top %lld, norm %d), %s, %d launches\n", - (long long)rows, (long long)ne, (long long)k, norm, - g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() - : "warm (back to back, mean)", iters); - std::printf(" %-28s %8.1f us\n", "serial scan (old)", us_old); - std::printf(" %-28s %8.1f us%s\n", "wave per row", us_new, - same ? " = old" : " DIFFERS from old"); + const std::string name = fmt("router_sigmoid_topk select at M=%lld n_expert=%lld top_k=%lld " + "norm=%d%s: libref's ids and weights", (long long)rows, + (long long)ne, (long long)k, norm, ties ? ", tied ranks" : ""); + if (rc != RAD_OK) { ok(name.c_str(), false, fmt("rc=%d", rc)); return; } + std::vector ids((size_t)(rows * ip)), want_ids((size_t)(rows * ip)); + std::vector wts((size_t)(rows * wp)), want_wts((size_t)(rows * wp)); + st_memcpy(ids.data(), d_i, ids.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(wts.data(), d_w, wts.size() * 4, hipMemcpyDeviceToHost); + std::memset(want_ids.data(), 0xa5, want_ids.size() * 4); + std::memset(want_wts.data(), 0xa5, want_wts.size() * 4); + void* ref = nullptr; + if (g_plugin) { + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + } + const auto count = ref ? (int (*)())dlsym(ref, "rad_kernel_count") : nullptr; + const auto at = ref ? (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at") : nullptr; + const RadKernelInfo* oracle = nullptr; + for (int i = 0; count && at && i < count(); ++i) + if (!std::strcmp(at(i)->op, "router_sigmoid_topk")) oracle = at(i); + if (!oracle) { + ok(name.c_str(), false, "reference operation unavailable"); + if (ref) dlclose(ref); + return; + } + std::vector hs = ts; + hs[0].data = lg.data(); hs[1].data = bv.data(); + hs[2].data = want_ids.data(); hs[3].data = want_wts.data(); + RadArgs ha = a; + ha.t = hs.data(); + const int hrc = oracle->launch(&ha, nullptr); + dlclose(ref); + if (hrc != RAD_OK) { ok(name.c_str(), false, fmt("host oracle rc=%d", hrc)); return; } + int64_t bad = 0, first = -1; + for (int64_t row = 0; row < rows; ++row) { + for (int64_t c = 0; c < ip; ++c) { + const size_t i = (size_t)(row * ip + c); + if (ids[i] != want_ids[i] && !bad++) first = row; + } + for (int64_t c = 0; c < wp; ++c) { + const size_t i = (size_t)(row * wp + c); + const bool same = + c < k ? std::fabs(wts[i] - want_wts[i]) <= 1e-5f * std::fabs(want_wts[i]) + : std::memcmp(&wts[i], &want_wts[i], 4) == 0; + if (!same && !bad++) first = row; + } + } + ok(name.c_str(), bad == 0, bad ? fmt("%lld words differ, the first in row %lld", (long long)bad, + (long long)first) : ""); } /* ---- GLM's decode fusions of the MoE block (r4d_glm.hip), each against the separate launches it @@ -14557,11 +15500,12 @@ static void moefuse_perf(const Plugin& pl, int64_t rows, int iters) { moefuse_gather(pl, rows, false, iters); } -/* gemm_nt_f32 at every tile form (RADIANCE_F32_GEMM_TILE), each compared byte for byte with the - * one-wave-per-output legacy kernel. Rows are pitched and the output keeps a filled pitch, so an - * overrun or a missed tail shows as a byte difference. Timed, every form also prints its time, - * its GB/s on weight + input + output and its TFLOP/s; weights rotate over copies past the - * last-level cache, as in bf16_perf. */ +/* gemm_nt_f32 at the tile form its rule picks for M, compared byte for byte with the arithmetic + * every form keeps, written out on the host: lane l folds k = l, l+32, ... with fmaf, then the xor + * butterfly over 16, 8, 4, 2, 1. Rows are pitched and the output keeps a filled pitch, so an + * overrun or a missed tail shows as a byte difference. Timed, it also prints its time, its GB/s on + * weight + input + output and its TFLOP/s; weights rotate over copies past the last-level cache, + * as in bf16_perf. */ static void f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int iters, bool timed) { const RadKernelInfo* r = find(pl, "gemm_nt_f32_bf16"); if (!r) { ok("gemm_nt_f32_bf16 forms", false, "row absent"); return; } @@ -14576,17 +15520,15 @@ static void f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int ite void* d_w = dalloc(wbytes * (size_t)copies); void* d_y = dalloc(ybytes); if (!d_x || !d_w || !d_y) { ok("gemm_nt_f32_bf16 forms", false, "allocation failed"); return; } - { - std::vector x((size_t)M * (size_t)xp); - for (size_t i = 0; i < x.size(); ++i) - x[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) / 1000); - st_memcpy(d_x, x.data(), x.size() * 2, hipMemcpyHostToDevice); - std::vector w((size_t)N * (size_t)K); - for (size_t i = 0; i < w.size(); ++i) - w[i] = (float)((int)(st_mix32((uint32_t)i + 0x51ed27u) % 2001) - 1000) / 8000; - for (int c = 0; c < copies; ++c) - st_memcpy((uint8_t*)d_w + (size_t)c * wbytes, w.data(), wbytes, hipMemcpyHostToDevice); - } + std::vector x((size_t)M * (size_t)xp); + for (size_t i = 0; i < x.size(); ++i) + x[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) / 1000); + st_memcpy(d_x, x.data(), x.size() * 2, hipMemcpyHostToDevice); + std::vector w((size_t)N * (size_t)K); + for (size_t i = 0; i < w.size(); ++i) + w[i] = (float)((int)(st_mix32((uint32_t)i + 0x51ed27u) % 2001) - 1000) / 8000; + for (int c = 0; c < copies; ++c) + st_memcpy((uint8_t*)d_w + (size_t)c * wbytes, w.data(), wbytes, hipMemcpyHostToDevice); std::vector ts = { T(d_x, RAD_BF16, { M, K }), T(d_w, RAD_F32, { N, K }), T(d_y, RAD_F32, { M, N }), }; @@ -14596,70 +15538,57 @@ static void f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int ite std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = 3; a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; - const char* saved = std::getenv("RADIANCE_F32_GEMM_TILE"); - const std::string keep = saved ? saved : ""; - auto run = [&](const char* form, std::vector* out) -> int { - if (form) setenv("RADIANCE_F32_GEMM_TILE", form, 1); - else unsetenv("RADIANCE_F32_GEMM_TILE"); - std::vector fill(ybytes, 0xa5); - st_memcpy(d_y, fill.data(), ybytes, hipMemcpyHostToDevice); - ts[1].data = d_w; - const int rc = r->launch(&a, nullptr); - if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : RAD_E_DEVICE; - out->resize(ybytes); - st_memcpy(out->data(), d_y, ybytes, hipMemcpyDeviceToHost); - return (int)RAD_OK; - }; - static const char* kForms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", "4x4", "8x4", - "16x2", "16x4", nullptr }; - std::vector legacy, got; - const int lrc = run("legacy", &legacy); - ok(fmt("gemm_nt_f32 legacy form at M=%lld N=%lld K=%lld", (long long)M, (long long)N, - (long long)K).c_str(), lrc == RAD_OK); - if (lrc == RAD_OK) { - for (const char* const* f = kForms;; ++f) { - const char* form = *f; - const int rc = run(form, &got); - const bool same = rc == RAD_OK && got == legacy; - size_t first = 0; - if (rc == RAD_OK && !same) - while (first < got.size() && got[first] == legacy[first]) ++first; - ok(fmt("gemm_nt_f32 form %s at M=%lld N=%lld K=%lld: byte-identical to legacy", - form ? form : "default", (long long)M, (long long)N, (long long)K).c_str(), - same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); - if (!form) break; + std::vector fill(ybytes, 0xa5), got(ybytes); + st_memcpy(d_y, fill.data(), ybytes, hipMemcpyHostToDevice); + int rc = r->launch(&a, nullptr); + if (rc == RAD_OK && st_stream_sync(nullptr) != hipSuccess) rc = RAD_E_DEVICE; + if (rc == RAD_OK) st_memcpy(got.data(), d_y, ybytes, hipMemcpyDeviceToHost); + /* The arithmetic on the host, into a copy of the filled output. */ + std::vector want = fill; + for (int64_t row = 0; row < M; ++row) + for (int64_t c = 0; c < N; ++c) { + float lane[32]; + for (int l = 0; l < 32; ++l) { + float sum = 0; + for (int64_t j = l; j < K; j += 32) + sum = std::fmaf(h_bf16(x[(size_t)(row * xp + j)]), w[(size_t)(c * K + j)], sum); + lane[l] = sum; + } + for (int mask = 16; mask; mask >>= 1) { + float next[32]; + for (int l = 0; l < 32; ++l) next[l] = lane[l] + lane[l ^ mask]; + std::memcpy(lane, next, sizeof lane); + } + std::memcpy(&want[(size_t)(row * yp + c) * 4], &lane[0], 4); } - } - if (timed && lrc == RAD_OK) { + const bool same = rc == RAD_OK && got == want; + size_t first = 0; + if (rc == RAD_OK && !same) + while (first < got.size() && got[first] == want[first]) ++first; + ok(fmt("gemm_nt_f32 at M=%lld N=%lld K=%lld: byte-identical to the host arithmetic", + (long long)M, (long long)N, (long long)K).c_str(), + same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); + if (timed && rc == RAD_OK) { const double bytes = (double)wbytes + (double)M * K * 2 + (double)M * N * 4; const double flop = 2.0 * (double)M * (double)N * (double)K; std::printf("\ngemm_nt_f32 N=%lld K=%lld M=%lld %.2f MiB weight, %d copies, %d iters\n", (long long)N, (long long)K, (long long)M, (double)wbytes / (1 << 20), copies, iters); - static const char* kTimed[] = { "legacy", "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", "4x4", - "8x4", "16x2", "16x4", nullptr }; - for (const char* const* f = kTimed;; ++f) { - const char* form = *f; - if (form) setenv("RADIANCE_F32_GEMM_TILE", form, 1); - else unsetenv("RADIANCE_F32_GEMM_TILE"); - const double us = st_time_us([&](int i) { - ts[1].data = (uint8_t*)d_w + (size_t)(i % copies) * wbytes; - r->launch(&a, nullptr); - }, iters, nullptr); - std::printf(" %-8s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", form ? form : "default", - us, bytes / (us * 1e3), flop / (us * 1e6)); - if (!form) break; - } + const double us = st_time_us([&](int i) { + ts[1].data = (uint8_t*)d_w + (size_t)(i % copies) * wbytes; + r->launch(&a, nullptr); + }, iters, nullptr); + std::printf(" %-8s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", "rule", us, + bytes / (us * 1e3), flop / (us * 1e6)); ts[1].data = d_w; } - if (saved) setenv("RADIANCE_F32_GEMM_TILE", keep.c_str(), 1); - else unsetenv("RADIANCE_F32_GEMM_TILE"); } -/* gemm_fp8a8_f32scale's dense forms (RADIANCE_FP8F32_FORM: decode at several R x S, rows) each - * compared byte for byte with the legacy 16x64 tile; the output keeps a filled pitch, so an - * overrun or a missed row shows. Timed, every form also prints its time and GB/s on the weight and its scale plane, the - * weight rotating over copies past the last-level cache. */ +/* gemm_fp8a8_f32scale's dense form at the shape (a decode form or a row tile, by the rule) + * compared byte for byte with the legacy 16x64 tile, which an activation pitch off 16 bytes takes; + * the output keeps a filled pitch, so an overrun or a missed row shows. Timed, it also prints its + * time and GB/s on the weight and its scale plane, the weight rotating over copies past the + * last-level cache. */ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int iters, bool timed) { const RadKernelInfo* r = find(pl, "gemm_fp8a8_f32scale"); if (!r) { ok("gemm_fp8a8_f32scale forms", false, "row absent"); return; } @@ -14671,11 +15600,12 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int if (copies > 64) copies = 64; } void* d_a = dalloc((size_t)(M * K)); + void* d_al = dalloc((size_t)(M * (K + 8))); void* d_as = dalloc((size_t)(M * sk * 4)); void* d_w = dalloc(wb * (size_t)copies); void* d_s = dalloc(sb); void* d_y = dalloc(yb); - if (!d_a || !d_as || !d_w || !d_s || !d_y) { ok("gemm_fp8a8_f32scale forms", false, "allocation failed"); return; } + if (!d_a || !d_al || !d_as || !d_w || !d_s || !d_y) { ok("gemm_fp8a8_f32scale forms", false, "allocation failed"); return; } { std::vector a((size_t)(M * K)), w(wb); for (size_t i = 0; i < a.size(); ++i) @@ -14683,6 +15613,9 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int for (size_t i = 0; i < w.size(); ++i) w[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i + 0x9e37u) % 2001) - 1000) / 500); st_memcpy(d_a, a.data(), a.size(), hipMemcpyHostToDevice); + /* The same rows at a pitch of K + 8 bytes. */ + st_memcpy2d(d_al, (size_t)(K + 8), a.data(), (size_t)K, (size_t)K, (size_t)M, + hipMemcpyHostToDevice); for (int c = 0; c < copies; ++c) st_memcpy((uint8_t*)d_w + (size_t)c * wb, w.data(), wb, hipMemcpyHostToDevice); std::vector as((size_t)(M * sk)), s(sb / 4); @@ -14703,18 +15636,16 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int 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; - const char* saved = std::getenv("RADIANCE_FP8F32_FORM"); - const std::string keep = saved ? saved : ""; - auto set = [](const char* form) { - if (form) setenv("RADIANCE_FP8F32_FORM", form, 1); - else unsetenv("RADIANCE_FP8F32_FORM"); - }; - auto run = [&](const char* form, std::vector* out) -> int { - set(form); + /* `legacy` reads the rows at the pitch off 16 bytes. */ + auto run = [&](bool legacy, std::vector* out) -> int { std::vector fill(yb, 0xa5); st_memcpy(d_y, fill.data(), yb, hipMemcpyHostToDevice); + ts[0].data = legacy ? d_al : d_a; + ts[0].stride[0] = legacy ? K + 8 : K; ts[2].data = d_w; const int rc = r->launch(&a, nullptr); + ts[0].data = d_a; + ts[0].stride[0] = K; if (rc != RAD_OK) return rc; if (st_stream_sync(nullptr) != hipSuccess) return (int)RAD_E_DEVICE; out->resize(yb); @@ -14722,47 +15653,30 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int return (int)RAD_OK; }; std::vector legacy, got; - const int lrc = run("legacy", &legacy); + const int lrc = run(true, &legacy); ok(fmt("gemm_fp8a8_f32scale legacy form at M=%lld N=%lld K=%lld", (long long)M, (long long)N, (long long)K).c_str(), lrc == RAD_OK); - static const char* kForms[] = { "decode", "decode1x16", "decode2x16", "decode3x8", - "decode1x8x2", "decode1x8x4", "decode2x8x2", "decode3x8x2", - "decode2x4x4", "rows1", "rows4", nullptr }; + const int rc = lrc == RAD_OK ? run(false, &got) : lrc; if (lrc == RAD_OK) { - for (const char* const* f = kForms;; ++f) { - const int rc = run(*f, &got); - const bool same = rc == RAD_OK && got == legacy; - size_t first = 0; - if (rc == RAD_OK && !same) while (first < got.size() && got[first] == legacy[first]) ++first; - ok(fmt("gemm_fp8a8_f32scale form %s at M=%lld N=%lld K=%lld: byte-identical to legacy", - *f ? *f : "default", (long long)M, (long long)N, (long long)K).c_str(), - same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); - if (!*f) break; - } + const bool same = rc == RAD_OK && got == legacy; + size_t first = 0; + if (rc == RAD_OK && !same) while (first < got.size() && got[first] == legacy[first]) ++first; + ok(fmt("gemm_fp8a8_f32scale at M=%lld N=%lld K=%lld: byte-identical to legacy", + (long long)M, (long long)N, (long long)K).c_str(), + same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); } - if (timed && lrc == RAD_OK) { + if (timed && rc == RAD_OK) { const double bytes = (double)(wb + sb), flop = 2.0 * (double)M * (double)N * (double)K; std::printf("\ngemm_fp8a8_f32scale N=%lld K=%lld M=%lld %.2f MiB weight + scales, %d copies, " "%d iters\n", (long long)N, (long long)K, (long long)M, bytes / (1 << 20), copies, iters); - static const char* kTimed[] = { "legacy", "decode1x8", "decode1x16", "decode3x8", - "decode1x8x2", "decode1x16x2", "decode1x4x4", - "decode1x8x4", "decode2x8x2", "decode2x4x2", - "decode2x4x4", "decode3x8x2", "decode3x4x2", "rows1", - "rows2", nullptr }; - for (const char* const* f = kTimed;; ++f) { - set(*f); - const double us = st_time_us([&](int i) { - ts[2].data = (uint8_t*)d_w + (size_t)(i % copies) * wb; - r->launch(&a, nullptr); - }, iters, nullptr); - std::printf(" %-11s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", *f ? *f : "default", us, - bytes / (us * 1e3), flop / (us * 1e6)); - if (!*f) break; - } + const double us = st_time_us([&](int i) { + ts[2].data = (uint8_t*)d_w + (size_t)(i % copies) * wb; + r->launch(&a, nullptr); + }, iters, nullptr); + std::printf(" %-11s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", "rule", us, + bytes / (us * 1e3), flop / (us * 1e6)); ts[2].data = d_w; } - if (saved) setenv("RADIANCE_FP8F32_FORM", keep.c_str(), 1); - else unsetenv("RADIANCE_FP8F32_FORM"); } /* The block-quantised trunk GEMMs GLM's checkpoints resolve to, at one shape: E4M3 with F32 @@ -22093,6 +23007,20 @@ static void device_phase(const Plugin& pl) { attn_numeric_case(pl, "attn_prefill_h256_gqa6_k6v4", 256, 6, 100, "k6_v4", 0, 1024); attn_numeric_case(pl, "attn_decode_h256_gqa6_k6v4", 256, 6, 1, "k6_v4", 0, 1024); attn_numeric_case(pl, "attn_decode_h256_gqa6_k6v4", 256, 6, 4, "k6_v4", 0, 2048); + /* Flash-Next's QSA layers (#138): 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). */ + for (const char* kv : { "fp8_v4", "k6_v4" }) { + const std::string t = kv[0] == 'f' ? "fp8v4" : "k6v4"; + const std::string p12 = "attn_prefill_h256_gqa12_" + t, d12 = "attn_decode_h256_gqa12_" + t; + const std::string p6 = "attn_prefill_h256_gqa6_bs4_" + t, d6 = "attn_decode_h256_gqa6_bs4_" + t; + attn_numeric_case(pl, p12.c_str(), 256, 12, 64, kv, 0, 1000, 4); + attn_numeric_case(pl, d12.c_str(), 256, 12, 1, kv, 0, 1000, 4); + attn_numeric_case(pl, d12.c_str(), 256, 12, 5, kv, 0, 2048, 4); + attn_numeric_case(pl, p6.c_str(), 256, 6, 64, kv, 0, 1000, 4); + attn_numeric_case(pl, d6.c_str(), 256, 6, 1, kv, 0, 1000, 4); + attn_numeric_case(pl, d6.c_str(), 256, 6, 10, kv, 0, 2048, 4); + } /* A ctx past a whole block (a partial last tile), and q_len 7: three waves, where the V * staging's unit count is not a multiple of the threads. */ for (const char* kv : { "fp8_v4", "k6_v4" }) { @@ -22120,6 +23048,11 @@ static void device_phase(const Plugin& pl) { attn_numeric_case(pl, "attn_decode_h128_gqa2_bf16kv", 128, 2, 24, "bf16", 0, 256); attn_gq_fold_case(pl, 3, false); attn_gq_fold_case(pl, 24, false); + /* And over the fp8_v4 and k6_v4 caches (Flash-Next's --kv-cache-dtype fp8_v4 / k6_v4). */ + for (int kvq : { 1, 2 }) { + attn_gq_fold_case(pl, 3, false, false, kvq); + attn_gq_fold_case(pl, 24, false, false, kvq); + } attn_gq_fold_case(pl, 3, true); attn_gq_fold_case(pl, 24, true); for (const bool bf16 : { false, true }) { @@ -22900,6 +23833,64 @@ static void device_phase(const Plugin& pl) { } } } + /* --- the f32 forms: a latent kept aside and put back, a zeroed f32 scratch --- */ + if (sel("cast_f32_f32")) { + const RadKernelInfo* r = find(pl, "cast_f32_f32"); + if (!r) ok("cast_f32_f32", false, "row absent"); + else { + const int64_t M = 6, n = 36, wide = 2 * n; + std::vector src((size_t)(M * n)); + for (int64_t i = 0; i < M * n; ++i) src[(size_t)i] = 0.37f * (float)((i * 29) % 83) - 9.1f; + void* d_src = dalloc((size_t)M * n * 4); + void* d_dst = dalloc((size_t)M * wide * 4); + std::vector pre((size_t)(M * wide), -7.5f); + st_memcpy(d_src, src.data(), (size_t)M * n * 4, hipMemcpyHostToDevice); + st_memcpy(d_dst, pre.data(), (size_t)M * wide * 4, hipMemcpyHostToDevice); + RadTensor ty = T(d_dst, RAD_F32, { M, n }); + ty.data = (void*)((float*)d_dst + n); + ty.stride[0] = wide; + std::vector ts = { T(d_src, RAD_F32, { M, n }), ty }; + std::vector ps = { PI("M", M), PI("n", n), PS("from", "f32"), PS("to", "f32") }; + run_case(r, ts, ps); + std::vector got((size_t)(M * wide)); + st_memcpy(got.data(), d_dst, (size_t)M * wide * 4, hipMemcpyDeviceToHost); + bool copied = true, spilled = false; + for (int64_t m = 0; m < M; ++m) + for (int64_t c = 0; c < wide; ++c) { + const float g = got[(size_t)(m * wide + c)]; + if (c >= n) copied = copied && std::memcmp(&g, &src[(size_t)(m * n + c - n)], 4) == 0; + else spilled = spilled || g != -7.5f; + } + ok("cast_f32_f32 copies into a column slice, byte for byte", copied); + ok("cast_f32_f32 leaves the columns outside the slice alone", !spilled); + } + } + if (sel("fill_f32")) { + const RadKernelInfo* r = find(pl, "fill_f32"); + if (!r) ok("fill_f32", false, "row absent"); + else { + const int64_t M = 5, n = 40, wide = 2 * n; + void* d = dalloc((size_t)M * wide * 4); + std::vector pre((size_t)(M * wide), -7.5f); + st_memcpy(d, pre.data(), (size_t)M * wide * 4, hipMemcpyHostToDevice); + RadTensor ty = T(d, RAD_F32, { M, n }); + ty.stride[0] = wide; + std::vector ts = { ty }; + std::vector ps = { PI("M", M), PI("n", n), PS("dtype", "f32"), PF("value", 1.37) }; + run_case(r, ts, ps); + std::vector got((size_t)(M * wide)); + st_memcpy(got.data(), d, (size_t)M * wide * 4, hipMemcpyDeviceToHost); + bool val = true, spilled = false; + for (int64_t m = 0; m < M; ++m) + for (int64_t c = 0; c < wide; ++c) { + const float g = got[(size_t)(m * wide + c)]; + if (c < n) val = val && g == 1.37f; + else spilled = spilled || g != -7.5f; + } + ok("fill_f32 writes the value exactly", val); + ok("fill_f32 leaves the columns past the pitch alone", !spilled); + } + } /* --- byte rows: the KV tier's transfer pair --- */ /* Pack and unpack a pool, the real layout in miniature: a "layer" is `rows` blocks of `n` * bytes, a session's blocks are scattered through it, and exactly those blocks must come back. @@ -23704,6 +24695,31 @@ static void device_phase(const Plugin& pl) { if (sel("resize_bilinear")) ups::resize_bilinear_cases(pl); if (sel("patch_fold_f32")) ups::patch_fold_cases(pl); if (sel("flow_renoise_f32")) ups::flow_renoise_cases(pl); + /* The joint image generators' ops. */ + if (sel("table_add_bf16")) g3::table_add_cases(pl); + if (sel("mix_rows_bf16")) g3::mix_rows_cases(pl); + if (sel("chan_stats_bf16")) g3::chan_stats_cases(pl); + if (sel("chan_stats_f32")) g3::chan_stats_f32_cases(pl); + if (sel("attn_cross_h128_bf16")) g3::attn_cross_cases(pl, 128); + if (sel("attn_cross_h64_bf16")) g3::attn_cross_cases(pl, 64); + if (sel("attn_dense_gqa")) g3::attn_dense_gqa_cases(pl); + if (sel("attn_dense_h384_bf16") || sel("attn_dense_h512_bf16")) g3::attn_wide_cases(pl); + if (sel("rms_mod_bf16") || sel("rms_mod_quant_fp8_bf16")) g3::rms_mod_forms(pl); + if (sel("timestep_embed_bf16")) g3::timestep_round_cases(pl); + /* LTX-2's. */ + if (sel("rope_split")) ltx::rope_cases(pl); + if (sel("head_gate")) ltx::gate_cases(pl); + if (sel("ltx_guide")) ltx::guide_cases(pl); + if (sel("pixel_norm")) ltx::pixel_norm_cases(pl); + if (sel("d2s3d") || sel("s2d3d")) ltx::resample_cases(pl); + if (sel("pix_patch") || sel("patch_pix8")) ltx::patch_cases(pl); + if (sel("tile_grid") || sel("tile_crop") || sel("tile_stitch")) ltx::tile_cases(pl); + if (sel("vol_index")) ltx::vol_index_cases(pl); + if (sel("attn_na3d")) ltx::na3d_cases(pl); + if (sel("stft_logmel")) ltx::stft_cases(pl); + if (sel("bwe_up")) ltx::bwe_cases(pl); + if (sel("conv2d_nhwc_bf16")) ltx::conv2d_cases(pl); + if (sel("int_affine")) ltx::int_affine_cases(pl); if (sel("vsa_select_h128_bf16")) vsa::select_cases(pl); if (sel("attn_vsa_h128_bf16")) vsa::attn_cases(pl); if (sel("quant_cols_fp8_bf16")) vsa::quant_cols_cases(pl); @@ -23797,37 +24813,14 @@ static void device_phase(const Plugin& pl) { fp8_f32scale_check(pl, true, 4, true, true, 288); fp8_f32scale_check(pl, true, 65, false); fp8_f32scale_check(pl, true, 65, true); - // The rule takes the expert-major form; pinned, the row tiles stay covered, and every - // stage and column-tile count meets several column tiles, a K of one stage and of - // several, and runs past sixteen rows. - const char* const pins[3] = { "RADIANCE_FP8F32_DECODE_EXPERTS", - "RADIANCE_FP8F32_EXPERTS_STAGE_K", - "RADIANCE_FP8F32_EXPERTS_COLTILES" }; - std::string kept[3]; - bool given[3]; - for (int i = 0; i < 3; ++i) { - const char* v = std::getenv(pins[i]); - given[i] = v; - if (v) kept[i] = v; - } - setenv(pins[0], "0", 1); + // The grouped row's three expert-major tilings, each over several column tiles and runs + // past sixteen rows: K 256 at 128 stages over four column tiles (above), a longer K at the + // 256 stage over four column tiles under 128 routed rows, and over one from there (top_k + // is 4 here). fp8_f32scale_check(pl, true, 17, true, true, 6, 512, 512); - fp8_f32scale_check(pl, true, 65, false); - setenv(pins[0], "1", 1); - for (const char* stage : { "128", "256" }) - for (const char* tiles : { "1", "4" }) { - setenv(pins[1], stage, 1); - setenv(pins[2], tiles, 1); - fp8_f32scale_check(pl, true, 17, true, true, 6, 512, 512); - fp8_f32scale_check(pl, true, 4, false, true, 288, 512, 384); - fp8_f32scale_check(pl, true, 65, false); - } - for (int i = 0; i < 3; ++i) { - if (given[i]) - setenv(pins[i], kept[i].c_str(), 1); - else - unsetenv(pins[i]); - } + fp8_f32scale_check(pl, true, 4, false, true, 288, 512, 384); + fp8_f32scale_check(pl, true, 65, true, true, 6, 512, 512); + fp8_f32scale_check(pl, true, 65, false, true, 288, 512, 384); } if (sel("moe_gemm_w4a8_mod4")) { @@ -23889,17 +24882,14 @@ static void device_phase(const Plugin& pl) { mhc_check(pl, nm, 33, 129, 8); } if (sel("mhc_pre_bf16") || sel("mhc_post_bf16")) { - /* Every finish and partial form and the vector mhc_post against the old dispatch, at the - * decode, verify and prefill row counts and on 16-byte rows, the vector paths' case. */ + /* The vector forms on 16-byte rows against the scalar forms on pitched rows, at the + * decode, verify and prefill row counts. */ for (int64_t rows : { 1, 6, 48, 128, 2048 }) mhcpre_perf(pl, rows, -1); } if (sel("mhc_pre_partial_bf16") || sel("mhc_pre_finish_bf16")) { for (int world : { 2, 4, 8 }) for (int64_t rows : { 1, 4, 31, 32, 33, 65, 130 }) - mhc_split_check(pl, rows, world, nullptr, nullptr); - for (const char* env : { "RADIANCE_MHC_PREFILL_COEFF4", "RADIANCE_MHC_PREFILL_ROWS4", - "RADIANCE_MHC_PREFILL_WARP" }) - for (int64_t rows : { 33, 130 }) mhc_split_check(pl, rows, 8, env, "0"); + mhc_split_check(pl, rows, world); } if (sel("swiglu_clamped_bf16")) { for (int64_t rows : { 1, 7, 33 }) @@ -23980,15 +24970,14 @@ static void device_phase(const Plugin& pl) { } if (sel("mla_project_bf16")) { for (const char* mode : { "absorb", "expand" }) { - for (int64_t rows : { 1, 2, 4, 33 }) + /* Every rows-a-group form (1, 2, 4, 8) and tails past the last full group. */ + for (int64_t rows : { 1, 2, 3, 4, 6, 33, 130 }) for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode); mla_project_check(pl, 1, 1, mode); mla_project_check(pl, 1, 64, mode); for (int64_t rows : { 1, 4, 33 }) for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode, true); } - /* Every row form against the one-row kernels, byte for byte, with tails at 3, 33 and 130. */ - for (int64_t rows : { 1, 3, 6, 33, 130 }) project_forms(pl, rows, -1); } if (sel("mla_attn_matrix_bf16")) { mla_check(pl, 7, 16, 17, "mla_attn_matrix_bf16"); @@ -24026,13 +25015,9 @@ static void device_phase(const Plugin& pl) { swaps); mla_check(pl, 33, 8, 513, "mla_attn_matrix_bf16", MlaFill::topk, "mla_attn_bf16", 0, 16); mla_check(pl, 4, 16, 65, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 4); - { /* The positional pairing, kept for comparison; tables wider than the union's lists - * (kUnionBlocks, 520) take it too. */ - ScopedEnv positional("RADIANCE_MLA_PAIR", "pos"); - mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr); - mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr); - mla_check(pl, 7, 8, 65, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 16); - } + /* Tables wider than the union's lists (kUnionBlocks, 520) take the positional pairing. */ + mla_check(pl, 33, 8, 521, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr); + mla_check(pl, 7, 8, 521, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr); mla_check(pl, 4, 8, 600, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 16); /* The element-wise key load, the fallback for a cache the vectors cannot read. */ mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr, 1); @@ -24048,8 +25033,8 @@ static void device_phase(const Plugin& pl) { kda_check(pl, mode, false, accepted, true); kda_check(pl, mode, true, accepted, true); } - /* Every form against the one-row shuffle-sum kernel, byte for byte, in all four modes. */ - for (int64_t M : { 1, 7, 48, 300 }) kda_forms(pl, M, -1); + /* GLM's TP8 shape against libref, in all four modes. */ + for (int64_t M : { 1, 7, 48, 300 }) kda_perf(pl, M, -1); } if (sel("moe_gemm_mxfp4a8")) { for (int m : { 1, 17, 65, 257 }) @@ -24067,151 +25052,32 @@ static void device_phase(const Plugin& pl) { for (int shape : { 1, 2, 3, 4 }) mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, "sorted", shape, false, 288, 8); mx_experts_check(pl, 1, 1, false, "token", 0, true); - // The rule takes the expert-major form at decode (at GLM's TP8 slices also above). Pinned, - // the row groups and the TP8 prefill form stay covered, and every expert-major stage and - // column-tile count meets narrow, parted and wide experts and runs of a hundred rows. - // Both weight decodes (RADIANCE_MXFP4_LUT) meet every form; dropped slots inside the runs - // and runs under 16 rows (288 experts) reach the TP8 prefill form at 65 and 257 tokens, - // with and without its stage prefetch (RADIANCE_MXFP4_PREFILL_PIPE). - constexpr int kPins = 10; - const char* const pins[kPins] = { - "RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_EXPERTS_STAGE_K", - "RADIANCE_MXFP4_EXPERTS_COLTILES", "RADIANCE_MXFP4_LUT", - "RADIANCE_MXFP4_ALIGNED_JOBS", "RADIANCE_MXFP4_PREFILL_N32", - "RADIANCE_MXFP4_PREFILL_M32", "RADIANCE_MXFP4_PREFILL_N64", - "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", "RADIANCE_MXFP4_PREFILL_PIPE" - }; - std::string kept[kPins]; - bool given[kPins]; - for (int i = 0; i < kPins; ++i) { - const char* v = std::getenv(pins[i]); - given[i] = v; - if (v) kept[i] = v; - } - // P64 is the rule at GLM's TP8 slices from 769 rows; off here, so the forms above stay the - // ones these cases name, and pinned or by its rule further down. - constexpr int kP64 = 12; - const char* const p64[kP64] = { "RADIANCE_MXFP4_PREFILL_P64", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", - "RADIANCE_MXFP4_PREFILL_P64_BM", - "RADIANCE_MXFP4_PREFILL_P64_BN", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", - "RADIANCE_MXFP4_PREFILL_P64_COLTILES", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", - "RADIANCE_MXFP4_PREFILL_P64_T_BM64", - "RADIANCE_MXFP4_PREFILL_P64_T_BN128", - "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", - "RADIANCE_MXFP4_PREFILL_P64_DB" }; - std::string kept64[kP64]; - bool given64[kP64]; - for (int i = 0; i < kP64; ++i) { - const char* v = std::getenv(p64[i]); - given64[i] = v; - if (v) kept64[i] = v; - } - for (int i = 1; i < kP64; ++i) unsetenv(p64[i]); - setenv(p64[0], "0", 1); - for (const char* lut : { "0", "1" }) { - setenv(pins[3], lut, 1); - setenv(pins[0], "0", 1); - for (int shape : { 1, 2, 3, 4 }) - mx_experts_check(pl, 17, shape % 2 ? 2 : 1, false, "sorted", shape); - mx_experts_check(pl, 1, 1, false, "token", 0, true); - for (const char* pipe : { "0", "1" }) { - setenv(pins[9], pipe, 1); - for (int shape : { 3, 4 }) { - mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, "sorted", shape, false, 288, - 8); - for (int m : { 65, 257 }) - mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, - shape == 4 ? "sorted" : "token", shape, false, 288, 8, - true); - } - // The TP8 prefill form outside GLM's slices: E8M0 codes 0 and 255, narrower and - // shorter odd experts, dropped slots. - for (int i = 4; i < 9; ++i) setenv(pins[i], "1", 1); - mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); - mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); - for (int i = 4; i < 9; ++i) unsetenv(pins[i]); - } - unsetenv(pins[9]); - setenv(pins[0], "1", 1); - for (const char* stage : { "128", "256" }) - for (const char* tiles : { "1", "4" }) { - setenv(pins[1], stage, 1); - setenv(pins[2], tiles, 1); - mx_experts_check(pl, 17, 1, false, "sorted", 2); - mx_experts_check(pl, 4, 2, true, "token", 3); - mx_experts_check(pl, 17, 2, false, "token"); - mx_experts_check(pl, 257, 2, true, "sorted"); - mx_experts_check(pl, 65, 1, false, "sorted", 4, false, 288, 8, true); - } - unsetenv(pins[1]); - unsetenv(pins[2]); - } - // The P64 form pinned below its row bounds: every BM x BN x stage at GLM's TP8 slices over - // 288 experts and 65 tokens (runs of about two rows, dropped slots), column tiles 1 and 4 - // with and without the LDS output at 257 tokens, and outside GLM's slices E8M0 codes 0 and - // 255 with narrower and shorter odd experts; then by its rule at 1024, 2048 and 4096 tokens - // (gate_up BM32 BN64 K256, BM64 BN64 K256 and BM64 BN128 K128 with the LDS output, down BM32 - // BN64 K128 x4 and BM64 BN128 K128 x4 with the LDS output). It always takes the table decode. - auto pin = [&](int bm, int bn, int sk, int ct, int out, int db = 0) { - const int v[8] = { 1, 0, 0, bm, bn, sk, ct, out }; - for (int i = 0; i < 8; ++i) setenv(p64[i], std::to_string(v[i]).c_str(), 1); - setenv(p64[11], db ? "1" : "0", 1); - }; - setenv(pins[0], "0", 1); - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - for (int sk : { 128, 256 }) { - pin(bm, bn, sk, 4, 0); - for (int shape : { 3, 4 }) - mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, - shape == 4 ? "sorted" : "token", shape, false, 288, 8, - true); - } - for (int out : { 0, 1 }) - for (int ct : { 1, 4 }) { - pin(64, 128, 128, ct, out); - for (int shape : { 3, 4 }) - mx_experts_check(pl, 257, shape % 2 ? 2 : 1, true, - shape == 4 ? "sorted" : "token", shape, false, 288, 8, true); - } - for (int out : { 0, 1 }) { - pin(64, 128, 128, 4, out); - mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); - mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); - } - // The double buffer at gate_up's slice wherever two stages fit, and with E8M0 codes 0 and - // 255 outside GLM's slices. - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) { - pin(bm, bn, 128, 4, bm == 64 && bn == 128, 1); - mx_experts_check(pl, 257, 2, true, "token", 3, false, 288, 8, true); - } - pin(32, 64, 256, 4, 0, 1); - mx_experts_check(pl, 257, 2, true, "token", 3, false, 288, 8, true); + // The form follows the routed rows (top_k 2 away from GLM, 8 at its 288 experts). Away + // from GLM's slices the row groups from 512 rows: E8M0 codes 0 and 255, narrower and + // shorter odd experts, dropped slots. mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); - for (int i = 0; i < kP64; ++i) unsetenv(p64[i]); - unsetenv(pins[0]); - for (int m : { 1024, 2048 }) - for (int shape : { 3, 4 }) - mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, shape == 4 ? "sorted" : "token", + mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); + // At GLM's TP4 slices the GLM prefill form from 512 rows, with dropped slots and runs under + // 16 rows, and with E8M0 codes 0 and 255. + for (int shape : { 1, 2 }) + for (int m : { 65, 257 }) { + mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, shape == 2 ? "sorted" : "token", shape, false, 288, 8, true); - mx_experts_check(pl, 4096, 1, true, "sorted", 4, false, 288, 8, true); - for (int i = 0; i < kP64; ++i) { - if (given64[i]) - setenv(p64[i], kept64[i].c_str(), 1); - else - unsetenv(p64[i]); - } - for (int i = 0; i < kPins; ++i) { - if (given[i]) - setenv(pins[i], kept[i].c_str(), 1); - else - unsetenv(pins[i]); - } + mx_experts_check(pl, m, shape % 2 ? 2 : 1, false, shape == 2 ? "sorted" : "token", + shape, true, 288, 8); + } + // At GLM's TP8 slices the expert-major form to its bound (gate_up 768 rows, down below + // P64's 5760), then P64 by its rule: gate_up BM32 BN64 K256 from 769 rows, BM64 BN64 K256 + // from 12288 and BM64 BN128 K128 with the LDS output from 24576; down BM32 BN64 K128 x4 + // from 5760 rows and BM64 BN128 K128 x4 with the LDS output from 24576. + mx_experts_check(pl, 96, 2, true, "token", 3, false, 288, 8, true); + mx_experts_check(pl, 719, 1, true, "sorted", 4, false, 288, 8, true); + for (int m : { 97, 1024, 2048, 3072 }) + mx_experts_check(pl, m, 2, true, "token", 3, false, 288, 8, true); + for (int m : { 720, 1024, 2048, 4096 }) + mx_experts_check(pl, m, 1, true, "sorted", 4, false, 288, 8, true); + mx_experts_check(pl, 1024, 2, false, "token", 3, true, 288, 8); + mx_experts_check(pl, 1024, 1, false, "sorted", 4, true, 288, 8); } if (sel("hc_read_e4m3")) { @@ -24614,8 +25480,8 @@ static void usage(void) { " --perf N K M [iters]: time the fp8 decode GEMMs at one shape and print the\n" " weight bandwidth each reaches.\n" " --perfbf16 N K M [iters]: the bf16 skinny GEMM at every variant it has.\n" - " --perff32 N K M [iters]: gemm_nt_f32 at every tile form, each compared byte\n" - " for byte with the legacy kernel, with GB/s and TFLOP/s.\n" + " --perff32 N K M [iters]: gemm_nt_f32 at the tile form its rule picks, compared\n" + " byte for byte with the host arithmetic, with GB/s and TFLOP/s.\n" " --perfq N K M [iters]: the block-quantised trunk rows GLM resolves to: E4M3 with\n" " F32 block scales and the three OCP-MXFP4 rows, GB/s on weight + scales.\n" " --perfw8 N K M [iters]: the 8-bit trunk GEMMs -- block E4M3 W8A8 and the int8\n" @@ -24669,27 +25535,22 @@ static void usage(void) { " --perfmxf8 M [iters] [experts] [top_k] [skew]: the same at the FP8 experts with f32\n" " block scales (moe_gemm_fp8a8_f32scale, GLM's MTP layer).\n" " --perfmhcpre M [iters]: mhc_pre (whole, partials alone, finish alone) and\n" - " mhc_post at GLM's shape, every form against the old dispatch.\n" + " mhc_post at GLM's shape, 16-byte rows against pitched ones.\n" " --perfrouter M [iters]: router_sigmoid_topk at GLM's shape (288 experts, top 8),\n" - " the wave-per-row select against the serial scan.\n" + " the wave-per-row select timed.\n" " --perfmoefuse M [iters]: GLM's decode fusions of the MoE block at M token\n" " rows (288 experts, top 8, TP8 widths), each against the separate\n" " launches it replaces: time of both and a byte comparison of every\n" " output (`= old` or DIFFERS). The router fusion takes M <= 128.\n" " --perfkda M [iters]: kda_update at GLM's TP8 shape: prefill of M tokens (one\n" - " sequence, and three anchored) and the 8x6 verify step, every row and\n" - " prefetch form timed and compared byte for byte with the old kernel.\n" - " --perfproject M [iters]: mla_project at GLM's TP8 shape, both modes, every\n" - " rows-a-group form timed and compared byte for byte with the old kernels.\n" + " sequence, and three anchored) and the 8x6 verify step, timed.\n" + " --perfproject M [iters]: mla_project at GLM's TP8 shape, both modes, timed.\n" " --perfmx M [iters] [experts] [top_k] [skew]: the MXFP4 expert GEMM at GLM's\n" " TP8 slices (gate_up 512 x 4096, down 4096 x 256) over a routing of an\n" " M-token chunk (288 experts, top 8 by default; uniform, or `skew` a Gamma\n" " CV per expert as g1.0 or a Zipf exponent as z1.1): time, touched weight\n" - " bytes, GB/s and TFLOP/s per projection; the rule, the expert-major form\n" - " at each pinned stage and column-tile count, the row groups and from 512\n" - " routed rows every prefill form and the P64 raster (BM x BN x stage,\n" - " down also x column tiles), each compared with the bytes of the pinned\n" - " TP8 prefill form.\n" + " bytes, GB/s and TFLOP/s per projection of the form the rule picks, and\n" + " how often it streams each touched expert slice.\n" " --perfmla M blocks heads [iters] [fill]: MLA attention without the oracle, so\n" " a 2048-row prefill chunk at 2k/8k context fits (blocks 513/2049).\n" " The wave row and the matrix row at both key loads (paired tiles at\n" @@ -24778,7 +25639,7 @@ int main(int argc, char** argv) { perf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perff32")) { - /* gemm_nt_f32 at every tile form (see f32_forms). */ + /* gemm_nt_f32 at its rule's tile form (see f32_forms). */ if (i + 3 >= argc) { usage(); return 2; } perf_f32 = 1; perf_n = std::strtoll(argv[++i], nullptr, 0); @@ -24874,7 +25735,7 @@ int main(int argc, char** argv) { if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_it = (int)std::strtol(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_dt = argv[++i]; } else if (!std::strcmp(argv[i], "--perfmhcpre")) { - /* mhc_pre and mhc_post at GLM's shape, every form, against the old dispatch. */ + /* mhc_pre and mhc_post at GLM's shape, 16-byte rows against pitched ones. */ if (i + 1 >= argc) { usage(); return 2; } mhc_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) mhc_it = (int)std::strtol(argv[++i], nullptr, 0); @@ -24887,7 +25748,7 @@ int main(int argc, char** argv) { mf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) mf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfkda") || !std::strcmp(argv[i], "--perfproject")) { - /* kda_update or mla_project at GLM's TP8 shape, every form, against the old kernel. */ + /* kda_update or mla_project at GLM's TP8 shape, timed. */ if (i + 1 >= argc) { usage(); return 2; } const bool kda = !std::strcmp(argv[i], "--perfkda"); (kda ? kda_m : proj_m) = std::strtoll(argv[++i], nullptr, 0); @@ -24895,7 +25756,7 @@ int main(int argc, char** argv) { (kda ? kda_it : proj_it) = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfmx") || !std::strcmp(argv[i], "--perfmxf8")) { mx_f8 = !std::strcmp(argv[i], "--perfmxf8"); - /* An expert GEMM at GLM's TP8 slices over an M-token chunk, every form: MXFP4, or with + /* An expert GEMM at GLM's TP8 slices over an M-token chunk: MXFP4, or with * --perfmxf8 the FP8 experts with f32 block scales. */ if (i + 1 >= argc) { usage(); return 2; } mx_m = std::strtoll(argv[++i], nullptr, 0); @@ -25058,8 +25919,8 @@ int main(int argc, char** argv) { if (kda_m || proj_m) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP - if (kda_m) kda_forms(pl, kda_m, kda_it); - if (proj_m) project_forms(pl, proj_m, proj_it); + if (kda_m) kda_perf(pl, kda_m, kda_it); + if (proj_m) project_perf(pl, proj_m, proj_it); dfree_all(); #else skip("kda_update and mla_project timing", "built without HIP"); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 8caf64ae..880482b3 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -316,11 +316,11 @@ extern "C" int r4d_shape_cast(const RadParam* p, int n_p, int operand, const int64_t M = pi(p, n_p, "M"); const int64_t n = pi(p, n_p, "n"); - /* Three rows serve the op, bf16 -> bf16 (a strided row copy), bf16 -> f32 and bf16 -> f16, - * and the shims refuse any other pair, so another pair is declined here. */ + /* The rows serve bf16 -> bf16 and f32 -> f32 (strided row copies), bf16 -> f32, bf16 -> f16 + * and f32 -> bf16, and the shims refuse any other pair, so another pair is declined here. */ const uint32_t f = dt_par(p, n_p, "from"), t = dt_par(p, n_p, "to"); - if (f != (uint32_t)RAD_BF16 || - (t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32 && t != (uint32_t)RAD_F16)) + const uint32_t bf = (uint32_t)RAD_BF16, f32 = (uint32_t)RAD_F32, f16 = (uint32_t)RAD_F16; + if (!(f == bf && (t == bf || t == f32 || t == f16)) && !(f == f32 && (t == bf || t == f32))) return RAD_E_UNSUPPORTED; const RadOpdDesc l[] = { opd(f, M, n), opd(t, M, n) }; R4D_PICK(l); diff --git a/libr4d/r4d_upscaler.hip b/libr4d/r4d_upscaler.hip index 361dc46e..6e51b0ec 100644 --- a/libr4d/r4d_upscaler.hip +++ b/libr4d/r4d_upscaler.hip @@ -51,10 +51,49 @@ __device__ __forceinline__ void st8(float* p, const float* f) { *(float4*)p = make_float4(f[0], f[1], f[2], f[3]); *(float4*)(p + 4) = make_float4(f[4], f[5], f[6], f[7]); } -// Eight per-channel values of an f32 or bf16 vector, its dtype known only at run time. -__device__ __forceinline__ void ld8w(const void* p, bool f32, int c, float* f) { - if (f32) ld8((const float*)p + c, f); - else ld8((const uint16_t*)p + c, f); +// Four- and two-channel forms of the above, and a chunk of CW (8, 4 or 2) channels through them. +__device__ __forceinline__ void ld4(const uint16_t* p, float* f) { + const uint2 u = *(const uint2*)p; + f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y); +} +__device__ __forceinline__ void ld4(const float* p, float* f) { + const float4 a = *(const float4*)p; + f[0] = a.x; f[1] = a.y; f[2] = a.z; f[3] = a.w; +} +__device__ __forceinline__ void st4(uint16_t* p, const float* f) { + *(uint2*)p = make_uint2(bf16x2_rne(f[0], f[1]), bf16x2_rne(f[2], f[3])); +} +__device__ __forceinline__ void st4(float* p, const float* f) { + *(float4*)p = make_float4(f[0], f[1], f[2], f[3]); +} +__device__ __forceinline__ void ld2(const uint16_t* p, float* f) { + const uint32_t u = *(const uint32_t*)p; + f[0] = bf16w_lo(u); f[1] = bf16w_hi(u); +} +__device__ __forceinline__ void ld2(const float* p, float* f) { + const float2 a = *(const float2*)p; + f[0] = a.x; f[1] = a.y; +} +__device__ __forceinline__ void st2(uint16_t* p, const float* f) { + *(uint32_t*)p = bf16x2_rne(f[0], f[1]); +} +__device__ __forceinline__ void st2(float* p, const float* f) { + *(float2*)p = make_float2(f[0], f[1]); +} +template __device__ __forceinline__ void ldc(const T* p, float* f) { + if constexpr (CW == 8) ld8(p, f); + else if constexpr (CW == 4) ld4(p, f); + else ld2(p, f); +} +template __device__ __forceinline__ void stc(T* p, const float* f) { + if constexpr (CW == 8) st8(p, f); + else if constexpr (CW == 4) st4(p, f); + else st2(p, f); +} +// CW per-channel values of an f32 or bf16 vector, its dtype known only at run time. +template __device__ __forceinline__ void ldcw(const void* p, bool f32, int c, float* f) { + if (f32) ldc((const float*)p + c, f); + else ldc((const uint16_t*)p + c, f); } // The volume a request runs at: (T, H, W) and its row count, or false for a geometry the operands @@ -101,6 +140,11 @@ __device__ __forceinline__ bool volume_of(const int* geom, long long rows, int* // guarded load instead, its last tile running past K), so neither operand's addresses cost vector // arithmetic per tile. // +// `tpad` pads the frames other than with zeros (LTX-2's VAE): 1 replicate, the frame clamped into +// the volume; 2 causal, output frame t's tap dt reading frame max(t + dt - 1 - tpre, 0), so the +// output has tpre more frames than the input. A neighbour's frame is resolved when its offset is, +// once a tap. +// // Measured on the R9700 at 300 W, warm, against gemm_nt_bias at bf16 at the same M, N and K = 27 // cin: 512 -> 512 at 84 x 48 x 37 148 TFLOP/s (the GEMM 146), at 42 x 24 x 37 149 (145). The // select-and-pointer form of the gather this replaces ran 136 and 134: its loop issued twice the @@ -133,13 +177,13 @@ __device__ __forceinline__ unsigned short conv_finish(float acc, float bv, unsig /* `vec` (host-checked): y, res and the bias take 16-byte accesses at every eight-column boundary. * `xrows` bounds the volume the device geometry may name, `xbytes` is x's extent (at most kOob) - * and `Mcap` bounds the rows written. */ + * and `Mcap` bounds the rows written; `tpad` and `tpre` as above. */ template __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel( const unsigned short* __restrict__ X, const unsigned short* __restrict__ Wt, const void* __restrict__ bias, const unsigned short* R, unsigned short* C, const int* __restrict__ geom, unsigned ldx, unsigned ldr, unsigned ldc, int Mcap, int xrows, - unsigned xbytes, int cin, int N, unsigned vec) { + unsigned xbytes, int cin, int N, unsigned vec, int tpad, int tpre) { typedef r4d_u32x4 U4; __shared__ __attribute__((aligned(16))) unsigned char s_a[2][kCBM * kCPB]; @@ -147,7 +191,8 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel( long long vol; if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return; const int HW = gH * gW; - const int Mv = vol < (long long)Mcap ? (int)vol : Mcap; + const long long ovol = vol + (long long)tpre * HW; + const int Mv = ovol < (long long)Mcap ? (int)ovol : Mcap; const uint32_t tid = threadIdx.x, lane = tid & 31u; const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5); @@ -197,10 +242,14 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel( const int delta = dt * HW + dy * gW + dx; #pragma unroll for (uint32_t i = 0; i < kCSPT; ++i) { - const bool ok = tap < kTaps && (unsigned)(vt[i] + dt) < (unsigned)gT && + int ft = vt[i] + dt; + if (tpad == 1) ft = min(max(ft, 0), gT - 1); + else if (tpad == 2) ft = max(ft - 1 - tpre, 0); + const bool ok = tap < kTaps && vt[i] >= 0 && (unsigned)ft < (unsigned)gT && (unsigned)(vy[i] + dy) < (unsigned)gH && (unsigned)(vx[i] + dx) < (unsigned)gW; - off[i] = ok ? (uint32_t)(vm[i] + delta) * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob; + const int src = tpad ? (ft * gH + vy[i] + dy) * gW + vx[i] + dx : vm[i] + delta; + off[i] = ok ? (uint32_t)src * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob; } }; @@ -387,9 +436,9 @@ __device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, flo n = nab; } -/* `cpr_log`: log2 of the chunks a row (n / 8, a power of two dividing the block); `gs8` the chunks - * a group. */ -template +/* `cpr_log`: log2 of the chunks a row (n / CW, a power of two dividing the block); `gs8` the + * chunks a group. A chunk is CW channels: 8, or 4 for groups of 4 channels. */ +template __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x, float* __restrict__ stats, int M, int groups, int cpr_log, int gs8, int ldx, int rpp) { @@ -401,16 +450,16 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x, const int r0 = p * rpp, r1 = min(M, r0 + rpp); float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f; for (int r = r0 + slot; r < r1; r += slots) { - float v[8]; - ld8(x + (size_t)r * ldx + c * 8, v); + float v[CW]; + ldc(x + (size_t)r * ldx + c * CW, v); if (cnt == 0.0f) shift = v[0]; #pragma unroll - for (int j = 0; j < 8; ++j) { + for (int j = 0; j < CW; ++j) { const float d = v[j] - shift; s1 += d; s2 += d * d; } - cnt += 8.0f; + cnt += (float)CW; } float mean = 0.0f, m2 = 0.0f; if (cnt > 0.0f) { @@ -466,7 +515,7 @@ __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, /* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32 * one. x and y may be the same memory: a thread reads its chunk before it writes it. */ -template +template __global__ __launch_bounds__(kT) void gn_apply_kernel( const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b, const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log, @@ -475,27 +524,27 @@ __global__ __launch_bounds__(kT) void gn_apply_kernel( const int tid = threadIdx.x; const int r = blockIdx.x * slots + (tid >> cpr_log); if (r >= M) return; - const int ck = tid & ((1 << cpr_log) - 1), c = ck * 8; + const int ck = tid & ((1 << cpr_log) - 1), c = ck * CW; const int g = ck / gs8; const float mean = stats[2 * g], rstd = stats[2 * g + 1]; - float v[8], wv[8], bv[8]; - ld8(x + (size_t)r * ldx + c, v); - ld8w(w, wf != 0, c, wv); - ld8w(b, bf != 0, c, bv); + float v[CW], wv[CW], bv[CW]; + ldc(x + (size_t)r * ldx + c, v); + ldcw(w, wf != 0, c, wv); + ldcw(b, bf != 0, c, bv); #pragma unroll - for (int j = 0; j < 8; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j]; + for (int j = 0; j < CW; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j]; if (modk) { - float sc[8], sf[8]; - ld8w(mod, modk == 2, c, sc); - ld8w(mod, modk == 2, n + c, sf); + float sc[CW], sf[CW]; + ldcw(mod, modk == 2, c, sc); + ldcw(mod, modk == 2, n + c, sf); #pragma unroll - for (int j = 0; j < 8; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j]; + for (int j = 0; j < CW; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j]; } if (silu) { #pragma unroll - for (int j = 0; j < 8; ++j) v[j] = v[j] / (1.0f + expf(-v[j])); + for (int j = 0; j < CW; ++j) v[j] = v[j] / (1.0f + expf(-v[j])); } - st8(y + (size_t)r * ldy + c, v); + stc(y + (size_t)r * ldy + c, v); } // ---------------------------------------------------------------------------- tconv_dw @@ -720,6 +769,15 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) { if (r4d_numel(w) < cout * K || r4d_numel(b) < cout || r4d_numel(geom) < 3) return R4D_NO(RAD_E_SHAPE); if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE); + const char* tp = r4d_gets(a, "tpad"); + int tpad = 0; + if (tp && *tp) { + if (!std::strcmp(tp, "replicate")) tpad = 1; + else if (!std::strcmp(tp, "causal")) tpad = 2; + else if (std::strcmp(tp, "zero")) return R4D_NO(RAD_E_INVAL); + } + const long long tpre = r4d_geti_or(a, "tpre", 0); + if (tpre < 0 || tpre > 64 || (tpre && tpad != 2)) return R4D_NO(RAD_E_INVAL); long long rx = 0, ldx = 0, ry = 0, rr = 0; if (!rows8(x, cin, &rx, &ldx) || !r4d_aligned(r4d_p(w), 16)) return R4D_NO(RAD_E_STRIDE); const long long ldy = r4d_rows_pitch(y, cout, &ry); @@ -747,7 +805,8 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) { #define C3_L(C6, RS, BF) \ return R4D_EMIT(stream, (conv3d_kernel), grid, dim3(kCThreads), 0, Xp, Wp, Bp, Rp, \ Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, (unsigned)ldy, \ - (int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec) + (int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec, tpad, \ + (int)tpre) #define C3_RES(C6, BF) do { if (res) C3_L(C6, true, BF); C3_L(C6, false, BF); } while (0) #define C3_BF(C6) do { if (bf32) C3_RES(C6, true); C3_RES(C6, false); } while (0) if (c64) C3_BF(true); @@ -774,12 +833,14 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { if (!std::strcmp(act, "silu")) silu = 1; else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL); } - /* A thread an 8-channel chunk inside one group, a row's chunks a power of two dividing the - * 256-thread block. */ - const int cpr_log = (n > 0 && !(n & 7)) ? log2_exact(n / 8) : -1; - if (cpr_log < 0 || n / 8 > kT || groups <= 0 || groups > kT || n % groups || - (n / groups) % 8) + /* A thread a chunk of CW channels inside one group (8; 4 for groups of 4 channels, the + * FLUX.2 VAE's 128 channels in 32 groups; 2 for groups of 2), a row's chunks a power of two + * dividing the 256-thread block. */ + if (groups <= 0 || groups > kT || n <= 0 || n % groups || (n / groups) % 2) return R4D_NO(RAD_E_SHAPE); + const int CW = (n / groups) % 8 == 0 ? 8 : (n / groups) % 4 == 0 ? 4 : 2; + const int cpr_log = log2_exact(n / CW); + if (cpr_log < 0 || n / CW > kT) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) || r4d_numel(st) < groups * (2 + 3 * kGnParts)) return R4D_NO(RAD_E_SHAPE); @@ -797,29 +858,36 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { long long rpp = (M + kGnParts - 1) / kGnParts; rpp = (rpp + slots - 1) / slots * slots; const int parts = (int)((M + rpp - 1) / rpp); - const int gs8 = (int)(n / groups / 8); + const int gs8 = (int)(n / groups / CW); float* S = (float*)r4d_wp(st); const float eps = (float)r4d_getf(a, "eps", 1e-5); int rc; - if (is_f32(x)) - rc = R4D_EMIT(stream, gn_part_kernel, dim3((unsigned)parts), dim3(kT), 0, - (const float*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, - (int)rpp); - else - rc = R4D_EMIT(stream, gn_part_kernel, dim3((unsigned)parts), dim3(kT), 0, - (const uint16_t*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, - (int)rpp); +#define GN_P(TX, C4) \ + rc = R4D_EMIT(stream, (gn_part_kernel), dim3((unsigned)parts), dim3(kT), 0, \ + (const TX*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, (int)rpp) + if (is_f32(x)) { + if (CW == 8) GN_P(float, 8); + else if (CW == 4) GN_P(float, 4); + else GN_P(float, 2); + } else { + if (CW == 8) GN_P(uint16_t, 8); + else if (CW == 4) GN_P(uint16_t, 4); + else GN_P(uint16_t, 2); + } +#undef GN_P if (rc != RAD_OK) return R4D_NO(rc); rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups, parts, eps); if (rc != RAD_OK) return R4D_NO(rc); const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1; const dim3 grid((unsigned)((M + slots - 1) / slots)); -#define GN_A(TX, TY) \ - return R4D_EMIT(stream, (gn_apply_kernel), grid, dim3(kT), 0, (const TX*)r4d_p(x), \ +#define GN_A2(TX, TY, C4) \ + return R4D_EMIT(stream, (gn_apply_kernel), grid, dim3(kT), 0, (const TX*)r4d_p(x),\ (TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \ (int)n, cpr_log, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \ modk, silu) +#define GN_A(TX, TY) \ + do { if (CW == 8) GN_A2(TX, TY, 8); if (CW == 4) GN_A2(TX, TY, 4); GN_A2(TX, TY, 2); } while (0) if (is_f32(x)) { if (is_f32(y)) GN_A(float, float); GN_A(float, uint16_t); @@ -827,6 +895,7 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { if (is_f32(y)) GN_A(uint16_t, float); GN_A(uint16_t, uint16_t); #undef GN_A +#undef GN_A2 } /* ------------------------------------------------------------------ tconv_dw */ diff --git a/libr4d/r4d_video.hip b/libr4d/r4d_video.hip index c1134cc6..aebd18aa 100644 --- a/libr4d/r4d_video.hip +++ b/libr4d/r4d_video.hip @@ -82,7 +82,8 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel( const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s, const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq, - float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld) { + float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld, float wadd, + int once, int layer, int none) { __shared__ float sh[kT / 32]; const int r = blockIdx.x; const int e = seq_of(cu, n_seq, r); @@ -109,7 +110,32 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel( for (int j = 0; j < 8; ++j) { v[k][j] = f[j]; ss += f[j] * f[j]; } } } - const float rs = 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps); + /* A LayerNorm centres first: the mean's block sum, then the centred squares'. */ + float mu = 0.0f; + if (layer) { + float sm = 0.0f; + #pragma unroll + for (int k = 0; k < kRmChunks; ++k) { + const int i = ((int)threadIdx.x + k * kT) * 8; + if (i < n) { + #pragma unroll + for (int j = 0; j < 8; ++j) sm += v[k][j]; + } + } + mu = block_sum(sm, sh) / (float)n; + __syncthreads(); + ss = 0.0f; + #pragma unroll + for (int k = 0; k < kRmChunks; ++k) { + const int i = ((int)threadIdx.x + k * kT) * 8; + if (i < n) { + #pragma unroll + for (int j = 0; j < 8; ++j) { v[k][j] -= mu; ss += v[k][j] * v[k][j]; } + } + } + } + /* `none`: no norm (libref's n2 = x); the flag is the same for the whole workgroup. */ + const float rs = none ? 1.0f : 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps); const uint16_t* sr = s + (size_t)e * s_ld; #pragma unroll for (int k = 0; k < kRmChunks; ++k) { @@ -118,10 +144,11 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel( float shf[8], scf[8], wf[8], o[8]; ld8(sr + i, shf); ld8(sr + n + i, scf); - ld8(w + i, wf); + if (w) ld8(w + i, wf); #pragma unroll for (int j = 0; j < 8; ++j) { - const float n2 = bfr(bfr(v[k][j] * rs) * wf[j]); + const float n1 = once ? v[k][j] * rs : bfr(v[k][j] * rs); + const float n2 = w ? bfr(n1 * (wf[j] + wadd)) : bfr(v[k][j] * rs); o[j] = bfr(bfr(n2 * bfr(1.0f + scf[j])) + shf[j]); } if (z) st8(z + (size_t)r * z_ld + i, o); @@ -431,10 +458,10 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) { const RadTensor* q = quant ? r4d_opt(a, 6) : nullptr; const RadTensor* qs = quant ? r4d_opt(a, 7) : nullptr; const RadTensor* z = r4d_opt(a, quant ? 8 : 6); - if (!sc || !w || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL); + if (!sc || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL); const bool gated = r4d_geti_or(a, "gated", 0) != 0; if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL); - if (!is_bf16(x) || !is_bf16(sc) || !is_bf16(w) || !is_i32(cu) || + if (!is_bf16(x) || !is_bf16(sc) || (w && !is_bf16(w)) || !is_i32(cu) || (gated && (!is_bf16(y) || !is_bf16(g))) || (z && !is_bf16(z)) || (quant && (q->dtype != RAD_F8E4M3 || qs->dtype != RAD_F32))) return R4D_NO(RAD_E_DTYPE); @@ -445,7 +472,7 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) { long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0; long long rq = 0, rqs = 0, ql = 0, qsl = 0; if (!rows8(x, n, &rx, &xl) || !rows8(sc, 2 * n, &rs, &sl) || !r4d_contig(cu) || - !r4d_contig(w) || ((uintptr_t)w->data & 15) || + (w && (!r4d_contig(w) || ((uintptr_t)w->data & 15))) || (gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) || (z && !rows8(z, n, &rz, &zl))) return R4D_NO(RAD_E_STRIDE); @@ -455,18 +482,26 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) { if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE); } const long long n_seq = r4d_numel(cu) - 1, rows = quant ? rq : rz; - if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || r4d_numel(w) < n || + if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || (w && r4d_numel(w) < n) || (quant && rqs < rows) || (gated && (ry < rows || rg < n_seq)) || (z && rz < rows)) return R4D_NO(RAD_E_SHAPE); const float eps = (float)r4d_getf(a, "eps", 1e-6); + const float wadd = (float)r4d_getf(a, "wadd", 0.0); + const int once = (int)r4d_geti_or(a, "norm_once", 0); + const char* nk = r4d_gets(a, "norm"); + const int layer = nk && !std::strcmp(nk, "layer"); + const int none = nk && !std::strcmp(nk, "none"); + if ((nk && !layer && !none && std::strcmp(nk, "rms")) || (none && w)) return R4D_NO(RAD_E_INVAL); #define R4D_RMQ(G, Q) \ hipLaunchKernelGGL((rms_mod_kernel), dim3((unsigned)rows), dim3(kT), 0, \ (hipStream_t)st, G ? (const uint16_t*)y->data : nullptr, \ G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \ - (const uint16_t*)w->data, (const int*)cu->data, (uint16_t*)x->data, \ + w ? (const uint16_t*)w->data : nullptr, (const int*)cu->data, \ + (uint16_t*)x->data, \ Q ? (uint8_t*)q->data : nullptr, Q ? (float*)qs->data : nullptr, \ z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \ - (int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl) + (int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl, wadd, once, layer, \ + none) if (quant) { if (gated) R4D_RMQ(true, true); else R4D_RMQ(false, true); diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index b8fed97e..d5c0ccd4 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -353,6 +353,156 @@ int ref_attn_dense(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ attn_cross */ +/* attn_dense with each entry's keys a run of their own: entry `s`'s queries are rows + * [cu[s], cu[s+1]) of `q` and its keys and values rows [cu_k[s], cu_k[s+1]) of `k` and `v`. With + * `causal` a query sees key j of its run when j <= its own index in its entry, both counted from + * the start: a video's rows reading its prompt (cross attention), or a padded prompt's rows of which + * the padding sees only the prompt. A query that sees no key is zero. */ +int ref_attn_cross(const RadArgs* a, RadStream) { + if (!have(a, 6)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *cuk = &a->t[4]; + const RadTensor *o = &a->t[5]; + const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0); + const int64_t gqa = p_int(a, "gqa", 1); + const int causal = (int)p_int(a, "causal", 0); + if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE; + if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED; + const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2] + : (q->rank == 2 ? q->shape[1] / head_dim : 1); + const int64_t kv_heads = q_heads / gqa; + if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1; + if (n_seq <= 0 || numel(cuk) < n_seq + 1) return RAD_E_SHAPE; + const int64_t total_q = numel(q) / (q_heads * head_dim); + const int64_t total_k = numel(k) / (kv_heads * head_dim); + if (total_q <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */ + if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE; + for (int64_t s = 0; s < n_seq; ++s) + if (cu_at(cu, s + 1) < cu_at(cu, s) || cu_at(cuk, s + 1) < cu_at(cuk, s) || + cu_at(cu, s + 1) > total_q || cu_at(cuk, s + 1) > total_k) + return RAD_E_SHAPE; + + 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 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 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 = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); + + REF_PAR_FOR(total_q * q_heads * head_dim * 64) + for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) { + const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa; + const int64_t b0 = cu_at(cu, s), b1 = cu_at(cu, s + 1); + const int64_t k0 = cu_at(cuk, s), k1 = cu_at(cuk, s + 1); + for (int64_t i = b0; i < b1; ++i) { + const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs; + const int64_t jend = causal ? std::min(k1, k0 + (i - b0) + 1) : k1; + float mx = -INFINITY; + for (int64_t j = k0; j < jend; ++j) { + const int64_t kb = j * k_rs + kh * k_hs; + float dot = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) + dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds); + dot *= scale; + if (dot > mx) mx = dot; + } + if (mx == -INFINITY) { + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f); + continue; + } + float acc[REF_HD_MAX]; + for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int64_t j = k0; j < jend; ++j) { + const int64_t kb = j * k_rs + kh * k_hs, vb = j * v_rs + kh * v_hs; + float dot = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) + dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds); + const float w = ref_exp(dot * scale - mx); + sum += w; + for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * ldt(v, vb + d * v_ds); + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv); + } + } + return RAD_OK; +} + +/* attn_na3d: 3-D neighborhood attention, NATTEN's na3d (LTX-2.5's diffusion decoder). The rows of + * q, k, v and out are the voxels of the volume geom = (T, H, W), i32 on the device, (t, i, j) + * row-major. A query attends the keys of a window `kt` x `kh` x `kw` (each extent at most its + * axis) centred on it and shifted inward at the border: along an axis of L and window n the + * window starts at clamp(c - n / 2, 0, L - n). Per head, in f32: each score the dot over d + * ascending times `scale` (default 1 / sqrt(head_dim)), the window's keys in raster order, the + * softmax as attn_cross takes it (the maximum, then the exponentials' sum), the output rounded to + * its dtype. Rows past T H W are not written. */ +int ref_attn_na3d(const RadArgs* a, RadStream) { + if (!have(a, 5)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *G = &a->t[3], *o = &a->t[4]; + const int64_t head_dim = p_int(a, "head_dim", 0); + const int64_t kt = p_int(a, "kt", 0), kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0); + if (head_dim <= 0 || kt <= 0 || kh <= 0 || kw <= 0 || numel(G) < 3 || q->rank != 2) + return RAD_E_SHAPE; + if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED; + const int64_t heads = q->shape[1] / head_dim; + const int64_t T = cu_at(G, 0), H = cu_at(G, 1), W = cu_at(G, 2); + if (heads <= 0 || q->shape[1] % head_dim || T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; + const int64_t N = std::min(q->shape[0], T * H * W); + if (N <= 0 || numel(k) < N * heads * head_dim || numel(v) < N * heads * head_dim || + numel(o) < N * heads * head_dim) + return RAD_E_SHAPE; + const int64_t nt = std::min(kt, T), nh = std::min(kh, H), nw = std::min(kw, W); + const int64_t q_ds = q->stride[1], q_rs = row_stride(q, heads * head_dim); + const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1, k_rs = row_stride(k, heads * head_dim); + const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1, v_rs = row_stride(v, heads * head_dim); + const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1, o_rs = row_stride(o, heads * head_dim); + const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim)); + auto start = [](int64_t c, int64_t n, int64_t L) { + return std::min(std::max(c - n / 2, 0), L - n); + }; + REF_PAR_FOR(N * heads * nt * nh * nw * head_dim) + for (int64_t rh = 0; rh < N * heads; ++rh) { + const int64_t r = rh / heads, h = rh % heads; + const int64_t t = r / (H * W), i = (r / W) % H, j = r % W; + const int64_t t0 = start(t, nt, T), i0 = start(i, nh, H), j0 = start(j, nw, W); + const int64_t qb = r * q_rs + h * head_dim * q_ds, ob = r * o_rs + h * head_dim * o_ds; + auto score = [&](int64_t key) { + const int64_t kb = key * k_rs + h * head_dim * k_ds; + float dot = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds); + return dot * scale; + }; + float mx = -INFINITY; + for (int64_t a1 = t0; a1 < t0 + nt; ++a1) + for (int64_t b1 = i0; b1 < i0 + nh; ++b1) + for (int64_t c1 = j0; c1 < j0 + nw; ++c1) mx = std::max(mx, score((a1 * H + b1) * W + c1)); + float acc[REF_HD_MAX]; + for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; + float sum = 0.0f; + for (int64_t a1 = t0; a1 < t0 + nt; ++a1) + for (int64_t b1 = i0; b1 < i0 + nh; ++b1) + for (int64_t c1 = j0; c1 < j0 + nw; ++c1) { + const int64_t key = (a1 * H + b1) * W + c1; + const float w = ref_exp(score(key) - mx); + sum += w; + const int64_t vb = key * v_rs + h * head_dim * v_ds; + for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * ldt(v, vb + d * v_ds); + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ kv_store */ /* Writes this step's keys and values into the paged cache at `slot_mapping`. The cache is INOUT, * not OUT: only mapped slots are touched and every other slot must survive, which the buffer diff --git a/libref/ref_audio.cpp b/libref/ref_audio.cpp index c4d4357c..e7bb319a 100644 --- a/libref/ref_audio.cpp +++ b/libref/ref_audio.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include @@ -712,6 +713,39 @@ int ref_iota(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ int_affine */ +/* y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j], the three lists space-separated integers + * of one length: shapes and sequence bounds a model derives from a pass's device geometry (a + * decoder's volume at each of its scales). y holds at least the lists' length. */ +static int parse_ints(const char* s, int64_t* v, int cap) { + int n = 0; + while (s && *s) { + char* e = nullptr; + const long long x = std::strtoll(s, &e, 10); + if (e == s) break; + if (n == cap) return -1; + v[n++] = x; + s = e; + } + return n; +} + +int ref_int_affine(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + int64_t src[16], mul[16], add[16]; + const int n = parse_ints(p_str(a, "src", ""), src, 16); + if (n <= 0 || parse_ints(p_str(a, "mul", ""), mul, 16) != n || + parse_ints(p_str(a, "add", ""), add, 16) != n || numel(y) < n) + return RAD_E_SHAPE; + for (int j = 0; j < n; ++j) { + if (src[j] >= numel(x)) return RAD_E_SHAPE; + const int64_t v = src[j] < 0 ? 0 : ld_int(x->dtype, x->data, offlin(x, src[j])); + st_int(y->dtype, y->data, offlin(y, j), v * mul[j] + add[j]); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ cu_repeat */ /* Sequence bounds of equal sequences: y[j] = j * len[0] * mult over y's elements. A pass's * lengths live on the device (a window's frames, the latents a vocoder decodes per channel group), diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp index 4246cc3f..4c42ed12 100644 --- a/libref/ref_gen.cpp +++ b/libref/ref_gen.cpp @@ -168,7 +168,7 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) { static int rms_mod_check(const RadTensor* y, const RadTensor* g, const RadTensor* s, const RadTensor* w, const RadTensor* x, int64_t n, int64_t n_seq, int64_t rows, bool gated) { - if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || numel(w) < n || + if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || (w && numel(w) < n) || numel(s) < n_seq * 2 * n) return RAD_E_SHAPE; if (gated && (rows_of(y, n) < rows || numel(g) < n_seq * n)) return RAD_E_SHAPE; @@ -184,10 +184,17 @@ static int rms_mod_check(const RadTensor* y, const RadTensor* g, const RadTensor * * The sum of squares is f32 in ascending order, read from the stored residual. `s` is * [n_seq, >= 2n] at its own row pitch, shift = s[e, 0:n] and scale = s[e, n:2n] (a column slice - * of the modulation table). The residual rounds to x's dtype and the norm chain to `dt`. */ + * of the modulation table). The residual rounds to x's dtype and the norm chain to `dt`. + * + * `wadd` is added to the gain in f32 (a zero-centred norm's 1 + w), and with `once` the norm and + * its gain round together, n2 = bf16(x rsqrt(...) (w + wadd)), as an f32 RMS norm with a gain + * stores its output (Krea 2's). With `layer` the norm is a LayerNorm (FLUX's, which has no gain: + * `w` absent), and with `none` there is no norm and no gain, n2 = x (LTX-2's text keys and values, + * modulated as they are). */ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* s, const RadTensor* w, const RadTensor* x, int64_t r, int64_t e, int64_t n, - float eps, bool gated, uint32_t dt, float* o) { + float eps, bool gated, uint32_t dt, float* o, float wadd = 0.0f, + bool once = false, bool layer = false, bool none = false) { const int64_t xb = rowoff(x, r, n), xs = laststride(x); if (gated) { const int64_t g_rs = row_stride(g, n), g_cs = laststride(g); @@ -197,13 +204,24 @@ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* stt(x, xb + i * xs, ldt(x, xb + i * xs) + p); } } + /* RMS: x rsqrt(mean(x^2) + eps). Layer: (x - mean) rsqrt(var + eps), the biased variance of + * the centred values; both sums f32 in ascending order. */ + float mu = 0.0f; + if (layer) { + for (int64_t i = 0; i < n; ++i) mu += ldt(x, xb + i * xs); + mu /= (float)n; + } float ss = 0.0f; - for (int64_t i = 0; i < n; ++i) { const float v = ldt(x, xb + i * xs); ss += v * v; } + for (int64_t i = 0; i < n && !none; ++i) { const float v = ldt(x, xb + i * xs) - mu; ss += v * v; } const float rs = 1.0f / std::sqrt(ss / (float)n + eps); - const int64_t s_rs = row_stride(s, 2 * n), s_cs = laststride(s), ws = laststride(w); + const int64_t s_rs = row_stride(s, 2 * n), s_cs = laststride(s), ws = w ? laststride(w) : 0; for (int64_t i = 0; i < n; ++i) { - const float n1 = round_dt(dt, ldt(x, xb + i * xs) * rs); - const float n2 = round_dt(dt, n1 * ldt(w, i * ws)); + const float v = ldt(x, xb + i * xs) - mu; + /* With no gain the norm is rounded once, as a norm without a weight stores it. */ + const float n2 = none ? round_dt(dt, v) + : !w ? round_dt(dt, v * rs) + : once ? round_dt(dt, v * rs * (ldt(w, i * ws) + wadd)) + : round_dt(dt, round_dt(dt, v * rs) * (ldt(w, i * ws) + wadd)); const float sc = round_dt(dt, 1.0f + ldt(s, e * s_rs + (n + i) * s_cs)); const float m = round_dt(dt, n2 * sc); o[i] = round_dt(dt, m + ldt(s, e * s_rs + i * s_cs)); @@ -215,18 +233,24 @@ static void rms_mod_row(const RadTensor* y, const RadTensor* g, const RadTensor* * the norm chain rounds to z's dtype. */ int ref_rms_mod(const RadArgs* a, RadStream) { if (a->n_t < 7) return RAD_E_INVAL; - const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = &a->t[3]; + const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3); const RadTensor *cu = &a->t[4], *x = &a->t[5], *z = &a->t[6]; const int64_t n = p_int(a, "n", 0); const bool gated = p_int(a, "gated", 0) != 0; const float eps = p_f32(a, "eps", 1e-6f); + const float wadd = p_f32(a, "wadd", 0.0f); + const bool once = p_int(a, "norm_once", 0) != 0; + const char* nk = p_str(a, "norm", "rms"); + const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0; + if (!layer && !none && std::strcmp(nk, "rms") != 0) return RAD_E_INVAL; + if (none && t_in(a, 3)) return RAD_E_INVAL; if (n <= 0 || (gated && (!y || !g))) return RAD_E_SHAPE; const int64_t rows = rows_of(z, n), n_seq = numel(cu) - 1; RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated)); REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { std::vector o((size_t)n); - rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, z->dtype, o.data()); + rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, z->dtype, o.data(), wadd, once, layer, none); const int64_t zb = rowoff(z, r, n), zs = laststride(z); for (int64_t i = 0; i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]); } @@ -238,11 +262,17 @@ int ref_rms_mod(const RadArgs* a, RadStream) { * bound. */ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) { if (a->n_t < 9) return RAD_E_INVAL; - const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = &a->t[3]; + const RadTensor *y = t_in(a, 0), *g = t_in(a, 1), *s = &a->t[2], *w = t_in(a, 3); const RadTensor *cu = &a->t[4], *x = &a->t[5], *q = &a->t[6], *sc = &a->t[7], *z = t_in(a, 8); const int64_t n = p_int(a, "n", 0), grp = p_int(a, "group", 0); const bool gated = p_int(a, "gated", 0) != 0; const float eps = p_f32(a, "eps", 1e-6f); + const float wadd = p_f32(a, "wadd", 0.0f); + const bool once = p_int(a, "norm_once", 0) != 0; + const char* nk = p_str(a, "norm", "rms"); + const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0; + if (!layer && !none && std::strcmp(nk, "rms") != 0) return RAD_E_INVAL; + if (none && t_in(a, 3)) return RAD_E_INVAL; if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE; const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp; RAD_REF_TRY(rms_mod_check(y, g, s, w, x, n, n_seq, rows, gated)); @@ -250,7 +280,7 @@ int ref_rms_mod_quant_fp8(const RadArgs* a, RadStream) { REF_PAR_FOR(rows * n) for (int64_t r = 0; r < rows; ++r) { std::vector o((size_t)n); - rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, RAD_BF16, o.data()); + rms_mod_row(y, g, s, w, x, r, seq_of(cu, n_seq, r), n, eps, gated, RAD_BF16, o.data(), wadd, once, layer, none); const int64_t zb = z ? rowoff(z, r, n) : 0, zs = z ? laststride(z) : 0; for (int64_t i = 0; z && i < n; ++i) stt(z, zb + i * zs, o[(size_t)i]); const int64_t qb = rowoff(q, r, n), qs = laststride(q); @@ -283,7 +313,8 @@ int ref_timestep_embed(const RadArgs* a, RadStream) { const float coef = (float)(-std::log(mp)); for (int64_t m = 0; m < rows; ++m) { const float tv = ldt(t, offlin(t, m)); - const float tt = round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv; + const float tt = round == 3 ? rbf(scale * rbf(tv)) : round == 2 ? scale * rbf(tv) + : round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv; const int64_t yb = rowoff(y, m, n), ys = laststride(y); for (int64_t i = 0; i < h; ++i) { const float f = ref_exp(coef * (float)i / (float)h); @@ -545,6 +576,8 @@ int ref_chan_affine(const RadArgs* a, RadStream) { * pad same k / 2 zeros on every side * pad down no zeros above and left, one below and right: ZeroPad2d((0, 1, 0, 1)) then the conv, * as a stride-2 downsample does + * pad causal k - 1 zeros above, none below, k / 2 a side across: a convolution causal along + * the rows (LTX-2's audio VAE, whose rows are time) * * f32 accumulation over (kh, kw, cin), the bias added, one rounding. */ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { @@ -554,14 +587,16 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1); const char* pad = p_str(a, "pad", "same"); const bool down = pad && !std::strcmp(pad, "down"); + const bool causal = pad && !std::strcmp(pad, "causal"); if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE; if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE; const int64_t Hin = x->shape[0], Win = x->shape[1] / cin; const int64_t Ho = y->shape[0], Wo = y->shape[1] / cout; if (Hin <= 0 || Win <= 0 || Ho <= 0 || Wo <= 0) return RAD_E_SHAPE; const int64_t Hv = Hin * up, Wv = Win * up; - const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2; - if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo) + const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2; + const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2; + if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo) return RAD_E_SHAPE; if (numel(w) < cout * cin * k * k || numel(b) < cout) return RAD_E_SHAPE; const int64_t xr = x->stride[0], yr = y->stride[0]; @@ -574,7 +609,7 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { const int64_t iy = oy * stride + kh - pt; if (iy < 0 || iy >= Hv) continue; for (int64_t kw = 0; kw < k; ++kw) { - const int64_t ix = ox * stride + kw - pt; + const int64_t ix = ox * stride + kw - pl; if (ix < 0 || ix >= Wv) continue; const int64_t xb = (iy / up) * xr + (ix / up) * cin; for (int64_t ci = 0; ci < cin; ++ci) @@ -895,3 +930,90 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) { } return RAD_OK; } + +/* ------------------------------------------------------------------ table_add */ +/* y[r, l n + c] = x[r, c] + t[l, c] for every row of `x` and every row l of the table: a shared + * modulation plus each block's own learned table (Krea 2's, LTX-2's), all blocks in one pass. The + * sum is f32, rounded once to y's dtype. `x` and `y` are read at their own row pitches. */ +int ref_table_add(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *T = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0), L = p_int(a, "L", 0); + if (n <= 0 || L <= 0 || numel(T) < L * n) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, L * n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const int64_t xs = laststride(X), ys = laststride(Y), ts = laststride(T); + REF_PAR_FOR(rows * L * n) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, L * n); + for (int64_t l = 0; l < L; ++l) + for (int64_t c = 0; c < n; ++c) + stt(Y, yb + (l * n + c) * ys, + ldt(X, xb + c * xs) + ldt(T, (l * n + c) * ts)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ mix_rows */ +/* y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows (Krea 2's + * text fusion folds twelve tapped layers of a token into one row). f32 sum in ascending i, rounded + * once to y's dtype. */ +int ref_mix_rows(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2]; + const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0); + if (n <= 0 || k <= 0 || numel(W) < k) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows * k) return RAD_E_SHAPE; + const int64_t xs = laststride(X), ys = laststride(Y), ws = laststride(W); + REF_PAR_FOR(rows * n * k) + for (int64_t r = 0; r < rows; ++r) { + const int64_t yb = rowoff(Y, r, n); + for (int64_t c = 0; c < n; ++c) { + float acc = 0.0f; + for (int64_t i = 0; i < k; ++i) + acc += ldt(W, i * ws) * ldt(X, rowoff(X, r * k + i, n) + c * xs); + stt(Y, yb + c * ys, acc); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ chan_stats */ +/* A latent normalised or denormalised by per-channel statistics a VAE keeps as weights: `mean` and + * `s` [n], `s` a standard deviation, or with `var` 1 a variance (std = sqrt(s + eps), a BatchNorm's + * running statistics). Each statistic is rounded to y's dtype as the reference casts it, and + * every step is a tensor the reference stores: `denorm` y = rd(rd(x std) + mean), `norm` + * y = rd(rd(x - mean) / std). */ +int ref_chan_stats(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Mn = &a->t[1], *Sd = &a->t[2], *Y = &a->t[3]; + const int64_t n = p_int(a, "n", 0); + const bool var = p_int(a, "var", 0) != 0; + const float eps = p_f32(a, "eps", 0.0f); + const char* mode = p_str(a, "mode", "denorm"); + const bool norm = std::strcmp(mode, "norm") == 0; + if (!norm && std::strcmp(mode, "denorm") != 0) return RAD_E_INVAL; + if (n <= 0 || numel(Mn) < n || numel(Sd) < n) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const uint32_t dt = Y->dtype; + std::vector mu((size_t)n), sd((size_t)n); + for (int64_t c = 0; c < n; ++c) { + mu[(size_t)c] = round_dt(dt, ldt(Mn, c * laststride(Mn))); + const float v = ldt(Sd, c * laststride(Sd)); + sd[(size_t)c] = round_dt(dt, var ? std::sqrt(v + eps) : v); + } + const int64_t xs = laststride(X), ys = laststride(Y); + REF_PAR_FOR(rows * n) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n); + for (int64_t c = 0; c < n; ++c) { + const float x = ldt(X, xb + c * xs); + const float y = norm ? round_dt(dt, round_dt(dt, x - mu[(size_t)c]) / sd[(size_t)c]) + : round_dt(dt, round_dt(dt, x * sd[(size_t)c]) + mu[(size_t)c]); + stt(Y, yb + c * ys, y); + } + } + return RAD_OK; +} diff --git a/libref/ref_ltx.cpp b/libref/ref_ltx.cpp new file mode 100644 index 00000000..b4aa348b --- /dev/null +++ b/libref/ref_ltx.cpp @@ -0,0 +1,722 @@ +/* ref_ltx.cpp -- LTX-2's ops (docs/OPS.md, "LTX-2"): its rotary over fractional coordinates, the + * per-head attention gate, and the sampler step that combines a step's guidance passes in the + * clean-estimate space. + * + * Every rounding follows the upstream model, which runs its transformer in bf16 and its rotary, + * guidance and sampler in f32 (diffusers' transformer_ltx2.py and pipeline_ltx2.py). + */ +#include "ref_common.h" +#include "ref_gemm.h" +#include "ref_ops.h" + +#include +#include +#include +#include + +using namespace ref; + +namespace { + +inline int64_t ldi(const RadTensor* t, int64_t i) { return ld_int(t->dtype, t->data, offlin(t, i)); } + +/* torch.linspace(0, 1, steps) in f64: the first half up from the start, the second down from the + * end, as torch computes it. */ +double linspace01(int64_t i, int64_t steps) { + if (steps <= 1) return 0.0; + const double step = 1.0 / (double)(steps - 1); + return i < steps / 2 ? step * (double)i : 1.0 - step * (double)(steps - 1 - i); +} + +int parse_list_f32(const char* s, std::vector* out) { + out->clear(); + while (s && *s) { + char* end = nullptr; + const double v = std::strtod(s, &end); + if (end == s) break; + out->push_back((float)v); + s = end; + } + return (int)out->size(); +} + +/* Element (d, r) of a [C, M] operand at its own strides; an integer operand reads as its value. */ +float pos_at(const RadTensor* p, int64_t d, int64_t r) { + const int64_t off = p->rank >= 2 ? d * p->stride[0] + r * p->stride[1] : r * laststride(p); + return ldt(p, off); +} + +} /* namespace */ + +/* ------------------------------------------------------------------ rope_split */ +/* LTX-2's rotary (LTX2AudioVideoRotaryPosEmbed, "split"): over the full width `dim` of all heads, + * P = dim / 2 pairs, the first `pad` = P - steps n_dims of them unrotated and the rest the + * frequency ladder freq[k] = f32(theta^linspace(0, 1, steps)[k] pi / 2) (f64 before the cast), + * steps = P / n_dims, its pairs interleaving the coordinates: pair pad + k n_dims + d turns by + * coordinate d at freq[k]. A coordinate c becomes the angle a = f32(f32(2 f32(c / max[d])) - 1) + * freq[k]. Head h owns pairs [h hd/2, (h+1) hd/2) and rotates its halves against each other, + * + * o1 = f32(f32(x1 cos a) - f32(x2 sin a)) o2 = f32(f32(x2 cos a) + f32(x1 sin a)) + * + * rounded to x's dtype. `head0` is the first head this operand holds (a rank's share). `x` is + * [M, >= n_head head_dim] at its own row pitch; `positions` [n_dims, M], f32 or integer, at its own + * strides. */ +int ref_rope_split(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *P = &a->t[1]; + const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0); + const int64_t dim = p_int(a, "dim", 0), nd = p_int(a, "n_dims", 0), h0 = p_int(a, "head0", 0); + const double theta = (double)p_f32(a, "theta", 10000.0f); + std::vector mx; + if (nh <= 0 || hd <= 0 || (hd & 1) || nd <= 0 || dim < (h0 + nh) * hd || + parse_list_f32(p_str(a, "max", ""), &mx) != (int)nd) + return RAD_E_SHAPE; + const int64_t P2 = dim / 2, steps = P2 / nd, pad = P2 - steps * nd, half = hd / 2; + const int64_t rows = rows_of(X, nh * hd); + if (rows <= 0 || P->rank < 1) return RAD_E_SHAPE; + std::vector freq((size_t)steps); + for (int64_t k = 0; k < steps; ++k) + freq[(size_t)k] = (float)(std::pow(theta, linspace01(k, steps)) * M_PI / 2.0); + const int64_t xs = laststride(X); + REF_PAR_FOR(rows * nh * hd) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, nh * hd); + for (int64_t h = 0; h < nh; ++h) + for (int64_t i = 0; i < half; ++i) { + const int64_t p = (h0 + h) * half + i; + if (p < pad) continue; /* cos 1, sin 0: the value as it is */ + const int64_t j = p - pad, d = j % nd, k = j / nd; + const float g = pos_at(P, d, r) / mx[(size_t)d]; + const float ang = (2.0f * g - 1.0f) * freq[(size_t)k]; + const float c = (float)std::cos((double)ang), s = (float)std::sin((double)ang); + const int64_t o1 = xb + (h * hd + i) * xs, o2 = xb + (h * hd + half + i) * xs; + const float x1 = ldt(X, o1), x2 = ldt(X, o2); + const float a1 = x1 * c, b1 = x2 * s, a2 = x2 * c, b2 = x1 * s; + stt(X, o1, a1 - b1); + stt(X, o2, a2 + b2); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ head_gate */ +/* LTX-2's gated attention: each head's output times 2 sigmoid of its logit, + * x = rd(x rd(2 rd(sigmoid(g)))) (the sigmoid of the bf16 logit rounded, doubled exactly). `g` is + * [M, >= n_head], `x` [M, >= n_head head_dim], each at its own row pitch. */ +int ref_head_gate(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *G = &a->t[0], *X = &a->t[1]; + const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0); + if (nh <= 0 || hd <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(X, nh * hd); + if (rows <= 0 || rows_of(G, nh) < rows) return RAD_E_SHAPE; + const int64_t xs = laststride(X), gs = laststride(G); + REF_PAR_FOR(rows * nh * hd) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, nh * hd), gb = rowoff(G, r, nh); + for (int64_t h = 0; h < nh; ++h) { + const float lg = ldt(G, gb + h * gs); + const float sg = round_dt(G->dtype, 1.0f / (1.0f + std::exp(-lg))); + const float gate = round_dt(X->dtype, 2.0f * sg); + for (int64_t i = 0; i < hd; ++i) { + const int64_t o = xb + (h * hd + i) * xs; + stt(X, o, ldt(X, o) * gate); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ ltx_guide */ +/* One LTX-2 sampler step over a modality's latent `x` (f32 [M, n]) from its guidance passes' + * velocities (each [M, n] at its own pitch, read as f32 as the pipeline upcasts them): + * + * x0_p = f32(x - f32(v_p sigma)) for every pass p + * g = x0_c [+ f32(f32(gs - 1) f32(x0_c - x0_u))] [+ f32(stg f32(x0_c - x0_s))] + * [+ f32(f32(ms - 1) f32(x0_c - x0_m))] left to right, f32 + * with rescale r > 0: g = f32(f32(r f32(g f32(std(x0_c) / std(g)))) + f32(f32(1 - r) g)) + * v = f32(f32(x - g) / sigma) x = f32(x + f32(f32(sigma_next - sigma) v)) + * + * A bracketed term is taken when its pass is bound and its coefficient is not zero (gs, ms 1; + * stg 0). std is the unbiased deviation over all M n values, accumulated in f64. `scales` is f32 + * [4] (gs, stg, ms, r) and `sched` f32 [2] (sigma, sigma_next), both read on the device; `stats` is + * the implementation's scratch (libref leaves it untouched). */ +int ref_ltx_guide(const RadArgs* a, RadStream) { + if (a->n_t < 8) return RAD_E_INVAL; + const RadTensor *Vc = &a->t[0], *Vu = t_in(a, 1), *Vs = t_in(a, 2), *Vm = t_in(a, 3); + const RadTensor *Sc = &a->t[4], *Sh = &a->t[5], *X = &a->t[7]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0 || numel(Sc) < 4 || numel(Sh) < 2) return RAD_E_SHAPE; + const int64_t rows = rows_of(X, n); + if (rows <= 0 || rows_of(Vc, n) < rows || (Vu && rows_of(Vu, n) < rows) || + (Vs && rows_of(Vs, n) < rows) || (Vm && rows_of(Vm, n) < rows)) + return RAD_E_SHAPE; + const float gs = ldt(Sc, 0), stg = ldt(Sc, laststride(Sc)), ms = ldt(Sc, 2 * laststride(Sc)); + const float rr = ldt(Sc, 3 * laststride(Sc)); + const float sig = ldt(Sh, 0), sig_n = ldt(Sh, laststride(Sh)); + const bool use_u = Vu && gs != 1.0f, use_s = Vs && stg != 0.0f, use_m = Vm && ms != 1.0f; + const float cu = gs - 1.0f, cm = ms - 1.0f; + const int64_t N = rows * n; + std::vector x0c((size_t)N), g((size_t)N); + auto x0 = [&](const RadTensor* V, int64_t r, int64_t c, float x) { + return x - ldt(V, rowoff(V, r, n) + c * laststride(V)) * sig; + }; + REF_PAR_FOR(N) + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = 0; c < n; ++c) { + const float x = ldt(X, rowoff(X, r, n) + c * laststride(X)); + const float xc = x0(Vc, r, c, x); + float v = xc; + if (use_u) v = v + cu * (xc - x0(Vu, r, c, x)); + if (use_s) v = v + stg * (xc - x0(Vs, r, c, x)); + if (use_m) v = v + cm * (xc - x0(Vm, r, c, x)); + x0c[(size_t)(r * n + c)] = xc; + g[(size_t)(r * n + c)] = v; + } + float fac = 1.0f, keep = 1.0f; + if (rr > 0.0f) { + auto stdev = [&](const std::vector& v) { + double m = 0.0; + for (float e : v) m += e; + m /= (double)N; + double ss = 0.0; + for (float e : v) ss += ((double)e - m) * ((double)e - m); + return (float)std::sqrt(ss / (double)(N > 1 ? N - 1 : 1)); + }; + fac = stdev(x0c) / stdev(g); + keep = (float)(1.0 - (double)rr); + } + const float dt = sig_n - sig; + REF_PAR_FOR(N) + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = 0; c < n; ++c) { + float v = g[(size_t)(r * n + c)]; + if (rr > 0.0f) v = rr * (v * fac) + keep * v; + const int64_t o = rowoff(X, r, n) + c * laststride(X); + const float x = ldt(X, o); + const float vel = (x - v) / sig; + stt(X, o, x + dt * vel); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ pixel_norm */ +/* An RMS norm over each row's n values as a model computes it in bf16 tensors, every step stored: + * + * m = rd(sum_i rd(x_i^2) / n) (f32 sum in ascending i) + * rsqrt form: z_i = rd(x_i rd(1 / sqrt(rd(m + eps)))) + * div form: z_i = rd(x_i / rd(sqrt(rd(m + eps)))) + * + * then with `act` silu z = rd(z / (1 + exp(-z))), and with `mult` z = rd(z mult) (the text + * connectors' scale to the DiT's width). rd is y's dtype. LTX-2's VAE PerChannelRMSNorm + * and audio PixelNorm are the div form; its text connectors' per-layer norm the rsqrt form, whose + * output `ileave` interleaves: row r = t L + l of x (L = ileave) goes to columns c L + l of y's row + * t, the layer index innermost as the reference flattens [C, L]. */ +int ref_pixel_norm(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0), L = p_int(a, "ileave", 1); + const float eps = p_f32(a, "eps", 1e-6f), mult = p_f32(a, "mult", 1.0f); + static const char* const kForms[] = { "rsqrt", "div" }; + static const char* const kActs[] = { "none", "silu" }; + const int form = p_enum(a, "form", kForms, 2, 0), act = p_enum(a, "act", kActs, 2, 0); + if (form < 0 || act < 0 || n <= 0 || L <= 0) return RAD_E_INVAL; + const int64_t rows = rows_of(Y, n * L) * L; + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const uint32_t dt = Y->dtype; + const int64_t xs = laststride(X), ys = laststride(Y); + REF_PAR_FOR(rows * n) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r / L, n * L), l = r % L; + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) { + const float v = ldt(X, xb + i * xs); + ss += round_dt(dt, v * v); + } + const float v = round_dt(dt, round_dt(dt, ss / (float)n) + eps); + const float s = form == 0 ? round_dt(dt, 1.0f / std::sqrt(v)) : round_dt(dt, std::sqrt(v)); + for (int64_t i = 0; i < n; ++i) { + const float x = ldt(X, xb + i * xs); + float z = round_dt(dt, form == 0 ? x * s : x / s); + if (act == 1) z = round_dt(dt, z / (1.0f + std::exp(-z))); + if (mult != 1.0f) z = round_dt(dt, z * mult); + stt(Y, yb + (i * L + l) * ys, z); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ d2s3d / s2d3d */ +/* LTX-2's video VAE resampling over voxel rows (row (t, i, j) of a T x H x W volume, channels + * innermost); `geom` is x's volume, i32 on the device. The packed channel of (c, a, b, d) is + * ((c st + a) sh + b) sw + d, a the frame offset, b the row's, d the column's. + * + * d2s3d, the upsampler's depth to space: y[(t st + a - drop, i sh + b, j sw + d), c] = x[(t, i, + * j), packed(c, a, b, d)], the first `drop` frames dropped (default st - 1, the causal mapping; + * T st - drop out). A copy. */ +int ref_d2s3d(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1); + const int64_t sw = p_int(a, "sw", 1), drop = p_int(a, "drop", st - 1); + if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || drop < 0 || drop >= st || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), P = st * sh * sw; + const int64_t To = T * st - drop, Ho = H * sh, Wo = W * sw; + if (T <= 0 || H <= 0 || W <= 0 || rows_of(X, C * P) < T * H * W || + rows_of(Y, C) < To * Ho * Wo) + return RAD_E_SHAPE; + const int64_t xs = laststride(X), ys = laststride(Y); + REF_PAR_FOR(To * Ho * Wo * C) + for (int64_t r = 0; r < To * Ho * Wo; ++r) { + const int64_t tt = r / (Ho * Wo) + drop, ii = (r / Wo) % Ho, jj = r % Wo; + const int64_t t = tt / st, aa = tt % st, i = ii / sh, b = ii % sh, j = jj / sw, d = jj % sw; + const int64_t xb = rowoff(X, (t * H + i) * W + j, C * P), yb = rowoff(Y, r, C); + for (int64_t c = 0; c < C; ++c) + stt(Y, yb + c * ys, ldt(X, xb + (((c * st + aa) * sh + b) * sw + d) * xs)); + } + return RAD_OK; +} + +/* s2d3d, the downsampler's space to depth: the volume with `tpre` frames prepended (frames 0 .. + * tpre - 1 again, the reference's hs[:, :, :st-1]) cut into st x sh x sw boxes, each box's values + * a packed row. `mode` copy writes the packed row (C st sh sw channels); `mean` averages each run + * of `group` consecutive packed channels (f32 sum, divided, rounded once; the residual's mean). + * With `add` 1 the result is added into y, y = rd(y + v). */ +int ref_s2d3d(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2]; + const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1); + const int64_t sw = p_int(a, "sw", 1), tpre = p_int(a, "tpre", 0), grp = p_int(a, "group", 1); + const bool add = p_int(a, "add", 0) != 0; + static const char* const kModes[] = { "copy", "mean" }; + const int mode = p_enum(a, "mode", kModes, 2, 0); + if (mode < 0) return RAD_E_INVAL; + if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || grp <= 0 || numel(G) < 3) + return RAD_E_SHAPE; + const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), P = C * st * sh * sw; + const int64_t Tv = T + tpre; + if (T <= 0 || Tv % st || H % sh || W % sw || (mode == 1 && P % grp)) return RAD_E_SHAPE; + const int64_t To = Tv / st, Ho = H / sh, Wo = W / sw, Co = mode == 1 ? P / grp : P; + if (rows_of(X, C) < T * H * W || rows_of(Y, Co) < To * Ho * Wo) return RAD_E_SHAPE; + const int64_t xs = laststride(X), ys = laststride(Y); + const uint32_t dt = Y->dtype; + REF_PAR_FOR(To * Ho * Wo * P) + for (int64_t r = 0; r < To * Ho * Wo; ++r) { + const int64_t t = r / (Ho * Wo), i = (r / Wo) % Ho, j = r % Wo; + const int64_t yb = rowoff(Y, r, Co); + auto val = [&](int64_t q) { /* packed channel q of this box */ + const int64_t d = q % sw, b = (q / sw) % sh, aa = (q / (sw * sh)) % st; + const int64_t c = q / (sw * sh * st); + const int64_t v = t * st + aa, tr = v < tpre ? v : v - tpre; + return ldt(X, rowoff(X, (tr * H + i * sh + b) * W + j * sw + d, C) + c * xs); + }; + for (int64_t o = 0; o < Co; ++o) { + float v; + if (mode == 0) { + v = val(o); + } else { + float s = 0.0f; + for (int64_t q = o * grp; q < (o + 1) * grp; ++q) s += val(q); + v = round_dt(dt, s / (float)grp); + } + const int64_t oy = yb + o * ys; + stt(Y, oy, add ? round_dt(dt, ldt(Y, oy)) + round_dt(dt, v) : v); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ pix_patch / patch_pix8 */ +/* LTX-2's patchifier, both ways, over dense 2-D operands whose shapes give the sizes. A patch of + * p x p pixels of C channels is one row of C p p values, channel c's offset (ph, pw) at + * c p p + pw p + ph with `order` wh (LTX-2's: the column offset outer) or c p p + ph p + pw with + * hw. + * + * pix_patch: an image x [H, W C] to patch rows y [H / p, (W / p) C p p]. A copy. */ +static inline int64_t patch_col(int64_t c, int64_t ph, int64_t pw, int64_t p, bool wh) { + return c * p * p + (wh ? pw * p + ph : ph * p + pw); +} + +int ref_pix_patch(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0); + const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0; + if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || X->shape[1] % C) return RAD_E_SHAPE; + const int64_t H = X->shape[0], W = X->shape[1] / C; + if (H <= 0 || W <= 0 || H % p || W % p || Y->shape[0] != H / p || + Y->shape[1] != (W / p) * C * p * p) + return RAD_E_SHAPE; + const int64_t xr = X->stride[0], yr = Y->stride[0]; + REF_PAR_FOR(H * W * C) + for (int64_t y = 0; y < H; ++y) + for (int64_t x = 0; x < W; ++x) + for (int64_t c = 0; c < C; ++c) + stt(Y, (y / p) * yr + (x / p) * C * p * p + patch_col(c, y % p, x % p, p, wh), + ldt(X, y * xr + x * C + c)); + return RAD_OK; +} + +/* patch_pix8: patch rows x [R, w C p p] (R a frame's patch rows times its frames) to RGB bytes + * y [R p, w p C], each byte round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)) with rd + * x's dtype, to_rgba8's rule. */ +int ref_patch_pix8(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0); + const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0; + if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || Y->dtype != RAD_U8 || + X->shape[1] % (C * p * p)) + return RAD_E_SHAPE; + const int64_t R = X->shape[0], w = X->shape[1] / (C * p * p); + if (R <= 0 || w <= 0 || Y->shape[0] != R * p || Y->shape[1] != w * p * C) return RAD_E_SHAPE; + const int64_t xr = X->stride[0], yr = Y->stride[0]; + const uint32_t dt = X->dtype; + uint8_t* yb = (uint8_t*)Y->data; + REF_PAR_FOR(R * p * w * p * C) + for (int64_t y = 0; y < R * p; ++y) + for (int64_t x = 0; x < w * p; ++x) + for (int64_t c = 0; c < C; ++c) { + const float v = ldt(X, (y / p) * xr + (x / p) * C * p * p + + patch_col(c, y % p, x % p, p, wh)); + const float cl = std::min(std::max(v, -1.0f), 1.0f); + float u = round_dt(dt, round_dt(dt, cl / 2.0f) + 0.5f); + u = std::min(std::max(u, 0.0f), 1.0f); + yb[y * yr + x * C + c] = (uint8_t)std::nearbyint(u * 255.0f); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ vol_index */ +/* A volume's voxel coordinates, the rotary positions of attention over it: geom = (T, H, W), i32 + * on the device; y i32 [3, n] component-major (at its own row pitch), voxel m = (t H + i) W + j's + * (t, i, j) at column m, for m < min(n, T H W). */ +int ref_vol_index(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *G = &a->t[0], *Y = &a->t[1]; + if (numel(G) < 3 || Y->rank != 2 || Y->shape[0] != 3) return RAD_E_SHAPE; + const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), n = Y->shape[1]; + if (T <= 0 || H <= 0 || W <= 0 || n <= 0) return RAD_E_SHAPE; + const int64_t m1 = std::min(n, T * H * W); + for (int64_t m = 0; m < m1; ++m) { + const int64_t v[3] = { m / (H * W), (m / W) % H, m % W }; + for (int64_t c = 0; c < 3; ++c) + st_int(Y->dtype, Y->data, c * Y->stride[0] + m * Y->stride[1], v[c]); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ tile_grid / tile_crop / tile_stitch */ +/* A decoder run in tiles, as diffusers cuts and blends them: LTX-2's VAE (`tiled_decode`, rule + * `stride`) and LTX-2.5's diffusion decoder (`_tile_intervals`, rule `intervals`). Along an axis + * of L cells a tile starts at every multiple of `stride` below L; under `intervals` one tile covers + * an axis of `tile` or fewer cells, and while more than one start is left and the last leaves fewer + * than `min` cells, that start is dropped. A tile but the last is min(tile, L - start) long; the + * last runs to L. Tiles are raster-ordered over (time band, row band, column band); without + * `tile_t` there is one time band of every frame. + * + * tile_grid: the boxes of the grid geom = (T, H, W), i32 on the device, into y i32 [M, 8], row k + * (t, h, w, t0, y0, x0, k, count); the last time band is `tail` cells longer than its cut (frames + * past T a decoder carries, which its crop takes and its output drops). Rows past the count are + * zero, tiles past M not written. A row's (t, h, w) is a decoder's volume operand and its first six + * entries tile_crop's box. */ +struct TileCut { + int64_t tile = 1, stride = 1, min = 1; + bool intervals = false; + int64_t count(int64_t L) const { + if (intervals && L <= tile) return 1; + int64_t n = (L + stride - 1) / stride; + while (intervals && n > 1 && L - (n - 1) * stride < min) --n; + return n; + } + int64_t len(int64_t L, int64_t k) const { + return k == count(L) - 1 ? L - k * stride : std::min(tile, L - k * stride); + } +}; + +static bool tile_cuts(const RadArgs* a, TileCut* s, TileCut* t) { + static const char* const kRules[] = { "stride", "intervals" }; + const int rule = p_enum(a, "rule", kRules, 2, 0); + s->tile = p_int(a, "tile", 0); + s->stride = p_int(a, "stride", 0); + s->min = p_int(a, "min", 1); + s->intervals = rule == 1; + t->tile = p_int(a, "tile_t", 1 << 30); + t->stride = p_int(a, "stride_t", 1 << 30); + t->min = p_int(a, "min_t", 1); + t->intervals = rule == 1; + return rule >= 0 && s->tile > 0 && s->stride > 0 && s->stride <= s->tile && s->min > 0 && + t->tile > 0 && t->stride > 0 && t->stride <= t->tile && t->min > 0; +} + +int ref_tile_grid(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *G = &a->t[0], *Y = &a->t[1]; + TileCut cs, ct; + const int64_t n = numel(Y) / 8, tail = p_int(a, "tail", 0); + if (!tile_cuts(a, &cs, &ct) || tail < 0 || n <= 0 || numel(G) < 3) return RAD_E_SHAPE; + const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2); + if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; + const int64_t nt = ct.count(T), ni = cs.count(H), nj = cs.count(W), count = nt * ni * nj; + for (int64_t k = 0; k < n; ++k) { + int64_t row[8] = {}; + if (k < count) { + const int64_t kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj; + const int64_t v[8] = { ct.len(T, kt) + (kt == nt - 1 ? tail : 0), cs.len(H, i), + cs.len(W, j), kt * ct.stride, i * cs.stride, j * cs.stride, k, + count }; + std::memcpy(row, v, sizeof row); + } + for (int64_t e = 0; e < 8; ++e) st_int(Y->dtype, Y->data, offlin(Y, k * 8 + e), row[e]); + } + return RAD_OK; +} + +/* tile_crop: one tile's voxels out of a volume. x [>= T H W, C] is the volume (row (t, yy, xx) + * row-major), geom its (T, H, W); box = (t, h, w, t0, y0, x0), i32 on the device (a tile_grid + * row); y [t h w, C], y[(a, i, j)] = x[(t0 + a, y0 + i, x0 + j)]. A copy. */ +int ref_tile_crop(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *B = &a->t[2], *Y = &a->t[3]; + const int64_t C = p_int(a, "C", 0); + if (C <= 0 || numel(G) < 3 || numel(B) < 6) return RAD_E_SHAPE; + const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2); + const int64_t t = ldi(B, 0), h = ldi(B, 1), w = ldi(B, 2); + const int64_t t0 = ldi(B, 3), y0 = ldi(B, 4), x0 = ldi(B, 5); + if (t <= 0 || h <= 0 || w <= 0 || t0 < 0 || y0 < 0 || x0 < 0 || t0 + t > T || y0 + h > H || + x0 + w > W || rows_of(X, C) < T * H * W || rows_of(Y, C) < t * h * w) + return RAD_E_SHAPE; + const int64_t xs = laststride(X), ys = laststride(Y); + REF_PAR_FOR(t * h * w * C) + for (int64_t r = 0; r < t * h * w; ++r) { + const int64_t f = r / (h * w), i = (r / w) % h, j = r % w; + const int64_t xb = rowoff(X, ((t0 + f) * H + y0 + i) * W + x0 + j, C), yb = rowoff(Y, r, C); + for (int64_t c = 0; c < C; ++c) stt(Y, yb + c * ys, ldt(X, xb + c * xs)); + } + return RAD_OK; +} + +/* tile_stitch: decoded tiles to RGB bytes. geom = (T, H, W) is the grid the tiles cut (tail cells + * excluded); a cell is `scale` patches of p x p pixels a side and `scale_t` frames, the first cell + * of the video one frame (the causal mapping: T cells are scale_t T - scale_t + 1 frames). x is + * every tile's decoder output in tile order, back to back: tile (kt, i, j) with cells [t0, t1) in + * time is F = scale_t (t1 - t0), less scale_t - 1 when t0 is 0, frames of (h scale) x (w scale) + * rows of patches (pix_patch's columns, C p p a row). `first` is the first frame y holds, i32 [1]. + * + * A pixel (Y, X) of frame n is time band kt's whose kept frames hold n (a band but the last keeps + * stride_t scale_t frames, the first scale_t - 1 fewer), then tile (i, j) = (Y / s, X / s) of that + * band, s = stride scale p, the last band of an axis keeping the rest. With R a tile's decoded + * value, every product and sum rounded to x's dtype (rd) and mix(a, b, k, e) = + * rd(rd(a f32(1 - k / e)) + rd(b f32(k / e))) (the quotients in f64), a band's picture S is + * diffusers' in-place blend_v then blend_h of its tiles: + * + * ev = min(rows of tile (i-1, j), rows of tile (i, j), (tile - stride) scale p), eh likewise + * up(c) = R(i-1, c)[rows(i-1) - ev + ly, .] the tile above's bottom margin + * A = mix(up(j-1)[., cols(j-1) - eh + lx], up(j)[., lx], lx, eh) when j > 0, lx < eh, + * else up(j)[., lx] (it was blended with its own left) + * V = mix(A, R(i, j)[ly, lx], ly, ev) when i > 0 and ly < ev, else R(i, j)[ly, lx] + * L = mix(up(j-1)[., cols(j-1) - eh + lx], R(i, j-1)[ly, cols(j-1) - eh + lx], ly, ev) + * when i > 0 and ly < ev, else R(i, j-1)[ly, cols(j-1) - eh + lx] + * S = mix(L, V, lx, eh) when j > 0 and lx < eh, else V + * + * and across time blend_t: frame f of band kt, f < et = min(F of band kt-1, F of band kt, + * (tile_t - stride_t) scale_t), is mix(S_{kt-1}[F_{kt-1} - et + f], S_kt[f], f, et). The byte is + * patch_pix8's, round(255 clamp(rd(rd(clamp(v, -1, 1) / 2) + 0.5), 0, 1)). y is u8 + * [n (H scale p), (W scale p) C], frames first .. first + n - 1. A tile above, to the left or + * before is never short enough for its own blends to reach the margin read here (a tile not last + * on its axis spans more than `stride`), so these are the reference's values exactly. */ +struct TileStore { + TileCut cs, ct; + int64_t T, H, W, sc, st, nt, ni, nj, hsum, wsum; + TileStore(const TileCut& s, const TileCut& t, int64_t T_, int64_t H_, int64_t W_, int64_t sc_, + int64_t st_) + : cs(s), ct(t), T(T_), H(H_), W(W_), sc(sc_), st(st_), nt(t.count(T_)), ni(s.count(H_)), + nj(s.count(W_)), hsum(0), wsum(0) { + for (int64_t i = 0; i < ni; ++i) hsum += cs.len(H, i); + for (int64_t j = 0; j < nj; ++j) wsum += cs.len(W, j); + } + int64_t frames(int64_t kt) const { + return st * ct.len(T, kt) - (kt == 0 ? st - 1 : 0); + } + /* Tile (kt, i, j)'s first patch row. */ + int64_t offset(int64_t kt, int64_t i, int64_t j) const { + int64_t before = 0; + for (int64_t q = 0; q < kt; ++q) before += frames(q); + int64_t left = 0, above = 0; + for (int64_t q = 0; q < j; ++q) left += cs.len(W, q); + for (int64_t q = 0; q < i; ++q) above += cs.len(H, q); + return sc * sc * (before * hsum * wsum + frames(kt) * (above * wsum + cs.len(H, i) * left)); + } + int64_t rows() const { return offset(nt, 0, 0); } +}; + +int ref_tile_stitch(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *G = &a->t[1], *Fst = &a->t[2], *Y = &a->t[3]; + TileCut cs, ct; + const int64_t sc = p_int(a, "scale", 0), st = p_int(a, "scale_t", 1); + const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0); + const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0; + if (!tile_cuts(a, &cs, &ct) || sc <= 0 || st <= 0 || p <= 0 || C <= 0 || numel(G) < 3 || + numel(Fst) < 1 || Y->dtype != RAD_U8 || Y->rank != 2) + return RAD_E_SHAPE; + const int64_t T = ldi(G, 0), H = ldi(G, 1), W = ldi(G, 2), f0 = ldi(Fst, 0); + const int64_t Hpx = H * sc * p, Wpx = W * sc * p, P = C * p * p; + if (T <= 0 || H <= 0 || W <= 0 || Y->shape[1] != Wpx * C || Y->shape[0] % Hpx) return RAD_E_SHAPE; + const int64_t nf = Y->shape[0] / Hpx; + const TileStore ts(cs, ct, T, H, W, sc, st); + if (nf <= 0 || f0 < 0 || f0 + nf > st * T - (st - 1) || rows_of(X, P) < ts.rows()) + return RAD_E_SHAPE; + const int64_t s = cs.stride * sc * p, E = (cs.tile - cs.stride) * sc * p; + const int64_t Et = (ct.tile - ct.stride) * st, xs = laststride(X); + const uint32_t dt = X->dtype; + auto R = [&](int64_t kt, int64_t i, int64_t j, int64_t f, int64_t yy, int64_t xx, int64_t c) { + const int64_t wp = cs.len(W, j) * sc, hp = cs.len(H, i) * sc; + const int64_t row = ts.offset(kt, i, j) + (f * hp + yy / p) * wp + xx / p; + return ldt(X, rowoff(X, row, P) + patch_col(c, yy % p, xx % p, p, wh) * xs); + }; + auto mix = [&](float va, float vb, int64_t k, int64_t e) { + const float wa = (float)(1.0 - (double)k / (double)e), wb = (float)((double)k / (double)e); + return round_dt(dt, round_dt(dt, va * wa) + round_dt(dt, vb * wb)); + }; + /* Band kt's spatially stitched value at its frame f. */ + auto S = [&](int64_t kt, int64_t f, int64_t Yp, int64_t Xp, int64_t c) { + const int64_t i = std::min(Yp / s, ts.ni - 1), ly = Yp - i * s; + const int64_t j = std::min(Xp / s, ts.nj - 1), lx = Xp - j * s; + const int64_t ha = i > 0 ? cs.len(H, i - 1) * sc * p : 0; + const int64_t ev = i > 0 ? std::min(std::min(ha, cs.len(H, i) * sc * p), E) : 0; + const int64_t wl = j > 0 ? cs.len(W, j - 1) * sc * p : 0; + const int64_t eh = j > 0 ? std::min(std::min(wl, cs.len(W, j) * sc * p), E) : 0; + const bool vb = i > 0 && ly < ev, hb = j > 0 && lx < eh; + float V = R(kt, i, j, f, ly, lx, c); + if (vb) { + const int64_t ya = ha - ev + ly; + float A = R(kt, i - 1, j, f, ya, lx, c); + if (hb) A = mix(R(kt, i - 1, j - 1, f, ya, wl - eh + lx, c), A, lx, eh); + V = mix(A, V, ly, ev); + } + if (hb) { + float L = R(kt, i, j - 1, f, ly, wl - eh + lx, c); + if (vb) L = mix(R(kt, i - 1, j - 1, f, ha - ev + ly, wl - eh + lx, c), L, ly, ev); + V = mix(L, V, lx, eh); + } + return V; + }; + uint8_t* yb = (uint8_t*)Y->data; + const int64_t yr = Y->stride[0], band = ct.stride * st; + REF_PAR_FOR(nf * Hpx * Wpx * C) + for (int64_t r = 0; r < nf * Hpx; ++r) { + const int64_t n = f0 + r / Hpx, Yp = r % Hpx; + const int64_t kt = std::min((n + st - 1) / band, ts.nt - 1); + const int64_t f = n - (kt == 0 ? 0 : kt * band - (st - 1)); + const int64_t et = kt > 0 ? std::min(std::min(ts.frames(kt - 1), ts.frames(kt)), Et) : 0; + for (int64_t Xp = 0; Xp < Wpx; ++Xp) + for (int64_t c = 0; c < C; ++c) { + float v = S(kt, f, Yp, Xp, c); + if (kt > 0 && f < et) v = mix(S(kt - 1, ts.frames(kt - 1) - et + f, Yp, Xp, c), v, f, et); + const float cl = std::min(std::max(v, -1.0f), 1.0f); + float u = round_dt(dt, round_dt(dt, cl / 2.0f) + 0.5f); + u = std::min(std::max(u, 0.0f), 1.0f); + yb[r * yr + Xp * C + c] = (uint8_t)std::nearbyint(u * 255.0f); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ stft_logmel */ +/* LTX-2's bandwidth extender's input: each channel's causal log-mel spectrogram, as its MelSTFT + * computes it in the vocoder's dtype. x [S, ch] (time rows, a channel a column), `basis` + * [2F, 1, nfft] (the windowed DFT, real rows then imaginary), `mel` [n_mel, F]; frame t of channel + * h reads samples t hop + j - (nfft - hop), zero before the start: + * + * s_k = rd(sum_j basis[k, j] x[.]) mag_k = rd(sqrt(rd(rd(re_k^2) + rd(im_k^2)))) + * y[t, h n_mel + m] = rd(log(max(rd(sum_k mel[m, k] mag_k), rd(1e-5)))) + * + * sums f32 in ascending order, rd y's dtype. y is [S / hop, ch n_mel]. */ +int ref_stft_logmel(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *B = &a->t[1], *Mb = &a->t[2], *Y = &a->t[3]; + const int64_t hop = p_int(a, "hop", 0), nfft = p_int(a, "nfft", 0), nm = p_int(a, "n_mel", 0); + const int64_t ch = p_int(a, "ch", 0); + if (hop <= 0 || nfft < hop || nm <= 0 || ch <= 0) return RAD_E_SHAPE; + const int64_t F = nfft / 2 + 1, S = rows_of(X, ch), frames = rows_of(Y, ch * nm); + if (S <= 0 || frames <= 0 || frames * hop > S || numel(B) < 2 * F * nfft || numel(Mb) < nm * F) + return RAD_E_SHAPE; + const uint32_t dt = Y->dtype; + const int64_t pad = nfft - hop, xs = laststride(X), ys = laststride(Y); + const float floor_v = round_dt(dt, 1e-5f); + REF_PAR_FOR(frames * ch * 2 * F * nfft) + for (int64_t t = 0; t < frames; ++t) + for (int64_t h = 0; h < ch; ++h) { + std::vector mag((size_t)F); + for (int64_t k = 0; k < F; ++k) { + float re = 0.0f, im = 0.0f; + for (int64_t j = 0; j < nfft; ++j) { + const int64_t s = t * hop + j - pad; + if (s < 0) continue; + const float v = ldt(X, rowoff(X, s, ch) + h * xs); + re += ldt(B, k * nfft + j) * v; + im += ldt(B, (F + k) * nfft + j) * v; + } + re = round_dt(dt, re); + im = round_dt(dt, im); + mag[(size_t)k] = round_dt(dt, std::sqrt(round_dt(dt, round_dt(dt, re * re) + + round_dt(dt, im * im)))); + } + const int64_t yb = rowoff(Y, t, ch * nm); + for (int64_t m = 0; m < nm; ++m) { + float s = 0.0f; + for (int64_t k = 0; k < F; ++k) s += ldt(Mb, m * F + k) * mag[(size_t)k]; + const float mel = std::max(round_dt(dt, s), floor_v); + stt(Y, yb + (h * nm + m) * ys, std::log(mel)); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ bwe_up */ +/* LTX-2's bandwidth extender's output: the low-rate waveform x [S, ch] raised `ratio` times by its + * Hann-windowed sinc resampler (UpSample1d, width ceil(6 / 0.99), its taps in x's dtype), added to + * the extender's residual `res` [S ratio, ch], clamped to [-1, 1]: + * + * f[n] = rd(sinc(u) cos^2(clamp(u, -6, 6) pi / 12) 0.99 / ratio), u = f32(n / ratio - w) 0.99 + * up[o] = rd(ratio rd(sum f[k] x[clamp(i - w, 0, S - 1)])), i ratio + k = o + 2 w ratio + * y[o] = clamp(rd(res[o] + up[o]), -1, 1) + * + * the filter's arithmetic f32 as torch builds it, rd x's dtype; y is f32 or x's dtype. */ +int ref_bwe_up(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Rz = &a->t[1], *Y = &a->t[2]; + const int64_t r = p_int(a, "ratio", 0), ch = p_int(a, "ch", 0); + if (r <= 0 || ch <= 0) return RAD_E_SHAPE; + const int64_t S = rows_of(X, ch), O = rows_of(Y, ch); + if (S <= 0 || O <= 0 || O > S * r || rows_of(Rz, ch) < O) return RAD_E_SHAPE; + const uint32_t dt = X->dtype; + const int64_t w = (int64_t)std::ceil(6.0 / 0.99), K = 2 * w * r + 1, off = 2 * w * r; + std::vector f((size_t)K); + for (int64_t n = 0; n < K; ++n) { + const float u = ((float)n / (float)r - (float)w) * 0.99f; + const float uc = std::min(std::max(u, -6.0f), 6.0f); + const float cw = std::cos(uc * (float)M_PI / 6.0f / 2.0f); + const float pu = (float)M_PI * u; + const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu; + f[(size_t)n] = round_dt(dt, sinc * (cw * cw) * 0.99f / (float)r); + } + const int64_t xs = laststride(X), rs = laststride(Rz), ys = laststride(Y); + REF_PAR_FOR(O * ch * K) + for (int64_t o = 0; o < O; ++o) + for (int64_t h = 0; h < ch; ++h) { + const int64_t u = o + off; + float acc = 0.0f; + for (int64_t k = u % r; k < K; k += r) { + const int64_t i = (u - k) / r; /* the padded input's index */ + const int64_t s = std::min(std::max(i - w, 0), S - 1); + acc += f[(size_t)k] * ldt(X, rowoff(X, s, ch) + h * xs); + } + const float up = round_dt(dt, (float)r * round_dt(dt, acc)); + const float v = round_dt(dt, ldt(Rz, rowoff(Rz, o, ch) + h * rs) + up); + stt(Y, rowoff(Y, o, ch) + h * ys, std::min(std::max(v, -1.0f), 1.0f)); + } + return RAD_OK; +} diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 16c6e76c..3c72d4cc 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -144,6 +144,10 @@ int ref_logits_gemm (const RadArgs*, RadStream); /* ---- attention */ int ref_attn_paged (const RadArgs*, RadStream); int ref_attn_dense (const RadArgs*, RadStream); +int ref_attn_cross (const RadArgs*, RadStream); +int ref_table_add (const RadArgs*, RadStream); +int ref_mix_rows (const RadArgs*, RadStream); +int ref_chan_stats (const RadArgs*, RadStream); int ref_kv_store (const RadArgs*, RadStream); int ref_rope (const RadArgs*, RadStream); int ref_rope_table (const RadArgs*, RadStream); @@ -172,6 +176,24 @@ int ref_group_norm(const RadArgs*, RadStream); int ref_tconv_dw(const RadArgs*, RadStream); int ref_resize_bilinear(const RadArgs*, RadStream); int ref_flow_renoise(const RadArgs*, RadStream); +/* ref_ltx.cpp */ +int ref_rope_split(const RadArgs*, RadStream); +int ref_head_gate(const RadArgs*, RadStream); +int ref_ltx_guide(const RadArgs*, RadStream); +int ref_pixel_norm(const RadArgs*, RadStream); +int ref_d2s3d(const RadArgs*, RadStream); +int ref_s2d3d(const RadArgs*, RadStream); +int ref_pix_patch(const RadArgs*, RadStream); +int ref_patch_pix8(const RadArgs*, RadStream); +int ref_vol_index(const RadArgs*, RadStream); +int ref_attn_na3d(const RadArgs*, RadStream); +int ref_tile_grid(const RadArgs*, RadStream); +int ref_tile_crop(const RadArgs*, RadStream); +int ref_tile_stitch(const RadArgs*, RadStream); +int ref_stft_logmel(const RadArgs*, RadStream); +int ref_bwe_up(const RadArgs*, RadStream); +/* ltx_guide's scratch, in f32 values: the deviations' partial sums of a device implementation. */ +enum { kLtxGuideStats = 8200 }; /* ref_vsa.cpp */ int ref_vsa_select(const RadArgs*, RadStream); int ref_attn_vsa(const RadArgs*, RadStream); @@ -194,6 +216,7 @@ int ref_chan_split(const RadArgs*, RadStream); int ref_interleave2(const RadArgs*, RadStream); int ref_iota(const RadArgs*, RadStream); int ref_cu_repeat(const RadArgs*, RadStream); +int ref_int_affine(const RadArgs*, RadStream); int ref_chan_affine(const RadArgs*, RadStream); int ref_conv2d_nhwc(const RadArgs*, RadStream); int ref_l2norm_chan(const RadArgs*, RadStream); @@ -362,6 +385,10 @@ REF_SHAPE_FN(ref_logits_gemm); REF_SHAPE_FN(ref_attn_paged); REF_SHAPE_FN(ref_attn_dense); +REF_SHAPE_FN(ref_attn_cross); +REF_SHAPE_FN(ref_table_add); +REF_SHAPE_FN(ref_mix_rows); +REF_SHAPE_FN(ref_chan_stats); REF_SHAPE_FN(ref_kv_store); REF_SHAPE_FN(ref_rope); REF_SHAPE_FN(ref_rope_table); @@ -388,6 +415,21 @@ REF_SHAPE_FN(ref_group_norm); REF_SHAPE_FN(ref_tconv_dw); REF_SHAPE_FN(ref_resize_bilinear); REF_SHAPE_FN(ref_flow_renoise); +REF_SHAPE_FN(ref_rope_split); +REF_SHAPE_FN(ref_head_gate); +REF_SHAPE_FN(ref_ltx_guide); +REF_SHAPE_FN(ref_pixel_norm); +REF_SHAPE_FN(ref_d2s3d); +REF_SHAPE_FN(ref_s2d3d); +REF_SHAPE_FN(ref_pix_patch); +REF_SHAPE_FN(ref_patch_pix8); +REF_SHAPE_FN(ref_vol_index); +REF_SHAPE_FN(ref_attn_na3d); +REF_SHAPE_FN(ref_tile_grid); +REF_SHAPE_FN(ref_tile_crop); +REF_SHAPE_FN(ref_tile_stitch); +REF_SHAPE_FN(ref_stft_logmel); +REF_SHAPE_FN(ref_bwe_up); REF_SHAPE_FN(ref_vsa_select); REF_SHAPE_FN(ref_attn_vsa); REF_SHAPE_FN(ref_conv1d); @@ -408,6 +450,7 @@ REF_SHAPE_FN(ref_chan_split); REF_SHAPE_FN(ref_interleave2); REF_SHAPE_FN(ref_iota); REF_SHAPE_FN(ref_cu_repeat); +REF_SHAPE_FN(ref_int_affine); REF_SHAPE_FN(ref_chan_affine); REF_SHAPE_FN(ref_conv2d_nhwc); REF_SHAPE_FN(ref_l2norm_chan); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index abcf91fa..fbf5cbe3 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -367,6 +367,13 @@ static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT( P_INTO("window_right") }; static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), OUT("out") }; +static const RadParamSpec pAttnCross[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"), + P_INT("causal"), P_STR("dtype"), P_F64O("scale") }; +static const RadOperandSpec oAttnCross[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), + OPD("cu_k"), OUT("out") }; +static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("kt"), P_INT("kh"), + P_INT("kw"), P_STR("dtype"), P_F64O("scale") }; +static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") }; /* `k_scale` and `v_scale` are the descales an fp8 cache is read back with, so a store divides by * them; optional because a bf16 cache has none. */ @@ -693,6 +700,13 @@ static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"), static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") }; /* `act` is the gate's activation, "tanh" (the default) or "none". */ +static const RadParamSpec pTableAdd[] = { P_INT("M"), P_INT("n"), P_INT("L"), P_STR("dtype") }; +static const RadOperandSpec oTableAdd[] = { OPD("x"), WGT("t"), OUT("y") }; +static const RadParamSpec pMixRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") }; +static const RadParamSpec pChanStats[] = { P_INT("M"), P_INT("n"), P_STR("mode"), P_INTO("var"), + P_F64O("eps"), P_STR("dtype") }; +static const RadOperandSpec oChanStats[] = { OPD("x"), WGT("mean"), WGT("s"), OUT("y") }; +static const RadOperandSpec oMixRows[] = { OPD("x"), WGT("w"), OUT("y") }; static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") }; static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") }; static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), @@ -701,12 +715,14 @@ static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD( INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; /* `s` is [n_seq, >= 2n], [shift | scale] in each row. */ static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"), - P_STR("dtype") }; -static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"), + P_STR("dtype"), P_F64O("wadd"), + P_INTO("norm_once"), P_STRO("norm") }; +static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"), OPD("cu_seqlens"), INOUT("x"), OUT("z") }; static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), - P_INT("gated"), P_STR("dtype") }; -static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"), + P_INT("gated"), P_STR("dtype"), P_F64O("wadd"), + P_INTO("norm_once"), P_STRO("norm") }; +static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"), OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") }; /* `t`, `sigma` and `sigma_next` are one f32 value each. */ @@ -789,7 +805,8 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se * (T, H, W) for conv3d_ndhwc and tconv_dw, (T, h, w, H, W) for resize_bilinear and (F, Hp, Wp) * for patch_fold, which shares patch_unfold's parameters and operands. */ static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), - P_INT("kt"), P_STR("dtype") }; + P_INT("kt"), P_STR("dtype"), P_STRO("tpad"), + P_INTO("tpre") }; static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"), OPD_O("res"), OUT("y") }; /* `mod` is one row [scale | shift]; `stats` the per-group mean and rstd, then scratch. */ @@ -805,6 +822,52 @@ static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stre P_STR("dtype") }; static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") }; +/* ---- LTX-2 (ref_ltx.cpp) */ +static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"), + P_INT("dim"), P_INT("n_dims"), P_F64("theta"), + P_STR("max"), P_INTO("head0"), P_STR("dtype") }; +static const RadOperandSpec oRopeSplit[] = { INOUT("x"), OPD("positions") }; +static const RadParamSpec pHeadGate[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"), + P_STR("dtype") }; +static const RadOperandSpec oHeadGate[] = { OPD("g"), INOUT("x") }; +static const RadParamSpec pLtxGuide[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oLtxGuide[] = { OPD("vc"), OPD_O("vu"), OPD_O("vs"), OPD_O("vm"), + OPD("scales"), OPD("sched"), INOUT("stats"), + INOUT("x") }; +static const RadParamSpec pPixelNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("form"), + P_STRO("act"), P_INTO("ileave"), P_STR("dtype"), + P_F64O("mult") }; +static const RadOperandSpec oPixelNorm[] = { OPD("x"), OUT("y") }; +static const RadParamSpec pD2s3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"), + P_INTO("drop"), P_STR("dtype") }; +static const RadOperandSpec oD2s3d[] = { OPD("x"), OPD("geom"), OUT("y") }; +static const RadParamSpec pS2d3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"), + P_INTO("tpre"), P_INTO("group"), P_STR("mode"), + P_INTO("add"), P_STR("dtype") }; +static const RadOperandSpec oS2d3d[] = { OPD("x"), OPD("geom"), INOUT("y") }; +static const RadParamSpec pPixPatch[] = { P_INT("M"), P_INT("p"), P_INT("C"), P_STRO("order"), + P_STR("dtype") }; +static const RadOperandSpec oPixPatch[] = { OPD("x"), OUT("y") }; +static const RadParamSpec pVolIndex[] = { P_INT("M") }; +static const RadOperandSpec oVolIndex[] = { OPD("geom"), OUT("y") }; +static const RadParamSpec pTileGrid[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), P_STRO("rule"), + P_INTO("min"), P_INTO("tile_t"), P_INTO("stride_t"), + P_INTO("min_t"), P_INTO("tail") }; +static const RadOperandSpec oTileGrid[] = { OPD("geom"), OUT("y") }; +static const RadParamSpec pTileCrop[] = { P_INT("M"), P_INT("C"), P_STR("dtype") }; +static const RadOperandSpec oTileCrop[] = { OPD("x"), OPD("geom"), OPD("box"), OUT("y") }; +static const RadParamSpec pTileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), + P_STRO("rule"), P_INTO("min"), P_INTO("tile_t"), + P_INTO("stride_t"), P_INTO("min_t"), P_INT("scale"), + P_INTO("scale_t"), P_INT("p"), P_INT("C"), + P_STRO("order"), P_STR("dtype") }; +static const RadOperandSpec oTileStitch[] = { OPD("x"), OPD("geom"), OPD("first"), OUT("y") }; +static const RadParamSpec pStftMel[] = { P_INT("M"), P_INT("hop"), P_INT("nfft"), P_INT("n_mel"), + P_INT("ch"), P_STR("dtype") }; +static const RadOperandSpec oStftMel[] = { OPD("x"), WGT("basis"), WGT("mel"), OUT("y") }; +static const RadParamSpec pBweUp[] = { P_INT("M"), P_INT("ratio"), P_INT("ch"), P_STR("dtype") }; +static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") }; + /* ---- audio generation (ref_audio.cpp) */ static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("dil"), P_STRO("act"), P_STR("dtype"), @@ -864,6 +927,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"), P_INTO("period") }; static const RadOperandSpec oIota[] = { OUT("y") }; static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") }; +static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") }; +static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") }; static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") }; /* ================================================================== the schema table */ @@ -948,6 +1013,16 @@ static const RadOpSchema kSchemas[] = { "rows; nothing else broadcasts. With `div`, y = rd(rd(a + b) / div), rd y's dtype: the last " "sum of a mean taken pairwise." }, { "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same one broadcast rule as `add`." }, +{ "table_add", ARR(pTableAdd), ARR(oTableAdd), + "y[r, l n + c] = x[r, c] + t[l, c]: a shared modulation row plus each of L learned rows, f32 sum " + "rounded once; `M` is y's rows." }, +{ "chan_stats", ARR(pChanStats), ARR(oChanStats), + "a latent through per-channel statistics held as weights: `denorm` y = rd(rd(x std) + mean), " + "`norm` y = rd(rd(x - mean) / std); std is `s`, or sqrt(s + eps) with `var` 1, each statistic " + "rounded to y's dtype." }, +{ "mix_rows", ARR(pMixRows), ARR(oMixRows), + "y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows, f32 sum in " + "ascending i rounded once; `M` is y's rows." }, { "mul_weight", ARR(pMulWeight), ARR(oMulWeight), "y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row " "(broadcast down the rows): a learned gain on an activation. f32 product, rounded once." }, @@ -1203,6 +1278,13 @@ static const RadOpSchema kSchemas[] = { "window, or i - j < window and j - i < window_right with `window_right`; 0 none. `block` cuts " "a segment into blocks of that many rows from its start, each attending within itself; 0 " "none." }, +{ "attn_cross", ARR(pAttnCross), ARR(oAttnCross), + "attn_dense with each entry's keys a run of their own: queries rows [cu[s], cu[s+1]), keys and " + "values rows [cu_k[s], cu_k[s+1]); with `causal` a query sees key j of its run when j <= its own " + "index, both counted from their run's start. A query that sees no key is zero." }, +{ "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d), + "3-D neighborhood attention (NATTEN's na3d) over the voxels of geom = (T, H, W): a query sees the " + "kt x kh x kw window centred on it, shifted inward at the border, each extent at most its axis." }, { "kv_store", ARR(pKvStore), ARR(oKvStore), "Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is " "INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." }, @@ -1572,6 +1654,53 @@ static const RadOpSchema kSchemas[] = { { "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise), "a clean latent re-noised to sigma s: x = f32(f32(f32(1 - s) x) + f32(s z)), z element " "k n + c of the normal stream (seed, `stream`) (abi/rad_philox.h)." }, +{ "rope_split", ARR(pRopeSplit), ARR(oRopeSplit), + "LTX-2's rotary over fractional coordinates: dim/2 pairs over all heads, the first `pad` " + "unrotated, then freq[k] = f32(theta^linspace(0,1,steps)[k] pi/2) with the n_dims coordinates " + "interleaved; angle f32(f32(2 f32(c / max)) - 1) freq; each head's halves rotated against each " + "other in f32, rounded to x's dtype. `head0` is the operand's first head." }, +{ "head_gate", ARR(pHeadGate), ARR(oHeadGate), + "x = rd(x rd(2 rd(sigmoid(g)))) per head: LTX-2's gated attention output." }, +{ "pixel_norm", ARR(pPixelNorm), ARR(oPixelNorm), + "an RMS norm over each row's n values as bf16 tensors compute it, every step rounded to y's " + "dtype: m = rd(sum rd(x^2) / n), then x rd(rsqrt(rd(m + eps))) (`form` rsqrt) or " + "x / rd(sqrt(rd(m + eps))) (div), optionally silu; `ileave` L writes x's row t L + l to " + "columns c L + l of y's row t." }, +{ "d2s3d", ARR(pD2s3d), ARR(oD2s3d), + "depth to space over voxel rows: packed channel ((c st + a) sh + b) sw + d of x's row (t, i, j) " + "to y's (t st + a - (st - 1), i sh + b, j sw + d), the first st - 1 frames dropped." }, +{ "s2d3d", ARR(pS2d3d), ARR(oS2d3d), + "space to depth over voxel rows, `tpre` leading frames prepended: each st x sh x sw box a packed " + "row (`mode` copy), or each run of `group` packed channels averaged (mean); `add` adds into y." }, +{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch), + "an image [H, W C] to patch rows [H/p, (W/p) C p p], channel c's (ph, pw) at c p p + pw p + ph " + "(order wh) or c p p + ph p + pw (hw)." }, +{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch), + "patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule, pix_patch's channel " + "order." }, +{ "vol_index", ARR(pVolIndex), ARR(oVolIndex), + "a volume's voxel coordinates (t, i, j), component-major: attention's rotary positions." }, +{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid), + "the tiles of a grid as diffusers cuts them (`rule` stride: tiled_decode's, a tile every " + "`stride` cells; intervals: _tile_intervals', a short last remnant merged), in space and " + "optionally time, one row (t, h, w, t0, y0, x0, k, count) a tile." }, +{ "tile_crop", ARR(pTileCrop), ARR(oTileCrop), + "one tile's voxels out of a volume: y[(a, i, j)] = x[(t0 + a, y0 + i, x0 + j)], box " + "(t, h, w, t0, y0, x0)." }, +{ "tile_stitch", ARR(pTileStitch), ARR(oTileStitch), + "decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h of each tile with the one " + "above and the one to its left, then blend_t of each time band with the one before, each kept to " + "its stride, then patch_pix8's bytes." }, +{ "stft_logmel", ARR(pStftMel), ARR(oStftMel), + "each channel's causal log-mel spectrogram from a windowed DFT basis and a mel filterbank, every " + "stored tensor rounded to y's dtype: frames S / hop, columns h n_mel + m." }, +{ "bwe_up", ARR(pBweUp), ARR(oBweUp), + "y = clamp(rd(res + up(x)), -1, 1): x raised `ratio` times by a Hann-windowed sinc resampler " + "(width ceil(6 / 0.99), taps in x's dtype, edges replicated)." }, +{ "ltx_guide", ARR(pLtxGuide), ARR(oLtxGuide), + "LTX-2's sampler step: each pass's clean estimate x - v sigma, the guidance deltas (CFG, STG, " + "modality) added in f32, an optional rescale by the deviations' ratio, the velocity back and " + "an Euler step of x, all f32. `scales` f32[4] (gs, stg, ms, rescale), `sched` f32[2]." }, { "conv1d", ARR(pConv1d), ARR(oConv1d), "a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost: x [rows, cin], " "y [rows, cout], PyTorch's [cout, cin, k] weight and an optional bias, dilation `dil` and padding " @@ -1636,6 +1765,9 @@ static const RadOpSchema kSchemas[] = { "y[i] = start + i * step over y's elements, or start + (i % period) * step with `period`." }, { "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "bounds of equal sequences, y[j] = j * len[0] * mult over y's elements." }, +{ "int_affine", ARR(pIntAffine), ARR(oIntAffine), + "y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists: shapes and " + "bounds derived from a pass's device geometry." }, }; /* ================================================================== the kernel table */ @@ -1819,6 +1951,12 @@ SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate SIMPLE("ref_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, ref_act_mul), SIMPLE("ref_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT, ref_mul_weight), +SIMPLE("ref_table_add", "table_add", "elem", "a row plus each of L table rows", DT_FLOAT, + ref_table_add), +SIMPLE("ref_mix_rows", "mix_rows", "elem", "a weighted sum of k consecutive rows", DT_FLOAT, + ref_mix_rows), +SIMPLE("ref_chan_stats", "chan_stats", "elem", "per-channel statistics held as weights", + DT_FLOAT, ref_chan_stats), SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT, ref_seg_mean), SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier", @@ -1942,6 +2080,11 @@ ROW("ref_attn_paged", "attn_paged", "attn", nullptr, nullptr, ref_attn_paged, nullptr), SIMPLE("ref_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT, ref_attn_dense), +SIMPLE("ref_attn_cross", "attn_cross", "attn", + "dense varlen attention, keys bounded apart from the queries (cu_k)", DT_FLOAT, + ref_attn_cross), +SIMPLE("ref_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT, + ref_attn_na3d), ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY, cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), nullptr, nullptr, ref_kv_store, nullptr), @@ -2117,6 +2260,27 @@ SIMPLE("ref_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch r ref_patch_fold), SIMPLE("ref_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma", DT_FLOAT, ref_flow_renoise), +SIMPLE("ref_rope_split", "rope_split", "elem", "LTX-2's split rotary over coordinates", DT_FLOAT, + ref_rope_split), +SIMPLE("ref_head_gate", "head_gate", "elem", "each head times 2 sigmoid of its logit", DT_FLOAT, + ref_head_gate), +SIMPLE("ref_ltx_guide", "ltx_guide", "elem", "LTX-2's guided sampler step", DT_FLOAT, + ref_ltx_guide), +SIMPLE("ref_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors compute it", DT_FLOAT, + ref_pixel_norm), +SIMPLE("ref_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, ref_d2s3d), +SIMPLE("ref_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, ref_s2d3d), +SIMPLE("ref_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, ref_pix_patch), +SIMPLE("ref_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, ref_patch_pix8), +SIMPLE("ref_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, ref_vol_index), +SIMPLE("ref_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, ref_tile_grid), +SIMPLE("ref_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, ref_tile_crop), +SIMPLE("ref_tile_stitch", "tile_stitch", "elem", "decoded tiles blended to RGB bytes", DT_FLOAT, + ref_tile_stitch), +SIMPLE("ref_stft_logmel", "stft_logmel", "elem", "a causal log-mel spectrogram", DT_FLOAT, + ref_stft_logmel), +SIMPLE("ref_bwe_up", "bwe_up", "elem", "a sinc-resampled waveform plus a residual, clamped", + DT_FLOAT, ref_bwe_up), SIMPLE("ref_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, channels innermost", DT_FLOAT, ref_conv1d), SIMPLE("ref_conv_t1d", "conv_t1d", "conv", "a transposed 1-D convolution growing each sequence", @@ -2150,6 +2314,8 @@ SIMPLE("ref_interleave2", "interleave2", "elem", "two streams interleaved", DT_A ref_interleave2), SIMPLE("ref_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, ref_iota), SIMPLE("ref_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, ref_cu_repeat), +SIMPLE("ref_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY, + ref_int_affine), }; /* ================================================================== plugin exports */ diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 30dbf06e..efa78320 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1328,6 +1328,60 @@ int ref_attn_dense_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("attn_dense", operand, out); } +int ref_attn_cross_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t gqa = gi(p, n_p, "gqa", 1); + if (M <= 0 || hd <= 0 || gqa <= 0) return RAD_E_UNSUPPORTED; + const int64_t nh = gqa, kvh = 1; + const uint32_t D = act_dt(p, n_p); + const int64_t S = n_seq_of(p, n_p); + + /* As many key rows as query rows, each side bounded by its own [0, ..., T]. */ + Opd o; + o.t(D, { M, nh, hd }); /* q */ + o.t(D, { M, kvh, hd }); /* k */ + o.t(D, { M, kvh, hd }); /* v */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_k */ + o.t(D, { M, nh, hd }); /* out */ + return o.finish("attn_cross", operand, out); +} + +int ref_table_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), L = gi(p, n_p, "L", 0); + if (M <= 0 || n <= 0 || L <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { L, n }); /* t */ + o.t(D, { M, L * n }); /* y */ + return o.finish("table_add", operand, out); +} + +int ref_mix_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0); + if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M * k, n }); /* x */ + o.t(D, { k }); /* w */ + o.t(D, { M, n }); /* y */ + return o.finish("mix_rows", operand, out); +} + +int ref_chan_stats_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { n }); /* mean */ + o.t_fill(D, { n }, (uint32_t)RAD_FILL_SIGMOID, 0); /* s -- a deviation or variance, > 0 */ + o.t(D, { M, n }); /* y */ + return o.finish("chan_stats", operand, out); +} + int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -2407,7 +2461,10 @@ int ref_rms_mod_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) o.skip(); } o.t(D, { 1, 2 * n }); /* s: [shift | scale] */ - o.t(D, { n }); /* w */ + /* A LayerNorm without a gain passes none, and no norm takes none. */ + const char* nk = gs(p, n_p, "norm"); + if (nk && (std::strcmp(nk, "layer") == 0 || std::strcmp(nk, "none") == 0)) o.skip(); /* w */ + else o.t(D, { n }); /* w */ o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ o.t(D, { M, n }); /* x, INOUT */ o.t(D, { M, n }); /* z */ @@ -2426,7 +2483,9 @@ int ref_rms_mod_quant_fp8_shape(const RadParam* p, int n_p, int operand, RadOpdD o.skip(); } o.t(D, { 1, 2 * n }); /* s */ - o.t(D, { n }); /* w */ + const char* nk = gs(p, n_p, "norm"); + if (nk && std::strcmp(nk, "layer") == 0) o.skip(); /* w: a LayerNorm without a gain */ + else o.t(D, { n }); /* w */ o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ o.t(D, { M, n }); /* x, INOUT */ o.t((uint32_t)RAD_F8E4M3, { M, n }); /* q */ @@ -3215,3 +3274,204 @@ int ref_cu_repeat_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out o.t_idx({ M }, 1, -1, 0); /* y */ return o.finish("cu_repeat", operand, out); } + +int ref_int_affine_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + if (M <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 16 }, 1000, -1, 0); /* x */ + o.t_idx({ M }, 1, -1, 0); /* y */ + return o.finish("int_affine", operand, out); +} + +/* ================================================================== LTX-2 (ref_ltx.cpp) */ +int ref_rope_split_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0), nd = gi(p, n_p, "n_dims", 0); + if (M <= 0 || nh <= 0 || hd <= 0 || nd <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(act_dt(p, n_p), { M, nh * hd }); /* x, INOUT */ + o.t((uint32_t)RAD_F32, { nd, M }); /* positions */ + return o.finish("rope_split", operand, out); +} + +int ref_head_gate_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + if (M <= 0 || nh <= 0 || hd <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, nh }); /* g */ + o.t(D, { M, nh * hd }); /* x, INOUT */ + return o.finish("head_gate", operand, out); +} + +/* The four guidance passes bound, scales and sigmas in (0, 1): every term taken. */ +int ref_ltx_guide_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p), F = (uint32_t)RAD_F32; + Opd o; + for (int i = 0; i < 4; ++i) o.t(D, { M, n }); /* vc, vu, vs, vm */ + o.t_fill(F, { 4 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* scales */ + o.t_fill(F, { 2 }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sched */ + o.t(F, { kLtxGuideStats }); /* stats, INOUT */ + o.t(F, { M, n }); /* x, INOUT */ + return o.finish("ltx_guide", operand, out); +} + +/* The rest of LTX-2's: its VAE's norm, resampling and patches, its vocoder's spectrogram and + * resampler. A volume op's `geom` is the cube of side cube_side(M), M its input's rows. */ +int ref_pixel_norm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), L = gi(p, n_p, "ileave", 1); + if (M <= 0 || n <= 0 || L <= 0 || M % L) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { M / L, n * L }); /* y */ + return o.finish("pixel_norm", operand, out); +} + +int ref_d2s3d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0), c = cube_side(M); + const int64_t st = gi(p, n_p, "st", 1), sh = gi(p, n_p, "sh", 1), sw = gi(p, n_p, "sw", 1); + if (c <= 0 || C <= 0 || st <= 0 || sh <= 0 || sw <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, C * st * sh * sw }); /* x */ + o.t_idx({ 3 }, 0, c, 0); /* geom */ + o.t(D, { (c * st - st + 1) * c * sh * c * sw, C }); /* y */ + return o.finish("d2s3d", operand, out); +} + +int ref_s2d3d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0), c = cube_side(M); + const int64_t st = gi(p, n_p, "st", 1), sh = gi(p, n_p, "sh", 1), sw = gi(p, n_p, "sw", 1); + const int64_t tpre = gi(p, n_p, "tpre", 0), g = gi(p, n_p, "group", 1); + const char* mode = gs(p, n_p, "mode"); + const bool mean = mode && !std::strcmp(mode, "mean"); + const int64_t P = C * st * sh * sw; + if (c <= 0 || C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || g <= 0 || + (c + tpre) % st || c % sh || c % sw || (mean && P % g)) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { c * c * c, C }); /* x */ + o.t_idx({ 3 }, 0, c, 0); /* geom */ + o.t(D, { ((c + tpre) / st) * (c / sh) * (c / sw), mean ? P / g : P }); /* y, INOUT */ + return o.finish("s2d3d", operand, out); +} + +int ref_pix_patch_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0); + const int64_t w = cols_for(M, 1), h = w ? M / w : 0; + if (!w || pp <= 0 || C <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { h * pp, w * pp * C }); /* x: the image */ + o.t(D, { h, w * C * pp * pp }); /* y: patch rows */ + return o.finish("pix_patch", operand, out); +} + +/* attn_na3d over a c x c x c volume, two heads. */ +int ref_attn_na3d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), hd = gi(p, n_p, "head_dim", 0), c = cube_side(M); + if (c <= 0 || hd <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const int64_t V = c * c * c; + Opd o; + o.t(D, { V, 2 * hd }); /* q */ + o.t(D, { V, 2 * hd }); /* k */ + o.t(D, { V, 2 * hd }); /* v */ + o.t_idx({ 3 }, 0, c, 0); /* geom */ + o.t(D, { V, 2 * hd }); /* out */ + return o.finish("attn_na3d", operand, out); +} + +int ref_vol_index_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), c = cube_side(M); + if (c <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 3 }, 0, c, 0); /* geom: c x c x c */ + o.t_idx({ 3, c * c * c }, 1, -1, 0); /* y */ + return o.finish("vol_index", operand, out); +} + +/* The tiled decode's ops: a c x c x c volume (every geom entry c), tiles and boxes inside it. */ +int ref_tile_grid_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), stride = gi(p, n_p, "stride", 0); + int64_t k = 0; + while ((k + 1) * (k + 1) <= M) ++k; + if (k <= 0 || stride <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ 3 }, 0, k * stride, 0); /* geom: k x k tiles */ + o.t_idx({ M, 8 }, 1, -1, 0); /* y */ + return o.finish("tile_grid", operand, out); +} + +int ref_tile_crop_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "C", 0); + int64_t k = 0; + while ((k + 1) * (k + 1) * (k + 1) <= M) ++k; + if (k <= 0 || C <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { 8 * k * k * k, C }); /* x: 2k x 2k x 2k */ + o.t_idx({ 3 }, 0, 2 * k, 0); /* geom */ + o.t_idx({ 6 }, 0, k, 0); /* box: k x k x k at (k, k, k) */ + o.t(D, { k * k * k, C }); /* y */ + return o.finish("tile_crop", operand, out); +} + +int ref_tile_stitch_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), tile = gi(p, n_p, "tile", 0); + const int64_t stride = gi(p, n_p, "stride", 0), sc = gi(p, n_p, "scale", 0); + const int64_t pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0); + if (tile <= 0 || stride <= 0 || stride > tile || sc <= 0 || pp <= 0 || C <= 0) + return RAD_E_UNSUPPORTED; + int64_t c = 0; + while ((c + 1) * (c + 1) * sc * pp <= M) ++c; + if (c <= 0) return RAD_E_UNSUPPORTED; + int64_t span = 0; /* the tiles' rows along an axis */ + for (int64_t s0 = 0; s0 < c; s0 += stride) span += std::min(tile, c - s0); + Opd o; + o.t(act_dt(p, n_p), { c * sc * sc * span * span, C * pp * pp }); /* x: c frames of tiles */ + o.t_idx({ 3 }, 0, c, 0); /* geom */ + o.t_idx({ 1 }, 0, 0, 0); /* first: frame 0 */ + o.t((uint32_t)RAD_U8, { c * c * sc * pp, c * sc * pp * C }); /* y: every frame */ + return o.finish("tile_stitch", operand, out); +} + +int ref_patch_pix8_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), pp = gi(p, n_p, "p", 0), C = gi(p, n_p, "C", 0); + const int64_t w = cols_for(M, 1), R = w ? M / w : 0; + if (!w || pp <= 0 || C <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(act_dt(p, n_p), { R, w * C * pp * pp }); /* x: patch rows */ + o.t((uint32_t)RAD_U8, { R * pp, w * pp * C }); /* y: bytes */ + return o.finish("patch_pix8", operand, out); +} + +int ref_stft_logmel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), hop = gi(p, n_p, "hop", 0), nfft = gi(p, n_p, "nfft", 0); + const int64_t nm = gi(p, n_p, "n_mel", 0), ch = gi(p, n_p, "ch", 0), F = nfft / 2 + 1; + if (M <= 0 || hop <= 0 || nfft < hop || nm <= 0 || ch <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M * hop, ch }); /* x: samples */ + o.t(D, { 2 * F, 1, nfft }); /* basis */ + o.t(D, { nm, F }); /* mel */ + o.t(D, { M, ch * nm }); /* y */ + return o.finish("stft_logmel", operand, out); +} + +int ref_bwe_up_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), r = gi(p, n_p, "ratio", 0), ch = gi(p, n_p, "ch", 0); + if (M <= 0 || r <= 0 || ch <= 0 || M % r) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M / r, ch }); /* x: the low-rate waveform */ + o.t(D, { M, ch }); /* res */ + o.t(D, { M, ch }); /* y */ + return o.finish("bwe_up", operand, out); +} diff --git a/libref/ref_video.cpp b/libref/ref_video.cpp index e6a2b35e..27dbeaf0 100644 --- a/libref/ref_video.cpp +++ b/libref/ref_video.cpp @@ -357,20 +357,30 @@ int ref_vtile_stitch(const RadArgs* a, RadStream) { * terms outside the volume zero. acc is f32, the taps in (dt, kh, kw) order and each tap's * channels ascending; rd is y's dtype. With `res` the convolution's output is rounded before the * residual is added, as a residual block's skip(x) + h adds two bf16 tensors. `res` may be y - * itself: each output element reads its own residual before its write, and no other. */ + * itself: each output element reads its own residual before its write, and no other. + * + * `tpad` sets the frames' padding (rows and columns stay zero-padded): `zero` (the default), + * `replicate` (the edge frame repeated, kt/2 a side: LTX-2's decoder) or `causal` (the first + * frame repeated kt - 1 times in front, nothing after: LTX-2's encoder). With `causal`, `tpre` + * more copies of the first frame stand in front of those, and y has T + tpre frames (LTX-2's + * temporal downsampler, which prepends its first frame before its convolution). */ int ref_conv3d_ndhwc(const RadArgs* a, RadStream) { if (a->n_t < 6 || !have(a, 4) || !t_in(a, 5)) return RAD_E_INVAL; const RadTensor *x = &a->t[0], *w = &a->t[1], *b = &a->t[2], *geom = &a->t[3]; const RadTensor *res = t_in(a, 4), *y = &a->t[5]; const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0); - const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0); - if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(geom) < 3) + const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0), tpre = p_int(a, "tpre", 0); + static const char* const kPads[] = { "zero", "replicate", "causal" }; + const int tpad = p_enum(a, "tpad", kPads, 3, 0); + if (tpad < 0 || (tpre && tpad != 2)) return RAD_E_INVAL; + if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || tpre < 0 || + numel(geom) < 3) return RAD_E_SHAPE; const int64_t T = ldi(geom, 0), H = ldi(geom, 1), W = ldi(geom, 2); if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE; - const int64_t rows = T * H * W, taps = kt * k * k; - if (rows_of(y, cout) < rows || rows_of(x, cin) < rows || (res && rows_of(res, cout) < rows) || - numel(w) < cout * cin * taps || numel(b) < cout) + const int64_t rows = (T + tpre) * H * W, taps = kt * k * k; + if (rows_of(y, cout) < rows || rows_of(x, cin) < T * H * W || + (res && rows_of(res, cout) < rows) || numel(w) < cout * cin * taps || numel(b) < cout) return RAD_E_SHAPE; const int64_t pz = kt / 2, ps = k / 2, xs = laststride(x), ys = laststride(y); const int64_t rs = res ? laststride(res) : 0; @@ -382,7 +392,11 @@ int ref_conv3d_ndhwc(const RadArgs* a, RadStream) { for (int64_t o = 0; o < cout; ++o) { float acc = 0.0f; for (int64_t dz = 0; dz < kt; ++dz) { - const int64_t tz = t + dz - pz; + /* The frame tap dz reads: zero pads, the edge frame repeated, or causal (the first + * frame repeated in front, `tpre` more copies of it before those). */ + int64_t tz = t + dz - pz; + if (tpad == 1) tz = std::min(std::max(tz, 0), T - 1); + else if (tpad == 2) tz = std::max(t + dz - (kt - 1) - tpre, 0); if (tz < 0 || tz >= T) continue; for (int64_t kh = 0; kh < k; ++kh) { const int64_t iy = i + kh - ps; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index bf2b8296..5482fc84 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -366,7 +366,7 @@ endif() # HIP names, each GPU thread is a fiber, and __syncthreads and cross-lane ops are barriers (one not # reached uniformly is reported as a deadlock). Checked against ports of libref's ref_attn_paged and # ref_qsa_select, the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, -# and for the LoRA pair libref itself when the test can load it. +# for the LoRA pair libref itself when the test can load it, and for KDA libref itself. # # Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang # C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so @@ -437,7 +437,7 @@ else() list(APPEND objs ${dir}/${stem}.o) endif() endforeach() - # test_lora opens libref with dlopen to hold the emulated kernels to it. + # test_lora and test_kda open libref with dlopen to hold the emulated kernels to it. set(dl "") foreach(l ${CMAKE_DL_LIBS}) list(APPEND dl -l${l}) @@ -470,8 +470,9 @@ if(R4D_EMU_BUILT) r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT}) # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can - # load one -- expand bit for bit, shrink to its bound. - set_tests_properties(r4d_emu_lora PROPERTIES + # load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within + # rounding, and that test needs it. + set_tests_properties(r4d_emu_lora r4d_emu_kda PROPERTIES ENVIRONMENT "RADIANCE_HOME=${CMAKE_BINARY_DIR}/radiance_home") # A seeded random sweep, mostly prefill shapes on the WMMA kernel, which the emulator runs at # about 2 s a case: `slow`. `r4d_emu_attn sweep 200` is a longer run by hand, a superset of it. diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 22691472..9d8dcd1f 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -349,6 +349,19 @@ ABI_FIELD(RadGenBatch, dec_lane) ABI_FIELD(RadGenBatch, dec_height) ABI_FIELD(RadGenBatch, dec_width) ABI_FIELD(RadGenBatch, dec_preview) +ABI_FIELD(RadGenBatch, branch) +ABI_FIELD(RadGenBatch, n_pad) +ABI_FIELD(RadGenBatch, valid_cu) +ABI_FIELD(RadGenBatch, n_img) +ABI_FIELD(RadGenBatch, img_cu) +ABI_FIELD(RadGenBatch, img_rows) +ABI_FIELD(RadGenBatch, mode_cu) +ABI_FIELD(RadGenBatch, rope_f) +ABI_FIELD(RadGenBatch, mode_rows) +ABI_FIELD(RadGenBatch, mode_src) +ABI_FIELD(RadGenBatch, mode_ccu) +ABI_FIELD(RadGenBatch, n_mode_h) +ABI_FIELD(RadGenBatch, mode_rope_f) ABI_STRUCT(RadGeneratorDecl) ABI_FIELD(RadGeneratorDecl, name) ABI_FIELD(RadGeneratorDecl, layout) @@ -382,6 +395,14 @@ ABI_FIELD(RadGeneratorDecl, shift_terminal) ABI_FIELD(RadGeneratorDecl, default_cfg) ABI_FIELD(RadGeneratorDecl, max_lanes) ABI_FIELD(RadGeneratorDecl, image_out) +ABI_FIELD(RadGeneratorDecl, cond_rows) +ABI_FIELD(RadGeneratorDecl, rope_hw_scale) +ABI_FIELD(RadGeneratorDecl, rope_text_l) +ABI_FIELD(RadGeneratorDecl, pad_multiple) +ABI_FIELD(RadGeneratorDecl, pad_token) +ABI_FIELD(RadGeneratorDecl, cfg_original) +ABI_FIELD(RadGeneratorDecl, default_negative) +ABI_FIELD(RadGeneratorDecl, ref_shrink_only) ABI_STRUCT(RadKVGroupBatch) ABI_FIELD(RadKVGroupBatch, group) ABI_FIELD(RadKVGroupBatch, slot_mapping) @@ -615,6 +636,12 @@ ABI_FIELD(RadVideoGenBatch, n_frames_out) ABI_FIELD(RadVideoGenBatch, n_samples) ABI_FIELD(RadVideoGenBatch, geom_from) ABI_FIELD(RadVideoGenBatch, upscale) +ABI_FIELD(RadVideoGenBatch, n_neg) +ABI_FIELD(RadVideoGenBatch, guidance_h) +ABI_FIELD(RadVideoGenBatch, image) +ABI_FIELD(RadVideoGenBatch, has_image) +ABI_FIELD(RadVideoGenBatch, guidance) +ABI_FIELD(RadVideoGenBatch, decoder) ABI_STRUCT(RadVideoGenDecl) ABI_FIELD(RadVideoGenDecl, name) ABI_FIELD(RadVideoGenDecl, tmpl) @@ -653,6 +680,30 @@ ABI_FIELD(RadVideoGenDecl, n_rungs) ABI_FIELD(RadVideoGenDecl, rungs) ABI_FIELD(RadVideoGenDecl, upscale_max) ABI_FIELD(RadVideoGenDecl, upscale_refine) +ABI_FIELD(RadVideoGenDecl, sched_kind) +ABI_FIELD(RadVideoGenDecl, dyn_shift) +ABI_FIELD(RadVideoGenDecl, base_shift) +ABI_FIELD(RadVideoGenDecl, max_shift) +ABI_FIELD(RadVideoGenDecl, base_seq) +ABI_FIELD(RadVideoGenDecl, max_seq) +ABI_FIELD(RadVideoGenDecl, shift_terminal) +ABI_FIELD(RadVideoGenDecl, n_refine_rungs) +ABI_FIELD(RadVideoGenDecl, refine_rungs) +ABI_FIELD(RadVideoGenDecl, step_text_rows) +ABI_FIELD(RadVideoGenDecl, guidance) +ABI_FIELD(RadVideoGenDecl, guidance_default) +ABI_FIELD(RadVideoGenDecl, default_negative) +ABI_FIELD(RadVideoGenDecl, image_cond) +ABI_FIELD(RadVideoGenDecl, image_crf) +ABI_FIELD(RadVideoGenDecl, text_left_pad) +ABI_FIELD(RadVideoGenDecl, audio_streams) +ABI_FIELD(RadVideoGenDecl, upscale_exact) +ABI_FIELD(RadVideoGenDecl, duration_out) +ABI_FIELD(RadVideoGenDecl, duration_min) +ABI_FIELD(RadVideoGenDecl, duration_max) +ABI_FIELD(RadVideoGenDecl, duration_dtype) +ABI_FIELD(RadVideoGenDecl, decoders) +ABI_FIELD(RadVideoGenDecl, decoder_max_area) ABI_STRUCT(RadVideoGeom) ABI_FIELD(RadVideoGeom, n_text) ABI_FIELD(RadVideoGeom, frames) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 67222040..6fc89cfb 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,4 +1,4 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 23 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 24 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ @@ -315,7 +315,7 @@ { "RadFuseStep", "n_p", 584, 4 }, { "RadFuseStep", "from", 588, 32 }, { "RadFuseStep", "n_from", 620, 4 }, -{ "RadGenBatch", "", 0, 224 }, +{ "RadGenBatch", "", 0, 320 }, { "RadGenBatch", "rows", 0, 8 }, { "RadGenBatch", "src", 8, 8 }, { "RadGenBatch", "rope", 16, 8 }, @@ -346,7 +346,20 @@ { "RadGenBatch", "dec_height", 212, 4 }, { "RadGenBatch", "dec_width", 216, 4 }, { "RadGenBatch", "dec_preview", 220, 4 }, -{ "RadGeneratorDecl", "", 0, 248 }, +{ "RadGenBatch", "branch", 224, 4 }, +{ "RadGenBatch", "n_pad", 228, 4 }, +{ "RadGenBatch", "valid_cu", 232, 8 }, +{ "RadGenBatch", "n_img", 240, 8 }, +{ "RadGenBatch", "img_cu", 248, 8 }, +{ "RadGenBatch", "img_rows", 256, 8 }, +{ "RadGenBatch", "mode_cu", 264, 8 }, +{ "RadGenBatch", "rope_f", 272, 8 }, +{ "RadGenBatch", "mode_rows", 280, 8 }, +{ "RadGenBatch", "mode_src", 288, 8 }, +{ "RadGenBatch", "mode_ccu", 296, 8 }, +{ "RadGenBatch", "n_mode_h", 304, 8 }, +{ "RadGenBatch", "mode_rope_f", 312, 8 }, +{ "RadGeneratorDecl", "", 0, 296 }, { "RadGeneratorDecl", "name", 0, 8 }, { "RadGeneratorDecl", "layout", 8, 4 }, { "RadGeneratorDecl", "tmpl_text", 16, 8 }, @@ -379,6 +392,14 @@ { "RadGeneratorDecl", "default_cfg", 224, 8 }, { "RadGeneratorDecl", "max_lanes", 232, 8 }, { "RadGeneratorDecl", "image_out", 240, 4 }, +{ "RadGeneratorDecl", "cond_rows", 248, 8 }, +{ "RadGeneratorDecl", "rope_hw_scale", 256, 8 }, +{ "RadGeneratorDecl", "rope_text_l", 264, 4 }, +{ "RadGeneratorDecl", "pad_multiple", 268, 4 }, +{ "RadGeneratorDecl", "pad_token", 272, 4 }, +{ "RadGeneratorDecl", "cfg_original", 276, 4 }, +{ "RadGeneratorDecl", "default_negative", 280, 8 }, +{ "RadGeneratorDecl", "ref_shrink_only", 288, 4 }, { "RadKVGroupBatch", "", 0, 72 }, { "RadKVGroupBatch", "group", 0, 4 }, { "RadKVGroupBatch", "slot_mapping", 8, 8 }, @@ -590,7 +611,7 @@ { "RadTunable", "n_values", 16, 4 }, { "RadTunable", "deflt", 24, 8 }, { "RadTunable", "doc", 32, 8 }, -{ "RadVideoGenBatch", "", 0, 192 }, +{ "RadVideoGenBatch", "", 0, 240 }, { "RadVideoGenBatch", "lane", 0, 4 }, { "RadVideoGenBatch", "geom", 4, 24 }, { "RadVideoGenBatch", "geom_d", 32, 8 }, @@ -612,7 +633,13 @@ { "RadVideoGenBatch", "n_samples", 152, 8 }, { "RadVideoGenBatch", "geom_from", 160, 24 }, { "RadVideoGenBatch", "upscale", 184, 8 }, -{ "RadVideoGenDecl", "", 0, 288 }, +{ "RadVideoGenBatch", "n_neg", 192, 4 }, +{ "RadVideoGenBatch", "guidance_h", 200, 8 }, +{ "RadVideoGenBatch", "image", 208, 8 }, +{ "RadVideoGenBatch", "has_image", 216, 4 }, +{ "RadVideoGenBatch", "guidance", 224, 8 }, +{ "RadVideoGenBatch", "decoder", 232, 4 }, +{ "RadVideoGenDecl", "", 0, 512 }, { "RadVideoGenDecl", "name", 0, 8 }, { "RadVideoGenDecl", "tmpl", 8, 8 }, { "RadVideoGenDecl", "max_text", 16, 8 }, @@ -650,6 +677,30 @@ { "RadVideoGenDecl", "rungs", 264, 8 }, { "RadVideoGenDecl", "upscale_max", 272, 8 }, { "RadVideoGenDecl", "upscale_refine", 280, 4 }, +{ "RadVideoGenDecl", "sched_kind", 284, 4 }, +{ "RadVideoGenDecl", "dyn_shift", 288, 4 }, +{ "RadVideoGenDecl", "base_shift", 296, 8 }, +{ "RadVideoGenDecl", "max_shift", 304, 8 }, +{ "RadVideoGenDecl", "base_seq", 312, 8 }, +{ "RadVideoGenDecl", "max_seq", 320, 8 }, +{ "RadVideoGenDecl", "shift_terminal", 328, 8 }, +{ "RadVideoGenDecl", "n_refine_rungs", 336, 4 }, +{ "RadVideoGenDecl", "refine_rungs", 344, 8 }, +{ "RadVideoGenDecl", "step_text_rows", 352, 8 }, +{ "RadVideoGenDecl", "guidance", 360, 4 }, +{ "RadVideoGenDecl", "guidance_default", 368, 64 }, +{ "RadVideoGenDecl", "default_negative", 432, 8 }, +{ "RadVideoGenDecl", "image_cond", 440, 4 }, +{ "RadVideoGenDecl", "image_crf", 444, 4 }, +{ "RadVideoGenDecl", "text_left_pad", 448, 8 }, +{ "RadVideoGenDecl", "audio_streams", 456, 4 }, +{ "RadVideoGenDecl", "upscale_exact", 460, 4 }, +{ "RadVideoGenDecl", "duration_out", 464, 4 }, +{ "RadVideoGenDecl", "duration_min", 472, 8 }, +{ "RadVideoGenDecl", "duration_max", 480, 8 }, +{ "RadVideoGenDecl", "duration_dtype", 488, 4 }, +{ "RadVideoGenDecl", "decoders", 496, 8 }, +{ "RadVideoGenDecl", "decoder_max_area", 504, 8 }, { "RadVideoGeom", "", 0, 24 }, { "RadVideoGeom", "n_text", 0, 4 }, { "RadVideoGeom", "frames", 4, 4 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index bc804bc0..bc51ff46 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -8,7 +8,7 @@ * * Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every * struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and - * the layout agrees with the table below, taken at RAD_ABI_VERSION 23 and RAD_FORMAT_VER 2. Under + * the layout agrees with the table below, taken at RAD_ABI_VERSION 24 and RAD_FORMAT_VER 2. Under * those versions a listed field may not move or change size, an ABI struct may only grow by fields * past its old end, and an on-disk struct may not change at all. The table is a snapshot of the * headers: nothing else states the layout. When it disagrees the test prints the live table. @@ -57,8 +57,8 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 23 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 23, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 24 / RAD_FORMAT_VER 2 (see the file header). */ +constexpr uint32_t kTableAbi = 24, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 84fbdf83..39ba088c 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -2375,7 +2375,6 @@ TEST(manifold_connections_preserve_saved_coefficients_and_use_a_separate_residua TEST(manifold_read_splits_its_projection_by_chunks_over_ranks_from_the_row_threshold) { using namespace rad::arch; - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); for (int world : { 1, 2, 4, 8 }) for (int rank = 0; rank < world; ++rank) { RadBuilder b; @@ -2501,7 +2500,6 @@ TEST(glm_routing_keeps_f32_logits_and_correction_replicated_under_tp4) { TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold) { using namespace rad::arch; - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); for (int world : { 1, 2, 4, 8 }) for (int rank = 0; rank < world; ++rank) { RadBuilder b; @@ -2578,44 +2576,6 @@ TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold) REQUIRE_EQ(ctx.issues.size(), (size_t)2); CHECK_EQ(ctx.issues[0].op, router.op_project); } - { - setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "64", 1); - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 128; - g.world = 8; - g.rank = 5; - GlmRouter::Config cfg; - cfg.rows = 128; - GlmRouter::Wire w; - w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); - w.logits = decl_b(&b, "logits", RAD_F32, { 128, 288 }); - w.ids = decl_b(&b, "ids", RAD_I32, { 128, 8 }); - w.weights = decl_b(&b, "weights", RAD_F32, { 128, 8 }); - GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", - "model.layers.3.mlp.gate.e_score_correction_bias" }; - GlmRouter router; - REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); - RadCtx ctx; - router.step(&ctx, 0, 64); - router.step(&ctx, 0, 63); - REQUIRE_EQ(ctx.issues.size(), (size_t)5); - CHECK_EQ(ctx.issues[0].op, router.split.op_part); - CHECK_EQ(ctx.issues[3].op, router.op_project); - setenv("RADIANCE_GLM_TP_SPLIT_ROWS", "0", 1); - RadBuilder off; - GlmRouter whole; - auto w2 = w; - w2.input = decl_b(&off, "hidden", RAD_BF16, { 128, 4096 }); - w2.logits = decl_b(&off, "logits", RAD_F32, { 128, 288 }); - w2.ids = decl_b(&off, "ids", RAD_I32, { 128, 8 }); - w2.weights = decl_b(&off, "weights", RAD_F32, { 128, 8 }); - REQUIRE_EQ(whole.declare(&off, nm, g, 3, "blk.3.router", cfg, w2, src), RAD_OK); - CHECK_EQ(count_op(off, "all_gather"), 0); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); - } } TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { @@ -2681,7 +2641,6 @@ TEST( meta.kv_val = vals; const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); for (int world : { 1, 4, 8 }) for (int rank = 0; rank < world; ++rank) { RadBuilder b; @@ -2900,77 +2859,72 @@ TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) { meta.kv_val = vals; const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); - // 256 is the default threshold; at 2048 the 256- and 1024-row levels lie below it. const int world = 8, rank = 3; - for (const char* split : { "256", "2048" }) - for (int64_t R : { 256, 3072 }) { - setenv("RADIANCE_GLM_TP_SPLIT_ROWS", split, 1); - auto encs = [&](RadBuilder& b) { - b.kv_block = 4; - b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, - { "mtp.blk.45.ffn_down_exps", fp8 }, - { "ffn_gate_up_exps", mx }, - { "ffn_down_exps", mx }, - { "ffn_gate_up_shexp", mx }, - { "ffn_down_shexp", mx }, - { "ffn_gate_up.weight", fp8 }, - { "ffn_down.weight", fp8 } }; - }; - RadBuildCtx c{}; - c.rank = rank; - c.world_size = world; - c.max_tok = 4096; - c.max_seqs = 8; - c.max_ctx = 32768; - c.max_spec = 3; - RadBuilder full; - encs(full); - REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); - RadBuildCtx p = c; - p.max_tok = R; - p.shape_probe = 1; - RadBuilder small; - encs(small); - REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); - REQUIRE_EQ(small.ops.size(), full.ops.size()); - int differ = 0; - for (size_t i = 0; i < full.ops.size(); ++i) { - if (small.ops[i].op != full.ops[i].op) { - ++differ; + for (int64_t R : { 256, 3072 }) { + auto encs = [&](RadBuilder& b) { + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + }; + RadBuildCtx c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 4096; + c.max_seqs = 8; + c.max_ctx = 32768; + c.max_spec = 3; + RadBuilder full; + encs(full); + REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); + RadBuildCtx p = c; + p.max_tok = R; + p.shape_probe = 1; + RadBuilder small; + encs(small); + REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); + REQUIRE_EQ(small.ops.size(), full.ops.size()); + int differ = 0; + for (size_t i = 0; i < full.ops.size(); ++i) { + if (small.ops[i].op != full.ops[i].op) { + ++differ; + continue; + } + REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); + for (size_t k = 0; k < full.ops[i].p.size(); ++k) { + const RecParam& a = full.ops[i].p[k]; + const RecParam& q = small.ops[i].p[k]; + if (a.kind == RAD_P_RANGE) continue; + // A capacity may shrink: its kernel writes by its operands' extents. + if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) continue; - } - REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); - for (size_t k = 0; k < full.ops[i].p.size(); ++k) { - const RecParam& a = full.ops[i].p[k]; - const RecParam& q = small.ops[i].p[k]; - if (a.kind == RAD_P_RANGE) continue; - // A capacity may shrink: its kernel writes by its operands' extents. - if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) - continue; - if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { - fprintf(stderr, - " split %s R %lld: op %zu '%s' param '%s': " - "%lld real, %lld small\n", - split, (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), - a.ival, q.ival); - ++differ; - } + if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { + fprintf(stderr, + " R %lld: op %zu '%s' param '%s': " + "%lld real, %lld small\n", + (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), + a.ival, q.ival); + ++differ; } } - CHECK_EQ(differ, 0); - REQUIRE_EQ(small.bufs.size(), full.bufs.size()); - for (size_t i = 0; i < full.bufs.size(); ++i) - for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) - CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); } - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + CHECK_EQ(differ, 0); + REQUIRE_EQ(small.bufs.size(), full.bufs.size()); + for (size_t i = 0; i < full.bufs.size(); ++i) + for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) + CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); + } } -/* The MoE block's decode fusions (RADIANCE_GLM_*): each switch, alone and with the others, changes - * exactly its launches against the step without switches, over a two-row trunk step, its draft - * pass and a 512-row prefill (past the router fusion's one-workgroup sort), with the step lint - * clean throughout. A switch value other than 0 or 1 is refused. */ +/* The MoE block's decode fusions: over a two-row trunk step, its draft pass and a 512-row prefill + * (past the router fusion's one-workgroup sort), each fused launch stands where it fits and the + * launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's + * row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) in every MoE pass. */ TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; @@ -2985,175 +2939,122 @@ TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { meta.kv_val = vals; const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - const char* const env[] = { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", - "RADIANCE_GLM_GATHER_INVERSE" }; - const int n_env = (int)(sizeof env / sizeof env[0]); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); - auto clear = [&]() { - for (const char* e : env) unsetenv(e); - }; using Counts = std::map; - /* Launches the first two switches remove (negative) and add, per step: trunk, draft pass, - * prefill. The trunk has 42 MoE layers, each a routed and a shared clamped SwiGLU, and three - * dense ones. The third turns every remaining sort and gather into its inverse form. */ - struct Delta { + /* Launches per step: trunk, draft pass, prefill. The trunk has 42 MoE layers, each a routed + * and a shared clamped SwiGLU, and three dense ones. */ + struct Want { const char* op; int trunk, draft, prefill; }; - const std::vector deltas[] = { - { { "router_sigmoid_topk_scatter", 42, 1, 0 }, - { "router_sigmoid_topk", -42, -1, 0 }, - { "moe_scatter", -42, -1, 0 }, - { "fill", -42, -1, 0 } }, - { { "swiglu_clamped_quant_fp8", 87, 2, 87 }, - { "swiglu_clamped", -87, -2, -87 }, - { "quant_act_fp8", -87, -2, -87 } }, + const Want wants[] = { + { "router_sigmoid_topk_scatter", 42, 1, 0 }, { "router_sigmoid_topk", 0, 0, 42 }, + { "swiglu_clamped_quant_fp8", 87, 2, 87 }, { "swiglu_clamped", 0, 0, 0 }, + { "moe_scatter", 0, 0, 0 }, { "moe_gather", 0, 0, 0 }, }; for (int world : { 1, 8 }) { - Counts base[3]; - for (int mask = 0; mask < (1 << n_env); ++mask) { - // At one rank only the extremes: no switch reads the world. - if (world == 1 && mask && mask != (1 << n_env) - 1) continue; - for (int e = 0; e < n_env; ++e) setenv(env[e], mask >> e & 1 ? "1" : "0", 1); - RadBuilder b; - b.kv_block = 4; - b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, - { "mtp.blk.45.ffn_down_exps", fp8 }, - { "ffn_gate_up_exps", mx }, - { "ffn_down_exps", mx }, - { "ffn_gate_up_shexp", mx }, - { "ffn_down_shexp", mx }, - { "ffn_gate_up.weight", fp8 }, - { "ffn_down.weight", fp8 } }; - RadBuildCtx build{}; - build.rank = 0; - build.world_size = world; - build.max_tok = 512; - build.max_seqs = 4; - build.max_ctx = 4096; - build.max_spec = 3; - REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); - int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, - slots[] = { 0, 1 }, out[] = { 1 }; - int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; - std::vector kv(b.kv_groups.size()); - for (size_t i = 0; i < kv.size(); ++i) { - kv[i].group = (rad_kvgroup)i + 1; - kv[i].slot_mapping = slots; - kv[i].block_table = tables; - kv[i].block_table_pitch = 32; - kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; - kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; - } - RadBatch batch{}; - batch.phase = RAD_PHASE_PREFILL; - batch.n_tok = 2; - batch.n_seq = 1; - batch.token_ids = ids; - batch.positions = positions; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.kv = kv.data(); - batch.n_kv_groups = (int)kv.size(); - batch.n_out = 1; - batch.out_ids = out; - RadCtx ctx; - ctx.b = &b; - ctx.rank = 0; - ctx.world = world; - ctx.batch = &batch; - Counts got[3]; - /* With the inverse, the fused selection writes it as its ninth operand and the gather - * reads it as its third. */ - const rad_buf inv = find_b(b, "expert_inverse") - ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) - : 0; - CHECK_EQ(inv != 0, (mask & 4) != 0); - auto run = [&](int k) { - ctx.issues.clear(); - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - CHECK_LINT(b, &ctx); - for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; - for (const auto& is : ctx.issues) { - const RecOp* o = b.op_of(is.op); - if (!o || !inv) continue; - if (o->op == "router_sigmoid_topk_scatter") - CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && - is.opd[8].handle == inv); - if (o->op == "moe_gather_inv") - CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && - is.opd[2].handle == inv); - } - }; - run(0); - batch.draft_pass = -1; - batch.n_draft_out = 1; - batch.draft_out_ids = out; - run(1); - std::vector long_ids(512, 7), long_positions(512), long_slots(512), - long_tables(1024); - for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; - int32_t long_cu[] = { 0, 512 }, last = 511; - for (auto& group : kv) { - group.slot_mapping = long_slots.data(); - group.block_table = long_tables.data(); - group.block_table_pitch = 1024; - } - batch.n_tok = 512; - batch.token_ids = long_ids.data(); - batch.positions = long_positions.data(); - batch.cu_seqlens = long_cu; - batch.out_ids = &last; - batch.draft_pass = 0; - batch.n_draft_out = 0; - batch.max_q_len = 512; - run(2); - if (mask == 0) { - for (int k = 0; k < 3; ++k) base[k] = got[k]; - continue; - } - for (int k = 0; k < 3; ++k) { - Counts want = base[k]; - for (int e = 0; e < 2; ++e) - if (mask >> e & 1) - for (const Delta& d : deltas[e]) - want[d.op] += k == 0 ? d.trunk : k == 1 ? d.draft : d.prefill; - if (mask & 4) { - want["moe_scatter_inv"] += want["moe_scatter"]; - want["moe_scatter"] = 0; - want["moe_gather_inv"] += want["moe_gather"]; - want["moe_gather"] = 0; - } - for (auto it = want.begin(); it != want.end();) - it = it->second == 0 ? want.erase(it) : std::next(it); - if (got[k] != want) { - fprintf(stderr, " world %d switches %d step %d:", world, mask, k); - for (const auto& [op, n] : want) - if (got[k][op] != n) - fprintf(stderr, " %s %d (want %d)", op.c_str(), got[k][op], n); - for (const auto& [op, n] : got[k]) - if (!want.count(op)) fprintf(stderr, " %s %d (want 0)", op.c_str(), n); - fprintf(stderr, "\n"); - } - CHECK(got[k] == want); - } - } - } - for (const char* e : env) { - clear(); - setenv(e, "2", 1); RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; RadBuildCtx build{}; build.rank = 0; - build.world_size = 8; - build.max_tok = 64; + build.world_size = world; + build.max_tok = 512; build.max_seqs = 4; build.max_ctx = 4096; build.max_spec = 3; - CHECK_EQ(glm5next::declare(&b, &meta, &build), RAD_E_INVAL); + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, + slots[] = { 0, 1 }, out[] = { 1 }; + int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; + std::vector kv(b.kv_groups.size()); + for (size_t i = 0; i < kv.size(); ++i) { + kv[i].group = (rad_kvgroup)i + 1; + kv[i].slot_mapping = slots; + kv[i].block_table = tables; + kv[i].block_table_pitch = 32; + kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; + kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; + } + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 2; + batch.n_seq = 1; + batch.token_ids = ids; + batch.positions = positions; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv.data(); + batch.n_kv_groups = (int)kv.size(); + batch.n_out = 1; + batch.out_ids = out; + RadCtx ctx; + ctx.b = &b; + ctx.rank = 0; + ctx.world = world; + ctx.batch = &batch; + Counts got[3]; + /* With the inverse, the fused selection writes it as its ninth operand and the gather + * reads it as its third. */ + const rad_buf inv = find_b(b, "expert_inverse") + ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) + : 0; + REQUIRE(inv != 0); + auto run = [&](int k) { + ctx.issues.clear(); + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + CHECK_LINT(b, &ctx); + for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; + for (const auto& is : ctx.issues) { + const RecOp* o = b.op_of(is.op); + if (!o) continue; + if (o->op == "router_sigmoid_topk_scatter") + CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && + is.opd[8].handle == inv); + if (o->op == "moe_gather_inv") + CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && + is.opd[2].handle == inv); + } + }; + run(0); + batch.draft_pass = -1; + batch.n_draft_out = 1; + batch.draft_out_ids = out; + run(1); + std::vector long_ids(512, 7), long_positions(512), long_slots(512), + long_tables(1024); + for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; + int32_t long_cu[] = { 0, 512 }, last = 511; + for (auto& group : kv) { + group.slot_mapping = long_slots.data(); + group.block_table = long_tables.data(); + group.block_table_pitch = 1024; + } + batch.n_tok = 512; + batch.token_ids = long_ids.data(); + batch.positions = long_positions.data(); + batch.cu_seqlens = long_cu; + batch.out_ids = &last; + batch.draft_pass = 0; + batch.n_draft_out = 0; + batch.max_q_len = 512; + run(2); + for (int k = 0; k < 3; ++k) + for (const Want& w : wants) { + const int want = k == 0 ? w.trunk : k == 1 ? w.draft : w.prefill; + if (got[k][w.op] != want) + fprintf(stderr, " world %d step %d: %s %d (want %d)\n", world, k, w.op, + got[k][w.op], want); + CHECK_EQ(got[k][w.op], want); + } } - clear(); } TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ring) { @@ -3296,7 +3197,7 @@ TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) { MlpFP8::Src src{ "post_attention_layernorm.weight", "mlp.gate_proj.weight", "mlp.up_proj.weight", "mlp.down_proj.weight" }; REQUIRE_EQ(block.declare(&b, nm, g, 0, w, src, false, false, kArNone, false, 10), RAD_OK); - CHECK_EQ(block.op_gated, 0); + CHECK_EQ(block.op_gated, 0u); CHECK_EQ(b.ops[block.gq_ffn.op - 1].op, std::string("swiglu_clamped")); RadCtx ctx; ctx.b = &b; @@ -3619,12 +3520,12 @@ TEST(mxfp4_expert_declarations_preserve_tp4_and_tp8_scale_geometry_and_movement_ if (glm) { CHECK_EQ(b.weights[moe.w_router - 1].d.dtype, RAD_F32); CHECK_EQ(b.ops[moe.op_topk - 1].op, std::string("router_sigmoid_topk")); - CHECK_EQ(moe.op_topk_scatter, 0); - CHECK_EQ(moe.op_router_fused, 0); + CHECK_EQ(moe.op_topk_scatter, 0u); + CHECK_EQ(moe.op_router_fused, 0u); CHECK_EQ(b.ops[moe.gq_exp.op - 1].op, std::string("swiglu_clamped")); CHECK_EQ(b.ops[moe.gq_sh.op - 1].op, std::string("swiglu_clamped")); CHECK_EQ(b.ops[moe.op_sgate - 1].op, std::string("fill")); - CHECK_EQ(moe.w_sgate, 0); + CHECK_EQ(moe.w_sgate, 0u); bool plain_shared = false; for (const auto& p : b.ops[moe.op_gather - 1].p) if (p.key == "act") plain_shared = p.sval == "none"; @@ -9475,10 +9376,9 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { } } -/* With the decode fusions switched off, GLM declares and steps the graph and launches it had - * before them, at one and eight ranks: a 4096-row prefill after history, a mixed step, a decode - * step, a verify and its draft passes. */ -TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) { +/* GLM declares and steps the pinned graph and launches at one and eight ranks: a 4096-row prefill + * after history, a mixed step, a decode step, a verify and its draft passes. */ +TEST(glm53_is_the_pinned_graph_and_steps) { const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", "index_topk" }; const char* vals[] = { "1", "4", "288", "2048" }; @@ -9496,12 +9396,8 @@ TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) { int world; uint64_t graph, steps; }; - const Case cases[] = { { 1, 0xd48139cb64abf0b1ull, 0x6982726c635df529ull }, - { 8, 0x90fc5bc69f1cfb10ull, 0x197c95726131b817ull } }; - for (const char* e : - { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" }) - setenv(e, "0", 1); - unsetenv("RADIANCE_GLM_TP_SPLIT_ROWS"); + const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull }, + { 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } }; for (const Case& cs : cases) { RadBuilder b; b.kv_block = 4; @@ -9525,9 +9421,6 @@ TEST(glm53_without_fusion_switches_is_the_pinned_graph_and_steps) { CHECK_EQ(g, cs.graph); CHECK_EQ(s, cs.steps); } - for (const char* e : - { "RADIANCE_GLM_ROUTER_FUSE", "RADIANCE_GLM_SWIGLU_QUANT", "RADIANCE_GLM_GATHER_INVERSE" }) - unsetenv(e); } /* Under a span a Flash-Next prefill of two intervals runs a pass at a time. At every world its diff --git a/tests/chat_test.cpp b/tests/chat_test.cpp index 46b5e9cb..df154adb 100644 --- a/tests/chat_test.cpp +++ b/tests/chat_test.cpp @@ -1043,6 +1043,36 @@ TEST(a_dotted_integer_is_an_index_as_in_jinja2) { CHECK_EQ(p.prompt, std::string("hi|assistant")); } +/* A template that takes one system message, first, as many do, against conversations the Chat + * Completions API allows: a system message after a user turn, and two at the head. They are + * rendered with the system messages merged, in order, into one at the head (#137). Any other + * refusal comes back in the template's own words, without the parser-generation wrapper. */ +TEST(system_messages_a_template_takes_only_first_are_merged_at_the_head) { + ChatTemplate t; + CHECK_OK(t.load( + "{%- for m in messages %}" + "{%- if m.role == 'system' and not loop.first %}" + "{{- raise_exception('System message must be at the beginning.') }}{%- endif %}" + "{%- if m.role == 'user' and m.content == 'boom' %}{{- raise_exception('no boom') }}{%- endif %}" + "<{{ m.role }}>{{ m.content }}" + "{%- endfor %}{%- if add_generation_prompt %}{% endif %}", "", "")); + ChatOptions opt; + opt.quiet = true; + auto render = [&](const json& msgs, ChatPrompt* p) { return t.apply(msgs, json(), opt, p); }; + ChatPrompt a, b, c, d; + CHECK_OK(render(json::parse(R"([{"role":"system","content":"s"},{"role":"user","content":"hi"}])"), &a)); + CHECK_EQ(a.prompt, std::string("shi")); + CHECK_OK(render(json::parse(R"([{"role":"user","content":"hi"},{"role":"system","content":"s"}])"), &b)); + CHECK_EQ(b.prompt, std::string("shi")); + CHECK_OK(render(json::parse(R"([{"role":"system","content":"s1"},{"role":"system", + "content":[{"type":"text","text":"s2"}]},{"role":"user","content":"hi"}])"), &c)); + CHECK_EQ(c.prompt, std::string("s1\n\ns2hi")); + CHECK(render(json::parse(R"([{"role":"system","content":"s"},{"role":"user","content":"boom"}])"), + &d) < 0); + CHECK(d.error.find("no boom") != std::string::npos); + CHECK(d.error.find("Unable to generate parser") == std::string::npos); +} + /* Unparseable Jinja (common in hand-built containers) is reported at load time as an error value; * a throw would cross the bringup path. */ TEST(a_template_that_does_not_parse_is_a_value_and_not_a_throw) { diff --git a/tests/gen_test.cpp b/tests/gen_test.cpp index 3114a6a9..8a2ea500 100644 --- a/tests/gen_test.cpp +++ b/tests/gen_test.cpp @@ -327,4 +327,99 @@ TEST(the_generator_admits_in_order_and_shutdown_answers_every_ticket) { CHECK(f.drv.next(1) == nullptr); } +/* The joint layout (RAD_GEN_LAYOUT_JOINT_STEP): no KV group; the conditioning's prompt padded to + * the declared multiple (padding at position 1, valid_cu bounding the prompt), the reference + * picture's tokens after it with its own l and scaled positions, and stored for every lane of the + * request. A denoising entry is that conditioning, read from its lane and branch's store rows, + * then the image, both in the pass order and mode by mode. */ +TEST(the_joint_layout_carries_the_conditioning_in_every_step) { + Program prog; + prog.generator = decl_base(); + RadGeneratorDecl& d = prog.generator; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.cond_rows = 64; + d.pad_multiple = 8; + d.pad_token = 99; + d.rope_hw_scale = 0.5; + d.rope_text_l = 1; + d.ref_area = 32 * 32; + prog.ctx.max_tok = 2048; + prog.ctx.max_seqs = 8; + prog.kv_groups.emplace_back(); + gen::Driver drv; + REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK); + auto r = std::make_unique(); + r->width = 64; + r->height = 32; + r->n = 2; + r->pos.tokens = { 1, 2, 3, 4, 5 }; + r->pos.n_drop = 1; + r->has_neg = true; + r->neg.tokens = { 1, 6 }; + r->neg.n_drop = 1; + r->cfg = 3.0f; + gen::Pixels px; + px.w = 32; + px.h = 32; + px.ch = 4; + px.bf16.assign(32 * 32 * 4, 0); + r->refs.push_back(px); + r->ticket = std::make_shared(); + std::string why; + REQUIRE_EQ(drv.submit(std::move(r), &why), (int)RAD_OK); + + /* The positive conditioning: 4 text rows padded to 8, then the picture's 2 x 2 tokens. */ + const RadBatch* b = drv.next(0); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND); + const RadGenBatch* G = b->gen_b; + CHECK_EQ(b->n_kv_groups, (int32_t)0); + CHECK_EQ(b->n_tok, (int64_t)9); /* five tokens and four padding */ + CHECK_EQ(G->rows, (int64_t)12); /* 8 text rows and 4 picture tokens */ + CHECK_EQ(G->n_pad, (int32_t)4); + CHECK_EQ(G->branch, (int32_t)0); + CHECK_EQ(G->valid_cu[1], (int32_t)5); + CHECK_EQ(b->token_ids[8], (int32_t)99); + CHECK_EQ(b->positions[8], (int32_t)1); + CHECK_EQ(G->n_lane, (int64_t)2); + CHECK_EQ(G->src[0], (int32_t)1); /* the prompt row after the drop */ + CHECK_EQ(G->src[8], (int32_t)-1); /* the picture's first latent row */ + CHECK_EQ(G->rope_f[3 * 12 + 2], 2.0f); /* text row 2: l = 2 */ + CHECK_EQ(G->rope_f[3 * 12 + 9], -1.0f); /* the picture: l = -1 */ + CHECK_EQ(G->rope_f[2 * 12 + 9], 0.5f); /* its token (0, 1): w = 0.5 */ + CHECK_OK(drv.done()); + b = drv.next(1); + REQUIRE(b != nullptr); + CHECK_EQ(b->gen_b->branch, (int32_t)1); + CHECK_EQ(b->gen_b->rows, (int64_t)12); /* one token padded to 8, the picture */ + CHECK_OK(drv.done()); + + /* A step: four entries (two images, each with its negative), 12 + 8 rows each. */ + b = drv.next(2); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE); + G = b->gen_b; + REQUIRE_EQ(b->n_seq, (int64_t)4); + CHECK_EQ(b->n_tok, (int64_t)80); + CHECK_EQ(G->n_img, (int64_t)32); + CHECK_EQ(b->cu_seqlens[1], (int32_t)20); + const int32_t lane0 = G->lane_dh[0]; + CHECK_EQ(G->src[0], (int32_t)(2 * lane0 * 64)); /* lane 0's positive row 0 */ + CHECK_EQ(G->src[20], (int32_t)((2 * lane0 + 1) * 64)); /* its negative row 0 */ + CHECK_EQ(G->src[12], (int32_t)-1); /* the first image row */ + CHECK_EQ(G->img_rows[0], (int32_t)12); + CHECK_EQ(G->img_cu[1], (int32_t)8); + CHECK_EQ(G->mode_cu[1], (int32_t)8); /* entry 0: text 0..8 */ + CHECK_EQ(G->mode_cu[2], (int32_t)12); /* pictures 8..12 */ + CHECK_EQ(G->mode_cu[3], (int32_t)20); /* image to 20 */ + CHECK_EQ(G->n_mode_h[0], (int64_t)32); + CHECK_EQ(G->n_mode_h[1], (int64_t)16); + CHECK_EQ(G->n_mode_h[2], (int64_t)32); + CHECK_EQ(G->mode_rows[32], (int32_t)8); /* the first picture row */ + CHECK_EQ(G->mode_ccu[1 * 5 + 1], (int32_t)4); /* pictures: entry 1 from 4 */ + CHECK_EQ(G->mode_rope_f[4 * 32 + 3 * 16 + 0], -1.0f); /* the pictures' l plane */ + CHECK_EQ(G->rope_f[1 * 80 + 12 + 4], 0.5f); /* image token (1, 0): h = 0.5 */ + CHECK_OK(drv.done()); +} + RAD_TEST_MAIN() diff --git a/tests/images_test.cpp b/tests/images_test.cpp index 8fe577ea..2cc5b814 100644 --- a/tests/images_test.cpp +++ b/tests/images_test.cpp @@ -171,6 +171,33 @@ TEST(usage_counts_each_pictures_tokens_in_every_branch) { /* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must * be the first picture's size. */ +/* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2): + * a request naming nothing is guided at the card's scale with the model's own empty negative + * prompt, handed on as s + 1; `guidance_scale` is the same field as `true_cfg_scale`, 0 turns it + * off, and naming both is refused. An RGB model refuses a transparent background. */ +TEST(guidance_follows_the_model_cards_terms_and_its_default_negative) { + Images s; + s.img.inf.cfg_original = true; + s.img.inf.default_cfg = 4.5; + s.img.inf.has_default_negative = true; + s.img.inf.default_negative = ""; + s.img.inf.pixel_channels = 3; + s.gen({ { "prompt", "a fox" } }); + REQUIRE(!s.img.got.empty()); + CHECK(s.last().has_neg); + CHECK_EQ(s.last().cfg, 5.5f); + s.gen({ { "prompt", "a fox" }, { "guidance_scale", 2.0 } }); + CHECK(s.last().has_neg); + CHECK_EQ(s.last().cfg, 3.0f); + s.gen({ { "prompt", "a fox" }, { "guidance_scale", 0.0 } }); + CHECK(!s.last().has_neg); + const json both = s.gen({ { "prompt", "x" }, { "guidance_scale", 2.0 }, { "true_cfg_scale", 2.0 } }, + 400); + CHECK_EQ(str_at(both["error"], "param"), std::string("guidance_scale")); + const json alpha = s.gen({ { "prompt", "x" }, { "background", "transparent" } }, 400); + CHECK_EQ(str_at(alpha["error"], "param"), std::string("background")); +} + TEST(an_auto_background_follows_the_pictures_alpha) { if (!mm::decoder_available()) return; Images s; diff --git a/tests/place_test.cpp b/tests/place_test.cpp index a9c34203..728c59c1 100644 --- a/tests/place_test.cpp +++ b/tests/place_test.cpp @@ -3834,48 +3834,57 @@ int process_vram(int64_t* out) { /* Tools and tests build and tear down movers repeatedly, and on a card every event or stream is * a hardware queue and VRAM. A mover that staged, promoted and filled a loan gives back every * event and every byte of device memory it took. */ +/* The runtime and the driver keep some memory for the life of the process once a path is first + * used: page tables for address ranges first mapped (a page, or a page and a 2 MiB directory), and + * on some hosts about 30 MiB the first copy sets up (#124: 2 MiB, 2 MiB + 4 KiB and 31 MiB + 348 + * KiB across runs on one host). So the work runs once before the count is taken, and the count + * after a second run may differ by a page and a directory, never by a buffer. */ TEST(a_mover_gives_back_every_event_and_device_byte) { - const int64_t events0 = rad_dev_live_events(); + auto run = [&]() { + const int64_t events0 = rad_dev_live_events(); + { + Fixture f; + build_dense(f, 8, 1 * MiB, /*host_kernel=*/false); + Config c = base_config(); + c.placement = "layer_offload"; + c.vram_weights_mib = 5; + c.host_pool_mib = 64; + PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; + Plan p; + REQUIRE_EQ(Planner(in).plan(&p), RAD_OK); + Mover m; + MoverConfig mc; + REQUIRE_EQ(m.init(f.prog, p, mc), RAD_OK); + RadStream compute = nullptr; + REQUIRE_EQ(rad_stream_create(&compute, 0), RAD_OK); + CHECK_OK(m.bind_compute_stream(compute)); + CHECK(rad_dev_live_events() > events0); + ComputeWork work; + for (int d = 0; d < 20; ++d) { + CHECK_OK(m.begin_dispatch(d, nullptr)); + work.run(compute); + CHECK_OK(m.prefetch_to_op(p.prefetch[(size_t)d % p.prefetch.size()].at_op)); + } + CHECK(m.stats().prefetched > 0); + CHECK_OK(rad_stream_sync(compute)); + rad_stream_destroy(compute); + } + { + LoanRig r; + REQUIRE_EQ(r.build(), RAD_OK); + CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll)); + for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) + CHECK_OK(r.dispatch()); + CHECK(r.m.stats().promotions > 0); + } + CHECK_EQ(rad_dev_live_events(), events0); + }; + run(); int64_t vram0 = 0, vram1 = 0; CHECK_OK(process_vram(&vram0)); - { - Fixture f; - build_dense(f, 8, 1 * MiB, /*host_kernel=*/false); - Config c = base_config(); - c.placement = "layer_offload"; - c.vram_weights_mib = 5; - c.host_pool_mib = 64; - PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; - Plan p; - REQUIRE_EQ(Planner(in).plan(&p), RAD_OK); - Mover m; - MoverConfig mc; - REQUIRE_EQ(m.init(f.prog, p, mc), RAD_OK); - RadStream compute = nullptr; - REQUIRE_EQ(rad_stream_create(&compute, 0), RAD_OK); - CHECK_OK(m.bind_compute_stream(compute)); - CHECK(rad_dev_live_events() > events0); - ComputeWork work; - for (int d = 0; d < 20; ++d) { - CHECK_OK(m.begin_dispatch(d, nullptr)); - work.run(compute); - CHECK_OK(m.prefetch_to_op(p.prefetch[(size_t)d % p.prefetch.size()].at_op)); - } - CHECK(m.stats().prefetched > 0); - CHECK_OK(rad_stream_sync(compute)); - rad_stream_destroy(compute); - } - { - LoanRig r; - REQUIRE_EQ(r.build(), RAD_OK); - CHECK_OK(r.m.set_loan(Mover::kLendKV, Loan::kAll)); - for (Deadline dl; (r.m.flex_used_bytes() == 0 || any_busy(r.h, r.hf.plan)) && !dl.passed();) - CHECK_OK(r.dispatch()); - CHECK(r.m.stats().promotions > 0); - } - CHECK_EQ(rad_dev_live_events(), events0); + run(); CHECK_OK(process_vram(&vram1)); - CHECK_EQ(vram1, vram0); + CHECK(vram1 - vram0 <= 2 * MiB + 4096); } RAD_TEST_MAIN() diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 67b6ed7c..4dd0689f 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -996,12 +996,10 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) { } /* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves - * every M up to its bound, a decode step's rows and a prefill chunk alike. RADIANCE_MLA_MATRIX_MAX_M - * lowers that bound, which this case does not cover. */ + * every M up to its bound, a decode step's rows and a prefill chunk alike. */ TEST(libr4d_resolves_the_mla_attention_by_rows) { const std::string so = libr4d(); if (so.empty()) return; - if (std::getenv("RADIANCE_MLA_MATRIX_MAX_M")) return; Registry r; CHECK(r.load_plugin(so, 0) >= 0); Geometry g; diff --git a/tests/r4d_emu/test_f32.cpp b/tests/r4d_emu/test_f32.cpp index b6232903..b67b6533 100644 --- a/tests/r4d_emu/test_f32.cpp +++ b/tests/r4d_emu/test_f32.cpp @@ -1,24 +1,24 @@ -/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. Every tile form - * (RADIANCE_F32_GEMM_TILE) must match the one-wave-per-output legacy kernel bit for bit, and the - * legacy kernel must match its arithmetic written out here: lane l folds k = l, l+32, ... with - * fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding - * stay untouched. +/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. The form the launcher picks + * at each shape (one wave an output at one row, else a tile of rows x columns a wave, by M; the + * shapes reach every one) must match the arithmetic written out here bit for bit: lane l folds + * k = l, l+32, ... with fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns + * and the pitch's padding stay untouched. * - * router_sigmoid_topk from the same unit: the wave-per-row select must match the serial scan - * (RADIANCE_ROUTER_SELECT=old) bit for bit, and the scan its arithmetic written out here, on - * random and on tied ranks, with the outputs' pitch padding untouched. */ + * router_sigmoid_topk from the same unit: the wave-per-row select must match a serial scan written + * out here bit for bit, on random and on tied ranks, with the outputs' pitch padding untouched. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" #include "ref_host.h" #include #include -#include #include #include #include -static float legacy_model(const uint16_t* x, const float* w, int k) { +extern const char* emu_last_kernel; + +static float gemm_model(const uint16_t* x, const float* w, int k) { float lane[32]; for (int l = 0; l < 32; ++l) { float s = 0; @@ -115,62 +115,41 @@ static void router_cases(std::mt19937& rng, int& cases, int& fails) { a.n_t = 4; a.p = p; a.n_p = 6; - auto run = [&](const char* form, std::vector& ids, std::vector& w) { - ids.assign((size_t)M * ip, -77); - w.assign((size_t)M * wp, -7.25f); - t[2].data = ids.data(); - t[3].data = w.data(); - if (form) - setenv("RADIANCE_ROUTER_SELECT", form, 1); - else - unsetenv("RADIANCE_ROUTER_SELECT"); - return r4d_rad_router_sigmoid_topk(&a, nullptr); - }; - std::vector ids_old, ids_new; - std::vector w_old, w_new; + std::vector ids((size_t)M * ip, -77); + std::vector w((size_t)M * wp, -7.25f); + t[2].data = ids.data(); + t[3].data = w.data(); ++cases; - if (run("old", ids_old, w_old) != RAD_OK) { - std::printf("FAIL router scan launch M=%d ne=%d\n", M, ne); - ++fails; - continue; - } + const int rc = r4d_rad_router_sigmoid_topk(&a, nullptr); int bad = 0; - for (int r = 0; r < M; ++r) { + for (int r = 0; r < M && rc == RAD_OK; ++r) { int mi[32]; float mw[32]; router_model(&lg[(size_t)r * lp], bias.data(), bp, ne, k, sh.norm, factor, mi, mw); - bad += std::memcmp(mi, &ids_old[(size_t)r * ip], (size_t)k * 4) != 0; - bad += std::memcmp(mw, &w_old[(size_t)r * wp], (size_t)k * 4) != 0; - for (int c = k; c < ip; ++c) bad += ids_old[(size_t)r * ip + c] != -77; - for (int c = k; c < wp; ++c) bad += w_old[(size_t)r * wp + c] != -7.25f; + bad += std::memcmp(mi, &ids[(size_t)r * ip], (size_t)k * 4) != 0; + bad += std::memcmp(mw, &w[(size_t)r * wp], (size_t)k * 4) != 0; + for (int c = k; c < ip; ++c) bad += ids[(size_t)r * ip + c] != -77; + for (int c = k; c < wp; ++c) bad += w[(size_t)r * wp + c] != -7.25f; } - if (bad) { - std::printf("FAIL router scan against its model at M=%d ne=%d k=%d: %d\n", M, ne, k, - bad); - ++fails; - } - ++cases; - const int rc = run(nullptr, ids_new, w_new); - if (rc != RAD_OK || ids_new != ids_old || - std::memcmp(w_new.data(), w_old.data(), w_new.size() * 4) != 0) { - std::printf("FAIL router wave select at M=%d ne=%d k=%d%s (rc %d)\n", M, ne, k, - sh.ties ? " tied" : "", rc); + if (rc != RAD_OK || bad) { + std::printf("FAIL router wave select against the scan at M=%d ne=%d k=%d%s (rc %d): " + "%d\n", + M, ne, k, sh.ties ? " tied" : "", rc, bad); ++fails; } } - unsetenv("RADIANCE_ROUTER_SELECT"); } int main() { std::mt19937 rng(17); std::normal_distribution nd(0.f, 1.f); - const char* forms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", - "4x4", "8x4", "16x2", "16x4", nullptr }; struct Shape { int M, N, K; }; - const Shape shapes[] = { { 1, 288, 512 }, { 3, 36, 129 }, { 8, 288, 129 }, { 33, 32, 512 }, - { 70, 36, 129 }, { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } }; + // One wave an output (M 1), the 2x1, 4x1 (M under 16 or N up to 8), 4x4 and 8x4 tiles. + const Shape shapes[] = { { 1, 288, 512 }, { 2, 288, 129 }, { 3, 36, 129 }, + { 8, 288, 129 }, { 33, 32, 512 }, { 70, 36, 129 }, + { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } }; int fails = 0, cases = 0; for (const Shape& sh : shapes) { const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3; @@ -211,49 +190,24 @@ int main() { a.n_t = 3; a.p = p; a.n_p = 4; - auto run = [&](const char* form, std::vector& y) { - y.assign((size_t)M * yp, -7.25f); - t[2].data = y.data(); - if (form) - setenv("RADIANCE_F32_GEMM_TILE", form, 1); - else - unsetenv("RADIANCE_F32_GEMM_TILE"); - return r4d_rad_gemm_nt_f32(&a, nullptr); - }; - std::vector legacy, got; + std::vector y((size_t)M * yp, -7.25f); + t[2].data = y.data(); ++cases; - if (run("legacy", legacy) != RAD_OK) { - std::printf("FAIL legacy launch M=%d N=%d K=%d\n", M, N, K); - ++fails; - continue; - } + const int rc = r4d_rad_gemm_nt_f32(&a, nullptr); int bad = 0; - for (int r = 0; r < M; ++r) { + for (int r = 0; r < M && rc == RAD_OK; ++r) { for (int c = 0; c < N; ++c) { - const float e = legacy_model(&x[(size_t)r * xp], &w[(size_t)c * K], K); - bad += std::memcmp(&e, &legacy[(size_t)r * yp + c], 4) != 0; + const float e = gemm_model(&x[(size_t)r * xp], &w[(size_t)c * K], K); + bad += std::memcmp(&e, &y[(size_t)r * yp + c], 4) != 0; } - for (int c = N; c < yp; ++c) bad += legacy[(size_t)r * yp + c] != -7.25f; + for (int c = N; c < yp; ++c) bad += y[(size_t)r * yp + c] != -7.25f; } - if (bad) { - std::printf("FAIL legacy kernel against its model at M=%d N=%d K=%d: %d words\n", M, N, - K, bad); + if (rc != RAD_OK || bad) { + std::printf("FAIL %s at M=%d N=%d K=%d against its model (rc %d): %d words\n", + emu_last_kernel, M, N, K, rc, bad); ++fails; } - for (const char* const* f = forms;; ++f) { - ++cases; - const int rc = run(*f, got); - const bool same = - rc == RAD_OK && std::memcmp(got.data(), legacy.data(), got.size() * 4) == 0; - if (!same) { - std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d)\n", *f ? *f : "default", M, N, - K, rc); - ++fails; - } - if (!*f) break; - } } - unsetenv("RADIANCE_F32_GEMM_TILE"); router_cases(rng, cases, fails); std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; diff --git a/tests/r4d_emu/test_fp8f32.cpp b/tests/r4d_emu/test_fp8f32.cpp index e68543e5..a8eadeec 100644 --- a/tests/r4d_emu/test_fp8f32.cpp +++ b/tests/r4d_emu/test_fp8f32.cpp @@ -1,20 +1,22 @@ /* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT - * emulator. The decode and row-tile forms (RADIANCE_FP8F32_FORM, each R x S x C and row count) must - * match the legacy 16x64 tile - * bit for bit: the same fragments, the same mma chain per 128-K block and the same fold order. - * Ragged row counts, pitched rows and a K that leaves the decode form's last wave group partly - * idle are covered; the output's pitch padding stays untouched. */ + * emulator. The form the rule picks at each shape (the decode form at one and two column tiles a + * wave and one to eight waves a block, the 16- and 32-row tiles) must match the legacy 16x64 tile, + * which serves an activation pitch off 16 bytes, bit for bit: the same fragments, the same mma + * chain per 128-K block and the same fold order. Ragged row counts, pitched rows and a K that + * leaves the decode form's last wave group partly idle are covered; the output's pitch padding + * stays untouched. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" #include "ref_host.h" #include #include -#include #include #include #include +extern const char* emu_last_kernel; + static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) { RadTensor t{}; t.data = p; @@ -32,19 +34,26 @@ int main() { std::normal_distribution nd(0.f, 1.f); struct Shape { int M, N, K; + const char* kernel; }; - const Shape shapes[] = { { 1, 256, 512 }, { 6, 128, 1536 }, { 17, 256, 512 }, - { 48, 128, 512 }, { 70, 128, 384 }, { 130, 128, 256 }, - { 3, 128, 4096 } }; - const char* forms[] = { "decode", "decode1x4", "decode1x32", "decode2x8", - "decode3x16", "decode1x8x2", "decode1x4x4", "decode2x8x2", - "decode3x4x2", "decode2x4x4", "rows1", "rows2", - "rows4", nullptr }; + const char* const dec1 = "(fp8_f32scale_decode<1, 1>)"; + const char* const dec2 = "(fp8_f32scale_decode<1, 2>)"; + const char* const rows = "fp8_f32scale_rows"; + // Decode at eight, four, two and one waves a block (K blocks 12/32, 4, 2, 1), at two column + // tiles a wave from 17 rows over N 1024 and 640; the 16-row tile, and the 32-row one at N 4096. + const Shape shapes[] = { { 1, 256, 512, dec1 }, { 6, 128, 1536, dec1 }, + { 17, 256, 512, dec1 }, { 48, 128, 512, dec1 }, + { 2, 128, 256, dec1 }, { 5, 256, 128, dec1 }, + { 3, 128, 4096, dec1 }, { 40, 1024, 512, dec2 }, + { 20, 640, 256, dec2 }, { 70, 128, 384, rows }, + { 130, 128, 256, rows }, { 33, 4096, 512, rows }, + { 70, 4096, 128, rows } }; int fails = 0, cases = 0; for (const Shape& sh : shapes) { - const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, yp = N + 8; - std::vector a((size_t)M * ap), w((size_t)N * K); + const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, lp = K + 8, yp = N + 8; + std::vector a((size_t)M * ap), al((size_t)M * lp), w((size_t)N * K); for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng)); + for (int r = 0; r < M; ++r) std::memcpy(&al[(size_t)r * lp], &a[(size_t)r * ap], K); for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f); std::vector as((size_t)M * kb), ws((size_t)(N / 128) * kb); // Scales over twelve octaves: K blocks of very different weight cancel, so a changed @@ -67,10 +76,12 @@ int main() { p[4].key = "dtype"; p[4].kind = RAD_P_STR; p[4].sval = "fp8a8f32"; - auto run = [&](const char* form, std::vector& y) { + // The pitch off 16 bytes takes the legacy tile. + auto run = [&](bool legacy, std::vector& y) { y.assign((size_t)M * yp, 0x7777); + t[0] = legacy ? mat(al.data(), RAD_F8E4M3, M, K, lp) + : mat(a.data(), RAD_F8E4M3, M, K, ap); t[4] = mat(y.data(), RAD_BF16, M, N, yp); - setenv("RADIANCE_FP8F32_FORM", form, 1); RadArgs ar{}; ar.t = t; ar.n_t = 7; @@ -80,8 +91,8 @@ int main() { }; std::vector legacy, got; ++cases; - if (run("legacy", legacy) != RAD_OK) { - std::printf("FAIL legacy M=%d N=%d K=%d\n", M, N, K); + if (run(true, legacy) != RAD_OK || std::strcmp(emu_last_kernel, "fp8_f32scale")) { + std::printf("FAIL legacy M=%d N=%d K=%d ran %s\n", M, N, K, emu_last_kernel); ++fails; continue; } @@ -92,19 +103,16 @@ int main() { std::printf("FAIL legacy output mostly zero at M=%d\n", M); ++fails; } - for (const char* const* f = forms; *f; ++f) { - ++cases; - const int rc = run(*f, got); - if (rc != RAD_OK || got != legacy) { - size_t i = 0; - while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i; - std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d, first word %zu)\n", *f, M, N, K, - rc, i); - ++fails; - } + ++cases; + const int rc = run(false, got); + if (rc != RAD_OK || std::strcmp(emu_last_kernel, sh.kernel) || got != legacy) { + size_t i = 0; + while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i; + std::printf("FAIL %s (want %s) at M=%d N=%d K=%d (rc %d, first word %zu)\n", + emu_last_kernel, sh.kernel, M, N, K, rc, i); + ++fails; } } - unsetenv("RADIANCE_FP8F32_FORM"); std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; } diff --git a/tests/r4d_emu/test_kda.cpp b/tests/r4d_emu/test_kda.cpp index 65cdba48..72c36fcc 100644 --- a/tests/r4d_emu/test_kda.cpp +++ b/tests/r4d_emu/test_kda.cpp @@ -1,15 +1,19 @@ -/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator. Every row and prefetch form - * must give the old one-row kernel's output and whole state buffer bit for bit, in all four modes: - * prefill per candidate and anchored, verify per candidate and anchored (after the replay of the - * accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten slot - * are mixed in. The GPU check of the same claim is r4d_selftest's kda_forms. */ +/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator, held to libref's kda_update + * (from $RADIANCE_HOME, which ctest sets) over the output and the whole state buffer, in all four + * modes: prefill per candidate and anchored, verify per candidate and anchored (after the replay + * of the accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten + * slot are mixed in, so a byte the reference leaves alone must stay as it was. The kernel's lane + * reductions sum in another order than libref's loops: f32 state within 2e-5 + 2e-5 |x|, bf16 + * output within one rounding step. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" +#include #include #include #include #include +#include #include #include #include @@ -33,6 +37,32 @@ static uint16_t f2b(float f) { return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); } +/* libref's kda_update, through the plugin's own exports, or null. */ +static RadLaunchFn load_libref() { + const char* home = std::getenv("RADIANCE_HOME"); + if (!home || !*home) return nullptr; + const std::string p = std::string(home) + "/kernels/libref.so"; + void* h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) return nullptr; + auto open = (int (*)(void))dlsym(h, "rad_plugin_open"); /* as the loader does */ + if (open && open() < 0) return nullptr; + auto cnt = (int (*)(void))dlsym(h, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at"); + if (!cnt || !at) return nullptr; + for (int i = 0; i < cnt(); ++i) { + const RadKernelInfo* k = at(i); + if (k && k->op && !std::strcmp(k->op, "kda_update")) return k->launch; + } + return nullptr; +} + +static float bf16_value(uint16_t b) { + const uint32_t u = (uint32_t)b << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + struct Case { const char* name; const char* mode; @@ -43,6 +73,11 @@ struct Case { }; int main() { + const RadLaunchFn reference = load_libref(); + if (!reference) { + std::printf("FAIL libref's kda_update not loadable (set RADIANCE_HOME)\n"); + return 1; + } std::mt19937 rng(41); std::uniform_real_distribution u(-1.f, 1.f); const int64_t H = 2, D = 128, slots = 16, tokens = 9; @@ -93,12 +128,6 @@ int main() { { 1, 1, 0 }, { { 5, 4.f }, { 6, 3.f }, { 7, 0.f } } }, }; - struct Form { - const char* rows; - const char* prefetch; - }; - const Form forms[] = { { "1", "1" }, { "2", "1" }, { "4", "1" }, - { "1", "0" }, { "2", "0" }, { "4", "0" } }; int fails = 0, checks = 0; for (const Case& c : cases) { std::vector start = state0; @@ -106,7 +135,7 @@ int main() { for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second; const int64_t seqs = (int64_t)c.cu.size() - 1; std::vector idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init; - auto run = [&](std::vector& out, std::vector& state) { + auto run = [&](RadLaunchFn launch, std::vector& out, std::vector& state) { out.assign((size_t)(tokens * H * D), 0x7777); state = start; RadTensor t[13] = { tens(in[0].data(), RAD_BF16, { tokens, H, D }), @@ -149,39 +178,40 @@ int main() { a.n_t = 13; a.p = p; a.n_p = 9; - return r4d_rad_kda_update(&a, nullptr); + return launch(&a, nullptr); }; std::vector ref_out, out; std::vector ref_state, state; - setenv("RADIANCE_KDA_FORM", "old", 1); - if (run(ref_out, ref_state) != RAD_OK) { - std::printf("FAIL %s: old form refused\n", c.name); + ++checks; + if (run(reference, ref_out, ref_state) != RAD_OK || + run(r4d_rad_kda_update, out, state) != RAD_OK) { + std::printf("FAIL %s: refused\n", c.name); ++fails; continue; } - unsetenv("RADIANCE_KDA_FORM"); bool written = false; for (size_t i = 0; i < ref_out.size(); ++i) written = written || ref_out[i] != 0x7777; - if (!written) { - std::printf("FAIL %s: the old form wrote no output\n", c.name); - ++fails; + size_t bad = 0; + double out_err = 0, state_err = 0; + for (size_t i = 0; i < out.size(); ++i) { + if (out[i] == ref_out[i]) continue; + const float x = bf16_value(out[i]), y = bf16_value(ref_out[i]); + const double e = std::fabs((double)x - y); + out_err = std::max(out_err, e); + if (!std::isfinite(x) || ref_out[i] == 0x7777 || out[i] == 0x7777 || + e > 1e-6 + 0.008 * std::fabs(y)) + ++bad; } - for (const Form& f : forms) { - setenv("RADIANCE_KDA_ROWS", f.rows, 1); - setenv("RADIANCE_KDA_PREFETCH", f.prefetch, 1); - ++checks; - const bool same = run(out, state) == RAD_OK && out == ref_out && - std::memcmp(state.data(), ref_state.data(), state.size() * 4) == 0; - if (!same) { - ++fails; - std::printf("FAIL %s, %s rows a wave, prefetch %s: differs from the old form\n", - c.name, f.rows, f.prefetch); - } + for (size_t i = 0; i < state.size(); ++i) { + if (state[i] == ref_state[i]) continue; + const double e = std::fabs((double)state[i] - ref_state[i]); + state_err = std::max(state_err, e); + if (!std::isfinite(state[i]) || e > 2e-5 + 2e-5 * std::fabs(ref_state[i])) ++bad; } - unsetenv("RADIANCE_KDA_ROWS"); - unsetenv("RADIANCE_KDA_PREFETCH"); + std::printf("%-24s output max %.3g, state max %.3g%s\n", c.name, out_err, state_err, + !written ? " NO OUTPUT" : bad ? " FAIL" : ""); + if (!written || bad) ++fails; } - std::printf("kda_update forms against the old kernel: %d of %d bit-identical\n", checks - fails, - checks); + std::printf("kda_update against libref: %d of %d within bounds\n", checks - fails, checks); return fails ? 1 : 0; } diff --git a/tests/r4d_emu/test_mhc.cpp b/tests/r4d_emu/test_mhc.cpp index 82bd77e6..520942bf 100644 --- a/tests/r4d_emu/test_mhc.cpp +++ b/tests/r4d_emu/test_mhc.cpp @@ -1,8 +1,9 @@ /* tests/r4d_emu: GLM's mHC read split by residual chunks (r4d_mhc.hip) on the host SIMT emulator. * Each rank's mhc_pre_partial over its chunks, the partials joined row by row as the * row-interleaved all_gather lays them out, then mhc_pre_finish, must give mhc_pre's x, post and - * comb bit for bit, under each of mhc_pre's kernel switches; the partial matrix's padding slots - * are zero. Every form is also held to the old dispatch, bit for bit. */ + * comb bit for bit; the partial matrix's padding slots are zero. On 16-byte rows the vector forms + * run, and they are held bit for bit to the same operands on pitched rows, where the scalar forms + * run. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -42,148 +43,123 @@ int main() { std::vector fn((size_t)(mix * W)), scale = { 0.7f, 0.9f, 1.1f }, base((size_t)mix); for (auto& v : fn) v = nd(rng) * 0.01f; for (auto& v : base) v = nd(rng) * 0.5f; - struct Form { - const char* env; - const char* value; - }; - const Form forms[] = { { nullptr, nullptr }, - { "RADIANCE_MHC_PREFILL_COEFF4", "0" }, - { "RADIANCE_MHC_PREFILL_ROWS4", "0" }, - { "RADIANCE_MHC_PREFILL_WARP", "0" } }; int fails = 0, cases = 0; for (int64_t rows : { 1, 5, 37 }) { const int64_t hp = W + 6, xp = n + 2; std::vector h((size_t)(rows * hp)); for (auto& v : h) v = f2b(nd(rng)); - for (const Form& f : forms) { - if (f.env) setenv(f.env, f.value, 1); - RadParam coef[8]{}; - coef[0] = { "M", RAD_P_INT, rows }; - coef[1] = { "n", RAD_P_INT, n }; - coef[2] = { "hc", RAD_P_INT, hc }; - coef[3] = { "iterations", RAD_P_INT, 20 }; - coef[4].key = "eps"; - coef[4].kind = RAD_P_F64; - coef[4].dval = 1e-5; - coef[5].key = "hc_eps"; - coef[5].kind = RAD_P_F64; - coef[5].dval = 1e-6; - coef[6].key = "dtype"; - coef[6].kind = RAD_P_STR; - coef[6].sval = "bf16"; - std::vector x((size_t)(rows * xp), 0x7777); - std::vector post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc)); - RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp), - mat(fn.data(), RAD_F32, mix, W, W), - vec(scale.data(), 3), - vec(base.data(), mix), - mat(x.data(), RAD_BF16, rows, n, xp), - mat(post.data(), RAD_F32, rows, hc, hc), - mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) }; - RadArgs a{}; - a.t = t; - a.n_t = 7; - a.p = coef; - a.n_p = 7; - if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) { - std::printf("FAIL mhc_pre M=%lld\n", (long long)rows); + RadParam coef[8]{}; + coef[0] = { "M", RAD_P_INT, rows }; + coef[1] = { "n", RAD_P_INT, n }; + coef[2] = { "hc", RAD_P_INT, hc }; + coef[3] = { "iterations", RAD_P_INT, 20 }; + coef[4].key = "eps"; + coef[4].kind = RAD_P_F64; + coef[4].dval = 1e-5; + coef[5].key = "hc_eps"; + coef[5].kind = RAD_P_F64; + coef[5].dval = 1e-6; + coef[6].key = "dtype"; + coef[6].kind = RAD_P_STR; + coef[6].sval = "bf16"; + std::vector x((size_t)(rows * xp), 0x7777); + std::vector post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc)); + RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp), + mat(fn.data(), RAD_F32, mix, W, W), + vec(scale.data(), 3), + vec(base.data(), mix), + mat(x.data(), RAD_BF16, rows, n, xp), + mat(post.data(), RAD_F32, rows, hc, hc), + mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadArgs a{}; + a.t = t; + a.n_t = 7; + a.p = coef; + a.n_p = 7; + if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) { + std::printf("FAIL mhc_pre M=%lld\n", (long long)rows); + ++fails; + continue; + } + for (int world : { 2, 4, 8 }) { + ++cases; + const int64_t mine = total / world; + std::vector gathered((size_t)(rows * total * S)); + bool padded = true, launched = true; + for (int rank = 0; rank < world; ++rank) { + std::vector part((size_t)(rows * mine * S), 7.0f); + RadTensor pt[3] = { t[0], t[1], + mat(part.data(), RAD_F32, rows, mine * S, mine * S) }; + RadParam pp[7]{}; + pp[0] = { "M", RAD_P_INT, rows }; + pp[1] = { "n", RAD_P_INT, n }; + pp[2] = { "hc", RAD_P_INT, hc }; + pp[3] = { "chunk", RAD_P_INT, 2048 }; + pp[4] = { "first", RAD_P_INT, rank * mine }; + pp[5] = { "chunks", RAD_P_INT, mine }; + pp[6].key = "dtype"; + pp[6].kind = RAD_P_STR; + pp[6].sval = "bf16"; + RadArgs pa{}; + pa.t = pt; + pa.n_t = 3; + pa.p = pp; + pa.n_p = 7; + launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK; + for (int64_t r = 0; r < rows; ++r) { + for (int64_t c = 0; c < mine; ++c) + for (int64_t j = mix + 1; j < S; ++j) + padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f; + std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)], + &part[(size_t)(r * mine * S)], (size_t)(mine * S * 4)); + } + } + std::vector x2((size_t)(rows * xp), 0x7777); + std::vector post2(post.size()), comb2(comb.size()); + RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S), + t[0], + t[2], + t[3], + mat(x2.data(), RAD_BF16, rows, n, xp), + mat(post2.data(), RAD_F32, rows, hc, hc), + mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadParam fp[8]; + std::memcpy(fp, coef, sizeof coef); + fp[6] = { "chunk", RAD_P_INT, 2048 }; + fp[7].key = "dtype"; + fp[7].kind = RAD_P_STR; + fp[7].sval = "bf16"; + RadArgs fa{}; + fa.t = ft; + fa.n_t = 7; + fa.p = fp; + fa.n_p = 8; + launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK; + const bool same = launched && x2 == x && + std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 && + std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0; + if (!same || !padded) { + std::printf("FAIL M=%lld world %d: %s\n", (long long)rows, world, + !launched ? "launch" + : !padded ? "padding" + : "differs"); ++fails; - continue; } - for (int world : { 2, 4, 8 }) { - ++cases; - const int64_t mine = total / world; - std::vector gathered((size_t)(rows * total * S)); - bool padded = true, launched = true; - for (int rank = 0; rank < world; ++rank) { - std::vector part((size_t)(rows * mine * S), 7.0f); - RadTensor pt[3] = { t[0], t[1], - mat(part.data(), RAD_F32, rows, mine * S, mine * S) }; - RadParam pp[7]{}; - pp[0] = { "M", RAD_P_INT, rows }; - pp[1] = { "n", RAD_P_INT, n }; - pp[2] = { "hc", RAD_P_INT, hc }; - pp[3] = { "chunk", RAD_P_INT, 2048 }; - pp[4] = { "first", RAD_P_INT, rank * mine }; - pp[5] = { "chunks", RAD_P_INT, mine }; - pp[6].key = "dtype"; - pp[6].kind = RAD_P_STR; - pp[6].sval = "bf16"; - RadArgs pa{}; - pa.t = pt; - pa.n_t = 3; - pa.p = pp; - pa.n_p = 7; - launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK; - for (int64_t r = 0; r < rows; ++r) { - for (int64_t c = 0; c < mine; ++c) - for (int64_t j = mix + 1; j < S; ++j) - padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f; - std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)], - &part[(size_t)(r * mine * S)], (size_t)(mine * S * 4)); - } - } - std::vector x2((size_t)(rows * xp), 0x7777); - std::vector post2(post.size()), comb2(comb.size()); - RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S), - t[0], - t[2], - t[3], - mat(x2.data(), RAD_BF16, rows, n, xp), - mat(post2.data(), RAD_F32, rows, hc, hc), - mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) }; - RadParam fp[8]; - std::memcpy(fp, coef, sizeof coef); - fp[6] = { "chunk", RAD_P_INT, 2048 }; - fp[7].key = "dtype"; - fp[7].kind = RAD_P_STR; - fp[7].sval = "bf16"; - RadArgs fa{}; - fa.t = ft; - fa.n_t = 7; - fa.p = fp; - fa.n_p = 8; - launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK; - const bool same = launched && x2 == x && - std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 && - std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0; - if (!same || !padded) { - std::printf("FAIL M=%lld world %d %s%s%s: %s\n", (long long)rows, world, - f.env ? f.env : "default", f.env ? "=" : "", f.env ? f.value : "", - !launched ? "launch" - : !padded ? "padding" - : "differs"); - ++fails; - } - } - if (f.env) unsetenv(f.env); } } - /* Every form against the old dispatch (one-wave finish from 32 rows, scalar mix and read - * below, scalar-row and rows4 partials, the per-output mhc_post) on 16-byte rows, where the - * vector paths run: mhc_pre's x, post and comb, mhc_pre_partial's matrix and mhc_post's - * output, bit for bit. */ - struct Pin { - const char* what; - const char* finish; - const char* vec; - const char* prow; - }; - const Pin pins[] = { { "rule", nullptr, nullptr, nullptr }, - { "finish scalar", "scalar", nullptr, nullptr }, - { "partials four-slot, 1 row a wave", nullptr, "1", "1" }, - { "partials four-slot, 2 rows a wave", nullptr, "1", "2" }, - { "partials four-slot, 4 rows a wave", nullptr, "1", "4" } }; - auto pin = [](const char* k, const char* v) { - if (v) - setenv(k, v, 1); - else - unsetenv(k); - }; + /* The vector forms (four-slot partials, the finish's 16-byte collapse, the eight-column + * mhc_post) on 16-byte rows against the scalar forms (one slot a thread, four rows and four + * coefficients a block from 32 rows, the per-output mhc_post) on the same operands with the + * residual pitched by two elements: mhc_pre's x, post and comb, mhc_pre_partial's matrix and + * mhc_post's output, bit for bit. */ for (int64_t rows : { 1, 5, 16, 37, 64 }) { std::vector h((size_t)(rows * W)), y((size_t)(rows * n)); for (auto& v : h) v = f2b(nd(rng)); for (auto& v : y) v = f2b(nd(rng)); + const int64_t pitched = W + 2; + std::vector hp((size_t)(rows * pitched), 0x7777); + for (int64_t r = 0; r < rows; ++r) + std::memcpy(&hp[(size_t)(r * pitched)], &h[(size_t)(r * W)], (size_t)W * 2); RadParam coef[7]{}; coef[0] = { "M", RAD_P_INT, rows }; coef[1] = { "n", RAD_P_INT, n }; @@ -202,13 +178,13 @@ int main() { std::vector x, o; std::vector p, c, part; }; - auto run = [&](Out* r) { + auto run = [&](Out* r, const uint16_t* hd, int64_t ld) { r->x.assign((size_t)(rows * n), 0x7777); r->o.assign((size_t)(rows * W), 0x7777); r->p.assign((size_t)(rows * hc), 0); r->c.assign((size_t)(rows * hc * hc), 0); r->part.assign((size_t)(rows * total * S), 7.0f); - RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, W), + RadTensor t[7] = { mat((void*)hd, RAD_BF16, rows, W, ld), mat(fn.data(), RAD_F32, mix, W, W), vec(scale.data(), 3), vec(base.data(), mix), @@ -249,34 +225,21 @@ int main() { return okay && r4d_rad_mhc_post(&oa, nullptr) == RAD_OK; }; Out ref, got; - pin("RADIANCE_MHC_FINISH", "old"); - pin("RADIANCE_MHC_PARTIAL_VEC", "0"); - pin("RADIANCE_MHC_POST_VEC", "0"); - const bool ref_ok = run(&ref); - pin("RADIANCE_MHC_POST_VEC", nullptr); - for (const Pin& f : pins) { - ++cases; - pin("RADIANCE_MHC_FINISH", f.finish); - pin("RADIANCE_MHC_PARTIAL_VEC", f.vec); - pin("RADIANCE_MHC_PARTIAL_ROWS", f.prow); - const bool launched = ref_ok && run(&got); - const char* bad = !launched ? "launch" - : got.x != ref.x ? "x" - : std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post" - : std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb" - : std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4) - ? "partials" - : got.o != ref.o ? "mhc_post" - : nullptr; - if (bad) { - std::printf("FAIL M=%lld %s against the old dispatch: %s differs\n", - (long long)rows, f.what, bad); - ++fails; - } + ++cases; + const bool launched = run(&ref, hp.data(), pitched) && run(&got, h.data(), W); + const char* bad = !launched ? "launch" + : got.x != ref.x ? "x" + : std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post" + : std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb" + : std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4) + ? "partials" + : got.o != ref.o ? "mhc_post" + : nullptr; + if (bad) { + std::printf("FAIL M=%lld 16-byte rows against pitched rows: %s differs\n", + (long long)rows, bad); + ++fails; } - for (const char* k : - { "RADIANCE_MHC_FINISH", "RADIANCE_MHC_PARTIAL_VEC", "RADIANCE_MHC_PARTIAL_ROWS" }) - unsetenv(k); } std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; diff --git a/tests/r4d_emu/test_mla.cpp b/tests/r4d_emu/test_mla.cpp index fd8d5330..95d125c7 100644 --- a/tests/r4d_emu/test_mla.cpp +++ b/tests/r4d_emu/test_mla.cpp @@ -3,7 +3,9 @@ * tile (eight heads of two neighbouring rows) on the tables it meets in serving: a prefill chunk * whose rows share one table, and rows past the DSA budget, where each row selects its own top * blocks and neighbours share most blocks but rarely a table position. The conflict counters - * (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. */ + * (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. Both pairings run on the + * same operands: the union at the case's table width, the positional pairing on the table + * widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -22,7 +24,7 @@ extern "C" void r4d_mla_matrix_stats(unsigned long long* out); namespace { -constexpr int D = 512, BS = 4; +constexpr int D = 512, BS = 4, kUnionBlocks = 520; enum class Fill { prefill, topk, ragged, repeat }; @@ -35,6 +37,7 @@ struct Case { bool scratch = false; /* lets the launcher split the history */ int form = 0; /* r4d_mla_matrix_pin_form */ int expect_second = -1; /* positional pairing: 0 no second pass, 1 some, -1 either */ + /* Unsplit only: with scratch the widened table gives the positional run more splits. */ bool bitwise_a = true; /* the union's request r equals the positional pairing's bit for bit */ bool bitwise_all = false; /* both requests do (the tables agree position by position) */ bool union_falls_back = false; /* the table is wider than the union's lists */ @@ -234,14 +237,24 @@ int run(const Case& c, std::mt19937& rng) { want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0; } - /* Both pairings on the same operands: the positional one (RADIANCE_MLA_PAIR=pos) and the - * union, which must never take a second pass. */ + /* Both pairings on the same operands: the positional one, on the table widened past the + * union's lists, and at the case's own width the launcher's choice, the union, which must + * never take a second pass. A tile of 16 heads has no pairing and runs once. */ const bool paired = H % 16 == 8; + const int wide = std::max(B, kUnionBlocks + 1); + std::vector bt_wide((size_t)M * wide, -1); + for (int r = 0; r < M; ++r) + std::copy(bt.begin() + (size_t)r * B, bt.begin() + (size_t)(r + 1) * B, + bt_wide.begin() + (size_t)r * wide); std::vector by_pos; int fails = 0; for (const char* pairing : { "pos", "union" }) { - if (!paired && !std::strcmp(pairing, "union")) break; - setenv("RADIANCE_MLA_PAIR", pairing, 1); + const bool by_page = !std::strcmp(pairing, "union"); + if (!paired && by_page) break; + const bool widened = paired && !by_page; + t[2] = widened ? tens(bt_wide.data(), RAD_I32, { M, wide }) + : tens(bt.data(), RAD_I32, { M, B }); + p[3].ival = widened ? wide : B; std::fill(out.begin(), out.end(), 0xffff); unsigned long long stats[3]; r4d_mla_matrix_stats(stats); @@ -249,7 +262,6 @@ int run(const Case& c, std::mt19937& rng) { const int rc = r4d_rad_mla_attn_matrix(&a, nullptr); r4d_mla_matrix_pin_form(0); r4d_mla_matrix_stats(stats); - unsetenv("RADIANCE_MLA_PAIR"); if (rc != RAD_OK) { std::printf("%-40s %-5s launch returned %d\n", c.name.c_str(), pairing, rc); ++fails; @@ -265,7 +277,6 @@ int run(const Case& c, std::mt19937& rng) { } bool ok = bad == 0; std::string note; - const bool by_page = !std::strcmp(pairing, "union"); if (!by_page) { by_pos = out; if (c.expect_second >= 0 && (stats[1] > 0) != (c.expect_second == 1)) { @@ -297,11 +308,11 @@ int run(const Case& c, std::mt19937& rng) { std::snprintf(buf, sizeof buf, " vs pos: %zu/%zu differ (r/r+1), max abs %.2e", first_diff_a, diff_b, max_ab); note += buf; - if (c.bitwise_a && first_diff_a) { + if (c.bitwise_a && !c.scratch && first_diff_a) { note += " (request r differs)"; ok = false; } - if (c.bitwise_all && diff_b) { + if (c.bitwise_all && !c.scratch && diff_b) { note += " (request r+1 differs)"; ok = false; } diff --git a/tests/r4d_emu/test_moemx.cpp b/tests/r4d_emu/test_moemx.cpp index 1ef630ce..63f461b2 100644 --- a/tests/r4d_emu/test_moemx.cpp +++ b/tests/r4d_emu/test_moemx.cpp @@ -1,30 +1,28 @@ -/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. Every form - * the RADIANCE_MXFP4_* switches reach must match the arithmetic-decode row-group form bit for bit, - * and both a host restatement of the per-element sequence: per 128 of K in order, per 32-wide group - * a fresh 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * - * E8M0 scale with two roundings and an add. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, - * dropped slots inside runs and past the routed rows, columns an odd expert does not have, a - * shorter K for odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes - * and pointer tables. The P64 forms (RADIANCE_MXFP4_PREFILL_P64) run at every BM, BN, stage and - * column-tile count, pinned below their row bound, with jobs cut at 32 and 64 rows, column - * blocks past N and the output through LDS at aligned and odd pitches. The table decode is also - * held to the arithmetic one over every code. */ +/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. The form the + * rule picks at each case (named per case, so a moved bound shows) must match a host restatement + * of the per-element sequence bit for bit: per 128 of K in order, per 32-wide group a fresh + * 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * E8M0 + * scale with two roundings and an add. Away from GLM's slices the expert-major forms (K 256 and a + * longer K) and the row groups; at GLM's TP4 down slice the GLM prefill form, at its TP8 gate_up + * slice the P64 form with streamed A. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, dropped + * slots inside runs and past the routed rows, columns an odd expert does not have, a shorter K for + * odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes and pointer + * tables. The table decode is also held to the arithmetic one over every code. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" #include "r4d_mxfp4.h" #include #include -#include #include #include -#include #include extern const char* emu_last_kernel; -/* The arithmetic decode the kernels used before the table (r4d_moe_mxfp4.hip, fp4x4 and its - * byte interleave), restated as the reference of r4d_mxfp4_unpack8_exact. */ +/* The bytewise arithmetic decode, the reference of r4d_mxfp4_unpack8_exact: per byte, magnitudes + * from 2 map to (m + 12) * 4, 0 and 1 to 0 and 48, the sign to bit 7; then the low and high + * nibbles' bytes interleave in k order. */ static uint32_t fp4x4_ref(uint32_t n) { const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u; const uint32_t mask = (flag << 5) - (flag >> 3); @@ -76,6 +74,7 @@ struct Case { bool sorted_a, tables, exceptional; std::vector runs; int tail; // dropped slots past the routed rows + const char* kernel; // the form the rule picks }; /* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative @@ -87,9 +86,6 @@ static size_t first_diff(const std::vector& a, const std::vector& a, const std::vector& b) { - return a.size() == b.size() && first_diff(a, b) == a.size(); -} static RadTensor ten(void* p, uint32_t dt, std::vector shape, std::vector stride) { @@ -104,18 +100,30 @@ static RadTensor ten(void* p, uint32_t dt, std::vector shape, return t; } +/* GLM's 288 experts: the given runs at experts spread over both classes, every other one empty. */ +static std::vector glm_runs(std::vector live) { + static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 }; + std::vector runs(288, 0); + for (size_t i = 0; i < live.size() && i < sizeof at / sizeof at[0]; ++i) runs[at[i]] = live[i]; + return runs; +} + int main() { int fails = check_decode(), cases = 1; if (fails) std::printf("FAIL table decode: %d mismatches\n", fails); const std::vector runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 }; + const char* const staged = "(moe_mxfp4_expert_staged_kernel<128, 4>)"; + const char* const expert = "(moe_mxfp4_expert_kernel<4, 256>)"; + const char* const groups = "moe_mxfp4_fp8_kernel"; const Case all[] = { - { "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6 }, + { "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6, + groups }, { "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9, - 2 }, - { "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4 }, - { "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4 }, - { "decode band, row groups of 4", + 2, groups }, + { "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4, groups }, + { "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4, groups }, + { "expert-major, K 384", 64, 384, 64, @@ -126,8 +134,9 @@ int main() { true, false, { 0, 1, 15, 16, 17, 30 }, - 3 }, - { "decode band, row groups of 1", + 3, + expert }, + { "expert-major, K 256, exceptional codes", 64, 256, 32, @@ -138,8 +147,9 @@ int main() { false, true, { 1, 0, 3, 15, 1 }, - 2 }, - { "P64 jobs at 32 and 64 rows, N under a block", + 2, + staged }, + { "expert-major, K 512:384, runs past 64 rows, N under a block", 96, 512, 96, @@ -150,8 +160,9 @@ int main() { false, false, { 32, 33, 31, 96, 128, 129, 0, 2 }, - 9 }, - { "P64 resident A, column tiles cut", + 9, + expert }, + { "expert-major, K 256:128, column tiles cut", 192, 256, 128, @@ -162,83 +173,47 @@ int main() { true, true, { 64, 63, 65, 1, 0, 127, 17 }, - 5 }, - }; - struct Form { - const char* env; - int stage, tiles, lut; - const char* kernel; - bool prefill; - bool pipe = false; - }; - /* env: DECODE_EXPERTS, ALIGNED_JOBS, PREFILL_N32, PREFILL_M32, PREFILL_N64, PREFILL_CACHE_ROWS */ - const Form forms[] = { - { "100000", 256, 1, 0, "moe_mxfp4_expert_kernel<4, 256, false>", false }, - { "100000", 256, 1, 1, "moe_mxfp4_expert_kernel<4, 256, true>", false }, - { "100000", 256, 4, 0, "moe_mxfp4_expert_staged_kernel<256, 4, false>", false }, - { "100000", 256, 4, 1, "moe_mxfp4_expert_staged_kernel<256, 4, true>", false }, - { "100000", 128, 1, 0, "moe_mxfp4_expert_staged_kernel<128, 1, false>", false }, - { "100000", 128, 1, 1, "moe_mxfp4_expert_staged_kernel<128, 1, true>", false }, - { "100000", 128, 4, 0, "moe_mxfp4_expert_staged_kernel<128, 4, false>", false }, - { "100000", 128, 4, 1, "moe_mxfp4_expert_staged_kernel<128, 4, true>", false }, - { "000000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", false }, - { "010000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", true }, - { "001000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true }, - { "011000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true }, - { "011100", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 2, false, true>", true }, - { "011110", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, false, true>", true }, - { "011111", 0, 0, 0, "moe_mxfp4_fp8_kernel<4, 2, true, false>", true }, - { "011111", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, true, true>", true }, - { "011111", 0, 0, 0, "moe_mxfp4_prefill_kernel", true, true }, - { "011111", 0, 0, 1, "moe_mxfp4_prefill_kernel", true, true }, - }; - /* P64 at every raster point, column tiles 4 (the resident form's default) and 1, and the LDS - * output at the default; the K of a case picks streamed or resident A. */ - struct P64 { - int bm, bn, sk, ct, out, db = 0; - }; - std::vector p64s; - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - for (int sk : { 128, 256 }) - for (int ct : { 1, 4 }) p64s.push_back({ bm, bn, sk, ct, 0 }); - p64s.push_back({ 64, 128, 128, 4, 1 }); - p64s.push_back({ 32, 64, 256, 1, 1 }); - /* The double buffer at every BM x BN x stage: where two stages do not fit in LDS, and with - * resident A, the single-buffer form runs. */ - for (int bm : { 32, 64 }) - for (int bn : { 64, 128 }) - for (int sk : { 128, 256 }) p64s.push_back({ bm, bn, sk, 4, 0, 1 }); - p64s.push_back({ 64, 128, 128, 4, 1, 1 }); - static const char* const kP64[] = { "RADIANCE_MXFP4_PREFILL_P64", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", - "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", - "RADIANCE_MXFP4_PREFILL_P64_BM", - "RADIANCE_MXFP4_PREFILL_P64_BN", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", - "RADIANCE_MXFP4_PREFILL_P64_COLTILES", - "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", - "RADIANCE_MXFP4_PREFILL_P64_T_BM64", - "RADIANCE_MXFP4_PREFILL_P64_T_BN128", - "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", - "RADIANCE_MXFP4_PREFILL_P64_DB" }; - /* The rule's tile with nothing pinned, by its row bounds (unset: this test's few rows are - * under all of them); the widest tiles take the LDS output. */ - struct Rule { - const char* t_bm64; - const char* t_bn128; - const char* t_down; - const char* streamed; - const char* resident; - }; - const Rule rules[] = { { nullptr, nullptr, nullptr, "<32, 64, 256, 1, false>", - "<32, 64, 128, 4, true>" }, - { "0", nullptr, nullptr, "<64, 64, 256, 1, false>", "<32, 64, 128, 4, true>" }, - { "0", "0", "0", "<64, 128, 128, 1, false>", "<64, 128, 128, 4, true>" } }; - static const char* const kEnv[] = { - "RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_ALIGNED_JOBS", - "RADIANCE_MXFP4_PREFILL_N32", "RADIANCE_MXFP4_PREFILL_M32", - "RADIANCE_MXFP4_PREFILL_N64", "RADIANCE_MXFP4_PREFILL_CACHE_ROWS" + 5, + staged }, + { "GLM TP4 down, the GLM prefill form", + 4096, + 512, + 4096, + 512, + 1, + 8, + true, + true, + true, + glm_runs({ 63, 96, 1, 130, 32, 31, 33, 64, 65 }), + 13, + "moe_mxfp4_prefill_kernel" }, + { "GLM TP8 gate_up, P64 BM32 BN64 K256", + 512, + 4096, + 512, + 4096, + 2, + 8, + false, + true, + false, + glm_runs({ 200, 33, 300, 31, 200 }), + 20, + "(moe_mxfp4_p64_kernel<32, 64, 256, 1, false>)" }, + { "GLM TP8 down, P64 BM32 BN64 K128 x4, A resident", + 4096, + 256, + 4096, + 256, + 1, + 8, + true, + true, + true, + glm_runs({ 900, 801, 779, 700, 700, 581, 600, 600, 63, 1 }), + 40, + "(moe_mxfp4_p64_kernel<32, 64, 128, 4, true>)" }, }; for (const Case& c : all) { @@ -264,21 +239,37 @@ int main() { // A dropped slot about every eleventh row, the first rows of some runs included. sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T); } + /* Stacked planes hold every expert; a pointer table names one of at most three slices a + * class, so GLM's 288 experts stay small. */ const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd }, nexp[2] = { (E + 1) / 2, E / 2 }; std::vector w[2], s[2]; std::vector wt[2], st[2]; + std::vector> wf[2]; + int slices[2]; for (int q = 0; q < 2; ++q) { - w[q].resize((size_t)nexp[q] * n[q] * k[q] / 2); - s[q].resize((size_t)nexp[q] * n[q] * k[q] / 32); + slices[q] = c.tables ? std::min(nexp[q], 3) : nexp[q]; + w[q].resize((size_t)slices[q] * n[q] * k[q] / 2); + s[q].resize((size_t)slices[q] * n[q] * k[q] / 32); for (auto& v : w[q]) v = (uint8_t)rng(); static const uint8_t special[] = { 0, 255, 1, 254, 127 }; for (size_t i = 0; i < s[q].size(); ++i) s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5] : (uint8_t)(118 + rng() % 16); for (int x = 0; x < nexp[q]; ++x) { - wt[q].push_back(w[q].data() + (size_t)x * n[q] * k[q] / 2); - st[q].push_back(s[q].data() + (size_t)x * n[q] * k[q] / 32); + wt[q].push_back(w[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 2); + st[q].push_back(s[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 32); + } + /* each slice's codes as the E4M3 values the table decode gives */ + for (int x = 0; x < slices[q]; ++x) { + std::vector f((size_t)n[q] * k[q]); + const uint8_t* src = w[q].data() + (size_t)x * n[q] * k[q] / 2; + for (size_t i = 0; i < f.size(); ++i) { + uint32_t lo, hi; + r4d_mxfp4_unpack8_exact((src[i / 2] >> (4 * (i & 1))) & 15u, &lo, &hi); + f[i] = rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu)); + } + wf[q].push_back(std::move(f)); } } auto plane = [&](int q, bool scale) { @@ -291,6 +282,8 @@ int main() { }; /* the per-element sequence, on the host */ + std::vector af(a.size()); + for (size_t i = 0; i < a.size(); ++i) af[i] = rad_fp8e4m3_to_f32(a[i]); std::vector ref((size_t)T * yp, 0x7777); for (int r = 0; r < T; ++r) for (int col = 0; col < OUT; ++col) { @@ -301,21 +294,15 @@ int main() { const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw; const bool valid = within < cw; const int wn = (col / pw) * cw + within; - const uint8_t* wr = - w[q].data() + (size_t)(e / 2) * n[q] * k[q] / 2 + (size_t)wn * k[q] / 2; - const uint8_t* sr = - s[q].data() + (size_t)(e / 2) * n[q] * k[q] / 32 + (size_t)wn * k[q] / 32; + const float* wr = wf[q][(size_t)((e / 2) % slices[q])].data() + (size_t)wn * k[q]; + const uint8_t* sr = (const uint8_t*)st[q][(size_t)(e / 2)] + (size_t)wn * k[q] / 32; + const float* arow = af.data() + (size_t)ar * ap; float total = 0.f; for (int kb = 0; kb < k[q]; kb += 128) for (int g = 0; g < 4; ++g) { float raw = 0.f; - for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk) { - const uint32_t code = valid ? (wr[kk / 2] >> (4 * (kk & 1))) & 15u : 0u; - uint32_t lo, hi; - r4d_mxfp4_unpack8_exact(code, &lo, &hi); - raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + kk]) * - rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu)); - } + for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk) + raw += arow[kk] * (valid ? wr[kk] : 0.f); const uint32_t x = valid ? sr[kb / 32 + g] : 127u; uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u; float scale; @@ -329,6 +316,12 @@ int main() { out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); // f32_to_bf16, r4d_common.h } + int live = 0; + for (uint16_t v : ref) live += v != 0 && v != 0x7777; + if (live < T * OUT / 3) { + std::printf("FAIL %s: output mostly zero\n", c.name); + ++fails; + } RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }), ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }), @@ -365,118 +358,25 @@ int main() { p[8] = pi("group", 128); p[9] = ps("a_order", c.sorted_a ? "sorted" : "token"); p[10] = ps("dtype", "mxfp4a8"); - auto run = [&](const Form& f, std::vector& y) { - y.assign((size_t)T * yp, 0x7777); - t[8] = ten(y.data(), RAD_BF16, { T, OUT }, { yp, 1 }); - for (int i = 0; i < 6; ++i) setenv(kEnv[i], f.env[i] == '1' ? "1" : "0", 1); - if (f.stage) { - setenv("RADIANCE_MXFP4_EXPERTS_STAGE_K", std::to_string(f.stage).c_str(), 1); - setenv("RADIANCE_MXFP4_EXPERTS_COLTILES", std::to_string(f.tiles).c_str(), 1); - } - setenv("RADIANCE_MXFP4_LUT", f.lut ? "1" : "0", 1); - setenv("RADIANCE_MXFP4_PREFILL_PIPE", f.pipe ? "1" : "0", 1); - RadArgs ar{}; - ar.t = t; - ar.n_t = 9; - ar.p = p; - ar.n_p = 11; - emu_last_kernel = ""; - return r4d_rad_moe_mxfp4(&ar, nullptr); - }; - auto run_p64 = [&](const P64& f, std::vector& y) { - const int v[8] = { 1, 0, 0, f.bm, f.bn, f.sk, f.ct, f.out }; - for (int i = 0; i < 8; ++i) setenv(kP64[i], std::to_string(v[i]).c_str(), 1); - setenv(kP64[11], f.db ? "1" : "0", 1); - const Form base = { "000000", 0, 0, 1, "", false }; - const int rc = run(base, y); - setenv(kP64[0], "0", 1); - return rc; - }; - const Form alt = { "000000", 0, 0, 0, "moe_mxfp4_fp8_kernel<1, 1, false, false>", false }; - std::vector legacy, got; + std::vector got((size_t)T * yp, 0x7777); + t[8] = ten(got.data(), RAD_BF16, { T, OUT }, { yp, 1 }); + RadArgs ar{}; + ar.t = t; + ar.n_t = 9; + ar.p = p; + ar.n_p = 11; + emu_last_kernel = ""; ++cases; - int rc = run(alt, legacy); - if (rc != RAD_OK || !std::strstr(emu_last_kernel, alt.kernel)) { - std::printf("FAIL %s: reference form rc %d kernel %s\n", c.name, rc, emu_last_kernel); + const int rc = r4d_rad_moe_mxfp4(&ar, nullptr); + const size_t i = first_diff(got, ref); + if (rc != RAD_OK || std::strcmp(emu_last_kernel, c.kernel) || i != got.size()) { + std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu (row %zu col %zu: " + "%04x, want %04x)\n", + c.name, T, emu_last_kernel, c.kernel, rc, i, i / yp, i % yp, + i < got.size() ? got[i] : 0, i < ref.size() ? ref[i] : 0); ++fails; - continue; - } - if (!same16(legacy, ref)) { - const size_t i = first_diff(legacy, ref); - std::printf("FAIL %s: reference form against the host sequence at row %zu col %zu: " - "%04x, want %04x\n", - c.name, i / yp, i % yp, legacy[i], ref[i]); - ++fails; - } - int live = 0; - for (uint16_t v : ref) live += v != 0 && v != 0x7777; - if (live < T * OUT / 3) { - std::printf("FAIL %s: output mostly zero\n", c.name); - ++fails; - } - for (const Form& f : forms) { - if (f.prefill && T < 512) continue; - ++cases; - rc = run(f, got); - const bool reached = std::strstr(emu_last_kernel, f.kernel) != nullptr; - if (rc != RAD_OK || !reached || !same16(got, legacy)) { - const size_t i = first_diff(got, legacy); - std::printf( - "FAIL %s: form %s stage %d tiles %d lut %d ran %s (want %s), rc %d, first " - "word %zu\n", - c.name, f.env, f.stage, f.tiles, f.lut, emu_last_kernel, f.kernel, rc, i); - ++fails; - } - } - const bool resident = NK <= 256; - for (const Rule& u : rules) { - ++cases; - for (const char* v : kP64) unsetenv(v); - setenv(kP64[0], "1", 1); - setenv(kP64[1], "0", 1); - setenv(kP64[2], "0", 1); - if (u.t_bm64) setenv(kP64[8], u.t_bm64, 1); - if (u.t_bn128) setenv(kP64[9], u.t_bn128, 1); - if (u.t_down) setenv(kP64[10], u.t_down, 1); - const Form base = { "000000", 0, 0, 1, "", false }; - rc = run(base, got); - for (const char* v : kP64) unsetenv(v); - const std::string want = - std::string("moe_mxfp4_p64_kernel") + (resident ? u.resident : u.streamed); - if (rc != RAD_OK || !std::strstr(emu_last_kernel, want.c_str()) || - !same16(got, legacy)) { - std::printf("FAIL %s: P64 rule ran %s (want %s), rc %d, first word %zu\n", c.name, - emu_last_kernel, want.c_str(), rc, first_diff(got, legacy)); - ++fails; - } - } - for (const P64& f : p64s) { - ++cases; - rc = run_p64(f, got); - const bool db = f.db && !resident && (f.sk == 128 || (f.bm == 32 && f.bn == 64)); - const std::string want = "moe_mxfp4_p64_kernel<" + std::to_string(f.bm) + ", " + - std::to_string(f.bn) + ", " + std::to_string(f.sk) + ", " + - (resident ? std::to_string(f.ct) : "1") + ", " + - (resident ? "true" : "false") + (db ? ", true>" : ">"); - const bool reached = std::strstr(emu_last_kernel, want.c_str()) != nullptr; - if (rc != RAD_OK || !reached || !same16(got, legacy)) { - const size_t i = first_diff(got, legacy); - std::printf("FAIL %s: P64 bm %d bn %d stage %d tiles %d out %d db %d ran %s (want " - "%s), rc %d, " - "first word %zu (row %zu col %zu: %04x, want %04x)\n", - c.name, f.bm, f.bn, f.sk, f.ct, f.out, f.db, emu_last_kernel, - want.c_str(), rc, i, i / yp, i % yp, i < got.size() ? got[i] : 0, - i < legacy.size() ? legacy[i] : 0); - ++fails; - } } } - for (const char* v : kEnv) unsetenv(v); - for (const char* v : kP64) unsetenv(v); - unsetenv("RADIANCE_MXFP4_EXPERTS_STAGE_K"); - unsetenv("RADIANCE_MXFP4_EXPERTS_COLTILES"); - unsetenv("RADIANCE_MXFP4_LUT"); - unsetenv("RADIANCE_MXFP4_PREFILL_PIPE"); std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; } diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 03e63ce7..052f5835 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -966,7 +966,7 @@ TEST(op_vocabulary) { * denoiser, and the index helpers that feed them. */ "conv1d", "conv_t1d", "snake", "cfg_topk_sample", "rvq_embed", "frame_mix_store", "end_status", "resample_nearest", "fourier_embed", "win_input", "win_prep", "win_finish", - "chan_split", "interleave2", "iota", "cu_repeat", "frame_store", + "chan_split", "interleave2", "iota", "cu_repeat", "int_affine", "frame_store", /* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its * decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free * activation. */ @@ -979,6 +979,20 @@ TEST(op_vocabulary) { * the fold back into patch rows and the re-noising. */ "conv3d_ndhwc", "group_norm", "tconv_dw", "resize_bilinear", "patch_fold", "flow_renoise", + /* The joint image generators' (Krea 2, FLUX.3): attention over separate key bounds, a + * per-layer table added to every row, a learned mix of consecutive rows, and the VAE's + * channel statistics. */ + "attn_cross", "table_add", "mix_rows", "chan_stats", + /* LTX-2's: its rotary over fractional coordinates, the per-head gate and the guided + * sampler step. */ + "rope_split", "head_gate", "ltx_guide", + /* Its VAE's norm, resampling and patches; its vocoder's spectrogram and resampler. */ + "pixel_norm", "d2s3d", "s2d3d", "pix_patch", "patch_pix8", "stft_logmel", "bwe_up", + /* Its VAE decoded in tiles: the boxes, a tile's latent, the blended stitch. */ + "tile_grid", "tile_crop", "tile_stitch", + /* LTX-2.5's diffusion decoder: its rotary's voxel coordinates and its neighborhood + * attention. */ + "vol_index", "attn_na3d", }; for (const char* op : kOps) { if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op); @@ -7063,6 +7077,188 @@ TEST(scale_rows_gates_each_row_by_its_scalar) { CHECK_EQ(y2.at(2), 36.0f); CHECK_EQ(y2.at(3), 48.0f); } +/* tile_grid: diffusers' tiled_decode boxes -- a tile every `stride` latents while it starts inside + * the axis, `tile` long or to the edge -- one row (t, h, w, t0, y0, x0, k, count) a tile, rows past + * the count zero. 29 rows at stride 14 are bands of 16, 15 and 1; 16 columns are bands of 16 and + * 2. Under `intervals` (the diffusion decoder's _tile_intervals) an axis of `tile` cells or fewer + * is one band and a last band shorter than `min` joins the one before: 61 frames at 40 / 28 are + * [0, 40) and [28, 61); 68 rows at 96 / 88 one band; 100 columns at 96 / 88, min 13, one band + * of 96 and then [88, 100) is 12 < 13, merged: [0, 100). The last time band carries `tail` more. */ +TEST(tile_grid_cuts_where_tiled_decode_does) { + T g(RAD_I32, {3}); g.n({3, 29, 16}); + T y(RAD_I32, {7, 8}); + A a; a.t(g).t(y).i("M", 7).i("tile", 16).i("stride", 14); + CHECK_OK(run("tile_grid", a)); + const int32_t want[7][8] = { { 3, 16, 16, 0, 0, 0, 0, 6 }, { 3, 16, 2, 0, 0, 14, 1, 6 }, + { 3, 15, 16, 0, 14, 0, 2, 6 }, { 3, 15, 2, 0, 14, 14, 3, 6 }, + { 3, 1, 16, 0, 28, 0, 4, 6 }, { 3, 1, 2, 0, 28, 14, 5, 6 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }; + for (int k = 0; k < 7; ++k) + for (int e = 0; e < 8; ++e) CHECK_EQ(y.iat(k * 8 + e), want[k][e]); + T g2(RAD_I32, {3}); g2.n({61, 68, 100}); + T y2(RAD_I32, {3, 8}); + A b; b.t(g2).t(y2).i("M", 3).i("tile", 96).i("stride", 88).s("rule", "intervals").i("min", 13) + .i("tile_t", 40).i("stride_t", 28).i("min_t", 6).i("tail", 8); + CHECK_OK(run("tile_grid", b)); + const int32_t want2[3][8] = { { 40, 68, 100, 0, 0, 0, 0, 2 }, { 41, 68, 100, 28, 0, 0, 1, 2 }, + { 0, 0, 0, 0, 0, 0, 0, 0 } }; + for (int k = 0; k < 3; ++k) + for (int e = 0; e < 8; ++e) CHECK_EQ(y2.iat(k * 8 + e), want2[k][e]); +} + +/* attn_na3d is attention over each query's window: on a 2 x 4 x 5 volume with a 3 x 3 x 3 window + * (2 in time, the axis's length), the window of the corner voxel (0, 0, 0) is shifted inward to + * start at (0, 0, 0), and of (1, 3, 4) to start at (0, 1, 2); against attention over exactly those + * keys. */ +TEST(attn_na3d_attends_the_inward_shifted_window) { + const int64_t Tn = 2, Hn = 4, Wn = 5, V = Tn * Hn * Wn, hd = 4; + auto val = [](int64_t i) { return (float)((i * 29) % 23 - 11) / 8.0f; }; + std::vector qv((size_t)(V * hd)), kv((size_t)(V * hd)), vv((size_t)(V * hd)); + for (int64_t i = 0; i < V * hd; ++i) { qv[(size_t)i] = val(i); kv[(size_t)i] = val(i + 7); vv[(size_t)i] = val(i + 13); } + T q(RAD_F32, {V, hd}); q.f(qv); + T k(RAD_F32, {V, hd}); k.f(kv); + T v(RAD_F32, {V, hd}); v.f(vv); + T g(RAD_I32, {3}); g.n({Tn, Hn, Wn}); + T o(RAD_F32, {V, hd}); + A a; a.t(q).t(k).t(v).t(g).t(o).i("M", V).i("head_dim", hd).i("kt", 3).i("kh", 3).i("kw", 3) + .s("dtype", "f32"); + CHECK_OK(run("attn_na3d", a)); + struct Q { int64_t t, i, j, t0, i0, j0; }; + for (const Q c : { Q{ 0, 0, 0, 0, 0, 0 }, Q{ 1, 3, 4, 0, 1, 2 }, Q{ 0, 2, 2, 0, 1, 1 } }) { + const int64_t r = (c.t * Hn + c.i) * Wn + c.j; + std::vector sc; + std::vector keys; + for (int64_t a1 = c.t0; a1 < c.t0 + 2; ++a1) + for (int64_t b1 = c.i0; b1 < c.i0 + 3; ++b1) + for (int64_t c1 = c.j0; c1 < c.j0 + 3; ++c1) { + const int64_t key = (a1 * Hn + b1) * Wn + c1; + double d = 0; + for (int64_t e = 0; e < hd; ++e) d += (double)qv[(size_t)(r * hd + e)] * kv[(size_t)(key * hd + e)]; + sc.push_back(d / 2.0); + keys.push_back(key); + } + double mx = -1e30, sum = 0; + for (double x : sc) mx = std::max(mx, x); + for (double& x : sc) { x = std::exp(x - mx); sum += x; } + for (int64_t e = 0; e < hd; ++e) { + double want = 0; + for (size_t n = 0; n < keys.size(); ++n) want += sc[n] / sum * vv[(size_t)(keys[n] * hd + e)]; + CHECK_NEAR(o.at(r * hd + e), want, 1e-5); + } + } +} + +/* vol_index: a 2 x 2 x 3 volume's coordinates, component-major; voxel 7 is (1, 0, 1). */ +TEST(vol_index_writes_each_voxels_coordinates) { + T g(RAD_I32, {3}); g.n({2, 2, 3}); + T y(RAD_I32, {3, 12}); + A a; a.t(g).t(y).i("M", 12); + CHECK_OK(run("vol_index", a)); + CHECK_EQ(y.iat(7), 1); CHECK_EQ(y.iat(12 + 7), 0); CHECK_EQ(y.iat(24 + 7), 1); + CHECK_EQ(y.iat(11), 1); CHECK_EQ(y.iat(12 + 11), 1); CHECK_EQ(y.iat(24 + 11), 2); +} + +/* tile_crop copies a box out of the volume: a 2 x 3 x 4 volume of its row indices, the 1 x 2 x 2 + * box at (1, 1, 1). */ +TEST(tile_crop_copies_the_box) { + T x(RAD_F32, {24, 1}); + std::vector v(24); + for (int i = 0; i < 24; ++i) v[(size_t)i] = (float)i; + x.f(v); + T g(RAD_I32, {3}); g.n({2, 3, 4}); + T b(RAD_I32, {6}); b.n({1, 2, 2, 1, 1, 1}); + T y(RAD_F32, {4, 1}); + A a; a.t(x).t(g).t(b).t(y).i("M", 4).i("C", 1).s("dtype", "f32"); + CHECK_OK(run("tile_crop", a)); + CHECK_EQ(y.at(0), 17.0f); CHECK_EQ(y.at(1), 18.0f); + CHECK_EQ(y.at(2), 21.0f); CHECK_EQ(y.at(3), 22.0f); +} + +/* tile_stitch: tiles cut from one picture stitch back to that picture's bytes (every blend mixes + * equal values; with an extent of 2 the weights are 0, 0.5 and 1, so exactly); and across a seam + * between a tile of zeros and one of ones, the first column of the right tile is the left tile's + * margin and the second their mean. A 5 x 5 latent grid at tile 4, stride 3, a latent 1 x 1 patch + * of 2 x 2 pixels: bands of 4 and 2 latents, 8 and 4 pixels, kept to 6. */ +TEST(tile_stitch_blends_as_tiled_decode_and_keeps_a_cut_picture) { + const int64_t H = 5, W = 5, tile = 4, stride = 3, p = 2, Hp = H * p, Wp = W * p; + auto band = [&](int64_t L, int64_t k) { return std::min(tile, L - k * stride); }; + auto band_of = [](int64_t L, int64_t k, int64_t t, int64_t s) { return std::min(t, L - k * s); }; + std::vector img((size_t)(Hp * Wp)); + for (int64_t i = 0; i < Hp * Wp; ++i) img[(size_t)i] = (float)((i * 37) % 63 - 31) / 32.0f; + auto store = [&](auto value) { + std::vector v; + for (int64_t i = 0; i < 2; ++i) + for (int64_t j = 0; j < 2; ++j) + for (int64_t py = 0; py < band(H, i); ++py) /* patch rows of the tile */ + for (int64_t px = 0; px < band(W, j); ++px) + for (int64_t dx = 0; dx < p; ++dx) /* order wh: column offset outer */ + for (int64_t dy = 0; dy < p; ++dy) + v.push_back(value(i, j, py * p + dy, px * p + dx)); + return v; + }; + auto run_stitch = [&](const std::vector& tiles, std::vector* out) { + T x(RAD_F32, {(int64_t)tiles.size() / (p * p), p * p}); x.f(tiles); + T g(RAD_I32, {3}); g.n({1, H, W}); + T f(RAD_I32, {1}); f.n({0}); + T y(RAD_U8, {Hp, Wp}); + A a; a.t(x).t(g).t(f).t(y).i("M", Hp).i("tile", tile).i("stride", stride).i("scale", 1) + .i("p", p).i("C", 1).s("dtype", "f32"); + CHECK_OK(run("tile_stitch", a)); + out->resize((size_t)(Hp * Wp)); + for (int64_t i = 0; i < Hp * Wp; ++i) (*out)[(size_t)i] = y.mem[(size_t)i]; + }; + std::vector got; + run_stitch(store([&](int64_t i, int64_t j, int64_t yy, int64_t xx) { + return img[(size_t)((i * stride * p + yy) * Wp + j * stride * p + xx)]; + }), &got); + for (int64_t i = 0; i < Hp * Wp; ++i) { + const float u = std::min(std::max(img[(size_t)i] / 2.0f + 0.5f, 0.0f), 1.0f); + CHECK_EQ((int)got[(size_t)i], (int)std::nearbyint(u * 255.0f)); + } + /* Left tiles zeros, right tiles ones: row 0 is 0 to column 6, the margin (0) at 6, the mean at + * 7, then 1 (bytes 128, 128, 191, 255). */ + run_stitch(store([](int64_t, int64_t j, int64_t, int64_t) { return j ? 1.0f : 0.0f; }), &got); + CHECK_EQ((int)got[5], 128); CHECK_EQ((int)got[6], 128); + CHECK_EQ((int)got[7], 191); CHECK_EQ((int)got[8], 255); + + /* In time too: 4 cells of 2 frames, the first one frame (7 frames), cut at tile_t 3, stride_t 2 + * into cells [0, 3) (frames 0..4) and [2, 4) (frames 3..6); each tile is its box of a 7-frame + * clip, and every frame stitches back to the clip's bytes. */ + const int64_t nfr = 7; + std::vector clip((size_t)(nfr * Hp * Wp)); + for (int64_t i = 0; i < (int64_t)clip.size(); ++i) clip[(size_t)i] = (float)((i * 53) % 61 - 30) / 32.0f; + std::vector tiles3; + for (int64_t kt = 0; kt < 2; ++kt) { + const int64_t P = kt == 0 ? 0 : 3, F = kt == 0 ? 5 : 4; + for (int64_t i = 0; i < 2; ++i) + for (int64_t j = 0; j < 2; ++j) + for (int64_t f = 0; f < F; ++f) + for (int64_t py = 0; py < band_of(H, i, tile, stride); ++py) + for (int64_t px = 0; px < band_of(W, j, tile, stride); ++px) + for (int64_t dx = 0; dx < p; ++dx) + for (int64_t dy = 0; dy < p; ++dy) + tiles3.push_back(clip[(size_t)(((P + f) * Hp + i * stride * p + + py * p + dy) * Wp + + j * stride * p + px * p + dx)]); + } + { + T x(RAD_F32, {(int64_t)tiles3.size() / (p * p), p * p}); x.f(tiles3); + T g(RAD_I32, {3}); g.n({4, H, W}); + T f(RAD_I32, {1}); f.n({0}); + T y(RAD_U8, {nfr * Hp, Wp}); + A a; a.t(x).t(g).t(f).t(y).i("M", nfr * Hp).i("tile", tile).i("stride", stride) + .i("tile_t", 3).i("stride_t", 2).i("scale", 1).i("scale_t", 2).i("p", p).i("C", 1) + .s("dtype", "f32"); + CHECK_OK(run("tile_stitch", a)); + int64_t bad = 0; + for (int64_t i = 0; i < nfr * Hp * Wp; ++i) { + const float u = std::min(std::max(clip[(size_t)i] / 2.0f + 0.5f, 0.0f), 1.0f); + bad += (int)y.mem[(size_t)i] != (int)std::nearbyint(u * 255.0f); + } + CHECK_EQ(bad, (int64_t)0); + } +} + TEST(sigmoid_is_the_logistic_function) { T x(RAD_F32, {1, 4}); x.f({0, 100, -100, 1}); T y(RAD_F32, {1, 4}); @@ -7749,6 +7945,7 @@ std::vector geometries() { G("interleave2", "M", 4, a.i("M", R).s("dtype", "f32")), G("iota", "M", 4, a.i("M", R).i("start", 0).i("step", 1)), G("cu_repeat", "M", 3, a.i("M", R).i("mult", 2)), + G("int_affine", "M", 3, a.i("M", R).s("src", "0 -1 2").s("mul", "2 0 4").s("add", "-1 5 -3")), G("frame_store", "M", 2, a.i("M", R).i("n_codes", 4).i("stride", 6).i("rep", 2) .i("skip", 0)), G("rms_mod", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).i("gated", 1).s("dtype", "bf16")), @@ -7784,6 +7981,35 @@ std::vector geometries() { G("patch_fold", "M", 8, a.i("M", R).i("C", 3).i("pt", 1).i("ph", 2).i("pw", 2) .s("mul", "1 2 3").s("add", "0 1 2").s("dtype", "f32")), G("flow_renoise", "M", 3, a.i("M", R).i("n", 8).i("stream", 1).s("dtype", "f32")), + G("attn_cross", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 0) + .s("dtype", "f32").i("n_head", 2)), + G("table_add", "M", 3, a.i("M", R).i("n", 8).i("L", 3).s("dtype", "f32")), + G("mix_rows", "M", 3, a.i("M", R).i("n", 8).i("k", 4).s("dtype", "f32")), + G("chan_stats", "M", 3, a.i("M", R).i("n", 8).s("mode", "norm").s("dtype", "f32")), + G("rope_split", "M", 3, a.i("M", R).i("n_head", 2).i("head_dim", 8).i("dim", 16) + .i("n_dims", 3).d("theta", 10000.0).s("max", "20 2048 2048") + .s("dtype", "f32")), + G("head_gate", "M", 3, a.i("M", R).i("n_head", 2).i("head_dim", 8).s("dtype", "f32")), + G("ltx_guide", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), + G("pixel_norm", "M", 4, a.i("M", R).i("n", 8).d("eps", 1e-6).s("form", "rsqrt") + .i("ileave", 2).d("mult", 2.5).s("dtype", "f32")), + /* M 7 is a cube of side 1 and 14 one of side 2, so the zero-row call sees the volume + * change. */ + G("d2s3d", "M", 7, a.i("M", R).i("C", 3).i("st", 2).i("sh", 2).i("sw", 2).s("dtype", "f32")), + G("s2d3d", "M", 7, a.i("M", R).i("C", 6).i("st", 1).i("sh", 1).i("sw", 1) + .i("group", 2).s("mode", "mean").s("dtype", "f32")), + G("pix_patch", "M", 4, a.i("M", R).i("p", 2).i("C", 3).s("dtype", "f32")), + G("patch_pix8", "M", 4, a.i("M", R).i("p", 2).i("C", 3).s("dtype", "f32")), + G("stft_logmel", "M", 3, a.i("M", R).i("hop", 4).i("nfft", 8).i("n_mel", 3).i("ch", 2) + .s("dtype", "f32")), + G("bwe_up", "M", 6, a.i("M", R).i("ratio", 3).i("ch", 2).s("dtype", "f32")), + G("tile_grid", "M", 4, a.i("M", R).i("tile", 4).i("stride", 3)), + G("vol_index", "M", 7, a.i("M", R)), + G("attn_na3d", "M", 7, a.i("M", R).i("head_dim", 8).i("kt", 3).i("kh", 3).i("kw", 3) + .s("dtype", "f32")), + G("tile_crop", "M", 7, a.i("M", R).i("C", 3).s("dtype", "f32")), + G("tile_stitch", "M", 100, a.i("M", R).i("tile", 4).i("stride", 3).i("scale", 2).i("p", 2) + .i("C", 3).s("dtype", "f32")), }; } #undef G diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index b90bf499..da6fbd01 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -229,7 +229,7 @@ struct Fixture { return (rad_op)(P.ops.size() - 1); } - int start(rad::ResidencyTable* res = nullptr, bool profile = false) { + int start(rad::ResidencyTable* res = nullptr, bool profile = false, bool record = false) { CtxDesc d; d.program = &P; d.rank = 1; @@ -241,8 +241,8 @@ struct Fixture { d.registry = registry; /* The arch bodies here issue whatever a case asks, which the batch does not describe, so * no pass may be recorded and replayed under the batch's key (a card records passes; the - * host backend cannot). */ - d.record_passes = false; + * host backend cannot). A case about the recording decision itself asks for it. */ + d.record_passes = record; return ctx.init(d); } @@ -1869,6 +1869,25 @@ TEST(a_lane_built_mid_step_starts_behind_lane_zero) { CHECK_EQ(dev_get(f, f.ctx.buf_ptr(y)), 4242); } +/* A calibration tap's gram_accum sums across passes while its plugin counts the summed rows in + * step; a played pass reissues the sum without calling step (#122). A program holding one records + * no passes; one without records them wherever the backend can. */ +TEST(a_program_with_a_calibration_tap_records_no_passes) { + { + Fixture f; + f.add_buffer("x", RAD_BF16, 64, 4, 0); + loose_op(f); + CHECK_OK(f.start(nullptr, false, /*record=*/true)); + CHECK_EQ(f.ctx.records_passes(), rad::tape_supported()); + } + Fixture f; + f.add_buffer("x", RAD_BF16, 64, 4, 0); + loose_op(f); + loose_op(f, "gram_accum"); + CHECK_OK(f.start(nullptr, false, /*record=*/true)); + CHECK(!f.ctx.records_passes()); +} + /* ================================================================== the pass key */ /* A recorded pass is replayed while its key holds, so the key must change with every batch field * and runtime state a pass's shape or arguments read, and must not change with the step number diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index fe015b94..4fd32561 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -1746,6 +1746,23 @@ static Interleaved interleave_run(int64_t n, bool decoder, int steps) { return out; } +/* Between a commit and the next step (where an encoder pass is prepared) the committed step's + * plan names a request the scheduler may already have released: a client cancelled it and the + * server reaped it. prefill_continues() reads only an open step's plan (#127). */ +TEST(prefill_continues_reads_no_committed_plan) { + Fixture f; + f.build(); + CHECK_OK(f.start()); + f.sch.set_stage_rows(64); + const uint64_t p = f.submit(2000, 4); + CHECK(f.sch.step() != nullptr); + CHECK(f.sch.prefill_continues()); + f.commit_plain(12); + CHECK_OK(f.sch.cancel(p)); + CHECK_OK(f.sch.reap(p)); + CHECK(!f.sch.prefill_continues()); +} + TEST(interleave_off_puts_a_chunk_in_every_step) { const Interleaved r = interleave_run(0, /*decoder=*/true, 8); CHECK_EQ(r.shape, std::string("CCCCCCCC")); @@ -2717,9 +2734,9 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) { f.build(/*blocks=*/4096, /*states=*/64); CHECK_OK(f.start()); - /* A prefill step samples nothing. Budget 128 tokens: this test walks 1 prefill + - * (kWindow-1) + 1 + kWindow = 65 steps, so 64 would run dry one step short. */ - uint64_t a = f.submit(160, 128, /*priority=*/0, /*ignore_eos=*/true); + /* A prefill step samples nothing. Budget 320 tokens: this test walks 1 prefill + one window, + * at most six windows until the floor is set and one more, 257 steps. */ + uint64_t a = f.submit(160, 320, /*priority=*/0, /*ignore_eos=*/true); REQUIRE(f.sch.step() != nullptr); f.commit_plain(11); f.sch.step_finished(); @@ -2745,9 +2762,11 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) { f.sch.step_finished(); CHECK_EQ(f.sch.metrics().step_ns_decode_best, (int64_t)0); - /* The SECOND window is the first gated one and sets the floor: positive, and no larger than - * the cumulative decode time it was drawn from. */ - for (int i = 0; i < rad::DecodeFloor::kWindow; ++i) { + /* The first gated window sets the floor: positive, and no larger than the cumulative decode + * time it was drawn from. The fixture's steps take microseconds and vary widely, so the gate + * may reject some and the window take more than kWindow steps to fill. */ + for (int i = 0; i < 6 * rad::DecodeFloor::kWindow && !f.sch.metrics().step_ns_decode_best; + ++i) { REQUIRE(f.sch.step() != nullptr); f.commit_plain(14); f.sch.step_finished(); @@ -2769,27 +2788,23 @@ TEST(the_decode_floor_records_only_single_sequence_decode_steps) { } TEST(the_decode_floor_ignores_a_decode_step_issued_behind_a_prefill) { - /* The live defect was a raw min latching the first decode step, which is issued ahead behind - * the prefill's host-side staging and whose bracket holds no GPU work. The fix does NOT - * exclude that step -- it is a real single-sequence decode step and belongs in the floor. It - * is made harmless by averaging: the floor is a min over window means, so the one degenerate - * bracket is diluted by the honest steps sharing its window. This pins that the - * prefill-following decode step IS eligible: a full window of decode steps that BEGINS with it - * produces a floor. Under the old predecessor-phase gate the first step was dropped, so a - * window of exactly kWindow decode steps fed only kWindow-1 samples and left the floor unset - * -- this test would have failed on that design. */ + /* The decode step issued behind the prefill's host-side staging is a real single-sequence + * decode step: it is eligible, and the window mean dilutes its short bracket. Decode steps + * that begin with it produce a floor. The fixture's steps take microseconds and vary widely, + * so the gate may reject some and a window take more than kWindow steps to fill. */ Fixture f; f.build(/*blocks=*/4096, /*states=*/64); CHECK_OK(f.start()); - uint64_t a = f.submit(160, 128, /*priority=*/0, /*ignore_eos=*/true); + uint64_t a = f.submit(160, 256, /*priority=*/0, /*ignore_eos=*/true); REQUIRE(f.sch.step() != nullptr); /* prefill */ f.commit_plain(21); f.sch.step_finished(); - /* Two windows: window 1 (holding the prefill-following step) is the un-gated warmup, so the - * floor only appears once a second, gated window completes. */ - for (int i = 0; i < 2 * rad::DecodeFloor::kWindow; ++i) { + /* Window 1 (holding the prefill-following step) is the un-gated warmup, so the floor only + * appears once a gated window completes. */ + for (int i = 0; i < 6 * rad::DecodeFloor::kWindow && !f.sch.metrics().step_ns_decode_best; + ++i) { REQUIRE(f.sch.step() != nullptr); CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE); CHECK_EQ(f.sch.plan().n_seq_decode, 1); diff --git a/tests/server_fakes.h b/tests/server_fakes.h index 7bcb18fd..51f183d0 100644 --- a/tests/server_fakes.h +++ b/tests/server_fakes.h @@ -144,6 +144,8 @@ struct FakeChatTemplate : IChatTemplate { if (!tools.empty()) s += "[tools:" + std::to_string(tools.size()) + "]"; if (!opt.enable_thinking) s += "[nothink]"; for (const auto& kv : opt.template_kwargs) s += "[" + kv.first + "=" + kv.second + "]"; + if (!default_effort.empty() && !opt.template_kwargs.count("reasoning_effort")) + s += "[reasoning_effort=" + default_effort + "]"; size_t n_msg = 0; int tool_msgs = 0; for (const auto& m : messages) { @@ -203,6 +205,8 @@ struct FakeChatTemplate : IChatTemplate { std::string refusal; std::string refuse_kwarg; std::vector efforts; /* JSON text, as the template context carries them */ + /* The effort a render naming none is written as, as Qwen3.8's template writes xhigh. */ + std::string default_effort; /* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */ std::string think_open, think_close; bool think_starts_open = false; diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 368f4c9e..c8862fa9 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -946,6 +946,14 @@ TEST(an_effort_the_template_refuses_is_answered_with_the_set_it_takes) { CHECK_EQ(set[0], std::string("low")); CHECK_EQ(set[1], std::string("medium")); CHECK_EQ(set[2], std::string("xhigh")); + CHECK(f.srv->template_default_effort().empty()); /* no level renders as no level */ + /* A template that writes one level when a request names none, as Qwen3.8's writes xhigh + * (#113): the probe names it. */ + f.tmpl.default_effort = "\"xhigh\""; + f.srv->probe_reasoning_efforts(); + CHECK_EQ(f.srv->template_default_effort(), std::string("xhigh")); + f.tmpl.default_effort.clear(); + f.srv->probe_reasoning_efforts(); OaiLimits lim = f.limits(); lim.reasoning_efforts = set; @@ -4016,6 +4024,56 @@ TEST(a_responses_request_becomes_the_chat_request_it_means) { &echo, &e) < 0); } +/* A namespace groups function tools (Codex sends every MCP server's tools that way). They reach + * the model flattened to __, the reply's function_call item reports the two apart, + * streamed and not, and the next turn's call and tool_choice come back joined (#119). */ +TEST(a_namespaces_tools_are_offered_flat_and_answered_apart) { + OaiLimits lim; + std::string chat, echo; + ApiError e; + std::map> ns; + CHECK_OK(responses_to_chat(R"({ + "tools":[{"type":"function","name":"plain","parameters":{"type":"object"}}, + {"type":"namespace","name":"crm","description":"d","tools":[ + {"type":"function","name":"find","parameters":{"type":"object"}}, + {"type":"custom","name":"raw"}]}], + "tool_choice":{"type":"function","namespace":"crm","name":"find"}, + "input":[{"role":"user","content":"x"}, + {"type":"function_call","call_id":"c1","namespace":"crm","name":"find","arguments":"{}"}, + {"type":"function_call_output","call_id":"c1","output":"y"}]})", + lim, &chat, &echo, &e, &ns)); + const json c = json::parse(chat); + CHECK_EQ(c["tools"].size(), (size_t)2); /* the custom tool left out */ + CHECK_EQ(c["tools"][1]["function"].value("name", ""), std::string("crm__find")); + CHECK_EQ(c["messages"][1]["tool_calls"][0]["function"].value("name", ""), std::string("crm__find")); + CHECK_EQ(c["tool_choice"]["function"].value("name", ""), std::string("crm__find")); + CHECK_EQ(ns.size(), (size_t)1); + CHECK_EQ(ns["crm__find"].first, std::string("crm")); + CHECK_EQ(json::parse(echo)["tools"].size(), (size_t)2); /* echoed as sent */ + + /* A flattened name may not shadow a top-level tool's. */ + CHECK(responses_to_chat(R"({"input":"x","tools":[{"type":"function","name":"crm__find"}, + {"type":"namespace","name":"crm","tools":[{"type":"function","name":"find"}]}]})", + lim, &chat, &echo, &e, &ns) < 0); + + Fixture f; + f.sched.reply = R"(TOOL:crm__find:{"q":"P"})"; + const std::string tools = R"("tools":[{"type":"namespace","name":"crm","tools":[)" + R"({"type":"function","name":"find","parameters":{"type":"object"}}]}],)"; + HttpResponse r = f.post("/v1/responses", "{" + tools + R"("input":"find P"})"); + CHECK_EQ(r.status, 200); + const json o = json::parse(r.body); + CHECK_EQ(o["output"][0].value("type", ""), std::string("function_call")); + CHECK_EQ(o["output"][0].value("namespace", ""), std::string("crm")); + CHECK_EQ(o["output"][0].value("name", ""), std::string("find")); + f.sched.join_all(); + HttpResponse st = f.post("/v1/responses", "{" + tools + R"("stream":true,"input":"find P"})"); + const std::string body = drain(st); + CHECK(has(body, R"("namespace":"crm")")); + CHECK(!has(body, "crm__find")); + f.sched.join_all(); +} + TEST(the_responses_api_answers_with_a_response_object_and_its_events) { Fixture f; HttpResponse r = f.post("/v1/responses", R"({"model":"m","input":"hi"})"); diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index 10bc8aa2..78a8a144 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -88,12 +88,13 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second); } const std::set> want = { - { "breeze", "" }, { "embeddinggemma2", "" }, { "gemma3", "" }, { "gemma4", "" }, + { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, { "flux3distilled", "" }, + { "gemma3", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, - { "qwen3asr", "" }, - { "minimaxh3", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; + { "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" }, + { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; std::set> got; for (const auto& [k, name] : keys) got.insert(k); if (got != want) diff --git a/tests/video_gen_test.cpp b/tests/video_gen_test.cpp index c1380d4e..9861d9e0 100644 --- a/tests/video_gen_test.cpp +++ b/tests/video_gen_test.cpp @@ -8,8 +8,10 @@ using namespace sched_fake; #include "gen/video_driver.h" +#include "rad_plugin.h" #include +#include #include #include @@ -55,9 +57,13 @@ RadVideoGenDecl decl_small() { return d; } +/* The soundtrack's rows a latent in fake_positions' layout: the declaration's audio_streams, or its + * two channels. */ +int g_audio_streams = 2; + /* The packed layout's rows, each position the row's index; a decode pass, ten rows a frame. */ int64_t fake_positions(int which, const RadVideoGeom* g, float* pos, int64_t cap) { - const int64_t rows = g->n_text + 2 * (int64_t)g->n_audio + + const int64_t rows = g->n_text + g_audio_streams * (int64_t)g->n_audio + (int64_t)g->lat_frames * (g->lat_h / 2) * (g->lat_w / 2); if (which == RAD_VPOS_DECODE) return 10 * (int64_t)g->frames; if (pos) { @@ -409,7 +415,7 @@ TEST(an_upscale_that_cannot_run_is_refused_at_submit) { /* What can never run is refused at submit: an empty or long prompt, a size off the multiple, * below the least side, over the area or the aspect, a length outside the chunks, steps outside - * 2..max. */ + * 2..max. A length of 0 chunks is none named. */ TEST(a_request_that_cannot_run_is_refused_at_submit) { VideoFixture f; f.build(); @@ -438,9 +444,395 @@ TEST(a_request_that_cannot_run_is_refused_at_submit) { r->height = 96; refused(std::move(r), "size"); refused(f.req(4), "chunks"); - refused(f.req(0), "chunks"); refused(f.req(1, 6), "num_inference_steps"); refused(f.req(1, 1), "num_inference_steps"); + /* No length named is the model's default. */ + auto none = f.req(0); + gen::VideoTicket* t = none->ticket.get(); + CHECK_OK(f.drv.submit(std::move(none), &why)); + CHECK_EQ(t->frames, 3); +} + +/* Decoders (RadVideoGenDecl::decoders): a request's index reaches every VDECODE pass; an index past + * the list, or a frame over the decoder's area, is refused at submit. */ +TEST(the_decoder_a_request_names_reaches_its_decode_passes) { + VideoFixture f; + f.build(); + f.prog.vgen_str.decoders = { "vae", "diffusion" }; + f.prog.vgen_str.decoder_max_area = { 64 * 64, 32 * 32 }; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1); + r->decoder = 1; + CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL); /* 64 x 32 over 32 x 32 */ + CHECK(why.find("diffusion") != std::string::npos); + r = f.req(1); + r->decoder = 2; + CHECK_EQ(f.drv.submit(std::move(r), &why), (int)RAD_E_INVAL); + r = f.req(1); + r->decoder = 1; + r->width = 32; + r->height = 32; + CHECK_OK(f.drv.submit(std::move(r), &why)); + int decodes = 0; + for (int i = 0; i < 20; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + if (b->gen == RAD_GEN_PASS_VDECODE) { + CHECK_EQ(b->vgen_b->decoder, 1); + ++decodes; + } + f.answer(0); + CHECK_OK(f.drv.done()); + } + CHECK(decodes > 0); +} + +/* A length head (RadVideoGenDecl::duration_out): a request that names no length is shaped at the + * default until its VCOND pass, whose prediction (ln seconds, read back) the driver turns into + * chunks -- clamped to the declared seconds, rounded half to even to frames, floored to the chunk + * grid and lifted a chunk under the minimum -- then held to the chunks the model makes. */ +TEST(a_length_head_sets_the_length_after_the_prompt_pass) { + struct Case { double sec; int32_t frames; }; + /* 4 fps, 2 frames a chunk + 1, 1..3 chunks, 0.5..2 s (2..8 frames): 1.3 s is 5.2 frames, 5; + * 1.125 s is 4.5, which rounds to 4 (half to even) and floors to 3; 0.1 s is held to 2 + * frames, which floor to 1 and are lifted to 3; 9 s is held to 8 frames, 7 on the grid. */ + const Case cases[] = { { 1.3, 5 }, { 1.125, 3 }, { 0.1, 3 }, { 9.0, 7 } }; + for (const Case& k : cases) { + VideoFixture f; + f.build(); + f.prog.video_gen.duration_out = 3; + f.prog.video_gen.duration_min = 0.5; + f.prog.video_gen.duration_max = 2.0; + f.prog.video_gen.duration_dtype = RAD_F32; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(0); + std::shared_ptr t = r->ticket; + CHECK_OK(f.drv.submit(std::move(r), &why)); + CHECK_EQ(t->frames, 3); /* the default, one chunk */ + const RadBatch* b = f.drv.next(0); + REQUIRE(b != nullptr); + CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VCOND); + REQUIRE_EQ(f.drv.readbacks().size(), (size_t)1); + CHECK_EQ(f.drv.readbacks()[0].buf, (rad_buf)3); + *static_cast(f.drv.readbacks()[0].host) = (float)std::log(k.sec); + CHECK_OK(f.drv.done()); + CHECK_EQ(t->frames, k.frames); + gen::VideoEvent e; + bool to = false; + REQUIRE(t->next(&e, 0, &to)); + CHECK_EQ(e.kind, (int)gen::VideoEvent::LENGTH); + CHECK_EQ(e.n, k.frames); + /* The steps run at that length. */ + b = f.drv.next(1); + REQUIRE(b != nullptr); + CHECK_EQ(b->gen, (int)RAD_GEN_PASS_VSTEP); + CHECK_EQ(b->vgen_b->geom.frames, k.frames); + } +} + +/* ---- form 1 (LTX-2's FlowMatchEulerDiscrete): evaluations, not grid points */ + +static uint32_t bits(float v) { + uint32_t u; + std::memcpy(&u, &v, 4); + return u; +} + +/* The dev schedule bit for bit against diffusers' scheduler (numpy 2.5): 30 evaluations of a + * 6144-token video shift by mu 2.7833 and stretch to end at 0.1; and 7 of a 1500-token one. */ +TEST(form_one_is_ltx2s_dynamically_shifted_schedule_bit_for_bit) { + RadVideoGenDecl d = decl_small(); + d.sched_kind = 1; + d.dyn_shift = 1; + d.base_shift = 0.95; + d.max_shift = 2.05; + d.base_seq = 1024; + d.max_seq = 4096; + d.shift_terminal = 0.1; + const gen::VideoSchedule s = gen::video_schedule(d, 30, 6144); + REQUIRE_EQ(s.sig_v.size(), (size_t)31); + CHECK_EQ(s.steps, 30); + const std::pair want[] = { + { 0, 0x3f800000u }, { 1, 0x3f7f3c87u }, { 2, 0x3f7e6c02u }, { 15, 0x3f6b19eeu }, + { 27, 0x3eff5f82u }, { 28, 0x3eb2f452u }, { 29, 0x3dccccd0u }, { 30, 0u }, + }; + for (const auto& w : want) CHECK_EQ(bits(s.sig_v[(size_t)w.first]), w.second); + CHECK(s.sig_a == s.sig_v); + const gen::VideoSchedule s7 = gen::video_schedule(d, 7, 1500); + const uint32_t want7[] = { 0x3f800000u, 0x3f6e0d50u, 0x3f57d30eu, 0x3f3b945eu, 0x3f167dc8u, + 0x3ec74586u, 0x3dccccd0u, 0u }; + REQUIRE_EQ(s7.sig_v.size(), (size_t)8); + for (int i = 0; i < 8; ++i) CHECK_EQ(bits(s7.sig_v[(size_t)i]), want7[i]); + /* One evaluation is a schedule of form 1. */ + CHECK_EQ(gen::video_schedule(d, 1, 6144).steps, 1); +} + +static const double kDistilled[] = { 1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, + 0.421875 }; +static const double kStage2[] = { 0.909375, 0.725, 0.421875 }; + +RadVideoGenDecl decl_distilled() { + RadVideoGenDecl d = decl_small(); + d.sched_kind = 1; + d.n_rungs = 8; + d.rungs = kDistilled; + d.default_steps = d.max_steps = 8; + d.upscale_max = 2.0; + d.n_refine_rungs = 3; + d.refine_rungs = kStage2; + d.upscale_refine = 3; + return d; +} + +/* A trained schedule of form 1 is its rungs as given, and with refinement the second stage's rungs + * follow the first's in place of the 0. */ +TEST(form_one_rungs_are_used_as_given_and_the_refinement_follows_them) { + const RadVideoGenDecl d = decl_distilled(); + const gen::VideoSchedule s = gen::video_schedule(d, 8); + REQUIRE_EQ(s.sig_v.size(), (size_t)9); + CHECK_EQ(s.steps, 8); + for (int i = 0; i < 8; ++i) CHECK_EQ(s.sig_v[(size_t)i], (float)kDistilled[i]); + CHECK_EQ(s.sig_v[8], 0.0f); + CHECK_EQ(gen::video_schedule(d, 9).steps, 0); + const gen::VideoSchedule r = gen::video_schedule(d, 8, 0, true); + REQUIRE_EQ(r.sig_v.size(), (size_t)12); + CHECK_EQ(r.steps, 11); + CHECK_EQ(r.sig_v[8], (float)kStage2[0]); + CHECK_EQ(r.sig_v[10], (float)kStage2[2]); + CHECK_EQ(r.sig_v[11], 0.0f); +} + +/* Two stages: every first-stage rung at the small size, the last to the clean estimate; the + * upscale re-noises to the second stage's first sigma; the second stage's rungs at the full size. + * The request's refinement is the second stage's length or nothing. */ +TEST(a_two_stage_request_runs_the_second_stages_own_rungs_after_the_upscale) { + VideoFixture f; + f.build(); + f.prog.video_gen = decl_distilled(); + f.prog.video_gen.rungs = nullptr; + f.prog.video_gen.refine_rungs = nullptr; + f.prog.vgen_str.rungs.assign(kDistilled, kDistilled + 8); + f.prog.vgen_str.refine_rungs.assign(kStage2, kStage2 + 3); + CHECK_OK(f.start()); + std::string why; + auto bad = f.req(1, 0); + bad->width = bad->height = 64; + bad->upscale = 2.0; + bad->refine = 2; + CHECK_EQ(f.drv.submit(std::move(bad), &why), (int)RAD_E_INVAL); + CHECK(has(why, "upscale_refine_steps must be 3")); + auto r = f.req(1, 0); + r->width = r->height = 64; + r->upscale = 2.0; + auto t = r->ticket; + CHECK_OK(f.drv.submit(std::move(r), &why)); + CHECK_EQ(t->steps, 11); + CHECK_EQ(t->refine, 3); + std::string kinds; + int n = 0; + for (int i = 0; i < 40; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + const RadVideoGenBatch* V = b->vgen_b; + kinds += kind_of(b->gen); + if (b->gen == RAD_GEN_PASS_VSTEP) { + const float cur = n < 8 ? (float)kDistilled[n] : (float)kStage2[n - 8]; + const float nxt = n == 7 || n == 10 ? 0.0f + : n < 7 ? (float)kDistilled[n + 1] : (float)kStage2[n - 7]; + CHECK_EQ(V->sched[1], cur); + CHECK_EQ(V->sched[2], nxt); + CHECK_EQ(V->geom.lat_h, n < 8 ? 2 : 4); + ++n; + } else if (b->gen == RAD_GEN_PASS_VUPSCALE) { + CHECK_EQ(V->sched[1], (float)kStage2[0]); + CHECK_EQ(V->sched[4], (float)kStage2[0]); + } + f.answer(0); + CHECK_OK(f.drv.done()); + } + CHECK_EQ(kinds, std::string("CSSSSSSSSUSSSAD")); + CHECK_EQ(t->status(), (int)RAD_OK); +} + +/* A guided model: the request's terms over the model's defaults reach every pass; the negative + * prompt rides in the VCOND pass after the prompt, each from position 0, only while a scale asks + * for the unconditional branch; the text rows of a step are the model's fixed count. */ +TEST(guidance_and_the_negative_prompt_reach_the_passes) { + VideoFixture f; + f.build(); + RadVideoGenDecl& d = f.prog.video_gen; + d.guidance = 1; + const double defaults[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 }; + std::memcpy(d.guidance_default, defaults, sizeof defaults); + d.step_text_rows = 6; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1, 3); + r->neg_tokens = { 9, 8 }; + r->guidance[1] = 0.0; + CHECK_OK(f.drv.submit(std::move(r), &why)); + const RadBatch* b = f.drv.next(0); + REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND); + const RadVideoGenBatch* V = b->vgen_b; + CHECK_EQ(b->n_tok, (int64_t)5); + CHECK_EQ(b->n_seq, 2); + CHECK_EQ(V->n_neg, 2); + CHECK(std::vector(b->cu_seqlens, b->cu_seqlens + 3) == std::vector({ 0, 3, 5 })); + CHECK(std::vector(b->token_ids, b->token_ids + 5) == + std::vector({ 1, 2, 3, 9, 8 })); + CHECK(std::vector(b->positions, b->positions + 5) == + std::vector({ 0, 1, 2, 0, 1 })); + CHECK_EQ(V->geom.n_text, 6); + REQUIRE(V->guidance_h != nullptr); + CHECK_EQ(V->guidance_h[0], 3.0f); + CHECK_EQ(V->guidance_h[1], 0.0f); + CHECK_EQ(V->guidance_h[3], 0.7f); + CHECK_OK(f.drv.done()); + b = f.drv.next(1); + REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP); + CHECK_EQ(b->n_tok, (int64_t)(6 + 60 + 2 * 2)); + CHECK_EQ(b->vgen_b->guidance_h[4], 7.0f); + /* The device copy the ops read. */ + REQUIRE(b->vgen_b->guidance != nullptr); + CHECK_EQ(b->vgen_b->guidance[0], 3.0f); + CHECK_EQ(b->vgen_b->guidance[4], 7.0f); + CHECK_OK(f.drv.done()); + + /* Both scales 1: no unconditional branch, so no negative prompt. */ + VideoFixture g; + g.build(); + g.prog.video_gen = d; + CHECK_OK(g.start()); + auto u = g.req(1, 3); + u->neg_tokens = { 9 }; + u->guidance[0] = 1.0; + u->guidance[4] = 1.0; + CHECK_OK(g.drv.submit(std::move(u), &why)); + b = g.drv.next(0); + REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND); + CHECK_EQ(b->n_tok, (int64_t)3); + CHECK_EQ(b->n_seq, 1); + CHECK_EQ(b->vgen_b->n_neg, 0); + + /* A guided request with no negative prompt cannot run; an unguided model takes no terms. */ + auto m = g.req(1, 3); + why.clear(); + CHECK_EQ(g.drv.submit(std::move(m), &why), (int)RAD_E_INVAL); + CHECK(has(why, "negative prompt")); + VideoFixture h; + h.build(); + CHECK_OK(h.start()); + auto q = h.req(1, 3); + q->guidance[2] = 2.0; + why.clear(); + CHECK_EQ(h.drv.submit(std::move(q), &why), (int)RAD_E_INVAL); + CHECK(has(why, "no guidance")); +} + +/* A first frame reaches the VCOND pass as bf16 x / 255 * 2 - 1 at the size the first steps run + * at, and every pass of the request says it has one; a model without image conditioning, or a + * frame of another size, is refused. */ +TEST(a_first_frame_reaches_the_prompt_pass_at_the_first_steps_size) { + VideoFixture f; + f.build(); + f.prog.video_gen.image_cond = 1; + f.prog.video_gen.upscale_max = 2.0; + f.prog.video_gen.upscale_refine = 1; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1, 3); + r->width = r->height = 64; + r->upscale = 2.0; + r->image.assign(32 * 32 * 3, 0); + r->image[0] = 255; + r->image[1] = 128; + auto wrong = f.req(1, 3); + wrong->image.assign(64 * 32 * 3, 0); + wrong->width = wrong->height = 64; + wrong->upscale = 2.0; + CHECK_EQ(f.drv.submit(std::move(wrong), &why), (int)RAD_E_INVAL); + CHECK(has(why, "32x32")); + CHECK_OK(f.drv.submit(std::move(r), &why)); + const RadBatch* b = f.drv.next(0); + REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND); + const RadVideoGenBatch* V = b->vgen_b; + REQUIRE(V->image != nullptr); + CHECK_EQ(V->has_image, 1); + CHECK_EQ(V->image[0], rad_f32_to_bf16(1.0f)); + CHECK_EQ(V->image[1], rad_f32_to_bf16(2.0f * (128.0f / 255.0f) - 1.0f)); + CHECK_EQ(V->image[2], rad_f32_to_bf16(-1.0f)); + CHECK_OK(f.drv.done()); + b = f.drv.next(1); + REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP); + CHECK(b->vgen_b->image == nullptr); + CHECK_EQ(b->vgen_b->has_image, 1); + + VideoFixture g; + g.build(); + CHECK_OK(g.start()); + auto q = g.req(1, 3); + q->image.assign(64 * 32 * 3, 0); + why.clear(); + CHECK_EQ(g.drv.submit(std::move(q), &why), (int)RAD_E_INVAL); + CHECK(has(why, "picture")); +} + +/* A left-padded encoder's prompt ends at text_left_pad - 1, the negative prompt too; one stream of + * soundtrack rows a latent; an exact upscaler takes its factor only, over sides it divides. */ +TEST(left_padded_prompts_one_audio_stream_and_an_exact_upscaler) { + VideoFixture f; + f.build(); + RadVideoGenDecl& d = f.prog.video_gen; + d.guidance = 1; + d.guidance_default[0] = 3.0; + d.guidance_default[4] = 1.0; + d.text_left_pad = 8; + d.audio_streams = 1; + d.upscale_max = 2.0; + d.upscale_refine = 1; + d.upscale_exact = 1; + g_audio_streams = 1; + CHECK_OK(f.start()); + std::string why; + auto r = f.req(1, 3); + r->neg_tokens = { 9, 8 }; + CHECK_OK(f.drv.submit(std::move(r), &why)); + const RadBatch* b = f.drv.next(0); + REQUIRE(b && b->gen == RAD_GEN_PASS_VCOND); + CHECK(std::vector(b->positions, b->positions + 5) == + std::vector({ 5, 6, 7, 6, 7 })); + CHECK_OK(f.drv.done()); + b = f.drv.next(1); + REQUIRE(b && b->gen == RAD_GEN_PASS_VSTEP); + /* 3 text rows, 30 soundtrack latents in one stream, 2 x 2 video patches. */ + CHECK_EQ(b->n_tok, (int64_t)(3 + 30 + 2 * 2)); + /* The soundtrack as a (30, 1, 1) volume; the video's rows cut at its first latent frame. */ + const int32_t* gd = b->vgen_b->geom_d; + CHECK(std::vector(gd + RAD_VGEOM_AUDIO_VOL, gd + RAD_VGEOM_AUDIO_VOL + 3) == + std::vector({ 30, 1, 1 })); + CHECK_EQ(gd[RAD_VGEOM_FIRST_CU], 0); + CHECK_EQ(gd[RAD_VGEOM_FIRST_CU + 2], 4); + CHECK_EQ(gd[RAD_VGEOM_FIRST_CU + 1] * gd[RAD_VGEOM_LAT_FRAMES], 4); + CHECK_OK(f.drv.done()); + + auto u = f.req(1, 3); + u->width = 64; + u->height = 32; + u->upscale = 2.0; + u->neg_tokens = { 9 }; + why.clear(); + CHECK_EQ(f.drv.submit(std::move(u), &why), (int)RAD_E_INVAL); + CHECK(has(why, "multiples of 64")); + auto v = f.req(1, 3); + v->width = v->height = 64; + v->upscale = 1.5; + v->neg_tokens = { 9 }; + why.clear(); + CHECK_EQ(f.drv.submit(std::move(v), &why), (int)RAD_E_INVAL); + CHECK(has(why, "exactly 2")); + g_audio_streams = 2; } RAD_TEST_MAIN() diff --git a/tests/videos_test.cpp b/tests/videos_test.cpp index 76ba6905..27c93a23 100644 --- a/tests/videos_test.cpp +++ b/tests/videos_test.cpp @@ -10,6 +10,7 @@ #include "server_fakes.h" #include "gen/video.h" +#include "mm/media.h" #include #include @@ -65,6 +66,13 @@ struct FakeVideoGen : IVideoGen { t.refine = r->refine > 0 ? r->refine : (int32_t)inf.upscale_refine; } if (finish_status == RAD_OK) { + /* A request that named no length learns the one the model chose first. */ + if (r->chunks == 0) { + gen::VideoEvent l; + l.kind = gen::VideoEvent::LENGTH; + l.n = 3; + t.push(std::move(l)); + } for (int s = 1; s <= 2; ++s) { gen::VideoEvent e; e.kind = gen::VideoEvent::STEP; @@ -209,6 +217,57 @@ TEST(the_generator_gets_the_size_the_chunks_and_the_steps) { v.wait(str_at(json::parse(r.body, nullptr, false), "id")); } +/* A model with a length head chooses the length of a request that names none or says "auto": the + * generator gets 0 chunks, the video object says "auto" until the model has chosen and then the + * length chosen. A length named is as for any model; without a head, none named is the default. */ +TEST(a_length_head_chooses_the_length_of_a_request_that_names_none) { + Videos v; + HttpResponse r = v.create(Videos::body()); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().chunks, 7); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + + v.gen.inf.length_head = true; + for (const json& b : { Videos::body(), Videos::body({ { "seconds", "auto" } }) }) { + r = v.create(b); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().chunks, 0); + json o = json::parse(r.body, nullptr, false); + CHECK_EQ(str_at(o, "seconds"), std::string("auto")); + o = v.wait(str_at(o, "id")); + CHECK_EQ(str_at(o, "status"), std::string("completed")); + CHECK_EQ(str_at(o, "seconds"), std::string("0.12")); /* 3 frames at 24 a second */ + } + r = v.create(Videos::body({ { "seconds", "8" } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().chunks, 11); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); +} + +/* A model with more than one decoder takes `decoder` by name, the default first: the generator gets + * its index, the video object names a decoder other than the default, an unknown name or a frame + * over the decoder's area is a 400 naming the field. A model with one decoder takes no name. */ +TEST(a_decoder_is_named_and_held_to_its_area) { + Videos v; + CHECK_EQ(v.refused(Videos::body({ { "decoder", "vae" } })), std::string("decoder")); + v.gen.inf.decoders = { "vae", "diffusion" }; + v.gen.inf.decoder_max_area = { 1344 * 768, 512 * 256 }; + HttpResponse r = v.create(Videos::body({ { "decoder", "diffusion" }, { "size", "512x256" } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().decoder, 1); + json o = json::parse(r.body, nullptr, false); + CHECK_EQ(str_at(o, "decoder"), std::string("diffusion")); + v.wait(str_at(o, "id")); + r = v.create(Videos::body({ { "decoder", "vae" } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().decoder, 0); + CHECK(!json::parse(r.body, nullptr, false).contains("decoder")); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + CHECK_EQ(v.refused(Videos::body({ { "decoder", "magic" } })), std::string("decoder")); + CHECK_EQ(v.refused(Videos::body({ { "decoder", "diffusion" }, { "size", "768x512" } })), + std::string("decoder")); +} + /* Latent upscaling: refused by a model without an upscaler; with one, the factor and the refine * steps reach the generator, a factor of 1 is none, and the refine steps need a factor. */ TEST(latent_upscale_reaches_the_generator_where_the_model_has_an_upscaler) { @@ -340,4 +399,163 @@ TEST(the_video_routes_are_501_without_a_video_model) { CHECK_EQ(f.get("/v1/videos").status, 501); } +namespace { + +/* A PNG of w x h, every pixel (r, g, b). */ +std::string png_rgb(int32_t w, int32_t h, uint8_t r, uint8_t g, uint8_t b) { + std::vector px; + for (int64_t i = 0; i < (int64_t)w * h; ++i) px.insert(px.end(), { r, g, b }); + std::vector file; + std::string why; + if (mm::encode_image(px.data(), w, h, 3, "png", 0, &file, &why) < 0) return std::string(); + return std::string(file.begin(), file.end()); +} + +std::string png_url(const std::string& bytes) { + return "data:image/png;base64," + base64_encode(bytes.data(), bytes.size()); +} + +/* A guided model that starts from a picture, as LTX-2.5's dev weights. */ +void guided(Videos& v, int32_t crf) { + VideoGenInfo& in = v.gen.inf; + in.guidance = true; + const double d[8] = { 3.0, 1.0, 3.0, 0.7, 7.0, 1.0, 3.0, 0.7 }; + std::copy(d, d + 8, in.guidance_default); + in.default_negative = "ugly"; + in.image_cond = true; + in.image_crf = crf; + in.step_evals = true; + in.upscale_max = 2.0; + in.upscale_refine = 3; +} + +std::string text_of(const std::vector& ids) { + std::string s; + for (int32_t c : ids) s += (char)c; + return s; +} + +} /* namespace */ + +/* Guidance terms and the negative prompt: refused by a model without guidance; on a guided one the + * named terms reach the generator (the rest NaN, the model's default), the negative prompt is + * rendered in the template (the model's own when none is named), and the video object reports the + * resolved terms. Steps count evaluations there, from 1. */ +TEST(guidance_and_the_negative_prompt_reach_a_guided_model) { + { + Videos v; + CHECK_EQ(v.refused(Videos::body({ { "negative_prompt", "x" } })), + std::string("negative_prompt")); + CHECK_EQ(v.refused(Videos::body({ { "stg_scale", 1 } })), std::string("stg_scale")); + } + Videos v; + guided(v, 0); + CHECK_EQ(v.refused(Videos::body({ { "guidance_rescale", 1.5 } })), + std::string("guidance_rescale")); + CHECK_EQ(v.refused(Videos::body({ { "audio_guidance_scale", -1 } })), + std::string("audio_guidance_scale")); + CHECK_EQ(v.refused(Videos::body({ { "negative_prompt", 3 } })), std::string("negative_prompt")); + HttpResponse r = v.create(Videos::body({ { "guidance_scale", 5 }, { "audio_stg_scale", "0" }, + { "negative_prompt", "blurry" }, + { "num_inference_steps", 1 } })); + REQUIRE_EQ(r.status, 200); + const gen::VideoRequest& q = v.gen.last(); + CHECK_EQ(q.guidance[0], 5.0); + CHECK_EQ(q.guidance[5], 0.0); + CHECK(std::isnan(q.guidance[1]) && std::isnan(q.guidance[4])); + CHECK(q.has_neg); + CHECK_EQ(text_of(q.neg_tokens), std::string("blurry")); + CHECK_EQ(q.steps, 1); + json o = json::parse(r.body, nullptr, false); + CHECK_EQ(o["guidance_scale"].get(), 5.0); + CHECK_EQ(o["guidance_rescale"].get(), 0.7); + CHECK_EQ(o["audio_guidance_scale"].get(), 7.0); + CHECK_EQ(str_at(o, "negative_prompt"), std::string("blurry")); + v.wait(str_at(o, "id")); + + r = v.create(Videos::body()); + REQUIRE_EQ(r.status, 200); + CHECK(!v.gen.last().has_neg); + CHECK_EQ(text_of(v.gen.last().neg_tokens), std::string("ugly")); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + + /* Both scales 1: unguided, so the object names no negative prompt. */ + r = v.create(Videos::body({ { "guidance_scale", 1 }, { "audio_guidance_scale", 1 } })); + REQUIRE_EQ(r.status, 200); + o = json::parse(r.body, nullptr, false); + CHECK(!o.contains("negative_prompt")); + v.wait(str_at(o, "id")); +} + +/* input_reference: refused by a text-only model; on a model that starts from a picture, a data URL + * in JSON or a file in a form becomes the first frame at the size the first steps run at (the + * small size under latent upscaling), an even colour staying that colour; task i2va goes with it. */ +TEST(input_reference_becomes_the_first_frame_at_the_first_steps_size) { + const std::string pic = png_rgb(300, 170, 200, 40, 90); + { + Videos v; + CHECK_EQ(v.refused(Videos::body({ { "input_reference", png_url(pic) } })), + std::string("input_reference")); + } + Videos v; + guided(v, 0); + CHECK_EQ(v.refused(Videos::body({ { "input_reference", "data:image/png;base64,AAAA" } })), + std::string("input_reference")); + CHECK_EQ(v.refused(Videos::body({ { "input_reference", png_url(pic) }, { "task", "t2va" } })), + std::string("task")); + HttpResponse r = v.create(Videos::body({ { "input_reference", { { "image_url", png_url(pic) } } }, + { "task", "i2va" } })); + REQUIRE_EQ(r.status, 200); + const gen::VideoRequest& q = v.gen.last(); + REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3); + CHECK_EQ((int)q.image[0], 200); + CHECK_EQ((int)q.image[1], 40); + CHECK_EQ((int)q.image[q.image.size() - 1], 90); + json o = json::parse(r.body, nullptr, false); + CHECK(o.value("input_reference", false)); + v.wait(str_at(o, "id")); + + r = v.create(Videos::body({ { "input_reference", png_url(pic) }, { "size", "512x512" }, + { "latent_upscale", 2 } })); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().image.size(), (size_t)256 * 256 * 3); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + + HttpRequest f; + f.method = "POST"; + f.path = "/v1/videos"; + f.form = { FormPart{ "prompt", "", "", "a boat" }, FormPart{ "size", "", "", "512x256" }, + FormPart{ "input_reference", "boat.png", "image/png", pic } }; + r = v.f->srv->router().dispatch(f); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(v.gen.last().image.size(), (size_t)512 * 256 * 3); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); +} + +/* With the model's H.264 quality the picture goes through the round trip first: an even colour + * comes back within a few levels (yuv420p's rounding), an odd size losing its last column. */ +TEST(input_reference_takes_the_models_h264_round_trip) { + Videos v; + guided(v, 18); + const std::string pic = png_rgb(301, 171, 200, 40, 90); + HttpResponse r = v.create(Videos::body({ { "input_reference", png_url(pic) } })); + if (r.status == 503) return; /* a build without libx264 refuses it, as it should */ + REQUIRE_EQ(r.status, 200); + const gen::VideoRequest& q = v.gen.last(); + REQUIRE_EQ(q.image.size(), (size_t)256 * 256 * 3); + const int want[3] = { 200, 40, 90 }; + for (size_t i = 0; i < q.image.size(); i += 997) + CHECK(std::abs((int)q.image[i] - want[i % 3]) <= 3); + v.wait(str_at(json::parse(r.body, nullptr, false), "id")); + + mm::Frame in, out; + in.w = 7; + in.h = 5; + in.rgb.assign(7 * 5 * 3, 128); + std::string why; + REQUIRE_EQ(mm::h264_roundtrip(in, 18, &out, &why), (int)RAD_OK); + CHECK_EQ(out.w, 6); + CHECK_EQ(out.h, 4); +} + RAD_TEST_MAIN() diff --git a/vendor/UPSTREAM b/vendor/UPSTREAM index 12b439eb..9faf508b 100644 --- a/vendor/UPSTREAM +++ b/vendor/UPSTREAM @@ -552,9 +552,9 @@ PATCH SERIES An escaped space or non-ASCII character is itself. \x and \u in a class need their hex digits; "\0" before a digit (a legacy octal) is refused. Every other class escape is now refused at conversion with a message naming it. Limits: a negated class still admits the - \u form of a character it leaves out (\u0009 for \t), and a positive class admits \t \n - \r \f \b only in their short form. gbnf_test covers each escape in and out of a class, quantified, and negated, and the - refusals. + \u form of a character it leaves out (\u0009 for \t), and a positive class admits \t \n \r \f + \b only in their short form. gbnf_test covers each escape in and out of a class, quantified, + and negated, and the refusals. patches/0021-jinja-a-dotted-integer-is-an-index.patch From 4246a1dd04e7e1bb8c1e9b6da847ea17c27a0f36 Mon Sep 17 00:00:00 2001 From: Deadcode Date: Tue, 20 Oct 2026 21:05:16 +0200 Subject: [PATCH 065/152] radiance 1.10.0 LoRA for image and video generators: - civitai and Hugging Face adapter files as published: kohya, ComfyUI and diffusers/PEFT key names; LoRA, LoCon, LoHa, LoKr and full-weight diffs; DoRA, OFT and Tucker are refused by name - stacked per request with a strength each, through the `loras` field or tags in the prompt; --lora-dir serves every file in a directory, GET /v1/loras lists them, and --max-loras / --max-lora-rank size the slots on the card (generators default to rank 64) - Krea 2, Qwen-Image 2.1, FLUX.3 [klein], MiniMax H3, LTX-2.5, Anima and SDXL New models: - Anima (base, aesthetic and turbo): Cosmos-Predict2 DiT with the Qwen3-0.6B text encoder and the Qwen-Image VAE, on one card - Stable Diffusion XL and its single-file finetunes (Illustrious, NoobAI including V-Pred, Pony), read as civitai ships them, with the Euler, Euler a and DPM++ 2M samplers Recipes: - q38-27b-mxfp4-df2: any bf16 Qwen3.8-27B or finetune at MXFP4 with the DFlash2 drafter - Krea 2 finetunes from civitai: scripts/krea2_native.py reads Krea's own key names, and krea-2-fp8-unscaled keeps a plain-fp8 file's codes exactly Changes: --max-num-batched-tokens defaults to 2048 (was 8192). Plugin ABI 25: out-of-tree plugins must be rebuilt. --- CMakeLists.txt | 2 +- README.md | 7 + abi/rad_abi.h | 2 +- abi/rad_builder.h | 111 +- abi/rad_format.h | 15 + abi/rad_runtime.h | 26 + arch/anima/CMakeLists.txt | 10 + arch/anima/anima.cpp | 1367 ++++++++++++++++ arch/common/rad_arch.h | 22 + arch/flux3/flux3.cpp | 26 + arch/krea2/krea2.cpp | 31 + arch/ltx2/ltx2.cpp | 3 + arch/minimaxh3/minimaxh3.cpp | 36 + arch/qwenimage21/qwenimage21.cpp | 11 + arch/sdxl/CMakeLists.txt | 10 + arch/sdxl/sdxl.cpp | 1236 ++++++++++++++ core/build/rad_build.h | 3 + core/build/rad_builder.cpp | 145 +- core/config.cpp | 41 +- core/engine.cpp | 49 +- core/engine.h | 28 + core/engine_bringup.cpp | 8 + core/engine_gen.cpp | 3 + core/engine_lora.cpp | 334 +++- core/format/checkpoint.cpp | 239 ++- core/format/checkpoint.h | 13 +- core/format/radfile.cpp | 141 +- core/format/radfile.h | 8 +- core/gen/driver.cpp | 91 +- core/gen/driver.h | 12 +- core/gen/gen.cpp | 131 ++ core/gen/gen.h | 34 + core/gen/pass.h | 2 + core/gen/video.h | 5 + core/gen/video_driver.cpp | 2 + core/gen/video_driver.h | 2 + core/lora/adapter.cpp | 986 ++++++++++++ core/lora/adapter.h | 183 +++ core/lora/config.h | 37 +- core/lora/declare.cpp | 111 +- core/lora/lora.cpp | 140 +- core/lora/lora.h | 24 + core/lora/slots.cpp | 17 +- core/lora/slots.h | 6 + core/rad_core.h | 28 +- core/runtime/ctx.h | 4 + core/runtime/issue.cpp | 100 +- core/server/iface.h | 23 + core/server/images.cpp | 117 +- core/server/loras.cpp | 117 ++ core/server/loras.h | 30 + core/server/server.cpp | 17 + core/server/server.h | 7 + core/server/videos.cpp | 29 +- core/text/tokenizer.cpp | 177 +- core/text/tokenizer.h | 4 + core/text/tokenizer_grapheme.cpp | 210 +++ core/text/tokenizer_grapheme.h | 56 + core/text/tokenizer_grapheme_ucd.cpp | 1878 ++++++++++++++++++++++ core/text/tokenizer_json.cpp | 98 +- data/recipes/anima-bf16.recipe | 16 + data/recipes/anima-fp8.recipe | 31 + data/recipes/krea-2-fp8-unscaled.recipe | 45 + data/recipes/q38-27b-mxfp4-df2.recipe | 41 + data/recipes/sdxl-bf16.recipe | 9 + deploy/compose/anima.yaml | 19 + deploy/compose/fasth3.yaml | 3 + deploy/compose/flux-3-klein.yaml | 3 + deploy/compose/krea-2-raw.yaml | 3 + deploy/compose/krea-2-turbo.yaml | 3 + deploy/compose/ltx-2.5.yaml | 4 + deploy/compose/minimax-h3.yaml | 3 + deploy/compose/qwen-image-2.1-turbo.yaml | 3 + deploy/compose/qwen-image-2.1.yaml | 3 + deploy/compose/sdxl.yaml | 15 + docs/ARCHITECTURES.md | 149 ++ docs/DOCKER.md | 2 + docs/GUIDE.md | 145 +- docs/OPS.md | 62 +- docs/TOOLS.md | 12 + libavx/avx_cases.cpp | 21 +- libavx/avx_check_hand.cpp | 45 + libavx/avx_gen.cpp | 273 ++++ libavx/avx_isa.h | 5 +- libavx/avx_lora.cpp | 15 +- libavx/avx_registry.cpp | 38 + libr4d/r4d_gen.hip | 354 ++++ libr4d/r4d_lora_bf16.hip | 153 ++ libr4d/r4d_plugin.h | 5 + libr4d/r4d_rows.cpp | 95 +- libr4d/r4d_selftest.cpp | 344 +++- libr4d/r4d_upscaler.hip | 107 +- libref/ref_gen.cpp | 284 ++++ libref/ref_lora.cpp | 18 +- libref/ref_ops.h | 10 + libref/ref_registry.cpp | 44 + libref/ref_shapes.cpp | 80 + scripts/README.md | 1 + scripts/krea2_native.py | 86 + tests/abi_layout_rows.h | 25 + tests/abi_layout_table.h | 31 +- tests/abi_layout_test.cpp | 6 +- tests/arch_test.cpp | 353 ++++ tests/checkpoint_test.cpp | 150 ++ tests/config_test.cpp | 17 +- tests/gen_lora_test.cpp | 585 +++++++ tests/gen_test.cpp | 224 +++ tests/images_test.cpp | 72 + tests/lora_test.cpp | 7 +- tests/mk_precompiled_goldens.py | 115 ++ tests/mk_tokenizer_goldens.py | 122 ++ tests/precompiled_golden.h | 1146 +++++++++++++ tests/precompiled_test.cpp | 103 ++ tests/r4d_emu/test_lora.cpp | 69 + tests/ref_test.cpp | 196 ++- tests/runtime_test.cpp | 37 +- tests/server_fakes.h | 8 + tests/shipped_plugins_test.cpp | 5 +- tests/text_test.cpp | 170 +- tools/gen_grapheme_ucd.py | 76 + tools/rad_convert.cpp | 28 + tools/rad_info.cpp | 2 + tools/rad_tokcheck.cpp | 6 +- tools/tokref.cpp | 6 +- 124 files changed, 14326 insertions(+), 387 deletions(-) create mode 100644 arch/anima/CMakeLists.txt create mode 100644 arch/anima/anima.cpp create mode 100644 arch/sdxl/CMakeLists.txt create mode 100644 arch/sdxl/sdxl.cpp create mode 100644 core/lora/adapter.cpp create mode 100644 core/lora/adapter.h create mode 100644 core/server/loras.cpp create mode 100644 core/server/loras.h create mode 100644 core/text/tokenizer_grapheme.cpp create mode 100644 core/text/tokenizer_grapheme.h create mode 100644 core/text/tokenizer_grapheme_ucd.cpp create mode 100644 data/recipes/anima-bf16.recipe create mode 100644 data/recipes/anima-fp8.recipe create mode 100644 data/recipes/krea-2-fp8-unscaled.recipe create mode 100644 data/recipes/q38-27b-mxfp4-df2.recipe create mode 100644 data/recipes/sdxl-bf16.recipe create mode 100644 deploy/compose/anima.yaml create mode 100644 deploy/compose/sdxl.yaml create mode 100755 scripts/krea2_native.py create mode 100644 tests/gen_lora_test.cpp create mode 100644 tests/mk_precompiled_goldens.py create mode 100644 tests/precompiled_golden.h create mode 100644 tests/precompiled_test.cpp create mode 100644 tools/gen_grapheme_ucd.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a6fbedcf..01b4b9fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is the server release that /version reports. The plugin ABI version is separate and is # read from abi/rad_abi.h below. -project(radiance VERSION 1.9.0 LANGUAGES C CXX) +project(radiance VERSION 1.10.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/README.md b/README.md index d1546995..3b980f2a 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,9 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, eight cards | `glm53-flash-mxfp4.rad` (171 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` | | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | +| Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` | | EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` | +| Anima Aesthetic FP8: anime and illustration, text to image, one card (Base and Turbo convert the same way) | `anima-aesthetic-fp8.rad` (3.0 GiB) | [convert](#convert-a-checkpoint) | `anima.yaml` | | Qwen3-ASR 1.7B bf16: speech to text, `/v1/audio/transcriptions` and live over `/v1/realtime`, 30 languages, one card | the checkpoint as it ships (4.1 GiB) | [Qwen/Qwen3-ASR-1.7B-hf](https://huggingface.co/Qwen/Qwen3-ASR-1.7B-hf) | — | A container holds everything the server needs: the weights, the tokeniser, the chat template and @@ -256,6 +258,11 @@ build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro- --draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2 build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \ --recipe data/recipes/q38-27b-w4a16.recipe +# Any single-file SDXL checkpoint (SDXL 1.0, Illustrious, NoobAI, Pony, a civitai finetune), with +# CLIP's tokenizer.json from openai/clip-vit-large-patch14 +build/bin/rad-convert /srv/models/hf/OnomaAIResearch/Illustrious-XL-v2.0/Illustrious-XL-v2.0.safetensors \ + -o illustrious-xl-v2.0-bf16.rad --recipe data/recipes/sdxl-bf16.recipe \ + --tokenizer /srv/models/hf/openai/clip-vit-large-patch14/tokenizer.json ``` With Docker, use `docker run --rm -v /srv/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`. diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 292e14b4..7353a917 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -17,7 +17,7 @@ extern "C" { * kind of plugin reports it, and a plugin that does not report exactly this version is refused at * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 24u +#define RAD_ABI_VERSION 25u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 5b1713c5..3e33597d 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -429,7 +429,7 @@ int rad_op_declared(RadBuilder* b, const char* op); * convert-time fusions (q/k/v into one qkv, gate and up into gate_up). It is the only component * that knows both sides, and rad-convert reads the map from it (spec §2.4). */ enum { RAD_MAP_COPY = 0, RAD_MAP_CONCAT = 1, RAD_MAP_WNORM = 2, RAD_MAP_ROWS = 3, - RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6 }; + RAD_MAP_TRANSPOSE = 4, RAD_MAP_EMA = 5, RAD_MAP_TAP = 6, RAD_MAP_COLS = 7 }; typedef struct RadNameMap { const char* declared; /* the name given to rad_decl_weight */ @@ -445,7 +445,8 @@ typedef struct RadNameMap { int src_index[8]; /* RAD_MAP_ROWS only: piece i is rows [src_index[i], src_index[i] + src_rows[i]) of the 2-D (or - * higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. */ + * higher, rows along dim 0) tensor src[i]; the pieces join along dim 0. RAD_MAP_COLS: columns + * [src_index[0], src_index[0] + src_rows[0]) of src[0]'s last dimension. */ int64_t src_rows[8]; } RadNameMap; @@ -463,7 +464,13 @@ typedef struct RadNameMap { * * RAD_MAP_ROWS keeps only row ranges of its sources (see src_rows), joined: a head read over a * fraction of a vocabulary (an audio model's codes, a few rows of a text model's 200K) stores that - * fraction rather than the whole table. + * fraction rather than the whole table. Successive ROWS maps for one name extend it in call order, + * as CONCAT maps do, so a weight may take more than eight pieces (an output projection whose rows + * are permuted, one piece a row). + * + * RAD_MAP_COLS keeps one column range of src[0] (see src_rows): a linear whose input carries + * channels the runtime never feeds (Cosmos's padding-mask channel, always zero) is read over the + * columns it is fed. * * RAD_MAP_TRANSPOSE swaps the last two dimensions of src[0] in each leading slice, [.., a, b] to * [.., b, a]: a linear a checkpoint keeps as (in, out), where the GEMMs read (out, in). @@ -478,7 +485,7 @@ typedef struct RadNameMap { * run on a single frame reads only its last temporal tap, so [cout, cin, kt, kh, kw] read at tap -1 * of dimension 2 is the 2-D convolution it then is. * - * TRANSPOSE, EMA and TAP are computed at convert in f32, like WNORM, and stored as the recipe + * TRANSPOSE, EMA, TAP and COLS are computed at convert in f32, like WNORM, and stored as the recipe * says. */ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m); @@ -714,7 +721,8 @@ typedef struct RadGeneratorDecl { /* The sampler: flow matching, Euler steps from sigma 1 towards 0. * A fixed schedule: `n_sigmas` values, the terminal 0 implied; a request may not change the - * step count. Otherwise `default_steps` sigmas from 1 to 1/steps, shifted: + * step count. Otherwise `default_steps` sigmas from 1 to 1/steps (or off `sigma_grid`'s + * table), shifted: * dyn_shift 0 sigma' = shift * s / (1 + (shift - 1) * s) * dyn_shift 1 mu linear in the image's token count, 256 -> base_shift .. max_seq -> * max_shift; shift_exp 1: exp(mu) / (exp(mu) + (1/s - 1)), 0: mu / (mu + ...) @@ -755,10 +763,103 @@ typedef struct RadGeneratorDecl { /* 1: a reference picture is shrunk to `ref_area` only when larger and cut to `size_multiple` * by a centred crop; 0: resized to `ref_area` at its own aspect. */ int32_t ref_shrink_only; + + /* ---- appended in ABI 25 (Anima, SDXL) */ + /* `aux_tokens` nonzero: the conditioning also reads the user's prompt through the container's + * second tokenizer (rad-convert --tokenizer2), as that tokenizer encodes it alone, special + * tokens included, and the COND pass carries the ids (RadGenBatch::aux_ids). A prompt whose + * second tokenisation is longer than `aux_max_tokens` is refused. */ + int64_t aux_max_tokens; + /* The unshifted sigmas of a schedule that is not fixed: 0 is diffusers' linspace(1, 1 / steps, + * steps); N > 0 picks them off a table of N timesteps as ComfyUI's `simple` scheduler does, + * step i at (N - floor(i N / steps)) / N, each an f32 quotient of the table's own. */ + int32_t sigma_grid; + /* A prompt shorter than this many tokens after `drop_prefix` is padded with `pad_token` up to + * it, the padding read as prompt (a reference tokenizer's minimum length: an empty prompt is + * one padding token, and stays empty rather than becoming " "). 0: no minimum. */ + int32_t min_tokens; + int32_t aux_tokens; + /* ---- a discrete-time denoiser (train_steps 0: the flow-matching sampler above) + * A model trained on `train_steps` timesteps of a variance-preserving schedule, betas from + * `beta_start` to `beta_end` (RAD_GEN_BETAS_*), sampled as k-diffusion samples it (Stable + * Diffusion's family). Its schedule is in sigmas, sigma_t = sqrt((1 - abar_t) / abar_t) for + * the cumulative product abar of 1 - beta; `zero_snr` rescales it to a zero terminal SNR + * (the last abar 4.8973451890853435e-08, as ComfyUI does). A request names a sampler + * (RAD_GEN_SAMPLER_*, one of those `samplers` holds as 1 << id, which the plugin's step + * serves) and a scheduler (RAD_GEN_SCHED_*), which places the request's steps between the + * table's largest and smallest sigma, 0 last. A DENOISE pass carries each entry's sigma, + * next and previous sigma in these units, the timestep the denoiser is conditioned on, the + * sampler and the step (RadGenBatch). n_sigmas, shift and the dynamic shift are unused. */ + double beta_start, beta_end; + int32_t train_steps; + int32_t beta_schedule; + int32_t zero_snr; + uint32_t samplers; + int32_t default_sampler; + int32_t default_scheduler; + + /* ---- the prompt in windows (a CLIP text encoder's fixed context) + * Nonzero: the prompt's tokens after `drop_prefix` are cut into runs of at most + * `chunk_tokens`, each laid out as `chunk_bos`, the run, `chunk_eos`, then `pad_token` up to + * chunk_tokens + 2 rows, the windows end to end; a prompt with no tokens is one window of + * the two markers and padding. The JOINT_STEP layout only, with `pad_multiple` 0, and + * `cond_rows` a whole number of windows. */ + int32_t chunk_tokens; + int32_t chunk_bos, chunk_eos; } RadGeneratorDecl; +/* RadGeneratorDecl::beta_schedule: betas linear in sqrt(beta) (Stable Diffusion's + * "scaled_linear"), or linear in beta. */ +enum { RAD_GEN_BETAS_SCALED_LINEAR = 0, RAD_GEN_BETAS_LINEAR = 1 }; +/* A discrete-time model's samplers, as k-diffusion (and ComfyUI) name and define them. */ +enum { + RAD_GEN_SAMPLER_EULER = 0, /* "euler" */ + RAD_GEN_SAMPLER_EULER_ANCESTRAL = 1, /* "euler_ancestral", eta 1 */ + RAD_GEN_SAMPLER_DPMPP_2M = 2, /* "dpmpp_2m" */ + RAD_GEN_SAMPLER_COUNT = 3 +}; +/* ... and its schedulers, ComfyUI's: "normal" (timesteps evenly spaced, the last at the smallest + * sigma), "karras" (rho 7), "exponential", "sgm_uniform" (normal without its last point) and + * "simple" (the table read at even strides). */ +enum { + RAD_GEN_SCHED_NORMAL = 0, + RAD_GEN_SCHED_KARRAS = 1, + RAD_GEN_SCHED_EXPONENTIAL = 2, + RAD_GEN_SCHED_SGM_UNIFORM = 3, + RAD_GEN_SCHED_SIMPLE = 4, + RAD_GEN_SCHED_COUNT = 5 +}; + int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d); +/* ================================================================== adapter key names */ +/* How LoRA files written for this model name its linears, for an image or video generator served + * with runtime adapters (--lora, --lora-dir, --max-loras; core/lora/). Adapter files from training + * tools and UIs name a module by the model's original code, not by the checkpoint the container + * was converted from, and wrap it in a prefix of their own: `diffusion_model.blocks.3.attn.wq`, + * kohya's `lora_unet_blocks_3_attn_wq`, a bare `blocks.3.attn.wq`. Both calls are optional, + * made before the GEMMs they cover are declared, and only a program that declares a root carries + * adapters at all. Additive exports; RAD_ABI_VERSION does not move. + * + * rad_lora_root declares one network the adapters may reach (the denoiser, a text encoder): every + * LoRA-capable GEMM over a checkpoint tensor whose name starts with `native` gets an adapter path. + * `spellings` lists, space separated, the prefixes adapter keys of this network start with in + * place of `native`; one ending in '_' is kohya's form, in which the rest of the key is the module + * path with every '.' written '_'. `native` itself is always accepted, and "-" stands for a key + * with no prefix at all. A key is tried against the longest matching spelling first. + * + * rad_lora_alias maps an adapter module that the checkpoint names differently. `from` and `to` + * are module paths relative to the root's prefixes (no ".weight"), '#' standing for a decimal + * index that `to` repeats in the same order. Rows [from_lo, from_hi) of the adapter module's + * output (its lora_B rows; from_hi 0 = all of them) land at rows from `to_lo` of the checkpoint + * module `to`. Several aliases with one `from` split a fused adapter module over separate + * checkpoint tensors (a `qkv` over `to_q`, `to_k`, `to_v`); several `from` into one `to` at + * different `to_lo` place separate adapter modules into one fused tensor. A module path that is + * the checkpoint's own needs no alias. */ +int rad_lora_root(RadBuilder* b, const char* native, const char* spellings); +int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to, + int64_t from_lo, int64_t from_hi, int64_t to_lo); + /* ================================================================== the audio generator */ /* A program that makes audio from text: an autoregressive language model writes the piece frame by * frame, with classifier-free guidance (each request runs a conditional and an unconditional diff --git a/abi/rad_format.h b/abi/rad_format.h index 73a40f99..625241d8 100644 --- a/abi/rad_format.h +++ b/abi/rad_format.h @@ -56,9 +56,16 @@ typedef struct RadFileHeader { uint64_t prof_off, prof_count; /* RadFileProfile[] -- expert popularity */ uint64_t data_off, data_bytes; /* the blob; RAD_ALIGN_POOL-aligned */ + /* reserved[RAD_HDR_AUX_VOCAB_OFF] and reserved[RAD_HDR_AUX_VOCAB_BYTES] place a second vocab + * section, laid out as the first (RadVocabHeader + its payload, its strings in the one string + * blob): a tokenizer a generator reads its prompt through beside the model's own + * (RadGeneratorDecl::aux_tokens). Both zero when there is none, as in a file written before + * the section existed; the rest are zero. */ uint64_t reserved[8]; } RadFileHeader; +enum { RAD_HDR_AUX_VOCAB_OFF = 0, RAD_HDR_AUX_VOCAB_BYTES = 1 }; + /* ------------------------------------------------------------------ metadata */ typedef struct RadFileKV { rad_stroff key; @@ -124,9 +131,17 @@ enum { RAD_TOK_BPE = 1, RAD_TOK_UNIGRAM = 2, RAD_TOK_WORDPIECE = 3, RAD_TOK_RWKV enum { RAD_NORM_NFC = 1, RAD_NORM_NFKC = 2, RAD_NORM_NFD = 3, RAD_NORM_NFKD = 4, RAD_NORM_LOWERCASE = 5, RAD_NORM_STRIP = 6, RAD_NORM_REPLACE = 7, RAD_NORM_PREPEND = 8, + RAD_NORM_PRECOMPILED = 9, RAD_PRE_BYTELEVEL = 32, RAD_PRE_SPLIT = 33, RAD_PRE_METASPACE = 34, RAD_PRE_WHITESPACE = 35, RAD_PRE_PUNCTUATION = 36, RAD_PRE_DIGITS = 37, RAD_PRE_BYTE_FALLBACK = 38, + /* BPE's end-of-word suffix (arg0, CLIP's ""): a word's last symbol carries it, so the + * merges and the vocabulary tell a word's end from its middle. */ + RAD_PRE_END_OF_WORD = 39, + /* An added token matched in the normalised text rather than the raw one (tokenizers' + * `normalized`): arg0 its spelling, iarg its id. Cut out after the normalisers and before + * the other pre-tokenisers. */ + RAD_PRE_ADDED_NORMALIZED = 40, RAD_DEC_BYTELEVEL = 64, RAD_DEC_METASPACE = 65, RAD_DEC_REPLACE = 66, RAD_DEC_STRIP = 67, RAD_DEC_FUSE = 68, RAD_DEC_BYTE_FALLBACK = 69 }; diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 912a25b4..6fde1f91 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -352,6 +352,32 @@ typedef struct RadGenBatch { const int32_t* mode_ccu; const int64_t* n_mode_h; const float* mode_rope_f; + + /* ---- appended in ABI 25 (Anima, SDXL) */ + /* COND, for a generator that reads its prompt through a second tokenizer + * (RadGeneratorDecl::aux_tokens): the user's prompt as that tokenizer encodes it, `n_aux` ids + * on the device, and `aux_cu` {0, n_aux} on the device. 0 and null otherwise. */ + int64_t n_aux; + const int32_t* aux_ids; + const int32_t* aux_cu; + /* ---- a discrete-time denoiser (RadGeneratorDecl::train_steps), DENOISE, one value per + * entry: the schedule's sigma before `sigma` (0 on an image's first step), `sigma` on the + * model's trained clock (the nearest of its timesteps, as ComfyUI conditions it), the + * request's sampler (RAD_GEN_SAMPLER_*) and the image's step, from 0. */ + const float* sigma_prev; + const float* timestep; + const int32_t* sampler; + const int32_t* step; + /* DENOISE: [n_seq, 2] each entry's image height and width in pixels, f32 (a model + * conditioned on its size); `entry_h` [n_seq, 4] the same entries on the host: the + * conditioning's rows (JOINT_STEP), the height and width in pixels, and the branch (0 the + * prompt, 1 the negative prompt), for a plugin whose ops take an image's geometry from their + * operands and so issue each entry on its own. */ + const float* size_px; + const int32_t* entry_h; + /* COND: the pass's token ids on the host ([n_tok]), for a plugin whose issue depends on + * where a window's end-of-text marker sits. */ + const int32_t* tokens_h; } RadGenBatch; /* An entry's flags on a DENOISE pass. */ diff --git a/arch/anima/CMakeLists.txt b/arch/anima/CMakeLists.txt new file mode 100644 index 00000000..b9bebe27 --- /dev/null +++ b/arch/anima/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/anima -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(anima LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(anima architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/anima.cpp) diff --git a/arch/anima/anima.cpp b/arch/anima/anima.cpp new file mode 100644 index 00000000..9a746204 --- /dev/null +++ b/arch/anima/anima.cpp @@ -0,0 +1,1367 @@ +/* anima -- Anima (CircleStone Labs and Comfy Org): text to an RGB image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt, as ComfyUI runs them (comfy/ldm/anima, comfy/ldm/cosmos/ + * predict2.py, comfy/text_encoders/anima.py): + * + * Conditioning: Qwen3-0.6B-Base reads the prompt as it is (no template), and its last hidden + * state after the final norm is the source. The LLM adapter (six blocks of 1024 wide, 16 heads of + * 64) then reads the same prompt again through T5's tokenizer: each T5 token's learned embedding + * is a query row that attends to the other T5 rows (self-attention) and to the Qwen3 rows (cross + * attention), both rotated with a 64-wide NeoX rotary at the rows' own indices, then a GELU MLP; + * an output linear and an RMS norm close it. Its rows, zero-padded to 512, are the DiT's context. + * An empty prompt is one padding token to Qwen3 and T5's alone. + * + * Denoiser: Cosmos-Predict2's MiniTrainDIT at 2B (28 blocks of 2048, 16 heads of 128). A token + * is 2 x 2 positions of the 16-channel latent (64 values, channel-major; 16 pixels a side) and + * the patch embedding reads them beside an all-zero padding-mask channel, so only its first 64 + * columns are kept (RAD_MAP_COLS). Each block: a self-attention with q/k RMS norms and a three-axis rotary over + * (frame, row, column) at 10000 x 4^(42/40) (the frame axis is 0 for an image), a cross-attention + * to the 512 context rows (q/k norms, no rotary), and a GELU MLP, each behind a LayerNorm + * without affine modulated by (shift, scale) and added back gated, `x += gate f(norm(x)(1 + scale) + * + shift)`. The modulation of each of the three is Linear(256, 6144)(Linear(2048, 256)(silu(e))) + * plus a shared AdaLN-LoRA term, `e` the RMS-normed sinusoid of the step's sigma (a timestep in + * [0, 1]) and the shared term Linear(2048, 6144)(silu(Linear(2048, 2048)(sinusoid))). + * + * Decoder: the Qwen-Image VAE (Wan 2.1's, its causal 3-D convolutions on one frame), 16 latent + * channels at 8x, read under ComfyUI's original Wan names (decoder.upsamples.N.residual.K). + * + * The model is a rectified flow (ComfyUI's FLOW at multiplier 1): the DiT predicts the velocity, + * sampled by Euler steps over ComfyUI's `simple` schedule at shift 3, guided as uncond + s (cond - + * uncond). The variant (`anima.variant` in the container, set at convert) picks the card's + * settings: Base and Aesthetic 30 steps at guidance 4 with the card's negative prompt, Turbo 10 + * steps unguided. + * + * ============================== THE CHECKPOINT ============================== + * + * ComfyUI's single files, merged by rad-convert (--add): the DiT under `net.` (Base) or + * `model.diffusion_model.` (Aesthetic 1.1, Turbo 1.1), the text encoder under `model.` and the VAE + * under its Wan names. The source names are the files' own, so a LoRA's module path (`blocks.N. + * self_attn.q_proj`) is the DiT key after its prefix. The prefix is read off the checkpoint at + * convert, and a container records it in the name of the one weight declared under it. + * + * ============================== WHAT IS QUANTISED ============================== + * + * One plugin serves bf16 and block-fp8 containers: the text encoder's linears and the DiT blocks' + * attention and MLP linears are LinearFP8s (rad_fp8.h), bf16 throughout when the first DiT + * projection is plain. The adapter, the modulation and embedding linears, the final layer and the + * VAE stay bf16. Every linear a LoRA for Anima names is a plain capable GEMM (gemm_nt or gemm_nt_q + * without rotation), its activation applied by a separate op. + * + * One card: tensor parallelism is refused. + */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace anima { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image: 1536 x 1536 pixels, 9216 latent tokens (the card's largest resolution). + * 1024 x 1024 is the default. */ +enum { kMaxImageTokens = 9216 }; +/* The context the DiT reads: the adapter's rows zero-padded to 512, as ComfyUI pads them. A prompt + * longer than that to T5 or Qwen3 is refused. */ +enum { kCondRows = 512 }; +/* Images in flight, and so the lanes of latent state. */ +enum { kMaxLanes = 8 }; +/* The adapter: six blocks over a 32128-row T5 embedding. */ +enum { kAdLayers = 6, kT5Vocab = 32128 }; +/* Qwen3's padding token: an empty prompt is this one token. */ +enum { kQwenPad = 151643 }; + +static const char* kNegative = + "worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts, " + "chromatic aberration"; + +/* Wan 2.1's latent statistics (ComfyUI's latent_formats.Wan21): x std + mean in f32. */ +static const double kLatMean[16] = { -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, + 1.5508, 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, + 0.2503, -0.2921 }; +static const double kLatStd[16] = { 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743, + 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160 }; + +/* ================================================================== the model */ +struct TeLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qn = 0, w_kn = 0; + LinearFP8 qkv{}, o{}, gate_up{}, down{}; + QuantFP8 q_h{}, q_attn{}, q_h2{}; + GateQuantFP8 gq{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_add1 = 0, op_n2 = 0, op_add2 = 0; +}; + +/* An adapter block: RMS-normed self-attention over the T5 rows, cross-attention to the Qwen3 rows + * and a GELU MLP, each added back. bf16 throughout. */ +struct AdLayer { + rad_weight w_nsa = 0, w_nca = 0, w_nmlp = 0; + rad_weight w_sqn = 0, w_skn = 0, w_cqn = 0, w_ckn = 0; + rad_weight w_sqkv = 0, w_so = 0, w_cq = 0, w_ckv = 0, w_co = 0; + rad_weight w_m1 = 0, b_m1 = 0, w_m2 = 0, b_m2 = 0; + rad_op op_nsa = 0, op_sqkv = 0, op_sqkr = 0, op_sattn = 0, op_so = 0, op_sadd = 0; + rad_op op_nca = 0, op_cq = 0, op_ckv = 0, op_cpq = 0, op_cpkv = 0, op_cqkr = 0, op_cattn = 0; + rad_op op_co = 0, op_cadd = 0; + rad_op op_nmlp = 0, op_m1 = 0, op_gelu = 0, op_m2 = 0, op_madd = 0; +}; + +/* A DiT block's three modulations and its linears. */ +struct DitLayer { + rad_weight w_qn = 0, w_kn = 0, w_cqn = 0, w_ckn = 0; + rad_weight w_mod1[3] = { 0, 0, 0 }, w_mod2[3] = { 0, 0, 0 }; + rad_op op_mod1[3] = { 0, 0, 0 }, op_mod2[3] = { 0, 0, 0 }, op_modadd[3] = { 0, 0, 0 }; + LinearFP8 qkv{}, o{}, cq{}, ck{}, cv{}, co{}, l1{}, l2{}; + QuantFP8 q_attn{}, q_cattn{}, q_ffn{}; + rad_op op_n1 = 0, op_qkr = 0, op_attn = 0; + rad_op op_n2 = 0, op_cqn = 0, op_ckn = 0, op_cattn = 0; + rad_op op_n3 = 0, op_gelu = 0; +}; + +/* Weight groups (movement units) by network. */ +enum : int { + kGrpAd = 1000, /* the adapter's blocks, kGrpAd + i; its model-level weights kGrpAd + 10 */ + kGrpVaeDec = 1200, + kGrpDit = 2000, /* the DiT's model-level weights; its blocks kGrpDit + 1.. */ +}; + +struct Model { + Names nm{""}; + Geom gt{}, ga{}, gd{}; /* the text encoder's, the adapter's and the DiT's geometry */ + int variant = 0; /* 0 base, 1 aesthetic, 2 turbo */ + std::string pre; /* the DiT's checkpoint prefix */ + + /* ---- the text encoder */ + rad_weight w_tok = 0, w_tnorm = 0; + rad_op op_embed = 0, op_tnorm = 0; + rad_buf b_tx = 0, b_tkv = 0, b_th2 = 0, b_tgu = 0, b_src = 0; + ActFP8 a_th{}, a_tattn{}, a_tffn{}; + std::vector te; + + /* ---- the adapter */ + rad_weight w_t5 = 0, w_aout = 0, b_aout = 0, w_anorm = 0; + rad_op op_t5 = 0, op_pos = 0, op_fill = 0, op_aout = 0, op_anorm = 0, op_ctxz = 0; + rad_op op_store = 0; + rad_buf b_ax = 0, b_ah = 0, b_aqkv = 0, b_aq = 0, b_akv = 0, b_aattn = 0, b_ab = 0, b_am = 0; + rad_buf b_apos = 0, b_ctx = 0; + std::vector ad; + + /* ---- the timestep and the modulations */ + rad_weight w_t1 = 0, w_t2 = 0, w_temb_norm = 0, w_f1 = 0, w_f2 = 0; + rad_op op_temb = 0, op_t1 = 0, op_tsilu = 0, op_t2 = 0, op_tnormed = 0, op_esilu = 0; + rad_op op_f1 = 0, op_f2 = 0, op_fadd = 0; + rad_buf b_tproj = 0, b_t1 = 0, b_t1s = 0, b_lora = 0, b_emb = 0, b_esilu = 0, b_mh = 0; + rad_buf b_mods = 0, b_mod1 = 0, b_fh = 0, b_fmod = 0; + + /* ---- the DiT */ + int64_t C = 64; /* latent values a token */ + rad_weight w_xemb = 0, w_final = 0; + rad_op op_randn = 0, op_lgather = 0, op_xemb = 0, op_cgather = 0; + rad_op op_g3 = 0, op_fn = 0, op_final = 0, op_euler = 0; + rad_buf b_lat = 0, b_h = 0, b_qkv = 0, b_cq = 0, b_ck = 0, b_cv = 0, b_ao = 0, b_l1 = 0; + rad_buf b_fz = 0, b_v = 0; + ActFP8 a_hm{}, a_attn{}, a_ffn{}, a_ctx{}; + std::vector dit; + LinearFP8 qkv0{}; + QuantFP8 q_ctx{}; + + /* ---- the per-image state and the conditioning store (PERSIST) */ + rad_buf b_state = 0, b_prev = 0, b_store = 0; + + /* ---- the VAE */ + Vae dec{}; + VImg dec_out{}; + rad_buf b_dl = 0, b_decin = 0, b_cu4 = 0, b_img = 0; + rad_op op_dnorm = 0, op_dzero = 0, op_unpack = 0, op_cu4 = 0, op_rgb = 0; + std::string mul, add; +}; + +static Model g_model[MAX_RANKS]; + +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int access, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A plain bf16 linear without a bias: gemm_nt, the activation a separate op. `src` is one + * checkpoint name, or several stacked along dim 0. */ +static rad_op dense(RadBuilder* b, const char* dn, std::initializer_list src, + int64_t N, int64_t K, int64_t rows, rad_buf in, rad_buf out, rad_weight* w, + int access, int group, std::initializer_list parts = {}) { + if (map_linear(b, dn, src) < 0) return 0; + *w = decl_w(b, dn, RAD_BF16, { N, K }, access, RAD_SHARD_NONE, grp_layer(group), 0, parts); + if (!*w) return 0; + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w)), + { in }, { out }); +} + +/* A bf16 linear with a bias. */ +static rad_op dense_bias(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t N, + int64_t K, int64_t rows, rad_buf in, rad_buf out, rad_weight* w, + rad_weight* bias, int access, int group) { + *w = wcopy(b, nm.f("%s.weight", dn), nm.ckpt("%s.weight", src), RAD_BF16, { N, K }, access, + group); + *bias = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { N }, access, group); + if (!*w || !*bias) return 0; + return rw(b, RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(*w, *bias)), + { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, + rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +/* An RMS norm with a gain, `rows` rows of `n`. */ +static rad_op rms(RadBuilder* b, int64_t rows, int64_t n, double eps, rad_weight w, rad_buf x, + rad_buf y) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +/* ================================================================== check_format */ +static int check_format(const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (rad_meta_geti(meta, "num_hidden_layers", 0) != 28 || + rad_meta_geti(meta, "hidden_size", 0) != 1024) { + fprintf(stderr, "radiance: anima: the text encoder must be Qwen3-0.6B (28 layers of " + "1024); convert with --config naming the directory of Qwen3-0.6B-Base's " + "config.json\n"); + return RAD_E_UNSUPPORTED; + } + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: anima: a 2B model served on one card; --tp %d is not " + "supported\n", ctx->world_size); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== declare */ +/* Qwen3-0.6B over the prompt: every layer, then the final norm, into `b_src`. */ +static int declare_te(RadBuilder* b, Model& m) { + Geom& g = m.gt; + Names& nm = m.nm; + const int64_t T = kCondRows; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + + RAD_ARCH_TRY(map_copy(b, nm.f("te.token_embd.weight"), nm.ckpt("model.embed_tokens.weight"))); + m.w_tok = decl_w(b, nm.f("te.token_embd.weight"), RAD_BF16, { g.n_vocab_all, g.n_embd }, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + m.b_tx = decl_b(b, nm.f("te.x"), RAD_BF16, { T, g.n_embd }); + m.a_th.x = decl_b(b, nm.f("te.h"), RAD_BF16, { T, g.n_embd }); + RAD_ARCH_TRY(m.a_th.declare_qs(b, nm, g, "te.h", g.n_embd, T)); + m.b_tkv = decl_b(b, nm.f("te.qkv"), RAD_BF16, { T, q_dim + 2 * kv_dim }); + m.a_tattn.x = decl_b(b, nm.f("te.attn"), RAD_BF16, { T, q_dim }); + RAD_ARCH_TRY(m.a_tattn.declare_qs(b, nm, g, "te.attn", q_dim, T)); + m.b_th2 = decl_b(b, nm.f("te.h2"), RAD_BF16, { T, g.n_embd }); + m.b_tgu = decl_b(b, nm.f("te.gate_up"), RAD_BF16, { T, 2 * g.n_ff }); + m.a_tffn.x = decl_b(b, nm.f("te.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_tffn.declare_qs(b, nm, g, "te.ffn", g.n_ff, T)); + m.b_src = decl_b(b, nm.f("te.out"), RAD_BF16, { T, g.n_embd }); + + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab_all), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_tok)), + {}, { m.b_tx }); + m.te.resize((size_t)g.n_layer); + for (int l = 0; l < (int)g.n_layer; ++l) { + TeLayer& L = m.te[(size_t)l]; + const char* lp = nm.ckpt("model.layers.%d", l); + L.w_n1 = wcopy(b, nm.f("te.blk.%d.attn_norm.weight", l), + nm.ckpt("%s.input_layernorm.weight", lp), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, l); + L.w_n2 = wcopy(b, nm.f("te.blk.%d.ffn_norm.weight", l), + nm.ckpt("%s.post_attention_layernorm.weight", lp), RAD_F32, { g.n_embd }, + RAD_ACCESS_PER_TOKEN, l); + L.w_qn = wcopy(b, nm.f("te.blk.%d.q_norm.weight", l), + nm.ckpt("%s.self_attn.q_norm.weight", lp), RAD_BF16, { g.head_dim }, + RAD_ACCESS_PER_TOKEN, l); + L.w_kn = wcopy(b, nm.f("te.blk.%d.k_norm.weight", l), + nm.ckpt("%s.self_attn.k_norm.weight", lp), RAD_BF16, { g.head_dim }, + RAD_ACCESS_PER_TOKEN, l); + if (!L.w_n1 || !L.w_n2 || !L.w_qn || !L.w_kn) return RAD_E_INVAL; + L.op_n1 = rms(b, T, g.n_embd, g.eps, L.w_n1, m.b_tx, m.a_th.x); + RAD_ARCH_TRY(L.q_h.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.qkv.declare(b, nm, g, nm.f("te.blk.%d.attn_qkv", l), q_dim + 2 * kv_dim, + g.n_embd, RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.self_attn.q_proj.weight", lp), + nm.ckpt("%s.self_attn.k_proj.weight", lp), + nm.ckpt("%s.self_attn.v_proj.weight", lp) }, + m.a_th, m.b_tkv, T, { q_dim, kv_dim, kv_dim })); + L.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_INT("rotary_dim", g.head_dim)), + RAD_WEIGHTS(L.w_qn, L.w_kn)), + { m.b_tkv }, { m.b_tkv }); + L.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)g.head_dim)), + RAD_INT("max_seqlen", T)), + RAD_NOWEIGHTS), + { m.b_tkv }, { m.a_tattn.x }); + RAD_ARCH_TRY(L.q_attn.declare(b, g, m.a_tattn, q_dim)); + RAD_ARCH_TRY(L.o.declare(b, nm, g, nm.f("te.blk.%d.attn_output", l), g.n_embd, q_dim, + RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.self_attn.o_proj.weight", lp) }, m.a_tattn, m.b_th2, + T)); + L.op_add1 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + L.op_n2 = rms(b, T, g.n_embd, g.eps, L.w_n2, m.b_tx, m.a_th.x); + RAD_ARCH_TRY(L.q_h2.declare(b, g, m.a_th, g.n_embd)); + RAD_ARCH_TRY(L.gate_up.declare(b, nm, g, nm.f("te.blk.%d.ffn_gate_up", l), 2 * g.n_ff, + g.n_embd, RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.mlp.gate_proj.weight", lp), + nm.ckpt("%s.mlp.up_proj.weight", lp) }, + m.a_th, m.b_tgu, T, { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(L.gq.declare(b, g, m.b_tgu, m.a_tffn, g.n_ff, "silu", T, true)); + RAD_ARCH_TRY(L.down.declare(b, nm, g, nm.f("te.blk.%d.ffn_down", l), g.n_embd, g.n_ff, + RAD_SHARD_NONE, grp_layer(l), + { nm.ckpt("%s.mlp.down_proj.weight", lp) }, m.a_tffn, m.b_th2, + T)); + L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2) + return RAD_E_INVAL; + } + m.w_tnorm = wcopy(b, nm.f("te.output_norm.weight"), nm.ckpt("model.norm.weight"), RAD_F32, + { g.n_embd }, RAD_ACCESS_PER_TOKEN, (int)g.n_layer - 1); + m.op_tnorm = rms(b, T, g.n_embd, g.eps, m.w_tnorm, m.b_tx, m.b_src); + return m.op_embed && m.w_tnorm && m.op_tnorm ? RAD_OK : RAD_E_INVAL; +} + +/* The LLM adapter: the T5 rows' embeddings through six blocks, the output linear and norm, into + * the 512 context rows (zero past the prompt's) and from there into every lane's store at this + * branch. Its cross-attention lays q (the T5 rows), k and v (the Qwen3 rows) side by side in one + * [q | k | v] row so one qk_norm_rope rotates each at its own row index. */ +static int declare_adapter(RadBuilder* b, Model& m) { + Geom& g = m.ga; + Names& nm = m.nm; + const char* P = m.pre.c_str(); + const int64_t R = kCondRows, D = g.n_embd, hd = g.head_dim, F = g.n_ff_all; + const int acc = RAD_ACCESS_PER_REQUEST; + const double eps = 1e-6; + const int gm = kGrpAd + 10; + + RAD_ARCH_TRY(map_copy(b, nm.f("ad.embed.weight"), nm.ckpt("%sllm_adapter.embed.weight", P))); + m.w_t5 = decl_w(b, nm.f("ad.embed.weight"), RAD_BF16, { kT5Vocab, D }, acc, RAD_SHARD_NONE, + grp_layer(gm)); + m.b_ax = decl_b(b, nm.f("ad.x"), RAD_BF16, { R, D }); + m.b_ah = decl_b(b, nm.f("ad.h"), RAD_BF16, { R, D }); + m.b_aqkv = decl_b(b, nm.f("ad.qkv"), RAD_BF16, { R, 3 * D }); + m.b_aq = decl_b(b, nm.f("ad.q"), RAD_BF16, { R, D }); + m.b_akv = decl_b(b, nm.f("ad.kv"), RAD_BF16, { R, 2 * D }); + m.b_aattn = decl_b(b, nm.f("ad.attn"), RAD_BF16, { R, D }); + m.b_ab = decl_b(b, nm.f("ad.branch"), RAD_BF16, { R, D }); + m.b_am = decl_b(b, nm.f("ad.mlp"), RAD_BF16, { R, F }); + m.b_apos = decl_b(b, nm.f("ad.pos"), RAD_I32, { R }); + m.b_ctx = decl_b(b, nm.f("ad.ctx"), RAD_BF16, { R, D }); + + m.op_t5 = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n_embd", D), + RAD_INT("n_vocab", kT5Vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(m.w_t5)), + {}, { m.b_ax }); + m.op_pos = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("start", 0), + RAD_INT("step", 1)), + RAD_NOWEIGHTS), + {}, { m.b_apos }); + /* The [q | k | v] rows past either side's count are read by the norm and rotary and never by + * the attention; zeroed once so they are finite. */ + m.op_fill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 3 * D), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_aqkv }); + if (!m.w_t5 || !m.op_t5 || !m.op_pos || !m.op_fill) return RAD_E_INVAL; + + auto qk_rope = [&](rad_weight qn, rad_weight kn) { + return rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", 10000.0), RAD_F64("eps", eps), + RAD_INT("rotary_dim", hd)), + RAD_WEIGHTS(qn, kn)), + { m.b_aqkv, m.b_apos }, { m.b_aqkv }); + }; + auto gather = [&](rad_buf src, rad_buf dst) { + return rw(b, RAD_OP(b, "gather_rows2", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { src, m.b_apos, dst }, { dst }); + }; + + m.ad.resize(kAdLayers); + for (int i = 0; i < kAdLayers; ++i) { + AdLayer& L = m.ad[(size_t)i]; + const int grp = kGrpAd + i; + const char* pre = nm.ckpt("%sllm_adapter.blocks.%d", P, i); + const char* dn = nm.f("ad.blk.%d", i); + L.w_nsa = wcopy(b, nm.f("%s.norm_sa.weight", dn), nm.ckpt("%s.norm_self_attn.weight", pre), + RAD_BF16, { D }, acc, grp); + L.w_nca = wcopy(b, nm.f("%s.norm_ca.weight", dn), nm.ckpt("%s.norm_cross_attn.weight", pre), + RAD_BF16, { D }, acc, grp); + L.w_nmlp = wcopy(b, nm.f("%s.norm_mlp.weight", dn), nm.ckpt("%s.norm_mlp.weight", pre), + RAD_BF16, { D }, acc, grp); + L.w_sqn = wcopy(b, nm.f("%s.sa_q_norm.weight", dn), + nm.ckpt("%s.self_attn.q_norm.weight", pre), RAD_BF16, { hd }, acc, grp); + L.w_skn = wcopy(b, nm.f("%s.sa_k_norm.weight", dn), + nm.ckpt("%s.self_attn.k_norm.weight", pre), RAD_BF16, { hd }, acc, grp); + L.w_cqn = wcopy(b, nm.f("%s.ca_q_norm.weight", dn), + nm.ckpt("%s.cross_attn.q_norm.weight", pre), RAD_BF16, { hd }, acc, grp); + L.w_ckn = wcopy(b, nm.f("%s.ca_k_norm.weight", dn), + nm.ckpt("%s.cross_attn.k_norm.weight", pre), RAD_BF16, { hd }, acc, grp); + if (!L.w_nsa || !L.w_nca || !L.w_nmlp || !L.w_sqn || !L.w_skn || !L.w_cqn || !L.w_ckn) + return RAD_E_INVAL; + /* ---- self-attention over the T5 rows */ + L.op_nsa = rms(b, R, D, eps, L.w_nsa, m.b_ax, m.b_ah); + L.op_sqkv = dense(b, nm.f("%s.sa_qkv.weight", dn), + { nm.ckpt("%s.self_attn.q_proj.weight", pre), + nm.ckpt("%s.self_attn.k_proj.weight", pre), + nm.ckpt("%s.self_attn.v_proj.weight", pre) }, + 3 * D, D, R, m.b_ah, m.b_aqkv, &L.w_sqkv, acc, grp, { D, D, D }); + L.op_sqkr = qk_rope(L.w_sqn, L.w_skn); + L.op_sattn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_aqkv }, { m.b_aattn }); + L.op_so = dense(b, nm.f("%s.sa_o.weight", dn), { nm.ckpt("%s.self_attn.o_proj.weight", pre) }, + D, D, R, m.b_aattn, m.b_ab, &L.w_so, acc, grp); + L.op_sadd = add_op(b, R, D, m.b_ax, m.b_ab, m.b_ax); + /* ---- cross-attention to the Qwen3 rows */ + L.op_nca = rms(b, R, D, eps, L.w_nca, m.b_ax, m.b_ah); + L.op_cq = dense(b, nm.f("%s.ca_q.weight", dn), { nm.ckpt("%s.cross_attn.q_proj.weight", pre) }, + D, D, R, m.b_ah, m.b_aq, &L.w_cq, acc, grp); + L.op_ckv = dense(b, nm.f("%s.ca_kv.weight", dn), + { nm.ckpt("%s.cross_attn.k_proj.weight", pre), + nm.ckpt("%s.cross_attn.v_proj.weight", pre) }, + 2 * D, m.gt.n_embd, R, m.b_src, m.b_akv, &L.w_ckv, acc, grp, { D, D }); + L.op_cpq = gather(m.b_aq, m.b_aqkv); + L.op_cpkv = rw(b, RAD_OP(b, "gather_rows2", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 2 * D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_akv, m.b_apos, m.b_aqkv }, { m.b_aqkv }); + L.op_cqkr = qk_rope(L.w_cqn, L.w_ckn); + L.op_cattn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_aqkv }, { m.b_aattn }); + L.op_co = dense(b, nm.f("%s.ca_o.weight", dn), { nm.ckpt("%s.cross_attn.o_proj.weight", pre) }, + D, D, R, m.b_aattn, m.b_ab, &L.w_co, acc, grp); + L.op_cadd = add_op(b, R, D, m.b_ax, m.b_ab, m.b_ax); + /* ---- the MLP */ + L.op_nmlp = rms(b, R, D, eps, L.w_nmlp, m.b_ax, m.b_ah); + L.op_m1 = dense_bias(b, nm, nm.f("%s.mlp1", dn), nm.ckpt("%s.mlp.0", pre), F, D, R, m.b_ah, + m.b_am, &L.w_m1, &L.b_m1, acc, grp); + L.op_gelu = unary(b, "gelu", R, F, m.b_am, m.b_am); + L.op_m2 = dense_bias(b, nm, nm.f("%s.mlp2", dn), nm.ckpt("%s.mlp.2", pre), D, F, R, m.b_am, + m.b_ab, &L.w_m2, &L.b_m2, acc, grp); + L.op_madd = add_op(b, R, D, m.b_ax, m.b_ab, m.b_ax); + if (!L.op_nsa || !L.op_sqkv || !L.op_sqkr || !L.op_sattn || !L.op_so || !L.op_sadd || + !L.op_nca || !L.op_cq || !L.op_ckv || !L.op_cpq || !L.op_cpkv || !L.op_cqkr || + !L.op_cattn || !L.op_co || !L.op_cadd || !L.op_nmlp || !L.op_m1 || !L.op_gelu || + !L.op_m2 || !L.op_madd) + return RAD_E_INVAL; + } + m.op_aout = dense_bias(b, nm, nm.f("ad.out"), nm.ckpt("%sllm_adapter.out_proj", P), D, D, R, + m.b_ax, m.b_ah, &m.w_aout, &m.b_aout, acc, gm); + m.w_anorm = wcopy(b, nm.f("ad.norm.weight"), nm.ckpt("%sllm_adapter.norm.weight", P), RAD_BF16, + { D }, acc, gm); + m.op_ctxz = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_ctx }); + m.op_anorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", D), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_anorm)), + { m.b_ah, m.b_ctx }, { m.b_ctx }); + /* Lane l's branch b at rows (2 l + b) kCondRows: the store's `stride` is two branches. */ + m.op_store = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", D), + RAD_INT("stride", 2 * (int64_t)kCondRows), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ctx, m.b_store }, { m.b_store }); + return m.op_aout && m.w_anorm && m.op_ctxz && m.op_anorm && m.op_store ? RAD_OK : RAD_E_INVAL; +} + +/* The final linear's rows reordered from the DiT's (row, column, channel) unpatchify order to the + * lane state's channel-major one: state value c 4 + k is output row k 16 + c. Eight ROWS maps of + * eight one-row pieces, joined in call order. */ +static int map_final(RadBuilder* b, const char* declared, const char* src, int64_t C) { + const int64_t ch = C / 4; + for (int64_t t0 = 0; t0 < C; t0 += 8) { + RadNameMap mp = map_base(declared, RAD_MAP_ROWS); + for (int64_t t = t0; t < t0 + 8 && t < C; ++t) { + const int64_t c = t / 4, k = t % 4; + mp.src[mp.n_src] = src; + mp.src_index[mp.n_src] = (int)(k * ch + c); + mp.src_rows[mp.n_src] = 1; + ++mp.n_src; + } + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + } + return RAD_OK; +} + +/* The step's timestep embedding and every modulation: the shared AdaLN-LoRA term, the normed + * embedding, each block's three (shift | scale | gate) rows into its columns of `mods`, and the + * final layer's (shift | scale). All `S` rows, one an entry. */ +static int declare_mod(RadBuilder* b, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const char* P = m.pre.c_str(); + const int64_t S = g.max_seqs, D = g.n_embd, L = g.n_layer, M3 = 3 * D; + const int64_t R = 256; /* AdaLN-LoRA's rank */ + const int acc = RAD_ACCESS_PER_TOKEN; + const int gx = kGrpDit; + m.b_tproj = decl_b(b, nm.f("dit.tproj"), RAD_BF16, { S, D }); + m.b_t1 = decl_b(b, nm.f("dit.t1"), RAD_BF16, { S, D }); + m.b_t1s = decl_b(b, nm.f("dit.t1s"), RAD_BF16, { S, D }); + m.b_lora = decl_b(b, nm.f("dit.adaln_lora"), RAD_BF16, { S, M3 }); + m.b_emb = decl_b(b, nm.f("dit.temb"), RAD_BF16, { S, D }); + m.b_esilu = decl_b(b, nm.f("dit.temb_silu"), RAD_BF16, { S, D }); + m.b_mh = decl_b(b, nm.f("dit.mod_h"), RAD_BF16, { S, R }); + m.b_mods = decl_b(b, nm.f("dit.mods"), RAD_BF16, { S, L * 3 * M3 }); + m.b_fh = decl_b(b, nm.f("dit.fmod_raw"), RAD_BF16, { S, 2 * D }); + m.b_fmod = decl_b(b, nm.f("dit.fmod"), RAD_BF16, { S, 2 * D }); + m.b_mod1 = decl_b(b, nm.f("dit.mod_one"), RAD_BF16, { S, M3 }); + const rad_buf mod1 = m.b_mod1; + + m.op_temb = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_tproj }); + m.op_t1 = dense(b, nm.f("dit.t_embed1.weight"), { nm.ckpt("%st_embedder.1.linear_1.weight", P) }, + D, D, S, m.b_tproj, m.b_t1, &m.w_t1, acc, gx); + m.op_tsilu = unary(b, "silu", S, D, m.b_t1, m.b_t1s); + m.op_t2 = dense(b, nm.f("dit.t_embed2.weight"), { nm.ckpt("%st_embedder.1.linear_2.weight", P) }, + M3, D, S, m.b_t1s, m.b_lora, &m.w_t2, acc, gx); + m.op_tnormed = rms(b, S, D, 1e-6, m.w_temb_norm, m.b_tproj, m.b_emb); + m.op_esilu = unary(b, "silu", S, D, m.b_emb, m.b_esilu); + if (!m.op_temb || !m.op_t1 || !m.op_tsilu || !m.op_t2 || !m.op_tnormed || !m.op_esilu) + return RAD_E_INVAL; + + static const char* kMods[3] = { "self_attn", "cross_attn", "mlp" }; + for (int64_t l = 0; l < L; ++l) { + DitLayer& B = m.dit[(size_t)l]; + const int grp = kGrpDit + 1 + (int)l; + for (int k = 0; k < 3; ++k) { + const char* src = nm.ckpt("%sblocks.%d.adaln_modulation_%s", P, (int)l, kMods[k]); + B.op_mod1[k] = dense(b, nm.f("dit.blk.%d.mod_%s.1.weight", (int)l, kMods[k]), + { nm.ckpt("%s.1.weight", src) }, R, D, S, m.b_esilu, m.b_mh, + &B.w_mod1[k], acc, grp); + B.op_mod2[k] = dense(b, nm.f("dit.blk.%d.mod_%s.2.weight", (int)l, kMods[k]), + { nm.ckpt("%s.2.weight", src) }, M3, R, S, m.b_mh, mod1, + &B.w_mod2[k], acc, grp); + B.op_modadd[k] = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", M3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { mod1, m.b_lora }, { m.b_mods }); + if (!B.op_mod1[k] || !B.op_mod2[k] || !B.op_modadd[k]) return RAD_E_INVAL; + } + } + m.op_f1 = dense(b, nm.f("dit.final.mod.1.weight"), + { nm.ckpt("%sfinal_layer.adaln_modulation.1.weight", P) }, R, D, S, m.b_esilu, + m.b_mh, &m.w_f1, acc, gx); + m.op_f2 = dense(b, nm.f("dit.final.mod.2.weight"), + { nm.ckpt("%sfinal_layer.adaln_modulation.2.weight", P) }, 2 * D, R, S, m.b_mh, + m.b_fh, &m.w_f2, acc, gx); + m.op_fadd = add_op(b, S, 2 * D, m.b_fh, m.b_lora, m.b_fmod); + return m.op_f1 && m.op_f2 && m.op_fadd ? RAD_OK : RAD_E_INVAL; +} + +static int declare_dit(RadBuilder* b, Model& m) { + Geom& g = m.gd; + Names& nm = m.nm; + const char* P = m.pre.c_str(); + const int64_t T = g.max_tok; + const int64_t D = g.n_embd, hd = g.head_dim, qd = g.q_dim(), C = m.C, L = g.n_layer; + const int64_t Dc = m.ga.n_embd; /* the context's width */ + const double eps = 1e-6; + const int gx = kGrpDit; + const int64_t NI = std::min(T, 2 * (int64_t)kMaxImageTokens); + + /* ---- the input rows: the images' latents a lane at a time through the patch embedding, and + * every entry's context rows out of the store */ + m.b_lat = decl_b(b, nm.f("dit.lat"), RAD_BF16, { NI, C }); + m.b_h = decl_b(b, nm.f("dit.h"), RAD_BF16, { T, D }); + m.op_randn = rw(b, RAD_OP(b, "randn_lanes", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state }); + m.op_lgather = rw(b, RAD_OP(b, "lane_gather", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_lat }); + { + const char* dn = nm.f("dit.x_embed.weight"); + RadNameMap mp = map_base(dn, RAD_MAP_COLS); + mp.n_src = 1; + mp.src[0] = nm.ckpt("%sx_embedder.proj.1.weight", P); + mp.src_index[0] = 0; + mp.src_rows[0] = C; + RAD_ARCH_TRY(rad_decl_name_map(b, &mp)); + m.w_xemb = decl_w(b, dn, RAD_BF16, { D, C }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(gx)); + if (!m.w_xemb) return RAD_E_INVAL; + m.op_xemb = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("N", D), RAD_INT("K", C), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_xemb)), + { m.b_lat }, { m.b_h }); + } + m.a_ctx.x = decl_b(b, nm.f("dit.ctx"), RAD_BF16, { T, Dc }); + RAD_ARCH_TRY(m.a_ctx.declare_qs(b, nm, g, "dit.ctx", Dc)); + m.op_cgather = rw(b, RAD_OP(b, "gather_rows2", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", Dc), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_store }, { m.a_ctx.x }); + RAD_ARCH_TRY(m.q_ctx.declare(b, g, m.a_ctx, Dc)); + if (!m.op_randn || !m.op_lgather || !m.op_xemb || !m.op_cgather) return RAD_E_INVAL; + + /* ---- the blocks */ + m.a_hm.x = decl_b(b, nm.f("dit.hm"), RAD_BF16, { T, D }); + RAD_ARCH_TRY(m.a_hm.declare_qs(b, nm, g, "dit.hm", D)); + m.b_qkv = decl_b(b, nm.f("dit.qkv"), RAD_BF16, { T, 3 * qd }); + m.a_attn.x = decl_b(b, nm.f("dit.attn"), RAD_BF16, { T, qd }); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "dit.attn", qd)); + m.b_ao = decl_b(b, nm.f("dit.ao"), RAD_BF16, { T, D }); + m.b_cq = decl_b(b, nm.f("dit.cq"), RAD_BF16, { T, qd }); + m.b_ck = decl_b(b, nm.f("dit.ck"), RAD_BF16, { T, qd }); + m.b_cv = decl_b(b, nm.f("dit.cv"), RAD_BF16, { T, qd }); + m.b_l1 = decl_b(b, nm.f("dit.l1"), RAD_BF16, { T, g.n_ff }); + m.a_ffn.x = decl_b(b, nm.f("dit.ffn"), RAD_BF16, { T, g.n_ff }); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "dit.ffn", g.n_ff)); + + /* Cosmos's rotary: of the 64 frequency pairs 22 turn with the frame, 21 with the row and 21 + * with the column, NeoX pairs over the head; the row and column ladders at 10000 scaled by + * the extrapolation ratio 4 to the power 42 / 40. The frame is 0 for an image, so its + * section's base does not matter. */ + const int64_t dim_h = hd / 6 * 2, dim_t = hd - 2 * dim_h; + const char* sections = nm.f("%lld %lld %lld", (long long)dim_t / 2, (long long)dim_h / 2, + (long long)dim_h / 2); + const double theta = 10000.0 * std::pow(4.0, (double)dim_h / (double)(dim_h - 2)); + + /* The modulated LayerNorm (no affine), gated by the branch before it when `gated`, into the + * next linear's input: codes for fp8, the bf16 plane for bf16. */ + auto mod_norm = [&](bool gated) { + const bool q = !g.w_bf16; + rad_op op = q ? RAD_OP(b, "rms_mod_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS) + : RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("gated", gated ? 1 : 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS); + if (!op) return op; + rad_buf rd[3] = { m.b_mods, m.b_h, m.b_ao }; + rad_buf wq[3] = { m.a_hm.q, m.a_hm.s, m.b_h }; + rad_buf wb[2] = { m.a_hm.x, m.b_h }; + rad_op_reads(b, op, rd, gated ? 3 : 2); + if (q) rad_op_writes(b, op, wq, 3); + else rad_op_writes(b, op, wb, 2); + return op; + }; + /* A per-head RMS norm in place: [rows, heads * hd] read as [rows heads, hd]. */ + auto head_norm = [&](rad_weight w, rad_buf x) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, T * g.n_head), RAD_INT("n", hd), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { x }); + }; + + for (int64_t l = 0; l < L; ++l) { + DitLayer& B = m.dit[(size_t)l]; + const int li = (int)l; + const int grp = kGrpDit + 1 + li; + const char* pre = nm.ckpt("%sblocks.%d", P, li); + const char* dn = nm.f("dit.blk.%d", li); + B.w_qn = wcopy(b, nm.f("%s.q_norm.weight", dn), nm.ckpt("%s.self_attn.q_norm.weight", pre), + RAD_BF16, { hd }, RAD_ACCESS_PER_TOKEN, grp); + B.w_kn = wcopy(b, nm.f("%s.k_norm.weight", dn), nm.ckpt("%s.self_attn.k_norm.weight", pre), + RAD_BF16, { hd }, RAD_ACCESS_PER_TOKEN, grp); + B.w_cqn = wcopy(b, nm.f("%s.cq_norm.weight", dn), + nm.ckpt("%s.cross_attn.q_norm.weight", pre), RAD_BF16, { hd }, + RAD_ACCESS_PER_TOKEN, grp); + B.w_ckn = wcopy(b, nm.f("%s.ck_norm.weight", dn), + nm.ckpt("%s.cross_attn.k_norm.weight", pre), RAD_BF16, { hd }, + RAD_ACCESS_PER_TOKEN, grp); + if (!B.w_qn || !B.w_kn || !B.w_cqn || !B.w_ckn) return RAD_E_INVAL; + + /* ---- self-attention */ + B.op_n1 = mod_norm(l > 0); + if (l == 0) B.qkv = m.qkv0; + RAD_ARCH_TRY(B.qkv.declare(b, nm, g, nm.f("%s.attn_qkv", dn), 3 * qd, D, RAD_SHARD_NONE, + grp_layer(grp), + { nm.ckpt("%s.self_attn.q_proj.weight", pre), + nm.ckpt("%s.self_attn.k_proj.weight", pre), + nm.ckpt("%s.self_attn.v_proj.weight", pre) }, + m.a_hm, m.b_qkv, 0, { qd, qd, qd })); + B.op_qkr = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "axial"), RAD_INT("rotary_dim", hd), + RAD_STR("sections", sections)), + RAD_WEIGHTS(B.w_qn, B.w_kn)), + { m.b_qkv }, { m.b_qkv }); + B.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_qkv }, { m.a_attn.x }); + RAD_ARCH_TRY(B.q_attn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.o.declare(b, nm, g, nm.f("%s.attn_output", dn), D, qd, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.self_attn.output_proj.weight", pre) }, + m.a_attn, m.b_ao)); + + /* ---- cross-attention to the context */ + B.op_n2 = mod_norm(true); + RAD_ARCH_TRY(B.cq.declare(b, nm, g, nm.f("%s.cross_q", dn), qd, D, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.cross_attn.q_proj.weight", pre) }, + m.a_hm, m.b_cq)); + RAD_ARCH_TRY(B.ck.declare(b, nm, g, nm.f("%s.cross_k", dn), qd, Dc, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.cross_attn.k_proj.weight", pre) }, + m.a_ctx, m.b_ck)); + RAD_ARCH_TRY(B.cv.declare(b, nm, g, nm.f("%s.cross_v", dn), qd, Dc, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.cross_attn.v_proj.weight", pre) }, + m.a_ctx, m.b_cv)); + B.op_cqn = head_norm(B.w_cqn, m.b_cq); + B.op_ckn = head_norm(B.w_ckn, m.b_ck); + B.op_cattn = rw(b, RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)hd))), + RAD_NOWEIGHTS), + { m.b_cq, m.b_ck, m.b_cv }, { m.a_attn.x }); + RAD_ARCH_TRY(B.q_cattn.declare(b, g, m.a_attn, qd)); + RAD_ARCH_TRY(B.co.declare(b, nm, g, nm.f("%s.cross_output", dn), D, qd, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.cross_attn.output_proj.weight", pre) }, + m.a_attn, m.b_ao)); + + /* ---- the MLP: layer1, an exact GELU, layer2 */ + B.op_n3 = mod_norm(true); + RAD_ARCH_TRY(B.l1.declare(b, nm, g, nm.f("%s.mlp_layer1", dn), g.n_ff, D, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.mlp.layer1.weight", pre) }, m.a_hm, + m.b_l1)); + B.op_gelu = unary(b, "gelu", T, g.n_ff, m.b_l1, m.a_ffn.x); + RAD_ARCH_TRY(B.q_ffn.declare(b, g, m.a_ffn, g.n_ff)); + RAD_ARCH_TRY(B.l2.declare(b, nm, g, nm.f("%s.mlp_layer2", dn), D, g.n_ff, RAD_SHARD_NONE, + grp_layer(grp), { nm.ckpt("%s.mlp.layer2.weight", pre) }, m.a_ffn, + m.b_ao)); + if (!B.op_n1 || !B.op_qkr || !B.op_attn || !B.op_n2 || !B.op_cqn || !B.op_ckn || + !B.op_cattn || !B.op_n3 || !B.op_gelu) + return RAD_E_INVAL; + } + + /* ---- the output: the last MLP gated in, the final modulated norm and linear, the sampler's + * step */ + m.b_fz = decl_b(b, nm.f("dit.fz"), RAD_BF16, { NI, D }); + m.b_v = decl_b(b, nm.f("dit.v"), RAD_BF16, { NI, C }); + m.op_g3 = rw(b, RAD_OP(b, "gate_add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_NOWEIGHTS), + { m.b_ao, m.b_mods, m.b_h }, { m.b_h }); + m.op_fn = rw(b, RAD_OP(b, "rms_mod", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", D), RAD_F64("eps", eps), + RAD_INT("gated", 0), RAD_STR("dtype", "bf16"), + RAD_STR("norm", "layer")), + RAD_NOWEIGHTS), + { m.b_fmod, m.b_h }, { m.b_h, m.b_fz }); + { + const char* dn = nm.f("dit.final.weight"); + RAD_ARCH_TRY(map_final(b, dn, nm.ckpt("%sfinal_layer.linear.weight", P), C)); + m.w_final = decl_w(b, dn, RAD_BF16, { C, D }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(gx)); + if (!m.w_final) return RAD_E_INVAL; + m.op_final = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("N", C), RAD_INT("K", D), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_final)), + { m.b_fz }, { m.b_v }); + } + m.op_euler = rw(b, RAD_OP(b, "flow_euler", + RAD_PARAMS(RAD_RANGE("M", 1, NI), RAD_INT("n", C), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_v, m.b_state, m.b_prev }, { m.b_state, m.b_prev }); + return m.op_g3 && m.op_fn && m.op_final && m.op_euler ? RAD_OK : RAD_E_INVAL; +} + +/* Wan 2.1's residual block under its own names: residual.0 (norm), .2 (conv), .3 (norm), .6 + * (conv), plus the input or its 1x1x1 `shortcut`. */ +static VImg wan_resblock(Vae& v, const VImg& x, int64_t out, const char* ckpt) { + Names& nm = *v.nm; + VImg h = x; + if (x.ch != out) h = v.conv(x, out, 1, 1, 1, "same", nm.f("%s.shortcut", ckpt)); + VImg t = v.norm(x, true, nm.f("%s.residual.0", ckpt), 4); + t = v.conv(t, out, 3, 1, 1, "same", nm.f("%s.residual.2", ckpt)); + t = v.norm(t, true, nm.f("%s.residual.3", ckpt), 4); + t = v.conv(t, out, 3, 1, 1, "same", nm.f("%s.residual.6", ckpt)); + return v.add(t, h); +} + +/* The decoder: the latent denormalised and unpacked to the VAE's 16 channels, then Wan 2.1's + * decoder on one frame. Its residual, head, conv1 and the top-level conv2 (post_quant_conv) + * convolutions are causal 3-D ones read at their last tap; the attention's and the upsamplers' + * are 2-D. */ +static int declare_decoder(RadBuilder* b, Model& m) { + Vae& v = m.dec; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = kGrpVaeDec; + v.base_px = (int64_t)kMaxImageTokens * 4; + v.form = VAE_CONV_CAUSAL; + const int64_t zd = 16, base = 96; + const double mult[4] = { 1, 2, 4, 4 }; + /* The packed channel c 4 + k reads latent channel c: the statistics repeated four times. */ + for (int64_t k = 0; k < 4 * zd; ++k) { + char t[64]; + std::snprintf(t, sizeof t, "%s%.9g", k ? " " : "", kLatStd[k / 4]); + m.mul += t; + std::snprintf(t, sizeof t, "%s%.9g", k ? " " : "", kLatMean[k / 4]); + m.add += t; + } + const int64_t NT = kMaxImageTokens; + m.b_dl = decl_b(b, nm.f("vdec.lat"), RAD_BF16, { NT, 4 * zd }); + m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { 4 * NT, zd }); + m.b_cu4 = decl_b(b, nm.f("vdec.cu"), RAD_I32, { 2 }); + /* ComfyUI's Wan21.process_out on the f32 latent: x std + mean in f32, then bf16. */ + m.op_dnorm = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", 4 * zd), + RAD_STR("mul", m.mul.c_str()), RAD_STR("add", m.add.c_str()), + RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"), + RAD_INT("round", 0)), + RAD_NOWEIGHTS), + { m.b_state, m.b_prev }, { m.b_dl }); + m.op_dzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("n", zd), + RAD_STR("dtype", "bf16"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_decin }); + m.op_unpack = rw(b, RAD_OP(b, "d2s_add", + RAD_PARAMS(RAD_RANGE("M", 1, 4 * NT), RAD_INT("cin", 4 * zd), + RAD_INT("cout", zd), RAD_INT("ft", 1), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_dl, m.b_decin }, { m.b_decin }); + m.op_cu4 = rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 4)), + RAD_NOWEIGHTS), + {}, { m.b_cu4 }); + if (!m.op_dnorm || !m.op_dzero || !m.op_unpack || !m.op_cu4) return RAD_E_INVAL; + + std::vector dims{ base * (int64_t)mult[3] }; + for (int i = 3; i >= 0; --i) dims.push_back(base * (int64_t)mult[i]); + VImg x{ m.b_decin, zd, 0 }; + x = v.conv(x, zd, 1, 1, 1, "same", "conv2"); + x = v.conv(x, dims[0], 3, 1, 1, "same", "decoder.conv1"); + x = wan_resblock(v, x, dims[0], "decoder.middle.0"); + v.form = VAE_CONV_2D; + x = v.attention(x, "decoder.middle.1"); + v.form = VAE_CONV_CAUSAL; + x = wan_resblock(v, x, dims[0], "decoder.middle.2"); + int idx = 0; + for (int i = 0; i < 4; ++i) { + for (int r = 0; r < 3; ++r) + x = wan_resblock(v, x, dims[(size_t)i + 1], nm.f("decoder.upsamples.%d", idx++)); + if (i != 3) { + v.form = VAE_CONV_2D; + x = v.conv(x, dims[(size_t)i + 1] / 2, 3, 1, 2, "same", + nm.f("decoder.upsamples.%d.resample.1", idx++)); + v.form = VAE_CONV_CAUSAL; + } + } + x = v.norm(x, true, "decoder.head.0", 4); + m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "decoder.head.2"); + if (!m.dec_out.buf) return RAD_E_INVAL; + RAD_ARCH_TRY(v.attn_reads(m.b_cu4)); + const int64_t px = (int64_t)kMaxImageTokens * 256; + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST); + m.op_rgb = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + return m.op_rgb ? RAD_OK : RAD_E_INVAL; +} + +/* Which of the release's key spellings the DiT is under: `net.` (Base) or `model.diffusion_model.` + * (Aesthetic and Turbo 1.1). The checkpoint answers at convert; a container, by which marker name + * it holds the timestep norm's gain under (declared under the prefix it was read with). */ +static int find_prefix(RadBuilder* b, Model& m, const char** marker) { + static const char* kPre[2] = { "net.", "model.diffusion_model." }; + static const char* kTag[2] = { "dit.t_norm.net.weight", "dit.t_norm.mdm.weight" }; + int found = -1; + for (int i = 0; i < 2; ++i) { + RAD_ARCH_TRY(map_copy(b, m.nm.f("%s", kTag[i]), + m.nm.ckpt("%st_embedding_norm.weight", kPre[i]))); + RadEncoding e{}; + if (weight_enc(b, m.nm.f("%s", kTag[i]), &e)) found = found < 0 ? i : 2; + } + if (found < 0 || found > 1) { + fprintf(stderr, "radiance: anima: the DiT's keys are under neither `net.` nor " + "`model.diffusion_model.`, or under both\n"); + return RAD_E_UNSUPPORTED; + } + m.pre = kPre[found]; + *marker = kTag[found]; + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta, ctx)); + RAD_ARCH_TRY(geom_from(m.gt, meta, ctx, "bf16", RAD_BF16)); + Names& nm = m.nm; + const char* variant = rad_meta_gets(meta, "anima.variant", "base"); + m.variant = std::strcmp(variant, "turbo") == 0 ? 2 : std::strcmp(variant, "aesthetic") == 0 ? 1 + : 0; + if (m.variant == 0 && std::strcmp(variant, "base") != 0) { + fprintf(stderr, "radiance: anima: anima.variant is '%s'; base, aesthetic or turbo\n", + variant); + return RAD_E_INVAL; + } + const char* marker = nullptr; + RAD_ARCH_TRY(find_prefix(b, m, &marker)); + + /* ---- the adapter's and the DiT's geometry */ + Geom& ga = m.ga; + ga = m.gt; + ga.n_embd = 1024; + ga.n_head = ga.n_head_all = ga.n_head_kv = ga.n_head_kv_all = 16; + ga.head_dim = 64; + ga.n_ff = ga.n_ff_all = 4096; + ga.w_bf16 = true; + Geom& gd = m.gd; + gd = m.gt; + gd.n_layer = 28; + gd.n_embd = 2048; + gd.n_head = gd.n_head_all = gd.n_head_kv = gd.n_head_kv_all = 16; + gd.head_dim = 128; + gd.n_ff = gd.n_ff_all = 8192; + gd.eps = 1e-6f; + + /* ---- bf16 or block fp8: what the container holds for the first DiT projection decides it + * for every LinearFP8 of the text encoder and the DiT (rad_fp8.h, Geom::w_bf16). */ + { + LinearFP8& probe = m.qkv0; + RAD_ARCH_TRY(probe.probe(b, nm, gd, nm.f("dit.blk.0.attn_qkv"), + { nm.ckpt("%sblocks.0.self_attn.q_proj.weight", m.pre.c_str()), + nm.ckpt("%sblocks.0.self_attn.k_proj.weight", m.pre.c_str()), + nm.ckpt("%sblocks.0.self_attn.v_proj.weight", m.pre.c_str()) })); + RadEncoding e{}; + const bool plain = weight_enc(b, nm.f("dit.blk.0.attn_qkv.weight"), &e) && + rad_enc_is(&e, "plain"); + gd.w_bf16 = m.gt.w_bf16 = plain; + } + + /* ---- the per-image state, the conditioning store, and in issue order the text encoder, + * the adapter, the modulations, the DiT and the decoder */ + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); + m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, + { 2 * (int64_t)kMaxLanes * kCondRows, m.ga.n_embd }, RAD_BUF_PERSIST); + m.w_temb_norm = decl_w(b, nm.f("%s", marker), RAD_BF16, { gd.n_embd }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(kGrpDit)); + if (!m.w_temb_norm) return RAD_E_INVAL; + m.dit.resize((size_t)gd.n_layer); + /* ---- adapter key names: LoRA files name the DiT by the checkpoint's own modules behind + * ComfyUI's or kohya's prefix, and the text encoder as kohya's `lora_te_layers_N_...`. */ + RAD_ARCH_TRY(lora_names(b, m.pre.c_str(), kLoraDiffusionSpellings, {})); + RAD_ARCH_TRY(lora_names(b, "model.layers.", "lora_te_layers_", {})); + RAD_ARCH_TRY(declare_te(b, m)); + RAD_ARCH_TRY(declare_adapter(b, m)); + RAD_ARCH_TRY(declare_mod(b, m)); + RAD_ARCH_TRY(declare_dit(b, m)); + RAD_ARCH_TRY(declare_decoder(b, m)); + + /* ---- what the core drives */ + if (!ctx->shape_probe) { + static thread_local std::string name; + name = std::string("anima-") + variant; + RadGeneratorDecl d{}; + d.name = name.c_str(); + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.tmpl_text = "{prompt}"; + d.tmpl_edit = "{prompt}"; + d.drop_prefix = ""; + d.latent_channels = m.C; + d.latent_scale = 16; + d.size_multiple = 16; + d.pixel_channels = 3; + d.slot_rows = 1; + d.max_tokens = kMaxImageTokens; + d.max_refs = 0; + d.ref_area = 1; + d.default_width = 1024; + d.default_height = 1024; + /* ComfyUI's FLOW sampling at shift 3 over its `simple` schedule of 1000 timesteps, Euler + * steps; Base and Aesthetic at the card's 30 steps and guidance 4 with its negative + * prompt, Turbo at 10 steps without guidance (the card's CFG 1). */ + d.default_steps = m.variant == 2 ? 10 : 30; + d.n_sigmas = 0; + d.sigmas = nullptr; + d.shift = 3.0; + d.dyn_shift = 0; + d.shift_exp = 0; + d.base_shift = d.max_shift = 0.0; + d.base_seq = 256; + d.max_seq = 4096; + d.shift_terminal = 0.0; + d.sigma_grid = 1000; + d.cfg_original = 0; + d.default_cfg = m.variant == 2 ? 1.0 : 4.0; + d.default_negative = kNegative; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + /* The conditioning's rows: the prompt padded to the 512 rows the DiT reads, which the + * COND pass leaves in each lane's store and every DENOISE entry names (mode 0). */ + d.cond_rows = kCondRows; + d.rope_hw_scale = 1.0; + d.rope_text_l = 0; + d.pad_multiple = kCondRows; + d.pad_token = kQwenPad; + d.min_tokens = 1; + d.aux_tokens = 1; + d.aux_max_tokens = kCondRows; + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + rad_note(b, "rank %d/%d: Anima (%s) -- Qwen3-0.6B, the LLM adapter, a 2B DiT of %lld blocks " + "(DiT keys under `%s`), %s linears", m.gt.rank, m.gt.world, variant, + (long long)gd.n_layer, m.pre.c_str(), gd.w_bf16 ? "bf16" : "block-fp8"); + return RAD_OK; +} + +/* ================================================================== step */ +/* Qwen3 over the prompt's own tokens (not the padding the layout adds), into `b_src`. */ +static void step_te(RadCtx* c, const RadBatch* batch, const Model& m, int64_t T) { + const Geom& g = m.gt; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const RadGenBatch* G = batch->gen_b; + RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), + brows(m.b_tx, T)); + const RadOperand pos = praw(batch->positions, RAD_I32, T); + const RadOperand cu = praw(G->valid_cu, RAD_I32, 2); + for (const TeLayer& L : m.te) { + RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_tx, T), RAD_W(L.w_n1), brows(m.a_th.x, T)); + L.q_h.step(c, T); + L.qkv.step(c, m.a_th, m.b_tkv, T); + RAD_ISSUE_N(c, L.op_qkr, T, brows(m.b_tkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_tkv, 0, q_dim, T), bcol(m.b_tkv, q_dim, kv_dim, T), + bcol(m.b_tkv, q_dim + kv_dim, kv_dim, T), cu, brows(m.a_tattn.x, T)); + L.q_attn.step(c, T); + L.o.step(c, m.a_tattn, m.b_th2, T); + RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_tx, T), RAD_W(L.w_n2), brows(m.a_th.x, T)); + L.q_h2.step(c, T); + L.gate_up.step(c, m.a_th, m.b_tgu, T); + L.gq.step(c, m.b_tgu, T); + L.down.step(c, m.a_tffn, m.b_th2, T); + RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + } + RAD_ISSUE_N(c, m.op_tnorm, T, brows(m.b_tx, T), RAD_W(m.w_tnorm), brows(m.b_src, T)); +} + +/* The conditioning: Qwen3, the adapter over the T5 rows, the 512 context rows into every lane's + * store at this branch. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t Lq = batch->n_tok - G->n_pad, Lt = G->n_aux, R = kCondRows; + const int64_t D = m.ga.n_embd; + if (Lq <= 0 || Lt <= 0 || Lq > R || Lt > R || !G->aux_ids || !G->aux_cu) { + rad_step_fail(c, "anima: a conditioning pass with no prompt, or no T5 tokens of it"); + return; + } + step_te(c, batch, m, Lq); + const int64_t Rm = std::max(Lq, Lt); + const RadOperand tcu = praw(G->aux_cu, RAD_I32, 2), qcu = praw(G->valid_cu, RAD_I32, 2); + RAD_ISSUE_N(c, m.op_t5, Lt, praw(G->aux_ids, RAD_I32, Lt), RAD_W(m.w_t5), brows(m.b_ax, Lt)); + RAD_ISSUE_N(c, m.op_pos, R, brows(m.b_apos, R)); + RAD_ISSUE_N(c, m.op_fill, R, brows(m.b_aqkv, R)); + for (const AdLayer& L : m.ad) { + RAD_ISSUE_N(c, L.op_nsa, Lt, brows(m.b_ax, Lt), RAD_W(L.w_nsa), brows(m.b_ah, Lt)); + RAD_ISSUE_N(c, L.op_sqkv, Lt, brows(m.b_ah, Lt), RAD_W(L.w_sqkv), brows(m.b_aqkv, Lt)); + RAD_ISSUE_N(c, L.op_sqkr, Lt, brows(m.b_aqkv, Lt), brows(m.b_apos, Lt), RAD_W(L.w_sqn), + RAD_W(L.w_skn)); + RAD_ISSUE_N(c, L.op_sattn, Lt, bcol(m.b_aqkv, 0, D, Lt), bcol(m.b_aqkv, D, D, Lt), + bcol(m.b_aqkv, 2 * D, D, Lt), tcu, brows(m.b_aattn, Lt)); + RAD_ISSUE_N(c, L.op_so, Lt, brows(m.b_aattn, Lt), RAD_W(L.w_so), brows(m.b_ab, Lt)); + RAD_ISSUE_N(c, L.op_sadd, Lt, brows(m.b_ax, Lt), brows(m.b_ab, Lt), brows(m.b_ax, Lt)); + + RAD_ISSUE_N(c, L.op_nca, Lt, brows(m.b_ax, Lt), RAD_W(L.w_nca), brows(m.b_ah, Lt)); + RAD_ISSUE_N(c, L.op_cq, Lt, brows(m.b_ah, Lt), RAD_W(L.w_cq), brows(m.b_aq, Lt)); + RAD_ISSUE_N(c, L.op_ckv, Lq, brows(m.b_src, Lq), RAD_W(L.w_ckv), brows(m.b_akv, Lq)); + RAD_ISSUE_N(c, L.op_cpq, Lt, brows(m.b_aq, Lt), brows(m.b_aq, Lt), brows(m.b_apos, Lt), + bcol(m.b_aqkv, 0, D, Lt)); + RAD_ISSUE_N(c, L.op_cpkv, Lq, brows(m.b_akv, Lq), brows(m.b_akv, Lq), brows(m.b_apos, Lq), + bcol(m.b_aqkv, D, 2 * D, Lq)); + RAD_ISSUE_N(c, L.op_cqkr, Rm, brows(m.b_aqkv, Rm), brows(m.b_apos, Rm), RAD_W(L.w_cqn), + RAD_W(L.w_ckn)); + RAD_ISSUE_N(c, L.op_cattn, Lt, bcol(m.b_aqkv, 0, D, Lt), bcol(m.b_aqkv, D, D, Lq), + bcol(m.b_aqkv, 2 * D, D, Lq), tcu, qcu, brows(m.b_aattn, Lt)); + RAD_ISSUE_N(c, L.op_co, Lt, brows(m.b_aattn, Lt), RAD_W(L.w_co), brows(m.b_ab, Lt)); + RAD_ISSUE_N(c, L.op_cadd, Lt, brows(m.b_ax, Lt), brows(m.b_ab, Lt), brows(m.b_ax, Lt)); + + RAD_ISSUE_N(c, L.op_nmlp, Lt, brows(m.b_ax, Lt), RAD_W(L.w_nmlp), brows(m.b_ah, Lt)); + RAD_ISSUE_N(c, L.op_m1, Lt, brows(m.b_ah, Lt), RAD_W(L.w_m1), RAD_W(L.b_m1), RAD_NONE, + brows(m.b_am, Lt)); + RAD_ISSUE_N(c, L.op_gelu, Lt, brows(m.b_am, Lt), brows(m.b_am, Lt)); + RAD_ISSUE_N(c, L.op_m2, Lt, brows(m.b_am, Lt), RAD_W(L.w_m2), RAD_W(L.b_m2), RAD_NONE, + brows(m.b_ab, Lt)); + RAD_ISSUE_N(c, L.op_madd, Lt, brows(m.b_ax, Lt), brows(m.b_ab, Lt), brows(m.b_ax, Lt)); + } + RAD_ISSUE_N(c, m.op_aout, Lt, brows(m.b_ax, Lt), RAD_W(m.w_aout), RAD_W(m.b_aout), RAD_NONE, + brows(m.b_ah, Lt)); + RAD_ISSUE_N(c, m.op_ctxz, R, brows(m.b_ctx, R)); + RAD_ISSUE_N(c, m.op_anorm, Lt, brows(m.b_ah, Lt), RAD_W(m.w_anorm), brows(m.b_ctx, Lt)); + RAD_ISSUE_N(c, m.op_store, R, brows(m.b_ctx, R), praw(G->lane, RAD_I32, G->n_lane), + brow_slice(m.b_store, (int64_t)G->branch * kCondRows, + 2 * (int64_t)kMaxLanes * kCondRows - G->branch * kCondRows, D)); +} + +/* One denoising step: the entries' modulations, the image rows through the patch embedding, every + * entry's context out of the store, the blocks, and the image rows' velocity through the + * sampler. */ +static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const Geom& g = m.gd; + const int64_t S = batch->n_seq, NI = G->n_img, N0 = G->n_mode_h[0]; + const int64_t D = g.n_embd, qd = g.q_dim(), hd = g.head_dim, M3 = 3 * D, L = g.n_layer; + const int64_t W = L * 3 * M3, nh = g.n_head; + const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1); + const RadOperand ccu = praw(G->mode_ccu, RAD_I32, S + 1); + const RadOperand lanes = praw(G->lane, RAD_I32, S); + const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens; + if (NI <= 0 || N0 <= 0) { + rad_step_fail(c, "anima: a denoising pass with no image or no context rows"); + return; + } + + /* ---- the modulations: block l's module k is columns [(3 l + k) 3D, +3D) of `mods`, as + * (shift | scale | gate) */ + RAD_ISSUE_N(c, m.op_temb, S, praw(G->sigma, RAD_F32, S), brows(m.b_tproj, S)); + RAD_ISSUE_N(c, m.op_t1, S, brows(m.b_tproj, S), RAD_W(m.w_t1), brows(m.b_t1, S)); + RAD_ISSUE_N(c, m.op_tsilu, S, brows(m.b_t1, S), brows(m.b_t1s, S)); + RAD_ISSUE_N(c, m.op_t2, S, brows(m.b_t1s, S), RAD_W(m.w_t2), brows(m.b_lora, S)); + RAD_ISSUE_N(c, m.op_tnormed, S, brows(m.b_tproj, S), RAD_W(m.w_temb_norm), brows(m.b_emb, S)); + RAD_ISSUE_N(c, m.op_esilu, S, brows(m.b_emb, S), brows(m.b_esilu, S)); + auto mod = [&](int64_t l, int k, int part, int64_t width) { + return bcol_at(m.b_mods, 0, W, (3 * l + k) * M3 + part * D, width, S); + }; + for (int64_t l = 0; l < L; ++l) { + const DitLayer& B = m.dit[(size_t)l]; + for (int k = 0; k < 3; ++k) { + RAD_ISSUE_N(c, B.op_mod1[k], S, brows(m.b_esilu, S), RAD_W(B.w_mod1[k]), + brows(m.b_mh, S)); + RAD_ISSUE_N(c, B.op_mod2[k], S, brows(m.b_mh, S), RAD_W(B.w_mod2[k]), + brows(m.b_mod1, S)); + RAD_ISSUE_N(c, B.op_modadd[k], S, brows(m.b_mod1, S), brows(m.b_lora, S), + mod(l, k, 0, M3)); + } + } + RAD_ISSUE_N(c, m.op_f1, S, brows(m.b_esilu, S), RAD_W(m.w_f1), brows(m.b_mh, S)); + RAD_ISSUE_N(c, m.op_f2, S, brows(m.b_mh, S), RAD_W(m.w_f2), brows(m.b_fh, S)); + RAD_ISSUE_N(c, m.op_fadd, S, brows(m.b_fh, S), bcol(m.b_lora, 0, 2 * D, S), + brows(m.b_fmod, S)); + + /* ---- the rows: the images' latents (noise on a first step) through the patch embedding, + * and every entry's context rows out of the store (mode 0, in entry order) */ + RAD_ISSUE_N(c, m.op_randn, NI, praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + lanes, icu, brows(m.b_state, LR)); + RAD_ISSUE_N(c, m.op_lgather, NI, brows(m.b_state, LR), lanes, icu, brows(m.b_lat, NI)); + RAD_ISSUE_N(c, m.op_xemb, NI, brows(m.b_lat, NI), RAD_W(m.w_xemb), brows(m.b_h, NI)); + const int64_t SR = 2 * (int64_t)kMaxLanes * kCondRows; + RAD_ISSUE_N(c, m.op_cgather, N0, brows(m.b_store, SR), brows(m.b_store, SR), + praw(G->mode_src, RAD_I32, N0), brows(m.a_ctx.x, N0)); + m.q_ctx.step(c, N0); + + /* ---- the blocks; the image rows' positions are mode 2's block of the mode-major planes */ + const int64_t img0 = G->n_mode_h[0] + G->n_mode_h[1]; + const RadOperand pos = praw2(G->mode_rope_f + 4 * img0, RAD_F32, 4, NI); + const bool q8 = !g.w_bf16; + auto head_rows = [&](rad_buf x, int64_t rows) { + return RAD_P_T2(rad_buf_ptr(c, x), RAD_BF16, rows * nh, hd); + }; + for (int64_t l = 0; l < L; ++l) { + const DitLayer& B = m.dit[(size_t)l]; + const RadOperand gy = l > 0 ? brows(m.b_ao, NI) : RAD_NONE; + const RadOperand gg = l > 0 ? mod(l - 1, 2, 2, D) : RAD_NONE; + if (q8) + RAD_ISSUE_N(c, B.op_n1, NI, gy, gg, mod(l, 0, 0, 2 * D), RAD_NONE, icu, + brows(m.b_h, NI), brows(m.a_hm.q, NI), brows(m.a_hm.s, NI), RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n1, NI, gy, gg, mod(l, 0, 0, 2 * D), RAD_NONE, icu, + brows(m.b_h, NI), brows(m.a_hm.x, NI)); + B.qkv.step(c, m.a_hm, m.b_qkv, NI); + RAD_ISSUE_N(c, B.op_qkr, NI, brows(m.b_qkv, NI), pos, RAD_W(B.w_qn), RAD_W(B.w_kn)); + RAD_ISSUE_N(c, B.op_attn, NI, bcol(m.b_qkv, 0, qd, NI), bcol(m.b_qkv, qd, qd, NI), + bcol(m.b_qkv, 2 * qd, qd, NI), icu, brows(m.a_attn.x, NI)); + B.q_attn.step(c, NI); + B.o.step(c, m.a_attn, m.b_ao, NI); + + if (q8) + RAD_ISSUE_N(c, B.op_n2, NI, brows(m.b_ao, NI), mod(l, 0, 2, D), mod(l, 1, 0, 2 * D), + RAD_NONE, icu, brows(m.b_h, NI), brows(m.a_hm.q, NI), brows(m.a_hm.s, NI), + RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n2, NI, brows(m.b_ao, NI), mod(l, 0, 2, D), mod(l, 1, 0, 2 * D), + RAD_NONE, icu, brows(m.b_h, NI), brows(m.a_hm.x, NI)); + B.cq.step(c, m.a_hm, m.b_cq, NI); + B.ck.step(c, m.a_ctx, m.b_ck, N0); + B.cv.step(c, m.a_ctx, m.b_cv, N0); + RAD_ISSUE_N(c, B.op_cqn, NI * nh, head_rows(m.b_cq, NI), RAD_W(B.w_cqn), + head_rows(m.b_cq, NI)); + RAD_ISSUE_N(c, B.op_ckn, N0 * nh, head_rows(m.b_ck, N0), RAD_W(B.w_ckn), + head_rows(m.b_ck, N0)); + RAD_ISSUE_N(c, B.op_cattn, NI, brows(m.b_cq, NI), brows(m.b_ck, N0), brows(m.b_cv, N0), + icu, ccu, brows(m.a_attn.x, NI)); + B.q_cattn.step(c, NI); + B.co.step(c, m.a_attn, m.b_ao, NI); + + if (q8) + RAD_ISSUE_N(c, B.op_n3, NI, brows(m.b_ao, NI), mod(l, 1, 2, D), mod(l, 2, 0, 2 * D), + RAD_NONE, icu, brows(m.b_h, NI), brows(m.a_hm.q, NI), brows(m.a_hm.s, NI), + RAD_NONE); + else + RAD_ISSUE_N(c, B.op_n3, NI, brows(m.b_ao, NI), mod(l, 1, 2, D), mod(l, 2, 0, 2 * D), + RAD_NONE, icu, brows(m.b_h, NI), brows(m.a_hm.x, NI)); + B.l1.step(c, m.a_hm, m.b_l1, NI); + RAD_ISSUE_N(c, B.op_gelu, NI, brows(m.b_l1, NI), brows(m.a_ffn.x, NI)); + B.q_ffn.step(c, NI); + B.l2.step(c, m.a_ffn, m.b_ao, NI); + } + + /* ---- the last MLP gated in, the final layer, the sampler */ + RAD_ISSUE_N(c, m.op_g3, NI, brows(m.b_ao, NI), mod(L - 1, 2, 2, D), icu, brows(m.b_h, NI)); + RAD_ISSUE_N(c, m.op_fn, NI, RAD_NONE, RAD_NONE, brows(m.b_fmod, S), RAD_NONE, icu, + brows(m.b_h, NI), brows(m.b_fz, NI)); + RAD_ISSUE_N(c, m.op_final, NI, brows(m.b_fz, NI), RAD_W(m.w_final), brows(m.b_v, NI)); + RAD_ISSUE_N(c, m.op_euler, NI, brows(m.b_v, NI), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->cfg, RAD_F32, S), + praw(G->pair, RAD_I32, S), lanes, praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), icu, RAD_NONE, RAD_NONE, brows(m.b_state, LR), + brows(m.b_prev, LR)); +} + +/* One image's latent to RGB: denormalised, unpacked to the VAE's grid, decoded. */ +static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t H = G->dec_height / 16, W = G->dec_width / 16, n = H * W, C = m.C; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dnorm, n, brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, C), + brows(m.b_dl, n)); + const int64_t zd = C / 4, H0 = 2 * H, W0 = 2 * W; + RAD_ISSUE_N(c, m.op_dzero, H0 * W0, brows(m.b_decin, H0 * W0)); + RAD_ISSUE_N(c, m.op_unpack, H0 * W0, RAD_P_T2(rad_buf_ptr(c, m.b_dl), RAD_BF16, H, W * C), + RAD_P_T2(rad_buf_ptr(c, m.b_decin), RAD_BF16, H0, W0 * zd)); + RAD_ISSUE_N(c, m.op_cu4, 2, praw(batch->cu_seqlens + 1, RAD_I32, 1), brows(m.b_cu4, 2)); + m.dec.issue(c, H0, W0, brows(m.b_cu4, 2), nullptr); + const int64_t npx = (int64_t)G->dec_height * G->dec_width; + RAD_ISSUE_N(c, m.op_rgb, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->gen_b) { + rad_step_fail(c, "anima is an image generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_COND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_DENOISE: step_denoise(c, batch, m); return; + case RAD_GEN_PASS_DECODE: step_decode(c, batch, m); return; + default: rad_step_fail(c, "anima: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: one image at the largest size with guidance, its context both ways. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kCondRows); + out->gen_patches = 0; + return RAD_OK; +} + +} /* namespace anima */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(anima) +RAD_ARCH_PLUGIN(anima, "anima", "", "0.1.0", + "Anima (Base, Aesthetic, Turbo): Qwen3-0.6B through the LLM adapter, Cosmos-Predict2's " + "2B diffusion transformer and the Qwen-Image VAE; bf16 or block-fp8 linears") +#endif diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index c138838a..01918a7f 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -432,6 +432,28 @@ inline int map_rows(RadBuilder* b, const char* declared, std::initializer_list& names) { + const int s = rad_lora_root(b, native, spellings); + if (s < 0) return s; + for (const LoraName& n : names) { + const int a = rad_lora_alias(b, native, n.from.c_str(), n.to.c_str(), n.from_lo, n.from_hi, + n.to_lo); + if (a < 0) return a; + } + return RAD_OK; +} +/* The prefixes ComfyUI, kohya and bare-key adapter files put before a diffusion model's modules. */ +inline const char* kLoraDiffusionSpellings = "diffusion_model. model.diffusion_model. lora_unet_ " + "base_model.model. -"; + /* A weight-normalised checkpoint tensor folded into its plain weight (RAD_MAP_WNORM). */ inline int map_wnorm(RadBuilder* b, const char* declared, const char* g, const char* v) { RadNameMap m = map_base(declared, RAD_MAP_WNORM); diff --git a/arch/flux3/flux3.cpp b/arch/flux3/flux3.cpp index 3eb721ac..4c2e6fa8 100644 --- a/arch/flux3/flux3.cpp +++ b/arch/flux3/flux3.cpp @@ -937,6 +937,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.b_mask = decl_b(b, nm.f("lat_mask"), RAD_F32, { lane_rows, 1 }, RAD_BUF_PERSIST); m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, { 2 * (int64_t)kMaxLanes * cond_rows(), gd.n_embd }, RAD_BUF_PERSIST); + /* ---- adapter key names. LoRA files name the blocks by Black Forest Labs' modules, as + * ComfyUI loads them (comfy/ldm/flux3): `single_blocks.N.q_proj` or a fused `qkv`, + * `attn_out`, `mlp_in`, `mlp_out`, and the mode blocks under `content_mode_blocks`. */ + { + const int64_t Q = gd.n_head_all * gd.head_dim; + std::vector n; + static const char* const kBlocks[][2] = { + { "single_blocks.#.", "single_transformer_blocks.#." }, + { "txt_mode_blocks.#.", "txt_mode_blocks.#." }, + { "content_mode_blocks.image.#.", "mode_blocks.image.#." }, + { "content_mode_blocks.image_cond.#.", "mode_blocks.image_cond.#." }, + }; + for (const auto& bl : kBlocks) { + const std::string f = bl[0], t = bl[1]; + n.push_back({ f + "q_proj", t + "attn.to_q" }); + n.push_back({ f + "k_proj", t + "attn.to_k" }); + n.push_back({ f + "v_proj", t + "attn.to_v" }); + n.push_back({ f + "qkv", t + "attn.to_q", 0, Q, 0 }); + n.push_back({ f + "qkv", t + "attn.to_k", Q, 2 * Q, 0 }); + n.push_back({ f + "qkv", t + "attn.to_v", 2 * Q, 3 * Q, 0 }); + n.push_back({ f + "attn_out", t + "attn.to_out.0" }); + n.push_back({ f + "mlp_in", t + "ff.linear_in" }); + n.push_back({ f + "mlp_out", t + "ff.linear_out" }); + } + RAD_ARCH_TRY(lora_names(b, "transformer.", kLoraDiffusionSpellings, n)); + } RAD_ARCH_TRY(declare_te(b, meta, m)); RAD_ARCH_TRY(declare_encoder(b, meta, m)); RAD_ARCH_TRY(declare_dit(b, meta, m)); diff --git a/arch/krea2/krea2.cpp b/arch/krea2/krea2.cpp index 9e994f53..99300df0 100644 --- a/arch/krea2/krea2.cpp +++ b/arch/krea2/krea2.cpp @@ -297,6 +297,36 @@ static int check_format(const RadModelMeta* meta) { return RAD_OK; } +/* ================================================================== adapter key names */ +/* LoRA files for Krea 2 name the DiT and the text fusion by the reference code's modules + * (krea-ai/krea-2 mmdit.py): `blocks.N.attn.wq`, `txtfusion.refiner_blocks.N.mlp.up`, `tproj.1`; + * the container keeps diffusers' names. The language model takes no adapters. */ +static int declare_lora_names(RadBuilder* b) { + std::vector n; + static const char* const kInner[][2] = { + { "attn.wq", "attn.to_q" }, { "attn.wk", "attn.to_k" }, { "attn.wv", "attn.to_v" }, + { "attn.wo", "attn.to_out.0" }, { "attn.gate", "attn.to_gate" }, + { "mlp.gate", "ff.gate" }, { "mlp.up", "ff.up" }, { "mlp.down", "ff.down" }, + }; + static const char* const kBlocks[][2] = { + { "blocks.#.", "transformer_blocks.#." }, + { "txtfusion.layerwise_blocks.#.", "text_fusion.layerwise_blocks.#." }, + { "txtfusion.refiner_blocks.#.", "text_fusion.refiner_blocks.#." }, + }; + for (const auto& bl : kBlocks) + for (const auto& in : kInner) + n.push_back({ std::string(bl[0]) + in[0], std::string(bl[1]) + in[1] }); + n.push_back({ "txtfusion.projector", "text_fusion.projector" }); + n.push_back({ "txtmlp.1", "txt_in.linear_1" }); + n.push_back({ "txtmlp.3", "txt_in.linear_2" }); + n.push_back({ "first", "img_in" }); + n.push_back({ "last_linear", "final_layer.linear" }); + n.push_back({ "tmlp.0", "time_embed.linear_1" }); + n.push_back({ "tmlp.2", "time_embed.linear_2" }); + n.push_back({ "tproj.1", "time_mod_proj" }); + return lora_names(b, "transformer.", kLoraDiffusionSpellings, n); +} + /* ================================================================== declare */ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { Geom& g = m.gt; @@ -1059,6 +1089,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_BF16, { lane_rows, m.C }, RAD_BUF_PERSIST); m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, { 2 * (int64_t)kMaxLanes * kCondRows, gd.n_embd }, RAD_BUF_PERSIST); + RAD_ARCH_TRY(declare_lora_names(b)); RAD_ARCH_TRY(declare_te(b, meta, m)); RAD_ARCH_TRY(declare_fusion(b, meta, m)); RAD_ARCH_TRY(declare_dit(b, meta, m)); diff --git a/arch/ltx2/ltx2.cpp b/arch/ltx2/ltx2.cpp index e0e9f6b5..2249cb05 100644 --- a/arch/ltx2/ltx2.cpp +++ b/arch/ltx2/ltx2.cpp @@ -3240,6 +3240,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ---- in issue order: the conditioning pass, the step, the frames, the soundtrack, the * upscale */ + /* LoRA files for LTX-2.5 name the DiT's modules as the checkpoint does (`transformer_blocks.N. + * attn1.to_q`, `ff.net.0.proj`), behind ComfyUI's or kohya's prefix. */ + RAD_ARCH_TRY(lora_names(b, "transformer.", kLoraDiffusionSpellings, {})); RAD_ARCH_TRY(declare_te(b, meta, m)); { const int64_t wz = std::max(rad_meta_geti(meta, "connectors.video_hidden_dim", 0), diff --git a/arch/minimaxh3/minimaxh3.cpp b/arch/minimaxh3/minimaxh3.cpp index 75c310e8..8d1a47b3 100644 --- a/arch/minimaxh3/minimaxh3.cpp +++ b/arch/minimaxh3/minimaxh3.cpp @@ -705,6 +705,41 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { return m.op_embed ? RAD_OK : RAD_E_INVAL; } +/* ================================================================== adapter key names */ +/* LoRA files for H3 name the DiT by ComfyUI's modules (comfy/ldm/minimax): one fused + * `attn.qkv_proj` (q, k, v), `attn.out_proj`, and `mlp.fc1` with the SwiGLU's gate half first, + * where the checkpoint keeps the value half first in `ff.net.0.proj`. */ +static int declare_lora_names(RadBuilder* b, const Model& m) { + std::vector n; + const int64_t Q = m.gd.n_head_all * m.gd.head_dim, KV = m.gd.n_head_kv_all * m.gd.head_dim; + const int64_t F = m.gd.n_ff_all; + static const char* const kBlocks[][2] = { + { "blocks.#.", "transformer_blocks.#." }, + { "token_refiner.blocks.#.", "token_refiner.refiner_blocks.#." }, + }; + for (const auto& bl : kBlocks) { + const std::string f = bl[0], t = bl[1]; + n.push_back({ f + "attn.qkv_proj", t + "attn.to_q", 0, Q, 0 }); + n.push_back({ f + "attn.qkv_proj", t + "attn.to_k", Q, Q + KV, 0 }); + n.push_back({ f + "attn.qkv_proj", t + "attn.to_v", Q + KV, Q + 2 * KV, 0 }); + n.push_back({ f + "attn.out_proj", t + "attn.to_out.0" }); + n.push_back({ f + "attn.to_gate_compress", t + "attn.to_gate_compress" }); + n.push_back({ f + "mlp.fc1", t + "ff.net.0.proj", 0, F, F }); + n.push_back({ f + "mlp.fc1", t + "ff.net.0.proj", F, 2 * F, 0 }); + n.push_back({ f + "mlp.fc2", t + "ff.net.2" }); + } + n.push_back({ "blocks.#.adaln_proj.linear", "transformer_blocks.#.adaln_proj.linear" }); + n.push_back({ "video_patch_proj", "proj_in" }); + n.push_back({ "audio_patch_proj", "audio_proj_in" }); + n.push_back({ "condition_proj", "context_embedder" }); + n.push_back({ "time_embedder.proj_in", "time_embedder.linear_1" }); + n.push_back({ "time_embedder.proj_out", "time_embedder.linear_2" }); + n.push_back({ "final_layer.video_out", "proj_out" }); + n.push_back({ "final_layer.audio_out", "audio_proj_out" }); + n.push_back({ "final_layer.adaln_proj.linear", "norm_out.linear" }); + return lora_names(b, "transformer.", kLoraDiffusionSpellings, n); +} + /* ================================================================== the token refiner */ /* `context_embedder` (5120 -> 5376, bf16, replicated), two plain blocks with full attention over * the prompt and no rotary, and the final RMSNorm into the lane's prompt rows. The feed-forward is @@ -1924,6 +1959,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ---- in issue order: the conditioning pass, the step, the soundtrack, the frames */ m.b_text = decl_b(b, nm.f("lane.text"), RAD_BF16, { (int64_t)kMaxLanes * kMaxText, m.D }, RAD_BUF_PERSIST); + RAD_ARCH_TRY(declare_lora_names(b, m)); RAD_ARCH_TRY(declare_te(b, meta, m)); RAD_ARCH_TRY(declare_refiner(b, meta, m)); RAD_ARCH_TRY(declare_tables(b, meta, m)); diff --git a/arch/qwenimage21/qwenimage21.cpp b/arch/qwenimage21/qwenimage21.cpp index 70b558b5..e6eb4021 100644 --- a/arch/qwenimage21/qwenimage21.cpp +++ b/arch/qwenimage21/qwenimage21.cpp @@ -911,6 +911,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * (Vae says why the order matters.) */ m.media = VisionTower::present(meta) && ctx->max_enc_patches > 0; if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, m.gt.n_embd, kGrpVision, true)); + /* ---- adapter key names. The DiT's LoRA files use the checkpoint's own names, or + * ComfyUI's, which join the SwiGLU's gate and up projections as `img_mlp.gate_up` [gate; up] + * (comfy/ldm/qwen_image21). */ + { + const int64_t F = gd.n_ff_all; + RAD_ARCH_TRY(lora_names(b, "transformer.", kLoraDiffusionSpellings, + { { "transformer_blocks.#.img_mlp.gate_up", + "transformer_blocks.#.img_mlp.gate_layer", 0, F, 0 }, + { "transformer_blocks.#.img_mlp.gate_up", + "transformer_blocks.#.img_mlp.proj", F, 2 * F, 0 } })); + } RAD_ARCH_TRY(declare_te(b, meta, m)); RAD_ARCH_TRY(declare_encoder(b, meta, m)); RAD_ARCH_TRY(declare_dit(b, meta, m)); diff --git a/arch/sdxl/CMakeLists.txt b/arch/sdxl/CMakeLists.txt new file mode 100644 index 00000000..4e4ce326 --- /dev/null +++ b/arch/sdxl/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/sdxl -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(sdxl LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(sdxl architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/sdxl.cpp) diff --git a/arch/sdxl/sdxl.cpp b/arch/sdxl/sdxl.cpp new file mode 100644 index 00000000..8ace9a10 --- /dev/null +++ b/arch/sdxl/sdxl.cpp @@ -0,0 +1,1236 @@ +/* sdxl -- Stable Diffusion XL and its finetunes (Illustrious, NoobAI, Pony, ...): text to an RGB + * image. + * + * ============================== THE MODEL ============================== + * + * Three networks behind one prompt, as Stability's single-file checkpoint holds them (read by + * rad-convert's SDXL importer, core/format/checkpoint.cpp open_sgm): + * + * Conditioning: two CLIP text encoders over the prompt in 77-token windows (the core cuts it, + * RadGeneratorDecl::chunk_tokens): CLIP ViT-L (12 layers, 768 wide, quick_gelu) and OpenCLIP + * ViT-bigG (32 layers, 1280 wide, gelu). Each window is encoded on its own, causally. The + * cross-attention context is ViT-L's and bigG's penultimate hidden states side by side, 2048 + * wide, the windows end to end; the pooled vector is bigG's last layer through its final norm at + * the first window's end-of-text token, through text_projection. ViT-L reads padding as + * end-of-text tokens, bigG as token 0 ("!"), as each tokenizer pads. + * + * Denoiser: a 2.6B UNet over 4-channel latents at 1/8 of the pixels, three levels (320, 640 and + * 1280 channels), residual blocks (GroupNorm, SiLU, 3x3 convolutions, the time embedding added + * per channel) and spatial transformers at the two lower levels (2 and 10 blocks of self + * attention, cross attention over the context and a GEGLU feed-forward, 64-wide heads). The time + * embedding is the timestep's plus the pooled vector's and the image size's (original size, + * crop at (0, 0), target size), each through its own sinusoid. It predicts the noise (eps), or + * with a `v_pred` checkpoint the velocity. + * + * Decoder: the SDXL VAE (AutoencoderKL, 4 latent channels at 8x, scaling 0.13025), run bf16 + * (bf16 has f32's range, so the fp16 overflow the original VAE is known for does not occur). + * + * Sampling is k-diffusion's over the discrete schedule (1000 steps, scaled-linear betas + * 0.00085..0.012): the core places the sigmas (ComfyUI's schedulers) and conditions each step at + * the nearest trained timestep; kd_input scales the f32 latent by c_in, the UNet runs at bf16, and + * kd_step applies guidance to the denoised estimates and takes the sampler's step (Euler, Euler + * ancestral, DPM++ 2M) in f32. + * + * ============================== ONE IMAGE AT A TIME ============================== + * + * A convolution reads its image's size from its operands, so a denoising pass runs the UNet once + * per entry (an image and its guidance branch are two entries) at that entry's size, over the + * same declared ops; the sampler ops run over every entry at once. The buffers the entries pass + * between them (the model input and output, the lanes, the stores) are kept for the program's + * life. + * + * ============================== RUNTIME LORA ============================== + * + * Every linear and every 3x3 convolution of the UNet and every linear of both text encoders is a + * plain GEMM over a weight declared under its checkpoint name: a 3x3 convolution is `im2col_nhwc` + * then `gemm_nt_bias` over the weight read as [cout, cin * 9] in the checkpoint's own order, a 1x1 + * skip convolution a GEMM over [cout, cin]. Only the UNet's conv_in and out.2 (4 channels) and the + * VAE are direct convolutions. + * + * One card: the model is small enough that tensor parallelism would only add all-reduces. + */ +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace sdxl { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +/* The largest image in latent pixels: 1536 x 1536 (or the same area at another aspect). */ +enum { kMaxImageTokens = 36864 }; +/* CLIP's window, and the windows a prompt may take. */ +enum { kWin = 77, kMaxWin = 8, kCondRows = kWin * kMaxWin }; +enum { kMaxLanes = 8 }; +enum { kLatC = 4, kCtx = 2048, kPooled = 1280, kAdd = 2816, kTemb = 1280, kGroups = 32 }; +enum { kBos = 49406, kEos = 49407 }; +static const double kVaeScale = 0.13025; +/* group_norm's scratch: 32 groups of (2 + 3 * 1024) floats (docs/OPS.md). */ +enum { kGnStats = kGroups * (2 + 3 * 1024) }; + +static const char* kUnet = "model.diffusion_model"; +static const char* kTe1 = "conditioner.embedders.0.transformer"; +static const char* kTe2 = "conditioner.embedders.1.transformer"; + +/* Movement groups: each text encoder one, the UNet's embeddings and blocks 21 (kGrpUnet + 0..20), + * the VAE one. All lie below the conditioning network's layer count, the container's n_layers, + * since the engine reads a group past it as a drafter's. */ +enum : int { kGrpTe1 = 0, kGrpTe2 = 1, kGrpUnet = 2, kGrpVae = 23 }; + +/* ================================================================== the text encoders */ +struct TextLayer { + rad_weight ln1w = 0, ln1b = 0, ln2w = 0, ln2b = 0; + rad_weight qw = 0, qb = 0, kw = 0, kb = 0, vw = 0, vb = 0, ow = 0, ob = 0; + rad_weight f1w = 0, f1b = 0, f2w = 0, f2b = 0; + rad_op op_ln1 = 0, op_q = 0, op_k = 0, op_v = 0, op_attn = 0, op_o = 0; + rad_op op_ln2 = 0, op_f1 = 0, op_act = 0, op_f2 = 0; +}; + +struct TextEnc { + int64_t D = 0, F = 0, L = 0; /* width, feed-forward width, layers run */ + int64_t tap = 0; /* the layer after which the context is taken */ + int64_t ctx_col = 0; /* where its columns of the context start */ + bool quick = false; /* quick_gelu (ViT-L) or gelu (bigG) */ + rad_weight tok = 0, pos = 0; + rad_buf x = 0, pe = 0, h = 0, q = 0, k = 0, v = 0, a = 0, f1 = 0, f2 = 0; + rad_op op_tok = 0, op_pad = 0, op_pos = 0, op_pe = 0, op_tap = 0; + std::vector layers; + /* bigG's pooled vector */ + rad_weight fnw = 0, fnb = 0, proj = 0; + rad_buf e1 = 0, e2 = 0; + rad_op op_eos = 0, op_fn = 0, op_proj = 0; +}; + +/* ================================================================== the UNet, recorded + * + * The UNet's ops are declared once and issued per entry at the entry's size, so each op is + * recorded with what rebuilds its operands: a value's rows are its level's pixels (level l is + * the latent at 1 / 2^l per side), one row, or the conditioning's rows. */ +enum { kRowsOne = -1, kRowsCond = -2, kRowsTwo = -3 }; + +struct V { + rad_buf buf = 0; + int lvl = 0; /* >= 0 a level; kRows* otherwise */ + int64_t pitch = 0; /* the buffer's width */ + int64_t col = 0, width = 0; /* a column slice; width 0 is the whole row */ + int64_t w() const { return width ? width : pitch; } +}; + +struct Opd { + /* ROWS a value's rows (the entry's conditioning when the value is the store), IMG a level's + * image [h, w * channels], XIN / EPS the entry's rows of the model input and output, IOTA the + * table's entry for a level's pixel count, STATS group_norm's scratch. */ + enum Kind : uint8_t { NONE, ROWS, IMG, WEIGHT, XIN, EPS, IOTA, STATS }; + Kind kind = NONE; + V v{}; + rad_weight w = 0; +}; + +struct UOp { + rad_op op = 0; + std::vector o; + int n = 0; /* the ranged value: a level's pixels, or kRows* */ +}; + +/* One entry's geometry and where its per-entry operands are. */ +struct Geo { + int64_t h = 0, w = 0; /* latent rows and columns */ + int64_t cond = 0; /* conditioning rows */ + int64_t store_row = 0, pool_row = 0; + int64_t row0 = 0; /* its first row in the pass's compact image order */ + int64_t px(int l) const { return (h >> l) * (w >> l); } + int64_t rows(int l) const { + return l >= 0 ? px(l) : l == kRowsOne ? 1 : l == kRowsTwo ? 2 : cond; + } +}; + +struct Net { + std::vector ops; + RadBuilder* b = nullptr; + Names* nm = nullptr; + int64_t P0 = kMaxImageTokens; + int n_buf = 0; + int grp = kGrpUnet; + rad_buf stats = 0, iota = 0, store = 0, xin = 0, eps = 0; + + int64_t cap(int lvl) const { + return lvl >= 0 ? P0 >> (2 * lvl) + : lvl == kRowsCond ? (int64_t)kCondRows : lvl == kRowsTwo ? 2 : 1; + } + V buf(int lvl, int64_t ch, uint32_t dt = RAD_BF16) { + V v; + v.lvl = lvl; + v.pitch = ch; + v.buf = decl_b(b, nm->f("unet.t%d", n_buf++), dt, { cap(lvl), ch }); + return v; + } + static Opd R(const V& v) { Opd o; o.kind = Opd::ROWS; o.v = v; return o; } + static Opd I(const V& v) { Opd o; o.kind = Opd::IMG; o.v = v; return o; } + static Opd W(rad_weight w) { Opd o; o.kind = Opd::WEIGHT; o.w = w; return o; } + static Opd Kd(Opd::Kind k) { Opd o; o.kind = k; return o; } + void add(rad_op op, std::vector o, int n, std::initializer_list rd, + std::initializer_list wr) { + rw(b, op, rd, wr); + UOp u; + u.op = op; + u.o = std::move(o); + u.n = n; + ops.push_back(std::move(u)); + } + /* A weight under its checkpoint name, declared at `shape` (a conv kernel read flat). */ + rad_weight wt(const char* src, std::initializer_list shape) { + if (map_copy(b, src, src) < 0) return 0; + return decl_w(b, src, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(grp)); + } + + /* y = x W^T (+ bias) (+ res): gemm_nt without a bias, gemm_nt_bias with one. */ + V lin(const V& x, int64_t N, const char* src, bool bias, const V* res = nullptr) { + V y = buf(x.lvl, N); + const int64_t K = x.w(); + rad_weight w = wt(nm->ckpt("%s.weight", src), { N, K }); + if (!bias) { + rad_op op = RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("N", N), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + add(op, { R(x), W(w), R(y) }, x.lvl, { x.buf }, { y.buf }); + return y; + } + rad_weight bw = wt(nm->ckpt("%s.bias", src), { N }); + rad_op op = RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("N", N), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + if (res) + add(op, { R(x), W(w), W(bw), R(*res), R(y) }, x.lvl, { x.buf, res->buf }, { y.buf }); + else + add(op, { R(x), W(w), W(bw), Kd(Opd::NONE), R(y) }, x.lvl, { x.buf }, { y.buf }); + return y; + } + /* A 3x3 convolution with a bias (+ res): im2col_nhwc, then a GEMM over the weight read as + * [cout, cin * 9], the checkpoint's order. `stride` 2 halves the side, `up` 2 doubles it. */ + V conv3(const V& x, int64_t cout, const char* src, int stride, int up, const V* res = nullptr) { + const int lo = x.lvl + (stride == 2 ? 1 : 0) - (up == 2 ? 1 : 0); + const int64_t cin = x.pitch; + V col = buf(lo, cin * 9); + rad_op op = RAD_OP(b, "im2col_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, cap(lo)), RAD_INT("cin", cin), + RAD_INT("k", 3), RAD_INT("stride", stride), + RAD_STR("pad", "same"), RAD_INT("up", up), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + add(op, { I(x), R(col) }, lo, { x.buf }, { col.buf }); + V y = buf(lo, cout); + rad_weight w = wt(nm->ckpt("%s.weight", src), { cout, cin * 9 }); + rad_weight bw = wt(nm->ckpt("%s.bias", src), { cout }); + rad_op g = RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, cap(lo)), RAD_INT("N", cout), + RAD_INT("K", cin * 9), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + if (res) + add(g, { R(col), W(w), W(bw), R(*res), R(y) }, lo, { col.buf, res->buf }, { y.buf }); + else + add(g, { R(col), W(w), W(bw), Kd(Opd::NONE), R(y) }, lo, { col.buf }, { y.buf }); + return y; + } + /* A direct convolution (conv_in and the output's, 4 channels on one side). */ + V conv_direct(const Opd& in, int lvl, int64_t cin, int64_t cout, const char* src, + const Opd* out = nullptr) { + V y{}; + y.lvl = lvl; + y.pitch = cout; + if (!out) y = buf(lvl, cout); + rad_weight w = wt(nm->ckpt("%s.weight", src), { cout, cin, 3, 3 }); + rad_weight bw = wt(nm->ckpt("%s.bias", src), { cout }); + rad_op op = RAD_OP(b, "conv2d_nhwc", + RAD_PARAMS(RAD_RANGE("M", 1, cap(lvl)), RAD_INT("cin", cin), + RAD_INT("cout", cout), RAD_INT("k", 3), RAD_INT("stride", 1), + RAD_STR("pad", "same"), RAD_INT("up", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + rw(b, op, { in.v.buf }, { out ? out->v.buf : y.buf }); + UOp u; + u.op = op; + u.o = { in, W(w), W(bw), out ? *out : I(y) }; + u.n = lvl; + ops.push_back(std::move(u)); + return y; + } + /* GroupNorm(32) with its affine, then SiLU or not. */ + V gn(const V& x, const char* src, double eps, bool silu) { + V y = buf(x.lvl, x.pitch); + rad_weight w = wt(nm->ckpt("%s.weight", src), { x.pitch }); + rad_weight bw = wt(nm->ckpt("%s.bias", src), { x.pitch }); + rad_op op = RAD_OP(b, "group_norm", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("n", x.pitch), + RAD_INT("groups", kGroups), RAD_F64("eps", eps), + RAD_STR("act", silu ? "silu" : "none"), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + add(op, { R(x), W(w), W(bw), Kd(Opd::NONE), Kd(Opd::STATS), R(y) }, x.lvl, + { x.buf, stats }, { y.buf, stats }); + return y; + } + V ln(const V& x, const char* src) { + V y = buf(x.lvl, x.pitch); + rad_weight w = wt(nm->ckpt("%s.weight", src), { x.pitch }); + rad_weight bw = wt(nm->ckpt("%s.bias", src), { x.pitch }); + rad_op op = RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("n", x.pitch), + RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bw)); + add(op, { R(x), W(w), W(bw), R(y) }, x.lvl, { x.buf }, { y.buf }); + return y; + } + /* y = x + e, e one row broadcast along x's rows. */ + V add_row(const V& x, const V& e) { + V y = buf(x.lvl, x.pitch); + rad_op op = RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("n", x.pitch), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + add(op, { R(x), R(e), R(y) }, x.lvl, { x.buf, e.buf }, { y.buf }); + return y; + } + /* dst's columns [col, col + x.w()) = x: a skip connection's half of a concatenation. */ + void copy(const V& x, const V& dst, int64_t col) { + V d = dst; + d.col = col; + d.width = x.w(); + rad_op op = RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, cap(x.lvl)), RAD_INT("n", x.w()), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS); + add(op, { R(x), R(d) }, x.lvl, { x.buf }, { dst.buf }); + } + /* {0, n}: the bounds of one sequence of the entry's rows at `lvl`, off the iota table. */ + V cu(int lvl) { + V y; + y.lvl = kRowsTwo; + y.pitch = 1; + y.buf = decl_b(b, nm->f("unet.cu%d", n_buf++), RAD_I32, { 2 }); + rad_op op = RAD_OP(b, "cu_repeat", RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", 1)), + RAD_NOWEIGHTS); + Opd it = Kd(Opd::IOTA); + it.v.lvl = lvl; + add(op, { it, R(y) }, kRowsTwo, { iota }, { y.buf }); + return y; + } + /* Self attention over the entry's rows, 64-wide heads. */ + V attn(const V& q, const V& k, const V& v, const V& cu_q) { + V y = buf(q.lvl, q.w()); + rad_op op = RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, cap(q.lvl)), RAD_INT("head_dim", 64), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 0.125)), + RAD_NOWEIGHTS); + add(op, { R(q), R(k), R(v), R(cu_q), R(y) }, q.lvl, { q.buf, k.buf, v.buf, cu_q.buf }, + { y.buf }); + return y; + } + /* Cross attention of the entry's rows over its conditioning's. */ + V xattn(const V& q, const V& k, const V& v, const V& cu_q, const V& cu_k) { + V y = buf(q.lvl, q.w()); + rad_op op = RAD_OP(b, "attn_cross", + RAD_PARAMS(RAD_RANGE("M", 1, cap(q.lvl)), RAD_INT("head_dim", 64), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 0.125)), + RAD_NOWEIGHTS); + add(op, { R(q), R(k), R(v), R(cu_q), R(cu_k), R(y) }, q.lvl, + { q.buf, k.buf, v.buf, cu_q.buf, cu_k.buf }, { y.buf }); + return y; + } + /* GEGLU: the projection's first half times gelu (erf) of its second. */ + V geglu(const V& p) { + const int64_t n = p.pitch / 2; + V y = buf(p.lvl, n); + V a = p, g = p; + a.col = 0; a.width = n; + g.col = n; g.width = n; + rad_op op = RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, cap(p.lvl)), RAD_INT("n", n), + RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + add(op, { R(g), R(a), R(y) }, p.lvl, { p.buf }, { y.buf }); + return y; + } + + /* ---- blocks */ + /* in_layers (GroupNorm, SiLU, conv), the time embedding's projection added per channel, + * out_layers (GroupNorm, SiLU, conv) plus the input or its 1x1 skip convolution. */ + V resblock(const V& x, int64_t cout, const char* pre, const V& emb_s) { + V t = gn(x, nm->ckpt("%s.in_layers.0", pre), 1e-5, true); + V h = conv3(t, cout, nm->ckpt("%s.in_layers.2", pre), 1, 1); + V e = lin(emb_s, cout, nm->ckpt("%s.emb_layers.1", pre), true); + h = add_row(h, e); + V t2 = gn(h, nm->ckpt("%s.out_layers.0", pre), 1e-5, true); + V skip = x; + if (x.pitch != cout) skip = lin(x, cout, nm->ckpt("%s.skip_connection", pre), true); + return conv3(t2, cout, nm->ckpt("%s.out_layers.3", pre), 1, 1, &skip); + } + /* SpatialTransformer with linear projections: GroupNorm, proj_in, `depth` blocks of self + * attention, cross attention and GEGLU each added back, proj_out plus the input. */ + V transformer(const V& x, const char* pre, int depth, const V& ctx, const V& cu_q, + const V& cu_k) { + const int64_t C = x.pitch; + V t = gn(x, nm->ckpt("%s.norm", pre), 1e-6, false); + V h = lin(t, C, nm->ckpt("%s.proj_in", pre), true); + for (int d = 0; d < depth; ++d) { + const char* bp = nm->ckpt("%s.transformer_blocks.%d", pre, d); + V a = ln(h, nm->ckpt("%s.norm1", bp)); + V q = lin(a, C, nm->ckpt("%s.attn1.to_q", bp), false); + V k = lin(a, C, nm->ckpt("%s.attn1.to_k", bp), false); + V v = lin(a, C, nm->ckpt("%s.attn1.to_v", bp), false); + V o = attn(q, k, v, cu_q); + h = lin(o, C, nm->ckpt("%s.attn1.to_out.0", bp), true, &h); + a = ln(h, nm->ckpt("%s.norm2", bp)); + q = lin(a, C, nm->ckpt("%s.attn2.to_q", bp), false); + k = lin(ctx, C, nm->ckpt("%s.attn2.to_k", bp), false); + v = lin(ctx, C, nm->ckpt("%s.attn2.to_v", bp), false); + o = xattn(q, k, v, cu_q, cu_k); + h = lin(o, C, nm->ckpt("%s.attn2.to_out.0", bp), true, &h); + a = ln(h, nm->ckpt("%s.norm3", bp)); + V p = lin(a, 8 * C, nm->ckpt("%s.ff.net.0.proj", bp), true); + V f = geglu(p); + h = lin(f, C, nm->ckpt("%s.ff.net.2", bp), true, &h); + } + return lin(h, C, nm->ckpt("%s.proj_out", pre), true, &x); + } + /* [a | b] along the channels. */ + V concat(const V& a, const V& s) { + V y = buf(a.lvl, a.pitch + s.pitch); + copy(a, y, 0); + copy(s, y, a.pitch); + return y; + } + + RadOperand opd(RadCtx* c, const Opd& o, const Geo& g) const; + void issue(RadCtx* c, const Geo& g) const; +}; + +/* ================================================================== the model */ +struct Model { + Names nm{""}; + std::string pred = "eps"; + bool zero_snr = false; + + /* ---- the conditioning */ + TextEnc te1{}, te2{}; + rad_buf b_pos = 0, b_wcu = 0, b_zero = 0, b_ctx = 0, b_pooled = 0; + rad_op op_pos = 0, op_wcu = 0, op_zero = 0, op_store = 0, op_pstore = 0; + + /* ---- the per-image state and the stores (PERSIST) */ + rad_buf b_state = 0, b_hist = 0, b_prev = 0, b_store = 0, b_pstore = 0; + rad_buf b_xin = 0, b_eps = 0, b_iota = 0, b_zf = 0; + rad_op op_iota = 0, op_zf = 0, op_kdin = 0, op_kdstep = 0; + + /* ---- the time and size embeddings, per entry */ + rad_weight w_t1 = 0, b_t1 = 0, w_t2 = 0, b_t2 = 0, w_l1 = 0, b_l1 = 0, w_l2 = 0, b_l2 = 0; + rad_buf b_tproj = 0, b_te1 = 0, b_te1s = 0, b_temb = 0, b_add = 0, b_le1 = 0, b_le1s = 0; + rad_buf b_emb = 0, b_embs = 0; + rad_op op_tproj = 0, op_t1 = 0, op_ts = 0, op_t2 = 0, op_pool = 0, op_szo = 0, op_szc = 0, + op_szt = 0, op_l1 = 0, op_ls = 0, op_l2 = 0, op_es = 0; + + /* ---- the UNet */ + Net net{}; + + /* ---- the decoder */ + Vae dec{}; + VImg dec_out{}; + rad_buf b_dlf = 0, b_decin = 0, b_img = 0; + rad_op op_dscale = 0, op_dcast = 0, op_rgb = 0; +}; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== the recorded UNet's issue */ +RadOperand Net::opd(RadCtx* c, const Opd& o, const Geo& g) const { + switch (o.kind) { + case Opd::NONE: return RAD_NONE; + case Opd::WEIGHT: return RAD_W(o.w); + case Opd::ROWS: { + /* The context is the entry's conditioning where the store keeps it. */ + if (o.v.buf == store) return brow_slice(store, g.store_row, g.cond, kCtx); + const int64_t r = g.rows(o.v.lvl); + if (o.v.width && o.v.width != o.v.pitch) return bcol(o.v.buf, o.v.col, o.v.width, r); + return brows(o.v.buf, r); + } + case Opd::IMG: { + const int l = o.v.lvl; + return RAD_P_T2(rad_buf_ptr(c, o.v.buf), RAD_BF16, g.h >> l, (g.w >> l) * o.v.pitch); + } + case Opd::XIN: + return RAD_P_T2((const char*)rad_buf_ptr(c, xin) + g.row0 * kLatC * 2, RAD_BF16, g.h, + g.w * kLatC); + case Opd::EPS: + return RAD_P_T2((char*)rad_buf_ptr(c, eps) + g.row0 * kLatC * 2, RAD_BF16, g.h, + g.w * kLatC); + case Opd::IOTA: return brow_slice(iota, g.rows(o.v.lvl), 1, 1); + case Opd::STATS: return RAD_P_T2(rad_buf_ptr(c, stats), RAD_F32, 1, kGnStats); + } + return RAD_NONE; +} + +void Net::issue(RadCtx* c, const Geo& g) const { + RadOperand a[8]; + for (const UOp& u : ops) { + const int n = (int)u.o.size(); + for (int i = 0; i < n; ++i) a[i] = opd(c, u.o[(size_t)i], g); + rad_issue(c, u.op, a, n, g.rows(u.n)); + } +} + +/* ================================================================== declare */ +static rad_weight wcopy(RadBuilder* b, const char* src, std::initializer_list shape, + int access, int group, bool mapped = false) { + if (!mapped && map_copy(b, src, src) < 0) return 0; + return decl_w(b, src, RAD_BF16, shape, access, RAD_SHARD_NONE, grp_layer(group)); +} + +/* A linear over `rows` rows: gemm_nt_bias with a bias (and a residual `res` added in), gemm_nt + * without. */ +static rad_op dense(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, + rad_weight bias, rad_buf in, rad_buf out, rad_buf res = 0) { + rad_op h = bias ? RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)) + : RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + if (res) return rw(b, h, { in, res }, { out }); + return rw(b, h, { in }, { out }); +} + +static rad_op unary(RadBuilder* b, const char* op, int64_t rows, int64_t n, rad_buf in, + rad_buf out) { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); +} + +static rad_op tstep_embed(RadBuilder* b, int64_t rows, int64_t n, rad_buf out) { + return rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("scale", 1.0), + RAD_F64("max_period", 10000.0), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { out }); +} + +/* One CLIP text encoder over T rows: token and position embeddings, `L` pre-norm layers, the + * context's columns copied out after layer `tap`. */ +static int declare_text(RadBuilder* b, Model& m, TextEnc& E, const char* root, int grp, + int64_t D, int64_t F, int64_t L, int64_t tap, bool pooled) { + Names& nm = m.nm; + const int64_t T = kCondRows; + const char* tm = nm.ckpt("%s.text_model", root); + E.D = D; + E.F = F; + E.L = L; + E.tap = tap; + E.tok = wcopy(b, nm.ckpt("%s.embeddings.token_embedding.weight", tm), { 49408, D }, + RAD_ACCESS_VOCAB, grp); + E.pos = wcopy(b, nm.ckpt("%s.embeddings.position_embedding.weight", tm), { kWin, D }, + RAD_ACCESS_PER_TOKEN, grp); + if (!E.tok || !E.pos) return RAD_E_INVAL; + const char* sc = nm.f("te%d", grp == kGrpTe1 ? 1 : 2); + E.x = decl_b(b, nm.f("%s.x", sc), RAD_BF16, { T, D }); + E.pe = decl_b(b, nm.f("%s.pe", sc), RAD_BF16, { T, D }); + E.h = decl_b(b, nm.f("%s.h", sc), RAD_BF16, { T, D }); + E.q = decl_b(b, nm.f("%s.q", sc), RAD_BF16, { T, D }); + E.k = decl_b(b, nm.f("%s.k", sc), RAD_BF16, { T, D }); + E.v = decl_b(b, nm.f("%s.v", sc), RAD_BF16, { T, D }); + E.a = decl_b(b, nm.f("%s.attn", sc), RAD_BF16, { T, D }); + E.f1 = decl_b(b, nm.f("%s.fc1", sc), RAD_BF16, { T, F }); + E.f2 = decl_b(b, nm.f("%s.act", sc), RAD_BF16, { T, F }); + auto embed = [&](rad_weight w, int64_t vocab, rad_buf ids, rad_buf out) { + rad_op op = RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", D), + RAD_INT("n_vocab", vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0)), + RAD_WEIGHTS(w)); + if (ids) return rw(b, op, { ids }, { out }); + return rw(b, op, {}, { out }); + }; + E.op_tok = embed(E.tok, 49408, 0, E.x); + /* Padding rows that read token 0 (bigG's tokenizer pads with "!"). */ + if (pooled) E.op_pad = embed(E.tok, 49408, m.b_zero, E.x); + E.op_pos = embed(E.pos, kWin, m.b_pos, E.pe); + E.op_pe = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { E.x, E.pe }, { E.x }); + if (!E.op_tok || !E.op_pos || !E.op_pe || (pooled && !E.op_pad)) return RAD_E_INVAL; + E.layers.resize((size_t)L); + for (int64_t l = 0; l < L; ++l) { + TextLayer& Y = E.layers[(size_t)l]; + const char* lp = nm.ckpt("%s.encoder.layers.%lld", tm, (long long)l); + const int g = grp; + auto w = [&](const char* fmt, std::initializer_list shape) { + return wcopy(b, nm.ckpt(fmt, lp), shape, RAD_ACCESS_PER_TOKEN, g); + }; + Y.ln1w = w("%s.layer_norm1.weight", { D }); + Y.ln1b = w("%s.layer_norm1.bias", { D }); + Y.qw = w("%s.self_attn.q_proj.weight", { D, D }); + Y.qb = w("%s.self_attn.q_proj.bias", { D }); + Y.kw = w("%s.self_attn.k_proj.weight", { D, D }); + Y.kb = w("%s.self_attn.k_proj.bias", { D }); + Y.vw = w("%s.self_attn.v_proj.weight", { D, D }); + Y.vb = w("%s.self_attn.v_proj.bias", { D }); + Y.ow = w("%s.self_attn.out_proj.weight", { D, D }); + Y.ob = w("%s.self_attn.out_proj.bias", { D }); + Y.ln2w = w("%s.layer_norm2.weight", { D }); + Y.ln2b = w("%s.layer_norm2.bias", { D }); + Y.f1w = w("%s.mlp.fc1.weight", { F, D }); + Y.f1b = w("%s.mlp.fc1.bias", { F }); + Y.f2w = w("%s.mlp.fc2.weight", { D, F }); + Y.f2b = w("%s.mlp.fc2.bias", { D }); + if (!Y.ln1w || !Y.ln1b || !Y.qw || !Y.qb || !Y.kw || !Y.kb || !Y.vw || !Y.vb || !Y.ow || + !Y.ob || !Y.ln2w || !Y.ln2b || !Y.f1w || !Y.f1b || !Y.f2w || !Y.f2b) + return RAD_E_INVAL; + auto lnorm = [&](rad_weight lw, rad_weight lb) { + return rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(lw, lb)), + { E.x }, { E.h }); + }; + Y.op_ln1 = lnorm(Y.ln1w, Y.ln1b); + Y.op_q = dense(b, T, D, D, Y.qw, Y.qb, E.h, E.q); + Y.op_k = dense(b, T, D, D, Y.kw, Y.kb, E.h, E.k); + Y.op_v = dense(b, T, D, D, Y.vw, Y.vb, E.h, E.v); + Y.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", 64), + RAD_INT("gqa", 1), RAD_INT("causal", 1), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 0.125), + RAD_INT("max_seqlen", kWin)), + RAD_NOWEIGHTS), + { E.q, E.k, E.v, m.b_wcu }, { E.a }); + Y.op_o = dense(b, T, D, D, Y.ow, Y.ob, E.a, E.x, E.x); + Y.op_ln2 = lnorm(Y.ln2w, Y.ln2b); + Y.op_f1 = dense(b, T, F, D, Y.f1w, Y.f1b, E.h, E.f1); + Y.op_act = unary(b, E.quick ? "gelu_quick" : "gelu", T, F, E.f1, E.f2); + Y.op_f2 = dense(b, T, D, F, Y.f2w, Y.f2b, E.f2, E.x, E.x); + if (!Y.op_ln1 || !Y.op_q || !Y.op_k || !Y.op_v || !Y.op_attn || !Y.op_o || !Y.op_ln2 || + !Y.op_f1 || !Y.op_act || !Y.op_f2) + return RAD_E_INVAL; + if (l == tap) + E.op_tap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { E.x }, { m.b_ctx }); + } + if (!E.op_tap) return RAD_E_INVAL; + if (!pooled) return RAD_OK; + /* The pooled vector: the first window's end-of-text row through the final norm and the + * projection. */ + E.fnw = wcopy(b, nm.ckpt("%s.final_layer_norm.weight", tm), { D }, RAD_ACCESS_PER_TOKEN, + grp); + E.fnb = wcopy(b, nm.ckpt("%s.final_layer_norm.bias", tm), { D }, RAD_ACCESS_PER_TOKEN, + grp); + E.proj = wcopy(b, nm.ckpt("%s.text_projection.weight", root), { kPooled, D }, + RAD_ACCESS_PER_TOKEN, grp); + if (!E.fnw || !E.fnb || !E.proj) return RAD_E_INVAL; + E.e1 = decl_b(b, nm.f("%s.eos", sc), RAD_BF16, { 1, D }); + E.e2 = decl_b(b, nm.f("%s.eos_norm", sc), RAD_BF16, { 1, D }); + E.op_eos = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { E.x, m.b_pos }, { E.e1 }); + E.op_fn = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", D), RAD_F64("eps", 1e-5), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.fnw, E.fnb)), + { E.e1 }, { E.e2 }); + E.op_proj = dense(b, 1, kPooled, D, E.proj, 0, E.e2, m.b_pooled); + return E.op_eos && E.op_fn && E.op_proj ? RAD_OK : RAD_E_INVAL; +} + +static int declare_cond(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t T = kCondRows; + /* Positions restart in every window; the windows' bounds; a row of token-0 ids. */ + m.b_pos = decl_b(b, nm.f("cond.pos"), RAD_I32, { T }); + m.b_wcu = decl_b(b, nm.f("cond.cu"), RAD_I32, { kMaxWin + 1 }); + m.b_zero = decl_b(b, nm.f("cond.zero_ids"), RAD_I32, { kWin }); + m.b_ctx = decl_b(b, nm.f("cond.ctx"), RAD_BF16, { T, kCtx }); + m.b_pooled = decl_b(b, nm.f("cond.pooled"), RAD_BF16, { 1, kPooled }); + m.op_pos = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("start", 0), + RAD_INT("step", 1), RAD_INT("period", kWin)), + RAD_NOWEIGHTS), + {}, { m.b_pos }); + m.op_wcu = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kMaxWin + 1), RAD_INT("start", 0), + RAD_INT("step", kWin)), + RAD_NOWEIGHTS), + {}, { m.b_wcu }); + m.op_zero = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kWin), RAD_INT("start", 0), + RAD_INT("step", 0)), + RAD_NOWEIGHTS), + {}, { m.b_zero }); + if (!m.op_pos || !m.op_wcu || !m.op_zero) return RAD_E_INVAL; + m.te1.quick = true; + m.te1.ctx_col = 0; + RAD_ARCH_TRY(declare_text(b, m, m.te1, kTe1, kGrpTe1, 768, 3072, 11, 10, false)); + m.te2.quick = false; + m.te2.ctx_col = 768; + RAD_ARCH_TRY(declare_text(b, m, m.te2, kTe2, kGrpTe2, 1280, 5120, 32, 30, true)); + /* Into every lane of the request at this branch: lane l's branch r at row (2 l + r) of the + * stores. */ + m.op_store = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", kCtx), + RAD_INT("stride", 2 * (int64_t)kCondRows), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_ctx, m.b_store }, { m.b_store }); + m.op_pstore = rw(b, RAD_OP(b, "lane_store", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", kPooled), + RAD_INT("stride", 2), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_pooled, m.b_pstore }, { m.b_pstore }); + return m.op_store && m.op_pstore ? RAD_OK : RAD_E_INVAL; +} + +/* The time embedding (the timestep's sinusoid through time_embed) plus the added embedding (the + * pooled vector beside the image size's three sinusoid pairs, through label_emb), and its SiLU, + * which every residual block projects. One row an entry. */ +static int declare_emb(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int g = kGrpUnet; + auto w = [&](const char* fmt, std::initializer_list shape) { + return wcopy(b, nm.ckpt(fmt, kUnet), shape, RAD_ACCESS_PER_TOKEN, g); + }; + m.w_t1 = wcopy(b, nm.ckpt("%s.time_embed.0.weight", kUnet), { kTemb, 320 }, + RAD_ACCESS_PER_TOKEN, g, true); + m.b_t1 = w("%s.time_embed.0.bias", { kTemb }); + m.w_t2 = w("%s.time_embed.2.weight", { kTemb, kTemb }); + m.b_t2 = w("%s.time_embed.2.bias", { kTemb }); + m.w_l1 = w("%s.label_emb.0.0.weight", { kTemb, kAdd }); + m.b_l1 = w("%s.label_emb.0.0.bias", { kTemb }); + m.w_l2 = w("%s.label_emb.0.2.weight", { kTemb, kTemb }); + m.b_l2 = w("%s.label_emb.0.2.bias", { kTemb }); + if (!m.w_t1 || !m.b_t1 || !m.w_t2 || !m.b_t2 || !m.w_l1 || !m.b_l1 || !m.w_l2 || !m.b_l2) + return RAD_E_INVAL; + m.b_tproj = decl_b(b, nm.f("emb.tproj"), RAD_BF16, { 1, 320 }); + m.b_te1 = decl_b(b, nm.f("emb.t1"), RAD_BF16, { 1, kTemb }); + m.b_te1s = decl_b(b, nm.f("emb.t1s"), RAD_BF16, { 1, kTemb }); + m.b_temb = decl_b(b, nm.f("emb.temb"), RAD_BF16, { 1, kTemb }); + m.b_add = decl_b(b, nm.f("emb.add"), RAD_BF16, { 1, kAdd }); + m.b_le1 = decl_b(b, nm.f("emb.l1"), RAD_BF16, { 1, kTemb }); + m.b_le1s = decl_b(b, nm.f("emb.l1s"), RAD_BF16, { 1, kTemb }); + m.b_emb = decl_b(b, nm.f("emb.emb"), RAD_BF16, { 1, kTemb }); + m.b_embs = decl_b(b, nm.f("emb.emb_silu"), RAD_BF16, { 1, kTemb }); + m.op_tproj = tstep_embed(b, 1, 320, m.b_tproj); + m.op_t1 = dense(b, 1, kTemb, 320, m.w_t1, m.b_t1, m.b_tproj, m.b_te1); + m.op_ts = unary(b, "silu", 1, kTemb, m.b_te1, m.b_te1s); + m.op_t2 = dense(b, 1, kTemb, kTemb, m.w_t2, m.b_t2, m.b_te1s, m.b_temb); + m.op_pool = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", kPooled), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_pstore }, { m.b_add }); + /* (height, width), (0, 0), (height, width): each value's 256-wide sinusoid, laid end to end + * after the pooled vector. */ + m.op_szo = tstep_embed(b, 2, 256, m.b_add); + m.op_szc = rw(b, RAD_OP(b, "timestep_embed", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("n", 256), + RAD_F64("scale", 1.0), RAD_F64("max_period", 10000.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_zf }, { m.b_add }); + m.op_szt = tstep_embed(b, 2, 256, m.b_add); + m.op_l1 = dense(b, 1, kTemb, kAdd, m.w_l1, m.b_l1, m.b_add, m.b_le1); + m.op_ls = unary(b, "silu", 1, kTemb, m.b_le1, m.b_le1s); + m.op_l2 = dense(b, 1, kTemb, kTemb, m.w_l2, m.b_l2, m.b_le1s, m.b_emb, m.b_temb); + m.op_es = unary(b, "silu", 1, kTemb, m.b_emb, m.b_embs); + return m.op_tproj && m.op_t1 && m.op_ts && m.op_t2 && m.op_pool && m.op_szo && m.op_szc && + m.op_szt && m.op_l1 && m.op_ls && m.op_l2 && m.op_es + ? RAD_OK : RAD_E_INVAL; +} + +/* The UNet, in the order a step runs it. */ +static int declare_unet(RadBuilder* b, Model& m) { + Net& n = m.net; + Names& nm = m.nm; + n.b = b; + n.nm = &nm; + n.stats = decl_b(b, nm.f("unet.gn_stats"), RAD_F32, { kGnStats }); + n.iota = m.b_iota; + n.store = m.b_store; + n.xin = m.b_xin; + n.eps = m.b_eps; + V emb_s{}; + emb_s.buf = m.b_embs; + emb_s.lvl = kRowsOne; + emb_s.pitch = kTemb; + V ctx{}; + ctx.buf = m.b_store; + ctx.lvl = kRowsCond; + ctx.pitch = kCtx; + const char* U = kUnet; + /* Every op's sequence bounds, off the iota table. */ + const V cu1 = n.cu(1), cu2 = n.cu(2), cuc = n.cu(kRowsCond); + /* ---- the input blocks; each output is kept for its skip connection */ + n.grp = kGrpUnet + 1; + Opd xin = Net::Kd(Opd::XIN); + xin.v.buf = m.b_xin; + V h = n.conv_direct(xin, 0, kLatC, 320, nm.ckpt("%s.input_blocks.0.0", U)); + std::vector skips{ h }; + struct In { int64_t c; int depth; bool down; }; + const In ins[] = { { 320, 0, false }, { 320, 0, false }, { 320, 0, true }, + { 640, 2, false }, { 640, 2, false }, { 640, 0, true }, + { 1280, 10, false }, { 1280, 10, false } }; + auto st = [&](const V& x, const char* pre, int depth) { + const V& cq = x.lvl == 1 ? cu1 : cu2; + return n.transformer(x, pre, depth, ctx, cq, cuc); + }; + for (int i = 1; i <= 8; ++i) { + const In& s = ins[i - 1]; + n.grp = kGrpUnet + 1 + i; + if (s.down) { + h = n.conv3(h, h.pitch, nm.ckpt("%s.input_blocks.%d.0.op", U, i), 2, 1); + } else { + h = n.resblock(h, s.c, nm.ckpt("%s.input_blocks.%d.0", U, i), emb_s); + if (s.depth) h = st(h, nm.ckpt("%s.input_blocks.%d.1", U, i), s.depth); + } + skips.push_back(h); + } + /* ---- the middle block */ + n.grp = kGrpUnet + 10; + h = n.resblock(h, 1280, nm.ckpt("%s.middle_block.0", U), emb_s); + h = st(h, nm.ckpt("%s.middle_block.1", U), 10); + h = n.resblock(h, 1280, nm.ckpt("%s.middle_block.2", U), emb_s); + /* ---- the output blocks: the matching input block's output concatenated after h */ + struct Out { int64_t c; int depth; bool up; }; + const Out outs[] = { { 1280, 10, false }, { 1280, 10, false }, { 1280, 10, true }, + { 640, 2, false }, { 640, 2, false }, { 640, 2, true }, + { 320, 0, false }, { 320, 0, false }, { 320, 0, false } }; + for (int i = 0; i < 9; ++i) { + const Out& s = outs[i]; + n.grp = kGrpUnet + 11 + i; + const V skip = skips.back(); + skips.pop_back(); + V cat = n.concat(h, skip); + h = n.resblock(cat, s.c, nm.ckpt("%s.output_blocks.%d.0", U, i), emb_s); + int sub = 1; + if (s.depth) h = st(h, nm.ckpt("%s.output_blocks.%d.%d", U, i, sub++), s.depth); + if (s.up) h = n.conv3(h, h.pitch, nm.ckpt("%s.output_blocks.%d.%d.conv", U, i, sub), 1, 2); + } + /* ---- the output: GroupNorm, SiLU, conv to the latent's channels */ + n.grp = kGrpUnet + 20; + V o = n.gn(h, nm.ckpt("%s.out.0", U), 1e-5, true); + Opd eps = Net::Kd(Opd::EPS); + eps.v.buf = m.b_eps; + eps.v.lvl = 0; + eps.v.pitch = kLatC; + Opd oi = Net::I(o); + n.conv_direct(oi, 0, 320, kLatC, nm.ckpt("%s.out.2", U), &eps); + for (const UOp& u : n.ops) if (!u.op) return RAD_E_INVAL; + return RAD_OK; +} + +/* The decoder: the f32 latent divided by the scaling factor, to bf16, then the VAE's decoder in + * diffusers' AutoencoderKL names (GroupNorm residual blocks, a mid-block attention, three 2x + * nearest upsamplings). */ +static int declare_decoder(RadBuilder* b, Model& m) { + Vae& v = m.dec; + Names& nm = m.nm; + v.nm = &nm; + v.b = b; + v.scope = "vdec"; + v.down = false; + v.first_group = kGrpVae; + v.base_px = kMaxImageTokens; + const int64_t NT = kMaxImageTokens; + m.b_dlf = decl_b(b, nm.f("vdec.lat_f32"), RAD_F32, { NT, kLatC }); + m.b_decin = decl_b(b, nm.f("vdec.in"), RAD_BF16, { NT, kLatC }); + char mul[64], zero[16]; + const double s = 1.0 / kVaeScale; + std::snprintf(mul, sizeof mul, "%.9g %.9g %.9g %.9g", s, s, s, s); + std::snprintf(zero, sizeof zero, "0 0 0 0"); + static thread_local std::string smul, szero; + smul = mul; + szero = zero; + m.op_dscale = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", kLatC), + RAD_STR("mul", smul.c_str()), + RAD_STR("add", szero.c_str()), + RAD_STR("mode", "fma"), RAD_STR("dtype", "f32"), + RAD_INT("round", 0)), + RAD_NOWEIGHTS), + { m.b_state, m.b_prev }, { m.b_dlf }); + m.op_dcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, NT), RAD_INT("n", kLatC), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { m.b_dlf }, { m.b_decin }); + if (!m.op_dscale || !m.op_dcast) return RAD_E_INVAL; + const int64_t ch[4] = { 512, 512, 256, 128 }; + const double eps = 1e-6; + VImg x{ m.b_decin, kLatC, 0 }; + x = v.conv(x, kLatC, 1, 1, 1, "same", "vae.post_quant_conv"); + x = v.conv(x, ch[0], 3, 1, 1, "same", "vae.decoder.conv_in"); + x = v.resblock_gn(x, x.ch, "vae.decoder.mid_block.resnets.0", kGroups, eps); + x = v.attention_gn(x, "vae.decoder.mid_block.attentions.0", kGroups, eps); + x = v.resblock_gn(x, x.ch, "vae.decoder.mid_block.resnets.1", kGroups, eps); + for (int i = 0; i < 4; ++i) { + for (int r = 0; r < 3; ++r) + x = v.resblock_gn(x, ch[i], nm.f("vae.decoder.up_blocks.%d.resnets.%d", i, r), kGroups, + eps); + if (i < 3) + x = v.conv(x, x.ch, 3, 1, 2, "same", + nm.f("vae.decoder.up_blocks.%d.upsamplers.0.conv", i)); + } + x = v.gnorm(x, true, "vae.decoder.conv_norm_out", kGroups, eps); + m.dec_out = v.conv(x, 3, 3, 1, 1, "same", "vae.decoder.conv_out"); + if (!m.dec_out.buf) return RAD_E_INVAL; + for (const VOp& o : v.ops) if (!o.op) return RAD_E_INVAL; + const int64_t px = NT * 64; + m.b_img = decl_b(b, nm.f("image_out"), RAD_U8, { px * 3 }, RAD_BUF_PERSIST); + m.op_rgb = rw(b, RAD_OP(b, "to_rgba8", + RAD_PARAMS(RAD_RANGE("M", 1, px), RAD_INT("n", 3), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.dec_out.buf }, { m.b_img }); + return m.op_rgb ? RAD_OK : RAD_E_INVAL; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + if (ctx->world_size > 1) { + fprintf(stderr, "radiance: sdxl runs on one card; serve it with a tensor-parallel size " + "of 1\n"); + return RAD_E_UNSUPPORTED; + } + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + Names& nm = m.nm; + m.pred = rad_meta_gets(meta, "sdxl.prediction", "eps"); + m.zero_snr = rad_meta_geti(meta, "sdxl.zero_snr", 0) != 0; + if (m.pred != "eps" && m.pred != "v") { + fprintf(stderr, "radiance: sdxl: prediction '%s' is neither eps nor v\n", m.pred.c_str()); + return RAD_E_UNSUPPORTED; + } + /* The weights are served bf16; the release's f16 is cast by the recipe. The first UNet weight + * is mapped here and declared with the embeddings. */ + { + const char* probe = nm.ckpt("%s.time_embed.0.weight", kUnet); + if (map_copy(b, probe, probe) < 0) return RAD_E_INVAL; + const uint32_t dt = weight_codes_dtype(b, probe, RAD_BF16); + if (dt != RAD_BF16) { + fprintf(stderr, "radiance: sdxl: the UNet is stored %s; convert with " + "data/recipes/sdxl-bf16.recipe, which casts the release to bf16\n", + rad_dtype_name(dt)); + return RAD_E_UNSUPPORTED; + } + } + const int64_t max_img = std::max(ctx->max_tok, kMaxImageTokens); + const int64_t lane_rows = (int64_t)kMaxLanes * kMaxImageTokens; + m.b_state = decl_b(b, nm.f("lat_state"), RAD_F32, { lane_rows, kLatC }, RAD_BUF_PERSIST); + m.b_hist = decl_b(b, nm.f("lat_hist"), RAD_F32, { lane_rows, kLatC }, RAD_BUF_PERSIST); + m.b_prev = decl_b(b, nm.f("lat_preview"), RAD_F32, { lane_rows, kLatC }, RAD_BUF_PERSIST); + m.b_store = decl_b(b, nm.f("cond_store"), RAD_BF16, + { 2 * (int64_t)kMaxLanes * kCondRows, kCtx }, RAD_BUF_PERSIST); + m.b_pstore = decl_b(b, nm.f("pooled_store"), RAD_BF16, { 2 * (int64_t)kMaxLanes, kPooled }, + RAD_BUF_PERSIST); + m.b_xin = decl_b(b, nm.f("unet_in"), RAD_BF16, { max_img, kLatC }, RAD_BUF_PERSIST); + m.b_eps = decl_b(b, nm.f("unet_out"), RAD_BF16, { max_img, kLatC }, RAD_BUF_PERSIST); + m.b_iota = decl_b(b, nm.f("iota"), RAD_I32, { kMaxImageTokens + 1 }, RAD_BUF_PERSIST); + m.b_zf = decl_b(b, nm.f("zeros_f32"), RAD_F32, { 1, 2 }, RAD_BUF_PERSIST); + /* ---- adapter key names: kohya's `lora_unet_` over the UNet's own single-file paths, and + * `lora_te1_` / `lora_te2_` over the two text encoders, whose layers are named as + * transformers' CLIPTextModel names them in both. */ + RAD_ARCH_TRY(lora_names(b, "model.diffusion_model.", kLoraDiffusionSpellings, {})); + RAD_ARCH_TRY(lora_names(b, "conditioner.embedders.0.transformer.", "lora_te1_", {})); + RAD_ARCH_TRY(lora_names(b, "conditioner.embedders.1.transformer.", "lora_te2_", {})); + RAD_ARCH_TRY(declare_cond(b, m)); + + /* ---- a denoising pass: the tables, the model input, then per entry the embeddings and the + * UNet, then the sampler */ + m.op_iota = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, kMaxImageTokens + 1), + RAD_INT("start", 0), RAD_INT("step", 1)), + RAD_NOWEIGHTS), + {}, { m.b_iota }); + m.op_zf = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", 2), + RAD_STR("dtype", "f32"), RAD_F64("value", 0.0)), + RAD_NOWEIGHTS), + {}, { m.b_zf }); + m.op_kdin = rw(b, RAD_OP(b, "kd_input", + RAD_PARAMS(RAD_RANGE("M", 1, max_img), RAD_INT("n", kLatC), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_state }, { m.b_state, m.b_xin }); + if (!m.op_iota || !m.op_zf || !m.op_kdin) return RAD_E_INVAL; + RAD_ARCH_TRY(declare_emb(b, m)); + RAD_ARCH_TRY(declare_unet(b, m)); + m.op_kdstep = rw(b, RAD_OP(b, "kd_step", + RAD_PARAMS(RAD_RANGE("M", 1, max_img), RAD_INT("n", kLatC), + RAD_INT("stride", (int64_t)kMaxImageTokens), + RAD_STR("pred", m.pred.c_str()), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_eps, m.b_state, m.b_hist, m.b_prev }, + { m.b_state, m.b_hist, m.b_prev }); + if (!m.op_kdstep) return RAD_E_INVAL; + RAD_ARCH_TRY(declare_decoder(b, m)); + + /* ---- what the core drives */ + if (!ctx->shape_probe) { + RadGeneratorDecl d{}; + d.name = "sdxl"; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.tmpl_text = "{prompt}"; + d.tmpl_edit = "{prompt}"; + d.drop_prefix = ""; + d.latent_channels = kLatC; + d.latent_scale = 8; + /* Two 2x downsamplings: the latent's sides are multiples of 4. */ + d.size_multiple = 32; + d.pixel_channels = 3; + d.slot_rows = 1; + d.max_tokens = kMaxImageTokens; + d.max_refs = 0; + d.ref_area = 1; + d.default_width = 1024; + d.default_height = 1024; + d.default_steps = 28; + d.n_sigmas = 0; + d.sigmas = nullptr; + d.shift = 1.0; + d.default_cfg = 6.0; + d.cfg_original = 0; + d.default_negative = ""; + d.max_lanes = kMaxLanes; + d.image_out = m.b_img; + d.cond_rows = kCondRows; + d.rope_hw_scale = 1.0; + d.pad_multiple = 0; + d.pad_token = kEos; + d.train_steps = 1000; + d.beta_schedule = RAD_GEN_BETAS_SCALED_LINEAR; + d.beta_start = 0.00085; + d.beta_end = 0.012; + d.zero_snr = m.zero_snr ? 1 : 0; + d.samplers = (1u << RAD_GEN_SAMPLER_EULER) | (1u << RAD_GEN_SAMPLER_EULER_ANCESTRAL) | + (1u << RAD_GEN_SAMPLER_DPMPP_2M); + d.default_sampler = RAD_GEN_SAMPLER_EULER_ANCESTRAL; + d.default_scheduler = RAD_GEN_SCHED_NORMAL; + d.chunk_tokens = kWin - 2; + d.chunk_bos = kBos; + d.chunk_eos = kEos; + RAD_ARCH_TRY(rad_declare_generator(b, &d)); + } + rad_note(b, "Stable Diffusion XL -- CLIP ViT-L and bigG, UNet %zu ops (%s prediction%s), " + "VAE %zu ops, bf16", + m.net.ops.size(), m.pred.c_str(), m.zero_snr ? ", zero terminal SNR" : "", + m.dec.ops.size()); + return RAD_OK; +} + +/* ================================================================== step */ +static void step_text(RadCtx* c, const RadBatch* batch, const Model& m, const TextEnc& E, + int64_t T, const std::vector& eos) { + const int64_t D = E.D, nw = T / kWin; + const RadOperand cu = brows(m.b_wcu, nw + 1); + RAD_ISSUE_N(c, E.op_tok, T, praw(batch->token_ids, RAD_I32, T), RAD_W(E.tok), brows(E.x, T)); + if (E.op_pad) + for (int64_t w = 0; w < nw; ++w) { + const int64_t first = w * kWin + eos[(size_t)w] + 1, n = (w + 1) * kWin - first; + if (n > 0) + RAD_ISSUE_N(c, E.op_pad, n, brows(m.b_zero, n), RAD_W(E.tok), + brow_slice(E.x, first, n, D)); + } + RAD_ISSUE_N(c, E.op_pos, T, brows(m.b_pos, T), RAD_W(E.pos), brows(E.pe, T)); + RAD_ISSUE_N(c, E.op_pe, T, brows(E.x, T), brows(E.pe, T), brows(E.x, T)); + for (int64_t l = 0; l < E.L; ++l) { + const TextLayer& Y = E.layers[(size_t)l]; + RAD_ISSUE_N(c, Y.op_ln1, T, brows(E.x, T), RAD_W(Y.ln1w), RAD_W(Y.ln1b), brows(E.h, T)); + RAD_ISSUE_N(c, Y.op_q, T, brows(E.h, T), RAD_W(Y.qw), RAD_W(Y.qb), RAD_NONE, brows(E.q, T)); + RAD_ISSUE_N(c, Y.op_k, T, brows(E.h, T), RAD_W(Y.kw), RAD_W(Y.kb), RAD_NONE, brows(E.k, T)); + RAD_ISSUE_N(c, Y.op_v, T, brows(E.h, T), RAD_W(Y.vw), RAD_W(Y.vb), RAD_NONE, brows(E.v, T)); + RAD_ISSUE_N(c, Y.op_attn, T, brows(E.q, T), brows(E.k, T), brows(E.v, T), cu, + brows(E.a, T)); + RAD_ISSUE_N(c, Y.op_o, T, brows(E.a, T), RAD_W(Y.ow), RAD_W(Y.ob), brows(E.x, T), + brows(E.x, T)); + RAD_ISSUE_N(c, Y.op_ln2, T, brows(E.x, T), RAD_W(Y.ln2w), RAD_W(Y.ln2b), brows(E.h, T)); + RAD_ISSUE_N(c, Y.op_f1, T, brows(E.h, T), RAD_W(Y.f1w), RAD_W(Y.f1b), RAD_NONE, + brows(E.f1, T)); + RAD_ISSUE_N(c, Y.op_act, T, brows(E.f1, T), brows(E.f2, T)); + RAD_ISSUE_N(c, Y.op_f2, T, brows(E.f2, T), RAD_W(Y.f2w), RAD_W(Y.f2b), brows(E.x, T), + brows(E.x, T)); + if (l == E.tap) + RAD_ISSUE_N(c, E.op_tap, T, brows(E.x, T), bcol(m.b_ctx, E.ctx_col, D, T)); + } + if (!E.op_eos) return; + /* b_pos holds 0..76 in its first window: row k of it is the index k. */ + RAD_ISSUE_N(c, E.op_eos, 1, brows(E.x, T), brow_slice(m.b_pos, eos[0], 1, 1), brows(E.e1, 1)); + RAD_ISSUE_N(c, E.op_fn, 1, brows(E.e1, 1), RAD_W(E.fnw), RAD_W(E.fnb), brows(E.e2, 1)); + RAD_ISSUE_N(c, E.op_proj, 1, brows(E.e2, 1), RAD_W(E.proj), brows(m.b_pooled, 1)); +} + +/* Both text encoders over the prompt's windows, the context and pooled vector into every lane + * of the request at this branch. */ +static void step_cond(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t T = batch->n_tok; + if (T <= 0 || T % kWin || T > kCondRows || !G->tokens_h) { + rad_step_fail(c, "sdxl: a conditioning pass is not whole 77-token windows"); + return; + } + const int64_t nw = T / kWin; + /* Each window's end-of-text marker: the first after its start marker. */ + std::vector eos((size_t)nw, kWin - 1); + for (int64_t w = 0; w < nw; ++w) + for (int64_t k = 1; k < kWin; ++k) + if (G->tokens_h[w * kWin + k] == kEos) { eos[(size_t)w] = k; break; } + RAD_ISSUE_N(c, m.op_pos, T, brows(m.b_pos, T)); + RAD_ISSUE_N(c, m.op_wcu, nw + 1, brows(m.b_wcu, nw + 1)); + RAD_ISSUE_N(c, m.op_zero, kWin, brows(m.b_zero, kWin)); + step_text(c, batch, m, m.te1, T, eos); + step_text(c, batch, m, m.te2, T, eos); + const int64_t br = G->branch; + RAD_ISSUE_N(c, m.op_store, T, brows(m.b_ctx, T), praw(G->lane, RAD_I32, G->n_lane), + brow_slice(m.b_store, br * kCondRows, + 2 * (int64_t)kMaxLanes * kCondRows - br * kCondRows, kCtx)); + RAD_ISSUE_N(c, m.op_pstore, 1, brows(m.b_pooled, 1), praw(G->lane, RAD_I32, G->n_lane), + brow_slice(m.b_pstore, br, 2 * (int64_t)kMaxLanes - br, kPooled)); +} + +/* The model input of every entry, then each entry's embeddings and UNet at its own size, then the + * sampler's step over every entry. */ +static void step_denoise(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t S = batch->n_seq, NI = G->n_img; + if (!G->entry_h || !G->timestep || !G->size_px) { + rad_step_fail(c, "sdxl: a denoising pass without its per-entry geometry"); + return; + } + const int64_t LR = (int64_t)kMaxLanes * kMaxImageTokens; + const RadOperand icu = praw(G->img_cu, RAD_I32, S + 1); + RAD_ISSUE_N(c, m.op_iota, kMaxImageTokens + 1, brows(m.b_iota, kMaxImageTokens + 1)); + RAD_ISSUE_N(c, m.op_zf, 1, brows(m.b_zf, 1)); + RAD_ISSUE_N(c, m.op_kdin, NI, praw(G->sigma, RAD_F32, S), praw(G->pair, RAD_I32, S), + praw(G->lane, RAD_I32, S), praw(G->flags, RAD_I32, S), + praw(G->seed, RAD_U32, 2 * S), icu, brows(m.b_state, LR), brows(m.b_xin, NI)); + int64_t row0 = 0; + for (int64_t e = 0; e < S; ++e) { + const int32_t* eh = G->entry_h + 4 * e; + Geo g; + g.cond = eh[0]; + g.h = eh[1] / 8; + g.w = eh[2] / 8; + g.row0 = row0; + const int64_t lane = G->lane_dh[e], br = eh[3]; + g.store_row = (2 * lane + br) * kCondRows; + g.pool_row = 2 * lane + br; + if (g.h % 4 || g.w % 4 || g.px(0) > kMaxImageTokens || g.cond > kCondRows) { + rad_step_fail(c, "sdxl: an entry's size is not one this model takes"); + return; + } + /* ---- the time and added embeddings */ + RAD_ISSUE_N(c, m.op_tproj, 1, praw(G->timestep + e, RAD_F32, 1), brows(m.b_tproj, 1)); + RAD_ISSUE_N(c, m.op_t1, 1, brows(m.b_tproj, 1), RAD_W(m.w_t1), RAD_W(m.b_t1), RAD_NONE, + brows(m.b_te1, 1)); + RAD_ISSUE_N(c, m.op_ts, 1, brows(m.b_te1, 1), brows(m.b_te1s, 1)); + RAD_ISSUE_N(c, m.op_t2, 1, brows(m.b_te1s, 1), RAD_W(m.w_t2), RAD_W(m.b_t2), RAD_NONE, + brows(m.b_temb, 1)); + char* add = (char*)rad_buf_ptr(c, m.b_add); + RAD_ISSUE_N(c, m.op_pool, 1, brow_slice(m.b_pstore, g.pool_row, 1, kPooled), + RAD_P_T2(add, RAD_BF16, 1, kPooled)); + RAD_ISSUE_N(c, m.op_szo, 2, praw(G->size_px + 2 * e, RAD_F32, 2), + RAD_P_T2(add + 2 * kPooled, RAD_BF16, 2, 256)); + RAD_ISSUE_N(c, m.op_szc, 2, praw(rad_buf_ptr(c, m.b_zf), RAD_F32, 2), + RAD_P_T2(add + 2 * (kPooled + 512), RAD_BF16, 2, 256)); + RAD_ISSUE_N(c, m.op_szt, 2, praw(G->size_px + 2 * e, RAD_F32, 2), + RAD_P_T2(add + 2 * (kPooled + 1024), RAD_BF16, 2, 256)); + RAD_ISSUE_N(c, m.op_l1, 1, brows(m.b_add, 1), RAD_W(m.w_l1), RAD_W(m.b_l1), RAD_NONE, + brows(m.b_le1, 1)); + RAD_ISSUE_N(c, m.op_ls, 1, brows(m.b_le1, 1), brows(m.b_le1s, 1)); + RAD_ISSUE_N(c, m.op_l2, 1, brows(m.b_le1s, 1), RAD_W(m.w_l2), RAD_W(m.b_l2), + brows(m.b_temb, 1), brows(m.b_emb, 1)); + RAD_ISSUE_N(c, m.op_es, 1, brows(m.b_emb, 1), brows(m.b_embs, 1)); + /* ---- the UNet */ + m.net.issue(c, g); + row0 += g.px(0); + } + if (row0 != NI) { + rad_step_fail(c, "sdxl: the entries' images do not add up to the pass's image rows"); + return; + } + RAD_ISSUE_N(c, m.op_kdstep, NI, brows(m.b_eps, NI), praw(G->sigma, RAD_F32, S), + praw(G->sigma_next, RAD_F32, S), praw(G->sigma_prev, RAD_F32, S), + praw(G->cfg, RAD_F32, S), praw(G->pair, RAD_I32, S), praw(G->lane, RAD_I32, S), + praw(G->flags, RAD_I32, S), praw(G->seed, RAD_U32, 2 * S), + praw(G->sampler, RAD_I32, S), praw(G->step, RAD_I32, S), icu, + brows(m.b_state, LR), brows(m.b_hist, LR), brows(m.b_prev, LR)); +} + +/* One image's latent to RGB. */ +static void step_decode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadGenBatch* G = batch->gen_b; + const int64_t H = G->dec_height / 8, W = G->dec_width / 8, n = H * W; + const rad_buf src = G->dec_preview ? m.b_prev : m.b_state; + RAD_ISSUE_N(c, m.op_dscale, n, + brow_slice(src, (int64_t)G->dec_lane * kMaxImageTokens, n, kLatC), + brows(m.b_dlf, n)); + RAD_ISSUE_N(c, m.op_dcast, n, brows(m.b_dlf, n), brows(m.b_decin, n)); + m.dec.issue(c, H, W, praw(batch->cu_seqlens, RAD_I32, 2), nullptr); + const int64_t npx = (int64_t)G->dec_height * G->dec_width; + RAD_ISSUE_N(c, m.op_rgb, npx, RAD_P_T2(rad_buf_ptr(c, m.dec_out.buf), RAD_BF16, npx, 3), + RAD_P_T2(rad_buf_ptr(c, m.b_img), RAD_U8, npx, 3)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->gen_b) { + rad_step_fail(c, "sdxl is an image generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_COND: step_cond(c, batch, m); return; + case RAD_GEN_PASS_DENOISE: step_denoise(c, batch, m); return; + case RAD_GEN_PASS_DECODE: step_decode(c, batch, m); return; + default: rad_step_fail(c, "sdxl: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +/* The rows a pass carries: one image at the largest size with guidance, its conditioning both + * ways. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = 2 * ((int64_t)kMaxImageTokens + kCondRows); + out->gen_patches = 0; + return RAD_OK; +} + +} /* namespace sdxl */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(sdxl) +RAD_ARCH_PLUGIN(sdxl, "sdxl", "", "0.1.0", + "Stable Diffusion XL and its finetunes (Illustrious, NoobAI, Pony): CLIP ViT-L and " + "OpenCLIP bigG text encoders, a 2.6B UNet sampled by k-diffusion's Euler, Euler " + "ancestral or DPM++ 2M, and the SDXL VAE; bf16, from the single-file checkpoint") +#endif diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 6559f969..3b008686 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -125,6 +125,9 @@ public: int declare_pooled(rad_buf b); int declare_drafter(const RadDrafterDecl* d); int drafter_shared_kv(int pos_offset); + int lora_root(const char* native, const char* spellings); + int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo, + int64_t from_hi, int64_t to_lo); int declare_encoder(const RadEncoderDecl* d); int declare_generator(const RadGeneratorDecl* d); int declare_audio_generator(const RadAudioGenDecl* d); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 236f2c4c..e97cac62 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -942,7 +942,7 @@ int Builder::decl_name_map(const RadNameMap* m) { } if (m->mode != RAD_MAP_COPY && m->mode != RAD_MAP_CONCAT && m->mode != RAD_MAP_WNORM && m->mode != RAD_MAP_ROWS && m->mode != RAD_MAP_TRANSPOSE && m->mode != RAD_MAP_EMA && - m->mode != RAD_MAP_TAP) { + m->mode != RAD_MAP_TAP && m->mode != RAD_MAP_COLS) { err(RAD_E_INVAL, "name map for '%s': unknown mode %d", m->declared, m->mode); return RAD_E_INVAL; } @@ -953,9 +953,11 @@ int Builder::decl_name_map(const RadNameMap* m) { : "the magnitude and the direction", m->n_src); return RAD_E_INVAL; } - if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP) && m->n_src != 1) { + if ((m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_TAP || m->mode == RAD_MAP_COLS) && + m->n_src != 1) { err(RAD_E_INVAL, "name map for '%s': a %s map names one source, not %d", m->declared, - m->mode == RAD_MAP_TAP ? "tap" : "transpose", m->n_src); + m->mode == RAD_MAP_TAP ? "tap" : m->mode == RAD_MAP_COLS ? "column" : "transpose", + m->n_src); return RAD_E_INVAL; } @@ -984,14 +986,20 @@ int Builder::decl_name_map(const RadNameMap* m) { m->declared, i, m->src_index[i], (long long)m->src_rows[i]); return RAD_E_INVAL; } + if (m->mode == RAD_MAP_COLS && (m->src_index[0] < 0 || m->src_rows[0] <= 0)) { + err(RAD_E_INVAL, "name map for '%s': the column range starts at %d and holds %lld columns", + m->declared, m->src_index[0], (long long)m->src_rows[0]); + return RAD_E_INVAL; + } - /* A CONCAT map may be declared in pieces; any other repeat is an error. + /* A CONCAT, ROWS or EMA map may be declared in pieces; any other repeat is an error. * * `src[8]` is the ABI's cap, and a sharded checkpoint exceeds it: Qwen3.8-Flash-Next stores * its n-gram embedding as 128 tensors `...ngram_embedding.shard_K.weight`. Growing the array * would cost ~80 MB of Program (one map per declared weight, ~50K weights). So successive * CONCAT maps for one name extend it in call order, and rad-convert joins their sources end - * to end (map_concat_shards() in arch/common/rad_arch.h). + * to end (map_concat_shards() in arch/common/rad_arch.h). ROWS maps extend the same way (a + * row permutation is one piece a row). * * Other repeats are refused: a lookup built with std::map::emplace would silently keep the * first, so a copy-paste mistake would convert weights from the wrong tensors. */ @@ -999,11 +1007,12 @@ int Builder::decl_name_map(const RadNameMap* m) { if (seen != name_map_first_.end()) { const RadNameMap& first = prog_.name_map[seen->second]; const bool joins = (c.mode == RAD_MAP_CONCAT && first.mode == RAD_MAP_CONCAT) || - (c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA); + (c.mode == RAD_MAP_EMA && first.mode == RAD_MAP_EMA) || + (c.mode == RAD_MAP_ROWS && first.mode == RAD_MAP_ROWS); if (!joins) { - err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT or EMA map may " - "be extended -- a repeated COPY map means two sources for one weight, " - "and which one wins is not something a declaration can express", + err(RAD_E_INVAL, "name map for '%s': declared twice, and only a CONCAT, ROWS or EMA " + "map may be extended -- a repeated COPY map means two sources for one " + "weight, and which one wins is not something a declaration can express", c.declared); return RAD_E_INVAL; } @@ -1232,7 +1241,32 @@ int Builder::declare_generator(const RadGeneratorDecl* d) { (long long)d->default_height, (long long)d->max_lanes); return RAD_E_INVAL; } - if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) || + if (d->train_steps < 0) { + err(RAD_E_INVAL, "declare_generator '%s': train_steps %d is negative", nm, + (int)d->train_steps); + return RAD_E_INVAL; + } + if (d->train_steps > 0) { + /* A discrete-time denoiser: its own schedule, a sampler it serves by default. */ + const uint32_t all = (1u << RAD_GEN_SAMPLER_COUNT) - 1; + if (d->train_steps < 2 || !(d->beta_start > 0) || !(d->beta_end > d->beta_start) || + !(d->beta_end < 1) || + (d->beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR && + d->beta_schedule != RAD_GEN_BETAS_LINEAR) || + d->n_sigmas != 0 || d->default_steps <= 0 || (d->samplers & ~all) || !d->samplers || + d->default_sampler < 0 || d->default_sampler >= RAD_GEN_SAMPLER_COUNT || + !(d->samplers & (1u << d->default_sampler)) || d->default_scheduler < 0 || + d->default_scheduler >= RAD_GEN_SCHED_COUNT || + !(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0))) { + err(RAD_E_INVAL, "declare_generator '%s': the discrete-time sampler is incomplete (%d " + "timesteps, betas %g..%g kind %d, %lld default steps, samplers 0x%x " + "default %d, scheduler %d, %d fixed sigmas, guidance %g)", nm, + (int)d->train_steps, d->beta_start, d->beta_end, (int)d->beta_schedule, + (long long)d->default_steps, (unsigned)d->samplers, (int)d->default_sampler, + (int)d->default_scheduler, (int)d->n_sigmas, d->default_cfg); + return RAD_E_INVAL; + } + } else if (d->n_sigmas < 0 || (d->n_sigmas > 0 && !d->sigmas) || (d->n_sigmas == 0 && d->default_steps <= 0) || !(d->default_cfg >= (d->cfg_original ? 0.0 : 1.0)) || (d->dyn_shift && (d->max_seq <= d->base_seq || d->base_seq <= 0)) || @@ -1244,6 +1278,23 @@ int Builder::declare_generator(const RadGeneratorDecl* d) { d->shift_terminal, d->default_cfg); return RAD_E_INVAL; } + if (d->sigma_grid < 0 || d->min_tokens < 0 || (d->aux_tokens && d->aux_max_tokens <= 0)) { + err(RAD_E_INVAL, "declare_generator '%s': sigma_grid %d, min_tokens %d and a second " + "tokenizer of at most %lld tokens are not a schedule and a prompt it can " + "read", nm, (int)d->sigma_grid, (int)d->min_tokens, + (long long)d->aux_max_tokens); + return RAD_E_INVAL; + } + if (d->chunk_tokens < 0 || + (d->chunk_tokens > 0 && + (!joint || d->pad_multiple != 0 || d->pad_token < 0 || d->chunk_bos < 0 || + d->chunk_eos < 0 || d->cond_rows % (d->chunk_tokens + 2) != 0))) { + err(RAD_E_INVAL, "declare_generator '%s': a prompt in windows of %d tokens needs the joint " + "layout without pad_multiple, bos, eos and pad tokens, and cond_rows a " + "whole number of windows (cond_rows %lld)", nm, (int)d->chunk_tokens, + (long long)d->cond_rows); + return RAD_E_INVAL; + } for (int i = 0; i < d->n_sigmas; ++i) if (!(d->sigmas[i] > 0.0 && d->sigmas[i] <= 1.0) || (i > 0 && !(d->sigmas[i] < d->sigmas[i - 1]))) { @@ -1764,6 +1815,69 @@ int Builder::drafter_shared_kv(int pos_offset) { return RAD_OK; } +int Builder::lora_root(const char* native, const char* spellings) { + if (finished_) { + err(RAD_E_STATE, "lora_root after declare finished"); + return RAD_E_STATE; + } + if (!native || !*native) { + err(RAD_E_INVAL, "lora_root: an empty checkpoint prefix would put every tensor in one " + "network; name the prefix the network's tensors share"); + return RAD_E_INVAL; + } + for (const LoraRoot& r : prog_.lora_roots) + if (r.native == native) { + err(RAD_E_INVAL, "lora_root '%s' declared twice", native); + return RAD_E_INVAL; + } + LoraRoot r; + r.native = native; + std::string cur; + for (const char* p = spellings ? spellings : "";; ++p) { + if (*p && *p != ' ') { cur += *p; continue; } + if (!cur.empty()) r.spellings.push_back(cur == "-" ? std::string() : cur); + cur.clear(); + if (!*p) break; + } + prog_.lora_roots.push_back(std::move(r)); + return RAD_OK; +} + +int Builder::lora_alias(const char* native, const char* from, const char* to, int64_t from_lo, + int64_t from_hi, int64_t to_lo) { + if (finished_) { + err(RAD_E_STATE, "lora_alias after declare finished"); + return RAD_E_STATE; + } + bool root = false; + for (const LoraRoot& r : prog_.lora_roots) root = root || (native && r.native == native); + if (!root) { + err(RAD_E_INVAL, "lora_alias '%s': its root '%s' is not declared (rad_lora_root first)", + from ? from : "", native ? native : ""); + return RAD_E_INVAL; + } + if (!from || !*from || !to || !*to) { + err(RAD_E_INVAL, "lora_alias under '%s': an empty module path", native); + return RAD_E_INVAL; + } + auto hashes = [](const char* s) { int n = 0; for (; *s; ++s) n += *s == '#'; return n; }; + if (hashes(from) != hashes(to)) { + err(RAD_E_INVAL, "lora_alias '%s' -> '%s': %d index placeholders against %d", from, to, + hashes(from), hashes(to)); + return RAD_E_INVAL; + } + if (from_lo < 0 || to_lo < 0 || (from_hi != 0 && from_hi <= from_lo)) { + err(RAD_E_INVAL, "lora_alias '%s' -> '%s': rows [%lld, %lld) to %lld", from, to, + (long long)from_lo, (long long)from_hi, (long long)to_lo); + return RAD_E_INVAL; + } + LoraAlias a; + a.root = native; a.from = from; a.to = to; + a.from_lo = from_lo; a.from_hi = from_hi; a.to_lo = to_lo; + prog_.lora_aliases.push_back(std::move(a)); + return RAD_OK; +} + void Builder::note_v(const char* f, va_list ap) { char msg[1024]; vsnprintf(msg, sizeof msg, f ? f : "", ap); @@ -2228,6 +2342,17 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { return B(b)->drafter_shared_kv(pos_offset); } +int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) { + if (!b) return RAD_E_INVAL; + return B(b)->lora_root(native, spellings); +} + +int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to, + int64_t from_lo, int64_t from_hi, int64_t to_lo) { + if (!b) return RAD_E_INVAL; + return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo); +} + int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { if (!b) return RAD_E_INVAL; return B(b)->declare_encoder(d); diff --git a/core/config.cpp b/core/config.cpp index 56c2f91a..47c147b4 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -23,6 +23,7 @@ #include #include #include +#include namespace rad { @@ -103,13 +104,20 @@ static const Flag g_flags[] = { " or host memory (default 3600). 0 keeps it until the memory\n" " is wanted" }, - { "--lora", "ADAPTER", "NAME=PATH: serve a PEFT LoRA adapter beside the base model,\n" - " as model NAME (repeatable). The base stays as it is; each\n" - " request picks its adapter by `model`"}, + { "--lora", "ADAPTER", "NAME=PATH: serve a LoRA adapter beside the base model\n" + " (repeatable). A text model takes a PEFT directory and\n" + " serves it as model NAME; an image or video generator takes\n" + " a .safetensors file (kohya, ComfyUI, PEFT, LyCORIS) that\n" + " a request names in `loras`. The base stays as it is"}, + { "--lora-dir", "DIR", "image and video generators: a request may name any\n" + " NAME.safetensors under DIR in `loras`, opened when first\n" + " asked for"}, { "--max-loras", "N", "adapter slots resident at once (default: the number of\n" - " --lora). Each slot holds one adapter's A/B on the card"}, - { "--max-lora-rank", "R", "the rank each slot is sized for (default 16); a smaller\n" - " adapter is zero-padded, a larger one refused"}, + " --lora, 2 with --lora-dir alone). A text model's slot holds\n" + " one adapter, a generator's one request's combination"}, + { "--max-lora-rank", "R", "the rank each slot is sized for (default 16 for a text\n" + " model, 64 for a generator); a text model's larger adapter is\n" + " refused, a generator's larger combination truncated"}, { "--lora-target-modules", "LIST", "comma-separated HF module leaf names adapters may\n" " target (q_proj,k_proj,...). Default: what the --lora\n" " adapters target. Needed with --max-loras and no --lora"}, @@ -520,6 +528,7 @@ int config_parse(int argc, char** argv, Config* c) { } c->lora.adapters.emplace_back(std::string(v, eq), std::string(eq + 1)); } + else if (S("--lora-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->lora.dir = v; } else if (S("--max-loras")) { if (!num(0, 64, &c->lora.max_loras)) return RAD_E_INVAL; } else if (S("--max-lora-rank")) { if (!num(1, 512, &c->lora.max_rank)) return RAD_E_INVAL; } else if (S("--lora-target-modules")) { @@ -881,21 +890,18 @@ int config_parse(int argc, char** argv, Config* c) { RAD_ERR("--lora names the adapter '%s' twice", name.c_str()); return RAD_E_INVAL; } - if (L.max_loras > 0 && L.max_loras < (int)L.adapters.size()) { - RAD_ERR("--max-loras %d holds fewer adapters than the %zu that --lora names", - L.max_loras, L.adapters.size()); - return RAD_E_INVAL; - } const bool rank_given = c->given.count("--max-lora-rank") != 0; if (!L.enabled() && (rank_given || !L.targets.empty())) { RAD_ERR("%s sizes runtime LoRA slots, and there are none: give --lora or --max-loras", rank_given ? "--max-lora-rank" : "--lora-target-modules"); return RAD_E_INVAL; } - if (L.adapters.empty() && L.max_loras > 0 && L.targets.empty()) { - RAD_ERR("--max-loras with no --lora names no module an adapter may target; give " - "--lora-target-modules (q_proj,k_proj,v_proj,o_proj,...)"); - return RAD_E_INVAL; + if (!L.dir.empty()) { + struct stat sb{}; + if (stat(L.dir.c_str(), &sb) != 0 || !S_ISDIR(sb.st_mode)) { + RAD_ERR("--lora-dir '%s' is not a directory", L.dir.c_str()); + return RAD_E_INVAL; + } } if (!c->kld_lora.empty() && !c->kld()) { RAD_ERR("--kld-lora scores through an adapter in KL mode; give --kld-record or " @@ -1019,9 +1025,12 @@ const ShowRow kShow[] = { std::string o; for (const auto& [n, p] : c.lora.adapters) o += (o.empty() ? "" : ", ") + n + "=" + p; return o.empty() ? std::string("none") : o; } }, + { "--lora-dir", [](const Config& c) { + return c.lora.dir.empty() ? std::string("none") : c.lora.dir; } }, { "--max-loras", [](const Config& c) { return c.lora.enabled() ? num(c.lora.slots()) : std::string("0 (off)"); } }, - { "--max-lora-rank", [](const Config& c) { return num(c.lora.max_rank); } }, + { "--max-lora-rank", [](const Config& c) { + return c.lora.max_rank > 0 ? num(c.lora.max_rank) : std::string("auto (16 text, 64 generator)"); } }, { "--lora-target-modules", [](const Config& c) { std::string o; for (const std::string& t : c.lora.targets) o += (o.empty() ? "" : ",") + t; diff --git a/core/engine.cpp b/core/engine.cpp index 1b15d259..3256f380 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2113,7 +2113,23 @@ int Engine::run_server() { o.graph_json = [this] { return dump_graph_json(ranks_[0]->program); }; /* Per request, from a reading at most a second old (Engine::diagnostics_json). */ o.diagnostics_json = [this] { return diagnostics_json(); }; - if (cfg_.lora.enabled()) { + if (cfg_.lora.enabled() && ranks_[0]->program.is_pass_driven()) { + /* A generator's request names its adapters in `loras`; `model` stays the model. */ + o.gen_lora_acquire = [this](const std::vector>& u, + int32_t* slot, std::shared_ptr* hold, std::string* note, + std::string* e) { + std::vector uses; + for (const auto& [n, w] : u) uses.push_back({ n, w }); + return gen_lora_acquire(uses, slot, hold, note, e); + }; + o.gen_lora_names = [this] { return gen_lora_names(); }; + o.lora_load = [this](const std::string& n, const std::string& d, std::string* e) { + return lora_load(n, d, e); + }; + o.lora_unload = [this](const std::string& n, std::string* e, int* in_flight) { + return lora_unload(n, e, in_flight); + }; + } else if (cfg_.lora.enabled()) { /* `model` picks the adapter, and the served model's own name picks the base. */ for (const auto& [name, dir] : cfg_.lora.adapters) if (name == o.model_id) { @@ -2347,7 +2363,14 @@ int Engine::run_server() { gen::Driver* drv = nullptr; const mm::Processor* proc = nullptr; server::ImageGenInfo inf; + Tokenizer aux; + bool has_aux = false; const server::ImageGenInfo& info() const override { return inf; } + int encode_aux(const std::string& text, std::vector* out) const override { + if (!has_aux) return RAD_E_UNSUPPORTED; + out->clear(); + return aux.encode(text, *out, /*add_special=*/true, /*parse_special=*/true); + } int submit(std::unique_ptr r, std::string* why) override { return drv->submit(std::move(r), why); } @@ -2393,6 +2416,27 @@ int Engine::run_server() { in.cfg_original = gd.cfg_original != 0; in.has_default_negative = pg.gen_str.has_default_negative; in.default_negative = pg.gen_str.default_negative; + in.min_tokens = gd.min_tokens; + in.pad_token = gd.pad_token; + in.aux_tokens = gd.aux_tokens != 0; + in.aux_max_tokens = gd.aux_max_tokens; + if (in.aux_tokens) { + if (!aux_vocab_) { + RAD_ERR("images: '%s' reads its prompt through a second tokenizer and %s carries " + "none; convert it with rad-convert --tokenizer2", in.name.c_str(), + cfg_.model.c_str()); + return RAD_E_FORMAT; + } + RAD_TRY(image_bridge.aux.init(aux_vocab_)); + image_bridge.has_aux = true; + } + in.samplers = gd.train_steps > 0 ? gd.samplers : 0; + in.default_sampler = gd.default_sampler; + in.default_scheduler = gd.default_scheduler; + in.chunk_tokens = gd.chunk_tokens; + in.chunk_bos = gd.chunk_bos; + in.chunk_eos = gd.chunk_eos; + in.chunk_pad = gd.pad_token; image_bridge.drv = img_gen_; image_bridge.proc = mm_proc.get(); d.images = &image_bridge; @@ -2407,6 +2451,9 @@ int Engine::run_server() { (long long)in.default_height, (long long)in.max_tokens, (long long)in.max_refs, in.fixed_schedule ? (std::to_string(in.fixed_steps) + " fixed steps").c_str() : (std::to_string(in.default_steps) + " steps by default").c_str()); + if (in.samplers) + RAD_INFO("images: sampler %s, scheduler %s by default", gen::sampler_name(in.default_sampler), + gen::scheduler_name(in.default_scheduler)); } /* An audio generator's endpoint: the driver's queue, the declared prompt and limits, and the diff --git a/core/engine.h b/core/engine.h index 7ffa8bab..4b07a680 100644 --- a/core/engine.h +++ b/core/engine.h @@ -31,6 +31,7 @@ #include "text/tokenizer.h" #include "format/radfile.h" #include "format/table_copy.h" +#include "lora/adapter.h" #include "lora/slots.h" #include @@ -155,6 +156,30 @@ public: int lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid, std::shared_ptr* hold); std::vector lora_names() const; + /* A generator's adapters: a request names one or more adapter files at their strengths, and + * gets the slot holding exactly that combination, composed into a free (or the least recently + * used idle) slot when none holds it yet. `note` says what the composition left out or + * approximated, for the reply. RAD_E_NOTFOUND names an adapter neither --lora nor --lora-dir + * provides; RAD_E_FULL means every slot is held by running requests. */ + struct LoraUse { std::string name; double weight = 1.0; }; + int gen_lora_acquire(const std::vector& uses, int32_t* slot, + std::shared_ptr* hold, std::string* note, std::string* err); + /* The adapter files a generator request may name: --lora's and those under --lora-dir. */ + std::vector gen_lora_names() const; + bool gen_lora_enabled() const { return lora_gen_; } +private: + /* A generator's adapter files by name (--lora, POST /v1/load_lora_adapter, --lora-dir), opened + * once and kept mapped; compositions read them when a combination is put in a slot. */ + int gen_lora_open(const std::string& name, std::shared_ptr* out, + std::string* err); + int gen_lora_start(); + /* Every rank's packed bytes into `slot` of its pools, each rank on a stream of its own. */ + int lora_copy(int slot, const std::vector>& packed, + std::string* err); + bool lora_gen_ = false; + std::unique_ptr lora_keys_; + mutable std::mutex lora_lib_mu_; + std::map>> lora_lib_; private: std::atomic lora_epoch_{0}; /* step-loop iterations, for slot reuse */ lora::SlotTable lora_table_; /* reads lora_epoch_, so declared after it */ @@ -216,6 +241,9 @@ private: * which references `vocab_` and must not outlive it. */ std::shared_ptr vocab_; std::unique_ptr vocab_view_; + /* The container's second vocabulary (rad-convert --tokenizer2), which an image generator that + * declares `aux_tokens` reads its prompt through; null without one. */ + std::shared_ptr aux_vocab_; /* The chunk geometry, resolved once and shared: the prefix cache needs the checkpoint interval * at configure time and the scheduler the whole geometry at init. Resolving it separately diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 55252355..7192f0a0 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -3663,6 +3663,14 @@ int Engine::load_vocab() { auto v = std::make_shared(); RAD_TRY(v->load(std::move(vb))); vocab_ = v; + if (file_ && file_->aux_vocab()) { + VocabBuild ab; + RAD_TRY(vocab_deserialize(file_->base(), (uint64_t)file_->size(), file_->aux_vocab().h, ab)); + auto av = std::make_shared(); + RAD_TRY(av->load(std::move(ab))); + aux_vocab_ = av; + RAD_INFO("vocab: a second vocabulary of %d tokens", aux_vocab_->n_tokens()); + } auto view = std::make_unique(); RAD_TRY(view->init(vocab_)); diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp index f1a6daf0..27b286da 100644 --- a/core/engine_gen.cpp +++ b/core/engine_gen.cpp @@ -43,6 +43,8 @@ int Engine::gen_loop() { return fail_loop(st); }; while (!stopping_.load(std::memory_order_acquire)) { + /* A round of the loop, idle or not: what lets a freed adapter slot cool (lora/slots.h). */ + lora_epoch_.fetch_add(1, std::memory_order_acq_rel); const RadBatch* b = gen_->next(step); if (!b) { step_batch_.store(nullptr, std::memory_order_release); @@ -52,6 +54,7 @@ int Engine::gen_loop() { } idle = 0; if (const int ps = prepare_release(b); ps < 0) return stop(ps); + for (auto& rk : ranks_) rk->ctx.set_gen_lora_slot(gen_->lora_slot()); issue_what_.store(kIssueModel, std::memory_order_release); step_batch_.store(b, std::memory_order_release); barrier_->arrive_and_wait(); /* release the ranks */ diff --git a/core/engine_lora.cpp b/core/engine_lora.cpp index 43b78c73..81ffec81 100644 --- a/core/engine_lora.cpp +++ b/core/engine_lora.cpp @@ -4,16 +4,25 @@ * A load packs the adapter for each rank (lora::load_adapter, host only), refuses a module no rank * placed, copies each rank's bytes into the slot on a stream of its own, waits, and only then * publishes the name. A request can name the adapter only after the publish, so no step reads a - * slot while it is written. */ + * slot while it is written. + * + * A generator keeps its adapter files in a library instead (--lora, --lora-dir, the load + * endpoint), and a slot holds one combination of them at given strengths, named by the + * combination: the first request that asks for it composes it (lora/adapter.h) into a free slot, + * or the least recently used one no request holds, and later ones find it there. */ #include "engine_priv.h" #include "lora/lora.h" #include +#include #include +#include #include +#include #include #include +#include #include namespace rad { @@ -50,13 +59,41 @@ int read_targets(const std::string& dir, std::set* out, std::string return RAD_OK; } +/* A generator's adapter name: a file stem under --lora-dir, possibly in a subdirectory, never + * leaving it. */ +bool valid_name(const std::string& n) { + if (n.empty() || n.size() > 200 || n[0] == '/' || n[0] == '.') return false; + if (n.find("..") != std::string::npos || n.find("//") != std::string::npos) return false; + for (char c : n) + if (!(std::isalnum((unsigned char)c) || c == '_' || c == '-' || c == '.' || c == '/' || + c == ' ' || c == '(' || c == ')' || c == '+' || c == ',')) + return false; + return true; +} + +bool is_file(const std::string& p) { + struct stat sb{}; + return stat(p.c_str(), &sb) == 0 && S_ISREG(sb.st_mode); +} + +/* The combination's slot name: the adapters sorted by name, each at its strength. */ +std::string combo_key(const std::vector& uses) { + std::string k; + for (const Engine::LoraUse& u : uses) k += fmt("%s%s*%.6g", k.empty() ? "" : "+", u.name.c_str(), u.weight); + return k; +} + } /* namespace */ int Engine::lora_targets() { if (!cfg_.lora.enabled()) return RAD_OK; lora_targets_ = std::set(cfg_.lora.targets.begin(), cfg_.lora.targets.end()); if (lora_targets_.empty()) { + /* A PEFT directory names its targets; an adapter file (a generator's) and a directory of + * them do not, and a generator's default is every plain GEMM under its declared roots. A + * text model refuses "*" at declare. */ for (const auto& [name, dir] : cfg_.lora.adapters) { + if (is_file(dir)) { lora_targets_.insert("*"); continue; } std::string err; const int s = read_targets(dir, &lora_targets_, &err); if (s < 0) { @@ -64,6 +101,7 @@ int Engine::lora_targets() { return s; } } + if (cfg_.lora.adapters.empty()) lora_targets_.insert("*"); } lora_table_.reset(cfg_.lora.slots(), &lora_epoch_); return RAD_OK; @@ -71,6 +109,12 @@ int Engine::lora_targets() { int Engine::lora_start() { if (!cfg_.lora.enabled()) return RAD_OK; + lora_gen_ = ranks_[0]->program.is_pass_driven(); + if (!lora_gen_ && cfg_.lora.slots() < (int)cfg_.lora.adapters.size()) { + RAD_ERR("lora: --max-loras %d holds fewer adapters than the %zu that --lora names", + cfg_.lora.slots(), cfg_.lora.adapters.size()); + return RAD_E_INVAL; + } size_t n_sites = 0; for (const auto& r : ranks_) n_sites += r->program.lora_sites.size(); if (n_sites == 0) { @@ -82,7 +126,7 @@ int Engine::lora_start() { } /* Every target is a module some rank carries adapters on. A leaf the model lacks, or holds * only outside the trunk (embedding, lm_head, a tower, the drafter), would target nothing. */ - { + if (!lora_targets_.count("*")) { std::set carried; for (const auto& r : ranks_) for (const lora::Site& site : r->lora_sites) @@ -117,9 +161,10 @@ int Engine::lora_start() { for (const std::string& x : lora_targets_) t += (t.empty() ? "" : ",") + x; RAD_INFO("lora: %zu GEMMs over %zu weights carry adapters on rank 0 (%s); %d slots of rank " "%d, %s a slot, %s on the card", P.lora_sites.size(), P.lora_pools.size(), t.c_str(), - cfg_.lora.slots(), cfg_.lora.max_rank, humanb(slot_bytes).c_str(), + cfg_.lora.slots(), cfg_.lora.rank(lora_gen_), humanb(slot_bytes).c_str(), humanb(slot_bytes * cfg_.lora.slots()).c_str()); } + if (lora_gen_) return gen_lora_start(); for (const auto& [name, dir] : cfg_.lora.adapters) { std::string err; const int s = lora_load(name, dir, &err); @@ -135,6 +180,37 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri std::lock_guard lk(lora_mu_); if (!cfg_.lora.enabled()) { *err = "the engine was started without adapters"; return RAD_E_STATE; } if (name.empty()) { *err = "an adapter needs a name"; return RAD_E_INVAL; } + if (lora_gen_) { + /* A generator's adapter goes into the library; a slot takes it when a request asks. */ + if (!valid_name(name)) { *err = "'" + name + "' is not an adapter name"; return RAD_E_INVAL; } + { + std::lock_guard lk2(lora_lib_mu_); + if (lora_lib_.count(name)) { *err = "an adapter named '" + name + "' is already loaded"; return RAD_E_INVAL; } + } + auto f = std::make_shared(); + RAD_TRY(f->open(dir, err)); + int placed = 0, rank = 0; + std::string first; + for (const lora::FileModule& m : f->modules()) { + std::string why; + if (!lora_keys_->resolve(m.key, &why).empty()) { ++placed; continue; } + if (first.empty()) first = m.key + ": " + why; + } + for (const lora::FileModule& m : f->modules()) + if (m.kind == lora::FileModule::LORA && m.t[0]) rank = std::max(rank, (int)m.t[0]->shape[0]); + if (placed == 0) { + *err = fmt("none of its %zu modules is a module of this model (%s)", f->modules().size(), + first.c_str()); + return RAD_E_NOTFOUND; + } + RAD_INFO("lora: '%s' -- %s, %d of %zu modules on this model%s%s%s", name.c_str(), + f->kind_name(), placed, f->modules().size(), + rank ? fmt(", rank %d", rank).c_str() : "", first.empty() ? "" : "; not placed: ", + first.c_str()); + std::lock_guard lk2(lora_lib_mu_); + lora_lib_[name] = { dir, f }; + return RAD_OK; + } /* A slot that is still cooling (lora/slots.h) is waited for here rather than answered with a * retry: the step loop goes round idle or busy, so the wait is milliseconds, and a hot swap * (unload, then load at once) would otherwise fail under traffic. Only other loads wait on @@ -155,7 +231,7 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri std::vector infos(ranks_.size()); std::vector> packed(ranks_.size()); for (size_t ri = 0; ri < ranks_.size(); ++ri) { - const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.max_rank, &infos[ri], + const int s = lora::load_adapter(dir, ranks_[ri]->lora_sites, cfg_.lora.rank(false), &infos[ri], &packed[ri], err); if (s < 0) { if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err; @@ -167,7 +243,19 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri if (s < 0) return s; } - /* ---- copy, per rank, on a stream of its own (the compute stream may be recording a pass) */ + RAD_TRY(lora_copy(slot, packed, err)); + + lora_table_.publish(slot, name, dir); + const lora::AdapterInfo& a = infos[0]; + RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(), + slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "", + a.base_model.empty() ? "(unnamed)" : a.base_model.c_str()); + return RAD_OK; +} + +int Engine::lora_copy(int slot, const std::vector>& packed, + std::string* err) { + /* Each rank on a stream of its own: the compute stream may be recording a pass. */ for (size_t ri = 0; ri < ranks_.size(); ++ri) { Rank& r = *ranks_[ri]; const Program& P = r.program; @@ -218,12 +306,6 @@ int Engine::lora_load(const std::string& name, const std::string& dir, std::stri return rc; } } - - lora_table_.publish(slot, name, dir); - const lora::AdapterInfo& a = infos[0]; - RAD_INFO("lora: '%s' in slot %d -- %zu modules, rank %lld, alpha %g%s, base %s", name.c_str(), - slot, a.modules.size(), (long long)a.max_module_rank, a.alpha, a.rslora ? " (rsLoRA)" : "", - a.base_model.empty() ? "(unnamed)" : a.base_model.c_str()); return RAD_OK; } @@ -233,11 +315,237 @@ int Engine::lora_acquire(const std::string& name, int32_t* slot, uint64_t* uid, } int Engine::lora_unload(const std::string& name, std::string* err, int* in_flight) { - return lora_table_.unload(name, in_flight, err); + if (!lora_gen_) return lora_table_.unload(name, in_flight, err); + /* A generator's adapter leaves the library, and every combination holding it its slot (at + * once when idle, after its requests otherwise). */ + { + std::lock_guard lk(lora_lib_mu_); + if (!lora_lib_.erase(name)) { + *err = "no adapter named '" + name + "' is loaded"; + return RAD_E_NOTFOUND; + } + } + *in_flight = 0; + for (const std::string& k : lora_table_.names()) { + bool uses = false; + size_t at = 0; + while (at <= k.size()) { + const size_t plus = std::min(k.find('+', at), k.size()); + const std::string part = k.substr(at, plus - at); + if (part.substr(0, part.rfind('*')) == name) uses = true; + at = plus + 1; + } + if (!uses) continue; + int n = 0; + std::string e; + lora_table_.unload(k, &n, &e); + *in_flight += n; + } + return RAD_OK; } std::vector Engine::lora_names() const { - return lora_table_.names(); + return lora_gen_ ? gen_lora_names() : lora_table_.names(); +} + +/* ================================================================== generator adapters */ +int Engine::gen_lora_start() { + /* Every slot's run of the slot-row table holds its own index (Program::lora_rows). */ + for (auto& rp : ranks_) { + Rank& r = *rp; + const Program& P = r.program; + if (!P.lora_rows || P.lora_rows_n <= 0) continue; + const int S = cfg_.lora.slots(); + std::vector v((size_t)(S * P.lora_rows_n)); + for (int s = 0; s < S; ++s) + std::fill(v.begin() + (int64_t)s * P.lora_rows_n, v.begin() + (int64_t)(s + 1) * P.lora_rows_n, s); + void* d = P.buffers[P.lora_rows].ptr; + if (!d || rad_dev_set(r.device) < 0) { + RAD_ERR("lora: rank %d: the slot-row table has no address", r.index); + return RAD_E_STATE; + } + RadStream st{}; + if (rad_stream_create(&st, 0) < 0) return RAD_E_DEVICE; + const int rc = rad_memcpy_async(d, v.data(), (int64_t)v.size() * 4, st); + const int sy = rad_stream_sync(st); + rad_stream_destroy(st); + if (rc < 0 || sy < 0) return RAD_E_DEVICE; + } + lora_keys_ = std::make_unique(ranks_[0]->program, ranks_[0]->lora_sites); + for (const auto& [name, path] : cfg_.lora.adapters) { + std::string err; + const int s = lora_load(name, path, &err); + if (s < 0) { + RAD_ERR("lora: adapter '%s' (%s): %s", name.c_str(), path.c_str(), err.c_str()); + return s; + } + } + if (!cfg_.lora.dir.empty()) + RAD_INFO("lora: requests may name the %zu adapter files under %s", gen_lora_names().size(), + cfg_.lora.dir.c_str()); + return RAD_OK; +} + +int Engine::gen_lora_open(const std::string& name, std::shared_ptr* out, + std::string* err) { + { + std::lock_guard lk(lora_lib_mu_); + auto it = lora_lib_.find(name); + if (it != lora_lib_.end()) { *out = it->second.second; return RAD_OK; } + } + const std::string path = cfg_.lora.dir + "/" + name + ".safetensors"; + if (cfg_.lora.dir.empty() || !valid_name(name) || !is_file(path)) { + *err = "no adapter named '" + name + "'" + + (cfg_.lora.dir.empty() ? std::string(" is loaded") + : " is loaded or under --lora-dir (GET /v1/loras lists them)"); + return RAD_E_NOTFOUND; + } + /* lora_load takes lora_mu_, which the caller holds: open here, as lora_load would. */ + auto f = std::make_shared(); + RAD_TRY(f->open(path, err)); + RAD_INFO("lora: '%s' opened from --lora-dir -- %s, %zu modules", name.c_str(), f->kind_name(), + f->modules().size()); + std::lock_guard lk(lora_lib_mu_); + lora_lib_[name] = { path, f }; + *out = f; + return RAD_OK; +} + +std::vector Engine::gen_lora_names() const { + std::set n; + { + std::lock_guard lk(lora_lib_mu_); + for (const auto& [k, v] : lora_lib_) n.insert(k); + } + if (!cfg_.lora.dir.empty()) { + /* Two levels: the directory and its subdirectories, as a UI's lora folder is laid out. */ + std::vector dirs{ "" }; + for (size_t i = 0; i < dirs.size(); ++i) { + const std::string rel = dirs[i]; + DIR* d = opendir((cfg_.lora.dir + "/" + rel).c_str()); + if (!d) continue; + while (dirent* e = readdir(d)) { + const std::string fn = e->d_name; + if (fn.empty() || fn[0] == '.') continue; + const std::string p = rel + fn; + struct stat sb{}; + if (stat((cfg_.lora.dir + "/" + p).c_str(), &sb) != 0) continue; + if (S_ISDIR(sb.st_mode)) { if (rel.empty()) dirs.push_back(p + "/"); continue; } + const size_t k = fn.size(); + if (k > 12 && fn.compare(k - 12, 12, ".safetensors") == 0) { + const std::string stem = p.substr(0, p.size() - 12); + if (valid_name(stem)) n.insert(stem); + } + } + closedir(d); + } + } + return std::vector(n.begin(), n.end()); +} + +int Engine::gen_lora_acquire(const std::vector& uses_in, int32_t* slot, + std::shared_ptr* hold, std::string* note, std::string* err) { + *slot = -1; + hold->reset(); + if (note) note->clear(); + if (!lora_gen_) { *err = "this model takes no adapters (start it with --lora or --lora-dir)"; return RAD_E_STATE; } + /* One entry per adapter, strengths of a repeated name summed; strength 0 is no adapter. */ + std::map by; + for (const LoraUse& u : uses_in) { + if (!std::isfinite(u.weight) || std::fabs(u.weight) > 16.0) { + *err = fmt("adapter '%s': strength %g is outside [-16, 16]", u.name.c_str(), u.weight); + return RAD_E_INVAL; + } + by[u.name] += u.weight; + } + std::vector uses; + for (const auto& [n, w] : by) if (w != 0.0) uses.push_back({ n, w }); + if (uses.empty()) return RAD_OK; + if (uses.size() > 16) { *err = fmt("%zu adapters in one request; at most 16", uses.size()); return RAD_E_INVAL; } + const std::string key = combo_key(uses); + uint64_t uid = 0; + if (lora_table_.acquire(key, slot, &uid, hold) == RAD_OK) return RAD_OK; + + std::lock_guard lk(lora_mu_); + if (lora_table_.acquire(key, slot, &uid, hold) == RAD_OK) return RAD_OK; + const auto t0 = std::chrono::steady_clock::now(); + std::vector ss; + for (const LoraUse& u : uses) { + lora::Strength s; + s.name = u.name; + s.weight = u.weight; + RAD_TRY(gen_lora_open(u.name, &s.file, err)); + ss.push_back(std::move(s)); + } + /* A slot: free, or freed from the least recently used combination no request holds. */ + const auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(2); + int sl = -1; + for (;;) { + bool cooling = false; + const int s = lora_table_.reserve(key, &sl, &cooling, err); + if (s >= 0) break; + if (s == RAD_E_FULL && !cooling) { + std::string ev; + if (lora_table_.evict_idle(&ev) == RAD_OK) continue; + *err = fmt("all %d adapter slots are held by running requests with other adapters " + "(--max-loras); retry when one finishes", cfg_.lora.slots()); + return RAD_E_FULL; + } + if (s != RAD_E_FULL || stopping_.load(std::memory_order_acquire) || + std::chrono::steady_clock::now() >= give_up) + return s; + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + const int rank = cfg_.lora.rank(true); + std::map comp; + lora::ComposeReport rep; + RAD_TRY(lora::compose(*lora_keys_, ss, rank, &comp, &rep, err)); + if (rep.modules == 0) { + *err = "none of the adapters' modules is a module of this model" + + (rep.unplaced.empty() ? std::string() : " (" + rep.unplaced[0] + ")"); + return RAD_E_NOTFOUND; + } + const std::map mods = lora::as_modules(comp, *lora_keys_); + std::vector> packed(ranks_.size()); + for (size_t ri = 0; ri < ranks_.size(); ++ri) { + lora::AdapterInfo info; + const int s = lora::pack_modules(ranks_[ri]->lora_sites, rank, mods, &info, &packed[ri], err, + /*compact=*/true); + if (s < 0) { + if (ranks_.size() > 1) *err = fmt("rank %zu: ", ri) + *err; + return s; + } + /* Pools past the last one a site names hold nothing (lora_declare's dropped GEMMs). */ + packed[ri].resize(ranks_[ri]->program.lora_pools.size()); + } + RAD_TRY(lora_copy(sl, packed, err)); + /* The ranks each pool takes in this slot, before a pass can name the slot (the publish). */ + for (size_t ri = 0; ri < ranks_.size(); ++ri) { + Program& P = ranks_[ri]->program; + const size_t S = (size_t)cfg_.lora.slots(); + for (size_t p = 0; p < P.lora_pools.size() && p < packed[ri].size(); ++p) + if (p * S + (size_t)sl < P.lora_rused.size()) + P.lora_rused[p * S + (size_t)sl] = packed[ri][p].empty ? 0 : (int32_t)packed[ri][p].r_used; + } + lora_table_.publish(sl, key, ""); + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + std::string n; + if (!rep.unplaced.empty()) + n += fmt("%zu adapter module%s not on this model (%s)", rep.unplaced.size(), + rep.unplaced.size() == 1 ? "" : "s", rep.unplaced[0].c_str()); + if (rep.exact < rep.modules) + n += fmt("%s%lld module%s past rank %d were truncated to it, keeping at worst %.1f%% of the " + "delta (%s)", n.empty() ? "" : "; ", (long long)(rep.modules - rep.exact), + rep.modules - rep.exact == 1 ? "" : "s", rank, 100.0 * rep.worst_kept, + rep.worst_module.c_str()); + RAD_INFO("lora: slot %d <- %s: %lld modules (%lld exact) in %.0f ms%s%s", sl, key.c_str(), + (long long)rep.modules, (long long)rep.exact, ms, n.empty() ? "" : "; ", n.c_str()); + if (note) *note = n; + if (lora_table_.acquire(key, slot, &uid, hold) != RAD_OK) { + *err = "the combination's slot was taken back before the request could hold it; retry"; + return RAD_E_STATE; + } + return RAD_OK; } } /* namespace rad */ diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 800c549d..f195e778 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -628,6 +628,191 @@ int Checkpoint::open_diffusers() { return RAD_OK; } +/* A single-file Stable Diffusion XL checkpoint in Stability's (sgm) layout, the form SDXL and its + * finetunes (Illustrious, NoobAI, Pony and the rest) are published in: one safetensors holding + * + * model.diffusion_model.* the UNet, under the names it is trained and adapted + * (LoRA) under, kept as they are; + * conditioner.embedders.0.transformer.* CLIP ViT-L's text model, already in transformers' + * CLIPTextModel names, kept; + * conditioner.embedders.1.model.* OpenCLIP ViT-bigG's text tower in open_clip's names, + * read as transformers' CLIPTextModelWithProjection + * under conditioner.embedders.1.transformer.: each + * block's fused in_proj split into q/k/v_proj (row + * views, nothing copied), c_fc / c_proj as fc1 / fc2, + * ln_1 / ln_2 / ln_final as layer_norm1 / layer_norm2 / + * final_layer_norm, and the (in, out) text_projection + * transposed into a linear's (out, in) + * `text_projection.weight`; + * first_stage_model.* the VAE, its decoder read in diffusers' AutoencoderKL + * names under vae. (its 1 x 1 attention convolutions + * keep their rank-4 shape). + * + * A `v_pred` tensor marks a v-prediction model and `ztsnr` one trained to a zero terminal SNR + * (ComfyUI's convention): they become the `sdxl.prediction` and `sdxl.zero_snr` keys. The + * architecture is `sdxl`. The checkpoint holds no tokenizer; rad-convert takes CLIP's with + * --tokenizer. */ +int Checkpoint::open_sgm() { + kind_ = SafeT; + RAD_TRY(add_shard(path_)); + bool vpred = false, zsnr = false; + std::vector add; + std::vector drop; + auto rename = [&](const SrcTensor& t, const std::string& name) { + SrcTensor v = t; + v.name = name; + add.push_back(std::move(v)); + drop.push_back(t.name); + }; + const std::string g_old = "conditioner.embedders.1.model."; + const std::string g_new = "conditioner.embedders.1.transformer."; + const std::string tm = g_new + "text_model."; + const std::string v_old = "first_stage_model."; + for (const SrcTensor& t : tensors_) { + const std::string& n = t.name; + if (n == "v_pred") { vpred = true; continue; } + if (n == "ztsnr") { zsnr = true; continue; } + if (n.rfind(g_old, 0) == 0) { + const std::string r = n.substr(g_old.size()); + if (r == "token_embedding.weight") { + rename(t, tm + "embeddings.token_embedding.weight"); + } else if (r == "positional_embedding") { + rename(t, tm + "embeddings.position_embedding.weight"); + } else if (r.rfind("ln_final.", 0) == 0) { + rename(t, tm + "final_layer_norm." + r.substr(std::strlen("ln_final."))); + } else if (r == "text_projection") { + /* x @ P in open_clip; a linear's weight is P^T. */ + if (t.shape.size() != 2 || !t.data || + (t.rad_dtype != RAD_F16 && t.rad_dtype != RAD_BF16 && t.rad_dtype != RAD_F32)) { + RAD_ERR("%s: '%s' is not a 2-D float matrix", path_.c_str(), n.c_str()); + return RAD_E_FORMAT; + } + const int64_t a = t.shape[0], b = t.shape[1]; + const int64_t es = rad_dtype_bytes(t.rad_dtype, 1); + owned_.push_back(std::make_unique((size_t)(a * b * es))); + uint8_t* dst = owned_.back().get(); + const uint8_t* src = (const uint8_t*)t.data; + for (int64_t i = 0; i < a; ++i) + for (int64_t j = 0; j < b; ++j) + std::memcpy(dst + (size_t)((j * a + i) * es), + src + (size_t)((i * b + j) * es), (size_t)es); + SrcTensor v = t; + v.name = g_new + "text_projection.weight"; + v.shape = { b, a }; + v.data = dst; + add.push_back(std::move(v)); + drop.push_back(n); + } else if (r.rfind("transformer.resblocks.", 0) == 0) { + /* transformer.resblocks.N. */ + const size_t p0 = std::strlen("transformer.resblocks."); + const size_t dot = r.find('.', p0); + if (dot == std::string::npos) continue; + const std::string layer = tm + "encoder.layers." + r.substr(p0, dot - p0) + "."; + const std::string rest = r.substr(dot + 1); + if (rest == "attn.in_proj_weight" || rest == "attn.in_proj_bias") { + const bool w = rest == "attn.in_proj_weight"; + if (t.shape.empty() || t.shape[0] % 3 || !t.data) { + RAD_ERR("%s: '%s' does not split into q, k and v", path_.c_str(), + n.c_str()); + return RAD_E_FORMAT; + } + const int64_t d = t.shape[0] / 3, rb = t.bytes / t.shape[0]; + const char* part[3] = { "q_proj", "k_proj", "v_proj" }; + for (int k = 0; k < 3; ++k) { + SrcTensor v = t; + v.name = layer + "self_attn." + part[k] + (w ? ".weight" : ".bias"); + v.shape[0] = d; + v.bytes = rb * d; + v.data = (const uint8_t*)t.data + (size_t)(k * d * rb); + add.push_back(std::move(v)); + } + drop.push_back(n); + } else { + static const std::pair kMap[] = { + { "attn.out_proj.", "self_attn.out_proj." }, { "ln_1.", "layer_norm1." }, + { "ln_2.", "layer_norm2." }, { "mlp.c_fc.", "mlp.fc1." }, + { "mlp.c_proj.", "mlp.fc2." } }; + for (const auto& [from, to] : kMap) + if (rest.rfind(from, 0) == 0) { + rename(t, layer + to + rest.substr(std::strlen(from))); + break; + } + } + } + continue; + } + if (n.rfind(v_old + "decoder.", 0) == 0 || n.rfind(v_old + "post_quant_conv.", 0) == 0) { + /* diffusers' convert_ldm_vae_checkpoint, the decoder's half. */ + std::string r = n.substr(v_old.size()); + auto sub = [&](const std::string& from, const std::string& to) { + const size_t at = r.find(from); + if (at != std::string::npos) r.replace(at, from.size(), to); + }; + sub("decoder.mid.block_1.", "decoder.mid_block.resnets.0."); + sub("decoder.mid.block_2.", "decoder.mid_block.resnets.1."); + sub("decoder.mid.attn_1.norm.", "decoder.mid_block.attentions.0.group_norm."); + sub("decoder.mid.attn_1.q.", "decoder.mid_block.attentions.0.to_q."); + sub("decoder.mid.attn_1.k.", "decoder.mid_block.attentions.0.to_k."); + sub("decoder.mid.attn_1.v.", "decoder.mid_block.attentions.0.to_v."); + sub("decoder.mid.attn_1.proj_out.", "decoder.mid_block.attentions.0.to_out.0."); + sub("decoder.norm_out.", "decoder.conv_norm_out."); + if (r.rfind("decoder.up.", 0) == 0) { + /* up.i runs at the i-th resolution from the bottom of the encoder's pyramid; + * up_blocks count in the order the decoder runs them. */ + const size_t p0 = std::strlen("decoder.up."), dot = r.find('.', p0); + if (dot == std::string::npos) continue; + const int i = std::atoi(r.substr(p0, dot - p0).c_str()); + std::string rest = r.substr(dot + 1); + if (rest.rfind("block.", 0) == 0) rest = "resnets." + rest.substr(6); + else if (rest.rfind("upsample.", 0) == 0) rest = "upsamplers.0." + rest.substr(9); + r = "decoder.up_blocks." + std::to_string(3 - i) + "." + rest; + } + sub(".nin_shortcut.", ".conv_shortcut."); + rename(t, "vae." + r); + } + } + for (const std::string& n : drop) index_.erase(n); + for (SrcTensor& v : add) { + if (index_.count(v.name)) { + RAD_ERR("%s: '%s' is read from two tensors", path_.c_str(), v.name.c_str()); + return RAD_E_FORMAT; + } + index_.emplace(v.name, tensors_.size()); + tensors_.push_back(std::move(v)); + } + meta_.arch = "sdxl"; + const size_t slash = path_.find_last_of('/'); + meta_.name = slash == std::string::npos ? path_ : path_.substr(slash + 1); + meta_.kv("sdxl.prediction", vpred ? "v" : "eps"); + meta_.kv("sdxl.zero_snr", zsnr ? "1" : "0"); + /* The typed dimensions are the conditioning network's, OpenCLIP bigG's text tower (as a + * diffusers pipeline's are its text encoder's), read off its tensors. */ + { + RadModelMeta& m = meta_.m; + const SrcTensor* tok = find(tm + "embeddings.token_embedding.weight"); + const SrcTensor* fc1 = find(tm + "encoder.layers.0.mlp.fc1.weight"); + int64_t layers = 0; + while (find(tm + "encoder.layers." + std::to_string(layers) + ".layer_norm1.weight")) + ++layers; + if (!tok || tok->shape.size() != 2 || !fc1 || fc1->shape.size() != 2 || !layers) { + RAD_ERR("%s: OpenCLIP bigG's text tower is incomplete", path_.c_str()); + return RAD_E_FORMAT; + } + m.n_layers = layers; + m.n_embd = tok->shape[1]; + m.head_dim = 64; + m.n_head = m.n_head_kv = m.n_embd / 64; + m.n_ff = fc1->shape[0]; + m.n_vocab = tok->shape[0]; + m.n_ctx_train = 77; + m.rms_eps = 1e-5f; + m.rope_theta = 10000.0f; + m.rope_scale = 1.0f; + } + meta_.finish(); + return RAD_OK; +} + int Checkpoint::open_safetensors(const std::string& path) { kind_ = SafeT; /* One shard, an index, or the directory holding either, as one namespace. */ @@ -644,15 +829,29 @@ int Checkpoint::open_safetensors(const std::string& path) { return open_diffusers(); if (is_file) { shards.push_back(path); + /* A single-file Stable Diffusion XL checkpoint, as Stability and every SDXL finetune + * ship one: read by its own importer. */ + SafeTensorsFile probe; + if (probe.open(path) == RAD_OK) { + bool unet = false, bigg = false; + for (const auto& t : probe.tensors()) { + unet = unet || t.name == "model.diffusion_model.label_emb.0.0.weight"; + bigg = bigg || + t.name.rfind("conditioner.embedders.1.model.transformer.resblocks.", 0) == 0; + } + if (unet && bigg) return open_sgm(); + } } else { RAD_TRY(shard_list(dir_, is_index ? path : dir_ + "/model.safetensors.index.json", is_index, &shards, &owner)); } for (const auto& sh : shards) RAD_TRY(add_shard(sh, "", owner.empty() ? nullptr : &owner)); - RAD_TRY(meta_from_config_json(dir_, &meta_)); - RAD_TRY(meta_merge_generation_config(dir_, &meta_)); - RAD_TRY(meta_merge_preprocessor_configs(dir_, &meta_)); + const std::string& md = meta_dir_.empty() ? dir_ : meta_dir_; + RAD_TRY(meta_from_config_json(md, &meta_)); + RAD_TRY(meta_merge_generation_config(md, &meta_)); + RAD_TRY(meta_merge_preprocessor_configs(md, &meta_)); + if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_; if (!is_file && !is_index) RAD_TRY(add_companions()); /* FP8's block, where the checkpoint states one. */ if (const char* bs = meta_.get("quantization_config.weight_block_size")) { @@ -1301,6 +1500,17 @@ int Checkpoint::add_draft(const std::string& dir, const std::string& prefix) { return RAD_OK; } +int Checkpoint::add_file(const std::string& path) { + if (kind_ != SafeT) { + RAD_ERR("%s is merged into a safetensors checkpoint's namespace; %s is not one", + path.c_str(), path_.c_str()); + return RAD_E_UNSUPPORTED; + } + RAD_TRY(add_shard(path)); + meta_.finish(); + return RAD_OK; +} + const SrcTensor* Checkpoint::find(const std::string& n) const { auto it = index_.find(n); return it == index_.end() ? nullptr : &tensors_[it->second]; @@ -1565,8 +1775,9 @@ static int resolve_wnorm(Checkpoint& ck, const RadNameMap& m, bool optional, Ckp } /* RAD_MAP_TRANSPOSE (src[0] [.., a, b] read as [.., b, a]), RAD_MAP_EMA (src[0] the embedding - * sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)) and - * RAD_MAP_TAP (one index of one dimension of src[0]), computed in f32 into `derived`. */ + * sums [bins, ...], src[1] the cluster usage [bins]; each row over max(usage, 1e-5)), RAD_MAP_TAP + * (one index of one dimension of src[0]) and RAD_MAP_COLS (one column range of src[0]), computed in + * f32 into `derived`. */ static int resolve_derived(Checkpoint& ck, const std::vector& maps, bool optional, CkptWeight* out, std::string* why) { auto refuse = [&](int rc, std::string msg) { @@ -1630,7 +1841,21 @@ static int resolve_derived(Checkpoint& ck, const std::vector& return refuse(RAD_E_FORMAT, "'" + a->name + "' cannot be read as f32"); out->rank = (uint32_t)rank; for (size_t i = 0; i < rank; ++i) out->shape[i] = a->shape[i]; - if (m.mode == RAD_MAP_TAP) { + if (m.mode == RAD_MAP_COLS) { + const int64_t cb = a->shape[rank - 1], c0 = m.src_index[0], nc = m.src_rows[0]; + if (c0 < 0 || nc <= 0 || c0 + nc > cb) + return refuse(RAD_E_SHAPE, "columns [" + std::to_string(c0) + ", " + + std::to_string(c0 + nc) + ") of '" + a->name + "', which " + "has " + std::to_string(cb)); + const int64_t outer = n / cb; + out->derived.resize((size_t)(outer * nc)); + for (int64_t o = 0; o < outer; ++o) + std::memcpy(&out->derived[(size_t)(o * nc)], &src[(size_t)(o * cb + c0)], + (size_t)nc * sizeof(float)); + out->shape[rank - 1] = nc; + out->why = "it is columns [" + std::to_string(c0) + ", " + std::to_string(c0 + nc) + + ") of '" + a->name + "', at convert -- a recipe rule stores it"; + } else if (m.mode == RAD_MAP_TAP) { const int d = m.concat_dim; if (d < 0 || (size_t)d >= rank || rank < 3) return refuse(RAD_E_SHAPE, "'" + a->name + "' has rank " + std::to_string(rank) + @@ -1709,7 +1934,7 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b if (maps.front()->mode == RAD_MAP_WNORM) return resolve_wnorm(ck, *maps.front(), optional, out, why); if (maps.front()->mode == RAD_MAP_TRANSPOSE || maps.front()->mode == RAD_MAP_EMA || - maps.front()->mode == RAD_MAP_TAP) + maps.front()->mode == RAD_MAP_TAP || maps.front()->mode == RAD_MAP_COLS) return resolve_derived(ck, maps, optional, out, why); struct Src1 { const char* name; int index; int64_t rows; }; std::vector srcs; diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 72e20805..3846d1cb 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -120,6 +120,14 @@ public: * borrows the target's embedding and head, so it goes into the target's container with its * tensors and config.json keys under `draft.`. */ int add_draft(const std::string& dir, const std::string& prefix); + /* Merge one more safetensors file, its tensor names kept: a release that ships its networks + * as separate single files (ComfyUI's split_files: a diffusion model, a text encoder and a + * VAE). A name already present is refused. */ + int add_file(const std::string& path); + /* Before open(): read config.json, generation_config.json and the tokenizer from `dir` rather + * than from beside the checkpoint, for a single-file checkpoint that ships none of them (the + * text encoder's repository describes such a release). */ + void set_meta_dir(const std::string& dir) { meta_dir_ = dir; } const SrcTensor* find(const std::string& n) const; const std::vector& tensors() const { return tensors_; } @@ -177,12 +185,13 @@ private: const std::unordered_map* owner = nullptr); int open_safetensors(const std::string& path); int open_diffusers(); + int open_sgm(); int add_companions(); int open_gguf(const std::string& path); void detect_import(); enum Kind { None, Gguf, SafeT } kind_ = None; - std::string path_, dir_, tok_dir_; + std::string path_, dir_, tok_dir_, meta_dir_; GgufFile gguf_; MetaOwn meta_; std::vector> shards_; @@ -249,7 +258,7 @@ struct CkptWeight { * (the values change), so a recipe rule stores it. */ bool wnorm = false; std::vector wnorm_scale; - /* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, RAD_MAP_EMA): its f32 + /* A weight computed from its sources at resolve (RAD_MAP_TRANSPOSE, EMA, TAP, COLS): its f32 * values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule * stores it. */ std::vector derived; diff --git a/core/format/radfile.cpp b/core/format/radfile.cpp index f36329bd..c8167e96 100644 --- a/core/format/radfile.cpp +++ b/core/format/radfile.cpp @@ -40,6 +40,7 @@ void RadFile::close() { hdr_ = nullptr; meta_ = nullptr; dir_ = nullptr; planes_ = nullptr; encs_ = nullptr; prof_ = nullptr; vocab_ = VocabSection{}; + aux_vocab_ = VocabSection{}; groups_.clear(); by_name_.clear(); path_.clear(); @@ -197,6 +198,9 @@ int RadFile::validate() { if (!need(span_n(hdr_->prof_off, hdr_->prof_count, sizeof(RadFileProfile)), "the expert profile")) return RAD_E_FORMAT; if (!need(span_ok(hdr_->vocab_off, hdr_->vocab_bytes), "the vocab section")) return RAD_E_FORMAT; + if (!need(span_ok(hdr_->reserved[RAD_HDR_AUX_VOCAB_OFF], + hdr_->reserved[RAD_HDR_AUX_VOCAB_BYTES]), "the second vocab section")) + return RAD_E_FORMAT; if (!need(span_ok(hdr_->data_off, hdr_->data_bytes), "the data blob")) return RAD_E_FORMAT; if (hdr_->data_bytes && (hdr_->data_off % RAD_ALIGN_POOL) != 0) { @@ -312,22 +316,29 @@ int RadFile::validate() { } /* ---------------------------------------------------------------- vocab */ - if (hdr_->vocab_bytes >= sizeof(RadVocabHeader)) { - /* The section is read in place through typed pointers, so the header and every array must - * be aligned to their element (the writer guarantees it). */ - if (hdr_->vocab_off % alignof(RadVocabHeader) != 0) { - RAD_ERR("%s: the vocab section starts at %llu, which is not %zu-aligned", path_.c_str(), - (unsigned long long)hdr_->vocab_off, alignof(RadVocabHeader)); + /* The vocab section, and the second one a generator may read its prompt through: the same + * layout, each checked against its own extent. */ + auto read_vocab = [&](uint64_t voff, uint64_t vbytes, const char* what, + VocabSection* out) -> int { + if (vbytes == 0) return RAD_OK; + if (vbytes < sizeof(RadVocabHeader)) { + RAD_ERR("%s: the %s section is %llu bytes, shorter than its own header (%zu)", + path_.c_str(), what, (unsigned long long)vbytes, sizeof(RadVocabHeader)); return RAD_E_FORMAT; } - const RadVocabHeader* v = (const RadVocabHeader*)(base_ + hdr_->vocab_off); + /* The section is read in place through typed pointers, so the header and every array must + * be aligned to their element (the writer guarantees it). */ + if (voff % alignof(RadVocabHeader) != 0) { + RAD_ERR("%s: the %s section starts at %llu, which is not %zu-aligned", path_.c_str(), + what, (unsigned long long)voff, alignof(RadVocabHeader)); + return RAD_E_FORMAT; + } + const RadVocabHeader* v = (const RadVocabHeader*)(base_ + voff); /* Offset 0 means an optional array is absent (scores are unigram-only; types default to * normal). Nothing real lives at file offset 0. */ auto arr_ok = [&](uint64_t off, uint64_t bytes, size_t align) { return bytes == 0 || off == 0 || - (off >= hdr_->vocab_off && - off - hdr_->vocab_off <= hdr_->vocab_bytes && - bytes <= hdr_->vocab_bytes - (off - hdr_->vocab_off) && + (off >= voff && off - voff <= vbytes && bytes <= vbytes - (off - voff) && off % align == 0); }; const uint64_t nt = v->n_tokens, nm = v->n_merges, ns = v->n_steps; @@ -336,47 +347,50 @@ int RadFile::validate() { !arr_ok(v->tok_type_off, nt, 1) || !arr_ok(v->merge_off, nm * 2 * sizeof(uint32_t), alignof(uint32_t)) || !arr_ok(v->step_off, ns * sizeof(RadVocabStep), alignof(RadVocabStep))) { - RAD_ERR("%s: the vocab section's arrays do not fit inside it, or one is not aligned " - "to its element", path_.c_str()); + RAD_ERR("%s: the %s section's arrays do not fit inside it, or one is not aligned to its " + "element", + path_.c_str(), what); return RAD_E_FORMAT; } - vocab_.h = v; - vocab_.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr; - vocab_.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr; - vocab_.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr; - vocab_.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr; - vocab_.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr; + VocabSection& vs = *out; + vs.h = v; + vs.tok_text = (nt && v->tok_text_off) ? (const rad_stroff*)(base_ + v->tok_text_off) : nullptr; + vs.tok_score = (nt && v->tok_score_off) ? (const float*)(base_ + v->tok_score_off) : nullptr; + vs.tok_type = (nt && v->tok_type_off) ? (const uint8_t*)(base_ + v->tok_type_off) : nullptr; + vs.merges = (nm && v->merge_off) ? (const uint32_t*)(base_ + v->merge_off) : nullptr; + vs.steps = (ns && v->step_off) ? (const RadVocabStep*)(base_ + v->step_off) : nullptr; - if (vocab_.tok_text) + if (vs.tok_text) for (uint64_t i = 0; i < nt; ++i) - if (!str_ok(vocab_.tok_text[i])) { - RAD_ERR("%s: vocab token %llu points outside the string blob", path_.c_str(), - (unsigned long long)i); + if (!str_ok(vs.tok_text[i])) { + RAD_ERR("%s: %s token %llu points outside the string blob", path_.c_str(), + what, (unsigned long long)i); return RAD_E_FORMAT; } - if (vocab_.steps) + if (vs.steps) for (uint64_t i = 0; i < ns; ++i) - if (!str_ok(vocab_.steps[i].arg0) || !str_ok(vocab_.steps[i].arg1)) { - RAD_ERR("%s: vocab step %llu points outside the string blob", path_.c_str(), + if (!str_ok(vs.steps[i].arg0) || !str_ok(vs.steps[i].arg1)) { + RAD_ERR("%s: %s step %llu points outside the string blob", path_.c_str(), what, (unsigned long long)i); return RAD_E_FORMAT; } - if (vocab_.merges) + if (vs.merges) for (uint64_t i = 0; i < nm * 2; ++i) - if (vocab_.merges[i] >= nt) { - RAD_ERR("%s: merge %llu names token %u of %llu", path_.c_str(), - (unsigned long long)(i / 2), vocab_.merges[i], (unsigned long long)nt); + if (vs.merges[i] >= nt) { + RAD_ERR("%s: %s merge %llu names token %u of %llu", path_.c_str(), what, + (unsigned long long)(i / 2), vs.merges[i], (unsigned long long)nt); return RAD_E_FORMAT; } if (!str_ok(v->chat_template)) { - RAD_ERR("%s: the chat template offset is outside the string blob", path_.c_str()); + RAD_ERR("%s: the %s section's chat template offset is outside the string blob", + path_.c_str(), what); return RAD_E_FORMAT; } - } else if (hdr_->vocab_bytes != 0) { - RAD_ERR("%s: the vocab section is %llu bytes, shorter than its own header (%zu)", - path_.c_str(), (unsigned long long)hdr_->vocab_bytes, sizeof(RadVocabHeader)); - return RAD_E_FORMAT; - } + return RAD_OK; + }; + RAD_TRY(read_vocab(hdr_->vocab_off, hdr_->vocab_bytes, "vocab", &vocab_)); + RAD_TRY(read_vocab(hdr_->reserved[RAD_HDR_AUX_VOCAB_OFF], + hdr_->reserved[RAD_HDR_AUX_VOCAB_BYTES], "second vocab", &aux_vocab_)); return RAD_OK; } @@ -956,6 +970,29 @@ int RadWriter::check_complete() const { return RAD_OK; } +/* A serialised vocab section's arrays rebased from section-relative to file offsets. */ +static void rebase_vocab(std::vector& blob, uint64_t at) { + auto* vh = (RadVocabHeader*)blob.data(); + if (vh->tok_text_off) vh->tok_text_off += at; + if (vh->tok_score_off) vh->tok_score_off += at; + if (vh->tok_type_off) vh->tok_type_off += at; + if (vh->merge_off) vh->merge_off += at; + if (vh->step_off) vh->step_off += at; +} + +int RadWriter::set_aux_vocab_section(const void* blob, int64_t bytes) { + std::vector keep; + keep.swap(vocab_blob_); + const bool had = have_vocab_; + const int s = set_vocab_section(blob, bytes); + keep.swap(vocab_blob_); + have_vocab_ = had; + if (s < 0) return s; + aux_vocab_blob_.assign((const uint8_t*)blob, (const uint8_t*)blob + bytes); + have_aux_vocab_ = true; + return RAD_OK; +} + int RadWriter::set_vocab_section(const void* blob, int64_t bytes) { if (!began_ || sealed_) return RAD_E_STATE; if (!blob || bytes < (int64_t)sizeof(RadVocabHeader)) { @@ -1049,6 +1086,10 @@ void RadWriter::layout(RadFileHeader* hp) { h.enc_count = encs_.size(); h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size()); h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0; + if (have_aux_vocab_) { + h.reserved[RAD_HDR_AUX_VOCAB_OFF] = (uint64_t)place8((int64_t)aux_vocab_blob_.size()); + h.reserved[RAD_HDR_AUX_VOCAB_BYTES] = aux_vocab_blob_.size(); + } h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile))); h.prof_count = prof_.size(); @@ -1095,14 +1136,8 @@ int RadWriter::finish() { * aligned within the blob, so alignment is preserved. */ for (auto& e : dir_) e.offset += h.data_off; for (auto& p : planes_) p.offset += h.data_off; - if (have_vocab_) { - auto* vh = (RadVocabHeader*)vocab_blob_.data(); - if (vh->tok_text_off) vh->tok_text_off += h.vocab_off; - if (vh->tok_score_off) vh->tok_score_off += h.vocab_off; - if (vh->tok_type_off) vh->tok_type_off += h.vocab_off; - if (vh->merge_off) vh->merge_off += h.vocab_off; - if (vh->step_off) vh->step_off += h.vocab_off; - } + if (have_vocab_) rebase_vocab(vocab_blob_, h.vocab_off); + if (have_aux_vocab_) rebase_vocab(aux_vocab_blob_, h.reserved[RAD_HDR_AUX_VOCAB_OFF]); int st = RAD_OK; int64_t at = 0; @@ -1120,6 +1155,9 @@ int RadWriter::finish() { emit(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), (int64_t)h.plane_off); emit(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), (int64_t)h.enc_off); if (have_vocab_) emit(vocab_blob_.data(), (int64_t)vocab_blob_.size(), (int64_t)h.vocab_off); + if (have_aux_vocab_) + emit(aux_vocab_blob_.data(), (int64_t)aux_vocab_blob_.size(), + (int64_t)h.reserved[RAD_HDR_AUX_VOCAB_OFF]); emit(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), (int64_t)h.prof_off); if (st < 0) { RAD_ERR("%s: %s", path_.c_str(), std::strerror(errno)); abort(); return st; } @@ -1249,6 +1287,10 @@ int RadWriter::finish_append() { h.enc_count = encs_.size(); h.vocab_off = (uint64_t)place8((int64_t)vocab_blob_.size()); h.vocab_bytes= have_vocab_ ? vocab_blob_.size() : 0; + if (have_aux_vocab_) { + h.reserved[RAD_HDR_AUX_VOCAB_OFF] = (uint64_t)place8((int64_t)aux_vocab_blob_.size()); + h.reserved[RAD_HDR_AUX_VOCAB_BYTES] = aux_vocab_blob_.size(); + } h.prof_off = (uint64_t)place8((int64_t)(prof_.size() * sizeof(RadFileProfile))); h.prof_count = prof_.size(); @@ -1264,14 +1306,8 @@ int RadWriter::finish_append() { if (!dir_abs_[i]) for (uint32_t k = 0; k < dir_[i].n_planes; ++k) planes_[dir_[i].plane_first + k].offset += (uint64_t)append_base_; - if (have_vocab_) { - auto* vh = (RadVocabHeader*)vocab_blob_.data(); - if (vh->tok_text_off) vh->tok_text_off += h.vocab_off; - if (vh->tok_score_off) vh->tok_score_off += h.vocab_off; - if (vh->tok_type_off) vh->tok_type_off += h.vocab_off; - if (vh->merge_off) vh->merge_off += h.vocab_off; - if (vh->step_off) vh->step_off += h.vocab_off; - } + if (have_vocab_) rebase_vocab(vocab_blob_, h.vocab_off); + if (have_aux_vocab_) rebase_vocab(aux_vocab_blob_, h.reserved[RAD_HDR_AUX_VOCAB_OFF]); int st = RAD_OK; auto put = [&](const void* p, int64_t bytes, uint64_t at) { @@ -1283,6 +1319,9 @@ int RadWriter::finish_append() { put(planes_.data(), (int64_t)(planes_.size() * sizeof(RadFilePlane)), h.plane_off); put(encs_.data(), (int64_t)(encs_.size() * sizeof(RadEncoding)), h.enc_off); if (have_vocab_) put(vocab_blob_.data(), (int64_t)vocab_blob_.size(), h.vocab_off); + if (have_aux_vocab_) + put(aux_vocab_blob_.data(), (int64_t)aux_vocab_blob_.size(), + h.reserved[RAD_HDR_AUX_VOCAB_OFF]); put(prof_.data(), (int64_t)(prof_.size() * sizeof(RadFileProfile)), h.prof_off); if (st >= 0 && ::ftruncate(fd_out_, (off_t)off) != 0) st = RAD_E_IO; /* Make everything durable before the new header names it. */ diff --git a/core/format/radfile.h b/core/format/radfile.h index adec085e..b381f8ed 100644 --- a/core/format/radfile.h +++ b/core/format/radfile.h @@ -141,6 +141,8 @@ public: /* ------------------------------------------------------------ vocab and profile */ VocabSection vocab() const { return vocab_; } + /* The second vocab section, or an empty one (RAD_HDR_AUX_VOCAB_OFF in rad_format.h). */ + VocabSection aux_vocab() const { return aux_vocab_; } int64_t profile_count() const { return (int64_t)hdr_->prof_count; } const RadFileProfile* profile() const { return prof_; } @@ -161,7 +163,7 @@ private: const RadFileProfile* prof_ = nullptr; uint64_t str_bytes_ = 1; - VocabSection vocab_; + VocabSection vocab_, aux_vocab_; std::vector groups_; std::unordered_map by_name_; }; @@ -244,6 +246,8 @@ public: /* The serialised vocab section. Its internal offsets must be section-relative (serialise with * section_file_off 0); finish() rebases them, as it does the directory. */ int set_vocab_section(const void* blob, int64_t bytes); + /* The second vocab section (RAD_HDR_AUX_VOCAB_OFF), serialised the same way. */ + int set_aux_vocab_section(const void* blob, int64_t bytes); void add_profile(int32_t layer, int32_t expert, float share); @@ -301,6 +305,8 @@ private: /* The vocab section, assembled in memory and appended verbatim. */ std::vector vocab_blob_; bool have_vocab_ = false; + std::vector aux_vocab_blob_; + bool have_aux_vocab_ = false; int64_t blob_bytes_ = 0; /* the blob's reserved length */ diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index c4d09ab0..001883cf 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -23,7 +23,7 @@ int64_t ref_tokens_max(const RadGeneratorDecl& d) { } struct Sizes { - int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0; + int64_t T = 0, S = 0, EP = 0, PD = 0, R = 0, P = 0, PX = 0, NT = 0, NB = 0, AX = 0; bool joint = false; }; @@ -43,6 +43,7 @@ Sizes sizes_of(const Program& prog, int64_t block_size) { z.PX = z.R * (ref_tokens_max(d) * s2) + d.max_tokens * s2; z.NT = d.max_tokens; z.NB = block_size > 0 ? (z.P + block_size - 1) / block_size : 0; + z.AX = d.aux_tokens ? d.aux_max_tokens : 0; return z; } @@ -85,6 +86,12 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) { { 0, J * z.T * I }, /* R_MSRC */ { 0, J * 3 * (z.S + 1) * I }, /* R_MCCU */ { 0, J * 4 * z.T * 4 }, /* R_MROPE */ + { 0, (z.AX ? z.AX + 2 : 0) * I }, /* R_AUX: a COND's {0, n} and second-tokenizer ids */ + { 0, z.S * 4 }, /* R_SIGP */ + { 0, z.S * 4 }, /* R_TSTEP */ + { 0, z.S * I }, /* R_SAMP */ + { 0, z.S * I }, /* R_STEPI */ + { 0, 2 * z.S * 4 }, /* R_SIZE */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { @@ -113,6 +120,14 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector& fixed_ = prog.gen_str.sigmas; kv_ = kv; ranks_ = ranks; + table_ = DiscreteTable{}; + if (discrete()) { + std::string why; + if (discrete_table(decl_, &table_, &why) < 0) { + RAD_ERR("image generator: %s", why.c_str()); + return RAD_E_INVAL; + } + } /* Exactly one paged full-attention KV group, holding the conditioning; none in the joint * layout, where the conditioning rides in the steps. Group handles start at 1 (group 0 is the * null handle); the KV manager and a batch both index by handle. */ @@ -216,6 +231,10 @@ int Driver::submit(std::unique_ptr r, std::string* why) { return no("at most " + std::to_string(d.max_refs) + " pictures a request"); for (const Branch* b : { &r->pos, &r->neg }) { if (b == &r->neg && !r->has_neg) continue; + if (d.aux_tokens && (b->aux.empty() || (int64_t)b->aux.size() > d.aux_max_tokens)) + return no("the prompt is " + std::to_string(b->aux.size()) + " tokens to the " + "model's second tokenizer, which reads 1.." + + std::to_string(d.aux_max_tokens)); if ((int64_t)b->tokens.size() > max_tok_) return no("the prompt is " + std::to_string(b->tokens.size()) + " tokens with its " "pictures; a conditioning pass carries " + std::to_string(max_tok_)); @@ -235,6 +254,10 @@ int Driver::submit(std::unique_ptr r, std::string* why) { r->inp_src.h != r->height)) return no("the mask's picture is not at the size being made"); if (r->previews < 0 || r->previews > 3) return no("partial_images must be 0..3"); + if (discrete() && (r->sampler < 0 || r->sampler >= RAD_GEN_SAMPLER_COUNT || + !(decl_.samplers & (1u << r->sampler)) || r->scheduler < 0 || + r->scheduler >= RAD_GEN_SCHED_COUNT)) + return no("the sampler or scheduler is not one this model serves"); r->ticket->t_submit_ns = (int64_t)rad_mono_ns(); std::lock_guard lk(mu_); if (closed_) { @@ -373,7 +396,13 @@ int Driver::admit_locked() { release_kv_locked(j); break; } - j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens); + if (discrete()) { + j.sigmas = schedule_discrete(decl_, table_, r.scheduler, r.steps); + j.tsteps.clear(); + for (float sg : j.sigmas) j.tsteps.push_back(sg > 0 ? (float)table_.timestep(sg) : 0.0f); + } else { + j.sigmas = schedule(decl_, fixed_, r.steps, j.tokens); + } const int32_t n_steps = (int32_t)j.sigmas.size() - 1; for (int b = 0; b < j.n_branch; ++b) { Cond& c = j.cond[b]; @@ -491,6 +520,16 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste G.mode_ccu = nullptr; G.n_mode_h = nullptr; G.mode_rope_f = nullptr; + G.n_aux = 0; + G.aux_ids = nullptr; + G.aux_cu = nullptr; + G.sigma_prev = nullptr; + G.timestep = nullptr; + G.sampler = nullptr; + G.step = nullptr; + G.size_px = nullptr; + G.entry_h = nullptr; + G.tokens_h = nullptr; } } @@ -529,15 +568,18 @@ const RadBatch* Driver::next(int step) { for (int b = 0; b < j.n_branch; ++b) if (!j.cond[b].encoded) return build_cond(j, b, step); } - /* 3. A denoise step over what is in flight, oldest request first. */ + /* 3. A denoise step over what is in flight, oldest request first, with the oldest one's + * adapters: a pass runs one runtime LoRA slot in every row. */ std::vector take; int64_t rows = 0, entries = 0; + int32_t lora = -2; for (auto& jp : jobs_) { Job& j = *jp; if (!j.admitted || j.failed) continue; bool ready = true; for (int b = 0; b < j.n_branch; ++b) ready = ready && j.cond[b].encoded; if (!ready) continue; + if (lora != -2 && j.req->lora_slot != lora) continue; const int32_t n_steps = (int32_t)j.sigmas.size() - 1; for (int32_t l : j.lanes) { const Lane& ln = lanes_[(size_t)l]; @@ -548,10 +590,13 @@ const RadBatch* Driver::next(int step) { rows += need; entries += j.n_branch; take.push_back(l); + lora = j.req->lora_slot; } } if (take.empty()) return nullptr; - return build_denoise(take, step); + const RadBatch* b = build_denoise(take, step); + pass_.lora_slot = lora; + return b; } const RadBatch* Driver::batch_for(int rank) const { @@ -704,6 +749,15 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { /* The conditioning is modulated at t = 0. */ hptr(R_SIG)[0] = 0.0f; reg_[R_SIG].used = 4; + /* The prompt through the second tokenizer, for a model that reads it. */ + const int64_t n_aux = decl_.aux_tokens ? (int64_t)br.aux.size() : 0; + if (n_aux) { + int32_t* ax = hptr(R_AUX); + ax[0] = 0; + ax[1] = (int32_t)n_aux; + std::memcpy(ax + 2, br.aux.data(), (size_t)n_aux * 4); + reg_[R_AUX].used = (n_aux + 2) * 4; + } /* Host-side arrays the plugin reads (segment kinds, pixel blocks, lanes), owned by the driver * for the life of the pass. */ host_bidi_ = c.lay.bidi; @@ -758,6 +812,10 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { G.n_lane = (int64_t)host_lanes_.size(); G.lane_h = host_lanes_.data(); G.lane = G.n_lane ? dptr(ri, R_LANE) : nullptr; + G.n_aux = n_aux; + G.aux_cu = n_aux ? dptr(ri, R_AUX) : nullptr; + G.aux_ids = n_aux ? dptr(ri, R_AUX) + 2 : nullptr; + G.tokens_h = hptr(R_TOK); if (joint()) { B.n_kv_groups = 0; B.kv = nullptr; @@ -771,6 +829,7 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { } pass_.kind = RAD_GEN_PASS_COND; pass_.job = j.id; + pass_.lora_slot = j.req->lora_slot; pass_.branch = branch; return &out_[0]; } @@ -821,6 +880,12 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step uint32_t* seed = hptr(R_SEED); int32_t* btab = hptr(R_BT); int32_t* used = hptr(R_USED); + float* sigp = hptr(R_SIGP); + float* tstep = hptr(R_TSTEP); + int32_t* samp = hptr(R_SAMP); + int32_t* stepi = hptr(R_STEPI); + float* size = hptr(R_SIZE); + host_entry_.assign((size_t)(4 * S), 0); int64_t row = 0; cu[0] = 0; pass_.lanes.clear(); @@ -866,6 +931,16 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step cu[i + 1] = (int32_t)row; sig[i] = j.sigmas[(size_t)ln.step]; sign[i] = j.sigmas[(size_t)ln.step + 1]; + sigp[i] = ln.step > 0 ? j.sigmas[(size_t)ln.step - 1] : 0.0f; + tstep[i] = discrete() ? j.tsteps[(size_t)ln.step] : 0.0f; + samp[i] = j.req->sampler; + stepi[i] = ln.step; + size[2 * i] = (float)j.req->height; + size[2 * i + 1] = (float)j.req->width; + host_entry_[(size_t)(4 * i)] = joint() ? (int32_t)c.lay.rows : 0; + host_entry_[(size_t)(4 * i + 1)] = j.req->height; + host_entry_[(size_t)(4 * i + 2)] = j.req->width; + host_entry_[(size_t)(4 * i + 3)] = e.branch; const bool neg = e.branch == 1; cfg[i] = neg ? 0.0f : (j.n_branch > 1 ? j.req->cfg : 1.0f); pair[i] = neg ? -2 : (j.n_branch > 1 ? (int32_t)(i + 1) : -1); @@ -930,6 +1005,8 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step reg_[R_GROPE].used = 3 * n_tok * 4; } reg_[R_SIG].used = reg_[R_SIGN].used = reg_[R_CFG].used = S * 4; + reg_[R_SIGP].used = reg_[R_TSTEP].used = reg_[R_SAMP].used = reg_[R_STEPI].used = S * 4; + reg_[R_SIZE].used = 2 * S * 4; reg_[R_PAIR].used = reg_[R_LANE].used = reg_[R_FLAGS].used = S * 4; reg_[R_SEED].used = 2 * S * 4; reg_[R_BT].used = joint() ? 0 : S * pitch * 4; @@ -954,6 +1031,12 @@ const RadBatch* Driver::build_denoise(const std::vector& take, int step G.lane_h = nullptr; G.rope = joint() ? nullptr : dptr(ri, R_GROPE); G.lane_dh = hptr(R_LANE); + G.sigma_prev = dptr(ri, R_SIGP); + G.timestep = dptr(ri, R_TSTEP); + G.sampler = dptr(ri, R_SAMP); + G.step = dptr(ri, R_STEPI); + G.size_px = dptr(ri, R_SIZE); + G.entry_h = host_entry_.data(); if (joint()) { G.src = dptr(ri, R_SRC); G.n_img = n_img; diff --git a/core/gen/driver.h b/core/gen/driver.h index 6bd715d6..701fed38 100644 --- a/core/gen/driver.h +++ b/core/gen/driver.h @@ -60,6 +60,7 @@ public: /* ---------------------------------------------------------- the engine thread */ const RadBatch* next(int step) override; const RadBatch* batch_for(int rank) const override; + int32_t lora_slot() const override { return pass_.lora_slot; } /* A decode pass's pixels: `image_out` into the pinned image buffer. */ const std::vector& readbacks() const override { return rb_; } int done() override; @@ -85,6 +86,8 @@ private: int32_t h_lat = 0, w_lat = 0; int64_t tokens = 0; std::vector sigmas; + /* A discrete-time model's: each step's timestep, beside `sigmas`. */ + std::vector tsteps; std::vector lanes; std::vector> ref_hw; int32_t images_done = 0; @@ -112,13 +115,15 @@ private: bool preview = false; std::vector lanes; /* DENOISE: the lanes it stepped, one per image */ std::vector marks; /* ... and whether each was marked for a preview */ + int32_t lora_slot = -1; /* every image of a pass runs with the same adapters */ }; /* Staging regions: their offsets in the host span and every rank's slab. */ struct Region { int64_t off = 0, bytes = 0, used = 0; }; enum { R_TOK, R_POS, R_ROPE, R_CU, R_MMROW, R_ENCPIX, R_ENCCRD, R_ENCCU, R_SRC, R_GROPE, R_SEG, R_SLOT, R_PX, R_MASK, R_SIG, R_SIGN, R_CFG, R_PAIR, R_LANE, R_FLAGS, R_SEED, - R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE, R_N }; + R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE, + R_AUX, R_SIGP, R_TSTEP, R_SAMP, R_STEPI, R_SIZE, R_N }; int layout_regions(); template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } @@ -147,6 +152,9 @@ private: RadGeneratorDecl decl_{}; std::vector fixed_; + /* A discrete-time model's sigma table (RadGeneratorDecl::train_steps), empty otherwise. */ + DiscreteTable table_; + bool discrete() const { return decl_.train_steps > 0; } int64_t max_tok_ = 0, max_seqs_ = 0, max_enc_ = 0, patch_dim_ = 0; int64_t max_rows_ = 0; /* the longest conditioning sequence */ int64_t max_px_ = 0; /* pixels the staging holds */ @@ -170,6 +178,8 @@ private: Pass pass_; /* Host arrays a COND pass's plugin reads on the host (RadGenBatch's _h fields). */ std::vector host_bidi_, host_px_, host_lanes_; + /* A DENOISE pass's per-entry host array (RadGenBatch::entry_h). */ + std::vector host_entry_; int64_t host_nmode_[3] = { 0, 0, 0 }; mutable std::mutex mu_; diff --git a/core/gen/gen.cpp b/core/gen/gen.cpp index 89e7eb2b..0ce151dd 100644 --- a/core/gen/gen.cpp +++ b/core/gen/gen.cpp @@ -67,6 +67,16 @@ std::vector schedule(const RadGeneratorDecl& d, const std::vector std::vector s; if (!fixed.empty()) { for (double v : fixed) s.push_back((float)v); + } else if (d.sigma_grid > 0) { + /* ComfyUI's `simple` scheduler: the model's table holds t = k / N for k = 1..N (an f32 + * quotient), and step i reads entry N - 1 - floor(i N / n), the floor of a Python float. */ + const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps; + const int64_t N = d.sigma_grid; + const double ss = (double)N / (double)n; + for (int32_t i = 0; i < n; ++i) { + const int64_t k = N - (int64_t)((double)i * ss); + s.push_back((float)k / (float)N); + } } else { const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps; /* np.linspace(1.0, 1 / n, n) in f64, then astype(f32). */ @@ -94,6 +104,127 @@ std::vector schedule(const RadGeneratorDecl& d, const std::vector return s; } +/* ================================================================== a discrete-time schedule */ +float DiscreteTable::sigma_at(double t) const { + const double hi = (double)(log_sigmas.size() - 1); + t = t < 0.0 ? 0.0 : t > hi ? hi : t; + const size_t lo = (size_t)std::floor(t), up = (size_t)std::ceil(t); + const float w = (float)(t - std::floor(t)); + return std::exp((1.0f - w) * log_sigmas[lo] + w * log_sigmas[up]); +} + +int32_t DiscreteTable::timestep(float sigma) const { + const float l = std::log(sigma); + int32_t best = 0; + float bd = std::fabs(l - log_sigmas[0]); + for (size_t i = 1; i < log_sigmas.size(); ++i) { + const float d = std::fabs(l - log_sigmas[i]); + if (d < bd) { bd = d; best = (int32_t)i; } + } + return best; +} + +int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why) { + const int32_t n = d.train_steps; + if (n < 2 || !(d.beta_start > 0) || !(d.beta_end > d.beta_start) || d.beta_end >= 1 || + (d.beta_schedule != RAD_GEN_BETAS_SCALED_LINEAR && d.beta_schedule != RAD_GEN_BETAS_LINEAR)) { + if (why) *why = "the discrete schedule needs two or more timesteps and betas rising in (0, 1)"; + return RAD_E_INVAL; + } + std::vector sig((size_t)n); + double abar = 1.0; + const bool sq = d.beta_schedule == RAD_GEN_BETAS_SCALED_LINEAR; + const double a = sq ? std::sqrt(d.beta_start) : d.beta_start; + const double b = sq ? std::sqrt(d.beta_end) : d.beta_end; + for (int32_t i = 0; i < n; ++i) { + const double v = a + (b - a) * (double)i / (double)(n - 1); + abar *= 1.0 - (sq ? v * v : v); + sig[(size_t)i] = std::sqrt((1.0 - abar) / abar); + } + if (d.zero_snr) { + /* ComfyUI's rescale_zero_terminal_snr_sigmas: sqrt(abar) shifted to end at 0 and scaled + * to keep its start, the last abar then set to a small positive value. */ + std::vector s((size_t)n); + for (int32_t i = 0; i < n; ++i) s[(size_t)i] = std::sqrt(1.0 / (sig[(size_t)i] * sig[(size_t)i] + 1.0)); + const double s0 = s.front(), sT = s.back(); + for (int32_t i = 0; i < n; ++i) { + double v = (s[(size_t)i] - sT) * (s0 / (s0 - sT)); + double ab = v * v; + if (i == n - 1) ab = 4.8973451890853435e-08; + sig[(size_t)i] = std::sqrt((1.0 - ab) / ab); + } + } + out->sigmas.resize((size_t)n); + out->log_sigmas.resize((size_t)n); + for (int32_t i = 0; i < n; ++i) { + out->sigmas[(size_t)i] = (float)sig[(size_t)i]; + out->log_sigmas[(size_t)i] = (float)std::log(sig[(size_t)i]); + } + return RAD_OK; +} + +std::vector schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t, + int32_t scheduler, int32_t steps) { + const int32_t n = steps > 0 ? steps : (int32_t)d.default_steps; + std::vector s; + const double smin = t.sigma_min(), smax = t.sigma_max(); + /* A point i of n evenly spaced from `a` to `b`, both ends included. */ + auto lin = [](double a, double b, int32_t i, int32_t cnt) { + return cnt <= 1 ? a : a + (b - a) * (double)i / (double)(cnt - 1); + }; + switch (scheduler) { + case RAD_GEN_SCHED_KARRAS: { + const double rho = 7.0, lo = std::pow(smin, 1.0 / rho), hi = std::pow(smax, 1.0 / rho); + for (int32_t i = 0; i < n; ++i) s.push_back((float)std::pow(lin(hi, lo, i, n), rho)); + break; + } + case RAD_GEN_SCHED_EXPONENTIAL: + for (int32_t i = 0; i < n; ++i) + s.push_back((float)std::exp(lin(std::log(smax), std::log(smin), i, n))); + break; + case RAD_GEN_SCHED_SIMPLE: { + const double stride = (double)t.sigmas.size() / (double)n; + for (int32_t i = 0; i < n; ++i) + s.push_back(t.sigmas[t.sigmas.size() - 1 - (size_t)((double)i * stride)]); + break; + } + case RAD_GEN_SCHED_SGM_UNIFORM: + case RAD_GEN_SCHED_NORMAL: + default: { + /* Timesteps from the largest sigma's to the smallest's, evenly spaced; sgm_uniform + * spaces n + 1 and drops the last. The model's clock ends at 0. */ + const double a = (double)t.timestep(t.sigma_max()), b = (double)t.timestep(t.sigma_min()); + const bool sgm = scheduler == RAD_GEN_SCHED_SGM_UNIFORM; + const int32_t cnt = sgm ? n + 1 : n; + for (int32_t i = 0; i < n; ++i) s.push_back(t.sigma_at(lin(a, b, i, cnt))); + break; + } + } + s.push_back(0.0f); + return s; +} + +namespace { +const char* const kSamplers[RAD_GEN_SAMPLER_COUNT] = { "euler", "euler_ancestral", "dpmpp_2m" }; +const char* const kScheds[RAD_GEN_SCHED_COUNT] = { "normal", "karras", "exponential", + "sgm_uniform", "simple" }; +} /* namespace */ + +const char* sampler_name(int32_t id) { + return id >= 0 && id < RAD_GEN_SAMPLER_COUNT ? kSamplers[id] : ""; +} +const char* scheduler_name(int32_t id) { + return id >= 0 && id < RAD_GEN_SCHED_COUNT ? kScheds[id] : ""; +} +int32_t sampler_id(const std::string& name) { + for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i) if (name == kSamplers[i]) return i; + return -1; +} +int32_t scheduler_id(const std::string& name) { + for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i) if (name == kScheds[i]) return i; + return -1; +} + /* ================================================================== the sequence */ void image_rope(int32_t pos, int32_t h, int32_t w, int32_t* planes, int64_t n_total) { const int32_t h0 = -(h - h / 2), w0 = -(w - w / 2); diff --git a/core/gen/gen.h b/core/gen/gen.h index 6ad9af96..597f9361 100644 --- a/core/gen/gen.h +++ b/core/gen/gen.h @@ -48,6 +48,9 @@ struct Branch { std::vector tokens; std::shared_ptr media; /* null for a prompt with no pictures */ int32_t n_drop = 0; + /* The user's prompt through the model's second tokenizer (RadGeneratorDecl::aux_tokens); + * empty otherwise. */ + std::vector aux; }; /* One finished image, or a preview of one. */ @@ -99,6 +102,8 @@ struct Request { float cfg = 1.0f; int32_t width = 0, height = 0; /* pixels, whole multiples of the declared multiple */ int32_t steps = 0; /* 0: the model's default (or its fixed schedule) */ + /* A discrete-time model's sampler and scheduler (RAD_GEN_SAMPLER_*, RAD_GEN_SCHED_*). */ + int32_t sampler = 0, scheduler = 0; int32_t n = 1; uint64_t seed = 0; /* image i draws its noise from seed + i */ int32_t previews = 0; /* partial images per image, 0..3 */ @@ -109,6 +114,10 @@ struct Request { bool inpaint = false; Pixels inp_src; std::vector inp_mask; + /* The runtime LoRA slot every pass of the request runs with (Engine::gen_lora_acquire), -1 + * for none, and the hold that keeps the slot's adapters in it until the request is done. */ + int32_t lora_slot = -1; + std::shared_ptr lora_hold; std::shared_ptr ticket; }; @@ -119,6 +128,31 @@ struct Request { std::vector schedule(const RadGeneratorDecl& d, const std::vector& fixed, int32_t steps, int64_t tokens); +/* ================================================================== a discrete-time schedule */ +/* The sigma table of a model trained on discrete timesteps (RadGeneratorDecl::train_steps), as + * ComfyUI's ModelSamplingDiscrete builds it: betas in f64, their cumulative product, sigma_t = + * sqrt((1 - abar_t) / abar_t), then f32, and the f32 logs. */ +struct DiscreteTable { + std::vector sigmas; /* [train_steps], ascending: sigmas[t] is timestep t's */ + std::vector log_sigmas; + float sigma_min() const { return sigmas.front(); } + float sigma_max() const { return sigmas.back(); } + /* sigma at a fractional timestep: the logs interpolated linearly, t clamped to the table. */ + float sigma_at(double t) const; + /* The timestep a sigma is conditioned at: the table's nearest in log sigma. */ + int32_t timestep(float sigma) const; +}; +/* RAD_E_INVAL with `why` for a declaration whose schedule cannot be built. */ +int discrete_table(const RadGeneratorDecl& d, DiscreteTable* out, std::string* why); +/* The n + 1 sigmas `scheduler` places for `steps` (0: the default) steps, the last 0. */ +std::vector schedule_discrete(const RadGeneratorDecl& d, const DiscreteTable& t, + int32_t scheduler, int32_t steps); +/* The names a request spells samplers and schedulers by, and their ids (-1: none). */ +const char* sampler_name(int32_t id); +const char* scheduler_name(int32_t id); +int32_t sampler_id(const std::string& name); +int32_t scheduler_id(const std::string& name); + /* ================================================================== the generator's sequence */ /* One conditioning sequence as the generator sees it (RadGeneratorDecl::layout): the prompt row or * reference latent row behind each row, rotary positions, segments, and the output image's frame. */ diff --git a/core/gen/pass.h b/core/gen/pass.h index 0577382d..e567c8bc 100644 --- a/core/gen/pass.h +++ b/core/gen/pass.h @@ -29,6 +29,8 @@ struct IPassDriver { * `step` is the engine's pass counter, carried into RadBatch::step. */ virtual const RadBatch* next(int step) = 0; virtual const RadBatch* batch_for(int rank) const = 0; + /* The runtime LoRA slot every row of the staged pass runs with, -1 for none. */ + virtual int32_t lora_slot() const { return -1; } /* What the staged pass's results are, valid until done(). */ virtual const std::vector& readbacks() const = 0; /* The pass has run on every rank, its streams are drained and the readbacks have landed. */ diff --git a/core/gen/video.h b/core/gen/video.h index eb0daf14..1d00161b 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -95,6 +95,11 @@ struct VideoRequest { std::vector image; /* The decoder (RadVideoGenDecl::decoders) by its index; 0 the model's default. */ int32_t decoder = 0; + /* The runtime LoRA slot the request's conditioning and denoising passes run with + * (Engine::gen_lora_acquire), -1 for none, and the hold that keeps it until the request is + * done. */ + int32_t lora_slot = -1; + std::shared_ptr lora_hold; std::shared_ptr ticket; }; diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index e702188c..34853e59 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -809,6 +809,7 @@ const RadBatch* VideoDriver::build_cond(Job& j, int step) { if (j.auto_len) rb_.assign(1, Readback{ decl_.duration_out, 4, duration_host_ }); pass_.kind = RAD_GEN_PASS_VCOND; pass_.job = j.id; + pass_.lora_slot = j.req->lora_slot; return &out_[0]; } @@ -858,6 +859,7 @@ const RadBatch* VideoDriver::build_step(Job& j, int step) { for (auto& B : out_) B.gen = RAD_GEN_PASS_VSTEP; pass_.kind = RAD_GEN_PASS_VSTEP; pass_.job = j.id; + pass_.lora_slot = j.req->lora_slot; return &out_[0]; } diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index 2962d229..d61b7a55 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -53,6 +53,7 @@ public: /* ---------------------------------------------------------- the engine thread */ const RadBatch* next(int step) override; const RadBatch* batch_for(int rank) const override; + int32_t lora_slot() const override { return pass_.lora_slot; } const std::vector& readbacks() const override { return rb_; } int done() override; @@ -99,6 +100,7 @@ private: int kind = 0; uint64_t job = 0; int32_t n_frames = 0; + int32_t lora_slot = -1; }; /* Staging regions: their offsets in the host span and every rank's slab. */ diff --git a/core/lora/adapter.cpp b/core/lora/adapter.cpp new file mode 100644 index 00000000..66dbeada --- /dev/null +++ b/core/lora/adapter.cpp @@ -0,0 +1,986 @@ +/* lora/adapter.cpp -- see adapter.h. Host code only. */ +#include "adapter.h" + +#include "rad_plugin.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace lora { + +namespace { + +#define TRY(x) do { const int s_ = (x); if (s_ < 0) return s_; } while (0) + +std::string fmt(const char* f, ...) __attribute__((format(printf, 1, 2))); +std::string fmt(const char* f, ...) { + char buf[2048]; + va_list ap; + va_start(ap, f); + vsnprintf(buf, sizeof buf, f, ap); + va_end(ap); + return buf; +} + +int fail(std::string* err, int code, const std::string& m) { + if (err) *err = m; + return code; +} + +bool ends_with(const std::string& s, const char* p) { + const size_t n = std::strlen(p); + return s.size() >= n && s.compare(s.size() - n, n, p) == 0; +} + +std::string shape_str(const std::vector& s) { + std::string r = "["; + for (size_t i = 0; i < s.size(); ++i) r += (i ? ", " : "") + std::to_string(s[i]); + return r + "]"; +} + +/* ---------------------------------------------------------------- tensors as f32 */ +bool float_dtype(uint32_t dt) { return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; } + +float elem(const StTensor& t, int64_t i) { + switch (t.dtype) { + case RAD_BF16: { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return rad_bf16_to_f32(v); } + case RAD_F16: { uint16_t v; std::memcpy(&v, t.data + 2 * i, 2); return rad_f16_to_f32(v); } + default: { float v; std::memcpy(&v, t.data + 4 * i, 4); return v; } + } +} + +/* A tensor as a row-major matrix [shape[0], product of the rest]. */ +int as_matrix(const StTensor* t, const char* what, int64_t* rows, int64_t* cols, + std::vector* out, std::string* err) { + if (!t) return fail(err, RAD_E_FORMAT, fmt("no %s tensor", what)); + if (!float_dtype(t->dtype)) + return fail(err, RAD_E_DTYPE, fmt("%s is %s; expected BF16, F16 or F32", t->name.c_str(), + t->dtype_str.c_str())); + if (t->shape.size() < 2 || !t->data) + return fail(err, RAD_E_SHAPE, fmt("%s has shape %s; expected a matrix", t->name.c_str(), + shape_str(t->shape).c_str())); + *rows = t->shape[0]; + *cols = t->numel() / (t->shape[0] ? t->shape[0] : 1); + if (out) { + out->resize((size_t)(*rows * *cols)); + for (int64_t i = 0; i < *rows * *cols; ++i) (*out)[(size_t)i] = elem(*t, i); + } + return RAD_OK; +} + +/* The trailing dims past the first two, all 1 (an up projection of a convolution is 1 x 1). */ +bool trailing_ones(const StTensor* t) { + for (size_t i = 2; i < t->shape.size(); ++i) if (t->shape[i] != 1) return false; + return true; +} + +/* One number: shape [] (numel() counts it as no element) or [1], a float or (as some trainers + * write an alpha) an integer or F64. */ +int scalar(const StTensor* t, double* v, std::string* err) { + const int64_t n = t->shape.empty() ? 1 : t->numel(); + if (n != 1 || !t->data) + return fail(err, RAD_E_FORMAT, fmt("%s is not one number", t->name.c_str())); + if (float_dtype(t->dtype)) { + *v = elem(*t, 0); + } else if (t->dtype == RAD_I64 && t->bytes >= 8) { + int64_t x; std::memcpy(&x, t->data, 8); *v = (double)x; + } else if (t->dtype == RAD_I32 && t->bytes >= 4) { + int32_t x; std::memcpy(&x, t->data, 4); *v = (double)x; + } else if (t->dtype_str == "F64" && t->bytes >= 8) { + std::memcpy(v, t->data, 8); + } else { + return fail(err, RAD_E_FORMAT, fmt("%s is %s, not a number this reader knows", + t->name.c_str(), t->dtype_str.c_str())); + } + return std::isfinite(*v) ? RAD_OK : fail(err, RAD_E_FORMAT, t->name + " is not finite"); +} + +/* ---------------------------------------------------------------- dense f32 kernels */ +/* C[m, n] (+)= A[m, k] B[k, n], row-major. */ +void mm(const float* A, const float* B, float* C, int64_t m, int64_t k, int64_t n, bool add = false) { + if (!add) std::fill(C, C + m * n, 0.0f); + for (int64_t i = 0; i < m; ++i) { + float* c = C + i * n; + for (int64_t p = 0; p < k; ++p) { + const float a = A[i * k + p]; + if (a == 0.0f) continue; + const float* b = B + p * n; + for (int64_t j = 0; j < n; ++j) c[j] += a * b[j]; + } + } +} +/* C[m, n] (+)= A[k, m]^T B[k, n]. */ +void mm_tn(const float* A, const float* B, float* C, int64_t m, int64_t k, int64_t n, bool add = false) { + if (!add) std::fill(C, C + m * n, 0.0f); + for (int64_t p = 0; p < k; ++p) { + const float* a = A + p * m; + const float* b = B + p * n; + for (int64_t i = 0; i < m; ++i) { + const float x = a[i]; + if (x == 0.0f) continue; + float* c = C + i * n; + for (int64_t j = 0; j < n; ++j) c[j] += x * b[j]; + } + } +} + +/* Orthonormalise the l columns of Y [n, l] in place (modified Gram-Schmidt, twice). A column + * that vanishes is left zero. */ +void orth(float* Y, int64_t n, int64_t l) { + std::vector col((size_t)n); + for (int64_t j = 0; j < l; ++j) { + for (int pass = 0; pass < 2; ++pass) + for (int64_t i = 0; i < j; ++i) { + double d = 0.0; + for (int64_t r = 0; r < n; ++r) d += (double)Y[r * l + i] * Y[r * l + j]; + for (int64_t r = 0; r < n; ++r) Y[r * l + j] -= (float)(d * Y[r * l + i]); + } + double nn = 0.0; + for (int64_t r = 0; r < n; ++r) nn += (double)Y[r * l + j] * Y[r * l + j]; + const double inv = nn > 1e-30 ? 1.0 / std::sqrt(nn) : 0.0; + for (int64_t r = 0; r < n; ++r) Y[r * l + j] = (float)(Y[r * l + j] * inv); + } +} + +/* Eigen-decomposition of a symmetric l x l matrix (cyclic Jacobi): eigenvalues in `w`, sorted + * descending, and eigenvectors as the columns of V [l, l]. */ +void sym_eig(std::vector G, int64_t l, std::vector* w, std::vector* V) { + V->assign((size_t)(l * l), 0.0); + for (int64_t i = 0; i < l; ++i) (*V)[(size_t)(i * l + i)] = 1.0; + for (int sweep = 0; sweep < 60; ++sweep) { + double off = 0.0, tot = 0.0; + for (int64_t i = 0; i < l; ++i) + for (int64_t j = 0; j < l; ++j) { + const double g = G[(size_t)(i * l + j)]; + tot += g * g; + if (i != j) off += g * g; + } + if (off <= 1e-24 * (tot > 0 ? tot : 1.0)) break; + for (int64_t p = 0; p < l; ++p) + for (int64_t q = p + 1; q < l; ++q) { + const double gpq = G[(size_t)(p * l + q)]; + if (std::fabs(gpq) < 1e-300) continue; + const double gpp = G[(size_t)(p * l + p)], gqq = G[(size_t)(q * l + q)]; + const double th = (gqq - gpp) / (2.0 * gpq); + const double t = (th >= 0 ? 1.0 : -1.0) / (std::fabs(th) + std::sqrt(th * th + 1.0)); + const double c = 1.0 / std::sqrt(t * t + 1.0), s = t * c; + for (int64_t k = 0; k < l; ++k) { + const double gkp = G[(size_t)(k * l + p)], gkq = G[(size_t)(k * l + q)]; + G[(size_t)(k * l + p)] = c * gkp - s * gkq; + G[(size_t)(k * l + q)] = s * gkp + c * gkq; + } + for (int64_t k = 0; k < l; ++k) { + const double gpk = G[(size_t)(p * l + k)], gqk = G[(size_t)(q * l + k)]; + G[(size_t)(p * l + k)] = c * gpk - s * gqk; + G[(size_t)(q * l + k)] = s * gpk + c * gqk; + } + for (int64_t k = 0; k < l; ++k) { + const double vkp = (*V)[(size_t)(k * l + p)], vkq = (*V)[(size_t)(k * l + q)]; + (*V)[(size_t)(k * l + p)] = c * vkp - s * vkq; + (*V)[(size_t)(k * l + q)] = s * vkp + c * vkq; + } + } + } + std::vector ord((size_t)l); + for (int64_t i = 0; i < l; ++i) ord[(size_t)i] = i; + std::sort(ord.begin(), ord.end(), [&](int64_t a, int64_t b) { + return G[(size_t)(a * l + a)] > G[(size_t)(b * l + b)]; + }); + std::vector V2((size_t)(l * l)); + w->resize((size_t)l); + for (int64_t c = 0; c < l; ++c) { + (*w)[(size_t)c] = G[(size_t)(ord[(size_t)c] * l + ord[(size_t)c])]; + for (int64_t r = 0; r < l; ++r) V2[(size_t)(r * l + c)] = (*V)[(size_t)(r * l + ord[(size_t)c])]; + } + *V = std::move(V2); +} + +/* ||B A||_F^2 for B [n, r], A [r, k]: trace((B^T B)(A A^T)). */ +double lowrank_energy(const std::vector& B, const std::vector& A, int64_t n, int64_t r, + int64_t k) { + std::vector bb((size_t)(r * r), 0.0), aa((size_t)(r * r), 0.0); + for (int64_t i = 0; i < n; ++i) + for (int64_t p = 0; p < r; ++p) { + const double x = B[(size_t)(i * r + p)]; + if (x == 0.0) continue; + for (int64_t q = 0; q < r; ++q) bb[(size_t)(p * r + q)] += x * B[(size_t)(i * r + q)]; + } + for (int64_t p = 0; p < r; ++p) + for (int64_t q = p; q < r; ++q) { + double d = 0.0; + for (int64_t j = 0; j < k; ++j) d += (double)A[(size_t)(p * k + j)] * A[(size_t)(q * k + j)]; + aa[(size_t)(p * r + q)] = aa[(size_t)(q * r + p)] = d; + } + double e = 0.0; + for (size_t i = 0; i < bb.size(); ++i) e += bb[i] * aa[i]; + return e; +} + +/* ---------------------------------------------------------------- the key suffixes */ +struct Suffix { + const char* s; + int kind; /* FileModule::Kind, or -1 alpha, -2 refused, -3 skipped */ + int slot; + const char* why; +}; +const Suffix kSuffix[] = { + { ".lora_down.weight", FileModule::LORA, 0, nullptr }, + { ".lora_up.weight", FileModule::LORA, 1, nullptr }, + { ".lora_A.default.weight", FileModule::LORA, 0, nullptr }, + { ".lora_B.default.weight", FileModule::LORA, 1, nullptr }, + { ".lora_A.weight", FileModule::LORA, 0, nullptr }, + { ".lora_B.weight", FileModule::LORA, 1, nullptr }, + { ".lora_linear_layer.down.weight", FileModule::LORA, 0, nullptr }, + { ".lora_linear_layer.up.weight", FileModule::LORA, 1, nullptr }, + { ".lora.down.weight", FileModule::LORA, 0, nullptr }, + { ".lora.up.weight", FileModule::LORA, 1, nullptr }, + { ".hada_w1_a", FileModule::LOHA, 0, nullptr }, + { ".hada_w1_b", FileModule::LOHA, 1, nullptr }, + { ".hada_w2_a", FileModule::LOHA, 2, nullptr }, + { ".hada_w2_b", FileModule::LOHA, 3, nullptr }, + { ".lokr_w1", FileModule::LOKR, 0, nullptr }, + { ".lokr_w1_a", FileModule::LOKR, 1, nullptr }, + { ".lokr_w1_b", FileModule::LOKR, 2, nullptr }, + { ".lokr_w2", FileModule::LOKR, 3, nullptr }, + { ".lokr_w2_a", FileModule::LOKR, 4, nullptr }, + { ".lokr_w2_b", FileModule::LOKR, 5, nullptr }, + { ".diff", FileModule::FULL, 0, nullptr }, + { ".alpha", -1, 0, nullptr }, + { ".lora_alpha", -1, 0, nullptr }, + { ".dora_scale", -2, 0, "a DoRA magnitude, which rescales the base weight's columns" }, + { ".lora_magnitude_vector.default.weight", -2, 0, "a DoRA magnitude, which rescales the base " + "weight's columns" }, + { ".lora_magnitude_vector.weight", -2, 0, "a DoRA magnitude, which rescales the base weight's " + "columns" }, + { ".lora_magnitude_vector", -2, 0, "a DoRA magnitude, which rescales the base weight's columns" }, + { ".hada_t1", -2, 0, "a LoHa Tucker core" }, + { ".hada_t2", -2, 0, "a LoHa Tucker core" }, + { ".lokr_t2", -2, 0, "a LoKr Tucker core" }, + { ".lora_mid.weight", -2, 0, "a LoCon Tucker core" }, + { ".oft_blocks", -2, 0, "an OFT rotation" }, + { ".oft_diag", -2, 0, "an OFT rotation" }, + { ".oft_R.weight", -2, 0, "an OFT rotation" }, + { ".boft_R", -2, 0, "a BOFT rotation" }, + { ".diff_b", -3, 0, "a bias delta" }, + { ".w_norm", -3, 0, "a norm's weight delta" }, + { ".b_norm", -3, 0, "a norm's bias delta" }, + { ".lora_B.bias", -3, 0, "a bias on lora_B" }, + { ".lora_up.bias", -3, 0, "a bias on lora_up" }, + { ".set_weight", -2, 0, "a replacement weight" }, +}; + +} /* namespace */ + +/* ================================================================== the file */ +int AdapterFile::open(const std::string& path, std::string* err) { + mods_.clear(); + skipped_.clear(); + if (st_.open(path) != RAD_OK) return fail(err, RAD_E_IO, path + ": cannot open as safetensors"); + std::map by; + std::map alphas; + for (const StTensor& t : st_.tensors()) { + const Suffix* hit = nullptr; + for (const Suffix& s : kSuffix) + if (ends_with(t.name, s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s; + if (!hit) { + skipped_.push_back({ t.name, "not an adapter tensor" }); + continue; + } + const std::string key = t.name.substr(0, t.name.size() - std::strlen(hit->s)); + if (hit->kind == -2) + return fail(err, RAD_E_UNSUPPORTED, fmt("%s: %s is %s; that kind of adapter is not " + "served", path.c_str(), t.name.c_str(), hit->why)); + if (hit->kind == -3) { skipped_.push_back({ t.name, hit->why }); continue; } + if (hit->kind == -1) { alphas[key] = &t; continue; } + FileModule& m = by[key]; + if (m.key.empty()) { m.key = key; m.kind = (FileModule::Kind)hit->kind; } + else if (m.kind != hit->kind) + return fail(err, RAD_E_FORMAT, fmt("%s: module %s mixes adapter kinds", path.c_str(), + key.c_str())); + if (m.t[hit->slot]) + return fail(err, RAD_E_FORMAT, fmt("%s: module %s has two %s tensors", path.c_str(), + key.c_str(), hit->s)); + m.t[hit->slot] = &t; + } + for (auto& [k, a] : alphas) { + auto it = by.find(k); + if (it == by.end()) { skipped_.push_back({ a->name, "an alpha of no module" }); continue; } + it->second.alpha = a; + } + for (auto& [k, m] : by) { + const char* missing = nullptr; + switch (m.kind) { + case FileModule::LORA: + if (!m.t[0] || !m.t[1]) missing = m.t[0] ? "up/B" : "down/A"; + break; + case FileModule::LOHA: + if (!m.t[0] || !m.t[1] || !m.t[2] || !m.t[3]) missing = "a hada_w factor"; + break; + case FileModule::LOKR: + if (!m.t[0] && !(m.t[1] && m.t[2])) missing = "lokr_w1 (or lokr_w1_a and _b)"; + else if (!m.t[3] && !(m.t[4] && m.t[5])) missing = "lokr_w2 (or lokr_w2_a and _b)"; + break; + case FileModule::FULL: break; + } + if (missing) + return fail(err, RAD_E_FORMAT, fmt("%s: module %s has no %s", path.c_str(), k.c_str(), + missing)); + mods_.push_back(m); + } + if (mods_.empty()) return fail(err, RAD_E_FORMAT, path + ": no adapter modules in the file"); + return RAD_OK; +} + +const char* AdapterFile::kind_name() const { + int n[4] = { 0, 0, 0, 0 }; + for (const FileModule& m : mods_) ++n[m.kind]; + const int k = (int)(std::max_element(n, n + 4) - n); + static const char* const kName[] = { "LoRA", "LoHa", "LoKr", "full" }; + return kName[k]; +} + +/* ================================================================== deltas */ +int module_delta(const FileModule& m, double w, Delta* out, std::string* err) { + *out = Delta{}; + double alpha = 0.0; + const bool has_alpha = m.alpha != nullptr; + if (has_alpha) TRY(scalar(m.alpha, &alpha, err)); + + if (m.kind == FileModule::LORA) { + int64_t r = 0, K = 0, N = 0, r2 = 0; + std::vector A, B; + TRY(as_matrix(m.t[0], "down", &r, &K, &A, err)); + TRY(as_matrix(m.t[1], "up", &N, &r2, &B, err)); + if (!trailing_ones(m.t[1]) || r2 != r) + return fail(err, RAD_E_SHAPE, fmt("module %s: down %s and up %s are not one rank-%lld " + "pair", m.key.c_str(), shape_str(m.t[0]->shape).c_str(), + shape_str(m.t[1]->shape).c_str(), (long long)r)); + const double s = w * (has_alpha && r > 0 ? alpha / (double)r : 1.0); + for (float& x : B) x = (float)(x * s); + out->N = N; out->K = K; out->r = r; out->rank_bound = r; out->low_rank = true; + out->A = std::move(A); out->B = std::move(B); + out->energy = lowrank_energy(out->B, out->A, N, r, K); + return RAD_OK; + } + + if (m.kind == FileModule::LOHA) { + int64_t N1 = 0, r1 = 0, r1b = 0, K1 = 0, N2 = 0, r2 = 0, r2b = 0, K2 = 0; + std::vector w1a, w1b, w2a, w2b; + TRY(as_matrix(m.t[0], "hada_w1_a", &N1, &r1, &w1a, err)); + TRY(as_matrix(m.t[1], "hada_w1_b", &r1b, &K1, &w1b, err)); + TRY(as_matrix(m.t[2], "hada_w2_a", &N2, &r2, &w2a, err)); + TRY(as_matrix(m.t[3], "hada_w2_b", &r2b, &K2, &w2b, err)); + if (r1 != r1b || r2 != r2b || N1 != N2 || K1 != K2) + return fail(err, RAD_E_SHAPE, fmt("module %s: LoHa factors %s %s %s %s do not pair", + m.key.c_str(), shape_str(m.t[0]->shape).c_str(), + shape_str(m.t[1]->shape).c_str(), + shape_str(m.t[2]->shape).c_str(), + shape_str(m.t[3]->shape).c_str())); + /* (w1a w1b) o (w2a w2b) = sum over (i, j) of (w1a[:, i] o w2a[:, j]) (w1b[i] o w2b[j]): + * exactly rank r1 r2. */ + const double s = w * (has_alpha && r1 > 0 ? alpha / (double)r1 : 1.0); + const int64_t R = r1 * r2, N = N1, K = K1; + out->B.assign((size_t)(N * R), 0.0f); + out->A.assign((size_t)(R * K), 0.0f); + for (int64_t n = 0; n < N; ++n) + for (int64_t i = 0; i < r1; ++i) + for (int64_t j = 0; j < r2; ++j) + out->B[(size_t)(n * R + i * r2 + j)] = + (float)(s * w1a[(size_t)(n * r1 + i)] * w2a[(size_t)(n * r2 + j)]); + for (int64_t i = 0; i < r1; ++i) + for (int64_t j = 0; j < r2; ++j) + for (int64_t k = 0; k < K; ++k) + out->A[(size_t)((i * r2 + j) * K + k)] = w1b[(size_t)(i * K + k)] * w2b[(size_t)(j * K + k)]; + out->N = N; out->K = K; out->r = R; out->rank_bound = R; out->low_rank = true; + out->energy = lowrank_energy(out->B, out->A, N, R, K); + return RAD_OK; + } + + if (m.kind == FileModule::LOKR) { + /* kron(w1 [a, b], w2 [c, e]) is [a c, b e]: element (i1 c + i2, j1 e + j2) is + * w1[i1, j1] w2[i2, j2]. A convolution's w2 [c, d, kh, kw] flattens to e = d kh kw, which + * is the flattened kron of the 4-D tensors. */ + int64_t a = 0, b = 0, dim = 0; + std::vector W1; + if (m.t[0]) { + TRY(as_matrix(m.t[0], "lokr_w1", &a, &b, &W1, err)); + } else { + int64_t r = 0, r2 = 0; + std::vector x, y; + TRY(as_matrix(m.t[1], "lokr_w1_a", &a, &r, &x, err)); + TRY(as_matrix(m.t[2], "lokr_w1_b", &r2, &b, &y, err)); + if (r != r2) return fail(err, RAD_E_SHAPE, "module " + m.key + ": lokr_w1_a/_b ranks differ"); + W1.resize((size_t)(a * b)); + mm(x.data(), y.data(), W1.data(), a, r, b); + dim = r; + } + int64_t c = 0, e = 0, r2 = 0; + auto W2 = std::make_shared>(); + auto W2a = std::make_shared>(); + auto W2b = std::make_shared>(); + if (m.t[3]) { + TRY(as_matrix(m.t[3], "lokr_w2", &c, &e, W2.get(), err)); + } else { + int64_t rr = 0; + TRY(as_matrix(m.t[4], "lokr_w2_a", &c, &r2, W2a.get(), err)); + TRY(as_matrix(m.t[5], "lokr_w2_b", &rr, &e, W2b.get(), err)); + if (rr != r2) return fail(err, RAD_E_SHAPE, "module " + m.key + ": lokr_w2_a/_b ranks differ"); + dim = r2; + } + const double s = w * (has_alpha && dim > 0 ? alpha / (double)dim : 1.0); + for (float& x : W1) x = (float)(x * s); + auto w1 = std::make_shared>(std::move(W1)); + const int64_t N = a * c, K = b * e; + out->N = N; out->K = K; + out->rank_bound = std::min(a, b) * (r2 ? r2 : std::min(c, e)); + const bool full2 = !W2->empty(); + /* ||kron(w1, w2)|| = ||w1|| ||w2|| */ + { + double e1 = 0.0; + for (float x : *w1) e1 += (double)x * x; + double e2 = 0.0; + if (full2) for (float x : *W2) e2 += (double)x * x; + else e2 = lowrank_energy(*W2a, *W2b, c, r2, e); + out->energy = e1 * e2; + } + /* Column x of X [K, l], as the matrix [b, e]: kron(w1, w2) x = w1 X w2^T, read as [a, c]. */ + out->apply = [=](const float* X, int64_t l, float* Y) { + std::vector xm((size_t)(b * e)), t((size_t)(b * c)), y((size_t)(a * c)), u; + for (int64_t col = 0; col < l; ++col) { + for (int64_t k = 0; k < K; ++k) xm[(size_t)k] = X[k * l + col]; + if (full2) { + /* t[j1, i2] = sum_j2 xm[j1, j2] w2[i2, j2] */ + for (int64_t j1 = 0; j1 < b; ++j1) + for (int64_t i2 = 0; i2 < c; ++i2) { + float d = 0.0f; + const float* xr = xm.data() + j1 * e; + const float* wr = W2->data() + i2 * e; + for (int64_t j2 = 0; j2 < e; ++j2) d += xr[j2] * wr[j2]; + t[(size_t)(j1 * c + i2)] = d; + } + } else { + u.assign((size_t)(b * r2), 0.0f); + for (int64_t j1 = 0; j1 < b; ++j1) + for (int64_t p = 0; p < r2; ++p) { + float d = 0.0f; + const float* xr = xm.data() + j1 * e; + const float* wr = W2b->data() + p * e; + for (int64_t j2 = 0; j2 < e; ++j2) d += xr[j2] * wr[j2]; + u[(size_t)(j1 * r2 + p)] = d; + } + for (int64_t j1 = 0; j1 < b; ++j1) + for (int64_t i2 = 0; i2 < c; ++i2) { + float d = 0.0f; + for (int64_t p = 0; p < r2; ++p) d += u[(size_t)(j1 * r2 + p)] * (*W2a)[(size_t)(i2 * r2 + p)]; + t[(size_t)(j1 * c + i2)] = d; + } + } + mm(w1->data(), t.data(), y.data(), a, b, c); + for (int64_t n = 0; n < N; ++n) Y[n * l + col] = y[(size_t)n]; + } + }; + /* The transpose: kron(w1, w2)^T y = w1^T Y w2, Y the column as [a, c], read as [b, e]. */ + out->apply_t = [=](const float* Yin, int64_t l, float* X) { + std::vector ym((size_t)(a * c)), t((size_t)(b * c)), x((size_t)(b * e)), u; + for (int64_t col = 0; col < l; ++col) { + for (int64_t n = 0; n < N; ++n) ym[(size_t)n] = Yin[n * l + col]; + mm_tn(w1->data(), ym.data(), t.data(), b, a, c); /* [b, c] */ + if (full2) { + mm(t.data(), W2->data(), x.data(), b, c, e); + } else { + u.assign((size_t)(b * r2), 0.0f); + mm(t.data(), W2a->data(), u.data(), b, c, r2); + mm(u.data(), W2b->data(), x.data(), b, r2, e); + } + for (int64_t k = 0; k < K; ++k) X[k * l + col] = x[(size_t)k]; + } + }; + return RAD_OK; + } + + /* FULL */ + int64_t N = 0, K = 0; + auto D = std::make_shared>(); + TRY(as_matrix(m.t[0], "diff", &N, &K, D.get(), err)); + for (float& x : *D) x = (float)(x * w); + out->N = N; out->K = K; out->rank_bound = std::min(N, K); + out->energy = 0.0; + for (float x : *D) out->energy += (double)x * x; + out->apply = [D, N, K](const float* X, int64_t l, float* Y) { mm(D->data(), X, Y, N, K, l); }; + out->apply_t = [D, N, K](const float* Yin, int64_t l, float* X) { mm_tn(D->data(), Yin, X, K, N, l); }; + return RAD_OK; +} + +void truncate(const Delta& d, int64_t r, std::vector* B, std::vector* A, double* kept) { + const int64_t N = d.N, K = d.K; + r = std::max(0, std::min({ r, N, K, d.rank_bound > 0 ? d.rank_bound : r })); + if (kept) *kept = 1.0; + if (d.low_rank && d.r <= r) { *B = d.B; *A = d.A; return; } + auto fwd = [&](const float* X, int64_t l, float* Y) { + if (!d.low_rank) { d.apply(X, l, Y); return; } + std::vector t((size_t)(d.r * l)); + mm(d.A.data(), X, t.data(), d.r, K, l); + mm(d.B.data(), t.data(), Y, N, d.r, l); + }; + auto bwd = [&](const float* Y, int64_t l, float* X) { + if (!d.low_rank) { d.apply_t(Y, l, X); return; } + std::vector t((size_t)(d.r * l)); + mm_tn(d.B.data(), Y, t.data(), d.r, N, l); + mm_tn(d.A.data(), t.data(), X, K, d.r, l); + }; + const int64_t l = std::min({ r + 8, N, K }); + /* A fixed sketch: the same adapter composes to the same bytes on every rank and every load. */ + std::vector Om((size_t)(K * l)); + uint64_t st = 0x2545F4914F6CDD1Dull ^ (uint64_t)(N * 1315423911ull + K); + for (float& x : Om) { + st ^= st << 13; st ^= st >> 7; st ^= st << 17; + x = (float)((double)(st >> 11) / (double)(1ull << 53) - 0.5); + } + std::vector Y((size_t)(N * l)), Z((size_t)(K * l)); + fwd(Om.data(), l, Y.data()); + orth(Y.data(), N, l); + for (int it = 0; it < 2; ++it) { + bwd(Y.data(), l, Z.data()); + orth(Z.data(), K, l); + fwd(Z.data(), l, Y.data()); + orth(Y.data(), N, l); + } + /* C^T = D^T Q [K, l]; the SVD of C = Q^T D from the eigen-decomposition of C C^T. */ + bwd(Y.data(), l, Z.data()); + std::vector G((size_t)(l * l), 0.0); + for (int64_t k = 0; k < K; ++k) + for (int64_t i = 0; i < l; ++i) { + const double x = Z[(size_t)(k * l + i)]; + if (x == 0.0) continue; + for (int64_t j = i; j < l; ++j) G[(size_t)(i * l + j)] += x * Z[(size_t)(k * l + j)]; + } + for (int64_t i = 0; i < l; ++i) + for (int64_t j = 0; j < i; ++j) G[(size_t)(i * l + j)] = G[(size_t)(j * l + i)]; + std::vector w, V; + sym_eig(G, l, &w, &V); + double tot = 0.0, top = 0.0; + for (int64_t i = 0; i < l; ++i) tot += std::max(0.0, w[(size_t)i]); + for (int64_t i = 0; i < r; ++i) top += std::max(0.0, w[(size_t)i]); + if (d.energy > 0.0) tot = std::max(tot, d.energy); + if (kept) *kept = tot > 0.0 ? std::min(1.0, top / tot) : 1.0; + B->assign((size_t)(N * r), 0.0f); + A->assign((size_t)(r * K), 0.0f); + for (int64_t i = 0; i < r; ++i) { + const double sg = std::sqrt(std::max(0.0, w[(size_t)i])); + if (sg <= 1e-20) continue; + /* B[:, i] = Q V[:, i] sigma_i; A[i] = V[:, i]^T C / sigma_i. */ + for (int64_t n = 0; n < N; ++n) { + double acc = 0.0; + for (int64_t j = 0; j < l; ++j) acc += (double)Y[(size_t)(n * l + j)] * V[(size_t)(j * l + i)]; + (*B)[(size_t)(n * r + i)] = (float)(acc * sg); + } + for (int64_t k = 0; k < K; ++k) { + double acc = 0.0; + for (int64_t j = 0; j < l; ++j) acc += V[(size_t)(j * l + i)] * Z[(size_t)(k * l + j)]; + (*A)[(size_t)(i * K + k)] = (float)(acc / sg); + } + } +} + +/* ================================================================== the key map */ +namespace { + +std::string underscored(std::string s) { + for (char& c : s) if (c == '.') c = '_'; + return s; +} + +std::regex pattern(const std::string& from, bool kohya) { + std::string re = "^"; + for (char c : kohya ? underscored(from) : from) { + if (c == '#') re += "([0-9]+)"; + else if (std::strchr(".^$|()[]{}*+?\\", c)) { re += '\\'; re += c; } + else re += c; + } + return std::regex(re + "$", std::regex::ECMAScript | std::regex::optimize); +} + +std::string module_of(const std::string& src) { + return ends_with(src, ".weight") ? src.substr(0, src.size() - 7) : std::string(); +} + +} /* namespace */ + +KeyMap::KeyMap(const Program& prog, const std::vector& sites) : prog_(&prog) { + for (const Site& s : sites) + for (size_t i = 0; i < s.sources.size(); ++i) { + const SiteSource& src = s.sources[i]; + if (!src.targeted) continue; + const size_t at = src.module.find('@'); + if (at != std::string::npos) { + /* A row piece: the module stays adaptable, its rows open (the adapter's say). */ + Piece p; + p.name = src.module; + p.lo = std::strtoll(src.module.c_str() + at + 1, nullptr, 10); + const size_t plus = src.module.find('+', at); + p.n = plus == std::string::npos ? 0 : std::strtoll(src.module.c_str() + plus + 1, nullptr, 10); + const std::string real = src.module.substr(0, at); + std::vector& ps = pieces_[real]; + bool dup = false; + for (const Piece& q : ps) dup = dup || q.name == p.name; + if (!dup) ps.push_back(p); + adaptable_[real] = { -1, s.K_full > 0 ? s.K_full : -1 }; + continue; + } + whole_.insert(src.module); + int64_t rows = -1; + if (src.part_lo >= 0) { + rows = 0; + for (int g = src.part_lo; g < src.part_hi; ++g) { + const int64_t t = s.part_total[(size_t)g]; + if (t <= 0) { rows = -1; break; } + rows += t; + } + } else if (s.sources.size() == 1 && s.part_total.size() == 1 && s.part_total[0] > 0) { + rows = s.part_total[0]; + } + adaptable_[src.module] = { rows, s.K_full > 0 ? s.K_full : -1 }; + } + for (const LoraRoot& r : prog.lora_roots) { + Root R; + R.native = r.native; + R.spellings = r.spellings; + R.spellings.push_back(r.native); + std::sort(R.spellings.begin(), R.spellings.end(), + [](const std::string& a, const std::string& b) { return a.size() > b.size(); }); + R.spellings.erase(std::unique(R.spellings.begin(), R.spellings.end()), R.spellings.end()); + roots_.push_back(std::move(R)); + } + for (const RadNameMap& m : prog.name_map) + for (int k = 0; k < m.n_src && k < 8; ++k) { + if (!m.src[k]) continue; + const std::string mod = module_of(m.src[k]); + if (mod.empty()) continue; + for (Root& R : roots_) { + if (mod.compare(0, R.native.size(), R.native) != 0) continue; + if (!adaptable_.count(mod) && !known_.count(mod)) + known_[mod] = "the base reads it with an op no adapter path follows (a fused " + "activation, a rotated input, or not a GEMM)"; + const std::string u = underscored(mod.substr(R.native.size())); + auto it = R.kohya.find(u); + if (it == R.kohya.end()) R.kohya[u] = mod; + else if (it->second != mod) it->second.clear(); /* ambiguous */ + } + } + for (const LoraAlias& a : prog.lora_aliases) { + for (size_t ri = 0; ri < roots_.size(); ++ri) { + if (roots_[ri].native != a.root) continue; + Alias x; + x.root = ri; + x.from = a.from; x.to = a.to; + x.from_lo = a.from_lo; x.from_hi = a.from_hi; x.to_lo = a.to_lo; + x.dotted = pattern(a.from, false); + x.kohya = pattern(a.from, true); + aliases_.push_back(std::move(x)); + } + } +} + +int64_t KeyMap::rows(const std::string& module) const { + auto it = adaptable_.find(module); + return it == adaptable_.end() ? -1 : it->second.first; +} +const std::vector& KeyMap::pieces(const std::string& module) const { + static const std::vector none; + auto it = pieces_.find(module); + return it == pieces_.end() ? none : it->second; +} +int64_t KeyMap::cols(const std::string& module) const { + auto it = adaptable_.find(module); + return it == adaptable_.end() ? -1 : it->second.second; +} + +bool KeyMap::lookup(const Root& r, const std::string& rel, bool kohya, std::vector* out, + std::string* why) const { + auto take = [&](const std::string& mod, int64_t lo, int64_t hi, int64_t to) { + if (adaptable_.count(mod)) { + Target t; + t.module = mod; t.from_lo = lo; t.from_hi = hi; t.to_lo = to; + out->push_back(t); + return true; + } + auto k = known_.find(mod); + if (k != known_.end() && why) *why = mod + ": " + k->second; + return false; + }; + if (kohya) { + auto it = r.kohya.find(rel); + if (it != r.kohya.end()) { + if (it->second.empty()) { if (why) *why = "its kohya name matches two modules of the base"; } + else if (take(it->second, 0, 0, 0)) return true; + } + } else if (take(r.native + rel, 0, 0, 0)) { + return true; + } + const size_t ri = (size_t)(&r - roots_.data()); + for (const Alias& a : aliases_) { + if (a.root != ri) continue; + std::smatch m; + if (!std::regex_match(rel, m, kohya ? a.kohya : a.dotted)) continue; + std::string to; + size_t g = 1; + for (char c : a.to) { + if (c == '#' && g < m.size()) to += m[g++].str(); + else to += c; + } + take(r.native + to, a.from_lo, a.from_hi, a.to_lo); + } + return !out->empty(); +} + +std::vector KeyMap::resolve(const std::string& key, std::string* why) const { + struct Cand { size_t root; size_t len; bool kohya; }; + std::vector cs; + for (size_t ri = 0; ri < roots_.size(); ++ri) + for (const std::string& sp : roots_[ri].spellings) + if (key.compare(0, sp.size(), sp) == 0) + cs.push_back({ ri, sp.size(), !sp.empty() && sp.back() == '_' }); + std::stable_sort(cs.begin(), cs.end(), [](const Cand& a, const Cand& b) { return a.len > b.len; }); + std::vector out; + std::string first_why; + for (const Cand& c : cs) { + std::string w; + if (lookup(roots_[c.root], key.substr(c.len), c.kohya, &out, &w)) return out; + if (first_why.empty()) first_why = w; + } + if (why) *why = !first_why.empty() ? first_why + : cs.empty() ? std::string("its prefix names no network of this model") + : std::string("no module of this model is named so"); + return out; +} + +/* ================================================================== composition */ +namespace { + +struct Part { + std::shared_ptr d; + int64_t from_lo = 0, n = 0, to_lo = 0; +}; + +} /* namespace */ + +int compose(const KeyMap& km, const std::vector& ads, int max_rank, + std::map* out, ComposeReport* rep, std::string* err) { + out->clear(); + *rep = ComposeReport{}; + std::map> by; + for (const Strength& s : ads) { + if (!s.file) return fail(err, RAD_E_INVAL, "adapter '" + s.name + "' is not open"); + for (const auto& [t, why] : s.file->skipped()) rep->skipped.push_back(s.name + ": " + t + ": " + why); + if (s.weight == 0.0) continue; + for (const FileModule& fm : s.file->modules()) { + std::string why; + const std::vector ts = km.resolve(fm.key, &why); + if (ts.empty()) { rep->unplaced.push_back(s.name + ": " + fm.key + ": " + why); continue; } + auto d = std::make_shared(); + std::string e; + if (module_delta(fm, s.weight, d.get(), &e) < 0) + return fail(err, RAD_E_FORMAT, s.name + ": " + e); + for (const Target& t : ts) { + Part p; + p.d = d; + p.from_lo = t.from_lo; + p.n = (t.from_hi > 0 ? t.from_hi : d->N) - t.from_lo; + p.to_lo = t.to_lo; + if (p.n <= 0 || t.from_lo + p.n > d->N) + return fail(err, RAD_E_SHAPE, fmt("%s: %s has %lld output rows; the base's alias " + "takes rows [%lld, %lld) of it for %s", + s.name.c_str(), fm.key.c_str(), (long long)d->N, + (long long)t.from_lo, (long long)(t.from_lo + p.n), + t.module.c_str())); + by[t.module].push_back(p); + } + } + } + + std::vector names; + for (auto& [k, v] : by) { names.push_back(k); (*out)[k]; } + std::vector errs(names.size()); + std::vector kept(names.size(), 1.0); + std::vector exact(names.size(), 1); + std::atomic next{ 0 }; + auto work = [&]() { + for (size_t i; (i = next.fetch_add(1)) < names.size();) { + const std::string& mod = names[i]; + const std::vector& ps = by.find(mod)->second; + Composite& c = out->find(mod)->second; + int64_t rows = km.rows(mod), K = km.cols(mod); + int64_t extent = 0; + for (const Part& p : ps) extent = std::max(extent, p.to_lo + p.n); + for (const KeyMap::Piece& pc : km.pieces(mod)) extent = std::max(extent, pc.lo + pc.n); + if (rows < 0) rows = extent; + if (K < 0) K = ps[0].d->K; + bool lr = true; + int64_t R = 0, bound = 0; + for (const Part& p : ps) { + if (p.d->K != K) { + errs[i] = fmt("%s: an adapter's delta has %lld input columns, the base's module " + "%lld", mod.c_str(), (long long)p.d->K, (long long)K); + break; + } + if (p.to_lo + p.n > rows) { + errs[i] = fmt("%s: an adapter's delta reaches row %lld of a module of %lld rows", + mod.c_str(), (long long)(p.to_lo + p.n), (long long)rows); + break; + } + lr = lr && p.d->low_rank; + R += p.d->low_rank ? p.d->r : 0; + bound += p.d->rank_bound; + } + if (!errs[i].empty()) continue; + c.rows = rows; c.K = K; + if (lr && R <= max_rank) { + /* Side by side: every delta its own block of ranks. */ + c.r = R; + c.B.assign((size_t)(rows * R), 0.0f); + c.A.assign((size_t)(R * K), 0.0f); + int64_t o = 0; + for (const Part& p : ps) { + const Delta& d = *p.d; + for (int64_t row = 0; row < p.n; ++row) + std::memcpy(&c.B[(size_t)((p.to_lo + row) * R + o)], + &d.B[(size_t)((p.from_lo + row) * d.r)], (size_t)d.r * 4); + std::memcpy(&c.A[(size_t)(o * K)], d.A.data(), (size_t)(d.r * K) * 4); + o += d.r; + } + continue; + } + /* The sum, as one operator over the module's rows, truncated to the slot's rank. */ + exact[i] = 0; + Delta sum; + sum.N = rows; sum.K = K; sum.rank_bound = bound; + /* One whole delta's energy is known; a sum's or a row slice's is what the sketch + * holds, exact when its rank is within the sketch's. */ + sum.energy = ps.size() == 1 && ps[0].from_lo == 0 && ps[0].n == ps[0].d->N + ? ps[0].d->energy : -1.0; + sum.apply = [&ps, rows](const float* X, int64_t l, float* Y) { + std::fill(Y, Y + rows * l, 0.0f); + for (const Part& p : ps) { + const Delta& d = *p.d; + std::vector y((size_t)(d.N * l)); + if (d.low_rank) { + std::vector t((size_t)(d.r * l)); + mm(d.A.data(), X, t.data(), d.r, d.K, l); + mm(d.B.data(), t.data(), y.data(), d.N, d.r, l); + } else { + d.apply(X, l, y.data()); + } + for (int64_t row = 0; row < p.n; ++row) + for (int64_t j = 0; j < l; ++j) + Y[(p.to_lo + row) * l + j] += y[(size_t)((p.from_lo + row) * l + j)]; + } + }; + sum.apply_t = [&ps, K](const float* Yin, int64_t l, float* X) { + std::fill(X, X + K * l, 0.0f); + std::vector x((size_t)(K * l)); + for (const Part& p : ps) { + const Delta& d = *p.d; + std::vector y((size_t)(d.N * l), 0.0f); + for (int64_t row = 0; row < p.n; ++row) + for (int64_t j = 0; j < l; ++j) + y[(size_t)((p.from_lo + row) * l + j)] = Yin[(p.to_lo + row) * l + j]; + if (d.low_rank) { + std::vector t((size_t)(d.r * l)); + mm_tn(d.B.data(), y.data(), t.data(), d.r, d.N, l); + mm_tn(d.A.data(), t.data(), x.data(), d.K, d.r, l); + } else { + d.apply_t(y.data(), l, x.data()); + } + for (int64_t k = 0; k < K * l; ++k) X[k] += x[(size_t)k]; + } + }; + truncate(sum, max_rank, &c.B, &c.A, &kept[i]); + c.r = (int64_t)(c.A.size() / (size_t)(K > 0 ? K : 1)); + /* Kept energy is exact when the sum is low-rank: ||B A||^2 of the parts side by side. */ + if (lr) { + std::vector Bc((size_t)(rows * R), 0.0f), Ac((size_t)(R * K), 0.0f); + int64_t o = 0; + for (const Part& p : ps) { + const Delta& d = *p.d; + for (int64_t row = 0; row < p.n; ++row) + std::memcpy(&Bc[(size_t)((p.to_lo + row) * R + o)], + &d.B[(size_t)((p.from_lo + row) * d.r)], (size_t)d.r * 4); + std::memcpy(&Ac[(size_t)(o * K)], d.A.data(), (size_t)(d.r * K) * 4); + o += d.r; + } + const double tot = lowrank_energy(Bc, Ac, rows, R, K); + const double got = lowrank_energy(c.B, c.A, rows, c.r, K); + kept[i] = tot > 0.0 ? std::min(1.0, got / tot) : 1.0; + } + } + }; + const unsigned hw = std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + std::vector th; + for (unsigned t = 1; t < hw && t < names.size(); ++t) th.emplace_back(work); + work(); + for (std::thread& t : th) t.join(); + for (size_t i = 0; i < names.size(); ++i) { + if (!errs[i].empty()) return fail(err, RAD_E_SHAPE, errs[i]); + ++rep->modules; + /* Held exactly: side by side, or an operator whose rank fits (LoKr, LoHa within R). */ + if (exact[i] || kept[i] >= 0.9999) ++rep->exact; + else if (kept[i] < rep->worst_kept) { rep->worst_kept = kept[i]; rep->worst_module = names[i]; } + } + return RAD_OK; +} + +std::map as_modules(std::map& c, const KeyMap& km) { + std::map m; + for (auto& [name, x] : c) { + if (x.r <= 0) continue; + const std::vector& pcs = km.pieces(name); + x.tPieces.assign(pcs.size(), StTensor{}); + x.tA = StTensor{}; + x.tA.name = name + ".A"; + x.tA.dtype = RAD_F32; + x.tA.dtype_str = "F32"; + x.tA.shape = { x.r, x.K }; + x.tA.bytes = x.A.size() * 4; + x.tA.data = (const uint8_t*)x.A.data(); + x.tB = StTensor{}; + x.tB.name = name + ".B"; + x.tB.dtype = RAD_F32; + x.tB.dtype_str = "F32"; + x.tB.shape = { x.rows, x.r }; + x.tB.bytes = x.B.size() * 4; + x.tB.data = (const uint8_t*)x.B.data(); + AdModule a; + a.name = name; + a.A = &x.tA; + a.B = &x.tB; + a.rank = x.r; + a.alpha = (double)x.r; + a.scale = 1.0f; + if (pcs.empty() || km.whole(name)) m[name] = a; + for (size_t i = 0; i < pcs.size(); ++i) { + StTensor& t = x.tPieces[i]; + t = x.tB; + t.name = pcs[i].name + ".B"; + t.shape = { pcs[i].n, x.r }; + t.bytes = (uint64_t)(pcs[i].n * x.r) * 4; + t.data = (const uint8_t*)(x.B.data() + pcs[i].lo * x.r); + AdModule p = a; + p.name = pcs[i].name; + p.B = &t; + m[p.name] = p; + } + } + return m; +} + +} /* namespace lora */ +} /* namespace rad */ diff --git a/core/lora/adapter.h b/core/lora/adapter.h new file mode 100644 index 00000000..b0faf017 --- /dev/null +++ b/core/lora/adapter.h @@ -0,0 +1,183 @@ +/* lora/adapter.h -- adapter files as image and video generators receive them, and the bytes of a + * slot holding one or several of them at chosen strengths. + * + * An adapter for a generator is one safetensors file, written by whichever tool trained or + * converted it, so the same delta arrives under several spellings: + * + * LoRA `.lora_down.weight` / `.lora_up.weight` (+ `.alpha`): kohya, ComfyUI; + * `.lora_A[.default].weight` / `.lora_B[...]` (+ `.alpha`): PEFT, diffusers, ai-toolkit; + * `.lora.down.weight` / `.lora.up.weight`; `.lora_linear_layer.down/up.weight`. + * delta = alpha / rank * up @ down; no alpha is a scale of 1. A convolution's down is + * [rank, cin, kh, kw] and its up [cout, rank, 1, 1], read as the flattened matrices. + * LoHa `.hada_w1_a/_w1_b/_w2_a/_w2_b` (+ alpha): delta = alpha / rank1 * + * (w1_a @ w1_b) * (w2_a @ w2_b), elementwise; exactly a rank1 * rank2 product of + * row-wise Kronecker factors. + * LoKr `.lokr_w1` or `_w1_a`/`_w1_b`, `.lokr_w2` or `_w2_a`/`_w2_b` (+ alpha): + * delta = scale * kron(w1, w2), scale alpha / rank of a decomposed factor, else 1. + * full `.diff`: the delta itself. + * + * Every module becomes a Delta, a linear map with its strength folded in. A slot holds, for each + * checkpoint module the adapters reach, the sum of the deltas that land there: the low-rank ones + * side by side while their ranks fit the slot's rank (exact), otherwise the sum's best rank-R + * approximation (a randomized SVD; the fraction of the delta's energy it keeps is reported). + * + * Where a module lands is the generator's own declaration (rad_lora_root, rad_lora_alias): a + * key's prefix names the network, its path the checkpoint module directly or through an alias, + * kohya's underscore form matched against the same names. */ +#pragma once +#include "lora.h" +#include "../format/safetensors.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace lora { + +/* One module of an adapter file, before it is mapped onto the base. */ +struct FileModule { + enum Kind { LORA, LOHA, LOKR, FULL }; + std::string key; /* the module as the file spells it, tensor suffix removed */ + Kind kind = LORA; + /* LORA: down, up. LOHA: w1_a, w1_b, w2_a, w2_b. LOKR: w1, w1_a, w1_b, w2, w2_a, w2_b. + * FULL: diff. */ + const StTensor* t[6] = {}; + const StTensor* alpha = nullptr; +}; + +class AdapterFile { +public: + /* Opens and groups the file's tensors by module. Refuses a file holding a form whose effect + * this engine cannot reproduce (DoRA's magnitude, OFT, Tucker cores), naming it. */ + int open(const std::string& path, std::string* err); + const std::string& path() const { return st_.path(); } + const std::vector& modules() const { return mods_; } + /* Tensors that change no linear (a trained bias, a norm's weight), with why; reported, not + * applied. */ + const std::vector>& skipped() const { return skipped_; } + /* The most common kind among the modules, for messages ("LoRA", "LoHa", ...). */ + const char* kind_name() const; + +private: + SafeTensorsFile st_; + std::vector mods_; + std::vector> skipped_; +}; + +/* A module's delta as a linear map [N, K] with its scale and strength folded in. Low-rank forms + * keep their factors (B [N, r] and A [r, K], row-major); the rest are applied as operators to + * blocks of `l` column vectors (X [K, l] -> Y [N, l], and the transpose), all f32. */ +struct Delta { + int64_t N = 0, K = 0; + int64_t rank_bound = 0; + double energy = -1.0; /* ||delta||_F^2, -1 when not known */ + bool low_rank = false; + int64_t r = 0; + std::vector B, A; + std::function apply, apply_t; +}; + +/* The delta of one module at strength `w`. RAD_E_SHAPE / RAD_E_DTYPE / RAD_E_FORMAT name the + * tensor. */ +int module_delta(const FileModule& m, double w, Delta* out, std::string* err); + +/* Rank-`r` factors of a delta given as an operator (randomized range finder, two power + * iterations): B [N, r], A [r, K]. `kept` is the fraction of the squared Frobenius norm kept, of + * Delta::energy when known and of what the sketch holds otherwise (1 when the delta's rank is at + * most r). */ +void truncate(const Delta& d, int64_t r, std::vector* B, std::vector* A, + double* kept); + +/* Where an adapter module lands in the base: rows [from_lo, from_hi) of its output (from_hi 0 = + * all) at rows from `to_lo` of the checkpoint module `module`. */ +struct Target { + std::string module; + int64_t from_lo = 0, from_hi = 0, to_lo = 0; +}; + +/* The generator's key names over one rank's Program and sites. */ +class KeyMap { +public: + KeyMap(const Program& prog, const std::vector& sites); + /* The targets of a file's module key; empty with `why` when it lands nowhere adaptable. */ + std::vector resolve(const std::string& key, std::string* why) const; + /* A checkpoint module's full rows and columns as the sites record them, or -1 when the + * declaration leaves them open. */ + int64_t rows(const std::string& module) const; + int64_t cols(const std::string& module) const; + /* The row pieces a module is cut into (RAD_MAP_ROWS; core/lora/lora.cpp names each + * `@+`), empty for a module the sites read whole; and whether a site + * also reads it whole. */ + struct Piece { std::string name; int64_t lo = 0, n = 0; }; + const std::vector& pieces(const std::string& module) const; + bool whole(const std::string& module) const { return whole_.count(module) != 0; } + +private: + struct Root { + std::string native; + std::vector spellings; + std::unordered_map kohya; /* underscored rel -> module */ + }; + struct Alias { + size_t root; + std::string from, to; + int64_t from_lo, from_hi, to_lo; + std::regex dotted, kohya; + }; + bool lookup(const Root& r, const std::string& rel, bool kohya, std::vector* out, + std::string* why) const; + + const Program* prog_; + std::vector roots_; + std::vector aliases_; + std::unordered_map> adaptable_; /* -> rows, cols */ + std::unordered_map known_; /* module -> why not adaptable */ + std::unordered_map> pieces_; + std::set whole_; +}; + +/* One adapter at a strength, for compose(). */ +struct Strength { + std::string name; + std::shared_ptr file; + double weight = 1.0; +}; + +/* What compose() did, for the log and the client. */ +struct ComposeReport { + int64_t modules = 0; /* checkpoint modules the slot carries */ + int64_t exact = 0; /* ... held exactly */ + double worst_kept = 1.0; /* lowest kept energy among the truncated */ + std::string worst_module; + std::vector unplaced; /* ": : why" */ + std::vector skipped; /* ": : why" */ +}; + +/* The factors of a composite, per checkpoint module: B [rows, r] and A [r, K], f32, held by the + * caller while the packer reads them. */ +struct Composite { + int64_t rows = 0, K = 0, r = 0; + std::vector B, A; + StTensor tA, tB; + std::vector tPieces; /* B's row ranges, one per piece of the module */ +}; + +/* The sum of the adapters' deltas per checkpoint module, at most `max_rank` each. Unplaced + * modules are reported, not refused, as UIs do. RAD_E_SHAPE when a module's shape disagrees with + * the base's. */ +int compose(const KeyMap& km, const std::vector& ads, int max_rank, + std::map* out, ComposeReport* rep, std::string* err); + +/* The packer's view of a composite (scale 1: the strengths and alphas are folded into B): a + * module under its own name where a site reads it whole, and each of its row pieces under the + * piece's name. */ +std::map as_modules(std::map& c, const KeyMap& km); + +} /* namespace lora */ +} /* namespace rad */ diff --git a/core/lora/config.h b/core/lora/config.h index fa8ad018..bf081209 100644 --- a/core/lora/config.h +++ b/core/lora/config.h @@ -1,9 +1,14 @@ -/* lora/config.h -- what runtime LoRA was started with (--lora, --max-loras, --max-lora-rank, - * --lora-target-modules). Read by declare (which sites and pools exist), by the adapter manager - * (what may be loaded into them) and by nothing else. +/* lora/config.h -- what runtime LoRA was started with (--lora, --lora-dir, --max-loras, + * --max-lora-rank, --lora-target-modules). Read by declare (which sites and pools exist), by the + * adapter manager (what may be loaded into them) and by nothing else. * - * Off unless asked for: with no adapter named and no --max-loras, `enabled()` is false, declare - * appends nothing, the program has no pool and no extra op, and no step carries an adapter slot. */ + * Off unless asked for: with no adapter named, no --lora-dir and no --max-loras, `enabled()` is + * false, declare appends nothing, the program has no pool and no extra op, and no step carries an + * adapter slot. + * + * A text model's slot holds one adapter; a generator's holds the combination one request asks for + * (several adapter files at their strengths, core/lora/adapter.h), so its slots are not tied to + * the number of adapters named. */ #pragma once #include #include @@ -12,20 +17,30 @@ namespace rad { struct LoraConfig { - /* NAME=PATH pairs to load at startup, in the order given. */ + /* NAME=PATH pairs to load at startup, in the order given: a PEFT directory, or for a + * generator one .safetensors file. */ std::vector> adapters; - /* Adapter slots resident at once. 0 with adapters named means "as many as were named". */ + /* A generator's adapter directory: a request may name any NAME.safetensors under it. */ + std::string dir; + /* Adapter slots resident at once. 0: as many as were named, and two with --lora-dir alone. */ int max_loras = 0; - /* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. */ - int max_rank = 16; + /* The rank every slot is sized for; an adapter of lower rank is zero-padded into it. 0: the + * default, kDefaultRank for a text model and kDefaultGenRank for a generator, whose adapter + * files run to rank 32 and are stacked. */ + int max_rank = 0; + static constexpr int kDefaultRank = 16, kDefaultGenRank = 64; + int rank(bool generator) const { + return max_rank > 0 ? max_rank : generator ? kDefaultGenRank : kDefaultRank; + } /* HF module leaf names (q_proj, gate_proj, in_proj_qkv, ...) the sites are built for, sorted * and unique. Empty: the union of the startup adapters' target_modules. */ std::vector targets; - bool enabled() const { return max_loras > 0 || !adapters.empty(); } + bool enabled() const { return max_loras > 0 || !adapters.empty() || !dir.empty(); } int slots() const { const int named = (int)adapters.size(); - return max_loras > 0 ? (max_loras > named ? max_loras : named) : named; + if (max_loras > 0) return max_loras; + return named > 0 ? named : (dir.empty() ? 0 : 2); } }; diff --git a/core/lora/declare.cpp b/core/lora/declare.cpp index 970e0f7f..ad04866b 100644 --- a/core/lora/declare.cpp +++ b/core/lora/declare.cpp @@ -3,6 +3,7 @@ #include "build/rad_build.h" #include "rad_internal.h" +#include #include #include #include @@ -73,23 +74,36 @@ rad_buf decl_persist(Builder& b, const std::string& name, uint32_t dtype, uint32 } /* namespace */ +/* A generator pass's adapter ops run over at most this many rows at a time: large enough that the + * kernels' row tiles are all busy, small enough that `t` for the largest rank is a few MiB. */ +constexpr int64_t kGenChunk = 8192; + int lora_declare(Builder& b, const LoraDeclare& d) { if (!d.cfg || !d.cfg->enabled()) return RAD_OK; Program& P = b.program(); /* Adapters are chosen per request and applied on the token steps of a model that writes - * logits; a generator's passes and an embedding model's requests carry no adapter. */ - if (P.is_pass_driven() || P.pooled_buf != RAD_NULL_HANDLE || - P.logits_buf == RAD_NULL_HANDLE) { - RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, and this one %s", - P.is_pass_driven() ? "is an image, audio or video generator" + * logits, or on every pass of a generator that names its adapter keys (rad_lora_root); an + * embedding model's requests carry no adapter. */ + const bool gen = P.is_pass_driven(); + if (gen ? P.lora_roots.empty() + : (P.pooled_buf != RAD_NULL_HANDLE || P.logits_buf == RAD_NULL_HANDLE)) { + RAD_ERR("lora: runtime LoRA adapters serve a model that generates text, or a generator " + "that declares how adapter files name its modules, and this one %s", + gen ? "is a generator that declares no adapter " + "key names (rad_lora_root)" : P.pooled_buf != RAD_NULL_HANDLE ? "makes embeddings" : "declares no logits"); return RAD_E_UNSUPPORTED; } + if (!gen && d.targets.count("*")) { + RAD_ERR("lora: an adapter without adapter_config.json names no target modules, and a " + "text model has no default set; give them with --lora-target-modules"); + return RAD_E_UNSUPPORTED; + } const int S = d.cfg->slots(); - const int max_rank = d.cfg->max_rank; + const int max_rank = d.cfg->rank(gen); const int64_t max_tok = P.ctx.max_tok; - if (S <= 0 || max_rank <= 0 || max_tok <= 0) { + if (S <= 0 || max_rank <= 0 || (!gen && max_tok <= 0)) { RAD_ERR("lora: %d slots of rank %d over steps of %lld tokens is not a configuration", S, max_rank, (long long)max_tok); return RAD_E_INVAL; @@ -150,6 +164,26 @@ int lora_declare(Builder& b, const LoraDeclare& d) { } } + /* ---- a token step's rows are its tokens; a generator pass's are each GEMM's own, issued in + * chunks of at most kGenChunk rows (Ctx::issue_lora), so `t` holds one chunk. */ + int64_t rows = max_tok; + if (gen) { + rows = 0; + for (const lora::Site& x : sites) + if (x.gemm > 0 && x.gemm < P.ops.size()) rows = std::max(rows, P.ops[x.gemm].range_hi); + rows = std::min(rows, kGenChunk); + } + + /* On the real declare, what the adapters cost: the pools are persistent buffers, so the + * arena plan (and with it what is left for weights and the KV cache) holds them. */ + if (d.sites_out) { + int64_t slot_bytes = 0; + for (const LoraPool& p : P.lora_pools) slot_bytes += 2 * p.R * p.K + 2 * p.N * p.R + 4 * p.N; + RAD_INFO("lora: %zu weights carry adapters, %d slots of rank %d, %s a slot on this rank, " + "%s in all (--max-loras, --max-lora-rank)", P.lora_pools.size(), S, max_rank, + humanb(slot_bytes).c_str(), humanb(slot_bytes * S).c_str()); + } + /* ---- t = A.x, one f32 plane per capacity R and lane. Persistent, not transient: the ops that * use it run at the GEMM's position, but the buffer plan would place a transient at the * appended ops' own position, the end of the program, and share its bytes with buffers live @@ -160,7 +194,7 @@ int lora_declare(Builder& b, const LoraDeclare& d) { if (t_by_r.count(x.R)) continue; LoraScratch sc; sc.R = x.R; - const int64_t sh[2] = { max_tok, x.R }; + const int64_t sh[2] = { rows, x.R }; for (int l = 0; l < 2; ++l) { sc.lane[l] = decl_persist(b, fmt("lora.t.r%lld.lane%d", (long long)x.R, l), RAD_F32, 2, sh); if (!sc.lane[l]) return RAD_E_STATE; @@ -169,9 +203,21 @@ int lora_declare(Builder& b, const LoraDeclare& d) { P.lora_t.push_back(sc); } + /* ---- a generator pass's slot operand: elements [s rows, (s + 1) rows) of an [S rows] i32 + * buffer, every one s (filled when the engine starts adapters) */ + P.lora_rows = 0; + P.lora_rows_n = 0; + if (gen && rows > 0) { + const int64_t sh[1] = { S * rows }; + P.lora_rows = decl_persist(b, "lora.slot_rows", RAD_I32, 1, sh); + if (!P.lora_rows) return RAD_E_STATE; + P.lora_rows_n = rows; + } + /* ---- the two ops behind each targeted GEMM */ P.lora_sites.clear(); int n_refused = 0; + std::vector dropped(sites.size(), 0); for (lora::Site& x : sites) { const uint32_t gh = x.gemm; if (gh == 0 || gh >= P.ops.size()) return RAD_E_STATE; @@ -186,7 +232,15 @@ int lora_declare(Builder& b, const LoraDeclare& d) { const int oa = opd_index(g, "a"), oas = opd_index(g, "a_scale"), oy = opd_index(g, "y"); const std::vector reads = b.op_read_set(gh), writes = b.op_write_set(gh); + /* A text model's targeted GEMM that cannot carry the ops is refused; a generator's, whose + * every plain GEMM is a candidate, stays the base and its modules are reported unplaced. */ auto refuse = [&](const std::string& why) { + if (gen) { + RAD_WARN("lora: op %u '%s' over '%s' carries no adapter: %s", gh, gop.c_str(), + x.weight.c_str(), why.c_str()); + dropped[(size_t)(&x - sites.data())] = 1; + return; + } RAD_ERR("lora: op %u '%s' over '%s': %s", gh, gop.c_str(), x.weight.c_str(), why.c_str()); ++n_refused; }; @@ -223,9 +277,14 @@ int lora_declare(Builder& b, const LoraDeclare& d) { sp[n_sp++] = RAD_STR("dtype", rad_dtype_name(a_dt)); const rad_op hs = b.decl_op("lora_shrink", sp, n_sp, nullptr, 0); - const RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R), - RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) }; - const rad_op he = b.decl_op("lora_expand", ep, 5, nullptr, 0); + RadParam ep[5] = { RAD_RANGE("M", lo, hi), RAD_INT("N", x.N_r), RAD_INT("R", x.R), + RAD_INT("S", S), RAD_STR("dtype", rad_dtype_name(y_dt)) }; + /* A generator's passes are many rows of one adapter: its expand runs on the WMMA + * (lora_expand_mm) where a library has it. A token step keeps the exact row, whose bytes + * do not depend on the batch. */ + const char* expand_op = gen && b.op_declared("lora_expand_mm") ? "lora_expand_mm" + : "lora_expand"; + const rad_op he = b.decl_op(expand_op, ep, 5, nullptr, 0); if (!hs || !he) { refuse(fmt("no kernel resolves lora_%s for an activation of %s and an output of %s", !hs ? "shrink" : "expand", rad_dtype_name(a_dt), rad_dtype_name(y_dt))); @@ -233,6 +292,28 @@ int lora_declare(Builder& b, const LoraDeclare& d) { } LoraIssueSite is; + /* A generator's slot packs its ranks from 0 (lora::pack_modules, compact): pairs that read + * the first half and quarter of R, so a rank-16 adapter in a slot sized 64 a module costs + * a quarter. Multiples of 16, the WMMA's step. */ + if (gen) { + int64_t prev = x.R; + for (int v = 0; v < 2; ++v) { + const int64_t rv = ((x.R >> (v + 1)) + 15) / 16 * 16; + if (rv < 16 || rv >= prev) break; + RadParam vs[6]; + for (int i = 0; i < n_sp; ++i) vs[i] = sp[i]; + vs[2] = RAD_INT("R", rv); + ep[2] = RAD_INT("R", rv); + const rad_op vs_op = b.decl_op("lora_shrink", vs, n_sp, nullptr, 0); + const rad_op ve_op = b.decl_op(expand_op, ep, 5, nullptr, 0); + if (!vs_op || !ve_op) break; + P.ops[vs_op].anchor = (int32_t)gh; + P.ops[ve_op].anchor = (int32_t)gh; + is.shrink_v[v] = vs_op; is.expand_v[v] = ve_op; is.R_v[v] = rv; + is.n_v = (int8_t)(v + 1); + prev = rv; + } + } is.gemm = gh; is.shrink = hs; is.expand = he; is.opd_a = (int8_t)oa; is.opd_a_scale = (int8_t)(coded ? oas : -1); @@ -248,7 +329,13 @@ int lora_declare(Builder& b, const LoraDeclare& d) { } if (n_refused) return RAD_E_UNSUPPORTED; - if (d.sites_out) *d.sites_out = std::move(sites); + if (gen) P.lora_rused.assign(P.lora_pools.size() * (size_t)S, 0); + if (d.sites_out) { + std::vector kept; + for (size_t i = 0; i < sites.size(); ++i) + if (!dropped[i]) kept.push_back(std::move(sites[i])); + *d.sites_out = std::move(kept); + } return RAD_OK; } diff --git a/core/lora/lora.cpp b/core/lora/lora.cpp index 777d625c..640f9a32 100644 --- a/core/lora/lora.cpp +++ b/core/lora/lora.cpp @@ -88,8 +88,13 @@ bool excluded_source(const std::string& src) { return false; } +/* A generator that declared adapter key names (rad_lora_root): its scope is those roots, every + * matrix under one of them, and none of the token model's rules below apply. */ +bool gen_scope(const Program& prog) { return !prog.lora_roots.empty(); } + const char* excluded_weight(const Program& prog, const WeightInfo& w) { if (w.decl.access == RAD_ACCESS_VOCAB) return "a vocabulary weight (embedding / lm_head)"; + if (gen_scope(prog)) return w.decl.rank == 2 ? nullptr : "not a matrix"; if (w.decl.access == RAD_ACCESS_PER_REQUEST) return "an encoder tower weight (per-request access)"; if (prog.meta.n_layers > 0 && w.decl.group.layer >= prog.meta.n_layers) return "a drafter / MTP layer (layer group at or above meta.n_layers)"; @@ -121,8 +126,23 @@ void scan_maps(const Program& prog, const std::string& declared, struct MapIndex { std::unordered_map> by; explicit MapIndex(const Program& prog) { - for (const RadNameMap& m : prog.name_map) - if (m.declared) by[m.declared].push_back(&m); + /* An entry repeated whole (a plugin's encoding probe maps the weight it then declares) is + * one entry. */ + auto same = [](const RadNameMap& a, const RadNameMap& b) { + if (a.mode != b.mode || a.n_src != b.n_src || a.concat_dim != b.concat_dim) return false; + for (int k = 0; k < a.n_src && k < 8; ++k) + if (std::strcmp(a.src[k] ? a.src[k] : "", b.src[k] ? b.src[k] : "") != 0 || + a.src_index[k] != b.src_index[k] || a.src_rows[k] != b.src_rows[k]) + return false; + return true; + }; + for (const RadNameMap& m : prog.name_map) { + if (!m.declared) continue; + std::vector& v = by[m.declared]; + bool dup = false; + for (const RadNameMap* x : v) dup = dup || same(*x, m); + if (!dup) v.push_back(&m); + } } const std::vector* find(const std::string& d) const { auto it = by.find(d); @@ -130,19 +150,27 @@ struct MapIndex { } }; +/* Is checkpoint tensor `src` an adapter target? A token model: its leaf is in the target list and + * it is in the trunk. A generator: it is under a declared root, and its leaf is in the list or the + * list is "*". */ +bool source_targeted(const Program& prog, const TargetSet& targets, const std::string& src) { + std::string leaf; + if (module_of(src, &leaf).empty()) return false; + if (!gen_scope(prog)) return targets.count(leaf) && !excluded_source(src); + if (!targets.count("*") && !targets.count(leaf)) return false; + for (const LoraRoot& r : prog.lora_roots) + if (src.compare(0, r.native.size(), r.native) == 0) return true; + return false; +} + /* weight_targeted(), over the maps already found. */ bool targeted_core(const Program& prog, const WeightInfo& w, const std::vector& maps, const TargetSet& targets) { if (targets.empty() || maps.empty()) return false; if (excluded_weight(prog, w)) return false; for (const RadNameMap* m : maps) - for (int k = 0; k < m->n_src && k < 8; ++k) { - if (!m->src[k]) continue; - const std::string src = m->src[k]; - std::string leaf; - if (module_of(src, &leaf).empty()) continue; - if (targets.count(leaf) && !excluded_source(src)) return true; - } + for (int k = 0; k < m->n_src && k < 8; ++k) + if (m->src[k] && source_targeted(prog, targets, m->src[k])) return true; return false; } @@ -464,40 +492,46 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets, if (!maps || maps->empty()) return fail(err, RAD_E_NOTFOUND, fmt("weight '%s' has no name-map entry", W.name.c_str())); std::vector srcs; + /* A row piece of a checkpoint tensor (RAD_MAP_ROWS) is a source of its own, named + * `@+`: the adapter's B rows it takes are that range of the + * module's. */ + std::vector piece; const bool alternatives = maps->size() == 1 && (*maps)[0]->mode == RAD_MAP_COPY && (*maps)[0]->n_src > 1; for (const RadNameMap* m : *maps) for (int k = 0; k < m->n_src && k < 8; ++k) { - if (m->src_index[k] >= 0) + const bool rows = m->mode == RAD_MAP_ROWS; + if (!rows && m->src_index[k] >= 0) return fail(err, RAD_E_UNSUPPORTED, fmt("weight '%s' is slice %d of the stacked checkpoint tensor %s; a " "LoRA on a stacked (expert) tensor is not supported", W.name.c_str(), m->src_index[k], m->src[k])); srcs.push_back(m->src[k] ? m->src[k] : ""); + piece.push_back(rows ? fmt("@%d+%lld", m->src_index[k], (long long)m->src_rows[k]) : ""); } if (alternatives) { /* COPY with alternatives: the first one the container holds is the weight, and which one * that is is not recorded. Usable only when exactly one alternative is targeted. */ std::vector hit; - for (const std::string& x : srcs) { - std::string leaf; - if (!module_of(x, &leaf).empty() && targets.count(leaf) && !excluded_source(x)) - hit.push_back(x); - } + for (const std::string& x : srcs) + if (source_targeted(prog, targets, x)) hit.push_back(x); if (hit.size() != 1) return fail(err, RAD_E_UNSUPPORTED, fmt("weight '%s' is one of %zu alternative checkpoint tensors and %zu of " "them are targeted; which one the container holds is not recorded", W.name.c_str(), srcs.size(), hit.size())); srcs = hit; + piece.assign(srcs.size(), ""); } int slot = 0; - for (const std::string& x : srcs) { + for (size_t si = 0; si < srcs.size(); ++si) { + const std::string& x = srcs[si]; SiteSource ss; std::string leaf; ss.module = module_of(x, &leaf); if (ss.module.empty()) ss.module = x; - ss.targeted = !leaf.empty() && targets.count(leaf) && !excluded_source(x); + ss.module += piece[si]; + ss.targeted = source_targeted(prog, targets, x); if (ss.targeted) ss.slot = slot++; s.sources.push_back(ss); } @@ -544,6 +578,8 @@ int make_site(const Program& prog, const MapIndex& mi, const TargetSet& targets, /* ================================================================== predicates */ bool weight_targeted(const Program& prog, rad_weight w, const TargetSet& targets) { if (targets.empty() || w == 0 || w >= prog.weights.size()) return false; + /* A generator's fused GEMMs are kept: its scope is the plain GEMMs (build_sites). */ + if (gen_scope(prog)) return false; const WeightInfo& wi = prog.weights[w]; if (excluded_weight(prog, wi)) return false; std::vector maps; @@ -598,7 +634,7 @@ bool op_is_site(const Program& prog, const OpInfo& op, rad_weight* b_out, std::s int find_unsupported_uses(const Program& prog, const TargetSet& targets, std::vector* out) { if (out) out->clear(); - if (targets.empty()) return 0; + if (targets.empty() || gen_scope(prog)) return 0; const MapIndex mi(prog); int n = 0; for (size_t i = 1; i < prog.ops.size(); ++i) { @@ -642,14 +678,47 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank, if (max_rank <= 0) return fail(err, RAD_E_INVAL, fmt("max LoRA rank %d", max_rank)); if (targets.empty()) return RAD_OK; const MapIndex mi(prog); + /* A generator's weight carries an adapter only when every op reading it is a site over it; one + * read elsewhere (a fused GEMM, a non-GEMM op) stays the base everywhere. */ + std::set other_reader; + if (gen_scope(prog)) + for (size_t i = 1; i < prog.ops.size(); ++i) { + const OpInfo& op = prog.ops[i]; + if (op.weights.empty() || !op_live(op)) continue; + rad_weight b = 0; + const bool site = op_is_site(prog, op, &b, nullptr); + for (rad_weight h : op.weights) + if (h && h < prog.weights.size() && + (!site || !b || prog.weights[b].source != prog.weights[h].source)) + other_reader.insert(prog.weights[h].source); + } std::map pool_of; std::vector first_site; for (size_t i = 1; i < prog.ops.size(); ++i) { rad_weight b = 0; if (!op_live(prog.ops[i]) || !op_is_site(prog, prog.ops[i], &b, nullptr)) continue; if (!targeted_idx(prog, mi, b, targets)) continue; + if (other_reader.count(prog.weights[b].source)) continue; + if (gen_scope(prog)) { + /* Checkpoint tensors copied, joined, transposed or cut into row pieces carry a + * generator's adapter; a folded or derived one (weight norm, EMA) stays the base. */ + bool whole = true; + if (const auto* maps = mi.find(prog.weights[b].source)) + for (const RadNameMap* m : *maps) + whole = whole && (m->mode == RAD_MAP_COPY || m->mode == RAD_MAP_CONCAT || + m->mode == RAD_MAP_TRANSPOSE || m->mode == RAD_MAP_ROWS); + if (!whole) continue; + } Site s; const int st = make_site(prog, mi, targets, max_rank, (uint32_t)i, b, &s, err); + if (st < 0 && gen_scope(prog)) { + /* A generator's every plain GEMM is a candidate; one whose geometry cannot be told + * stays the base, as a fused one does. */ + RAD_WARN("lora: '%s' carries no adapter: %s", prog.weights[b].name.c_str(), + err ? err->c_str() : ""); + if (err) err->clear(); + continue; + } if (st < 0) return st; auto it = pool_of.find(b); if (it == pool_of.end()) { @@ -729,15 +798,6 @@ std::string explain_module(const Program& prog, const TargetSet& targets, const /* ================================================================== the adapter */ namespace { -struct AdModule { - std::string name; - const StTensor* A = nullptr; - const StTensor* B = nullptr; - int64_t rank = 0; - double alpha = 0.0; - float scale = 0.0f; -}; - struct Slot { int32_t pool; int32_t source; }; } /* namespace */ @@ -937,6 +997,12 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max info->leaves.insert(d == std::string::npos ? am.name : am.name.substr(d + 1)); } + return pack_modules(sites, max_rank, mods, info, packed, err); +} + +int pack_modules(const std::vector& sites, int max_rank, + const std::map& mods, AdapterInfo* info, + std::vector* packed, std::string* err, bool compact) { /* ---- the sites, by pool: the representative of each pool and where its modules sit. */ int32_t n_pools = 0; for (const Site& s : sites) { @@ -955,7 +1021,9 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max } std::unordered_map> where; for (int32_t p = 0; p < n_pools; ++p) { - if (!rep[(size_t)p]) return fail(err, RAD_E_INVAL, fmt("pool %d has no site", p)); + /* A pool whose only GEMM could carry no adapter ops (lora_declare drops it) holds + * nothing. */ + if (!rep[(size_t)p]) continue; const Site& s = *rep[(size_t)p]; for (size_t i = 0; i < s.sources.size(); ++i) if (s.sources[i].targeted) where[s.sources[i].module].push_back({ p, (int32_t)i }); @@ -1001,9 +1069,10 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max /* ---- pack, pool by pool */ packed->resize((size_t)n_pools); for (int32_t p = 0; p < n_pools; ++p) { - const Site& s = *rep[(size_t)p]; PackedSite& out = (*packed)[(size_t)p]; out.pool = p; + if (!rep[(size_t)p]) continue; + const Site& s = *rep[(size_t)p]; out.a.assign((size_t)(s.R * s.K_r), 0); out.b.assign((size_t)(s.N_r * s.R), 0); out.scale.assign((size_t)s.N_r, 0.0f); @@ -1135,12 +1204,19 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max } /* Pack. A: rows t_off.. of the module's block; B: rows y_col.., columns t_off..; scale on - * the module's rows. */ + * the module's rows. Compact: the modules' ranks one after another from 0. */ + std::vector off(n, 0); + int64_t used = 0; + for (size_t i = 0; i < n; ++i) { + off[i] = compact ? used : (int64_t)s.sources[i].slot * max_rank; + if (am[i]) used += am[i]->rank; + } + out.r_used = compact ? used : s.R; for (size_t i = 0; i < n; ++i) { if (!am[i]) continue; const StTensor& A = *am[i]->A; const int64_t r = am[i]->rank, kc = A.shape[1]; - const int64_t t0 = (int64_t)s.sources[i].slot * max_rank; + const int64_t t0 = off[i]; for (int64_t j = 0; j < r; ++j) for (int64_t k = 0; k < s.K_r; ++k) out.a[(size_t)((t0 + j) * s.K_r + k)] = elem_bf16(A, j * kc + s.k_lo + k); @@ -1156,7 +1232,7 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max if (yr < 0 || yr >= s.N_r) return fail(err, RAD_E_STATE, fmt("weight '%s': a part lands outside y", s.weight.c_str())); for (int64_t j = 0; j < r; ++j) - out.b[(size_t)(yr * s.R + sp.t_off + j)] = elem_bf16(B, row * r + j); + out.b[(size_t)(yr * s.R + off[i] + j)] = elem_bf16(B, row * r + j); out.scale[(size_t)yr] = am[i]->scale; } } diff --git a/core/lora/lora.h b/core/lora/lora.h index 9538343c..11156ce2 100644 --- a/core/lora/lora.h +++ b/core/lora/lora.h @@ -19,12 +19,14 @@ #include "../rad_core.h" #include +#include #include #include #include #include namespace rad { +struct StTensor; namespace lora { /* HF module leaf names, ordered so every caller builds the same set. Empty targets nothing. */ @@ -82,6 +84,8 @@ struct PackedSite { std::vector scale; /* [N_r]: the module's alpha/r (alpha/sqrt(r) rsLoRA) on its rows */ int32_t pool = -1; bool empty = true; /* no module of this adapter lands in this pool */ + /* Packed compact (pack_modules): the ranks the modules take, from j = 0; R otherwise. */ + int64_t r_used = 0; }; /* What an adapter is, independent of the name it is served under. */ @@ -157,6 +161,26 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank, int load_adapter(const std::string& dir, const std::vector& sites, int max_rank, AdapterInfo* info, std::vector* packed, std::string* err); +/* One module's factors as the packer reads them: lora_A [rank, K] and lora_B [rows, rank] in any + * dtype a safetensors tensor carries (BF16, F16, F32), and the scale its rows run at. `name` is the + * module path the base's name map spells (without ".weight"). */ +struct AdModule { + std::string name; + const StTensor* A = nullptr; + const StTensor* B = nullptr; + int64_t rank = 0; + double alpha = 0.0; + float scale = 0.0f; +}; + +/* load_adapter's second half, for any source of factors: `mods` (by name) packed into one + * PackedSite per pool of `sites`, in the slot layout of the pool's sites. Fills info->modules and + * info->absent. `compact`: the modules of a pool take consecutive ranks from j = 0, in source + * order, instead of a block of max_rank each, so a pass may run only the first r_used of them. */ +int pack_modules(const std::vector& sites, int max_rank, + const std::map& mods, AdapterInfo* info, + std::vector* packed, std::string* err, bool compact = false); + /* After load_adapter on every rank: refuse a module that no rank placed. With `prog`/`targets` * (any one rank's) the message says why it is not a site (base lacks it, scope, target list, op). */ int check_placed(const std::vector& per_rank, std::string* err, diff --git a/core/lora/slots.cpp b/core/lora/slots.cpp index 18d10014..f14c94f6 100644 --- a/core/lora/slots.cpp +++ b/core/lora/slots.cpp @@ -60,6 +60,7 @@ uint64_t SlotTable::publish(int slot, const std::string& name, const std::string s.uid = next_uid_++; s.used = true; s.draining = false; + s.last_use = ++uses_; return s.uid; } @@ -69,10 +70,11 @@ int SlotTable::acquire(const std::string& name, int32_t* slot, uint64_t* uid, { std::lock_guard lk(mu_); for (size_t i = 0; i < slots_.size() && !u; ++i) { - const Slot& x = slots_[i]; + Slot& x = slots_[i]; if (x.uid == 0 || x.draining || x.name != name) continue; u = x.uid; *slot = (int32_t)i; + x.last_use = ++uses_; ++refs_[u]; } } @@ -125,6 +127,19 @@ int SlotTable::unload(const std::string& name, int* in_flight, std::string* err) return RAD_E_NOTFOUND; } +int SlotTable::evict_idle(std::string* evicted) { + std::lock_guard lk(mu_); + Slot* best = nullptr; + for (Slot& x : slots_) { + if (x.uid == 0 || x.draining || refs_.count(x.uid)) continue; + if (!best || x.last_use < best->last_use) best = &x; + } + if (!best) return RAD_E_FULL; + if (evicted) *evicted = best->name; + free_slot(*best, " to make room"); + return RAD_OK; +} + std::vector SlotTable::names() const { std::lock_guard lk(mu_); std::vector out; diff --git a/core/lora/slots.h b/core/lora/slots.h index f5e63cbc..a3381428 100644 --- a/core/lora/slots.h +++ b/core/lora/slots.h @@ -61,6 +61,10 @@ public: * RAD_E_NOTFOUND: nothing of that name is loaded. */ int unload(const std::string& name, int* in_flight, std::string* err); + /* Free the least recently acquired loaded slot that no request holds, for a load that found + * none free; its name in *evicted. RAD_E_FULL when every loaded slot is held. */ + int evict_idle(std::string* evicted); + /* The loaded adapters a request may name, in slot order: not the draining ones. */ std::vector names() const; /* Requests holding the adapter `name` (draining or not), 0 for none or no such adapter. */ @@ -73,6 +77,7 @@ private: bool used = false; /* ever held an adapter, so `freed_at` means something */ bool draining = false; uint64_t freed_at = 0; /* `epoch` when it was last freed */ + uint64_t last_use = 0; /* acquire counter at its last acquire or publish */ }; void free_slot(Slot& s, const char* how); /* under mu_ */ void release(uint64_t uid); /* a hold's deleter */ @@ -82,6 +87,7 @@ private: std::vector slots_; std::map refs_; /* uid -> holds */ uint64_t next_uid_ = 1; + uint64_t uses_ = 0; const std::atomic* epoch_ = nullptr; }; diff --git a/core/rad_core.h b/core/rad_core.h index c552cf73..6185bf76 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -310,6 +310,11 @@ struct LoraIssueSite { int32_t pool = -1; /* index into Program::lora_pools */ int32_t t = -1; /* index into Program::lora_t */ int64_t R = 0, K = 0, N = 0; + /* A generator's narrower pairs: the same pools read to rank R_v[i] < R, the pass taking the + * narrowest that holds its slot's ranks (Program::lora_rused). */ + uint32_t shrink_v[2] = { 0, 0 }, expand_v[2] = { 0, 0 }; + int64_t R_v[2] = { 0, 0 }; + int8_t n_v = 0; }; /* One targeted weight's adapter slots: A [S, R, K], B [S, N, R] bf16 and the per-column scale * [S, N] f32, persistent buffers, so the arena plan (and with it the KV budget) holds them. */ @@ -323,6 +328,16 @@ struct LoraScratch { int64_t R = 0; rad_buf lane[2] = { 0, 0 }; }; +/* A generator's adapter key names (rad_lora_root, rad_lora_alias in rad_builder.h). */ +struct LoraRoot { + std::string native; /* checkpoint prefix of the network's tensors */ + std::vector spellings; /* adapter-side prefixes; "" is a bare key */ +}; +struct LoraAlias { + std::string root; /* LoraRoot::native it is relative to */ + std::string from, to; /* module paths, '#' a decimal index */ + int64_t from_lo = 0, from_hi = 0, to_lo = 0; +}; /* Everything declare produced. The core owns it; the plugin only ever sees handles into it. */ class Program { @@ -349,6 +364,17 @@ public: std::vector lora_sites; std::vector lora_pools; std::vector lora_t; + /* A generator's adapter key names: declared by the plugin whether or not adapters are on. A + * generator that declares no root carries no adapters. */ + std::vector lora_roots; + std::vector lora_aliases; + /* A generator's pass runs with one adapter in every row: `lora_rows` is [S * lora_rows_n] + * i32, run s all s, so a pass's slot operand is run s of it. 0 on a token-step program. */ + rad_buf lora_rows = 0; + int64_t lora_rows_n = 0; + /* A generator's slots pack each combination's ranks from j = 0: the ranks pool p takes in + * slot s at [p * S + s], 0 for a pool the combination does not reach (no adapter op runs). */ + std::vector lora_rused; /* The declared draft head (rad_declare_drafter). `kind == RAD_DRAFT_NONE` when none, the * normal case: the engine then speculates with the scheduler's prompt-lookup drafter or not at @@ -716,7 +742,7 @@ struct Config { * slower. `on` forces P2P and stops startup naming the refused pairs instead of falling * back. */ int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */ - int64_t max_tok = 8192; /* --max-num-batched-tokens */ + int64_t max_tok = 2048; /* --max-num-batched-tokens */ /* --busy-prefill-chunk: how much of a step a prefill chunk may take when other work is * pending in it (decode rows, another prefill, a request waiting for admission). -1 = auto: * leave those their rows plus a share for admission, but keep at least the smallest pass the diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 66daed98..95ea0caf 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -201,6 +201,9 @@ public: /* Call once on the rank thread before its first run_step: the backend's current device is * thread-local, and init may have run on another thread. */ int bind_thread(); + /* The runtime LoRA slot every row of the generator passes that follow runs with, -1 for none + * (Ctx::issue_lora). Set by the pass loop before it releases the rank for a pass. */ + void set_gen_lora_slot(int32_t s) { gen_lora_slot_ = s; } /* ---------------------------------------------------------- run-phase queries */ const RadBatch* batch() const { return batch_; } @@ -350,6 +353,7 @@ private: int bind_weights(); int bind_ops(); int issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n); + int32_t gen_lora_slot_ = -1; int bind_routing(); int bind_profiling(); int check_domain(rad_op h, int domain) const; diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 05f33e02..086dc7b7 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -424,17 +424,21 @@ int Ctx::issue(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { * A row-parallel gemm's y is this rank's partial sum and the plugin reduces it after this returns, * so the delta rides the same reduction (B.A.x is linear in x's shards). Nothing is issued on a * step with no adapter row (RadBatch::lora_slot null), which is then the pass an engine without - * adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder or generator - * pass never reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h), - * so reaching one here is refused rather than run without its delta. */ + * adapters runs, nor on a draft pass, whose proposals the trunk verifies. An encoder pass never + * reaches a site: such a weight is outside the targets' scope rule (core/lora/lora.h), so reaching + * one here is refused rather than run without its delta. + * + * A generator's pass runs one adapter in all its rows (gen_lora_slot_, -1 for none), whatever the + * rows are -- a stream's tokens, a text encoder's taps, a video's patches -- so its slot operand + * is row `slot` of Program::lora_rows, the gemm's first n rows of it. */ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { if (!batch_) return RAD_OK; - if (batch_->enc != 0 || batch_->gen != 0) + const bool gen = batch_->gen != 0; + if (batch_->enc != 0) return abort_step_msg(h, RAD_E_UNSUPPORTED, - "a LoRA-targeted gemm was issued by an encoder or generator pass, " - "which runtime LoRA does not reach; leave its module out of " - "--lora-target-modules"); - if (!batch_->lora_slot || batch_->draft_pass != 0) return RAD_OK; + "a LoRA-targeted gemm was issued by an encoder pass, which runtime " + "LoRA does not reach; leave its module out of --lora-target-modules"); + if (gen ? gen_lora_slot_ < 0 : (!batch_->lora_slot || batch_->draft_pass != 0)) return RAD_OK; const OpPlan& p = plans_[h]; const LoraIssueSite& s = program_->lora_sites[(size_t)p.lora_site]; if (n == RAD_N_BATCH) n = batch_->n_tok; @@ -467,13 +471,15 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { rad_dtype_name(xd.dtype), rad_dtype_name(yd.dtype))); const int64_t yw = yd.rank >= 2 ? yd.shape[yd.rank - 1] : 0; if (yw <= 0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output has no width"); - if (ya.cols == 0 && ya.offset % yw != 0) + /* A token step reads each row's slot at the row the gemm wrote, so the views must name token + * rows; a generator pass's one slot holds for any rows. */ + if (!gen && ya.cols == 0 && ya.offset % yw != 0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's output view starts inside a " "row, so its token rows cannot be told"); - const int64_t r0 = ya.offset / yw; + const int64_t r0 = gen ? 0 : ya.offset / yw; /* The activation must start at the same row: shrink reads x's row m and expand writes y's row * m with one slot. */ - { + if (!gen) { const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0; if (xw <= 0 || (xa.cols == 0 && xa.offset % xw != 0) || xa.offset / xw != r0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: the gemm's activation and output " @@ -483,26 +489,72 @@ int Ctx::issue_lora(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { (int)op_domain_[s.expand].load(std::memory_order_relaxed) != dom) return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: the adapter ops were placed in " "another domain than the gemm they follow"); - if (r0 < 0 || r0 + n > batch_->n_tok) + if (!gen && (r0 < 0 || r0 + n > batch_->n_tok)) return abort_step_msg(h, RAD_E_STATE, fmt("LoRA site: the gemm wrote rows [%lld, %lld) of a %lld-token step", (long long)r0, (long long)(r0 + n), (long long)batch_->n_tok)); + if (gen && (!program_->lora_rows || gen_lora_slot_ >= program_->lora_pools[(size_t)s.pool].S)) + return abort_step_msg(h, RAD_E_STATE, + fmt("LoRA site: a generator pass in slot %d of %lld", gen_lora_slot_, + (long long)program_->lora_pools[(size_t)s.pool].S)); /* Each row's adapter is the step batch's (RadBatch::lora_slot), rewritten in stream order * before each step's kernels, so the pointer this launch records is the one a replay of it - * reads. */ + * reads. A generator pass is never recorded, so its run of the slot table is named directly, + * and it runs the pair over chunks of at most lora_rows_n rows: a video's passes run to + * hundreds of thousands of rows, and `t` and the slot run are sized for one chunk. */ const LoraPool& pool = program_->lora_pools[(size_t)s.pool]; const rad_buf t = program_->lora_t[(size_t)s.t].lane[lane_ ? 1 : 0]; - RadOperand slot = RAD_P_T(batch_->lora_slot + r0, RAD_I32); - slot.rows = n; - const RadOperand tv = RAD_B_N(t, 0, n); - const RadOperand sh[5] = { xa, - s.opd_a_scale >= 0 && s.opd_a_scale < n_opd ? opd[s.opd_a_scale] - : RAD_NONE, - slot, RAD_B(pool.a), tv }; - int rc = issue_body((rad_op)s.shrink, sh, 5, n); - if (rc < 0) return rc; - const RadOperand ex[5] = { tv, slot, RAD_B(pool.b), RAD_B(pool.scale), ya }; - return issue_body((rad_op)s.expand, ex, 5, n); + /* A generator's slot holds its ranks from 0 (Program::lora_rused): no pair where it holds + * none, the narrowest declared pair that holds them otherwise. */ + uint32_t sh_op = s.shrink, ex_op = s.expand; + int64_t rv = s.R; + if (gen) { + const size_t ui = (size_t)s.pool * (size_t)pool.S + (size_t)gen_lora_slot_; + const int64_t used = ui < program_->lora_rused.size() ? program_->lora_rused[ui] : s.R; + if (used <= 0) return RAD_OK; + for (int v = 0; v < s.n_v; ++v) + if (s.R_v[v] >= used) { sh_op = s.shrink_v[v]; ex_op = s.expand_v[v]; rv = s.R_v[v]; } + } + RadOperand xs = s.opd_a_scale >= 0 && s.opd_a_scale < n_opd ? opd[s.opd_a_scale] + : RAD_NONE; + const int64_t step = gen ? program_->lora_rows_n : n; + if (step <= 0) return abort_step_msg(h, RAD_E_STATE, "LoRA site: no slot rows"); + int64_t sw = 0; /* a_scale's row stride, for a chunk past the first */ + if (n > step && xs.kind != RAD_OPK_NONE) { + if (xs.kind != RAD_OPK_BUF || (size_t)xs.handle >= program_->buffers.size()) + return abort_step_msg(h, RAD_E_UNSUPPORTED, "LoRA site: a generator pass's activation " + "scale is not a declared buffer, so its " + "rows cannot be chunked"); + const RadBufDecl& sd = program_->buffers[xs.handle].decl; + sw = sd.rank >= 2 ? sd.shape[sd.rank - 1] : 1; + } + const int64_t xw = xd.rank >= 2 ? xd.shape[xd.rank - 1] : 0; + for (int64_t c = 0; c < n; c += step) { + const int64_t nc = std::min(step, n - c); + RadOperand x = xa, y = ya, a_s = xs; + if (c > 0) { + x.offset += c * xw; + y.offset += c * yw; + if (a_s.kind == RAD_OPK_BUF) a_s.offset += c * sw; + } + if (n > step) { + x.rows = nc; + y.rows = nc; + if (a_s.kind == RAD_OPK_BUF) a_s.rows = nc; + } + RadOperand slot = gen ? RAD_B(program_->lora_rows) : RAD_P_T(batch_->lora_slot + r0, RAD_I32); + if (gen) slot.offset = (int64_t)gen_lora_slot_ * program_->lora_rows_n; + slot.rows = nc; + RadOperand tv = RAD_B_N(t, 0, nc); + if (rv < s.R) tv.cols = rv; + const RadOperand sh[5] = { x, a_s, slot, RAD_B(pool.a), tv }; + int rc = issue_body((rad_op)sh_op, sh, 5, nc); + if (rc < 0) return rc; + const RadOperand ex[5] = { tv, slot, RAD_B(pool.b), RAD_B(pool.scale), y }; + rc = issue_body((rad_op)ex_op, ex, 5, nc); + if (rc < 0) return rc; + } + return RAD_OK; } int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { diff --git a/core/server/iface.h b/core/server/iface.h index e492463a..8cd70dd4 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -599,6 +599,22 @@ struct ImageGenInfo { /* A reference picture is shrunk to `ref_area` only when larger, then centre-cropped to the * size multiple; otherwise resized to `ref_area` at its aspect. */ bool ref_shrink_only = false; + /* A prompt of fewer tokens after the drop prefix is padded with `pad_token` up to this many + * (RadGeneratorDecl::min_tokens); 0: no minimum. */ + int64_t min_tokens = 0; + int32_t pad_token = 0; + /* The prompt is also read through the model's second tokenizer (IImageGen::encode_aux), at + * most `aux_max_tokens` ids of it. */ + bool aux_tokens = false; + int64_t aux_max_tokens = 0; + /* A discrete-time model (RadGeneratorDecl::train_steps): the samplers it serves (1 << id) + * and the sampler and scheduler a request gets when it names none. 0 samplers: flow + * matching, which takes neither field. */ + uint32_t samplers = 0; + int32_t default_sampler = 0, default_scheduler = 0; + /* The prompt in windows (RadGeneratorDecl::chunk_tokens): tokens a window, its markers and + * its padding token; 0 for a prompt read whole. */ + int32_t chunk_tokens = 0, chunk_bos = 0, chunk_eos = 0, chunk_pad = 0; }; class IImageGen { @@ -612,6 +628,13 @@ public: virtual int picture(const mm::Frame& f, std::shared_ptr* out, std::string* why) = 0; virtual int64_t queued() const = 0; virtual int64_t running() const = 0; + /* The user's prompt through the model's second tokenizer (ImageGenInfo::aux_tokens), with the + * special tokens that tokenizer adds; RAD_E_UNSUPPORTED for a model without one. */ + virtual int encode_aux(const std::string& text, std::vector* out) const { + (void)text; + (void)out; + return RAD_E_UNSUPPORTED; + } }; /* The audio generator (core/gen/audio_driver.h), for a model that makes music or other audio from diff --git a/core/server/images.cpp b/core/server/images.cpp index f8c888ab..15b44357 100644 --- a/core/server/images.cpp +++ b/core/server/images.cpp @@ -21,6 +21,7 @@ * `.completed` event per image. */ #include "server.h" +#include "loras.h" #include "oai.h" #include "gen/gen.h" @@ -58,6 +59,7 @@ struct ImgReq { bool has_neg = false; double cfg = 1.0; int32_t w = 0, h = 0, n = 1, steps = 0, previews = 0; + int32_t sampler = 0, scheduler = 0; bool seed_given = false; uint64_t seed = 0; std::string background = "auto", format = "png", quality = "auto"; @@ -89,6 +91,11 @@ json form_value(const std::string& key, const std::string& v) { if (v == "true" || v == "1") return json(true); if (v == "false" || v == "0") return json(false); } + /* `loras` as JSON text, or one adapter's name. */ + if ((key == "loras" || key == "lora") && !v.empty() && (v[0] == '[' || v[0] == '{')) { + json j = json::parse(v, nullptr, false); + if (!j.is_discarded()) return j; + } return json(v); } @@ -235,7 +242,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { "output_compression", "response_format", "stream", "partial_images", "moderation", "style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale", "guidance_scale", - "num_inference_steps", "width", "height", + "num_inference_steps", "width", "height", "loras", "lora", "sampler", "scheduler", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; @@ -262,7 +269,20 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { return error_response(err_bad("prompt", "expected a string"), req.peer); if (!body.contains("prompt")) return error_response(err_bad("prompt", "the prompt is required"), req.peer); - if (r.prompt.empty()) r.prompt = " "; + /* Runtime LoRA adapters: `loras` and tags, which leave the prompt. */ + std::vector> loras; + { + std::string field, why; + if (parse_loras(body, &r.prompt, &loras, &field, &why) < 0) + return error_response(err_bad(field.c_str(), why), req.peer); + if (!loras.empty() && !opt_.gen_lora_acquire) + return error_response(err_unsupported(field.c_str(), "this server was started without " + "adapters (--lora, --lora-dir)"), + req.peer); + } + /* An empty prompt becomes " ", as in the diffusers pipelines, unless the model pads a short + * prompt itself (ImageGenInfo::min_tokens), as ComfyUI's tokenizers do. */ + if (r.prompt.empty() && info.min_tokens == 0) r.prompt = " "; std::string rf; if (str("response_format", &rf) < 0 || (!rf.empty() && rf != "b64_json" && rf != "url")) return error_response(err_bad("response_format", "expected b64_json"), req.peer); @@ -335,6 +355,39 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { else if (r.quality == "medium") steps = std::max(1, info.default_steps * 3 / 4); } r.steps = (int32_t)steps; + /* A discrete-time model's sampler and scheduler, by ComfyUI's names. */ + { + std::string sname, kname; + if (str("sampler", &sname) < 0) + return error_response(err_bad("sampler", "expected a string"), req.peer); + if (str("scheduler", &kname) < 0) + return error_response(err_bad("scheduler", "expected a string"), req.peer); + if (!info.samplers && (!sname.empty() || !kname.empty())) + return error_response(err_unsupported(sname.empty() ? "scheduler" : "sampler", + "this model samples with flow-matching Euler " + "on its own schedule"), req.peer); + r.sampler = info.default_sampler; + r.scheduler = info.default_scheduler; + if (!sname.empty()) { + r.sampler = gen::sampler_id(sname); + if (r.sampler < 0 || !(info.samplers & (1u << r.sampler))) { + ApiError e = err_bad("sampler", "'" + sname + "' is not a sampler this model serves"); + for (int32_t i = 0; i < RAD_GEN_SAMPLER_COUNT; ++i) + if (info.samplers & (1u << i)) e.supported.push_back(gen::sampler_name(i)); + return error_response(e, req.peer); + } + } + if (!kname.empty()) { + r.scheduler = gen::scheduler_id(kname); + if (r.scheduler < 0) { + ApiError e = err_bad("scheduler", "'" + kname + "' is not a scheduler this model " + "serves"); + for (int32_t i = 0; i < RAD_GEN_SCHED_COUNT; ++i) + e.supported.push_back(gen::scheduler_name(i)); + return error_response(e, req.peer); + } + } + } /* -1 asks for a random seed, as llama-server and the chat endpoints read it. */ if (body.contains("seed") && !body["seed"].is_null()) { if (!body["seed"].is_number_integer()) @@ -365,12 +418,12 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { "..30"), req.peer); } /* Guidance needs a scale past its off value and a negative prompt: the request's (empty - * becomes " ", as in the reference pipeline), or the model's own. */ + * becomes " " as the prompt does), or the model's own. */ const bool guided = r.cfg > cfg_off; const bool named_neg = body.contains("negative_prompt") && !body["negative_prompt"].is_null(); r.has_neg = guided && (named_neg || info.has_default_negative); if (r.has_neg && !named_neg) r.negative = info.default_negative; - else if (r.has_neg && r.negative.empty()) r.negative = " "; + else if (r.has_neg && r.negative.empty() && info.min_tokens == 0) r.negative = " "; if (guided && !r.has_neg) return error_response(err_bad(cfg_key, "guidance needs a negative_prompt"), req.peer); @@ -470,6 +523,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { g->height = r.h; g->n = r.n; g->steps = r.steps; + g->sampler = r.sampler; + g->scheduler = r.scheduler; g->seed = r.seed; g->previews = r.previews; /* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is @@ -585,6 +640,41 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { return RAD_E_STATE; } out->n_drop = (int32_t)drop.size(); + /* The reference tokenizer's minimum length: an empty prompt is padding the model reads. */ + while ((int64_t)out->tokens.size() - out->n_drop < info.min_tokens) + out->tokens.push_back(info.pad_token); + if (info.aux_tokens) { + if (deps_.images->encode_aux(prompt, &out->aux) < 0) { + *err = err_internal("the prompt could not be read by the model's second " + "tokenizer"); + return RAD_E_STATE; + } + if ((int64_t)out->aux.size() > info.aux_max_tokens) { + *err = err_bad("prompt", "the prompt is " + std::to_string(out->aux.size()) + + " tokens to this model's second tokenizer, which " + "reads at most " + + std::to_string(info.aux_max_tokens)); + return RAD_E_INVAL; + } + } + /* A prompt read in windows: runs of at most chunk_tokens after the prefix, each between + * its markers and padded to the window. */ + if (info.chunk_tokens > 0) { + const size_t W = (size_t)info.chunk_tokens; + std::vector win(out->tokens.begin(), out->tokens.begin() + out->n_drop); + const size_t n_body = out->tokens.size() - (size_t)out->n_drop; + size_t at = 0; + do { + const size_t take = std::min(W, n_body - at); + win.push_back(info.chunk_bos); + win.insert(win.end(), out->tokens.begin() + out->n_drop + (std::ptrdiff_t)at, + out->tokens.begin() + out->n_drop + (std::ptrdiff_t)(at + take)); + win.push_back(info.chunk_eos); + win.resize(win.size() + (W - take), info.chunk_pad); + at += take; + } while (at < n_body); + out->tokens = std::move(win); + } if ((int64_t)out->tokens.size() > info.max_cond_tokens) { *err = err_bad("prompt", "the prompt is " + std::to_string(out->tokens.size()) + " tokens with its pictures; this deployment conditions on " @@ -600,6 +690,19 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { return error_response(err, req.peer); } + /* ---- the adapters' slot, held until the request is done */ + std::string lora_note; + if (!loras.empty()) { + std::string why; + const int s = opt_.gen_lora_acquire(loras, &g->lora_slot, &g->lora_hold, &lora_note, &why); + if (s < 0) { + ApiError e = err_bad("loras", why); + if (s == RAD_E_NOTFOUND) { e.status = 404; e.type = "not_found_error"; } + else if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; } + return error_response(e, req.peer); + } + } + /* ---- admitted and queued */ if (auto no = admit(1, req.peer)) return *no; std::shared_ptr ticket = g->ticket; @@ -613,9 +716,11 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { return error_response(e, req.peer); } } - RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s", edit ? "edit" : "generation", r.w, + std::string lora_s; + for (const auto& [n, w] : loras) lora_s += (lora_s.empty() ? " loras=" : ",") + n + fmt(":%g", w); + RAD_INFO("images: %s %dx%d n=%d steps=%d seed=%llu%s%s%s%s", edit ? "edit" : "generation", r.w, r.h, r.n, r.steps, (unsigned long long)r.seed, r.has_neg ? " guided" : "", - r.has_mask ? " masked" : "", r.stream ? " streamed" : ""); + r.has_mask ? " masked" : "", r.stream ? " streamed" : "", lora_s.c_str()); /* ---- one finished picture to a file */ const std::string size_s = std::to_string(r.w) + "x" + std::to_string(r.h); diff --git a/core/server/loras.cpp b/core/server/loras.cpp new file mode 100644 index 00000000..05188744 --- /dev/null +++ b/core/server/loras.cpp @@ -0,0 +1,117 @@ +/* loras.cpp -- see loras.h. */ +#include "loras.h" +#include "rad_internal.h" + +#include +#include + +namespace rad { +namespace server { + +namespace { + +/* "name" or "name:strength" (the last ':' splits, so a name may hold one). */ +bool split_entry(const std::string& s, std::string* name, double* w) { + *w = 1.0; + const size_t c = s.rfind(':'); + if (c != std::string::npos && c + 1 < s.size()) { + char* end = nullptr; + const double v = std::strtod(s.c_str() + c + 1, &end); + if (end && *end == '\0' && std::isfinite(v)) { + *name = s.substr(0, c); + *w = v; + return !name->empty(); + } + } + *name = s; + return !name->empty(); +} + +} /* namespace */ + +int parse_loras(const nlohmann::json& body, std::string* prompt, + std::vector>* out, std::string* field, + std::string* why) { + out->clear(); + const char* key = body.contains("loras") ? "loras" : "lora"; + if (body.contains(key) && !body[key].is_null()) { + *field = key; + const nlohmann::json& v = body[key]; + auto entry = [&](const nlohmann::json& e) -> bool { + std::string name; + double w = 1.0; + if (e.is_string()) { + if (!split_entry(e.get(), &name, &w)) return false; + } else if (e.is_object()) { + if (!e.contains("name") || !e["name"].is_string()) return false; + name = e["name"].get(); + for (const char* k : { "weight", "strength", "scale" }) + if (e.contains(k) && !e[k].is_null()) { + if (!e[k].is_number()) return false; + w = e[k].get(); + } + } else { + return false; + } + if (name.empty() || !std::isfinite(w)) return false; + out->push_back({ name, w }); + return true; + }; + if (v.is_array()) { + for (const nlohmann::json& e : v) + if (!entry(e)) { + *why = "each entry is a name, \"name:strength\" or {\"name\", \"weight\"}"; + return RAD_E_INVAL; + } + } else if (v.is_object() && !v.contains("name")) { + for (auto it = v.begin(); it != v.end(); ++it) { + if (!it.value().is_number() || !std::isfinite(it.value().get())) { + *why = "a {name: strength} object's strengths are numbers"; + return RAD_E_INVAL; + } + out->push_back({ it.key(), it.value().get() }); + } + } else if (!entry(v)) { + *why = "expected a list of adapters (names, \"name:strength\" or {\"name\", \"weight\"})"; + return RAD_E_INVAL; + } + } + /* tags in the prompt. */ + if (prompt) { + std::string p; + size_t at = 0; + for (;;) { + const size_t open = prompt->find("substr(at); break; } + const size_t close = prompt->find('>', open); + if (close == std::string::npos) { p += prompt->substr(at); break; } + std::string name; + double w = 1.0; + if (!split_entry(prompt->substr(open + 6, close - open - 6), &name, &w)) { + *field = "prompt"; + *why = "a tag names no adapter"; + return RAD_E_INVAL; + } + out->push_back({ name, w }); + p += prompt->substr(at, open - at); + at = close + 1; + } + if (p.size() != prompt->size()) { + /* Tidy the gaps the tags leave: runs of spaces, and commas with nothing between. */ + std::string t; + for (char c : p) { + if (c == ' ' && (t.empty() || t.back() == ' ')) continue; + t += c; + } + for (size_t k; (k = t.find(", ,")) != std::string::npos;) t.erase(k, 2); + for (size_t k; (k = t.find(",,")) != std::string::npos;) t.erase(k, 1); + while (!t.empty() && (t[0] == ' ' || t[0] == ',')) t.erase(0, 1); + while (!t.empty() && (t.back() == ' ' || t.back() == ',')) t.pop_back(); + *prompt = t.empty() ? std::string(" ") : t; + } + } + return RAD_OK; +} + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/loras.h b/core/server/loras.h new file mode 100644 index 00000000..904cfdb0 --- /dev/null +++ b/core/server/loras.h @@ -0,0 +1,30 @@ +/* loras.h -- which runtime LoRA adapters an image or video request asks for, and at what strength. + * + * Two spellings, merged: + * + * `loras` in the body: a list whose entries are a name, "name:strength", or an object + * {"name": ..., "weight" | "strength" | "scale": ...}; or an object {name: strength}. + * `lora` is the same field. + * + * or in the prompt, as Stable Diffusion web UIs write it: the + * tag is taken out of the prompt, the text around it kept. + * + * A strength not given is 1. */ +#pragma once +#include + +#include +#include +#include + +namespace rad { +namespace server { + +/* RAD_OK with the adapters in `out` (possibly none) and their tags removed from *prompt; + * RAD_E_INVAL with `why` for a malformed entry. `field` receives the field the error is about. */ +int parse_loras(const nlohmann::json& body, std::string* prompt, + std::vector>* out, std::string* field, + std::string* why); + +} /* namespace server */ +} /* namespace rad */ diff --git a/core/server/server.cpp b/core/server/server.cpp index d72dc82d..49361853 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -132,6 +132,7 @@ void Server::register_routes() { return r; }); router_.get ("/v1/models", [this](const HttpRequest& q) { return handle_models(q); }); + router_.get ("/v1/loras", [this](const HttpRequest& q) { return handle_loras(q); }); router_.get ("/v1/models/*id", [this](const HttpRequest& q) { return handle_models(q); }); router_.post("/v1/load_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, true); }); router_.post("/v1/unload_lora_adapter", [this](const HttpRequest& q) { return handle_lora_admin(q, false); }); @@ -1864,6 +1865,22 @@ HttpResponse Server::handle_models(const HttpRequest& req) { /* Runtime LoRA admin, vLLM's routes and bodies: {"lora_name", "lora_path"} to load, {"lora_name"} * to unload. The path is read on this machine, so without --api-key only a loopback client may * ask, the rule /diagnostics follows. */ +/* A generator's adapter files: what `loras` and tags may name. */ +HttpResponse Server::handle_loras(const HttpRequest& req) { + using json = nlohmann::json; + if (!opt_.gen_lora_names) { + ApiError e; + e.status = 404; + e.type = "not_found_error"; + e.message = "this server takes no adapters in image or video requests (--lora, --lora-dir)"; + return error_response(e, req.peer); + } + json data = json::array(); + for (const std::string& n : opt_.gen_lora_names()) data.push_back({ { "id", n }, { "object", "lora" } }); + metrics_.observe_http(200); + return HttpResponse::json_body(200, json_dump(json{ { "object", "list" }, { "data", std::move(data) } })); +} + HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) { using json = nlohmann::json; auto fail = [&](int status, const char* type, const std::string& msg) { diff --git a/core/server/server.h b/core/server/server.h index f1cded21..353c9939 100644 --- a/core/server/server.h +++ b/core/server/server.h @@ -141,6 +141,12 @@ struct ServerOptions { * of an adapter requests still use drains it: RAD_OK with *in_flight > 0 (Engine::lora_unload). */ std::function lora_load; std::function lora_unload; + /* A generator's adapters (Engine::gen_lora_acquire): the images and videos endpoints' `loras` + * and tags get a slot holding that combination, a hold on it and a note on what was + * left out; `gen_lora_names` is GET /v1/loras. Unset without adapters. */ + std::function>&, int32_t*, + std::shared_ptr*, std::string*, std::string*)> gen_lora_acquire; + std::function()> gen_lora_names; std::string api_key; bool cors = true; @@ -240,6 +246,7 @@ private: void realtime_run(RealtimeSession& s, WsConn& ws); bool realtime_loop(RealtimeSession& s, WsConn& ws); HttpResponse handle_models(const HttpRequest& req); + HttpResponse handle_loras(const HttpRequest& req); HttpResponse handle_metrics(const HttpRequest& req); std::optional refuse_text(const std::string& peer, ApiShape shape = ApiShape::OpenAI); diff --git a/core/server/videos.cpp b/core/server/videos.cpp index b1de899f..e33182f2 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -39,6 +39,7 @@ * special tokens and the prompt without, so a caller cannot write control tokens into it. */ #include "server.h" +#include "loras.h" #include "oai.h" #include "gen/video.h" @@ -168,7 +169,9 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { return error_response(err_bad(p.name, "'" + p.name + "' takes text, not a file"), req.peer); json v = p.data; - if (p.name == "target" || p.name == "conditions") { + if (p.name == "target" || p.name == "conditions" || + ((p.name == "loras" || p.name == "lora") && !p.data.empty() && + (p.data[0] == '[' || p.data[0] == '{'))) { v = json::parse(p.data, nullptr, false); if (v.is_discarded()) return error_response(err_bad(p.name, "expected JSON"), req.peer); @@ -183,7 +186,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { static const char* kKnown[] = { "model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps", "task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", - "negative_prompt", "decoder", + "negative_prompt", "decoder", "loras", "lora", /* RadVideoGenBatch::guidance_h's order */ "guidance_scale", "stg_scale", "modality_scale", "guidance_rescale", "audio_guidance_scale", "audio_stg_scale", "audio_modality_scale", "audio_guidance_rescale", @@ -210,7 +213,17 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { if (!has(body, "prompt") || !body["prompt"].is_string() || body["prompt"].get().find_first_not_of(" \t\r\n") == std::string::npos) return bad("prompt", "the prompt is required, as a non-empty string"); - const std::string prompt = body["prompt"].get(); + std::string prompt = body["prompt"].get(); + /* Runtime LoRA adapters: `loras` and tags, which leave the prompt. */ + std::vector> loras; + { + std::string field, why; + if (parse_loras(body, &prompt, &loras, &field, &why) < 0) return bad(field.c_str(), why); + if (!loras.empty() && !opt_.gen_lora_acquire) + return error_response(err_unsupported(field.c_str(), "this server was started without " + "adapters (--lora, --lora-dir)"), + req.peer); + } if (has(body, "input_reference")) { /* JSON: a data URL, as a string or an image_url object. */ const json& v = body["input_reference"]; @@ -497,6 +510,16 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { } /* ---- admitted and queued: the job holds its place until its file is written */ + if (!loras.empty()) { + std::string why, note; + const int s = opt_.gen_lora_acquire(loras, &r->lora_slot, &r->lora_hold, ¬e, &why); + if (s < 0) { + ApiError e = err_bad("loras", why); + if (s == RAD_E_NOTFOUND) { e.status = 404; e.type = "not_found_error"; } + else if (s != RAD_E_INVAL) { e.status = 503; e.type = "server_error"; } + return error_response(e, req.peer); + } + } if (auto no = admit(1, req.peer)) return *no; auto j = std::make_shared(); j->id = new_video_id(); diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index 3be3237b..41924cf7 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -1,5 +1,6 @@ #include "text/tokenizer.h" #include "text/tokenizer_bpe.h" +#include "text/tokenizer_grapheme.h" #include "text/tokenizer_nfc.h" #include "text/tokenizer_regex.h" #include "text/unicode_norm.h" @@ -388,6 +389,8 @@ struct TokEncoder { /* Split, a regex Replace, ByteLevel with use_regex, and the character-class * pre-tokenisers; `re2` is BertPreTokenizer's punctuation after its whitespace split. */ std::unique_ptr re, re2; + /* Precompiled: the decoded character map. */ + std::unique_ptr pmap; }; std::vector norm, pre; uint32_t kind = RAD_TOK_BPE; @@ -403,6 +406,12 @@ struct TokEncoder { TokTable text; /* token text -> lowest id */ TokTable raw; /* raw bytes a byte-level token stands for -> id */ int32_t byte_sym[256]; /* raw byte -> id of its byte-level character */ + /* BPE's end-of-word suffix (RAD_PRE_END_OF_WORD), empty without one. A word's last symbol + * is its text with the suffix: `raw_eow` holds the tokens ending in it by the raw bytes + * before it, and `byte_sym_eow` a byte's character with it. */ + std::string eow; + TokTable raw_eow; + int32_t byte_sym_eow[256]; int32_t byte_tok[256]; /* raw byte -> id of "<0xNN>" */ MergeTable merges; std::vector types; @@ -419,6 +428,10 @@ struct TokEncoder { std::unique_ptr[]> self_merges; SpecialMatcher specials; + /* The added tokens matched in the normalised text (RAD_PRE_ADDED_NORMALIZED); `specials` + * holds the rest. */ + SpecialMatcher nspecials; + bool has_nspecials = false; mutable SegmentCache cache; int build(const VocabBuild& b, const std::vector& special); @@ -443,11 +456,19 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& special) for (const VocabStep& s : b.steps) { if (step_is_norm(s.kind)) { - Step st{ s, nullptr, nullptr }; + Step st{ s, nullptr, nullptr, nullptr }; if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) RAD_TRY(compile(s.arg0, "Replace", &st.re)); + if (s.kind == RAD_NORM_PRECOMPILED) { + st.pmap = std::make_unique(); + std::string why; + if (st.pmap->load(s.arg0, &why) < 0) { + RAD_ERR("vocab: the Precompiled normaliser's map: %s", why.c_str()); + return RAD_E_FORMAT; + } + } norm.push_back(std::move(st)); } else if (step_is_pre(s.kind)) { - Step st{ s, nullptr, nullptr }; + Step st{ s, nullptr, nullptr, nullptr }; if (s.kind == RAD_PRE_SPLIT) RAD_TRY(compile(s.arg0, "Split", &st.re)); if (s.kind == RAD_PRE_WHITESPACE) { RAD_TRY(compile(s.flags == kPreWhitespace ? k_word_runs : k_space_runs, @@ -462,6 +483,7 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& special) if (s.flags & 2) RAD_TRY(compile(k_gpt2_pattern, "ByteLevel", &st.re)); } if (s.kind == RAD_PRE_BYTE_FALLBACK) byte_fallback = true; + if (s.kind == RAD_PRE_END_OF_WORD) eow = s.arg0; if (s.kind == RAD_PRE_METASPACE && s.iarg == 1) prepend_first = true; pre.push_back(std::move(st)); } @@ -469,7 +491,7 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& special) if (kind == RAD_TOK_BPE) { for (size_t k = pre.size(); k-- > 0; ) { const uint32_t sk = pre[k].step.kind; - if (sk == RAD_PRE_BYTE_FALLBACK) continue; + if (sk == RAD_PRE_BYTE_FALLBACK || sk == RAD_PRE_END_OF_WORD) continue; if (sk == RAD_PRE_BYTELEVEL) defer_bytelevel = (int)k; break; } @@ -490,12 +512,20 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& special) const char buf[7] = { '<', '0', 'x', hex[c >> 4], hex[c & 15], '>', 0 }; byte_tok[c] = text.find(buf); byte_sym[c] = text.find(a.to_utf8[c]); + byte_sym_eow[c] = eow.empty() ? -1 : text.find(a.to_utf8[c] + eow); } if (defer_bytelevel >= 0) { raw.reserve(n); std::string r; - for (size_t i = 0; i < n; ++i) - if (!b.tokens[i].empty() && byte_decode_strict(b.tokens[i], &r)) raw.insert(r, (int32_t)i); + for (size_t i = 0; i < n; ++i) { + const std::string& t = b.tokens[i]; + if (t.empty()) continue; + if (!eow.empty() && t.size() > eow.size() && + t.compare(t.size() - eow.size(), eow.size(), eow) == 0 && + byte_decode_strict(t.substr(0, t.size() - eow.size()), &r)) + raw_eow.insert(r, (int32_t)i); + if (byte_decode_strict(t, &r)) raw.insert(r, (int32_t)i); + } } /* Keyed by the pair as the vocab lists it; the lowest rank wins a duplicate. A symbol's id is @@ -511,7 +541,17 @@ int TokEncoder::build(const VocabBuild& b, const std::vector& special) merges.insert((int32_t)l, (int32_t)rr, (uint32_t)r, text.find(cat)); } - specials.build(special, b.tokens, b.types); + /* Each matcher keeps the priority order of `special` (longest first). */ + std::vector raw_special, norm_special; + for (int32_t id : special) { + bool normalized = false; + for (const VocabStep& s : b.steps) + normalized |= s.kind == RAD_PRE_ADDED_NORMALIZED && s.iarg == id; + (normalized ? norm_special : raw_special).push_back(id); + } + specials.build(raw_special, b.tokens, b.types); + nspecials.build(norm_special, b.tokens, b.types); + has_nspecials = !norm_special.empty(); self_merges.reset(new std::atomic[n]()); /* A byte-level BPE never looks text up by its mapped spelling once `raw` exists. */ if (defer_bytelevel >= 0) text = TokTable(); @@ -541,8 +581,8 @@ int Vocab::load(VocabBuild b) { * so a vocabulary that declares one does not load. */ for (const VocabStep& s : b_.steps) { const uint32_t k = s.kind; - if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PREPEND) || - (k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_BYTE_FALLBACK) || + if ((k >= RAD_NORM_NFC && k <= RAD_NORM_PRECOMPILED) || + (k >= RAD_PRE_BYTELEVEL && k <= RAD_PRE_ADDED_NORMALIZED) || (k >= RAD_DEC_BYTELEVEL && k <= RAD_DEC_BYTE_FALLBACK)) continue; RAD_ERR("vocab: %s is not implemented", step_describe(s).c_str()); @@ -570,6 +610,19 @@ int Vocab::load(VocabBuild b) { if (s.kind == RAD_DEC_STRIP && fused) fused_strip = true; } } + /* A token matched in the normalised text is one of the vocabulary's added tokens, spelt as + * the step says. */ + for (const VocabStep& s : b_.steps) { + if (s.kind != RAD_PRE_ADDED_NORMALIZED) continue; + const int32_t id = (int32_t)s.iarg; + if (s.iarg < 0 || s.iarg >= (int64_t)b_.tokens.size() || s.arg0.empty() || + b_.tokens[(size_t)id] != s.arg0 || + (!b_.types.empty() && b_.types[(size_t)id] != RAD_TT_CONTROL && + b_.types[(size_t)id] != RAD_TT_USER_DEFINED)) { + RAD_ERR("vocab: %s names no added token of that spelling", step_describe(s).c_str()); + return RAD_E_FORMAT; + } + } if (b_.types.empty()) b_.types.assign(b_.tokens.size(), (uint8_t)RAD_TT_NORMAL); if (b_.types.size() != b_.tokens.size()) { RAD_ERR("vocab: %zu tokens but %zu token types", b_.tokens.size(), b_.types.size()); @@ -781,6 +834,8 @@ std::string step_describe(const VocabStep& s) { return fmt("Replace(%s '%s' -> '%s')", (s.flags & 1) ? "regex" : "literal", s.arg0.c_str(), s.arg1.c_str()); case RAD_NORM_PREPEND: return fmt("Prepend('%s')", s.arg0.c_str()); + case RAD_NORM_PRECOMPILED: + return fmt("Precompiled(%zu base64 bytes)", s.arg0.size()); case RAD_PRE_BYTELEVEL: return fmt("ByteLevel(add_prefix_space=%d use_regex=%d)", (s.flags & 1) ? 1 : 0, (s.flags & 2) ? 1 : 0); @@ -806,6 +861,9 @@ std::string step_describe(const VocabStep& s) { case RAD_PRE_DIGITS: return fmt("Digits(individual=%d)", (s.flags & 1) ? 1 : 0); case RAD_PRE_BYTE_FALLBACK: return "ByteFallback"; + case RAD_PRE_END_OF_WORD: return fmt("EndOfWordSuffix('%s')", s.arg0.c_str()); + case RAD_PRE_ADDED_NORMALIZED: + return fmt("AddedNormalized('%s' = %lld)", s.arg0.c_str(), (long long)s.iarg); case RAD_DEC_BYTELEVEL: return "decode ByteLevel"; case RAD_DEC_METASPACE: return fmt("decode Metaspace('%s' prepend=%lld)", s.arg0.c_str(), (long long)s.iarg); @@ -839,7 +897,13 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) { std::vector cpts = unicode_cpts_from_utf8(text); std::string out; out.reserve(text.size()); - for (uint32_t c : cpts) out += unicode_cpt_to_utf8(unicode_tolower(c)); + /* HuggingFace lowercases a character at a time with Rust's char::to_lowercase, whose + * one unconditional mapping to two characters is U+0130 (I with dot above) to + * "i" U+0307; every other character maps to one. */ + for (uint32_t c : cpts) { + if (c == 0x130) out += "i\xcc\x87"; + else out += unicode_cpt_to_utf8(unicode_tolower(c)); + } text.swap(out); break; } @@ -868,6 +932,7 @@ void apply_norm(std::string& text, const TokEncoder::Step& st) { } break; case RAD_NORM_PREPEND: text = s.arg0 + text; break; + case RAD_NORM_PRECOMPILED: text = st.pmap->normalize(text); break; } } @@ -1055,7 +1120,8 @@ private: void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out, EncodeScratch& sc) { const bool raw = e.defer_bytelevel >= 0; - const TokTable& table = raw ? e.raw : e.text; + const bool eow = !e.eow.empty(); + const TokTable& table = raw ? (eow ? e.raw_eow : e.raw) : e.text; /* A user-defined token is taken whole: added tokens must round-trip, and the merge table was * never fitted over them, so re-merging can give a different sequence. @@ -1065,7 +1131,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out * different split of a rare word). The raw-byte table finds the same entry by its byte * spelling. A control entry is never taken whole: reaching here means the caller asked for * it to be read as text. */ - const int32_t whole = table.find(w); + /* With an end-of-word suffix the whole word is its text and the suffix: `raw_eow` is keyed + * without it, the text table with it. */ + const int32_t whole = eow && !raw ? table.find(std::string(w) + e.eow) : table.find(w); if (whole >= 0 && (e.types[whole] == RAD_TT_USER_DEFINED || (e.ignore_merges && e.types[whole] != RAD_TT_CONTROL))) { out.push_back(whole); @@ -1083,10 +1151,13 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out if (raw) { for (size_t i = 0; i < n; ++i) syms.push_back({ (uint32_t)i, 1, e.byte_sym[(unsigned char)w[i]] }); + if (eow) syms.back().id = e.byte_sym_eow[(unsigned char)w[n - 1]]; } else { for (size_t i = 0; i < n; ) { const size_t len = std::min(unicode_len_utf8(w[i]), n - i); - syms.push_back({ (uint32_t)i, (uint32_t)len, table.find(w.substr(i, len)) }); + syms.push_back({ (uint32_t)i, (uint32_t)len, + eow && i + len == n ? table.find(std::string(w.substr(i, len)) + e.eow) + : table.find(w.substr(i, len)) }); i += len; } } @@ -1103,9 +1174,12 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out /* Miss: decompose into byte tokens, spelt per the chain. Under ByteLevel each byte is its * own mapped codepoint, so the piece splits at codepoint boundaries; under byte fallback * a byte is "<0xNN>". */ + const bool last = s.start + s.len == n; if (raw) { - for (unsigned char c : str) { - const int32_t b = e.byte_sym[c]; + for (size_t k = 0; k < str.size(); ++k) { + const unsigned char c = (unsigned char)str[k]; + const int32_t b = eow && last && k + 1 == str.size() ? e.byte_sym_eow[c] + : e.byte_sym[c]; if (b >= 0) out.push_back(b); else RAD_WARN("tokenizer: no token for byte-level piece '%s'", alphabet().to_utf8[c].c_str()); @@ -1113,7 +1187,9 @@ void bpe_word(const TokEncoder& e, std::string_view w, std::vector& out } else if (e.bytelevel) { for (size_t k = 0; k < str.size(); ) { const size_t m = std::min(unicode_len_utf8(str[k]), str.size() - k); - const int32_t b = e.text.find(str.substr(k, m)); + const int32_t b = eow && last && k + m == str.size() + ? e.text.find(std::string(str.substr(k, m)) + e.eow) + : e.text.find(str.substr(k, m)); if (b >= 0) out.push_back(b); else RAD_WARN("tokenizer: no token for byte-level piece '%s'", std::string(str.substr(k, m)).c_str()); @@ -1142,9 +1218,13 @@ void bpe(const TokEncoder& e, const Pieces& p, std::vector& out, Encode if (w.empty()) continue; /* A one-byte word of a byte-level vocab is that byte's token; the lookup and the merge * would both land on byte_sym. A missing one takes the warning path in bpe_word. */ - if (raw && w.size() == 1 && e.byte_sym[(unsigned char)w[0]] >= 0) { - out.push_back(e.byte_sym[(unsigned char)w[0]]); - continue; + if (raw && w.size() == 1) { + const int32_t b = e.eow.empty() ? e.byte_sym[(unsigned char)w[0]] + : e.byte_sym_eow[(unsigned char)w[0]]; + if (b >= 0) { + out.push_back(b); + continue; + } } if (w.size() > WordCache::kMaxKey) { bpe_word(e, w, out, sc); continue; } const uint64_t h = tok_hash(w); @@ -1259,13 +1339,10 @@ void wordpiece(const Vocab& v, const TokEncoder& e, const Pieces& p, std::vector } } -/* One segment -- the text between two special tokens -- through the whole chain. `at_start`: - * the segment begins the text (see apply_metaspace). */ -int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg, - std::vector& out, EncodeScratch& sc, WordCache& words, bool at_start) { +/* Normalised text in `sc.p.buf` through the pre-tokenisers and the model. */ +int encode_normalized(const Vocab& v, const TokEncoder& e, std::vector& out, + EncodeScratch& sc, WordCache& words, bool at_start) { Pieces& p = sc.p; - p.buf.assign(seg.data(), seg.size()); - for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st); if (p.buf.size() > (size_t)(UINT32_MAX / 8)) { RAD_ERR("tokenizer: a %zu-byte segment is past what one encode can index", p.buf.size()); return RAD_E_INVAL; @@ -1302,6 +1379,12 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg, case RAD_PRE_BYTE_FALLBACK: /* Declares how an unknown piece is encoded, not a split; bpe_word handles it. */ break; + case RAD_PRE_END_OF_WORD: + /* Declares how a word's last symbol is spelt, not a split; bpe_word handles it. */ + break; + case RAD_PRE_ADDED_NORMALIZED: + /* Cut out by encode_segment before the pre-tokenisers run. */ + break; } } @@ -1323,8 +1406,45 @@ int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg, return RAD_OK; } +/* One segment -- the text between two special tokens -- through the whole chain. `at_start`: + * the segment begins the text (see apply_metaspace). The added tokens matched in the normalised + * text are cut out of it after the normalisers, under the same `parse_special` rule as the raw + * ones, and each piece between them goes through the rest of the chain on its own. */ +int encode_segment(const Vocab& v, const TokEncoder& e, std::string_view seg, + std::vector& out, EncodeScratch& sc, WordCache& words, bool at_start, + bool parse_special) { + Pieces& p = sc.p; + p.buf.assign(seg.data(), seg.size()); + for (const TokEncoder::Step& st : e.norm) apply_norm(p.buf, st); + if (!e.has_nspecials) return encode_normalized(v, e, out, sc, words, at_start); + + const std::string norm = p.buf; + std::vector frags; + e.nspecials.split(norm, parse_special, frags); + for (const SpecialFrag& f : frags) { + if (f.id >= 0) { out.push_back(f.id); continue; } + if (f.len == 0) continue; + p.buf.assign(norm, f.off, f.len); + RAD_TRY(encode_normalized(v, e, out, sc, words, at_start && f.off == 0)); + } + return RAD_OK; +} + } /* namespace */ +int vocab_normalize(const std::vector& steps, std::string* text) { + for (const VocabStep& s : steps) { + if (!step_is_norm(s.kind)) continue; + TokEncoder::Step st{ s, nullptr, nullptr }; + if (s.kind == RAD_NORM_REPLACE && (s.flags & 1)) { + std::string why; + if (TokRegex::compile(s.arg0, &st.re, &why) < 0) return RAD_E_UNSUPPORTED; + } + apply_norm(*text, st); + } + return RAD_OK; +} + /* ================================================================== encode */ int Tokenizer::init(std::shared_ptr v) { @@ -1372,14 +1492,17 @@ int Tokenizer::encode(std::string_view text, std::vector& out, /* The cache is keyed on the segment's bytes, so a segment whose ids also depend on * starting the text bypasses it. */ const bool at_start = f.off == 0; - if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first)) { - RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start)); + /* A segment's ids also depend on parse_special when added tokens are matched in its + * normalised text; the cache holds only the parse_special form. */ + if (!use_cache_ || seg.size() < kSegmentCacheMin || (at_start && e.prepend_first) || + (e.has_nspecials && !parse_special)) { + RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start, parse_special)); continue; } const uint64_t h = tok_hash(seg); if (e.cache.lookup(seg, h, out)) continue; const size_t start = out.size(); - RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start)); + RAD_TRY(encode_segment(*v_, e, seg, out, sc, words, at_start, parse_special)); e.cache.insert(seg, h, out.data() + start, out.size() - start); } diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h index e7c5aaae..96a2c822 100644 --- a/core/text/tokenizer.h +++ b/core/text/tokenizer.h @@ -337,6 +337,10 @@ int vocab_serialize(const VocabBuild& in, StringSink& strings, uint64_t section_ int vocab_deserialize(const void* file_base, uint64_t file_bytes, const RadVocabHeader* h, VocabBuild& out); +/* `text` through the normaliser steps of `steps` (the others are skipped), as the encoder runs + * them. RAD_E_UNSUPPORTED when a Replace pattern does not compile. */ +int vocab_normalize(const std::vector& steps, std::string* text); + /* Human-readable one-liner for a step, for --debug-graph and for the convert log. */ std::string step_describe(const VocabStep& s); diff --git a/core/text/tokenizer_grapheme.cpp b/core/text/tokenizer_grapheme.cpp new file mode 100644 index 00000000..a43ef72b --- /dev/null +++ b/core/text/tokenizer_grapheme.cpp @@ -0,0 +1,210 @@ +/* tokenizer_grapheme.cpp -- extended grapheme clusters and the precompiled normaliser + * (tokenizer_grapheme.h). */ +#include "text/tokenizer_grapheme.h" +#include "rad_internal.h" + +#include +#include + +namespace rad { + +namespace { + +enum Gcb : uint32_t { kOther, kCR, kLF, kControl, kExtend, kZWJ, kRI, kPrepend, kSpacingMark, + kL, kV, kT, kLV, kLVT }; +enum InCB : uint32_t { kInNone, kInLinker, kInConsonant, kInExtend }; + +uint32_t lookup(const ucd::GbRange* r, size_t n, uint32_t c) { + size_t lo = 0, hi = n; + while (lo < hi) { + const size_t mid = (lo + hi) / 2; + if (r[mid].last < c) lo = mid + 1; + else hi = mid; + } + return lo < n && r[lo].first <= c ? r[lo].v : 0; +} + +uint32_t gcb(uint32_t c) { return lookup(ucd::k_gcb, ucd::k_gcb_n, c); } +bool pict(uint32_t c) { return lookup(ucd::k_ext_pict, ucd::k_ext_pict_n, c) != 0; } +uint32_t incb(uint32_t c) { return lookup(ucd::k_incb, ucd::k_incb_n, c); } + +/* One codepoint off well-formed UTF-8 at `p`, its byte length in *len. A byte that starts no + * well-formed sequence is taken alone. */ +uint32_t utf8_at(const unsigned char* p, size_t left, size_t* len) { + const unsigned char b = p[0]; + auto cont = [&](size_t k) { return k < left && (p[k] & 0xC0) == 0x80; }; + if (b < 0x80) { *len = 1; return b; } + if ((b & 0xE0) == 0xC0 && cont(1)) { *len = 2; return ((b & 0x1Fu) << 6) | (p[1] & 0x3Fu); } + if ((b & 0xF0) == 0xE0 && cont(1) && cont(2)) { + *len = 3; + return ((b & 0x0Fu) << 12) | ((p[1] & 0x3Fu) << 6) | (p[2] & 0x3Fu); + } + if ((b & 0xF8) == 0xF0 && cont(1) && cont(2) && cont(3)) { + *len = 4; + return ((b & 0x07u) << 18) | ((p[1] & 0x3Fu) << 12) | ((p[2] & 0x3Fu) << 6) | + (p[3] & 0x3Fu); + } + *len = 1; + return 0xFFFD; +} + +int b64_value(char c) { + if (c >= 'A' && c <= 'Z') return c - 'A'; + if (c >= 'a' && c <= 'z') return c - 'a' + 26; + if (c >= '0' && c <= '9') return c - '0' + 52; + if (c == '+') return 62; + if (c == '/') return 63; + return -1; +} + +} /* namespace */ + +/* UAX #29's rules GB3 to GB13 in their order, the lookbehind of GB9c (a conjunct's consonant, + * linker and consonant), GB11 (an emoji ZWJ sequence) and GB12/13 (regional indicator pairs) + * carried as state from the cluster's start, where no such sequence can be cut. */ +size_t grapheme_end(const uint32_t* cps, size_t n, size_t i) { + uint32_t prev = gcb(cps[i]); + /* The text so far ends in Extended_Pictographic Extend*; and did before `prev`. */ + bool ep = pict(cps[i]), ep_before = false; + /* Regional indicators ending at `prev`. */ + int ri = prev == kRI ? 1 : 0; + /* GB9c: 0 nothing, 1 a consonant then Extend/Linker without a linker, 2 with one. */ + int conj = 0; + { + const uint32_t in = incb(cps[i]); + conj = in == kInConsonant ? 1 : 0; + } + size_t j = i + 1; + for (; j < n; ++j) { + const uint32_t c = cps[j], cur = gcb(c); + bool join; + if (prev == kCR && cur == kLF) join = true; /* GB3 */ + else if (prev == kControl || prev == kCR || prev == kLF) join = false; /* GB4 */ + else if (cur == kControl || cur == kCR || cur == kLF) join = false; /* GB5 */ + else if (prev == kL && (cur == kL || cur == kV || cur == kLV || cur == kLVT)) join = true; + else if ((prev == kLV || prev == kV) && (cur == kV || cur == kT)) join = true; /* GB7 */ + else if ((prev == kLVT || prev == kT) && cur == kT) join = true; /* GB8 */ + else if (cur == kExtend || cur == kZWJ) join = true; /* GB9 */ + else if (cur == kSpacingMark) join = true; /* GB9a */ + else if (prev == kPrepend) join = true; /* GB9b */ + else if (conj == 2 && incb(c) == kInConsonant) join = true; /* GB9c */ + else if (prev == kZWJ && ep_before && pict(c)) join = true; /* GB11 */ + else if (prev == kRI && cur == kRI && (ri & 1)) join = true; /* GB12/13 */ + else join = false; + if (!join) break; + ep_before = ep; + ep = pict(c) || (ep && cur == kExtend); + ri = cur == kRI ? ri + 1 : 0; + const uint32_t in = incb(c); + if (in == kInConsonant) conj = 1; + else if (in == kInLinker && conj >= 1) conj = 2; + else if (in == kInExtend && conj >= 1) { /* kept */ } + else conj = 0; + prev = cur; + } + return j; +} + +/* ================================================================== the precompiled map */ +/* The charsmap is a little-endian u32 byte count of the trie, the trie's u32 units (Darts' double + * array), then the replacement strings, each NUL-terminated. */ +int PrecompiledMap::load(std::string_view b64, std::string* why) { + std::string raw; + raw.reserve(b64.size() / 4 * 3); + uint32_t acc = 0; + int bits = 0; + for (char ch : b64) { + if (ch == '=') break; + const int v = b64_value(ch); + if (v < 0) { + if (why) *why = "the precompiled charsmap is not base64"; + return RAD_E_FORMAT; + } + acc = (acc << 6) | (uint32_t)v; + bits += 6; + if (bits >= 8) { + bits -= 8; + raw.push_back((char)((acc >> bits) & 0xFF)); + } + } + if (raw.size() < 4) { + if (why) *why = "the precompiled charsmap is shorter than its header"; + return RAD_E_FORMAT; + } + uint32_t tbytes = 0; + std::memcpy(&tbytes, raw.data(), 4); + if (tbytes % 4 || (size_t)tbytes > raw.size() - 4 || tbytes == 0) { + if (why) *why = "the precompiled charsmap's trie does not fit it"; + return RAD_E_FORMAT; + } + trie_.resize(tbytes / 4); + std::memcpy(trie_.data(), raw.data() + 4, tbytes); + blob_.assign(raw.data() + 4 + tbytes, raw.size() - 4 - tbytes); + return RAD_OK; +} + +bool PrecompiledMap::transform(std::string_view s, std::string_view* out) const { + auto offset = [](uint32_t u) { return (u >> 10) << ((u & (1u << 9)) >> 6); }; + auto label = [](uint32_t u) { return u & ((1u << 31) | 0xFFu); }; + auto leaf = [](uint32_t u) { return ((u >> 8) & 1u) != 0; }; + auto value = [](uint32_t u) { return u & ((1u << 31) - 1); }; + size_t pos = 0; + uint32_t unit = trie_[0]; + pos ^= offset(unit); + for (unsigned char c : s) { + if (c == 0) break; + pos ^= c; + if (pos >= trie_.size()) return false; + unit = trie_[pos]; + if (label(unit) != c) return false; + pos ^= offset(unit); + if (pos >= trie_.size()) return false; + if (leaf(unit)) { + const size_t at = value(trie_[pos]); + if (at >= blob_.size()) return false; + const size_t end = blob_.find('\0', at); + *out = std::string_view(blob_).substr(at, (end == std::string::npos ? blob_.size() + : end) - at); + return true; + } + } + return false; +} + +/* HuggingFace's Precompiled::normalize: a cluster under six bytes goes whole to its shortest + * mapped prefix's replacement when it has one; otherwise each character goes to its own, or + * stays. */ +std::string PrecompiledMap::normalize(std::string_view text) const { + std::vector cps; + std::vector at; + cps.reserve(text.size()); + at.reserve(text.size() + 1); + const unsigned char* p = (const unsigned char*)text.data(); + for (size_t k = 0; k < text.size();) { + size_t len = 1; + cps.push_back(utf8_at(p + k, text.size() - k, &len)); + at.push_back(k); + k += len; + } + at.push_back(text.size()); + std::string out; + out.reserve(text.size()); + std::string_view rep; + for (size_t i = 0; i < cps.size();) { + const size_t e = grapheme_end(cps.data(), cps.size(), i); + const std::string_view g = text.substr(at[i], at[e] - at[i]); + if (g.size() < 6 && transform(g, &rep)) { + out.append(rep); + } else { + for (size_t k = i; k < e; ++k) { + const std::string_view ch = text.substr(at[k], at[k + 1] - at[k]); + if (transform(ch, &rep)) out.append(rep); + else out.append(ch); + } + } + i = e; + } + return out; +} + +} /* namespace rad */ diff --git a/core/text/tokenizer_grapheme.h b/core/text/tokenizer_grapheme.h new file mode 100644 index 00000000..c0109836 --- /dev/null +++ b/core/text/tokenizer_grapheme.h @@ -0,0 +1,56 @@ +/* tokenizer_grapheme.h -- extended grapheme clusters (UAX #29) and SentencePiece's precompiled + * normaliser, which walks its text by them. + * + * HuggingFace tokenizers' `Precompiled` normaliser (a SentencePiece model's `precompiled_charsmap`, + * T5's among them) takes the text one extended grapheme cluster at a time: a cluster shorter than + * six bytes is replaced whole by the mapping of its shortest mapped prefix, if it has one; + * otherwise each of its characters is replaced by its own mapping or kept. The cluster + * boundaries are therefore part of the result, and they are Unicode 16.0.0's, the version the + * reference's segmentation crate implements (tools/gen_grapheme_ucd.py writes the tables). + */ +#pragma once +#include +#include +#include +#include +#include + +namespace rad { + +namespace ucd { +/* A run of codepoints [first, last] holding one value of a property. */ +struct GbRange { uint32_t first, last; uint32_t v; }; +/* Grapheme_Cluster_Break, values in tools/gen_grapheme_ucd.py's GCB order (0 is Other). */ +extern const GbRange k_gcb[]; +extern const size_t k_gcb_n; +/* Extended_Pictographic (v 1). */ +extern const GbRange k_ext_pict[]; +extern const size_t k_ext_pict_n; +/* Indic_Conjunct_Break: 1 Linker, 2 Consonant, 3 Extend (absent: None). */ +extern const GbRange k_incb[]; +extern const size_t k_incb_n; +} /* namespace ucd */ + +/* The end of the extended grapheme cluster that starts at `cps[i]`: the index one past its last + * codepoint. `i < n`. */ +size_t grapheme_end(const uint32_t* cps, size_t n, size_t i); + +/* SentencePiece's precompiled character map: a double-array trie over UTF-8 source strings, each + * leaf the offset of its NUL-terminated replacement in a string blob. */ +class PrecompiledMap { +public: + /* `charsmap_b64` is tokenizer.json's `precompiled_charsmap` as it stands, base64. RAD_OK, or + * RAD_E_FORMAT with `why` for a map that does not decode or whose trie points outside it. */ + int load(std::string_view charsmap_b64, std::string* why); + bool ready() const { return !trie_.empty(); } + /* The normalised text, as HuggingFace's Precompiled normaliser writes it. */ + std::string normalize(std::string_view text) const; + +private: + /* The replacement of the shortest mapped prefix of `s`, or false when no prefix is mapped. */ + bool transform(std::string_view s, std::string_view* out) const; + std::vector trie_; + std::string blob_; +}; + +} /* namespace rad */ diff --git a/core/text/tokenizer_grapheme_ucd.cpp b/core/text/tokenizer_grapheme_ucd.cpp new file mode 100644 index 00000000..a0549450 --- /dev/null +++ b/core/text/tokenizer_grapheme_ucd.cpp @@ -0,0 +1,1878 @@ +/* tokenizer_grapheme_ucd.cpp -- GENERATED by tools/gen_grapheme_ucd.py from the Unicode 16.0.0 UCD; + * do not edit. The properties UAX #29's extended grapheme cluster rules read (tokenizer_grapheme.h). */ +#include "text/tokenizer_grapheme.h" + +namespace rad { +namespace ucd { + +const GbRange k_gcb[] = { + { 0x0, 0x9, 3 }, + { 0xA, 0xA, 2 }, + { 0xB, 0xC, 3 }, + { 0xD, 0xD, 1 }, + { 0xE, 0x1F, 3 }, + { 0x7F, 0x9F, 3 }, + { 0xAD, 0xAD, 3 }, + { 0x300, 0x36F, 4 }, + { 0x483, 0x489, 4 }, + { 0x591, 0x5BD, 4 }, + { 0x5BF, 0x5BF, 4 }, + { 0x5C1, 0x5C2, 4 }, + { 0x5C4, 0x5C5, 4 }, + { 0x5C7, 0x5C7, 4 }, + { 0x600, 0x605, 7 }, + { 0x610, 0x61A, 4 }, + { 0x61C, 0x61C, 3 }, + { 0x64B, 0x65F, 4 }, + { 0x670, 0x670, 4 }, + { 0x6D6, 0x6DC, 4 }, + { 0x6DD, 0x6DD, 7 }, + { 0x6DF, 0x6E4, 4 }, + { 0x6E7, 0x6E8, 4 }, + { 0x6EA, 0x6ED, 4 }, + { 0x70F, 0x70F, 7 }, + { 0x711, 0x711, 4 }, + { 0x730, 0x74A, 4 }, + { 0x7A6, 0x7B0, 4 }, + { 0x7EB, 0x7F3, 4 }, + { 0x7FD, 0x7FD, 4 }, + { 0x816, 0x819, 4 }, + { 0x81B, 0x823, 4 }, + { 0x825, 0x827, 4 }, + { 0x829, 0x82D, 4 }, + { 0x859, 0x85B, 4 }, + { 0x890, 0x891, 7 }, + { 0x897, 0x89F, 4 }, + { 0x8CA, 0x8E1, 4 }, + { 0x8E2, 0x8E2, 7 }, + { 0x8E3, 0x902, 4 }, + { 0x903, 0x903, 8 }, + { 0x93A, 0x93A, 4 }, + { 0x93B, 0x93B, 8 }, + { 0x93C, 0x93C, 4 }, + { 0x93E, 0x940, 8 }, + { 0x941, 0x948, 4 }, + { 0x949, 0x94C, 8 }, + { 0x94D, 0x94D, 4 }, + { 0x94E, 0x94F, 8 }, + { 0x951, 0x957, 4 }, + { 0x962, 0x963, 4 }, + { 0x981, 0x981, 4 }, + { 0x982, 0x983, 8 }, + { 0x9BC, 0x9BC, 4 }, + { 0x9BE, 0x9BE, 4 }, + { 0x9BF, 0x9C0, 8 }, + { 0x9C1, 0x9C4, 4 }, + { 0x9C7, 0x9C8, 8 }, + { 0x9CB, 0x9CC, 8 }, + { 0x9CD, 0x9CD, 4 }, + { 0x9D7, 0x9D7, 4 }, + { 0x9E2, 0x9E3, 4 }, + { 0x9FE, 0x9FE, 4 }, + { 0xA01, 0xA02, 4 }, + { 0xA03, 0xA03, 8 }, + { 0xA3C, 0xA3C, 4 }, + { 0xA3E, 0xA40, 8 }, + { 0xA41, 0xA42, 4 }, + { 0xA47, 0xA48, 4 }, + { 0xA4B, 0xA4D, 4 }, + { 0xA51, 0xA51, 4 }, + { 0xA70, 0xA71, 4 }, + { 0xA75, 0xA75, 4 }, + { 0xA81, 0xA82, 4 }, + { 0xA83, 0xA83, 8 }, + { 0xABC, 0xABC, 4 }, + { 0xABE, 0xAC0, 8 }, + { 0xAC1, 0xAC5, 4 }, + { 0xAC7, 0xAC8, 4 }, + { 0xAC9, 0xAC9, 8 }, + { 0xACB, 0xACC, 8 }, + { 0xACD, 0xACD, 4 }, + { 0xAE2, 0xAE3, 4 }, + { 0xAFA, 0xAFF, 4 }, + { 0xB01, 0xB01, 4 }, + { 0xB02, 0xB03, 8 }, + { 0xB3C, 0xB3C, 4 }, + { 0xB3E, 0xB3F, 4 }, + { 0xB40, 0xB40, 8 }, + { 0xB41, 0xB44, 4 }, + { 0xB47, 0xB48, 8 }, + { 0xB4B, 0xB4C, 8 }, + { 0xB4D, 0xB4D, 4 }, + { 0xB55, 0xB57, 4 }, + { 0xB62, 0xB63, 4 }, + { 0xB82, 0xB82, 4 }, + { 0xBBE, 0xBBE, 4 }, + { 0xBBF, 0xBBF, 8 }, + { 0xBC0, 0xBC0, 4 }, + { 0xBC1, 0xBC2, 8 }, + { 0xBC6, 0xBC8, 8 }, + { 0xBCA, 0xBCC, 8 }, + { 0xBCD, 0xBCD, 4 }, + { 0xBD7, 0xBD7, 4 }, + { 0xC00, 0xC00, 4 }, + { 0xC01, 0xC03, 8 }, + { 0xC04, 0xC04, 4 }, + { 0xC3C, 0xC3C, 4 }, + { 0xC3E, 0xC40, 4 }, + { 0xC41, 0xC44, 8 }, + { 0xC46, 0xC48, 4 }, + { 0xC4A, 0xC4D, 4 }, + { 0xC55, 0xC56, 4 }, + { 0xC62, 0xC63, 4 }, + { 0xC81, 0xC81, 4 }, + { 0xC82, 0xC83, 8 }, + { 0xCBC, 0xCBC, 4 }, + { 0xCBE, 0xCBE, 8 }, + { 0xCBF, 0xCC0, 4 }, + { 0xCC1, 0xCC1, 8 }, + { 0xCC2, 0xCC2, 4 }, + { 0xCC3, 0xCC4, 8 }, + { 0xCC6, 0xCC8, 4 }, + { 0xCCA, 0xCCD, 4 }, + { 0xCD5, 0xCD6, 4 }, + { 0xCE2, 0xCE3, 4 }, + { 0xCF3, 0xCF3, 8 }, + { 0xD00, 0xD01, 4 }, + { 0xD02, 0xD03, 8 }, + { 0xD3B, 0xD3C, 4 }, + { 0xD3E, 0xD3E, 4 }, + { 0xD3F, 0xD40, 8 }, + { 0xD41, 0xD44, 4 }, + { 0xD46, 0xD48, 8 }, + { 0xD4A, 0xD4C, 8 }, + { 0xD4D, 0xD4D, 4 }, + { 0xD4E, 0xD4E, 7 }, + { 0xD57, 0xD57, 4 }, + { 0xD62, 0xD63, 4 }, + { 0xD81, 0xD81, 4 }, + { 0xD82, 0xD83, 8 }, + { 0xDCA, 0xDCA, 4 }, + { 0xDCF, 0xDCF, 4 }, + { 0xDD0, 0xDD1, 8 }, + { 0xDD2, 0xDD4, 4 }, + { 0xDD6, 0xDD6, 4 }, + { 0xDD8, 0xDDE, 8 }, + { 0xDDF, 0xDDF, 4 }, + { 0xDF2, 0xDF3, 8 }, + { 0xE31, 0xE31, 4 }, + { 0xE33, 0xE33, 8 }, + { 0xE34, 0xE3A, 4 }, + { 0xE47, 0xE4E, 4 }, + { 0xEB1, 0xEB1, 4 }, + { 0xEB3, 0xEB3, 8 }, + { 0xEB4, 0xEBC, 4 }, + { 0xEC8, 0xECE, 4 }, + { 0xF18, 0xF19, 4 }, + { 0xF35, 0xF35, 4 }, + { 0xF37, 0xF37, 4 }, + { 0xF39, 0xF39, 4 }, + { 0xF3E, 0xF3F, 8 }, + { 0xF71, 0xF7E, 4 }, + { 0xF7F, 0xF7F, 8 }, + { 0xF80, 0xF84, 4 }, + { 0xF86, 0xF87, 4 }, + { 0xF8D, 0xF97, 4 }, + { 0xF99, 0xFBC, 4 }, + { 0xFC6, 0xFC6, 4 }, + { 0x102D, 0x1030, 4 }, + { 0x1031, 0x1031, 8 }, + { 0x1032, 0x1037, 4 }, + { 0x1039, 0x103A, 4 }, + { 0x103B, 0x103C, 8 }, + { 0x103D, 0x103E, 4 }, + { 0x1056, 0x1057, 8 }, + { 0x1058, 0x1059, 4 }, + { 0x105E, 0x1060, 4 }, + { 0x1071, 0x1074, 4 }, + { 0x1082, 0x1082, 4 }, + { 0x1084, 0x1084, 8 }, + { 0x1085, 0x1086, 4 }, + { 0x108D, 0x108D, 4 }, + { 0x109D, 0x109D, 4 }, + { 0x1100, 0x115F, 9 }, + { 0x1160, 0x11A7, 10 }, + { 0x11A8, 0x11FF, 11 }, + { 0x135D, 0x135F, 4 }, + { 0x1712, 0x1715, 4 }, + { 0x1732, 0x1734, 4 }, + { 0x1752, 0x1753, 4 }, + { 0x1772, 0x1773, 4 }, + { 0x17B4, 0x17B5, 4 }, + { 0x17B6, 0x17B6, 8 }, + { 0x17B7, 0x17BD, 4 }, + { 0x17BE, 0x17C5, 8 }, + { 0x17C6, 0x17C6, 4 }, + { 0x17C7, 0x17C8, 8 }, + { 0x17C9, 0x17D3, 4 }, + { 0x17DD, 0x17DD, 4 }, + { 0x180B, 0x180D, 4 }, + { 0x180E, 0x180E, 3 }, + { 0x180F, 0x180F, 4 }, + { 0x1885, 0x1886, 4 }, + { 0x18A9, 0x18A9, 4 }, + { 0x1920, 0x1922, 4 }, + { 0x1923, 0x1926, 8 }, + { 0x1927, 0x1928, 4 }, + { 0x1929, 0x192B, 8 }, + { 0x1930, 0x1931, 8 }, + { 0x1932, 0x1932, 4 }, + { 0x1933, 0x1938, 8 }, + { 0x1939, 0x193B, 4 }, + { 0x1A17, 0x1A18, 4 }, + { 0x1A19, 0x1A1A, 8 }, + { 0x1A1B, 0x1A1B, 4 }, + { 0x1A55, 0x1A55, 8 }, + { 0x1A56, 0x1A56, 4 }, + { 0x1A57, 0x1A57, 8 }, + { 0x1A58, 0x1A5E, 4 }, + { 0x1A60, 0x1A60, 4 }, + { 0x1A62, 0x1A62, 4 }, + { 0x1A65, 0x1A6C, 4 }, + { 0x1A6D, 0x1A72, 8 }, + { 0x1A73, 0x1A7C, 4 }, + { 0x1A7F, 0x1A7F, 4 }, + { 0x1AB0, 0x1ACE, 4 }, + { 0x1B00, 0x1B03, 4 }, + { 0x1B04, 0x1B04, 8 }, + { 0x1B34, 0x1B3D, 4 }, + { 0x1B3E, 0x1B41, 8 }, + { 0x1B42, 0x1B44, 4 }, + { 0x1B6B, 0x1B73, 4 }, + { 0x1B80, 0x1B81, 4 }, + { 0x1B82, 0x1B82, 8 }, + { 0x1BA1, 0x1BA1, 8 }, + { 0x1BA2, 0x1BA5, 4 }, + { 0x1BA6, 0x1BA7, 8 }, + { 0x1BA8, 0x1BAD, 4 }, + { 0x1BE6, 0x1BE6, 4 }, + { 0x1BE7, 0x1BE7, 8 }, + { 0x1BE8, 0x1BE9, 4 }, + { 0x1BEA, 0x1BEC, 8 }, + { 0x1BED, 0x1BED, 4 }, + { 0x1BEE, 0x1BEE, 8 }, + { 0x1BEF, 0x1BF3, 4 }, + { 0x1C24, 0x1C2B, 8 }, + { 0x1C2C, 0x1C33, 4 }, + { 0x1C34, 0x1C35, 8 }, + { 0x1C36, 0x1C37, 4 }, + { 0x1CD0, 0x1CD2, 4 }, + { 0x1CD4, 0x1CE0, 4 }, + { 0x1CE1, 0x1CE1, 8 }, + { 0x1CE2, 0x1CE8, 4 }, + { 0x1CED, 0x1CED, 4 }, + { 0x1CF4, 0x1CF4, 4 }, + { 0x1CF7, 0x1CF7, 8 }, + { 0x1CF8, 0x1CF9, 4 }, + { 0x1DC0, 0x1DFF, 4 }, + { 0x200B, 0x200B, 3 }, + { 0x200C, 0x200C, 4 }, + { 0x200D, 0x200D, 5 }, + { 0x200E, 0x200F, 3 }, + { 0x2028, 0x202E, 3 }, + { 0x2060, 0x206F, 3 }, + { 0x20D0, 0x20F0, 4 }, + { 0x2CEF, 0x2CF1, 4 }, + { 0x2D7F, 0x2D7F, 4 }, + { 0x2DE0, 0x2DFF, 4 }, + { 0x302A, 0x302F, 4 }, + { 0x3099, 0x309A, 4 }, + { 0xA66F, 0xA672, 4 }, + { 0xA674, 0xA67D, 4 }, + { 0xA69E, 0xA69F, 4 }, + { 0xA6F0, 0xA6F1, 4 }, + { 0xA802, 0xA802, 4 }, + { 0xA806, 0xA806, 4 }, + { 0xA80B, 0xA80B, 4 }, + { 0xA823, 0xA824, 8 }, + { 0xA825, 0xA826, 4 }, + { 0xA827, 0xA827, 8 }, + { 0xA82C, 0xA82C, 4 }, + { 0xA880, 0xA881, 8 }, + { 0xA8B4, 0xA8C3, 8 }, + { 0xA8C4, 0xA8C5, 4 }, + { 0xA8E0, 0xA8F1, 4 }, + { 0xA8FF, 0xA8FF, 4 }, + { 0xA926, 0xA92D, 4 }, + { 0xA947, 0xA951, 4 }, + { 0xA952, 0xA952, 8 }, + { 0xA953, 0xA953, 4 }, + { 0xA960, 0xA97C, 9 }, + { 0xA980, 0xA982, 4 }, + { 0xA983, 0xA983, 8 }, + { 0xA9B3, 0xA9B3, 4 }, + { 0xA9B4, 0xA9B5, 8 }, + { 0xA9B6, 0xA9B9, 4 }, + { 0xA9BA, 0xA9BB, 8 }, + { 0xA9BC, 0xA9BD, 4 }, + { 0xA9BE, 0xA9BF, 8 }, + { 0xA9C0, 0xA9C0, 4 }, + { 0xA9E5, 0xA9E5, 4 }, + { 0xAA29, 0xAA2E, 4 }, + { 0xAA2F, 0xAA30, 8 }, + { 0xAA31, 0xAA32, 4 }, + { 0xAA33, 0xAA34, 8 }, + { 0xAA35, 0xAA36, 4 }, + { 0xAA43, 0xAA43, 4 }, + { 0xAA4C, 0xAA4C, 4 }, + { 0xAA4D, 0xAA4D, 8 }, + { 0xAA7C, 0xAA7C, 4 }, + { 0xAAB0, 0xAAB0, 4 }, + { 0xAAB2, 0xAAB4, 4 }, + { 0xAAB7, 0xAAB8, 4 }, + { 0xAABE, 0xAABF, 4 }, + { 0xAAC1, 0xAAC1, 4 }, + { 0xAAEB, 0xAAEB, 8 }, + { 0xAAEC, 0xAAED, 4 }, + { 0xAAEE, 0xAAEF, 8 }, + { 0xAAF5, 0xAAF5, 8 }, + { 0xAAF6, 0xAAF6, 4 }, + { 0xABE3, 0xABE4, 8 }, + { 0xABE5, 0xABE5, 4 }, + { 0xABE6, 0xABE7, 8 }, + { 0xABE8, 0xABE8, 4 }, + { 0xABE9, 0xABEA, 8 }, + { 0xABEC, 0xABEC, 8 }, + { 0xABED, 0xABED, 4 }, + { 0xAC00, 0xAC00, 12 }, + { 0xAC01, 0xAC1B, 13 }, + { 0xAC1C, 0xAC1C, 12 }, + { 0xAC1D, 0xAC37, 13 }, + { 0xAC38, 0xAC38, 12 }, + { 0xAC39, 0xAC53, 13 }, + { 0xAC54, 0xAC54, 12 }, + { 0xAC55, 0xAC6F, 13 }, + { 0xAC70, 0xAC70, 12 }, + { 0xAC71, 0xAC8B, 13 }, + { 0xAC8C, 0xAC8C, 12 }, + { 0xAC8D, 0xACA7, 13 }, + { 0xACA8, 0xACA8, 12 }, + { 0xACA9, 0xACC3, 13 }, + { 0xACC4, 0xACC4, 12 }, + { 0xACC5, 0xACDF, 13 }, + { 0xACE0, 0xACE0, 12 }, + { 0xACE1, 0xACFB, 13 }, + { 0xACFC, 0xACFC, 12 }, + { 0xACFD, 0xAD17, 13 }, + { 0xAD18, 0xAD18, 12 }, + { 0xAD19, 0xAD33, 13 }, + { 0xAD34, 0xAD34, 12 }, + { 0xAD35, 0xAD4F, 13 }, + { 0xAD50, 0xAD50, 12 }, + { 0xAD51, 0xAD6B, 13 }, + { 0xAD6C, 0xAD6C, 12 }, + { 0xAD6D, 0xAD87, 13 }, + { 0xAD88, 0xAD88, 12 }, + { 0xAD89, 0xADA3, 13 }, + { 0xADA4, 0xADA4, 12 }, + { 0xADA5, 0xADBF, 13 }, + { 0xADC0, 0xADC0, 12 }, + { 0xADC1, 0xADDB, 13 }, + { 0xADDC, 0xADDC, 12 }, + { 0xADDD, 0xADF7, 13 }, + { 0xADF8, 0xADF8, 12 }, + { 0xADF9, 0xAE13, 13 }, + { 0xAE14, 0xAE14, 12 }, + { 0xAE15, 0xAE2F, 13 }, + { 0xAE30, 0xAE30, 12 }, + { 0xAE31, 0xAE4B, 13 }, + { 0xAE4C, 0xAE4C, 12 }, + { 0xAE4D, 0xAE67, 13 }, + { 0xAE68, 0xAE68, 12 }, + { 0xAE69, 0xAE83, 13 }, + { 0xAE84, 0xAE84, 12 }, + { 0xAE85, 0xAE9F, 13 }, + { 0xAEA0, 0xAEA0, 12 }, + { 0xAEA1, 0xAEBB, 13 }, + { 0xAEBC, 0xAEBC, 12 }, + { 0xAEBD, 0xAED7, 13 }, + { 0xAED8, 0xAED8, 12 }, + { 0xAED9, 0xAEF3, 13 }, + { 0xAEF4, 0xAEF4, 12 }, + { 0xAEF5, 0xAF0F, 13 }, + { 0xAF10, 0xAF10, 12 }, + { 0xAF11, 0xAF2B, 13 }, + { 0xAF2C, 0xAF2C, 12 }, + { 0xAF2D, 0xAF47, 13 }, + { 0xAF48, 0xAF48, 12 }, + { 0xAF49, 0xAF63, 13 }, + { 0xAF64, 0xAF64, 12 }, + { 0xAF65, 0xAF7F, 13 }, + { 0xAF80, 0xAF80, 12 }, + { 0xAF81, 0xAF9B, 13 }, + { 0xAF9C, 0xAF9C, 12 }, + { 0xAF9D, 0xAFB7, 13 }, + { 0xAFB8, 0xAFB8, 12 }, + { 0xAFB9, 0xAFD3, 13 }, + { 0xAFD4, 0xAFD4, 12 }, + { 0xAFD5, 0xAFEF, 13 }, + { 0xAFF0, 0xAFF0, 12 }, + { 0xAFF1, 0xB00B, 13 }, + { 0xB00C, 0xB00C, 12 }, + { 0xB00D, 0xB027, 13 }, + { 0xB028, 0xB028, 12 }, + { 0xB029, 0xB043, 13 }, + { 0xB044, 0xB044, 12 }, + { 0xB045, 0xB05F, 13 }, + { 0xB060, 0xB060, 12 }, + { 0xB061, 0xB07B, 13 }, + { 0xB07C, 0xB07C, 12 }, + { 0xB07D, 0xB097, 13 }, + { 0xB098, 0xB098, 12 }, + { 0xB099, 0xB0B3, 13 }, + { 0xB0B4, 0xB0B4, 12 }, + { 0xB0B5, 0xB0CF, 13 }, + { 0xB0D0, 0xB0D0, 12 }, + { 0xB0D1, 0xB0EB, 13 }, + { 0xB0EC, 0xB0EC, 12 }, + { 0xB0ED, 0xB107, 13 }, + { 0xB108, 0xB108, 12 }, + { 0xB109, 0xB123, 13 }, + { 0xB124, 0xB124, 12 }, + { 0xB125, 0xB13F, 13 }, + { 0xB140, 0xB140, 12 }, + { 0xB141, 0xB15B, 13 }, + { 0xB15C, 0xB15C, 12 }, + { 0xB15D, 0xB177, 13 }, + { 0xB178, 0xB178, 12 }, + { 0xB179, 0xB193, 13 }, + { 0xB194, 0xB194, 12 }, + { 0xB195, 0xB1AF, 13 }, + { 0xB1B0, 0xB1B0, 12 }, + { 0xB1B1, 0xB1CB, 13 }, + { 0xB1CC, 0xB1CC, 12 }, + { 0xB1CD, 0xB1E7, 13 }, + { 0xB1E8, 0xB1E8, 12 }, + { 0xB1E9, 0xB203, 13 }, + { 0xB204, 0xB204, 12 }, + { 0xB205, 0xB21F, 13 }, + { 0xB220, 0xB220, 12 }, + { 0xB221, 0xB23B, 13 }, + { 0xB23C, 0xB23C, 12 }, + { 0xB23D, 0xB257, 13 }, + { 0xB258, 0xB258, 12 }, + { 0xB259, 0xB273, 13 }, + { 0xB274, 0xB274, 12 }, + { 0xB275, 0xB28F, 13 }, + { 0xB290, 0xB290, 12 }, + { 0xB291, 0xB2AB, 13 }, + { 0xB2AC, 0xB2AC, 12 }, + { 0xB2AD, 0xB2C7, 13 }, + { 0xB2C8, 0xB2C8, 12 }, + { 0xB2C9, 0xB2E3, 13 }, + { 0xB2E4, 0xB2E4, 12 }, + { 0xB2E5, 0xB2FF, 13 }, + { 0xB300, 0xB300, 12 }, + { 0xB301, 0xB31B, 13 }, + { 0xB31C, 0xB31C, 12 }, + { 0xB31D, 0xB337, 13 }, + { 0xB338, 0xB338, 12 }, + { 0xB339, 0xB353, 13 }, + { 0xB354, 0xB354, 12 }, + { 0xB355, 0xB36F, 13 }, + { 0xB370, 0xB370, 12 }, + { 0xB371, 0xB38B, 13 }, + { 0xB38C, 0xB38C, 12 }, + { 0xB38D, 0xB3A7, 13 }, + { 0xB3A8, 0xB3A8, 12 }, + { 0xB3A9, 0xB3C3, 13 }, + { 0xB3C4, 0xB3C4, 12 }, + { 0xB3C5, 0xB3DF, 13 }, + { 0xB3E0, 0xB3E0, 12 }, + { 0xB3E1, 0xB3FB, 13 }, + { 0xB3FC, 0xB3FC, 12 }, + { 0xB3FD, 0xB417, 13 }, + { 0xB418, 0xB418, 12 }, + { 0xB419, 0xB433, 13 }, + { 0xB434, 0xB434, 12 }, + { 0xB435, 0xB44F, 13 }, + { 0xB450, 0xB450, 12 }, + { 0xB451, 0xB46B, 13 }, + { 0xB46C, 0xB46C, 12 }, + { 0xB46D, 0xB487, 13 }, + { 0xB488, 0xB488, 12 }, + { 0xB489, 0xB4A3, 13 }, + { 0xB4A4, 0xB4A4, 12 }, + { 0xB4A5, 0xB4BF, 13 }, + { 0xB4C0, 0xB4C0, 12 }, + { 0xB4C1, 0xB4DB, 13 }, + { 0xB4DC, 0xB4DC, 12 }, + { 0xB4DD, 0xB4F7, 13 }, + { 0xB4F8, 0xB4F8, 12 }, + { 0xB4F9, 0xB513, 13 }, + { 0xB514, 0xB514, 12 }, + { 0xB515, 0xB52F, 13 }, + { 0xB530, 0xB530, 12 }, + { 0xB531, 0xB54B, 13 }, + { 0xB54C, 0xB54C, 12 }, + { 0xB54D, 0xB567, 13 }, + { 0xB568, 0xB568, 12 }, + { 0xB569, 0xB583, 13 }, + { 0xB584, 0xB584, 12 }, + { 0xB585, 0xB59F, 13 }, + { 0xB5A0, 0xB5A0, 12 }, + { 0xB5A1, 0xB5BB, 13 }, + { 0xB5BC, 0xB5BC, 12 }, + { 0xB5BD, 0xB5D7, 13 }, + { 0xB5D8, 0xB5D8, 12 }, + { 0xB5D9, 0xB5F3, 13 }, + { 0xB5F4, 0xB5F4, 12 }, + { 0xB5F5, 0xB60F, 13 }, + { 0xB610, 0xB610, 12 }, + { 0xB611, 0xB62B, 13 }, + { 0xB62C, 0xB62C, 12 }, + { 0xB62D, 0xB647, 13 }, + { 0xB648, 0xB648, 12 }, + { 0xB649, 0xB663, 13 }, + { 0xB664, 0xB664, 12 }, + { 0xB665, 0xB67F, 13 }, + { 0xB680, 0xB680, 12 }, + { 0xB681, 0xB69B, 13 }, + { 0xB69C, 0xB69C, 12 }, + { 0xB69D, 0xB6B7, 13 }, + { 0xB6B8, 0xB6B8, 12 }, + { 0xB6B9, 0xB6D3, 13 }, + { 0xB6D4, 0xB6D4, 12 }, + { 0xB6D5, 0xB6EF, 13 }, + { 0xB6F0, 0xB6F0, 12 }, + { 0xB6F1, 0xB70B, 13 }, + { 0xB70C, 0xB70C, 12 }, + { 0xB70D, 0xB727, 13 }, + { 0xB728, 0xB728, 12 }, + { 0xB729, 0xB743, 13 }, + { 0xB744, 0xB744, 12 }, + { 0xB745, 0xB75F, 13 }, + { 0xB760, 0xB760, 12 }, + { 0xB761, 0xB77B, 13 }, + { 0xB77C, 0xB77C, 12 }, + { 0xB77D, 0xB797, 13 }, + { 0xB798, 0xB798, 12 }, + { 0xB799, 0xB7B3, 13 }, + { 0xB7B4, 0xB7B4, 12 }, + { 0xB7B5, 0xB7CF, 13 }, + { 0xB7D0, 0xB7D0, 12 }, + { 0xB7D1, 0xB7EB, 13 }, + { 0xB7EC, 0xB7EC, 12 }, + { 0xB7ED, 0xB807, 13 }, + { 0xB808, 0xB808, 12 }, + { 0xB809, 0xB823, 13 }, + { 0xB824, 0xB824, 12 }, + { 0xB825, 0xB83F, 13 }, + { 0xB840, 0xB840, 12 }, + { 0xB841, 0xB85B, 13 }, + { 0xB85C, 0xB85C, 12 }, + { 0xB85D, 0xB877, 13 }, + { 0xB878, 0xB878, 12 }, + { 0xB879, 0xB893, 13 }, + { 0xB894, 0xB894, 12 }, + { 0xB895, 0xB8AF, 13 }, + { 0xB8B0, 0xB8B0, 12 }, + { 0xB8B1, 0xB8CB, 13 }, + { 0xB8CC, 0xB8CC, 12 }, + { 0xB8CD, 0xB8E7, 13 }, + { 0xB8E8, 0xB8E8, 12 }, + { 0xB8E9, 0xB903, 13 }, + { 0xB904, 0xB904, 12 }, + { 0xB905, 0xB91F, 13 }, + { 0xB920, 0xB920, 12 }, + { 0xB921, 0xB93B, 13 }, + { 0xB93C, 0xB93C, 12 }, + { 0xB93D, 0xB957, 13 }, + { 0xB958, 0xB958, 12 }, + { 0xB959, 0xB973, 13 }, + { 0xB974, 0xB974, 12 }, + { 0xB975, 0xB98F, 13 }, + { 0xB990, 0xB990, 12 }, + { 0xB991, 0xB9AB, 13 }, + { 0xB9AC, 0xB9AC, 12 }, + { 0xB9AD, 0xB9C7, 13 }, + { 0xB9C8, 0xB9C8, 12 }, + { 0xB9C9, 0xB9E3, 13 }, + { 0xB9E4, 0xB9E4, 12 }, + { 0xB9E5, 0xB9FF, 13 }, + { 0xBA00, 0xBA00, 12 }, + { 0xBA01, 0xBA1B, 13 }, + { 0xBA1C, 0xBA1C, 12 }, + { 0xBA1D, 0xBA37, 13 }, + { 0xBA38, 0xBA38, 12 }, + { 0xBA39, 0xBA53, 13 }, + { 0xBA54, 0xBA54, 12 }, + { 0xBA55, 0xBA6F, 13 }, + { 0xBA70, 0xBA70, 12 }, + { 0xBA71, 0xBA8B, 13 }, + { 0xBA8C, 0xBA8C, 12 }, + { 0xBA8D, 0xBAA7, 13 }, + { 0xBAA8, 0xBAA8, 12 }, + { 0xBAA9, 0xBAC3, 13 }, + { 0xBAC4, 0xBAC4, 12 }, + { 0xBAC5, 0xBADF, 13 }, + { 0xBAE0, 0xBAE0, 12 }, + { 0xBAE1, 0xBAFB, 13 }, + { 0xBAFC, 0xBAFC, 12 }, + { 0xBAFD, 0xBB17, 13 }, + { 0xBB18, 0xBB18, 12 }, + { 0xBB19, 0xBB33, 13 }, + { 0xBB34, 0xBB34, 12 }, + { 0xBB35, 0xBB4F, 13 }, + { 0xBB50, 0xBB50, 12 }, + { 0xBB51, 0xBB6B, 13 }, + { 0xBB6C, 0xBB6C, 12 }, + { 0xBB6D, 0xBB87, 13 }, + { 0xBB88, 0xBB88, 12 }, + { 0xBB89, 0xBBA3, 13 }, + { 0xBBA4, 0xBBA4, 12 }, + { 0xBBA5, 0xBBBF, 13 }, + { 0xBBC0, 0xBBC0, 12 }, + { 0xBBC1, 0xBBDB, 13 }, + { 0xBBDC, 0xBBDC, 12 }, + { 0xBBDD, 0xBBF7, 13 }, + { 0xBBF8, 0xBBF8, 12 }, + { 0xBBF9, 0xBC13, 13 }, + { 0xBC14, 0xBC14, 12 }, + { 0xBC15, 0xBC2F, 13 }, + { 0xBC30, 0xBC30, 12 }, + { 0xBC31, 0xBC4B, 13 }, + { 0xBC4C, 0xBC4C, 12 }, + { 0xBC4D, 0xBC67, 13 }, + { 0xBC68, 0xBC68, 12 }, + { 0xBC69, 0xBC83, 13 }, + { 0xBC84, 0xBC84, 12 }, + { 0xBC85, 0xBC9F, 13 }, + { 0xBCA0, 0xBCA0, 12 }, + { 0xBCA1, 0xBCBB, 13 }, + { 0xBCBC, 0xBCBC, 12 }, + { 0xBCBD, 0xBCD7, 13 }, + { 0xBCD8, 0xBCD8, 12 }, + { 0xBCD9, 0xBCF3, 13 }, + { 0xBCF4, 0xBCF4, 12 }, + { 0xBCF5, 0xBD0F, 13 }, + { 0xBD10, 0xBD10, 12 }, + { 0xBD11, 0xBD2B, 13 }, + { 0xBD2C, 0xBD2C, 12 }, + { 0xBD2D, 0xBD47, 13 }, + { 0xBD48, 0xBD48, 12 }, + { 0xBD49, 0xBD63, 13 }, + { 0xBD64, 0xBD64, 12 }, + { 0xBD65, 0xBD7F, 13 }, + { 0xBD80, 0xBD80, 12 }, + { 0xBD81, 0xBD9B, 13 }, + { 0xBD9C, 0xBD9C, 12 }, + { 0xBD9D, 0xBDB7, 13 }, + { 0xBDB8, 0xBDB8, 12 }, + { 0xBDB9, 0xBDD3, 13 }, + { 0xBDD4, 0xBDD4, 12 }, + { 0xBDD5, 0xBDEF, 13 }, + { 0xBDF0, 0xBDF0, 12 }, + { 0xBDF1, 0xBE0B, 13 }, + { 0xBE0C, 0xBE0C, 12 }, + { 0xBE0D, 0xBE27, 13 }, + { 0xBE28, 0xBE28, 12 }, + { 0xBE29, 0xBE43, 13 }, + { 0xBE44, 0xBE44, 12 }, + { 0xBE45, 0xBE5F, 13 }, + { 0xBE60, 0xBE60, 12 }, + { 0xBE61, 0xBE7B, 13 }, + { 0xBE7C, 0xBE7C, 12 }, + { 0xBE7D, 0xBE97, 13 }, + { 0xBE98, 0xBE98, 12 }, + { 0xBE99, 0xBEB3, 13 }, + { 0xBEB4, 0xBEB4, 12 }, + { 0xBEB5, 0xBECF, 13 }, + { 0xBED0, 0xBED0, 12 }, + { 0xBED1, 0xBEEB, 13 }, + { 0xBEEC, 0xBEEC, 12 }, + { 0xBEED, 0xBF07, 13 }, + { 0xBF08, 0xBF08, 12 }, + { 0xBF09, 0xBF23, 13 }, + { 0xBF24, 0xBF24, 12 }, + { 0xBF25, 0xBF3F, 13 }, + { 0xBF40, 0xBF40, 12 }, + { 0xBF41, 0xBF5B, 13 }, + { 0xBF5C, 0xBF5C, 12 }, + { 0xBF5D, 0xBF77, 13 }, + { 0xBF78, 0xBF78, 12 }, + { 0xBF79, 0xBF93, 13 }, + { 0xBF94, 0xBF94, 12 }, + { 0xBF95, 0xBFAF, 13 }, + { 0xBFB0, 0xBFB0, 12 }, + { 0xBFB1, 0xBFCB, 13 }, + { 0xBFCC, 0xBFCC, 12 }, + { 0xBFCD, 0xBFE7, 13 }, + { 0xBFE8, 0xBFE8, 12 }, + { 0xBFE9, 0xC003, 13 }, + { 0xC004, 0xC004, 12 }, + { 0xC005, 0xC01F, 13 }, + { 0xC020, 0xC020, 12 }, + { 0xC021, 0xC03B, 13 }, + { 0xC03C, 0xC03C, 12 }, + { 0xC03D, 0xC057, 13 }, + { 0xC058, 0xC058, 12 }, + { 0xC059, 0xC073, 13 }, + { 0xC074, 0xC074, 12 }, + { 0xC075, 0xC08F, 13 }, + { 0xC090, 0xC090, 12 }, + { 0xC091, 0xC0AB, 13 }, + { 0xC0AC, 0xC0AC, 12 }, + { 0xC0AD, 0xC0C7, 13 }, + { 0xC0C8, 0xC0C8, 12 }, + { 0xC0C9, 0xC0E3, 13 }, + { 0xC0E4, 0xC0E4, 12 }, + { 0xC0E5, 0xC0FF, 13 }, + { 0xC100, 0xC100, 12 }, + { 0xC101, 0xC11B, 13 }, + { 0xC11C, 0xC11C, 12 }, + { 0xC11D, 0xC137, 13 }, + { 0xC138, 0xC138, 12 }, + { 0xC139, 0xC153, 13 }, + { 0xC154, 0xC154, 12 }, + { 0xC155, 0xC16F, 13 }, + { 0xC170, 0xC170, 12 }, + { 0xC171, 0xC18B, 13 }, + { 0xC18C, 0xC18C, 12 }, + { 0xC18D, 0xC1A7, 13 }, + { 0xC1A8, 0xC1A8, 12 }, + { 0xC1A9, 0xC1C3, 13 }, + { 0xC1C4, 0xC1C4, 12 }, + { 0xC1C5, 0xC1DF, 13 }, + { 0xC1E0, 0xC1E0, 12 }, + { 0xC1E1, 0xC1FB, 13 }, + { 0xC1FC, 0xC1FC, 12 }, + { 0xC1FD, 0xC217, 13 }, + { 0xC218, 0xC218, 12 }, + { 0xC219, 0xC233, 13 }, + { 0xC234, 0xC234, 12 }, + { 0xC235, 0xC24F, 13 }, + { 0xC250, 0xC250, 12 }, + { 0xC251, 0xC26B, 13 }, + { 0xC26C, 0xC26C, 12 }, + { 0xC26D, 0xC287, 13 }, + { 0xC288, 0xC288, 12 }, + { 0xC289, 0xC2A3, 13 }, + { 0xC2A4, 0xC2A4, 12 }, + { 0xC2A5, 0xC2BF, 13 }, + { 0xC2C0, 0xC2C0, 12 }, + { 0xC2C1, 0xC2DB, 13 }, + { 0xC2DC, 0xC2DC, 12 }, + { 0xC2DD, 0xC2F7, 13 }, + { 0xC2F8, 0xC2F8, 12 }, + { 0xC2F9, 0xC313, 13 }, + { 0xC314, 0xC314, 12 }, + { 0xC315, 0xC32F, 13 }, + { 0xC330, 0xC330, 12 }, + { 0xC331, 0xC34B, 13 }, + { 0xC34C, 0xC34C, 12 }, + { 0xC34D, 0xC367, 13 }, + { 0xC368, 0xC368, 12 }, + { 0xC369, 0xC383, 13 }, + { 0xC384, 0xC384, 12 }, + { 0xC385, 0xC39F, 13 }, + { 0xC3A0, 0xC3A0, 12 }, + { 0xC3A1, 0xC3BB, 13 }, + { 0xC3BC, 0xC3BC, 12 }, + { 0xC3BD, 0xC3D7, 13 }, + { 0xC3D8, 0xC3D8, 12 }, + { 0xC3D9, 0xC3F3, 13 }, + { 0xC3F4, 0xC3F4, 12 }, + { 0xC3F5, 0xC40F, 13 }, + { 0xC410, 0xC410, 12 }, + { 0xC411, 0xC42B, 13 }, + { 0xC42C, 0xC42C, 12 }, + { 0xC42D, 0xC447, 13 }, + { 0xC448, 0xC448, 12 }, + { 0xC449, 0xC463, 13 }, + { 0xC464, 0xC464, 12 }, + { 0xC465, 0xC47F, 13 }, + { 0xC480, 0xC480, 12 }, + { 0xC481, 0xC49B, 13 }, + { 0xC49C, 0xC49C, 12 }, + { 0xC49D, 0xC4B7, 13 }, + { 0xC4B8, 0xC4B8, 12 }, + { 0xC4B9, 0xC4D3, 13 }, + { 0xC4D4, 0xC4D4, 12 }, + { 0xC4D5, 0xC4EF, 13 }, + { 0xC4F0, 0xC4F0, 12 }, + { 0xC4F1, 0xC50B, 13 }, + { 0xC50C, 0xC50C, 12 }, + { 0xC50D, 0xC527, 13 }, + { 0xC528, 0xC528, 12 }, + { 0xC529, 0xC543, 13 }, + { 0xC544, 0xC544, 12 }, + { 0xC545, 0xC55F, 13 }, + { 0xC560, 0xC560, 12 }, + { 0xC561, 0xC57B, 13 }, + { 0xC57C, 0xC57C, 12 }, + { 0xC57D, 0xC597, 13 }, + { 0xC598, 0xC598, 12 }, + { 0xC599, 0xC5B3, 13 }, + { 0xC5B4, 0xC5B4, 12 }, + { 0xC5B5, 0xC5CF, 13 }, + { 0xC5D0, 0xC5D0, 12 }, + { 0xC5D1, 0xC5EB, 13 }, + { 0xC5EC, 0xC5EC, 12 }, + { 0xC5ED, 0xC607, 13 }, + { 0xC608, 0xC608, 12 }, + { 0xC609, 0xC623, 13 }, + { 0xC624, 0xC624, 12 }, + { 0xC625, 0xC63F, 13 }, + { 0xC640, 0xC640, 12 }, + { 0xC641, 0xC65B, 13 }, + { 0xC65C, 0xC65C, 12 }, + { 0xC65D, 0xC677, 13 }, + { 0xC678, 0xC678, 12 }, + { 0xC679, 0xC693, 13 }, + { 0xC694, 0xC694, 12 }, + { 0xC695, 0xC6AF, 13 }, + { 0xC6B0, 0xC6B0, 12 }, + { 0xC6B1, 0xC6CB, 13 }, + { 0xC6CC, 0xC6CC, 12 }, + { 0xC6CD, 0xC6E7, 13 }, + { 0xC6E8, 0xC6E8, 12 }, + { 0xC6E9, 0xC703, 13 }, + { 0xC704, 0xC704, 12 }, + { 0xC705, 0xC71F, 13 }, + { 0xC720, 0xC720, 12 }, + { 0xC721, 0xC73B, 13 }, + { 0xC73C, 0xC73C, 12 }, + { 0xC73D, 0xC757, 13 }, + { 0xC758, 0xC758, 12 }, + { 0xC759, 0xC773, 13 }, + { 0xC774, 0xC774, 12 }, + { 0xC775, 0xC78F, 13 }, + { 0xC790, 0xC790, 12 }, + { 0xC791, 0xC7AB, 13 }, + { 0xC7AC, 0xC7AC, 12 }, + { 0xC7AD, 0xC7C7, 13 }, + { 0xC7C8, 0xC7C8, 12 }, + { 0xC7C9, 0xC7E3, 13 }, + { 0xC7E4, 0xC7E4, 12 }, + { 0xC7E5, 0xC7FF, 13 }, + { 0xC800, 0xC800, 12 }, + { 0xC801, 0xC81B, 13 }, + { 0xC81C, 0xC81C, 12 }, + { 0xC81D, 0xC837, 13 }, + { 0xC838, 0xC838, 12 }, + { 0xC839, 0xC853, 13 }, + { 0xC854, 0xC854, 12 }, + { 0xC855, 0xC86F, 13 }, + { 0xC870, 0xC870, 12 }, + { 0xC871, 0xC88B, 13 }, + { 0xC88C, 0xC88C, 12 }, + { 0xC88D, 0xC8A7, 13 }, + { 0xC8A8, 0xC8A8, 12 }, + { 0xC8A9, 0xC8C3, 13 }, + { 0xC8C4, 0xC8C4, 12 }, + { 0xC8C5, 0xC8DF, 13 }, + { 0xC8E0, 0xC8E0, 12 }, + { 0xC8E1, 0xC8FB, 13 }, + { 0xC8FC, 0xC8FC, 12 }, + { 0xC8FD, 0xC917, 13 }, + { 0xC918, 0xC918, 12 }, + { 0xC919, 0xC933, 13 }, + { 0xC934, 0xC934, 12 }, + { 0xC935, 0xC94F, 13 }, + { 0xC950, 0xC950, 12 }, + { 0xC951, 0xC96B, 13 }, + { 0xC96C, 0xC96C, 12 }, + { 0xC96D, 0xC987, 13 }, + { 0xC988, 0xC988, 12 }, + { 0xC989, 0xC9A3, 13 }, + { 0xC9A4, 0xC9A4, 12 }, + { 0xC9A5, 0xC9BF, 13 }, + { 0xC9C0, 0xC9C0, 12 }, + { 0xC9C1, 0xC9DB, 13 }, + { 0xC9DC, 0xC9DC, 12 }, + { 0xC9DD, 0xC9F7, 13 }, + { 0xC9F8, 0xC9F8, 12 }, + { 0xC9F9, 0xCA13, 13 }, + { 0xCA14, 0xCA14, 12 }, + { 0xCA15, 0xCA2F, 13 }, + { 0xCA30, 0xCA30, 12 }, + { 0xCA31, 0xCA4B, 13 }, + { 0xCA4C, 0xCA4C, 12 }, + { 0xCA4D, 0xCA67, 13 }, + { 0xCA68, 0xCA68, 12 }, + { 0xCA69, 0xCA83, 13 }, + { 0xCA84, 0xCA84, 12 }, + { 0xCA85, 0xCA9F, 13 }, + { 0xCAA0, 0xCAA0, 12 }, + { 0xCAA1, 0xCABB, 13 }, + { 0xCABC, 0xCABC, 12 }, + { 0xCABD, 0xCAD7, 13 }, + { 0xCAD8, 0xCAD8, 12 }, + { 0xCAD9, 0xCAF3, 13 }, + { 0xCAF4, 0xCAF4, 12 }, + { 0xCAF5, 0xCB0F, 13 }, + { 0xCB10, 0xCB10, 12 }, + { 0xCB11, 0xCB2B, 13 }, + { 0xCB2C, 0xCB2C, 12 }, + { 0xCB2D, 0xCB47, 13 }, + { 0xCB48, 0xCB48, 12 }, + { 0xCB49, 0xCB63, 13 }, + { 0xCB64, 0xCB64, 12 }, + { 0xCB65, 0xCB7F, 13 }, + { 0xCB80, 0xCB80, 12 }, + { 0xCB81, 0xCB9B, 13 }, + { 0xCB9C, 0xCB9C, 12 }, + { 0xCB9D, 0xCBB7, 13 }, + { 0xCBB8, 0xCBB8, 12 }, + { 0xCBB9, 0xCBD3, 13 }, + { 0xCBD4, 0xCBD4, 12 }, + { 0xCBD5, 0xCBEF, 13 }, + { 0xCBF0, 0xCBF0, 12 }, + { 0xCBF1, 0xCC0B, 13 }, + { 0xCC0C, 0xCC0C, 12 }, + { 0xCC0D, 0xCC27, 13 }, + { 0xCC28, 0xCC28, 12 }, + { 0xCC29, 0xCC43, 13 }, + { 0xCC44, 0xCC44, 12 }, + { 0xCC45, 0xCC5F, 13 }, + { 0xCC60, 0xCC60, 12 }, + { 0xCC61, 0xCC7B, 13 }, + { 0xCC7C, 0xCC7C, 12 }, + { 0xCC7D, 0xCC97, 13 }, + { 0xCC98, 0xCC98, 12 }, + { 0xCC99, 0xCCB3, 13 }, + { 0xCCB4, 0xCCB4, 12 }, + { 0xCCB5, 0xCCCF, 13 }, + { 0xCCD0, 0xCCD0, 12 }, + { 0xCCD1, 0xCCEB, 13 }, + { 0xCCEC, 0xCCEC, 12 }, + { 0xCCED, 0xCD07, 13 }, + { 0xCD08, 0xCD08, 12 }, + { 0xCD09, 0xCD23, 13 }, + { 0xCD24, 0xCD24, 12 }, + { 0xCD25, 0xCD3F, 13 }, + { 0xCD40, 0xCD40, 12 }, + { 0xCD41, 0xCD5B, 13 }, + { 0xCD5C, 0xCD5C, 12 }, + { 0xCD5D, 0xCD77, 13 }, + { 0xCD78, 0xCD78, 12 }, + { 0xCD79, 0xCD93, 13 }, + { 0xCD94, 0xCD94, 12 }, + { 0xCD95, 0xCDAF, 13 }, + { 0xCDB0, 0xCDB0, 12 }, + { 0xCDB1, 0xCDCB, 13 }, + { 0xCDCC, 0xCDCC, 12 }, + { 0xCDCD, 0xCDE7, 13 }, + { 0xCDE8, 0xCDE8, 12 }, + { 0xCDE9, 0xCE03, 13 }, + { 0xCE04, 0xCE04, 12 }, + { 0xCE05, 0xCE1F, 13 }, + { 0xCE20, 0xCE20, 12 }, + { 0xCE21, 0xCE3B, 13 }, + { 0xCE3C, 0xCE3C, 12 }, + { 0xCE3D, 0xCE57, 13 }, + { 0xCE58, 0xCE58, 12 }, + { 0xCE59, 0xCE73, 13 }, + { 0xCE74, 0xCE74, 12 }, + { 0xCE75, 0xCE8F, 13 }, + { 0xCE90, 0xCE90, 12 }, + { 0xCE91, 0xCEAB, 13 }, + { 0xCEAC, 0xCEAC, 12 }, + { 0xCEAD, 0xCEC7, 13 }, + { 0xCEC8, 0xCEC8, 12 }, + { 0xCEC9, 0xCEE3, 13 }, + { 0xCEE4, 0xCEE4, 12 }, + { 0xCEE5, 0xCEFF, 13 }, + { 0xCF00, 0xCF00, 12 }, + { 0xCF01, 0xCF1B, 13 }, + { 0xCF1C, 0xCF1C, 12 }, + { 0xCF1D, 0xCF37, 13 }, + { 0xCF38, 0xCF38, 12 }, + { 0xCF39, 0xCF53, 13 }, + { 0xCF54, 0xCF54, 12 }, + { 0xCF55, 0xCF6F, 13 }, + { 0xCF70, 0xCF70, 12 }, + { 0xCF71, 0xCF8B, 13 }, + { 0xCF8C, 0xCF8C, 12 }, + { 0xCF8D, 0xCFA7, 13 }, + { 0xCFA8, 0xCFA8, 12 }, + { 0xCFA9, 0xCFC3, 13 }, + { 0xCFC4, 0xCFC4, 12 }, + { 0xCFC5, 0xCFDF, 13 }, + { 0xCFE0, 0xCFE0, 12 }, + { 0xCFE1, 0xCFFB, 13 }, + { 0xCFFC, 0xCFFC, 12 }, + { 0xCFFD, 0xD017, 13 }, + { 0xD018, 0xD018, 12 }, + { 0xD019, 0xD033, 13 }, + { 0xD034, 0xD034, 12 }, + { 0xD035, 0xD04F, 13 }, + { 0xD050, 0xD050, 12 }, + { 0xD051, 0xD06B, 13 }, + { 0xD06C, 0xD06C, 12 }, + { 0xD06D, 0xD087, 13 }, + { 0xD088, 0xD088, 12 }, + { 0xD089, 0xD0A3, 13 }, + { 0xD0A4, 0xD0A4, 12 }, + { 0xD0A5, 0xD0BF, 13 }, + { 0xD0C0, 0xD0C0, 12 }, + { 0xD0C1, 0xD0DB, 13 }, + { 0xD0DC, 0xD0DC, 12 }, + { 0xD0DD, 0xD0F7, 13 }, + { 0xD0F8, 0xD0F8, 12 }, + { 0xD0F9, 0xD113, 13 }, + { 0xD114, 0xD114, 12 }, + { 0xD115, 0xD12F, 13 }, + { 0xD130, 0xD130, 12 }, + { 0xD131, 0xD14B, 13 }, + { 0xD14C, 0xD14C, 12 }, + { 0xD14D, 0xD167, 13 }, + { 0xD168, 0xD168, 12 }, + { 0xD169, 0xD183, 13 }, + { 0xD184, 0xD184, 12 }, + { 0xD185, 0xD19F, 13 }, + { 0xD1A0, 0xD1A0, 12 }, + { 0xD1A1, 0xD1BB, 13 }, + { 0xD1BC, 0xD1BC, 12 }, + { 0xD1BD, 0xD1D7, 13 }, + { 0xD1D8, 0xD1D8, 12 }, + { 0xD1D9, 0xD1F3, 13 }, + { 0xD1F4, 0xD1F4, 12 }, + { 0xD1F5, 0xD20F, 13 }, + { 0xD210, 0xD210, 12 }, + { 0xD211, 0xD22B, 13 }, + { 0xD22C, 0xD22C, 12 }, + { 0xD22D, 0xD247, 13 }, + { 0xD248, 0xD248, 12 }, + { 0xD249, 0xD263, 13 }, + { 0xD264, 0xD264, 12 }, + { 0xD265, 0xD27F, 13 }, + { 0xD280, 0xD280, 12 }, + { 0xD281, 0xD29B, 13 }, + { 0xD29C, 0xD29C, 12 }, + { 0xD29D, 0xD2B7, 13 }, + { 0xD2B8, 0xD2B8, 12 }, + { 0xD2B9, 0xD2D3, 13 }, + { 0xD2D4, 0xD2D4, 12 }, + { 0xD2D5, 0xD2EF, 13 }, + { 0xD2F0, 0xD2F0, 12 }, + { 0xD2F1, 0xD30B, 13 }, + { 0xD30C, 0xD30C, 12 }, + { 0xD30D, 0xD327, 13 }, + { 0xD328, 0xD328, 12 }, + { 0xD329, 0xD343, 13 }, + { 0xD344, 0xD344, 12 }, + { 0xD345, 0xD35F, 13 }, + { 0xD360, 0xD360, 12 }, + { 0xD361, 0xD37B, 13 }, + { 0xD37C, 0xD37C, 12 }, + { 0xD37D, 0xD397, 13 }, + { 0xD398, 0xD398, 12 }, + { 0xD399, 0xD3B3, 13 }, + { 0xD3B4, 0xD3B4, 12 }, + { 0xD3B5, 0xD3CF, 13 }, + { 0xD3D0, 0xD3D0, 12 }, + { 0xD3D1, 0xD3EB, 13 }, + { 0xD3EC, 0xD3EC, 12 }, + { 0xD3ED, 0xD407, 13 }, + { 0xD408, 0xD408, 12 }, + { 0xD409, 0xD423, 13 }, + { 0xD424, 0xD424, 12 }, + { 0xD425, 0xD43F, 13 }, + { 0xD440, 0xD440, 12 }, + { 0xD441, 0xD45B, 13 }, + { 0xD45C, 0xD45C, 12 }, + { 0xD45D, 0xD477, 13 }, + { 0xD478, 0xD478, 12 }, + { 0xD479, 0xD493, 13 }, + { 0xD494, 0xD494, 12 }, + { 0xD495, 0xD4AF, 13 }, + { 0xD4B0, 0xD4B0, 12 }, + { 0xD4B1, 0xD4CB, 13 }, + { 0xD4CC, 0xD4CC, 12 }, + { 0xD4CD, 0xD4E7, 13 }, + { 0xD4E8, 0xD4E8, 12 }, + { 0xD4E9, 0xD503, 13 }, + { 0xD504, 0xD504, 12 }, + { 0xD505, 0xD51F, 13 }, + { 0xD520, 0xD520, 12 }, + { 0xD521, 0xD53B, 13 }, + { 0xD53C, 0xD53C, 12 }, + { 0xD53D, 0xD557, 13 }, + { 0xD558, 0xD558, 12 }, + { 0xD559, 0xD573, 13 }, + { 0xD574, 0xD574, 12 }, + { 0xD575, 0xD58F, 13 }, + { 0xD590, 0xD590, 12 }, + { 0xD591, 0xD5AB, 13 }, + { 0xD5AC, 0xD5AC, 12 }, + { 0xD5AD, 0xD5C7, 13 }, + { 0xD5C8, 0xD5C8, 12 }, + { 0xD5C9, 0xD5E3, 13 }, + { 0xD5E4, 0xD5E4, 12 }, + { 0xD5E5, 0xD5FF, 13 }, + { 0xD600, 0xD600, 12 }, + { 0xD601, 0xD61B, 13 }, + { 0xD61C, 0xD61C, 12 }, + { 0xD61D, 0xD637, 13 }, + { 0xD638, 0xD638, 12 }, + { 0xD639, 0xD653, 13 }, + { 0xD654, 0xD654, 12 }, + { 0xD655, 0xD66F, 13 }, + { 0xD670, 0xD670, 12 }, + { 0xD671, 0xD68B, 13 }, + { 0xD68C, 0xD68C, 12 }, + { 0xD68D, 0xD6A7, 13 }, + { 0xD6A8, 0xD6A8, 12 }, + { 0xD6A9, 0xD6C3, 13 }, + { 0xD6C4, 0xD6C4, 12 }, + { 0xD6C5, 0xD6DF, 13 }, + { 0xD6E0, 0xD6E0, 12 }, + { 0xD6E1, 0xD6FB, 13 }, + { 0xD6FC, 0xD6FC, 12 }, + { 0xD6FD, 0xD717, 13 }, + { 0xD718, 0xD718, 12 }, + { 0xD719, 0xD733, 13 }, + { 0xD734, 0xD734, 12 }, + { 0xD735, 0xD74F, 13 }, + { 0xD750, 0xD750, 12 }, + { 0xD751, 0xD76B, 13 }, + { 0xD76C, 0xD76C, 12 }, + { 0xD76D, 0xD787, 13 }, + { 0xD788, 0xD788, 12 }, + { 0xD789, 0xD7A3, 13 }, + { 0xD7B0, 0xD7C6, 10 }, + { 0xD7CB, 0xD7FB, 11 }, + { 0xFB1E, 0xFB1E, 4 }, + { 0xFE00, 0xFE0F, 4 }, + { 0xFE20, 0xFE2F, 4 }, + { 0xFEFF, 0xFEFF, 3 }, + { 0xFF9E, 0xFF9F, 4 }, + { 0xFFF0, 0xFFFB, 3 }, + { 0x101FD, 0x101FD, 4 }, + { 0x102E0, 0x102E0, 4 }, + { 0x10376, 0x1037A, 4 }, + { 0x10A01, 0x10A03, 4 }, + { 0x10A05, 0x10A06, 4 }, + { 0x10A0C, 0x10A0F, 4 }, + { 0x10A38, 0x10A3A, 4 }, + { 0x10A3F, 0x10A3F, 4 }, + { 0x10AE5, 0x10AE6, 4 }, + { 0x10D24, 0x10D27, 4 }, + { 0x10D69, 0x10D6D, 4 }, + { 0x10EAB, 0x10EAC, 4 }, + { 0x10EFC, 0x10EFF, 4 }, + { 0x10F46, 0x10F50, 4 }, + { 0x10F82, 0x10F85, 4 }, + { 0x11000, 0x11000, 8 }, + { 0x11001, 0x11001, 4 }, + { 0x11002, 0x11002, 8 }, + { 0x11038, 0x11046, 4 }, + { 0x11070, 0x11070, 4 }, + { 0x11073, 0x11074, 4 }, + { 0x1107F, 0x11081, 4 }, + { 0x11082, 0x11082, 8 }, + { 0x110B0, 0x110B2, 8 }, + { 0x110B3, 0x110B6, 4 }, + { 0x110B7, 0x110B8, 8 }, + { 0x110B9, 0x110BA, 4 }, + { 0x110BD, 0x110BD, 7 }, + { 0x110C2, 0x110C2, 4 }, + { 0x110CD, 0x110CD, 7 }, + { 0x11100, 0x11102, 4 }, + { 0x11127, 0x1112B, 4 }, + { 0x1112C, 0x1112C, 8 }, + { 0x1112D, 0x11134, 4 }, + { 0x11145, 0x11146, 8 }, + { 0x11173, 0x11173, 4 }, + { 0x11180, 0x11181, 4 }, + { 0x11182, 0x11182, 8 }, + { 0x111B3, 0x111B5, 8 }, + { 0x111B6, 0x111BE, 4 }, + { 0x111BF, 0x111BF, 8 }, + { 0x111C0, 0x111C0, 4 }, + { 0x111C2, 0x111C3, 7 }, + { 0x111C9, 0x111CC, 4 }, + { 0x111CE, 0x111CE, 8 }, + { 0x111CF, 0x111CF, 4 }, + { 0x1122C, 0x1122E, 8 }, + { 0x1122F, 0x11231, 4 }, + { 0x11232, 0x11233, 8 }, + { 0x11234, 0x11237, 4 }, + { 0x1123E, 0x1123E, 4 }, + { 0x11241, 0x11241, 4 }, + { 0x112DF, 0x112DF, 4 }, + { 0x112E0, 0x112E2, 8 }, + { 0x112E3, 0x112EA, 4 }, + { 0x11300, 0x11301, 4 }, + { 0x11302, 0x11303, 8 }, + { 0x1133B, 0x1133C, 4 }, + { 0x1133E, 0x1133E, 4 }, + { 0x1133F, 0x1133F, 8 }, + { 0x11340, 0x11340, 4 }, + { 0x11341, 0x11344, 8 }, + { 0x11347, 0x11348, 8 }, + { 0x1134B, 0x1134C, 8 }, + { 0x1134D, 0x1134D, 4 }, + { 0x11357, 0x11357, 4 }, + { 0x11362, 0x11363, 8 }, + { 0x11366, 0x1136C, 4 }, + { 0x11370, 0x11374, 4 }, + { 0x113B8, 0x113B8, 4 }, + { 0x113B9, 0x113BA, 8 }, + { 0x113BB, 0x113C0, 4 }, + { 0x113C2, 0x113C2, 4 }, + { 0x113C5, 0x113C5, 4 }, + { 0x113C7, 0x113C9, 4 }, + { 0x113CA, 0x113CA, 8 }, + { 0x113CC, 0x113CD, 8 }, + { 0x113CE, 0x113D0, 4 }, + { 0x113D1, 0x113D1, 7 }, + { 0x113D2, 0x113D2, 4 }, + { 0x113E1, 0x113E2, 4 }, + { 0x11435, 0x11437, 8 }, + { 0x11438, 0x1143F, 4 }, + { 0x11440, 0x11441, 8 }, + { 0x11442, 0x11444, 4 }, + { 0x11445, 0x11445, 8 }, + { 0x11446, 0x11446, 4 }, + { 0x1145E, 0x1145E, 4 }, + { 0x114B0, 0x114B0, 4 }, + { 0x114B1, 0x114B2, 8 }, + { 0x114B3, 0x114B8, 4 }, + { 0x114B9, 0x114B9, 8 }, + { 0x114BA, 0x114BA, 4 }, + { 0x114BB, 0x114BC, 8 }, + { 0x114BD, 0x114BD, 4 }, + { 0x114BE, 0x114BE, 8 }, + { 0x114BF, 0x114C0, 4 }, + { 0x114C1, 0x114C1, 8 }, + { 0x114C2, 0x114C3, 4 }, + { 0x115AF, 0x115AF, 4 }, + { 0x115B0, 0x115B1, 8 }, + { 0x115B2, 0x115B5, 4 }, + { 0x115B8, 0x115BB, 8 }, + { 0x115BC, 0x115BD, 4 }, + { 0x115BE, 0x115BE, 8 }, + { 0x115BF, 0x115C0, 4 }, + { 0x115DC, 0x115DD, 4 }, + { 0x11630, 0x11632, 8 }, + { 0x11633, 0x1163A, 4 }, + { 0x1163B, 0x1163C, 8 }, + { 0x1163D, 0x1163D, 4 }, + { 0x1163E, 0x1163E, 8 }, + { 0x1163F, 0x11640, 4 }, + { 0x116AB, 0x116AB, 4 }, + { 0x116AC, 0x116AC, 8 }, + { 0x116AD, 0x116AD, 4 }, + { 0x116AE, 0x116AF, 8 }, + { 0x116B0, 0x116B7, 4 }, + { 0x1171D, 0x1171D, 4 }, + { 0x1171E, 0x1171E, 8 }, + { 0x1171F, 0x1171F, 4 }, + { 0x11722, 0x11725, 4 }, + { 0x11726, 0x11726, 8 }, + { 0x11727, 0x1172B, 4 }, + { 0x1182C, 0x1182E, 8 }, + { 0x1182F, 0x11837, 4 }, + { 0x11838, 0x11838, 8 }, + { 0x11839, 0x1183A, 4 }, + { 0x11930, 0x11930, 4 }, + { 0x11931, 0x11935, 8 }, + { 0x11937, 0x11938, 8 }, + { 0x1193B, 0x1193E, 4 }, + { 0x1193F, 0x1193F, 7 }, + { 0x11940, 0x11940, 8 }, + { 0x11941, 0x11941, 7 }, + { 0x11942, 0x11942, 8 }, + { 0x11943, 0x11943, 4 }, + { 0x119D1, 0x119D3, 8 }, + { 0x119D4, 0x119D7, 4 }, + { 0x119DA, 0x119DB, 4 }, + { 0x119DC, 0x119DF, 8 }, + { 0x119E0, 0x119E0, 4 }, + { 0x119E4, 0x119E4, 8 }, + { 0x11A01, 0x11A0A, 4 }, + { 0x11A33, 0x11A38, 4 }, + { 0x11A39, 0x11A39, 8 }, + { 0x11A3A, 0x11A3A, 7 }, + { 0x11A3B, 0x11A3E, 4 }, + { 0x11A47, 0x11A47, 4 }, + { 0x11A51, 0x11A56, 4 }, + { 0x11A57, 0x11A58, 8 }, + { 0x11A59, 0x11A5B, 4 }, + { 0x11A84, 0x11A89, 7 }, + { 0x11A8A, 0x11A96, 4 }, + { 0x11A97, 0x11A97, 8 }, + { 0x11A98, 0x11A99, 4 }, + { 0x11C2F, 0x11C2F, 8 }, + { 0x11C30, 0x11C36, 4 }, + { 0x11C38, 0x11C3D, 4 }, + { 0x11C3E, 0x11C3E, 8 }, + { 0x11C3F, 0x11C3F, 4 }, + { 0x11C92, 0x11CA7, 4 }, + { 0x11CA9, 0x11CA9, 8 }, + { 0x11CAA, 0x11CB0, 4 }, + { 0x11CB1, 0x11CB1, 8 }, + { 0x11CB2, 0x11CB3, 4 }, + { 0x11CB4, 0x11CB4, 8 }, + { 0x11CB5, 0x11CB6, 4 }, + { 0x11D31, 0x11D36, 4 }, + { 0x11D3A, 0x11D3A, 4 }, + { 0x11D3C, 0x11D3D, 4 }, + { 0x11D3F, 0x11D45, 4 }, + { 0x11D46, 0x11D46, 7 }, + { 0x11D47, 0x11D47, 4 }, + { 0x11D8A, 0x11D8E, 8 }, + { 0x11D90, 0x11D91, 4 }, + { 0x11D93, 0x11D94, 8 }, + { 0x11D95, 0x11D95, 4 }, + { 0x11D96, 0x11D96, 8 }, + { 0x11D97, 0x11D97, 4 }, + { 0x11EF3, 0x11EF4, 4 }, + { 0x11EF5, 0x11EF6, 8 }, + { 0x11F00, 0x11F01, 4 }, + { 0x11F02, 0x11F02, 7 }, + { 0x11F03, 0x11F03, 8 }, + { 0x11F34, 0x11F35, 8 }, + { 0x11F36, 0x11F3A, 4 }, + { 0x11F3E, 0x11F3F, 8 }, + { 0x11F40, 0x11F42, 4 }, + { 0x11F5A, 0x11F5A, 4 }, + { 0x13430, 0x1343F, 3 }, + { 0x13440, 0x13440, 4 }, + { 0x13447, 0x13455, 4 }, + { 0x1611E, 0x16129, 4 }, + { 0x1612A, 0x1612C, 8 }, + { 0x1612D, 0x1612F, 4 }, + { 0x16AF0, 0x16AF4, 4 }, + { 0x16B30, 0x16B36, 4 }, + { 0x16D63, 0x16D63, 10 }, + { 0x16D67, 0x16D6A, 10 }, + { 0x16F4F, 0x16F4F, 4 }, + { 0x16F51, 0x16F87, 8 }, + { 0x16F8F, 0x16F92, 4 }, + { 0x16FE4, 0x16FE4, 4 }, + { 0x16FF0, 0x16FF1, 4 }, + { 0x1BC9D, 0x1BC9E, 4 }, + { 0x1BCA0, 0x1BCA3, 3 }, + { 0x1CF00, 0x1CF2D, 4 }, + { 0x1CF30, 0x1CF46, 4 }, + { 0x1D165, 0x1D169, 4 }, + { 0x1D16D, 0x1D172, 4 }, + { 0x1D173, 0x1D17A, 3 }, + { 0x1D17B, 0x1D182, 4 }, + { 0x1D185, 0x1D18B, 4 }, + { 0x1D1AA, 0x1D1AD, 4 }, + { 0x1D242, 0x1D244, 4 }, + { 0x1DA00, 0x1DA36, 4 }, + { 0x1DA3B, 0x1DA6C, 4 }, + { 0x1DA75, 0x1DA75, 4 }, + { 0x1DA84, 0x1DA84, 4 }, + { 0x1DA9B, 0x1DA9F, 4 }, + { 0x1DAA1, 0x1DAAF, 4 }, + { 0x1E000, 0x1E006, 4 }, + { 0x1E008, 0x1E018, 4 }, + { 0x1E01B, 0x1E021, 4 }, + { 0x1E023, 0x1E024, 4 }, + { 0x1E026, 0x1E02A, 4 }, + { 0x1E08F, 0x1E08F, 4 }, + { 0x1E130, 0x1E136, 4 }, + { 0x1E2AE, 0x1E2AE, 4 }, + { 0x1E2EC, 0x1E2EF, 4 }, + { 0x1E4EC, 0x1E4EF, 4 }, + { 0x1E5EE, 0x1E5EF, 4 }, + { 0x1E8D0, 0x1E8D6, 4 }, + { 0x1E944, 0x1E94A, 4 }, + { 0x1F1E6, 0x1F1FF, 6 }, + { 0x1F3FB, 0x1F3FF, 4 }, + { 0xE0000, 0xE001F, 3 }, + { 0xE0020, 0xE007F, 4 }, + { 0xE0080, 0xE00FF, 3 }, + { 0xE0100, 0xE01EF, 4 }, + { 0xE01F0, 0xE0FFF, 3 }, +}; +const size_t k_gcb_n = sizeof k_gcb / sizeof k_gcb[0]; + +const GbRange k_ext_pict[] = { + { 0xA9, 0xA9, 1 }, + { 0xAE, 0xAE, 1 }, + { 0x203C, 0x203C, 1 }, + { 0x2049, 0x2049, 1 }, + { 0x2122, 0x2122, 1 }, + { 0x2139, 0x2139, 1 }, + { 0x2194, 0x2199, 1 }, + { 0x21A9, 0x21AA, 1 }, + { 0x231A, 0x231B, 1 }, + { 0x2328, 0x2328, 1 }, + { 0x2388, 0x2388, 1 }, + { 0x23CF, 0x23CF, 1 }, + { 0x23E9, 0x23F3, 1 }, + { 0x23F8, 0x23FA, 1 }, + { 0x24C2, 0x24C2, 1 }, + { 0x25AA, 0x25AB, 1 }, + { 0x25B6, 0x25B6, 1 }, + { 0x25C0, 0x25C0, 1 }, + { 0x25FB, 0x25FE, 1 }, + { 0x2600, 0x2605, 1 }, + { 0x2607, 0x2612, 1 }, + { 0x2614, 0x2685, 1 }, + { 0x2690, 0x2705, 1 }, + { 0x2708, 0x2712, 1 }, + { 0x2714, 0x2714, 1 }, + { 0x2716, 0x2716, 1 }, + { 0x271D, 0x271D, 1 }, + { 0x2721, 0x2721, 1 }, + { 0x2728, 0x2728, 1 }, + { 0x2733, 0x2734, 1 }, + { 0x2744, 0x2744, 1 }, + { 0x2747, 0x2747, 1 }, + { 0x274C, 0x274C, 1 }, + { 0x274E, 0x274E, 1 }, + { 0x2753, 0x2755, 1 }, + { 0x2757, 0x2757, 1 }, + { 0x2763, 0x2767, 1 }, + { 0x2795, 0x2797, 1 }, + { 0x27A1, 0x27A1, 1 }, + { 0x27B0, 0x27B0, 1 }, + { 0x27BF, 0x27BF, 1 }, + { 0x2934, 0x2935, 1 }, + { 0x2B05, 0x2B07, 1 }, + { 0x2B1B, 0x2B1C, 1 }, + { 0x2B50, 0x2B50, 1 }, + { 0x2B55, 0x2B55, 1 }, + { 0x3030, 0x3030, 1 }, + { 0x303D, 0x303D, 1 }, + { 0x3297, 0x3297, 1 }, + { 0x3299, 0x3299, 1 }, + { 0x1F000, 0x1F0FF, 1 }, + { 0x1F10D, 0x1F10F, 1 }, + { 0x1F12F, 0x1F12F, 1 }, + { 0x1F16C, 0x1F171, 1 }, + { 0x1F17E, 0x1F17F, 1 }, + { 0x1F18E, 0x1F18E, 1 }, + { 0x1F191, 0x1F19A, 1 }, + { 0x1F1AD, 0x1F1E5, 1 }, + { 0x1F201, 0x1F20F, 1 }, + { 0x1F21A, 0x1F21A, 1 }, + { 0x1F22F, 0x1F22F, 1 }, + { 0x1F232, 0x1F23A, 1 }, + { 0x1F23C, 0x1F23F, 1 }, + { 0x1F249, 0x1F3FA, 1 }, + { 0x1F400, 0x1F53D, 1 }, + { 0x1F546, 0x1F64F, 1 }, + { 0x1F680, 0x1F6FF, 1 }, + { 0x1F774, 0x1F77F, 1 }, + { 0x1F7D5, 0x1F7FF, 1 }, + { 0x1F80C, 0x1F80F, 1 }, + { 0x1F848, 0x1F84F, 1 }, + { 0x1F85A, 0x1F85F, 1 }, + { 0x1F888, 0x1F88F, 1 }, + { 0x1F8AE, 0x1F8FF, 1 }, + { 0x1F90C, 0x1F93A, 1 }, + { 0x1F93C, 0x1F945, 1 }, + { 0x1F947, 0x1FAFF, 1 }, + { 0x1FC00, 0x1FFFD, 1 }, +}; +const size_t k_ext_pict_n = sizeof k_ext_pict / sizeof k_ext_pict[0]; + +const GbRange k_incb[] = { + { 0x300, 0x36F, 3 }, + { 0x483, 0x489, 3 }, + { 0x591, 0x5BD, 3 }, + { 0x5BF, 0x5BF, 3 }, + { 0x5C1, 0x5C2, 3 }, + { 0x5C4, 0x5C5, 3 }, + { 0x5C7, 0x5C7, 3 }, + { 0x610, 0x61A, 3 }, + { 0x64B, 0x65F, 3 }, + { 0x670, 0x670, 3 }, + { 0x6D6, 0x6DC, 3 }, + { 0x6DF, 0x6E4, 3 }, + { 0x6E7, 0x6E8, 3 }, + { 0x6EA, 0x6ED, 3 }, + { 0x711, 0x711, 3 }, + { 0x730, 0x74A, 3 }, + { 0x7A6, 0x7B0, 3 }, + { 0x7EB, 0x7F3, 3 }, + { 0x7FD, 0x7FD, 3 }, + { 0x816, 0x819, 3 }, + { 0x81B, 0x823, 3 }, + { 0x825, 0x827, 3 }, + { 0x829, 0x82D, 3 }, + { 0x859, 0x85B, 3 }, + { 0x897, 0x89F, 3 }, + { 0x8CA, 0x8E1, 3 }, + { 0x8E3, 0x902, 3 }, + { 0x915, 0x939, 2 }, + { 0x93A, 0x93A, 3 }, + { 0x93C, 0x93C, 3 }, + { 0x941, 0x948, 3 }, + { 0x94D, 0x94D, 1 }, + { 0x951, 0x957, 3 }, + { 0x958, 0x95F, 2 }, + { 0x962, 0x963, 3 }, + { 0x978, 0x97F, 2 }, + { 0x981, 0x981, 3 }, + { 0x995, 0x9A8, 2 }, + { 0x9AA, 0x9B0, 2 }, + { 0x9B2, 0x9B2, 2 }, + { 0x9B6, 0x9B9, 2 }, + { 0x9BC, 0x9BC, 3 }, + { 0x9BE, 0x9BE, 3 }, + { 0x9C1, 0x9C4, 3 }, + { 0x9CD, 0x9CD, 1 }, + { 0x9D7, 0x9D7, 3 }, + { 0x9DC, 0x9DD, 2 }, + { 0x9DF, 0x9DF, 2 }, + { 0x9E2, 0x9E3, 3 }, + { 0x9F0, 0x9F1, 2 }, + { 0x9FE, 0x9FE, 3 }, + { 0xA01, 0xA02, 3 }, + { 0xA3C, 0xA3C, 3 }, + { 0xA41, 0xA42, 3 }, + { 0xA47, 0xA48, 3 }, + { 0xA4B, 0xA4D, 3 }, + { 0xA51, 0xA51, 3 }, + { 0xA70, 0xA71, 3 }, + { 0xA75, 0xA75, 3 }, + { 0xA81, 0xA82, 3 }, + { 0xA95, 0xAA8, 2 }, + { 0xAAA, 0xAB0, 2 }, + { 0xAB2, 0xAB3, 2 }, + { 0xAB5, 0xAB9, 2 }, + { 0xABC, 0xABC, 3 }, + { 0xAC1, 0xAC5, 3 }, + { 0xAC7, 0xAC8, 3 }, + { 0xACD, 0xACD, 1 }, + { 0xAE2, 0xAE3, 3 }, + { 0xAF9, 0xAF9, 2 }, + { 0xAFA, 0xAFF, 3 }, + { 0xB01, 0xB01, 3 }, + { 0xB15, 0xB28, 2 }, + { 0xB2A, 0xB30, 2 }, + { 0xB32, 0xB33, 2 }, + { 0xB35, 0xB39, 2 }, + { 0xB3C, 0xB3C, 3 }, + { 0xB3E, 0xB3F, 3 }, + { 0xB41, 0xB44, 3 }, + { 0xB4D, 0xB4D, 1 }, + { 0xB55, 0xB57, 3 }, + { 0xB5C, 0xB5D, 2 }, + { 0xB5F, 0xB5F, 2 }, + { 0xB62, 0xB63, 3 }, + { 0xB71, 0xB71, 2 }, + { 0xB82, 0xB82, 3 }, + { 0xBBE, 0xBBE, 3 }, + { 0xBC0, 0xBC0, 3 }, + { 0xBCD, 0xBCD, 3 }, + { 0xBD7, 0xBD7, 3 }, + { 0xC00, 0xC00, 3 }, + { 0xC04, 0xC04, 3 }, + { 0xC15, 0xC28, 2 }, + { 0xC2A, 0xC39, 2 }, + { 0xC3C, 0xC3C, 3 }, + { 0xC3E, 0xC40, 3 }, + { 0xC46, 0xC48, 3 }, + { 0xC4A, 0xC4C, 3 }, + { 0xC4D, 0xC4D, 1 }, + { 0xC55, 0xC56, 3 }, + { 0xC58, 0xC5A, 2 }, + { 0xC62, 0xC63, 3 }, + { 0xC81, 0xC81, 3 }, + { 0xCBC, 0xCBC, 3 }, + { 0xCBF, 0xCC0, 3 }, + { 0xCC2, 0xCC2, 3 }, + { 0xCC6, 0xCC8, 3 }, + { 0xCCA, 0xCCD, 3 }, + { 0xCD5, 0xCD6, 3 }, + { 0xCE2, 0xCE3, 3 }, + { 0xD00, 0xD01, 3 }, + { 0xD15, 0xD3A, 2 }, + { 0xD3B, 0xD3C, 3 }, + { 0xD3E, 0xD3E, 3 }, + { 0xD41, 0xD44, 3 }, + { 0xD4D, 0xD4D, 1 }, + { 0xD57, 0xD57, 3 }, + { 0xD62, 0xD63, 3 }, + { 0xD81, 0xD81, 3 }, + { 0xDCA, 0xDCA, 3 }, + { 0xDCF, 0xDCF, 3 }, + { 0xDD2, 0xDD4, 3 }, + { 0xDD6, 0xDD6, 3 }, + { 0xDDF, 0xDDF, 3 }, + { 0xE31, 0xE31, 3 }, + { 0xE34, 0xE3A, 3 }, + { 0xE47, 0xE4E, 3 }, + { 0xEB1, 0xEB1, 3 }, + { 0xEB4, 0xEBC, 3 }, + { 0xEC8, 0xECE, 3 }, + { 0xF18, 0xF19, 3 }, + { 0xF35, 0xF35, 3 }, + { 0xF37, 0xF37, 3 }, + { 0xF39, 0xF39, 3 }, + { 0xF71, 0xF7E, 3 }, + { 0xF80, 0xF84, 3 }, + { 0xF86, 0xF87, 3 }, + { 0xF8D, 0xF97, 3 }, + { 0xF99, 0xFBC, 3 }, + { 0xFC6, 0xFC6, 3 }, + { 0x102D, 0x1030, 3 }, + { 0x1032, 0x1037, 3 }, + { 0x1039, 0x103A, 3 }, + { 0x103D, 0x103E, 3 }, + { 0x1058, 0x1059, 3 }, + { 0x105E, 0x1060, 3 }, + { 0x1071, 0x1074, 3 }, + { 0x1082, 0x1082, 3 }, + { 0x1085, 0x1086, 3 }, + { 0x108D, 0x108D, 3 }, + { 0x109D, 0x109D, 3 }, + { 0x135D, 0x135F, 3 }, + { 0x1712, 0x1715, 3 }, + { 0x1732, 0x1734, 3 }, + { 0x1752, 0x1753, 3 }, + { 0x1772, 0x1773, 3 }, + { 0x17B4, 0x17B5, 3 }, + { 0x17B7, 0x17BD, 3 }, + { 0x17C6, 0x17C6, 3 }, + { 0x17C9, 0x17D3, 3 }, + { 0x17DD, 0x17DD, 3 }, + { 0x180B, 0x180D, 3 }, + { 0x180F, 0x180F, 3 }, + { 0x1885, 0x1886, 3 }, + { 0x18A9, 0x18A9, 3 }, + { 0x1920, 0x1922, 3 }, + { 0x1927, 0x1928, 3 }, + { 0x1932, 0x1932, 3 }, + { 0x1939, 0x193B, 3 }, + { 0x1A17, 0x1A18, 3 }, + { 0x1A1B, 0x1A1B, 3 }, + { 0x1A56, 0x1A56, 3 }, + { 0x1A58, 0x1A5E, 3 }, + { 0x1A60, 0x1A60, 3 }, + { 0x1A62, 0x1A62, 3 }, + { 0x1A65, 0x1A6C, 3 }, + { 0x1A73, 0x1A7C, 3 }, + { 0x1A7F, 0x1A7F, 3 }, + { 0x1AB0, 0x1ACE, 3 }, + { 0x1B00, 0x1B03, 3 }, + { 0x1B34, 0x1B3D, 3 }, + { 0x1B42, 0x1B44, 3 }, + { 0x1B6B, 0x1B73, 3 }, + { 0x1B80, 0x1B81, 3 }, + { 0x1BA2, 0x1BA5, 3 }, + { 0x1BA8, 0x1BAD, 3 }, + { 0x1BE6, 0x1BE6, 3 }, + { 0x1BE8, 0x1BE9, 3 }, + { 0x1BED, 0x1BED, 3 }, + { 0x1BEF, 0x1BF3, 3 }, + { 0x1C2C, 0x1C33, 3 }, + { 0x1C36, 0x1C37, 3 }, + { 0x1CD0, 0x1CD2, 3 }, + { 0x1CD4, 0x1CE0, 3 }, + { 0x1CE2, 0x1CE8, 3 }, + { 0x1CED, 0x1CED, 3 }, + { 0x1CF4, 0x1CF4, 3 }, + { 0x1CF8, 0x1CF9, 3 }, + { 0x1DC0, 0x1DFF, 3 }, + { 0x200D, 0x200D, 3 }, + { 0x20D0, 0x20F0, 3 }, + { 0x2CEF, 0x2CF1, 3 }, + { 0x2D7F, 0x2D7F, 3 }, + { 0x2DE0, 0x2DFF, 3 }, + { 0x302A, 0x302F, 3 }, + { 0x3099, 0x309A, 3 }, + { 0xA66F, 0xA672, 3 }, + { 0xA674, 0xA67D, 3 }, + { 0xA69E, 0xA69F, 3 }, + { 0xA6F0, 0xA6F1, 3 }, + { 0xA802, 0xA802, 3 }, + { 0xA806, 0xA806, 3 }, + { 0xA80B, 0xA80B, 3 }, + { 0xA825, 0xA826, 3 }, + { 0xA82C, 0xA82C, 3 }, + { 0xA8C4, 0xA8C5, 3 }, + { 0xA8E0, 0xA8F1, 3 }, + { 0xA8FF, 0xA8FF, 3 }, + { 0xA926, 0xA92D, 3 }, + { 0xA947, 0xA951, 3 }, + { 0xA953, 0xA953, 3 }, + { 0xA980, 0xA982, 3 }, + { 0xA9B3, 0xA9B3, 3 }, + { 0xA9B6, 0xA9B9, 3 }, + { 0xA9BC, 0xA9BD, 3 }, + { 0xA9C0, 0xA9C0, 3 }, + { 0xA9E5, 0xA9E5, 3 }, + { 0xAA29, 0xAA2E, 3 }, + { 0xAA31, 0xAA32, 3 }, + { 0xAA35, 0xAA36, 3 }, + { 0xAA43, 0xAA43, 3 }, + { 0xAA4C, 0xAA4C, 3 }, + { 0xAA7C, 0xAA7C, 3 }, + { 0xAAB0, 0xAAB0, 3 }, + { 0xAAB2, 0xAAB4, 3 }, + { 0xAAB7, 0xAAB8, 3 }, + { 0xAABE, 0xAABF, 3 }, + { 0xAAC1, 0xAAC1, 3 }, + { 0xAAEC, 0xAAED, 3 }, + { 0xAAF6, 0xAAF6, 3 }, + { 0xABE5, 0xABE5, 3 }, + { 0xABE8, 0xABE8, 3 }, + { 0xABED, 0xABED, 3 }, + { 0xFB1E, 0xFB1E, 3 }, + { 0xFE00, 0xFE0F, 3 }, + { 0xFE20, 0xFE2F, 3 }, + { 0xFF9E, 0xFF9F, 3 }, + { 0x101FD, 0x101FD, 3 }, + { 0x102E0, 0x102E0, 3 }, + { 0x10376, 0x1037A, 3 }, + { 0x10A01, 0x10A03, 3 }, + { 0x10A05, 0x10A06, 3 }, + { 0x10A0C, 0x10A0F, 3 }, + { 0x10A38, 0x10A3A, 3 }, + { 0x10A3F, 0x10A3F, 3 }, + { 0x10AE5, 0x10AE6, 3 }, + { 0x10D24, 0x10D27, 3 }, + { 0x10D69, 0x10D6D, 3 }, + { 0x10EAB, 0x10EAC, 3 }, + { 0x10EFC, 0x10EFF, 3 }, + { 0x10F46, 0x10F50, 3 }, + { 0x10F82, 0x10F85, 3 }, + { 0x11001, 0x11001, 3 }, + { 0x11038, 0x11046, 3 }, + { 0x11070, 0x11070, 3 }, + { 0x11073, 0x11074, 3 }, + { 0x1107F, 0x11081, 3 }, + { 0x110B3, 0x110B6, 3 }, + { 0x110B9, 0x110BA, 3 }, + { 0x110C2, 0x110C2, 3 }, + { 0x11100, 0x11102, 3 }, + { 0x11127, 0x1112B, 3 }, + { 0x1112D, 0x11134, 3 }, + { 0x11173, 0x11173, 3 }, + { 0x11180, 0x11181, 3 }, + { 0x111B6, 0x111BE, 3 }, + { 0x111C0, 0x111C0, 3 }, + { 0x111C9, 0x111CC, 3 }, + { 0x111CF, 0x111CF, 3 }, + { 0x1122F, 0x11231, 3 }, + { 0x11234, 0x11237, 3 }, + { 0x1123E, 0x1123E, 3 }, + { 0x11241, 0x11241, 3 }, + { 0x112DF, 0x112DF, 3 }, + { 0x112E3, 0x112EA, 3 }, + { 0x11300, 0x11301, 3 }, + { 0x1133B, 0x1133C, 3 }, + { 0x1133E, 0x1133E, 3 }, + { 0x11340, 0x11340, 3 }, + { 0x1134D, 0x1134D, 3 }, + { 0x11357, 0x11357, 3 }, + { 0x11366, 0x1136C, 3 }, + { 0x11370, 0x11374, 3 }, + { 0x113B8, 0x113B8, 3 }, + { 0x113BB, 0x113C0, 3 }, + { 0x113C2, 0x113C2, 3 }, + { 0x113C5, 0x113C5, 3 }, + { 0x113C7, 0x113C9, 3 }, + { 0x113CE, 0x113D0, 3 }, + { 0x113D2, 0x113D2, 3 }, + { 0x113E1, 0x113E2, 3 }, + { 0x11438, 0x1143F, 3 }, + { 0x11442, 0x11444, 3 }, + { 0x11446, 0x11446, 3 }, + { 0x1145E, 0x1145E, 3 }, + { 0x114B0, 0x114B0, 3 }, + { 0x114B3, 0x114B8, 3 }, + { 0x114BA, 0x114BA, 3 }, + { 0x114BD, 0x114BD, 3 }, + { 0x114BF, 0x114C0, 3 }, + { 0x114C2, 0x114C3, 3 }, + { 0x115AF, 0x115AF, 3 }, + { 0x115B2, 0x115B5, 3 }, + { 0x115BC, 0x115BD, 3 }, + { 0x115BF, 0x115C0, 3 }, + { 0x115DC, 0x115DD, 3 }, + { 0x11633, 0x1163A, 3 }, + { 0x1163D, 0x1163D, 3 }, + { 0x1163F, 0x11640, 3 }, + { 0x116AB, 0x116AB, 3 }, + { 0x116AD, 0x116AD, 3 }, + { 0x116B0, 0x116B7, 3 }, + { 0x1171D, 0x1171D, 3 }, + { 0x1171F, 0x1171F, 3 }, + { 0x11722, 0x11725, 3 }, + { 0x11727, 0x1172B, 3 }, + { 0x1182F, 0x11837, 3 }, + { 0x11839, 0x1183A, 3 }, + { 0x11930, 0x11930, 3 }, + { 0x1193B, 0x1193E, 3 }, + { 0x11943, 0x11943, 3 }, + { 0x119D4, 0x119D7, 3 }, + { 0x119DA, 0x119DB, 3 }, + { 0x119E0, 0x119E0, 3 }, + { 0x11A01, 0x11A0A, 3 }, + { 0x11A33, 0x11A38, 3 }, + { 0x11A3B, 0x11A3E, 3 }, + { 0x11A47, 0x11A47, 3 }, + { 0x11A51, 0x11A56, 3 }, + { 0x11A59, 0x11A5B, 3 }, + { 0x11A8A, 0x11A96, 3 }, + { 0x11A98, 0x11A99, 3 }, + { 0x11C30, 0x11C36, 3 }, + { 0x11C38, 0x11C3D, 3 }, + { 0x11C3F, 0x11C3F, 3 }, + { 0x11C92, 0x11CA7, 3 }, + { 0x11CAA, 0x11CB0, 3 }, + { 0x11CB2, 0x11CB3, 3 }, + { 0x11CB5, 0x11CB6, 3 }, + { 0x11D31, 0x11D36, 3 }, + { 0x11D3A, 0x11D3A, 3 }, + { 0x11D3C, 0x11D3D, 3 }, + { 0x11D3F, 0x11D45, 3 }, + { 0x11D47, 0x11D47, 3 }, + { 0x11D90, 0x11D91, 3 }, + { 0x11D95, 0x11D95, 3 }, + { 0x11D97, 0x11D97, 3 }, + { 0x11EF3, 0x11EF4, 3 }, + { 0x11F00, 0x11F01, 3 }, + { 0x11F36, 0x11F3A, 3 }, + { 0x11F40, 0x11F42, 3 }, + { 0x11F5A, 0x11F5A, 3 }, + { 0x13440, 0x13440, 3 }, + { 0x13447, 0x13455, 3 }, + { 0x1611E, 0x16129, 3 }, + { 0x1612D, 0x1612F, 3 }, + { 0x16AF0, 0x16AF4, 3 }, + { 0x16B30, 0x16B36, 3 }, + { 0x16F4F, 0x16F4F, 3 }, + { 0x16F8F, 0x16F92, 3 }, + { 0x16FE4, 0x16FE4, 3 }, + { 0x16FF0, 0x16FF1, 3 }, + { 0x1BC9D, 0x1BC9E, 3 }, + { 0x1CF00, 0x1CF2D, 3 }, + { 0x1CF30, 0x1CF46, 3 }, + { 0x1D165, 0x1D169, 3 }, + { 0x1D16D, 0x1D172, 3 }, + { 0x1D17B, 0x1D182, 3 }, + { 0x1D185, 0x1D18B, 3 }, + { 0x1D1AA, 0x1D1AD, 3 }, + { 0x1D242, 0x1D244, 3 }, + { 0x1DA00, 0x1DA36, 3 }, + { 0x1DA3B, 0x1DA6C, 3 }, + { 0x1DA75, 0x1DA75, 3 }, + { 0x1DA84, 0x1DA84, 3 }, + { 0x1DA9B, 0x1DA9F, 3 }, + { 0x1DAA1, 0x1DAAF, 3 }, + { 0x1E000, 0x1E006, 3 }, + { 0x1E008, 0x1E018, 3 }, + { 0x1E01B, 0x1E021, 3 }, + { 0x1E023, 0x1E024, 3 }, + { 0x1E026, 0x1E02A, 3 }, + { 0x1E08F, 0x1E08F, 3 }, + { 0x1E130, 0x1E136, 3 }, + { 0x1E2AE, 0x1E2AE, 3 }, + { 0x1E2EC, 0x1E2EF, 3 }, + { 0x1E4EC, 0x1E4EF, 3 }, + { 0x1E5EE, 0x1E5EF, 3 }, + { 0x1E8D0, 0x1E8D6, 3 }, + { 0x1E944, 0x1E94A, 3 }, + { 0x1F3FB, 0x1F3FF, 3 }, + { 0xE0020, 0xE007F, 3 }, + { 0xE0100, 0xE01EF, 3 }, +}; +const size_t k_incb_n = sizeof k_incb / sizeof k_incb[0]; + +} /* namespace ucd */ +} /* namespace rad */ diff --git a/core/text/tokenizer_json.cpp b/core/text/tokenizer_json.cpp index 10cc61ca..4ce100ea 100644 --- a/core/text/tokenizer_json.cpp +++ b/core/text/tokenizer_json.cpp @@ -9,6 +9,7 @@ * vocab_serialize() into the .rad's vocab section, and back. */ #include "text/tokenizer.h" +#include "text/tokenizer_grapheme.h" #include "text/tokenizer_regex.h" #include "text/gguf.h" @@ -164,6 +165,21 @@ int read_normalizer(const json& n, std::vector& out, const char* orig out.push_back(s); return RAD_OK; } + if (t == "Precompiled") { + /* SentencePiece's precompiled character map (T5's), kept base64 as the file carries it + * and decoded at load (tokenizer_grapheme.h). */ + s.kind = RAD_NORM_PRECOMPILED; + s.arg0 = str_or(n, "precompiled_charsmap", ""); + PrecompiledMap pm; + std::string why; + if (s.arg0.empty() || pm.load(s.arg0, &why) < 0) { + RAD_ERR("%s: Precompiled normalizer: %s", origin, + s.arg0.empty() ? "no precompiled_charsmap" : why.c_str()); + return RAD_E_FORMAT; + } + out.push_back(s); + return RAD_OK; + } if (t == "Prepend") { s.kind = RAD_NORM_PREPEND; s.arg0 = str_or(n, "prepend", ""); @@ -385,12 +401,10 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l if (type == "BPE") { out.kind = RAD_TOK_BPE; out.ignore_merges = bool_or(m, "ignore_merges", false); - /* Subword affixes change what every merge produces, and dropout makes encoding random; - * the encoder implements neither. */ - for (const char* k : { "continuing_subword_prefix", "end_of_word_suffix" }) { - const std::string v = str_or(m, k, ""); - if (!v.empty()) return refuse_value(origin, (std::string("BPE ") + k).c_str(), v); - } + /* A continuation prefix changes what every merge produces, and dropout makes encoding + * random; the encoder implements neither. */ + const std::string prefix = str_or(m, "continuing_subword_prefix", ""); + if (!prefix.empty()) return refuse_value(origin, "BPE continuing_subword_prefix", prefix); if (const json* d = get(m, "dropout"); d && d->is_number() && d->get() > 0.0) return refuse_value(origin, "BPE dropout", d->dump()); RAD_TRY(read_text_to_id("BPE")); @@ -434,6 +448,18 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l return RAD_E_UNSUPPORTED; } + /* The end-of-word suffix (CLIP's "") is a model property in tokenizer.json but a step + * here, as byte fallback is below: it changes the symbols a word starts as. */ + if (type == "BPE") { + const std::string eow = str_or(m, "end_of_word_suffix", ""); + if (!eow.empty()) { + VocabStep s; + s.kind = RAD_PRE_END_OF_WORD; + s.arg0 = eow; + out.steps.push_back(s); + } + } + /* Byte fallback is a model property in tokenizer.json but a step here: it changes what the * encoder does on a miss. */ if (bool_or(m, "byte_fallback", false)) { @@ -472,12 +498,17 @@ int read_model(const json& m, VocabBuild& out, const char* origin, uint64_t id_l * The encoder matches an added token against the raw text, exactly as written. HuggingFace's * AddedToken flags each change that: `single_word` matches only between word boundaries, * `normalized` matches against the normalised text (the same thing when there is no normaliser), - * and `lstrip` / `rstrip` take the whitespace beside a match into it. Most files spell out every + * and `lstrip` / `rstrip` take the whitespace beside a match into it. A normalised token becomes a + * RAD_PRE_ADDED_NORMALIZED step, placed first among the pre-tokenisers (so `<|StartOfText|>` under + * a Lowercase is CLIP's `<|startoftext|>`); one whose spelling the normaliser itself changes would + * be matched by that changed spelling, which is refused. Most files spell out every * flag, so a flag is refused only at a value that changes the result. lstrip and rstrip would * also refuse released models (Phi-3's chat markers carry rstrip), and the container has no field * to carry them, so they are warned about instead. */ int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id_limit, - bool has_normalizer) { + const std::vector& norm) { + const bool has_normalizer = !norm.empty(); + std::vector matched_normalized; if (!arr.is_array()) return RAD_OK; std::string stripped; for (const json& e : arr) { @@ -500,14 +531,27 @@ int read_added(const json& arr, VocabBuild& out, const char* origin, uint64_t id const bool special = bool_or(e, "special", false); if (bool_or(e, "single_word", false)) return refuse_value(origin, "added token single_word=true on", content); - if (has_normalizer && bool_or(e, "normalized", false)) - return refuse_value(origin, "added token normalized=true (under a normalizer) on", - content); + if (has_normalizer && bool_or(e, "normalized", false)) { + std::string n = content; + if (vocab_normalize(norm, &n) != RAD_OK || n != content) + return refuse_value(origin, "added token normalized=true (under a normalizer that " + "changes its spelling) on", content); + if (!content.empty()) { + VocabStep st; + st.kind = RAD_PRE_ADDED_NORMALIZED; + st.arg0 = content; + st.iarg = (int64_t)id; + matched_normalized.push_back(st); + } + } if (bool_or(e, "lstrip", false) || bool_or(e, "rstrip", false)) stripped += (stripped.empty() ? "" : " ") + content; out.tokens[id] = content; out.types[id] = special ? (uint8_t)RAD_TT_CONTROL : (uint8_t)RAD_TT_USER_DEFINED; } + /* Ahead of the other pre-tokenisers, after the normalisers. */ + out.steps.insert(out.steps.begin() + (std::ptrdiff_t)norm.size(), matched_normalized.begin(), + matched_normalized.end()); if (!stripped.empty()) RAD_WARN("%s: added tokens %s take the whitespace beside them in HuggingFace (lstrip / " "rstrip); this tokenizer keeps it as text, so prompts with whitespace next to " @@ -544,8 +588,11 @@ void read_config_json(const std::string& dir, VocabBuild& out) { auto it = id_of.find(text); return it == id_of.end() ? -1 : it->second; }; - out.bos = token_id("bos_token"); - out.eos = token_id("eos_token"); + /* An id the post-processor already gave (interpret_tokenizer_json) stays when the config + * names no such token. */ + const int32_t bos = token_id("bos_token"), eos = token_id("eos_token"); + if (bos >= 0 || out.bos < 0) out.bos = bos; + if (eos >= 0 || out.eos < 0) out.eos = eos; out.pad = token_id("pad_token"); out.unk = out.unk >= 0 ? out.unk : token_id("unk_token"); out.sep = token_id("sep_token"); @@ -622,7 +669,7 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi out.steps.insert(out.steps.end(), dec.begin(), dec.end()); if (const json* a = get(j, "added_tokens")) - RAD_TRY(read_added(*a, out, origin, id_limit, !norm.empty())); + RAD_TRY(read_added(*a, out, origin, id_limit, norm)); /* The model's unknown token, by text. The encoder emits it for text no token covers, which * HuggingFace does too; tokenizer_config.json's unk_token, read later, agrees or is absent. */ @@ -654,7 +701,28 @@ int interpret_tokenizer_json(const json& j, uint64_t id_limit, const char* origi * Only a special token before and/or after the sequence is read. The config's * add_bos_token / add_eos_token, read later, win where present. */ if (const json* pp = get(j, "post_processor")) { - if (str_or(*pp, "type", "") == "TemplateProcessing") { + const std::string ppt = str_or(*pp, "type", ""); + /* RobertaProcessing and BertProcessing frame a sequence as `cls $A sep`; they name the + * two tokens, which stand for BOS and EOS where the config names none (CLIP's). */ + if (ppt == "RobertaProcessing" || ppt == "BertProcessing") { + auto framing = [&](const char* k) -> int32_t { + const json* v = get(*pp, k); + int32_t id = -1; + if (!v || !v->is_array() || v->size() != 2 || !read_id((*v)[1], out.tokens.size(), &id)) + return -1; + return id; + }; + const int32_t cls = framing("cls"), sep = framing("sep"); + if (cls < 0 || sep < 0) { + RAD_ERR("%s: %s names no [token, id] cls and sep in the vocabulary", origin, + ppt.c_str()); + return RAD_E_FORMAT; + } + out.bos = cls; + out.eos = sep; + out.add_bos = out.add_eos = true; + } + if (ppt == "TemplateProcessing") { const json* single = get(*pp, "single"); if (single && single->is_array() && !single->empty()) { auto special = [](const json& e) -> bool { return e.is_object() && e.contains("SpecialToken"); }; diff --git a/data/recipes/anima-bf16.recipe b/data/recipes/anima-bf16.recipe new file mode 100644 index 00000000..571ae96c --- /dev/null +++ b/data/recipes/anima-bf16.recipe @@ -0,0 +1,16 @@ +# anima-bf16.recipe -- Anima (Base, Aesthetic or Turbo) at bf16. +# +# rad-convert /split_files/diffusion_models/anima-aesthetic-v1.1.safetensors \ +# --add /split_files/text_encoders/qwen_3_06b_base.safetensors \ +# --add /split_files/vae/qwen_image_vae.safetensors \ +# --config --tokenizer2 /comfy/text_encoders/t5_tokenizer/tokenizer.json \ +# --arch anima --set anima.variant=aesthetic \ +# --recipe data/recipes/anima-bf16.recipe -o anima-aesthetic-bf16.rad +# +# Every linear stays as the release holds it (bf16). Two weights are computed at convert, in f32, +# and stored bf16 here: the patch embedding without its padding-mask columns, and the VAE's causal +# 3-D convolutions read at their last temporal tap. + +dit.x_embed.weight cast dtype=bf16 +decoder.* cast dtype=bf16 +conv2.* cast dtype=bf16 diff --git a/data/recipes/anima-fp8.recipe b/data/recipes/anima-fp8.recipe new file mode 100644 index 00000000..b91d1bfd --- /dev/null +++ b/data/recipes/anima-fp8.recipe @@ -0,0 +1,31 @@ +# anima-fp8.recipe -- Anima (Base, Aesthetic or Turbo) with block-scaled fp8 linears. +# +# rad-convert /split_files/diffusion_models/anima-aesthetic-v1.1.safetensors \ +# --add /split_files/text_encoders/qwen_3_06b_base.safetensors \ +# --add /split_files/vae/qwen_image_vae.safetensors \ +# --config --tokenizer2 /comfy/text_encoders/t5_tokenizer/tokenizer.json \ +# --arch anima --set anima.variant=aesthetic \ +# --recipe data/recipes/anima-fp8.recipe -o anima-aesthetic-fp8.rad +# +# Every linear of the text encoder and of the DiT's 28 blocks (self- and cross-attention, MLP) +# becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the fp8a8 GEMMs over activations +# quantised the same way. The LLM adapter, the embeddings, the modulation linears, the final layer +# and the VAE stay bf16. The patch embedding (without its padding-mask columns) and the VAE's causal +# convolutions (at their last temporal tap) are computed at convert and stored bf16. + +te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.cross_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.cross_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.cross_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.cross_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.mlp_layer1.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dit.blk.*.mlp_layer2.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +dit.x_embed.weight cast dtype=bf16 +decoder.* cast dtype=bf16 +conv2.* cast dtype=bf16 diff --git a/data/recipes/krea-2-fp8-unscaled.recipe b/data/recipes/krea-2-fp8-unscaled.recipe new file mode 100644 index 00000000..11a12f07 --- /dev/null +++ b/data/recipes/krea-2-fp8-unscaled.recipe @@ -0,0 +1,45 @@ +# krea-2-fp8-unscaled.recipe -- a Krea 2 finetune shipped as plain fp8 (every tensor E4M3 with no +# scale, as ComfyUI's fp8 checkpoints and most civitai Krea 2 files store it), with block-scaled fp8 +# linears. +# +# rad-convert \ +# --recipe data/recipes/krea-2-fp8-unscaled.recipe -o finetune-fp8.rad +# +# The DiT's and the text fusion's linears keep the checkpoint's codes: every value is already on the +# E4M3 grid, so a block scale of exactly 1 (rule=fixed) holds each one as the code it was shipped +# as, where an absmax scale would round it a second time. The text encoder is the release's bf16 and +# is rounded as krea-2-fp8.recipe rounds it. The norms, tables and embedders the finetune stores as +# E4M3 are widened exactly to the dtypes krea-2-fp8.recipe gives them. A Turbo finetune takes +# Turbo's model_index.json (`is_distilled`: 8 steps, no guidance), a Raw one Raw's. + +te.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +te.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +fuse.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +fuse.*.attn_gate.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +fuse.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +fuse.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +fuse.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +dit.blk.*.attn_qkv.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +dit.blk.*.attn_gate.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +dit.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +dit.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 +dit.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 rule=fixed scale_value=1 + +# The release stores its norms, modulation tables, embedders, projector and output layer f32. +# diffusers keeps every norm f32 and runs the rest bf16. Here the text fusion's norms, the q/k norms +# and txt_in's norm stay f32; the DiT's norm1, norm2 and final norm are bf16, the fused modulation +# kernel's operand, with the rest. +fuse.*.norm1.weight cast dtype=f32 +fuse.*.norm2.weight cast dtype=f32 +fuse.*.q_norm.weight cast dtype=f32 +fuse.*.k_norm.weight cast dtype=f32 +dit.blk.*.q_norm.weight cast dtype=f32 +dit.blk.*.k_norm.weight cast dtype=f32 +txt.norm.weight cast dtype=f32 +fuse.* cast dtype=bf16 +txt.* cast dtype=bf16 +dit.* cast dtype=bf16 +vae.* cast dtype=bf16 diff --git a/data/recipes/q38-27b-mxfp4-df2.recipe b/data/recipes/q38-27b-mxfp4-df2.recipe new file mode 100644 index 00000000..0c39e4ca --- /dev/null +++ b/data/recipes/q38-27b-mxfp4-df2.recipe @@ -0,0 +1,41 @@ +# q38-27b-mxfp4-df2.recipe -- a bf16 Qwen3.8-27B (or a finetune of it) at MXFP4 with the DFlash2 +# drafter. +# +# rad-convert --draft-model \ +# --recipe q38-27b-mxfp4-df2.recipe \ +# --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \ +# -o q38-27b-mxfp4-df2.rad +# +# The --set keys give the container the family's fp8 descriptor, so qwen35_fp8 serves it as it +# serves the Quark, ParoQuant and NVFP4 releases; without them a bf16 checkpoint selects +# qwen35_bf16, which has no 4-bit GEMM. +# +# The trunk's linears are rounded to MXFP4 (`fp4_e2m1`, an e8m0 scale per 32 of K, the OCP exponent +# rule) from the bf16 source, once: the encoding and kernels of q38-27b-quark-mxfp4-df2.recipe, +# without Quark's AWQ fold. The delta net's a/b projections, the norms, the embedding and the +# vision tower stay bf16; the head goes block fp8 as in the other 27B recipes. The checkpoint's MTP +# head is not read: the DFlash2 drafter displaces it. +# +# The drafter as q38-27b-quark-mxfp4-df2.recipe makes it: its linears at MXFP4, and a 2-bit copy +# of the target's head (u2 with a u8 zero, least-squares clip search) whose top 32 the engine +# rescores against the target's fp8 head. + +blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.attn_qg.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ssm_inz.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ssm_out.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 rule=search + +dflash.fc.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 diff --git a/data/recipes/sdxl-bf16.recipe b/data/recipes/sdxl-bf16.recipe new file mode 100644 index 00000000..66902a70 --- /dev/null +++ b/data/recipes/sdxl-bf16.recipe @@ -0,0 +1,9 @@ +# sdxl-bf16.recipe -- Stable Diffusion XL (and its finetunes: Illustrious, NoobAI, Pony, ...) at bf16. +# +# rad-convert .safetensors --tokenizer \ +# --recipe data/recipes/sdxl-bf16.recipe -o sdxl.rad +# +# A single-file SDXL checkpoint (Stability's layout) ships its weights f16, some finetunes partly +# bf16 or f32; every weight the model reads is served bf16. The VAE's encoder, the text encoders' +# unused tails and the checkpoint's bookkeeping tensors are not carried. +* cast dtype=bf16 diff --git a/deploy/compose/anima.yaml b/deploy/compose/anima.yaml new file mode 100644 index 00000000..794863e3 --- /dev/null +++ b/deploy/compose/anima.yaml @@ -0,0 +1,19 @@ +# Anima Aesthetic (circlestone-labs/Anima) as block fp8: text to image on OpenAI's +# /v1/images/generations, on one card, RADIANCE_GPU in .env (default 0). The Base and Turbo +# containers serve the same way (anima-base-fp8.rad, anima-turbo-fp8.rad). +# The CircleStone Labs Non-Commercial License and NVIDIA's Open Model License apply to the model; +# the pictures may be used commercially. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/anima and add `--lora-dir /models/loras/anima` to the command; +# a request names them in `loras` or as in its prompt. +name: radiance-anima +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-anima + environment: + ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}" + command: > + --model /models/anima-aesthetic-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 diff --git a/deploy/compose/fasth3.yaml b/deploy/compose/fasth3.yaml index 921fc5f6..f6c265b3 100644 --- a/deploy/compose/fasth3.yaml +++ b/deploy/compose/fasth3.yaml @@ -2,6 +2,9 @@ # distilled to eight steps with video sparse attention, the same /v1/videos API and host memory # as minimax-h3.yaml, about 70 s a 1344x768 clip. It runs only its trained schedule, so a # request's num_inference_steps may only be 9 (grid points). MiniMax-H3's license applies to it. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/h3 and add `--lora-dir /models/loras/h3` to the command; +# a request names them in `loras` or as in its prompt. name: radiance-fasth3 services: radiance: diff --git a/deploy/compose/flux-3-klein.yaml b/deploy/compose/flux-3-klein.yaml index b3214063..ecc70aba 100644 --- a/deploy/compose/flux-3-klein.yaml +++ b/deploy/compose/flux-3-klein.yaml @@ -2,6 +2,9 @@ # to ten reference pictures on OpenAI's /v1/images/generations and /v1/images/edits, on one card, # RADIANCE_GPU in .env (default 0). For the base model, point --model at flux-3-klein-base-fp8.rad. # The FLUX Kommunity License (non-commercial use) applies. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/flux3 and add `--lora-dir /models/loras/flux3` to the command; +# a request names them in `loras` or as in its prompt. name: radiance-flux-3-klein services: radiance: diff --git a/deploy/compose/krea-2-raw.yaml b/deploy/compose/krea-2-raw.yaml index f65e554a..527cadf6 100644 --- a/deploy/compose/krea-2-raw.yaml +++ b/deploy/compose/krea-2-raw.yaml @@ -1,6 +1,9 @@ # Krea 2 Raw (krea/Krea-2-Raw) as block fp8: text to image on OpenAI's /v1/images/generations, on one # card, RADIANCE_GPU in .env (default 0). The Krea 2 Community License and Krea's acceptable use # policy apply. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/krea2 and add `--lora-dir /models/loras/krea2` to the command; +# a request names them in `loras` or as in its prompt. name: radiance-krea-2-raw services: radiance: diff --git a/deploy/compose/krea-2-turbo.yaml b/deploy/compose/krea-2-turbo.yaml index 87b6f3cc..c15e9223 100644 --- a/deploy/compose/krea-2-turbo.yaml +++ b/deploy/compose/krea-2-turbo.yaml @@ -1,6 +1,9 @@ # Krea 2 Turbo (krea/Krea-2-Turbo) as block fp8: text to image on OpenAI's /v1/images/generations, # on one card, RADIANCE_GPU in .env (default 0). # The Krea 2 Community License and Krea's acceptable use policy apply. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/krea2 and add `--lora-dir /models/loras/krea2` to the command; +# a request names them in `loras` or as in its prompt. name: radiance-krea-2-turbo services: radiance: diff --git a/deploy/compose/ltx-2.5.yaml b/deploy/compose/ltx-2.5.yaml index 0c737922..287f1dd3 100644 --- a/deploy/compose/ltx-2.5.yaml +++ b/deploy/compose/ltx-2.5.yaml @@ -2,6 +2,10 @@ # from text or from text and a first frame, on OpenAI's /v1/videos, on one card, RADIANCE_GPU in # .env (default 0). The text encoder is read from pinned host memory (--vision-tower-placement ram). # For the base model, point --model at ltx-2.5-fp8.rad. The LTX-2.x Community License applies. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/ltx2 and add `--lora-dir /models/loras/ltx2` to the command; +# a request names them in `loras` or as in its prompt. +# At one card the adapter slots fit at `--max-lora-rank 16 --max-loras 1` (433 MiB). name: radiance-ltx-2.5 services: radiance: diff --git a/deploy/compose/minimax-h3.yaml b/deploy/compose/minimax-h3.yaml index ad684a2e..548a7e71 100644 --- a/deploy/compose/minimax-h3.yaml +++ b/deploy/compose/minimax-h3.yaml @@ -3,6 +3,9 @@ # The text encoder and the modulation projections are read from pinned host memory # (--vision-tower-placement ram), about 39 GiB of it. MiniMax-H3's license excludes use in the EU, # the UK, the Republic of Korea and the USA. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/h3 and add `--lora-dir /models/loras/h3` to the command; +# a request names them in `loras` or as in its prompt. name: radiance-minimax-h3 services: radiance: diff --git a/deploy/compose/qwen-image-2.1-turbo.yaml b/deploy/compose/qwen-image-2.1-turbo.yaml index e1916d52..0df9ae68 100644 --- a/deploy/compose/qwen-image-2.1-turbo.yaml +++ b/deploy/compose/qwen-image-2.1-turbo.yaml @@ -2,6 +2,9 @@ # qwen-image-2.1.yaml's model, the same images API, 2048x2048 by default. It samples on its own # 8-step schedule, so a request's num_inference_steps may only be 8. --tp-wire wht6 sends the DiT's # all-reduces as 6-bit; drop it for the exact wire. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/qwen-image and add `--lora-dir /models/loras/qwen-image` to the command; +# a request names them in `loras` or as in its prompt. name: radiance-qwen-image-turbo services: radiance: diff --git a/deploy/compose/qwen-image-2.1.yaml b/deploy/compose/qwen-image-2.1.yaml index 233841c3..3febe137 100644 --- a/deploy/compose/qwen-image-2.1.yaml +++ b/deploy/compose/qwen-image-2.1.yaml @@ -5,6 +5,9 @@ # batch and context for an image generator itself (docs/GUIDE.md §5.6). --tp-wire wht6 sends the # DiT's all-reduces as 6-bit: about 10% faster per picture at a cost of a few tenths of a dB # against diffusers; drop it for the exact wire. +# LoRA files (Civitai and the like, docs/GUIDE.md §4.9.2): put them under +# $RADIANCE_MODELS/loras/qwen-image and add `--lora-dir /models/loras/qwen-image` to the command; +# a request names them in `loras` or as in its prompt. name: radiance-qwen-image services: radiance: diff --git a/deploy/compose/sdxl.yaml b/deploy/compose/sdxl.yaml new file mode 100644 index 00000000..a7bf5d82 --- /dev/null +++ b/deploy/compose/sdxl.yaml @@ -0,0 +1,15 @@ +# Stable Diffusion XL or one of its finetunes (here Illustrious-XL v2.0, OnomaAIResearch) at bf16: text +# to image on OpenAI's /v1/images/generations, on one card, RADIANCE_GPU in .env (default 0). Any +# single-file SDXL checkpoint converts the same way (README, "Stable Diffusion XL"); point --model +# at its container. The checkpoint's own license applies. +name: radiance-sdxl +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-sdxl + environment: + ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}" + command: > + --model /models/illustrious-xl-v2.0-bf16.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index dadd297e..9c11fd90 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -22,7 +22,9 @@ plugin claims. | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 | | `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 | | `arch/krea2` | `krea2` | *(empty)* | Krea 2 Raw and Turbo, an image generator: Qwen3-VL-4B's tapped layers through a text-fusion transformer, a 12.9B single-stream DiT and Wan 2.1's VAE, from the diffusers pipeline directory; bf16 or block fp8 | +| `arch/sdxl` | `sdxl` | *(empty)* | Stable Diffusion XL and its finetunes (Illustrious, NoobAI, Pony), an image generator: CLIP ViT-L and OpenCLIP bigG text encoders, the 2.6B UNet sampled by k-diffusion's Euler, Euler ancestral or DPM++ 2M on ComfyUI's schedules, the SDXL VAE; from the single-file checkpoint, bf16, one card | | `arch/flux3` | `flux3` | *(empty)* | FLUX.3 [klein] and its base, an image generator and editor: Qwen3-VL-4B's tapped layers, a 5.6B three-mode DiT over the text, up to ten reference pictures and the image, FLUX.2's VAE; bf16 or block fp8 | +| `arch/anima` | `anima` | *(empty)* | Anima (Base, Aesthetic, Turbo), an image generator: Qwen3-0.6B-Base through the LLM adapter over the prompt's T5 tokens, Cosmos-Predict2's 2B cross-attention DiT and the Qwen-Image VAE, from the release's single files; bf16 or block fp8, one card | | `arch/flux3distilled` | `flux3distilled` | *(empty)* | the same plugin under the name FLUX.3 [klein]'s step-distilled release gives itself (`Flux3DistilledModularPipeline`; its base is a `Flux3ModularPipeline`) | | `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text | | `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 | @@ -39,6 +41,25 @@ The traps below are readings that are wrong without any error: the model produce widths, the KV page size and the attention kernel's band. `core/engine_bringup.cpp` takes it from the container's meta. +## Adapter key names of the generators + +A generator that serves LoRA files ([GUIDE §4.9.2](GUIDE.md)) declares, before its GEMMs, how +those files name its modules (`rad_lora_root`, `rad_lora_alias`; `lora_names` in +`arch/common/rad_arch.h`). Files follow the model's original code or ComfyUI's port of it, while +containers keep the diffusers names, and the two disagree in ways that load without an error and +generate garbage: a fused `qkv` against separate q, k and v, a SwiGLU projection whose gate half +comes first in one and second in the other. The tables, by plugin: + +| plugin | adapter files | checkpoint | +|---|---|---| +| `krea2` | `blocks.N.attn.wq/wk/wv/wo/gate`, `mlp.gate/up/down`, `txtfusion.{layerwise,refiner}_blocks.N.*`, `first`, `last_linear`, `tmlp.0/2`, `tproj.1`, `txtmlp.1/3` | `transformer_blocks.N.attn.to_q/...`, `ff.*`, `text_fusion.*`, `img_in`, `final_layer.linear`, `time_embed.linear_1/2`, `time_mod_proj`, `txt_in.linear_1/2` | +| `qwenimage21` | the checkpoint's names, or `img_mlp.gate_up` = [gate; up] | `img_mlp.gate_layer`, `img_mlp.proj` | +| `minimaxh3` | `blocks.N.attn.qkv_proj` (q, k, v), `out_proj`, `mlp.fc1` = [gate; up], `fc2`; `token_refiner.blocks.N.*`; `video_patch_proj`, `audio_patch_proj`, `condition_proj`, `time_embedder.proj_in/out`, `final_layer.video_out/audio_out` | `attn.to_q/k/v`, `to_out.0`, `ff.net.0.proj` = [up; gate], `ff.net.2`; `token_refiner.refiner_blocks.N.*`; `proj_in`, `audio_proj_in`, `context_embedder`, `time_embedder.linear_1/2`, `proj_out`, `audio_proj_out` | +| `flux3` | `single_blocks.N`, `txt_mode_blocks.N`, `content_mode_blocks.{image,image_cond}.N` with `q_proj/k_proj/v_proj` or `qkv`, `attn_out`, `mlp_in`, `mlp_out` | `single_transformer_blocks.N`, `txt_mode_blocks.N`, `mode_blocks.{image,image_cond}.N` with `attn.to_q/k/v`, `attn.to_out.0`, `ff.linear_in/out` | +| `ltx2` | the checkpoint's names | | +| `anima` | the checkpoint's names behind `diffusion_model.` / `lora_unet_`; the text encoder as `lora_te_layers_N_...` | DiT under `net.` or `model.diffusion_model.`, Qwen3 under `model.layers.` | +| `sdxl` | kohya's `lora_unet_` over the single-file UNet paths (convolutions included), `lora_te1_` / `lora_te2_` over the CLIPs' transformers names | UNet under `model.diffusion_model.`, CLIP-L and bigG under `conditioner.embedders.{0,1}.transformer.` | + --- # `llama`: the plain decoder @@ -922,6 +943,76 @@ quantisation's: the container's codes decoded to bf16 on the host give the same --- +# `sdxl`: Stable Diffusion XL and its finetunes, an image generator + +`arch/sdxl` serves SDXL 1.0 and every finetune published as one `.safetensors` in Stability's +(sgm) layout: Illustrious, NoobAI, Pony and the civitai checkpoints built on them. rad-convert's +importer (`core/format/checkpoint.cpp`, `open_sgm`) reads the file as it ships; the plugin is a +JOINT_STEP generator whose conditioning rides in each lane's store and is read by the UNet's cross +attention, and whose sampler is the core's discrete-time one (`RadGeneratorDecl::train_steps`). + +``` +names the UNet under model.diffusion_model.*, CLIP ViT-L under + conditioner.embedders.0.transformer.text_model.*, both as the file has them; OpenCLIP + bigG renamed to transformers' CLIPTextModelWithProjection under + conditioner.embedders.1.transformer.* (in_proj split into q/k/v_proj, c_fc/c_proj as + fc1/fc2, ln_* as layer_norm*, text_projection transposed into a linear's weight); the VAE + decoder in diffusers' names under vae.*. These are the names kohya's lora_unet_*, + lora_te1_* and lora_te2_* adapters are written against +text the prompt in CLIP windows: BOS, up to 75 tokens, EOS, padding to 77 (the core cuts them, + RadGeneratorDecl::chunk_tokens), each window encoded on its own and causally. ViT-L (12 + layers, quick_gelu) and bigG (32 layers, gelu); the context is ViT-L's and bigG's + PENULTIMATE hidden states side by side (2048 wide, no final norm); the pooled vector is + bigG's LAST layer through final_layer_norm at the first window's EOS, through + text_projection +padding ViT-L's padding is EOS (49407), bigG's is token 0 ("!"), as the two tokenizers pad; the + padded rows are part of the context the UNet attends to +UNet 320/640/1280 channels at 1, 1/2, 1/4 of the latent; residual blocks (GroupNorm(32) eps + 1e-5, SiLU, 3x3 conv, the time embedding's projection added per channel, a 1x1 skip when + the width changes); spatial transformers (GroupNorm eps 1e-6, linear proj_in/out, blocks + of self attention, cross attention over the context and GEGLU, 64-wide heads) 2 deep at + 1/2, 10 deep at 1/4 and in the middle; skip connections concatenated after h +added the time embedding (sinusoid of the timestep, cos first, 320 wide) plus label_emb of + [pooled | sinusoids of (height, width), (0, 0), (height, width)] (2816 wide) +VAE AutoencoderKL, 4 channels at 8x, the latent divided by 0.13025; run bf16 +sampler k-diffusion over 1000 scaled-linear timesteps (betas 0.00085..0.012): f32 latent lanes, + the UNet's input x / sqrt(sigma^2 + 1), the timestep the nearest trained one (ComfyUI), + guidance on the denoised estimates; Euler, Euler ancestral, DPM++ 2M on ComfyUI's + normal, karras, exponential, sgm_uniform and simple schedules +``` + +Each denoising pass runs the UNet once per entry at that entry's size: a convolution's image size +comes from its operands, so two sizes cannot share a launch. The sampler ops run over every entry. +Every 3x3 convolution is `im2col_nhwc` and a `gemm_nt_bias` over the weight read as +`[cout, cin * 9]` (the checkpoint's order), so it carries a runtime LoRA like a linear; this is 9% +faster than `conv2d_nhwc` over the UNet's shapes at 1024x1024, slower only at 1/1 with 320 +channels. conv_in and out.2 (4 channels) are direct convolutions. + +Traps: + +- **The context is the penultimate layer of both encoders.** hidden_states[-2], before any final + norm; only the pooled vector goes through bigG's final norm, from its last layer. +- **bigG's padding is not EOS.** Its tokenizer pads with "!"; reading the padding as EOS changes + the context rows the UNet attends to (it does not change the pooled vector). +- **The size conditioning is (height, width), not (width, height)**, each through its own + 256-wide sinusoid, after the pooled vector. +- **open_clip's text_projection multiplies from the right** (x @ P); a linear's weight is P^T. +- **bf16, not f16.** The release is f16 and the SDXL VAE overflows in f16; bf16 has f32's range. + +Against a torch reference -- diffusers' text encoders, UNet and VAE in f32 under the same +k-diffusion loop, schedule and Philox noise -- from the same seeds at 1024x1024 on one R9700 (relative +L2; diffusers' own bf16 run against the same f32 one in brackets): ViT-L's context 0.28% (0.28%), +bigG's 1.8% (2.0%), the pooled vector 0.9% (1.0%), the UNet's first evaluation 0.25% (0.31%); the VAE +on the same latent 45.0 dB. Whole pictures (PSNR against f32; diffusers bf16 in brackets): SDXL 1.0 +Euler 31.3 dB (27.4), DPM++ 2M Karras 34.6 dB, Euler ancestral 24.8 dB (18.0); Illustrious-XL v2.0 +Euler 30.0 dB, Euler ancestral 22.3 dB (25.7), 832x1216 Euler 33.1 dB (28.3 against a reference +given (width, height) for its size); NoobAI-XL V-Pred 1.0 (v prediction, zero terminal +SNR) Euler 22.4 dB (22.6). A 91-token prompt's two windows against the same windows encoded by +transformers in f32 (Illustrious): ViT-L 0.7% in each, bigG 1.6% and 2.2%, the pooled vector 1.3%. +An image is the same bytes whether its pass carries other requests' images of other sizes or not. + +--- + # `flux3`: FLUX.3 [klein] and its base, an image generator and editor `arch/flux3` declares a JOINT_STEP generator over three modes: the text, the reference pictures' @@ -968,6 +1059,64 @@ base guided 2.30, an edit with one reference picture 1.16. --- +# `anima`: Anima (Base, Aesthetic, Turbo), an image generator + +`arch/anima` declares a JOINT_STEP generator, though its DiT is a cross-attention model: the +conditioning pass leaves each lane's 512 context rows in its store, and every denoising step reads +them back (the entry's text mode, `mode_src`) for the cross-attention's keys and values; the text +rows the layout carries are never run through the DiT. Served on `/v1/images/generations`; it +takes no reference pictures. + +``` +text Qwen3-0.6B-Base over the prompt as it is (no template); its last hidden state after the + final norm. An empty prompt is one <|endoftext|> (min_tokens 1), not " " +adapter the LLM adapter: the prompt's T5 tokens (the container's second vocabulary) as query + rows, embedded from a 32128-row table; six blocks of RMS-normed self-attention over them, + cross-attention to the Qwen3 rows and a GELU MLP, 16 heads of 64, q and k RMS-normed and + rotated (NeoX, theta 1e4) at their own row index on either side; out_proj and an RMS + norm; zero-padded to 512 rows +DiT Cosmos-Predict2's MiniTrainDIT at 2B: 28 blocks of 2048 (16 heads of 128); per block a + self-attention (q/k RMS norms, a NeoX rotary of 22 + 21 + 21 frequency pairs over + frame, row and column at 10000 x 4^(42/40); the frame is 0), a cross-attention to the + 512 context rows (q/k norms, no rotary) and a GELU MLP, each behind a LayerNorm without + affine times (1 + scale) plus shift and added back times its gate +modulation each of a block's three: Linear(256, 6144)(Linear(2048, 256)(silu(e))) + the shared + AdaLN-LoRA term Linear(2048, 6144)(silu(Linear(2048, 2048)(t))), t the sinusoid of the + step's sigma (a timestep in [0, 1], [cos | sin]) and e its RMS norm +patches a token is 2 x 2 latents, 64 values channel-major; the patch embedding was trained on 68 + (a padding-mask channel, always zero), read over its first 64 columns (RAD_MAP_COLS); + the final linear's rows reordered from (row, column, channel) to channel-major +VAE the Qwen-Image VAE under ComfyUI's Wan 2.1 names, 16 channels at 8x; the latent + denormalised with Wan 2.1's statistics in f32 +schedule ComfyUI's FLOW sampling (multiplier 1, shift 3) and its `simple` scheduler over 1000 + timesteps (sigma_grid), Euler steps; guidance uncond + s (cond - uncond). Base and + Aesthetic: 30 steps, s 4, the card's negative prompt; Turbo: 10 steps, unguided. The + variant is `anima.variant` (rad-convert --set) +``` + +Traps: + +- **T5 tokens, not Qwen3's, are the queries.** The adapter reads the same prompt twice: Qwen3's + ids for the source, T5's for the queries; T5's normaliser is SentencePiece's precompiled map + over extended grapheme clusters (core/text/tokenizer_grapheme.h). Reading the queries off Qwen3's + tokens gives a plausible, wrong picture. +- **The padding rows are attended to.** The context is zero-padded to 512 rows and the DiT's + cross-attention reads all 512: a zero row is a zero key and value, which still takes its share + of the softmax. +- **The DiT keys have two spellings.** Base ships `net.blocks.N...`, Aesthetic 1.1 and Turbo 1.1 + `model.diffusion_model.blocks.N...`; the plugin reads the prefix off the checkpoint at convert + and keeps the file's own names as the name map's sources. +- **The empty negative prompt is not " ".** ComfyUI encodes "" as one padding token for Qwen3 and + for T5; the core keeps an empty prompt empty for a model with `min_tokens`. + +Against ComfyUI in bf16 on an RTX 4090 from the same noise: the DiT's velocity at sigma 1 rel +0.48% (cos 0.99999) from the bf16 container and 1.5% from the block-fp8 one, the adapter's 512 rows +rel 1.9% (Qwen3's output in bf16 against ComfyUI's f32), the VAE on the same latent 46.9 dB; three +1024 x 1024 pictures after 30 guided steps 32.8, 36.0 and 39.0 dB from bf16, 26.7, 26.0 and 28.6 dB +from fp8 (the same picture to the eye). + +--- + # `qwen3asr`: speech to text `model_type: qwen3_asr` (`Qwen3ASRForConditionalGeneration`), served from the checkpoint as it diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 99f58bb1..4d1bbb43 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -145,7 +145,9 @@ the cards the engine runs on. | `qwen-image-2.1.yaml` | `qwen-image-2.1-fp8.rad` | Qwen-Image 2.1 as block fp8 on two cards: OpenAI's images API, generation and edits | | `qwen-image-2.1-turbo.yaml` | `qwen-image-2.1-turbo-fp8.rad` | Qwen-Image 2.1 Turbo, the same in 8 steps | | `krea-2-turbo.yaml`, `krea-2-raw.yaml` | `krea-2-turbo-fp8.rad`, `krea-2-raw-fp8.rad` | Krea 2 Turbo and Raw as block fp8: text to image on one card (`RADIANCE_GPU`) | +| `anima.yaml` | `anima-aesthetic-fp8.rad` | Anima Aesthetic as block fp8: text to image on one card (`RADIANCE_GPU`); the Base and Turbo containers serve the same way | | `flux-3-klein.yaml` | `flux-3-klein-fp8.rad` | FLUX.3 [klein] as block fp8: generation and edits on one card (`RADIANCE_GPU`); the base container serves the same way | +| `sdxl.yaml` | `illustrious-xl-v2.0-bf16.rad` | Stable Diffusion XL in bf16 (here Illustrious-XL v2.0; any single-file SDXL checkpoint converts the same way): text to image on one card (`RADIANCE_GPU`) | | `qwen3-asr-1.7b.yaml` | `Qwen3-ASR-1.7B-hf/` (the checkpoint) | Qwen3-ASR 1.7B: `/v1/audio/transcriptions` and live `/v1/realtime`, on one card (`RADIANCE_GPU`) | | `minimax-h3.yaml` | `minimax-h3-fp8.rad` | MiniMax-H3 as block fp8: video with its stereo soundtrack on `/v1/videos`, two cards and about 39 GiB of pinned host memory | | `fasth3.yaml` | `fasth3-8-step-v2-fp8.rad` | FastVideo's FastH3 8-Step V2, the same in eight steps | diff --git a/docs/GUIDE.md b/docs/GUIDE.md index cad2fee6..6c89aebb 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -277,6 +277,7 @@ and runs. | `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) | | `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) | | `krea2` | Krea 2 Raw and Turbo, an image model from text (§5.6) | +| `anima` | Anima Base, Aesthetic and Turbo, an anime and illustration image model from text (§5.6) | | `flux3`, `flux3distilled` | FLUX.3 [klein] and its base, an image model that also edits (§5.6); one plugin under the two names the releases give themselves | | `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) | | `minimaxmusic3` | MiniMax-Music3, songs from a description and lyrics (§5.15) | @@ -405,6 +406,36 @@ rad-convert /srv/models/krea/Krea-2-Turbo -o krea-2-turbo-fp8.rad \ rad-convert /srv/models/black-forest-labs/flux-3-image-klein -o flux-3-klein-fp8.rad \ --recipe data/recipes/flux-3-klein-fp8.recipe +# A Krea 2 finetune shipped as one DiT file in Krea's key names (civitai, ComfyUI): rewritten as the +# transformer/ of a directory holding the release's other parts (Turbo's model_index.json for a Turbo +# finetune, Raw's for a Raw one); a plain-fp8 file keeps its codes under krea-2-fp8-unscaled.recipe +P=/srv/models/lustify-krea2; mkdir -p $P/transformer +cp -r /srv/models/krea/Krea-2-Turbo/{model_index.json,scheduler,text_encoder,tokenizer,vae} $P/ +cp /srv/models/krea/Krea-2-Turbo/transformer/config.json $P/transformer/ +scripts/krea2_native.py lustifyNSFWCheckpoint_v10Krea2_fp8.safetensors \ + $P/transformer/diffusion_pytorch_model.safetensors +rad-convert $P -o lustify-krea2-turbo-fp8.rad --recipe data/recipes/krea-2-fp8-unscaled.recipe + +# Anima, an image model (§5.6): the release's three single files merged (--add), Qwen3-0.6B-Base's +# config.json and tokenizer.json (--config: the repository or a directory with just those two), and +# ComfyUI's T5 tokenizer (comfy/text_encoders/t5_tokenizer/tokenizer.json, with its +# tokenizer_config.json beside it) as the second vocabulary. The variant (base, aesthetic, turbo) +# sets the defaults; anima-bf16.recipe keeps every linear bf16 +A=/srv/models/circlestone-labs/Anima/split_files +rad-convert $A/diffusion_models/anima-aesthetic-v1.1.safetensors \ + --add $A/text_encoders/qwen_3_06b_base.safetensors --add $A/vae/qwen_image_vae.safetensors \ + --config /srv/models/Qwen/Qwen3-0.6B-Base --tokenizer2 /srv/ComfyUI/comfy/text_encoders/t5_tokenizer/tokenizer.json \ + --arch anima --set anima.variant=aesthetic -o anima-aesthetic-fp8.rad \ + --recipe data/recipes/anima-fp8.recipe + +# Stable Diffusion XL or any of its finetunes (Illustrious, NoobAI, Pony, ...), an image model +# (§5.6): the single .safetensors as civitai and Hugging Face publish it (Stability's layout, read as +# it ships), bf16 throughout (6.4 GiB, one card). The file carries no tokenizer: CLIP's tokenizer.json +# (openai/clip-vit-large-patch14) is passed beside it +rad-convert /srv/models/OnomaAIResearch/Illustrious-XL-v2.0/Illustrious-XL-v2.0.safetensors \ + -o illustrious-xl-v2.0-bf16.rad --recipe data/recipes/sdxl-bf16.recipe \ + --tokenizer /srv/models/openai/clip-vit-large-patch14/tokenizer.json + # LTX-2.5, video with sound (§5.16): the diffusers pipeline directory, latent_upsampler/ included # for the distilled release's two-stage recipe; fp8 blocks for the text encoder, the connectors and # the DiT, or bf16 (both recipes keep the vocoders f32, which they run in) @@ -515,6 +546,13 @@ rad-convert /srv/models/amd/GLM-5.3-Flash-Quark-MXFP4 \ rad-convert /srv/models/unsloth/Qwen3.8-27B-NVFP4 --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \ --recipe data/recipes/q38-27b-nvfp4-df2.recipe -o q38-27b-nvfp4-df2.rad +# A bf16 Qwen3.8-27B or finetune (here orcarouter's Uncensored) with the DFlash2 drafter: the trunk +# rounded to MXFP4 once, the head block fp8; the --set keys select the quantised plugin +rad-convert /srv/models/orcarouter/Qwen3.8-27B-Uncensored --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 \ + --recipe data/recipes/q38-27b-mxfp4-df2.recipe \ + --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \ + -o qwen3.8-27b-uncensored-mxfp4.rad + # An int4 W4A16 Qwen3.8-27B (compressed-tensors AWQ or GPTQ, AutoRound's auto_gptq; here ukisai's # Swift 1.5 W4A16-AWQ, and its INT4 and W4A16-AutoRound the same way): the shipped grids on the # 4-bit GEMMs, the head block fp8 @@ -1345,11 +1383,57 @@ below. Refused at startup or load, by name: DoRA, embedding or `lm_head` LoRA, `modules_to_save`, trained biases, PEFT's `layer_replication`, QA-LoRA and activated LoRA, a module the base does not have, and a module some op cannot carry -- a routed MoE expert, a rotated (ParoQuant) or otherwise transformed -weight, a GEMM fed int8 codes in the WMMA's step order (`w4a8`, `w8a8`, `w2a8`). Adapters serve models that generate text: an -image, audio or video generator and an embedding model refuse `--lora` and `--max-loras`. A fused -GEMM over a targeted weight (the fp8 gated gate_up fold) is not used while LoRA is on, for base -requests too; the unfused pair runs instead. A drafter keeps the base's weights: proposals are -still verified by the adapter, so output is exact and only the acceptance rate can drop. +weight, a GEMM fed int8 codes in the WMMA's step order (`w4a8`, `w8a8`, `w2a8`). An audio +generator and an embedding model refuse `--lora` and `--max-loras`; image and video generators take +adapter files instead (§4.9.2). A fused GEMM over a targeted weight (the fp8 gated gate_up fold) is +not used while LoRA is on, for base requests too; the unfused pair runs instead. A drafter keeps the +base's weights: proposals are still verified by the adapter, so output is exact and only the +acceptance rate can drop. + +### 4.9.2 LoRA files for image and video models + +The LoRAs shared for image and video models (Civitai, Hugging Face) are single `.safetensors` files, +named after the model's original code and written by whichever trainer or UI made them. Radiance +reads them as they come, on Krea 2, Anima, Stable Diffusion XL and its finetunes (Illustrious, +NoobAI, Pony), Qwen-Image 2.1, MiniMax H3, FLUX.3 [klein] and LTX-2.5: + +```sh +radiance --model krea-2-turbo-fp8.rad --lora-dir /loras --lora film=/loras/film-grain.safetensors +``` + +- **Spellings:** kohya (`lora_unet_blocks_0_attn_wq.lora_down/up` + `alpha`), ComfyUI + (`diffusion_model.*.lora_A/B` or `lora_down/up`), PEFT/diffusers (`transformer.*.lora_A/B`, + `.default`), bare keys, and the checkpoint's own names. Each model declares how its original + module names map onto the container's (a fused `qkv` onto separate q, k and v, a SwiGLU whose + halves are ordered the other way), so a file trained against either layout lands on the same + weights. +- **Kinds:** LoRA and LoCon (`alpha / rank * up @ down`; on SDXL a LoCon's convolutions too, its + 3 x 3 `down` read flattened as the UNet's im2col GEMMs read theirs), LoHa (`hada_w*`, applied exactly as a + product of rank1 x rank2), LoKr (`lokr_w*`, by its Kronecker structure) and full deltas (`.diff`). + DoRA, OFT and Tucker cores are refused by name; bias and norm deltas are reported and left out. +- **Choosing per request:** `/v1/images/generations`, `/v1/images/edits` and `/v1/videos` take + `"loras": ["film", "ink:0.6", {"name": "style/watercolor", "weight": 0.8}]` (or an object + `{"film": 1, "ink": 0.6}`), and Stable Diffusion web UI tags in the prompt, ``, + which are taken out of the prompt. A strength not given is 1; several adapters stack. + `GET /v1/loras` lists what a request may name: the `--lora` files and every `NAME.safetensors` + under `--lora-dir` (subdirectories one level deep, as `sub/NAME`). +- **Slots:** a slot holds one combination of adapters at their strengths. The first request that + asks for a combination composes it into a free slot, or into the least recently used one no running + request holds (milliseconds to a second, logged with what it left out); later requests find it + there. Requests with different combinations run in separate passes. `--max-loras` sets the slot + count (default: the number of `--lora`, 2 with `--lora-dir` alone). +- **Rank:** `--max-lora-rank` (default 64 for a generator) is the rank every checkpoint module's + slot holds. The slots are VRAM the weights and the arena would otherwise have (startup prints + their size); LTX-2.5, which fills one card on its own, fits one slot at rank 16. Stacked adapters whose ranks fit it, and LoHa and LoKr within it, are held exactly; + past it the sum is truncated to its best rank-R approximation, and the log says how much of the + delta was kept. +- **What carries an adapter:** every plain GEMM of the denoiser (attention, feed-forward, the text + fusion or refiner, embedders and modulation where they are plain), and of the text encoder where + adapter files train it (Anima's Qwen3, SDXL's two CLIPs as kohya's `lora_te1_` / `lora_te2_`; + CLIP-L's last layer, whose output SDXL never reads, has nothing to adapt). An adapter module the model has no + such GEMM for is reported and skipped, as UIs do. +- `POST /v1/load_lora_adapter {"lora_name": "x", "lora_path": "/file.safetensors"}` adds a file + under a name; unload removes it and frees the slots of every combination using it. ### 4.10 Every flag @@ -1368,7 +1452,7 @@ still verified by the adapter, so output is exact and only the acceptance rate c | flag | default | | |---|---|---| -| `--max-num-batched-tokens N` | 8192 | largest token count one step may carry | +| `--max-num-batched-tokens N` | 2048 | largest token count one step may carry | | `--prefill-interleave N` | 0 (off) | decode-only steps after each prefill chunk while other sequences decode (§4.5), at most 64 | | `--busy-prefill-chunk MODE` | auto | a prefill chunk's share of a step that has other work: `auto` leaves decode rows and waiting requests their room (§4.5), `off` takes the whole step, `N` holds it to N tokens | | `--max-num-seqs N` | 256 | largest number of sequences one step may carry | @@ -1392,9 +1476,10 @@ still verified by the adapter, so output is exact and only the acceptance rate c | flag | default | | |---|---|---| -| `--lora NAME=PATH` | none | serve a PEFT LoRA adapter as model NAME; repeatable | -| `--max-loras N` | the number of `--lora` | adapter slots resident at once; 0 with no `--lora` is off | -| `--max-lora-rank R` | 16 | the rank each slot is sized for | +| `--lora NAME=PATH` | none | serve a LoRA adapter: a PEFT directory as model NAME (text), a `.safetensors` file requests name in `loras` (image and video, §4.9.2); repeatable | +| `--lora-dir DIR` | none | image and video models: requests may name any `NAME.safetensors` under DIR | +| `--max-loras N` | the number of `--lora` (2 with `--lora-dir` alone) | adapter slots resident at once; 0 with no adapter is off | +| `--max-lora-rank R` | 16 text, 64 image and video | the rank each slot is sized for | | `--lora-target-modules LIST` | the adapters' own | HF module names adapters may target | **Host tier for finished conversations** @@ -1756,7 +1841,7 @@ becomes up to 280 tokens by default (`--image-tokens`, or a request's `image_tok `document`, `Retrieval-query`, `STS`, ...) and applies to text and content-part inputs; a model that states a default prompt applies it when the request names none. -**An image model** (Qwen-Image 2.1 or 2.1-Turbo, Krea 2, FLUX.3 [klein]) serves OpenAI's images API only; completions, chat +**An image model** (Qwen-Image 2.1 or 2.1-Turbo, Krea 2, FLUX.3 [klein], Anima) serves OpenAI's images API only; completions, chat and embeddings answer 501. OpenAI images clients (Open WebUI, the OpenAI SDKs) work unchanged; the picture always comes back in the response. The engine sizes the step, batch and context for an image model itself (`--max-num-batched-tokens` and `--max-model-len` from the model's largest pass, @@ -1829,6 +1914,44 @@ pictures, each shrunk to 1024x1024 of area when larger. The guidance scale is `g `true_cfg_scale` (one of them), in the model card's terms. FLUX.3's pipeline can rewrite a prompt with a separate language model first; radiance reads the prompt as given. +**Anima** makes RGB pictures, 1024x1024 by default, sides rounded down to multiples of 16, up to +1536x1536 (9216 latent tokens; the card's range is 512x512 to 1536x1536). Base and Aesthetic run 30 +steps at guidance 4 (`uncond + s (cond - uncond)`, so 1 is off) against the card's negative prompt +(`worst quality, low quality, score_1, score_2, score_3, artist name, blurry, jpeg artifacts, +chromatic aberration`); Turbo runs 10 unguided. The sampler is ComfyUI's Euler over its `simple` +schedule at shift 3, so a seed's noise aside, a picture is what ComfyUI's `euler` / `simple` +workflow makes. The prompt is read as written, Danbooru tags and natural language as the card +describes: ComfyUI's `(word:1.2)` weighting and its `\(` escapes are not interpreted, so write +`fern (sousou no frieren)` rather than `fern \(sousou no frieren\)`. A prompt is at most 512 +tokens to either of its two tokenizers. Anima reads only text, so `/v1/images/edits` answers 501. +It is under the CircleStone Labs non-commercial license (the pictures may be used commercially). +On one R9700 a 1024x1024 picture takes 8.5 s from the Aesthetic or Base fp8 container (30 guided +steps) and 12.0 s from bf16; Turbo takes 1.6 s (fp8) and 2.2 s (bf16); 1536x1536 takes 24.8 s (fp8). +The fp8 pictures look the same as bf16's; against ComfyUI from the same noise bf16 is 33 to 39 dB, +fp8 26 to 29 dB (docs/ARCHITECTURES.md). + +**Stable Diffusion XL** and its finetunes (Illustrious, NoobAI, Pony: any single-file SDXL +checkpoint, §3.2) take the same fields and two more, `sampler` and `scheduler`, by ComfyUI's names: + +| field | | +|---|---| +| `sampler` | `euler`, `euler_ancestral` (the default) or `dpmpp_2m` | +| `scheduler` | `normal` (the default), `karras`, `exponential`, `sgm_uniform` or `simple` | + +A model sampled by flow matching refuses both fields. SDXL makes RGB pictures, 1024x1024 by default, +sides rounded down to multiples of 32, up to 36864 latent tokens (1536x1536, or that area at another +aspect: 2048x1152). It runs 28 steps at guidance 6 (`guidance_scale`, uncond + s (cond - uncond)) +against an empty negative prompt unless the request names one; guidance 1 turns it off. A prompt +longer than CLIP's 75 tokens is read in windows of 75, each encoded on its own and laid end to end +(A1111's and ComfyUI's long-prompt behaviour), up to 8 windows. Emphasis syntax such as +`(masterpiece:1.2)` is not interpreted: the parentheses and the number are read as text. The noise +is radiance's own (the same seed gives the same picture here, not the picture ComfyUI gives). +`/v1/images/edits` answers 501: there is no image-to-image or inpainting yet. A v-prediction +checkpoint (NoobAI-XL V-Pred, marked by its `v_pred` tensor) is sampled as one, with the zero +terminal SNR schedule when the checkpoint says so (`ztsnr`). On one R9700 a 1024x1024 picture at 28 +guided steps takes about 5.1 s and 1536x1536 at 25 about 10.8 s; images in flight together share +passes but not launches (the UNet runs once per image and branch), so two take twice as long. + ### 5.7 Request fields | field | notes | @@ -2748,7 +2871,7 @@ is the part of a log to paste into an issue. Its sections: warning is also printed as a `W` line of its own. ``` -I STARTUP REPORT -- radiance 1.9.0 +I STARTUP REPORT -- radiance 1.10.0 I CONFIGURATION -- every option, the value in force, and where it came from I --model /models/flashnext.rad [command line] I --tp 2 [command line] diff --git a/docs/OPS.md b/docs/OPS.md index 94348275..0897ac51 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -219,6 +219,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) | | `seg_sinusoid` | `M`(range) `n` `period` `max_timescale`:f64/opt `cu_div`/opt `dtype` | `cu_seqlens` → `y` | | `gelu` / `silu` | `M`(range) `n` `dtype` | `x` → `y` | +| `gelu_quick` | `M`(range) `n` `dtype` | `x` → `y` | | `cast` | `M`(range) `n` `from` `to` | `x` → `y` | | `softmax` | `M`(range) `n` `dtype` | `x` → `y` | | `sigmoid` | `M`(range) `n` `dtype` | `x` → `y` | @@ -230,6 +231,10 @@ at once. Run it before adding a kernel plugin; the loader names only the first c `gelu` (exact erf) and `silu` share one schema; `silu` has a row of its own because a row names one op. +**`gelu_quick`** is CLIP's `quick_gelu`, `x * sigmoid(1.702 x)`, rounded where torch stores each +tensor in a reduced dtype: `a = rd(1.702 x)`, `s = rd(1 / (1 + exp(-a)))`, `y = rd(x s)`, `rd` the +rounding to `y`'s dtype and the arithmetic f32 (CLIP-L's feed-forward in SDXL's text encoder). + **`rmsnorm`** is `y = x * rsqrt(mean(x^2) + eps) * (w + wadd)`; `wadd` is GemmaRMSNorm's `1 +`, added in f32. `mult` scales the normed row before its one rounding, for a residual branch weighted by a constant (Gemma 4's audio feed-forward adds half its output). For a power of two this equals @@ -732,6 +737,7 @@ butterfly), so every tile is byte-identical (`tests/r4d_emu/test_f32.cpp`). |---|---|---| | `lora_shrink` | `M`(range) `K` `R` `S` `group`/opt `dtype` | `a`, `a_scale`?, `slot`, `lora_a` → `t` | | `lora_expand` | `M`(range) `N` `R` `S` `dtype` | `t`, `slot`, `lora_b`, `scale`, `y`:inout | +| `lora_expand_mm` | `M`(range) `N` `R` `S` `dtype` | `t`, `slot`, `lora_b`, `scale`, `y`:inout | The two halves of `y += scale ⊙ (B · (A · x))` at a trunk GEMM, issued by the core right after the GEMM in the GEMM's own row slice, with several adapters and no adapter mixed in one step; a step @@ -740,7 +746,9 @@ an i32 per row naming its adapter's pool slot -- the step batch's `RadBatch::lor GEMM's first row on; **a row with `slot < 0 || slot >= S` is a base row and neither op touches it**: `lora_shrink` writes nothing into its `t` row, and `lora_expand` does not read or write its `y` row at all — so a base row stays bit for bit what the GEMM wrote, where `y + 0` would already -have turned a -0 into +0. +have turned a -0 into +0. On an image or video generator's pass every row runs the same adapter, +and `slot` is a run of the core's slot-row table holding that slot's index in every element, so the +GEMM's rows need not be the pass's token rows. - `lora_shrink`: `t[m, j] = Σ_k x(m, k) · lora_a[s, j, k]`, `s = slot[m]`, f32 accumulate. `a`/`a_scale` are the GEMM's own first two operands, and `x(m, k)` is the value `gemm_nt_q` uses @@ -756,6 +764,13 @@ have turned a -0 into +0. `[S, N, R]` bf16 and `scale` `[S, N]` f32 — per output column, so a fused projection whose parts carry different `alpha / r` is one launch. +- `lora_expand_mm`: `lora_expand` with `t` rounded to bf16 and the sum over `j` in any order, + `y[m, n] = y[m, n] + scale[s, n] · Σ_j bf16(t[m, j]) · lora_b[s, n, j]`, f32 accumulate, one + rounding to `y`; base rows as `lora_expand`. A row's bytes may depend on `M`. The core declares + it in place of `lora_expand` for an image or video generator, whose passes are thousands of rows + of one adapter and where the exact row's scalar sum is most of the adapter's cost; libr4d runs + it on the WMMA over 64 x 64 tiles. + `a`, `a_scale` and `y` may be row and column slices of wider buffers; every row stride is the tensor's. The pools are ordinary inputs and not weights: the engine owns them as program buffers and copies an adapter into a slot between steps, so a recorded pass replays the same pointers and @@ -1006,8 +1021,11 @@ says which (`libref/ref_gen.cpp`). | `lane_store` | `M`(range) `n` `stride` `dtype` | `src`, `lane`, `dst`:inout | | `randn_lanes` | `M`(range) `n` `stride` `dtype` | `flags`, `seed`, `lane`, `cu_seqlens`, `dst`:inout | | `flow_euler` | `M`(range) `n` `stride` `dtype` | `v`, `sigma`, `sigma_next`, `cfg`, `pair`, `lane`, `flags`, `seed`, `cu_seqlens`, `inp_lat`?, `inp_mask`?, `state`:inout, `preview`:inout? | +| `kd_input` | `M`(range) `n` `stride` `dtype` | `sigma`, `pair`, `lane`, `flags`, `seed`, `cu_seqlens`, `state`:inout → `y` | +| `kd_step` | `M`(range) `n` `stride` `pred` `dtype` | `out`, `sigma`, `sigma_next`, `sigma_prev`, `cfg`, `pair`, `lane`, `flags`, `seed`, `sampler`, `step`, `cu_seqlens`, `state`:inout, `hist`:inout, `preview`:inout? | | `chan_affine` | `M`(range) `n` `mul` `add` `mode` `dtype` `round`/opt | `x` → `y` | | `conv2d_nhwc` | `M`(range) `cin` `cout` `k` `stride` `pad` `up` `dtype` | `x`, `w`w, `b`w → `y` | +| `im2col_nhwc` | `M`(range) `cin` `k` `stride` `pad` `up` `dtype` | `x` → `y` | | `l2norm_chan` | `M`(range) `n` `act` `dtype` | `x`, `gamma`w → `y` | | `d2s_add` | `M`(range) `cin` `cout` `ft` `dtype` | `x`, `y`:inout | | `s2d_avg_add` | `M`(range) `cin` `cout` `ft` `dtype` | `x`, `y`:inout | @@ -1057,6 +1075,34 @@ source into every listed lane (a repainted picture's latent into each of its ima `x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise))` with `m` the lane's f32 `inp_mask` row, `src` its `inp_lat` row and `noise` the seed's stream. +**The k-diffusion sampler.** A denoiser trained on discrete timesteps of a variance-preserving +schedule (SDXL; eps- or v-prediction) is sampled as k-diffusion samples it, in the +variance-exploding form `x = x0 + sigma eps`: the lane holds `x` in f32 (`state` and `hist` are f32 +`[lanes * stride, n]`), the model reads `c_in x` with `c_in = 1 / sqrt(sigma^2 + 1)`, and its output +`out` (`dtype`, in the pass's compact image order bounded by `cu_seqlens`) becomes the clean +estimate. Entries, pairs, lanes, flags and seeds are `flow_euler`'s; `sigma`, `sigma_next`, +`sigma_prev` and `cfg` are f32 `[n_seq]`, `sampler` and `step` i32 `[n_seq]`. Every product and sum +is one f32 rounding; `log`, `expm1` and `sqrt` are the library's. A repaint (flag 2) is refused. + +- `kd_input`: for every entry with `pair != -2`, a first step (flag 1) sets the lane to the seed's + normal stream times `sqrt(1 + sigma^2)` (`rad_philox_normal(seed, k n + c)`, the start of a + schedule at the model's largest sigma); then `y = rd(x / sqrt(sigma^2 + 1))` at the entry's rows + and, when `pair >= 0`, at the pair's rows too, so the negative entry reads the same latent without + a second writer. +- `kd_step`: for every entry with `pair != -2`, with `x` the lane's value, + `D(o) = x - sigma o` (`pred` `eps`) or `x / (sigma^2 + 1) - o sigma / sqrt(sigma^2 + 1)` (`v`), + guided as `D = D(o_u) + cfg (D(o_c) - D(o_u))` against the pair's rows (`D(o_c)` without one); + flag 4 writes `D` to the lane's `preview`. Then by `sampler`: + 0, Euler: `x' = x + (sigma_next - sigma)(x - D) / sigma`; + 1, Euler ancestral (eta 1): `sigma_up = min(sigma_next, sqrt(sigma_next^2 (sigma^2 - + sigma_next^2) / sigma^2))`, `sigma_down = sqrt(sigma_next^2 - sigma_up^2)`, + `x' = x + (x - D) / sigma (sigma_down - sigma)`, plus `sigma_up` times the seed's stream + `1 + step` (`rad_philox_normal_s`, element `k n + c`) while `sigma_next > 0`; + 2, DPM++ 2M: `x' = D` at `sigma_next` 0; otherwise with `t = -ln sigma`, `h = -ln sigma_next - t`, + `x' = (sigma_next / sigma) x - expm1(-h) D'`, where `D' = D` on a first step and otherwise + `(1 + 1/(2r)) D - (1/(2r)) hist` with `r = (t + ln sigma_prev) / h`. + Every step stores `D` to `hist` for the next. Any other sampler is refused. + **Images** are `[height, width * channels]`, dense, and the ops read both sizes off the operand shapes: an image's size belongs to a request, and a parameter is fixed at declare. @@ -1065,6 +1111,16 @@ shapes: an image's size belongs to a request, and a parameter is fixed at declar is `k/2` zeros a side, `down` is none above and left and one below and right (`ZeroPad2d((0,1,0,1))` before a stride-2 conv), `causal` is `k - 1` rows above, none below and `k/2` columns a side (causal along the rows: LTX-2's audio VAE). f32 accumulation, the bias added, one rounding. +- `im2col_nhwc`: `conv2d_nhwc`'s receptive fields as rows, so a convolution is a GEMM against the + checkpoint's own weight. `x` is the image `[Hin, Win * cin]` (rows at their own pitch), read + through `up`, `pad` and `stride` as `conv2d_nhwc` reads it; `y` is `[Ho * Wo, cin * k * k]`, its + rows exactly the output pixels, and row `oy * Wo + ox`, column `(ci * k + i) * k + j` holds the + value `conv2d_nhwc` multiplies `w[o, ci, i, j]` by, 0 in the padding. That column order is the + weight's own `[cout, cin, k, k]` flattened, so `y @ w.reshape(cout, cin k k)^T + b` (a + `gemm_nt_bias`) is the convolution with the weight as stored, and a runtime LoRA over that GEMM + reads a conv adapter's down projection `[rank, cin, k, k]` flattened the same way. A copy: no + arithmetic, the bits moved. libr4d stages a block's k input rows in LDS so its reads and its + stores are both coalesced; it serves `k` up to 7 and `stride` and `up` 1 or 2. - `l2norm_chan`: each pixel's channels to unit L2 (eps 1e-12), times `sqrt(n)`, times `gamma` (three roundings), then `act` `none` or `silu`. - `chan_affine`: `mul` and `add` are space-separated lists of `n` values, each rounded to bf16; @@ -1464,7 +1520,9 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t and `rstd_g`, and the rest is the implementation's scratch (partial sums of up to 1024 parts a group; libref leaves it untouched). A kernel may take several launches but must be deterministic, a fixed reduction order with no float atomics. `y` may be the same memory as `x`. `w` and `b` - `[n]`, bf16 or f32. MiniMax-H3: `n` 512, `groups` 32, `eps` 1e-5. + `[n]`, bf16 or f32. MiniMax-H3: `n` 512, `groups` 32, `eps` 1e-5; SDXL's UNet 320 to 2560 + channels in 32 groups (10 to 80 a group), its VAE 128 to 512. libr4d serves `n` a multiple of 8 + up to 8192 with an even group width. - `tconv_dw`: a depthwise convolution along the frames (a Conv3d of kernel `(k, 1, 1)`, one group a channel): `geom = (T, H, W)`, `P = H W` rows a frame, `w` PyTorch's `[n, 1, k, 1, 1]` (tap `j` of channel `c` at `c k + j`), `b [n]`, `k` odd: diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 40bd4843..443d2266 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -107,6 +107,12 @@ rad-convert [options] -o else every library found --tokenizer F tokenizer.json; its declared chain is baked instead of being reconstructed from a pre-tokenizer name + --tokenizer2 F a second tokenizer.json, baked as the container's second vocab: a + generator that reads its prompt through two tokenizers + --add FILE one more .safetensors file merged in, its tensor names kept (a release + shipped as separate single files). Repeatable + --config DIR config.json, generation_config.json and tokenizer.json from DIR, for a + single-file checkpoint that ships none --imatrix F llama.cpp imatrix: expert profile, column importances, error weighting --set K=V a metadata key, seen by declare and written into the container. Repeatable --max-tok N the max_tok declare is run at (default 8192) @@ -268,6 +274,12 @@ rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad refuses a `--max-tok` and context pair whose score plane would pass 2 GiB. - `--max-spec`: a container carries what the model can serve, so a draft head is written even when this run would not draft. `0` leaves it out. +- `--add`, `--config` and `--tokenizer2` read a release that ships as ComfyUI's single files + (Anima: a diffusion model, a text encoder and a VAE in `split_files/`): the files merge into one + namespace with their own tensor names (a name in two files is refused), the text encoder's + repository supplies the config and tokenizer the plugin is sized by, and a second tokenizer.json + (with its `tokenizer_config.json` beside it) becomes the container's second vocab section, which + a generator declaring `aux_tokens` reads its prompt through. GUIDE §3.2 has the Anima command. - `--draft-model` merges a drafter here; the engine refuses the flag. The drafter's tensors go in under a `draft.` prefix and its config under `draft.` keys. It has no embedding and no `lm_head` of its own; it uses the target's. diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 67460da9..cdc34b1b 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -314,8 +314,9 @@ std::vector build_cases() { add("lora_shrink", { HI("M", M), HI("K", K), HI("R", 48), HI("S", 4), HI("group", 128), HS("dtype", dt) }, 0, 2.0 * M * 48 * K); for (const char* dt : { "f32", "bf16", "f16" }) - add("lora_expand", { HI("M", M), HI("N", 645), HI("R", 48), HI("S", 4), - HS("dtype", dt) }, 0, 2.0 * M * 645 * 48); + for (const char* op : { "lora_expand", "lora_expand_mm" }) + add(op, { HI("M", M), HI("N", 645), HI("R", 48), HI("S", 4), HS("dtype", dt) }, 0, + 2.0 * M * 645 * 48); } for (const char* dt : { "f32", "bf16" }) { add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt), @@ -728,6 +729,10 @@ std::vector build_cases() { add("randn_lanes", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2), HS("dtype", dt) }); add("flow_euler", { HI("M", 24), HI("n", 64), HI("stride", 16), HS("dtype", dt) }); + add("kd_input", { HI("M", 24), HI("n", 4), HI("stride", 16), HS("dtype", dt) }); + for (const char* pred : { "eps", "v" }) + add("kd_step", { HI("M", 24), HI("n", 4), HI("stride", 16), HS("pred", pred), + HS("dtype", dt) }); for (const char* mode : { "fma", "inv" }) for (int round : { 1, 0 }) add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()), @@ -737,6 +742,7 @@ std::vector build_cases() { add("l2norm_chan", { HI("M", 9), HI("n", 645), HS("act", act), HS("dtype", dt) }); add("to_rgba8", { HI("M", 9), HI("n", 4), HS("dtype", dt) }); add("gelu_tanh", { HI("M", 6), HI("n", 645), HS("dtype", dt) }); + add("gelu_quick", { HI("M", 6), HI("n", 645), HS("dtype", dt) }); add("scatter_add_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }); struct Conv { int M, cin, cout, k, stride, up; const char* pad; }; static const Conv kConv[] = { @@ -751,6 +757,17 @@ std::vector build_cases() { HI("stride", v.stride), HS("pad", v.pad), HI("up", v.up), HS("dtype", dt) }, 0, 2.0 * v.M * v.cout * v.cin * v.k * v.k); + /* The convolutions' geometries once each: cout is not a parameter of the unfold. */ + for (const Conv& v : kConv) { + bool seen = false; + for (const Conv* u = kConv; u != &v; ++u) + seen = seen || (u->M == v.M && u->cin == v.cin && u->k == v.k && + u->stride == v.stride && u->up == v.up && u->pad == v.pad); + if (seen) continue; + add("im2col_nhwc", { HI("M", v.M), HI("cin", v.cin), HI("k", v.k), + HI("stride", v.stride), HS("pad", v.pad), HI("up", v.up), + HS("dtype", dt) }); + } for (int ft : { 1, 2 }) { add("d2s_add", { HI("M", 64), HI("cin", 24), HI("cout", 24), HI("ft", ft), HS("dtype", dt) }); diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index 2898a0c0..dc50cbc5 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -1913,6 +1913,51 @@ void gen_cases(std::vector& hs) { .pi("M", 17).pi("n", n).pi("stride", 6).ps("dtype", dn); hs.push_back(std::move(h)); } + { + /* The k-diffusion input: entry 0 a first step guided against entry 1 (pair -2, which + * only its positive entry writes), entry 2 a later step, unguided, in lane 3. */ + static const uint32_t kSeeds[6] = { 11u, 0u, 0u, 0u, 0xfeedbeefu, 3u }; + Hand h(("first, parked, later, n 4" + sfx).c_str(), "kd_input", 0.0); + h.dense(RAD_F32, { 3 }, [](int64_t i) { return 14.6f - 6.0f * (float)i; }) + .idx({ 1, -2, -1 }) + .idx({ 0, 1, 3 }) + .idx({ 1, 0, 0 }) + .raw(RAD_U32, { 6 }, kSeeds) + .idx({ 0, 5, 10, 13 }) + .dense(RAD_F32, { 24, 4 }, hfill(227), true) + .dense(dt, { 13, 4 }, zero, true) + .pi("M", 13).pi("n", 4).pi("stride", 6).ps("dtype", dn); + hs.push_back(std::move(h)); + } + for (const char* pred : { "eps", "v" }) { + /* Every sampler: entry 0 Euler guided against entry 1 with a preview, entry 2 Euler + * ancestral at step 7, entry 3 DPM++ 2M past its first step, entry 4 DPM++ 2M's first + * step, entry 5 Euler ancestral to sigma 0, entry 6 DPM++ 2M to sigma 0. */ + static const uint32_t kSeeds[14] = { 3u, 0u, 4u, 0u, 5u, 9u, 6u, 1u, 7u, 0u, 8u, 0u, + 9u, 2u }; + Hand h(("seven entries, every sampler, " + std::string(pred) + sfx).c_str(), "kd_step", + 0.0); + static const float kS[7] = { 6.0f, 6.0f, 3.5f, 1.25f, 9.0f, 0.4f, 0.3f }; + static const float kSn[7] = { 4.5f, 4.5f, 2.0f, 0.7f, 6.5f, 0.0f, 0.0f }; + static const float kSp[7] = { 0.0f, 0.0f, 5.0f, 2.0f, 0.0f, 0.9f, 0.6f }; + h.dense(dt, { 21, 5 }, hfill(228)) + .dense(RAD_F32, { 7 }, [](int64_t i) { return kS[i]; }) + .dense(RAD_F32, { 7 }, [](int64_t i) { return kSn[i]; }) + .dense(RAD_F32, { 7 }, [](int64_t i) { return kSp[i]; }) + .dense(RAD_F32, { 7 }, [](int64_t) { return 6.5f; }) + .idx({ 1, -2, -1, -1, -1, -1, -1 }) + .idx({ 0, 1, 2, 3, 4, 5, 6 }) + .idx({ 4, 0, 0, 0, 1, 0, 0 }) + .raw(RAD_U32, { 14 }, kSeeds) + .idx({ 0, 0, 1, 2, 2, 1, 2 }) + .idx({ 0, 0, 7, 4, 0, 20, 21 }) + .idx({ 0, 3, 6, 9, 12, 15, 18, 21 }) + .dense(RAD_F32, { 28, 5 }, hfill(229, 3.0f), true) + .dense(RAD_F32, { 28, 5 }, hfill(230), true) + .dense(RAD_F32, { 28, 5 }, zero, true) + .pi("M", 21).pi("n", 5).pi("stride", 4).ps("pred", pred).ps("dtype", dn); + hs.push_back(std::move(h)); + } { Hand h(("a mask column into three lanes" + sfx).c_str(), "lane_store", 0.0); h.dense(dt, { 9, 1 }, hfill(225)) diff --git a/libavx/avx_gen.cpp b/libavx/avx_gen.cpp index f49025db..8edbefac 100644 --- a/libavx/avx_gen.cpp +++ b/libavx/avx_gen.cpp @@ -677,6 +677,203 @@ AVX_KERNEL(flow_euler) { return RAD_OK; } +/* ------------------------------------------------------------------ kd_input, kd_step */ +/* The k-diffusion sampler over a discrete-time denoiser (libref/ref_gen.cpp): libref's f32 steps + * bit for bit, element by element, `kd_keep` holding every product to its own rounding before the + * sum that follows it. The lanes are a few thousand rows of four channels, so a scalar loop costs + * nothing next to the denoiser. */ +namespace { + +enum { kSamplerEuler = 0, kSamplerEulerAncestral = 1, kSamplerDpmpp2m = 2 }; + +/* A product the compiler may not fuse into the next add (any ISA level: a scalar in an xmm). */ +inline float kd_keep(float x) { __asm__("" : "+x"(x)); return x; } + +struct KdEntry { + float s = 0, sn = 0, w = 0; + float cskip = 0, cout = 0; + float sup = 0, sdown = 0; + float ratio = 0, em = 0; + float c1 = 0, c2 = 0; + bool second = false; +}; + +KdEntry kd_entry(float s, float sn, float sp, float w, int64_t sampler, bool first) { + KdEntry k; + k.s = s; + k.sn = sn; + k.w = w; + const float s2p = kd_keep(s * s) + 1.0f; + k.cskip = 1.0f / s2p; + k.cout = s / std::sqrt(s2p); + if (sampler == kSamplerEulerAncestral) { + const float s2 = kd_keep(s * s), sn2 = kd_keep(sn * sn); + const float up2 = kd_keep(sn2 * (s2 - sn2)) / s2; + float sup = std::sqrt(up2); + if (!(sup < sn)) sup = sn; + const float dn2 = sn2 - kd_keep(sup * sup); + k.sup = sup; + k.sdown = std::sqrt(dn2 > 0.0f ? dn2 : 0.0f); + } else if (sampler == kSamplerDpmpp2m && sn > 0.0f) { + const float t = -std::log(s), tn = -std::log(sn); + const float h = tn - t; + k.ratio = sn / s; + k.em = std::expm1(-h); + if (!first) { + const float hl = t - (-std::log(sp)); + const float r = hl / h; + k.c2 = 1.0f / kd_keep(2.0f * r); + k.c1 = 1.0f + k.c2; + k.second = true; + } + } + return k; +} + +inline float kd_denoised(const KdEntry& k, bool v_pred, float x, float o) { + return v_pred ? kd_keep(x * k.cskip) - kd_keep(o * k.cout) : x - kd_keep(k.s * o); +} + +inline float kd_next(const KdEntry& k, int64_t sampler, float x, float D, float hist, float nz) { + if (sampler == kSamplerEuler) { + const float d = (x - D) / k.s; + return x + kd_keep((k.sn - k.s) * d); + } + if (sampler == kSamplerEulerAncestral) { + const float d = (x - D) / k.s; + float xn = x + kd_keep(d * (k.sdown - k.s)); + if (k.sn > 0.0f) xn = xn + kd_keep(nz * k.sup); + return xn; + } + if (k.sn == 0.0f) return D; + const float Dd = k.second ? kd_keep(k.c1 * D) - kd_keep(k.c2 * hist) : D; + return kd_keep(k.ratio * x) - kd_keep(k.em * Dd); +} + +} /* namespace */ + +/* The model's input per entry that moves a lane: a first step's noise times sqrt(1 + sigma^2) + * into the lane, then rd(x / sqrt(sigma^2 + 1)) at the entry's rows and its pair's. Every entry is + * checked before any is written. */ +AVX_KERNEL(kd_input) { + if (!rad_args_have(a, 8)) return RAD_E_INVAL; + const RadTensor *sg = &a->t[0], *pair = &a->t[1], *lane = &a->t[2], *fl = &a->t[3]; + const RadTensor *seed = &a->t[4], *cu = &a->t[5], *st = &a->t[6], *Y = &a->t[7]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), y_rows = rows_of(Y, n); + if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; + if (numel(sg) < n_seq || numel(pair) < n_seq || numel(lane) < n_seq || numel(fl) < n_seq || + numel(seed) < 2 * n_seq) + return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ldi(pair, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ldi(lane, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > y_rows) + return RAD_E_SHAPE; + if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len || + cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > y_rows))) + return RAD_E_SHAPE; + if (ldi(fl, offlin(fl, e)) & kInpaint) return RAD_E_UNSUPPORTED; + } + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ldi(pair, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ldi(lane, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0; + const float s = ldt(sg, offlin(sg, e)); + const float init = std::sqrt(1.0f + kd_keep(s * s)); + const float cin = 1.0f / std::sqrt(kd_keep(s * s) + 1.0f); + const bool first = (ldi(fl, offlin(fl, e)) & kFirst) != 0; + const uint64_t sd = seed_of(seed, e); + AVX_PARALLEL_FOR_IF(len * n * 8 >= AVX_PAR_MIN) + for (int64_t k = 0; k < len; ++k) { + const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st); + const int64_t yb = rowoff(Y, b0 + k, n), ys = laststride(Y); + const int64_t pb = pr >= 0 ? rowoff(Y, p0 + k, n) : 0; + for (int64_t c = 0; c < n; ++c) { + if (first) stt(st, sb + c * ss, rad_philox_normal(sd, (uint64_t)(k * n + c)) * init); + const float v = ldt(st, sb + c * ss) * cin; + stt(Y, yb + c * ys, v); + if (pr >= 0) stt(Y, pb + c * ys, v); + } + } + } + return RAD_OK; +} + +/* One sampler step per entry that moves a lane, libref's arithmetic (docs/OPS.md, kd_step). */ +AVX_KERNEL(kd_step) { + if (!rad_args_have(a, 14)) return RAD_E_INVAL; + const RadTensor *O = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *sgp = &a->t[3]; + const RadTensor *cfg = &a->t[4], *pair = &a->t[5], *lane = &a->t[6], *fl = &a->t[7]; + const RadTensor *seed = &a->t[8], *smp = &a->t[9], *stp = &a->t[10], *cu = &a->t[11]; + const RadTensor *st = &a->t[12], *hs = &a->t[13], *pv = rad_arg_in(a, 14); + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + const char* pred = p_str(a, "pred", "eps"); + const bool v_pred = pred && !std::strcmp(pred, "v"); + if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return RAD_E_INVAL; + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), o_rows = rows_of(O, n); + if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; + for (const RadTensor* t : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp }) + if (numel(t) < n_seq) return RAD_E_SHAPE; + if (numel(seed) < 2 * n_seq || rows_of(hs, n) < st_rows || (pv && rows_of(pv, n) < st_rows)) + return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ldi(pair, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ldi(lane, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > o_rows) + return RAD_E_SHAPE; + if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len || + cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > o_rows))) + return RAD_E_SHAPE; + const int64_t f = ldi(fl, offlin(fl, e)), sm = ldi(smp, offlin(smp, e)); + if ((f & kInpaint) || sm < kSamplerEuler || sm > kSamplerDpmpp2m) return RAD_E_UNSUPPORTED; + if ((f & kPreview) && !pv) return RAD_E_INVAL; + } + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ldi(pair, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ldi(lane, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0; + const int64_t f = ldi(fl, offlin(fl, e)), sm = ldi(smp, offlin(smp, e)); + const uint64_t stream = (uint64_t)(uint32_t)(1 + ldi(stp, offlin(stp, e))); + const KdEntry K = kd_entry(ldt(sg, offlin(sg, e)), ldt(sgn, offlin(sgn, e)), + ldt(sgp, offlin(sgp, e)), ldt(cfg, offlin(cfg, e)), sm, + (f & kFirst) != 0); + const uint64_t sd = seed_of(seed, e); + AVX_PARALLEL_FOR_IF(len * n * 8 >= AVX_PAR_MIN) + for (int64_t k = 0; k < len; ++k) { + const int64_t ob = rowoff(O, b0 + k, n), os = laststride(O); + const int64_t ub = pr >= 0 ? rowoff(O, p0 + k, n) : 0; + const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st); + const int64_t hb = rowoff(hs, L * stride + k, n), hss = laststride(hs); + for (int64_t c = 0; c < n; ++c) { + const float x = ldt(st, sb + c * ss); + float D = kd_denoised(K, v_pred, x, ldt(O, ob + c * os)); + if (pr >= 0) { + const float Du = kd_denoised(K, v_pred, x, ldt(O, ub + c * os)); + D = Du + kd_keep(K.w * (D - Du)); + } + if (f & kPreview) + stt(pv, rowoff(pv, L * stride + k, n) + c * laststride(pv), D); + const float nz = sm == kSamplerEulerAncestral && K.sn > 0.0f + ? rad_philox_normal_s(sd, stream, (uint64_t)(k * n + c)) : 0.0f; + stt(st, sb + c * ss, kd_next(K, sm, x, D, ldt(hs, hb + c * hss), nz)); + stt(hs, hb + c * hss, D); + } + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ flow_x0_step */ /* x' = f32(f32(r x) + f32(f32(1 - r) d)) with d = f32(x + f32((1 - t) v)) and * r = sigma_next / sigma: libref's f32 steps bit for bit, `keep` holding each product to its own @@ -768,6 +965,56 @@ AVX_KERNEL(chan_affine) { return RAD_OK; } +/* ------------------------------------------------------------------ im2col_nhwc */ +/* conv2d_nhwc's receptive fields as rows (libref's definition): y [Ho * Wo, cin * k * k], column + * (ci k + i) k + j of row oy * Wo + ox the input at that tap, 0 in the padding. Each output row is + * filled tap by tap from the input pixel's channel run; bf16 into bf16 copies the bits. Parallel + * over output image rows. */ +AVX_KERNEL(im2col_nhwc) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t cin = p_int(a, "cin", 0), k = p_int(a, "k", 0); + const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1); + const char* pad = p_str(a, "pad", "same"); + const bool down = pad && !std::strcmp(pad, "down"); + const bool causal = pad && !std::strcmp(pad, "causal"); + if (cin <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE; + if (X->rank != 2 || X->shape[1] % cin) return RAD_E_SHAPE; + const int64_t Hin = X->shape[0], Win = X->shape[1] / cin, kk = cin * k * k; + if (Hin <= 0 || Win <= 0) return RAD_E_SHAPE; + const int64_t Hv = Hin * up, Wv = Win * up; + const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2; + const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2; + const int64_t Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1; + if (Ho <= 0 || Wo <= 0 || rows_of(Y, kk) != Ho * Wo) return RAD_E_SHAPE; + const int64_t xr = X->stride[0], xs = laststride(X), ys = laststride(Y); + const bool bits = X->dtype == RAD_BF16 && Y->dtype == RAD_BF16; + AVX_PARALLEL_FOR_IF(Ho * Wo * kk >= AVX_PAR_MIN) + for (int64_t oy = 0; oy < Ho; ++oy) + for (int64_t ox = 0; ox < Wo; ++ox) { + const int64_t yb = rowoff(Y, oy * Wo + ox, kk); + for (int64_t i = 0; i < k; ++i) { + const int64_t iy = oy * stride + i - pt; + for (int64_t j = 0; j < k; ++j) { + const int64_t ix = ox * stride + j - pl; + const bool in = iy >= 0 && iy < Hv && ix >= 0 && ix < Wv; + const int64_t xb = in ? (iy / up) * xr + (ix / up) * cin * xs : 0; + const int64_t yt = yb + (i * k + j) * ys; + for (int64_t ci = 0; ci < cin; ++ci) { + const int64_t yo = yt + ci * k * k * ys; + if (bits) { + ((uint16_t*)Y->data)[yo] = + in ? ((const uint16_t*)X->data)[xb + ci * xs] : (uint16_t)0; + } else { + stt(Y, yo, in ? ldt(X, xb + ci * xs) : 0.0f); + } + } + } + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ conv2d_nhwc */ /* An image convolution as GEMMs over patch rows. x [Hin, Win * cin] and y [Ho, Wo * cout] are * images whose sizes come from the operands, rows at their own pitch and channels contiguous, as @@ -1169,6 +1416,32 @@ AVX_KERNEL(gelu_tanh) { return RAD_OK; } +/* ------------------------------------------------------------------ gelu_quick */ +/* CLIP's quick_gelu in libref's three roundings: a = rd(1.702 x), s = rd(sigmoid(a)), + * y = rd(x s), libm's exp, element by element: a text encoder's feed-forward, small beside its + * GEMMs. */ +AVX_KERNEL(gelu_quick) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *Y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE; + const uint32_t dt = Y->dtype; + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n), xs = laststride(X); + const int64_t yb = rowoff(Y, r, n), ys = laststride(Y); + for (int64_t c = 0; c < n; ++c) { + const float v = ldt(X, xb + c * xs); + const float t = narrow1(dt, 1.702f * v); + const float s = narrow1(dt, 1.0f / (1.0f + std::exp(-t))); + stt(Y, yb + c * ys, v * s); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ scatter_add_rows */ /* x[idx[i]] = x[idx[i]] + v[i], rounded to x's dtype; a negative index adds nothing. Every index * is checked before the first write. Rows run in parallel only when no destination repeats: a diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index e5b14941..57fac4df 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -98,7 +98,7 @@ int avx_par_force(int threads); /* ---- gemm and the vocabulary edges */ \ X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \ X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \ - X(lora_shrink) X(lora_expand) \ + X(lora_shrink) X(lora_expand) X(lora_expand_mm) \ /* ---- attention */ \ X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(rope) \ X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \ @@ -117,7 +117,8 @@ int avx_par_force(int threads); X(gather_rows2) X(lane_gather) X(lane_store) X(randn_lanes) \ X(flow_euler) X(chan_affine) X(conv2d_nhwc) X(l2norm_chan) \ X(d2s_add) X(s2d_avg_add) X(to_rgba8) X(gelu_tanh) \ - X(scatter_add_rows) X(attn_prefix_self) \ + X(scatter_add_rows) X(attn_prefix_self) X(kd_input) X(kd_step) \ + X(gelu_quick) X(im2col_nhwc) \ /* ---- video generation */ \ X(rms_mod) X(rms_mod_quant_fp8) X(flow_x0_step) X(patch_unfold) \ X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \ diff --git a/libavx/avx_lora.cpp b/libavx/avx_lora.cpp index 1e43dcd7..fbf6c51d 100644 --- a/libavx/avx_lora.cpp +++ b/libavx/avx_lora.cpp @@ -150,8 +150,8 @@ AVX_KERNEL(lora_shrink) { return RAD_OK; } -/* operands: t, slot, lora_b, scale, y (inout) */ -AVX_KERNEL(lora_expand) { +/* operands: t, slot, lora_b, scale, y (inout). `bf16_t`: lora_expand_mm, t rounded to bf16. */ +static int expand_impl(const RadArgs* a, bool bf16_t) { if (!rad_args_have(a, 5)) return RAD_E_INVAL; const RadTensor *T = &a->t[0], *SL = &a->t[1], *LB = &a->t[2], *SC = &a->t[3], *Y = &a->t[4]; const int64_t N = p_int(a, "N", 0), R = p_int(a, "R", 0), S = p_int(a, "S", 0); @@ -176,6 +176,12 @@ AVX_KERNEL(lora_expand) { const int64_t s = row_slot(SL, m, S); if (s < 0) continue; /* a base row: not read, not written */ const float* tv = in_row(T, m * mt.rs, R, scratch_f32((size_t)R)); + if (bf16_t) { + float* tr = scratch_f32((size_t)R); + if (tr != tv) for (int64_t j = 0; j < R; ++j) tr[j] = tv[j]; + for (int64_t j = 0; j < R; ++j) tr[j] = rad_bf16_to_f32(rad_f32_to_bf16(tr[j])); + tv = tr; + } const float* bv = in_row(LB, s * pb.s0 + n * pb.s1, R, scratch_f32_b((size_t)R)); const float d = scd[s * sc_r + n * sc_c] * dotf(tv, bv, R); const int64_t o = m * ys_r + n * ys_c; @@ -183,3 +189,8 @@ AVX_KERNEL(lora_expand) { } return RAD_OK; } + +AVX_KERNEL(lora_expand) { return expand_impl(a, false); } + +/* lora_expand with t rounded to bf16 (docs/OPS.md). */ +AVX_KERNEL(lora_expand_mm) { return expand_impl(a, true); } diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 602ac0c6..11470960 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -550,11 +550,24 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"), OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"), INOUT("state"), INOUT_O("preview") }; +/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */ +static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"), + P_STR("dtype") }; +static const RadOperandSpec oKdInput[] = { OPD("sigma"), OPD("pair"), OPD("lane"), OPD("flags"), + OPD("seed"), OPD("cu_seqlens"), INOUT("state"), + OUT("y") }; +static const RadOperandSpec oKdStep[] = { OPD("out"), OPD("sigma"), OPD("sigma_next"), + OPD("sigma_prev"), OPD("cfg"), OPD("pair"), OPD("lane"), + OPD("flags"), OPD("seed"), OPD("sampler"), OPD("step"), + OPD("cu_seqlens"), INOUT("state"), INOUT("hist"), + INOUT_O("preview") }; static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), P_STR("mode"), P_STR("dtype"), P_INTO("round") }; static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") }; static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") }; +static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"), + P_STR("pad"), P_INT("up"), P_STR("dtype") }; static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") }; static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"), @@ -937,6 +950,9 @@ static const RadOpSchema kSchemas[] = { { "lora_expand", ARR(pLoraExpand), ARR(oLoraExpand), "y[m, n] += scale[slot[m], n] * sum_j t[m, j] * lora_b[slot[m], n, j]; a base row is neither " "read nor written." }, +{ "lora_expand_mm", ARR(pLoraExpand), ARR(oLoraExpand), + "lora_expand with t rounded to bf16, the sum over j in any order; a base row is neither read nor " + "written." }, { "gemm_nt_q_gated", ARR(pGemmQGated), ARR(oGemmQGated), "gemm_nt_q over a [N, K] gate_up plane with gated_quant_fp8's pass in the epilogue, byte for " "byte the pair. `N` is the weight's rows, twice the fused width; the output is [M, N/2]." }, @@ -1044,12 +1060,22 @@ static const RadOpSchema kSchemas[] = { { "flow_euler", ARR(pLane), ARR(oFlowEuler), "one flow-matching Euler step per entry that moves a lane, with guidance, the preview and the " "repaint's kept region; libref's roundings bit for bit." }, +{ "kd_input", ARR(pLane), ARR(oKdInput), + "a k-diffusion sampler's model input per entry that moves a lane: a first step's noise times " + "sqrt(1 + sigma^2) into the lane, then rd(x / sqrt(sigma^2 + 1)) at the entry's and its pair's " + "rows; libref's arithmetic bit for bit." }, +{ "kd_step", ARR(pKdStep), ARR(oKdStep), + "one k-diffusion sampler step per entry that moves a lane: the guided clean estimate from an " + "eps or v output, then Euler, Euler ancestral or DPM++ 2M; libref's arithmetic bit for bit." }, { "chan_affine", ARR(pChanAffine), ARR(oUnary), "a per-channel affine from two lists of n bf16 values, `fma` or `inv`; `round` 0 keeps the " "lists and the arithmetic in f32, rounded once." }, { "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc), "an image convolution, channels innermost, as GEMMs over bands of patch rows; `up` 2 reads the " "input upsampled nearest-neighbour, `pad` same or down." }, +{ "im2col_nhwc", ARR(pIm2col), ARR(oUnary), + "conv2d_nhwc's receptive fields as rows, y [Hout * Wout, cin * k * k], column (ci * k + i) * k " + "+ j the value conv2d_nhwc multiplies weight[o, ci, i, j] by; libref's copies bit for bit." }, { "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm), "each pixel's channels to unit L2, times sqrt(n), times gamma (three roundings), then `act`." }, { "d2s_add", ARR(pSpaceDepth), ARR(oSpaceDepth), @@ -1060,6 +1086,8 @@ static const RadOpSchema kSchemas[] = { { "to_rgba8", ARR(pMnD), ARR(oUnary), "decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them, u8 out." }, { "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." }, +{ "gelu_quick", ARR(pMnD), ARR(oUnary), + "CLIP's quick_gelu, three roundings: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)." }, { "scatter_add_rows", ARR(pMnD), ARR(oScatterRows), "x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." }, { "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS), @@ -1473,6 +1501,9 @@ SIMPLE("avx_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base SIMPLE("avx_lora_expand", "lora_expand", "gemm", "y += scale * (t B[slot]^T) per row, base rows untouched", "f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", L(lora_expand)), +SIMPLE("avx_lora_expand_mm", "lora_expand_mm", "gemm", + "y += scale * (bf16(t) B[slot]^T) per row, base rows untouched", + "f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", L(lora_expand_mm)), SIMPLE("avx_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm", "gemm_nt_q over a gate_up plane with the gated E4M3 quantiser in the epilogue", "i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; fp8_e4m3 out, f32 scale", @@ -1586,11 +1617,17 @@ SIMPLE("avx_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's DT_FLOAT, L(randn_lanes)), SIMPLE("avx_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance", DT_FLOAT, L(flow_euler)), +SIMPLE("avx_kd_input", "kd_input", "elem", "a k-diffusion sampler's model input", DT_FLOAT, + L(kd_input)), +SIMPLE("avx_kd_step", "kd_step", "elem", "a k-diffusion sampler step with guidance", DT_FLOAT, + L(kd_step)), SIMPLE("avx_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists", DT_FLOAT, L(chan_affine)), SIMPLE("avx_conv2d_nhwc", "conv2d_nhwc", "conv", "an image convolution, channels innermost, as GEMMs over patch rows", DT_FLOAT, L(conv2d_nhwc)), +SIMPLE("avx_im2col_nhwc", "im2col_nhwc", "elem", "a convolution's receptive fields as rows", + DT_FLOAT, L(im2col_nhwc)), SIMPLE("avx_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu", DT_FLOAT, L(l2norm_chan)), SIMPLE("avx_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT, L(d2s_add)), @@ -1598,6 +1635,7 @@ SIMPLE("avx_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added L(s2d_avg_add)), SIMPLE("avx_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, L(to_rgba8)), SIMPLE("avx_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, L(gelu_tanh)), +SIMPLE("avx_gelu_quick", "gelu_quick", "elem", "quick gelu", DT_FLOAT, L(gelu_quick)), SIMPLE("avx_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT, L(scatter_add_rows)), SIMPLE("avx_attn_prefix_self", "attn_prefix_self", "attn", diff --git a/libr4d/r4d_gen.hip b/libr4d/r4d_gen.hip index 97a4cfde..8f9d5877 100644 --- a/libr4d/r4d_gen.hip +++ b/libr4d/r4d_gen.hip @@ -17,6 +17,7 @@ #include "r4d_q8.h" #include "rad_philox.h" +#include #include #include #include @@ -380,6 +381,118 @@ __global__ __launch_bounds__(kT) void flow_euler_kernel( st[so] = f32_to_bf16(xn); } +// ---------------------------------------------------------------------------- kd_input, kd_step +// The k-diffusion sampler over a discrete-time denoiser (libref's ref_kd_input / ref_kd_step): the +// lanes hold x = x0 + sigma eps in f32, a thread one element of one entry, every entry's constants +// computed by each of its threads (a handful of f32 operations beside the element's own). +constexpr int kKdEuler = 0, kKdAncestral = 1, kKdDpm2m = 2; + +struct KdConst { + float s, sn, w, cskip, cout, sup, sdown, ratio, em, c1, c2; + bool second; +}; + +__device__ __forceinline__ KdConst kd_const(float s, float sn, float sp, float w, int sampler, + bool first) { + KdConst k{}; + k.s = s; + k.sn = sn; + k.w = w; + const float s2p = s * s + 1.0f; + k.cskip = 1.0f / s2p; + k.cout = s / sqrtf(s2p); + if (sampler == kKdAncestral) { + const float s2 = s * s, sn2 = sn * sn; + const float up2 = sn2 * (s2 - sn2) / s2; + float sup = sqrtf(up2); + if (!(sup < sn)) sup = sn; + const float dn2 = sn2 - sup * sup; + k.sup = sup; + k.sdown = sqrtf(dn2 > 0.0f ? dn2 : 0.0f); + } else if (sampler == kKdDpm2m && sn > 0.0f) { + const float t = -logf(s), tn = -logf(sn); + const float h = tn - t; + k.ratio = sn / s; + k.em = expm1f(-h); + if (!first) { + const float r = (t - (-logf(sp))) / h; + k.c2 = 1.0f / (2.0f * r); + k.c1 = 1.0f + k.c2; + k.second = true; + } + } + return k; +} + +__device__ __forceinline__ float kd_den(const KdConst& k, bool v_pred, float x, float o) { + return v_pred ? x * k.cskip - o * k.cout : x - k.s * o; +} + +__global__ __launch_bounds__(kT) void kd_input_kernel( + const float* __restrict__ sg, const int* __restrict__ pair, const int* __restrict__ lane, + const int* __restrict__ flags, const uint32_t* __restrict__ seed, const int* __restrict__ cu, + float* __restrict__ st, uint16_t* __restrict__ y, int n, int stride, int st_ld, int y_ld) { + const int e = blockIdx.y; + const int pr = pair[e]; + if (pr == -2) return; + const int b0 = cu[e]; + const int64_t len = cu[e + 1] - b0; + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + if (i >= len * n) return; + const int64_t k = i / n, c = i % n; + const float s = sg[e]; + float* xp = st + ((size_t)lane[e] * stride + k) * st_ld + c; + if (flags[e] & 1) *xp = rad_philox_normal(seed_of(seed, e), (uint64_t)i) * sqrtf(1.0f + s * s); + const uint16_t v = f32_to_bf16(*xp * (1.0f / sqrtf(s * s + 1.0f))); + y[(size_t)(b0 + k) * y_ld + c] = v; + if (pr >= 0) y[(size_t)(cu[pr] + k) * y_ld + c] = v; +} + +__global__ __launch_bounds__(kT) void kd_step_kernel( + const uint16_t* __restrict__ out, const float* __restrict__ sg, const float* __restrict__ sgn, + const float* __restrict__ sgp, const float* __restrict__ cfg, const int* __restrict__ pair, + const int* __restrict__ lane, const int* __restrict__ flags, const uint32_t* __restrict__ seed, + const int* __restrict__ sampler, const int* __restrict__ step, const int* __restrict__ cu, + float* __restrict__ st, float* __restrict__ hist, float* __restrict__ pv, int n, int stride, + int o_ld, int st_ld, int h_ld, int pv_ld, int v_pred) { + const int e = blockIdx.y; + const int pr = pair[e]; + if (pr == -2) return; + const int b0 = cu[e]; + const int64_t len = cu[e + 1] - b0; + const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x; + if (i >= len * n) return; + const int64_t k = i / n, c = i % n; + const int f = flags[e], sm = sampler[e]; + const KdConst K = kd_const(sg[e], sgn[e], sgp[e], cfg[e], sm, (f & 1) != 0); + const size_t row = (size_t)lane[e] * stride + k; + const float x = st[row * st_ld + c]; + float D = kd_den(K, v_pred != 0, x, bf2f(out[(size_t)(b0 + k) * o_ld + c])); + if (pr >= 0) { + const float Du = kd_den(K, v_pred != 0, x, bf2f(out[(size_t)(cu[pr] + k) * o_ld + c])); + D = Du + K.w * (D - Du); + } + if ((f & 4) && pv) pv[row * pv_ld + c] = D; + float xn; + if (sm == kKdEuler) { + xn = x + (K.sn - K.s) * ((x - D) / K.s); + } else if (sm == kKdAncestral) { + xn = x + ((x - D) / K.s) * (K.sdown - K.s); + if (K.sn > 0.0f) + xn += rad_philox_normal_s(seed_of(seed, e), (uint64_t)(uint32_t)(1 + step[e]), + (uint64_t)i) * K.sup; + } else if (sm != kKdDpm2m) { + return; + } else if (K.sn == 0.0f) { + xn = D; + } else { + const float Dd = K.second ? K.c1 * D - K.c2 * hist[row * h_ld + c] : D; + xn = K.ratio * x - K.em * Dd; + } + st[row * st_ld + c] = xn; + hist[row * h_ld + c] = D; +} + // ---------------------------------------------------------------------------- per-channel ops // The two lists ride in the kernel arguments, whose segment the backend caps at 768 bytes; two // lists of 64 channels (a latent's) take 512. @@ -504,6 +617,20 @@ __global__ __launch_bounds__(kT) void to_rgba8_kernel(const uint16_t* __restrict y[i] = (uint8_t)rintf(u * 255.0f); } +// ---------------------------------------------------------------------------- gelu_quick +// CLIP's quick_gelu, libref's three roundings: a workgroup a row, a thread an element. +template +__global__ __launch_bounds__(kT) void gelu_quick_kernel(const T* __restrict__ x, T* __restrict__ y, + int n, int x_ld, int y_ld) { + const int r = blockIdx.x; + for (int c = threadIdx.x; c < n; c += kT) { + const float v = ca_ld(x, (size_t)r * x_ld + c); + const float a = ca_rd(y, 1.702f * v); + const float s = ca_rd(y, 1.0f / (1.0f + expf(-a))); + ca_st(y, (int64_t)r * y_ld + c, v * s); + } +} + __global__ __launch_bounds__(kT) void gelu_tanh_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int n, int x_ld, int y_ld) { const int r = blockIdx.x; @@ -698,6 +825,91 @@ __global__ __launch_bounds__(kT) void conv_direct_kernel( y[(size_t)oy * y_ld + (size_t)ox * cout + co] = f32_to_bf16(acc + bf2f(bias[co])); } +// ---------------------------------------------------------------------------- im2col_nhwc +// conv2d_nhwc's receptive fields as rows: y[oy Wo + ox][(ci k + i) k + j] = the input at tap +// (i, j) of output pixel (oy, ox), channel ci. A block is a run of IC_TW output pixels of one +// output row and IC_CC input channels: it stages the k input rows those pixels read (through the +// upsample and the zero padding) in LDS channel-major, [cl][i][xw], 16 bytes of NHWC channels a +// load, then writes each pixel's cc k k columns -- one contiguous run of its y row -- VW elements a +// thread, so both the reads and the writes are coalesced. KS is k at compile time (3 and 1), 0 for +// any other. Values are copied bit for bit. +constexpr int IC_TW = 32; +constexpr int IC_CC = 64; + +template +__global__ __launch_bounds__(kT) void im2col_nhwc_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo, + int k_rt, int stride, int up, int pt, int pl, int64_t x_ld, int64_t y_ld, int vec) { + extern __shared__ uint16_t ic_lds[]; + const int k = KS ? KS : k_rt, kk = k * k; + const int ox0 = blockIdx.x * IC_TW, oy = blockIdx.y, c0 = blockIdx.z * IC_CC; + const int cc = min(IC_CC, cin - c0), nq = min(IC_TW, Wo - ox0); + const int W = (IC_TW - 1) * stride + k; + const int iy0 = oy * stride - pt, ix0 = ox0 * stride - pl; + const int sites = k * W; + const int tid = threadIdx.x; + if (vec) { + const int groups = cc >> 3; + for (int u = tid; u < sites * groups; u += kT) { + const int g = u % groups, site = u / groups; + const int i = site / W, xw = site - i * W; + const int iy = iy0 + i, ix = ix0 + xw; + uint4 v = make_uint4(0, 0, 0, 0); + if (iy >= 0 && iy < Hv && ix >= 0 && ix < Wv) + v = *(const uint4*)(x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin + c0 + + g * 8); + const uint32_t w4[4] = { v.x, v.y, v.z, v.w }; + #pragma unroll + for (int e = 0; e < 8; ++e) + ic_lds[((g * 8 + e) * k + i) * W + xw] = + (uint16_t)(e & 1 ? w4[e >> 1] >> 16 : w4[e >> 1] & 0xffffu); + } + } else { + for (int u = tid; u < sites * cc; u += kT) { + const int cl = u % cc, site = u / cc; + const int i = site / W, xw = site - i * W; + const int iy = iy0 + i, ix = ix0 + xw; + uint16_t v = 0; + if (iy >= 0 && iy < Hv && ix >= 0 && ix < Wv) + v = x[(size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin + c0 + cl]; + ic_lds[(cl * k + i) * W + xw] = v; + } + } + __syncthreads(); + /* The block's pixels' runs as one list of VW-element pieces, so every thread stores whatever + * the run length; a thread's (pixel, piece) advances by the block each pass, without a + * division. */ + const int span = cc * kk, pieces = span / VW; + uint16_t* yb = y + (size_t)((int64_t)oy * Wo + ox0) * y_ld + (size_t)c0 * kk; + int q = tid / pieces, pc = tid - q * pieces; + for (; q < nq;) { + const int t = pc * VW; + uint16_t* yr = yb + (size_t)q * y_ld; + const int xq = q * stride; + uint16_t v[VW]; + #pragma unroll + for (int e = 0; e < VW; ++e) { + const int te = t + e; + const int cl = te / kk, r = te - cl * kk, i = r / k, j = r - i * k; + v[e] = ic_lds[(cl * k + i) * W + xq + j]; + } + if constexpr (VW == 8) + *(uint4*)(yr + t) = make_uint4((uint32_t)v[0] | ((uint32_t)v[1] << 16), + (uint32_t)v[2] | ((uint32_t)v[3] << 16), + (uint32_t)v[4] | ((uint32_t)v[5] << 16), + (uint32_t)v[6] | ((uint32_t)v[7] << 16)); + else if constexpr (VW == 4) + *(uint2*)(yr + t) = make_uint2((uint32_t)v[0] | ((uint32_t)v[1] << 16), + (uint32_t)v[2] | ((uint32_t)v[3] << 16)); + else if constexpr (VW == 2) + *(uint32_t*)(yr + t) = (uint32_t)v[0] | ((uint32_t)v[1] << 16); + else + yr[t] = v[0]; + pc += kT; + while (pc >= pieces) { pc -= pieces; ++q; } + } +} + inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); } inline unsigned blocks_for(int64_t n) { return (unsigned)((n + kT - 1) / kT); } @@ -1073,6 +1285,72 @@ extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) { return st_of(hipGetLastError()); } +extern "C" int r4d_rad_kd_input(const RadArgs* a, RadStream s) { + const RadTensor *sg = r4d_opt(a, 0), *pair = r4d_opt(a, 1), *lane = r4d_opt(a, 2); + const RadTensor *fl = r4d_opt(a, 3), *seed = r4d_opt(a, 4), *cu = r4d_opt(a, 5); + const RadTensor *st = r4d_opt(a, 6), *y = r4d_opt(a, 7); + if (!sg || !pair || !lane || !fl || !seed || !cu || !st || !y) return R4D_NO(RAD_E_INVAL); + if (st->dtype != RAD_F32 || !is_bf16(y) || sg->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0); + long long rs = 0, ry = 0; + const long long sl = r4d_rows_pitch(st, n, &rs), yl = r4d_rows_pitch(y, n, &ry); + if (sl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (n <= 0 || stride <= 0 || n_seq <= 0 || rs < stride) return R4D_NO(RAD_E_SHAPE); + /* One scalar of each kind an entry, two seed words. A lane's rows, a pair's entry and a + * repaint flag (device data) are not checked. */ + for (const RadTensor* e : { sg, pair, lane, fl }) + if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(kd_input_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0, + (hipStream_t)s, (const float*)sg->data, (const int*)pair->data, + (const int*)lane->data, (const int*)fl->data, (const uint32_t*)seed->data, + (const int*)cu->data, (float*)st->data, (uint16_t*)y->data, (int)n, + (int)stride, (int)sl, (int)yl); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_kd_step(const RadArgs* a, RadStream s) { + const RadTensor *o = r4d_opt(a, 0), *sg = r4d_opt(a, 1), *sgn = r4d_opt(a, 2); + const RadTensor *sgp = r4d_opt(a, 3), *cfg = r4d_opt(a, 4), *pair = r4d_opt(a, 5); + const RadTensor *lane = r4d_opt(a, 6), *fl = r4d_opt(a, 7), *seed = r4d_opt(a, 8); + const RadTensor *smp = r4d_opt(a, 9), *stp = r4d_opt(a, 10), *cu = r4d_opt(a, 11); + const RadTensor *st = r4d_opt(a, 12), *hs = r4d_opt(a, 13), *pv = r4d_opt(a, 14); + if (!o || !sg || !sgn || !sgp || !cfg || !pair || !lane || !fl || !seed || !smp || !stp || !cu || + !st || !hs) + return R4D_NO(RAD_E_INVAL); + if (!is_bf16(o) || st->dtype != RAD_F32 || hs->dtype != RAD_F32 || + (pv && pv->dtype != RAD_F32)) + return R4D_NO(RAD_E_DTYPE); + const char* pred = r4d_gets(a, "pred"); + const int v_pred = pred && !std::strcmp(pred, "v"); + if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return R4D_NO(RAD_E_INVAL); + const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0); + long long ro = 0, rs = 0, rh = 0, rp = 0; + const long long ol = r4d_rows_pitch(o, n, &ro), sl = r4d_rows_pitch(st, n, &rs); + const long long hl = r4d_rows_pitch(hs, n, &rh), pl = pv ? r4d_rows_pitch(pv, n, &rp) : 0; + if (ol < 0 || sl < 0 || hl < 0 || pl < 0) return R4D_NO(RAD_E_STRIDE); + const long long n_seq = r4d_numel(cu) - 1; + if (n <= 0 || stride <= 0 || n_seq <= 0 || rs < stride || rh < rs || (pv && rp < rs)) + return R4D_NO(RAD_E_SHAPE); + /* One scalar of each kind an entry, two seed words. A lane's rows, a pair's entry, the + * sampler ids and the flags (device data) are not checked here: the kernel leaves the lane of + * an entry whose sampler it does not know, and writes no preview without the operand, where + * libref refuses both. */ + for (const RadTensor* e : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp }) + if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(kd_step_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0, + (hipStream_t)s, (const uint16_t*)o->data, (const float*)sg->data, + (const float*)sgn->data, (const float*)sgp->data, (const float*)cfg->data, + (const int*)pair->data, (const int*)lane->data, (const int*)fl->data, + (const uint32_t*)seed->data, (const int*)smp->data, (const int*)stp->data, + (const int*)cu->data, (float*)st->data, (float*)hs->data, + pv ? (float*)pv->data : nullptr, (int)n, (int)stride, (int)ol, (int)sl, + (int)hl, (int)pl, v_pred); + return st_of(hipGetLastError()); +} + /* Both rows: x and y bf16 (chan_affine_bf16) or both f32 (chan_affine_f32). `round` 0 keeps the * lists and the arithmetic in f32. */ extern "C" int r4d_rad_chan_affine(const RadArgs* a, RadStream s) { @@ -1175,6 +1453,61 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) { return st_of(hipGetLastError()); } +extern "C" int r4d_rad_im2col_nhwc(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE); + const long long cin = r4d_geti_or(a, "cin", 0), k = r4d_geti_or(a, "k", 0); + const long long stride = r4d_geti_or(a, "stride", 1), up = r4d_geti_or(a, "up", 1); + const char* pad = r4d_gets(a, "pad"); + const bool down = pad && !std::strcmp(pad, "down"); + const bool causal = pad && !std::strcmp(pad, "causal"); + if (pad && !down && !causal && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL); + if (cin <= 0 || k <= 0 || k > 7 || stride <= 0 || stride > 2 || up <= 0 || up > 2) + return R4D_NO(RAD_E_SHAPE); + long long Hin = 0, Win = 0; + if (!image_of(x, cin, &Hin, &Win, true)) return R4D_NO(RAD_E_SHAPE); + const long long Hv = Hin * up, Wv = Win * up; + const long long pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2; + const long long pl = down ? 0 : k / 2, pr = down ? 1 : k / 2; + const long long Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1; + const long long KK = cin * k * k; + long long rows = 0; + const long long y_ld = r4d_rows_pitch(y, KK, &rows); + if (y_ld < 0 || y->stride[y->rank - 1] != 1) return R4D_NO(RAD_E_STRIDE); + if (Ho <= 0 || Wo <= 0 || rows != Ho * Wo || Ho > 65535 || Ho * Wo * y_ld >= (1ll << 40)) + return R4D_NO(RAD_E_SHAPE); + /* 16-byte channel loads where every chunk's channels start on one; the widest store every + * chunk's run, the row pitch and the base allow. */ + const long long tail = cin % IC_CC ? cin % IC_CC : IC_CC; + const int vec = cin % 8 == 0 && x->stride[0] % 8 == 0 && !((uintptr_t)x->data & 15); + auto fits = [&](long long vw) { + return (std::min((long long)IC_CC, cin) * k * k) % vw == 0 && (tail * k * k) % vw == 0 && + y_ld % vw == 0 && !((uintptr_t)y->data & (2 * vw - 1)); + }; + const int VW = fits(8) ? 8 : fits(4) ? 4 : fits(2) ? 2 : 1; + const long long W = (IC_TW - 1) * stride + k; + const size_t lds = (size_t)(std::min((long long)IC_CC, cin) * k * W) * sizeof(uint16_t); + const dim3 grid((unsigned)((Wo + IC_TW - 1) / IC_TW), (unsigned)Ho, + (unsigned)((cin + IC_CC - 1) / IC_CC)); +#define R4D_IC(KS, V) \ + hipLaunchKernelGGL((im2col_nhwc_kernel), grid, dim3(kT), lds, (hipStream_t)s, \ + (const uint16_t*)x->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \ + (int)Wo, (int)k, (int)stride, (int)up, (int)pt, (int)pl, \ + (int64_t)x->stride[0], (int64_t)y_ld, vec) +#define R4D_IC_K(V) \ + if (k == 3) R4D_IC(3, V); \ + else if (k == 1) R4D_IC(1, V); \ + else R4D_IC(0, V) + if (VW == 8) { R4D_IC_K(8); } + else if (VW == 4) { R4D_IC_K(4); } + else if (VW == 2) { R4D_IC_K(2); } + else { R4D_IC_K(1); } +#undef R4D_IC_K +#undef R4D_IC + return st_of(hipGetLastError()); +} + extern "C" int r4d_rad_l2norm_chan(const RadArgs* a, RadStream s) { const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2); if (!x || !g || !y) return R4D_NO(RAD_E_INVAL); @@ -1246,6 +1579,27 @@ extern "C" int r4d_rad_to_rgba8(const RadArgs* a, RadStream s) { return st_of(hipGetLastError()); } +extern "C" int r4d_rad_gelu_quick(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + const bool f32 = x->dtype == RAD_F32; + if ((!is_bf16(x) && !f32) || y->dtype != x->dtype) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rx = 0, ry = 0; + const long long xl = r4d_rows_pitch(x, n, &rx), yl = r4d_rows_pitch(y, n, &ry); + if (n <= 0 || xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx < ry) return R4D_NO(RAD_E_SHAPE); + if (f32) + hipLaunchKernelGGL(gelu_quick_kernel, dim3((unsigned)ry), dim3(kT), 0, + (hipStream_t)s, (const float*)x->data, (float*)y->data, (int)n, (int)xl, + (int)yl); + else + hipLaunchKernelGGL(gelu_quick_kernel, dim3((unsigned)ry), dim3(kT), 0, + (hipStream_t)s, (const uint16_t*)x->data, (uint16_t*)y->data, (int)n, + (int)xl, (int)yl); + return st_of(hipGetLastError()); +} + extern "C" int r4d_rad_gelu_tanh(const RadArgs* a, RadStream s) { const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); if (!x || !y) return R4D_NO(RAD_E_INVAL); diff --git a/libr4d/r4d_lora_bf16.hip b/libr4d/r4d_lora_bf16.hip index bce778f2..0eb48bac 100644 --- a/libr4d/r4d_lora_bf16.hip +++ b/libr4d/r4d_lora_bf16.hip @@ -252,6 +252,11 @@ enum { kExThreads = 256, kZMax = 16, /* the passes of one tile spread over at most this many blocks */ kZGrid = 256, /* ... and only while the grid is smaller than this */ + kMmMT = 128, /* expand_mm: rows a tile, 32 a wave */ + kMmNT = 256, /* expand_mm: columns a tile, 128 a wave */ + kMmJC = 32, /* expand_mm: j a staged step */ + kMmWaves = 8, /* 4 (rows) x 2 (columns) over the tile */ + kMmThreads = kMmWaves * 32, }; struct ShrinkTArgs { @@ -590,6 +595,119 @@ __global__ __launch_bounds__(kExThreads) void lora_expand_tiled_kernel(ExpandTAr } } +/* lora_expand_mm: the same delta on the WMMA, t rounded to bf16, for the passes whose rows are + * many and mostly of one slot (an image or video generator's). One block a (256 columns, 128 rows), + * eight waves, wave w the 32 rows at 32 (w >> 1) and the 128 columns at 128 (w & 1): 2 x 8 WMMA + * tiles. Each 32-wide j step stages t's [128 rows][32 j] (rounded to bf16) and B[s]'s [256 columns] + * [32 j] in LDS, read by every wave; B's fragment is the WMMA's A operand (16 n x 16 j) and t's its + * B (16 j x 16 m), so lane l's eight outputs are row l % 16 of its m tile at columns 8 (l / 16) .. + * +7 -- eight neighbours in y. Rows of a slot not in the pass are staged as zeros and not stored. */ +template +__global__ __launch_bounds__(kMmThreads) void lora_expand_mm_kernel(ExpandTArgs T) { + __shared__ uint16_t ts[kMmMT][kMmJC + 8]; /* +8: rows land on different banks */ + __shared__ uint16_t bs[kMmNT][kMmJC + 8]; + __shared__ int mm_slot[kMmMT], mm_list[kMmMT]; + __shared__ int mm_n; + const ExpandArgs& A = T.b; + const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int col = lane & 15, half = lane >> 4; + const long long nb = (long long)blockIdx.x * kMmNT; + const int mb = (int)blockIdx.y * kMmMT; + const int wm = 32 * (wave >> 1), wn = 128 * (wave & 1); + + for (int i = tid; i < kMmMT; i += kMmThreads) { + int s = -1; + if (mb + i < T.M) { + s = A.slot[(long long)(mb + i) * A.slot_st]; + if (s < 0 || s >= A.S) s = -1; + } + mm_slot[i] = s; + } + __syncthreads(); + if (tid == 0) mm_n = distinct_slots(mm_slot, mm_list, kMmMT); + __syncthreads(); + const int npass = mm_n; + + for (int p = 0; p < npass; ++p) { + const int s = mm_list[p]; + const uint16_t* bp = A.lb + (long long)s * A.lb_s0; + lr_v8f acc[2][8]; + for (int b = 0; b < 2; ++b) + for (int a = 0; a < 8; ++a) acc[b][a] = (lr_v8f)(0.0f); + for (int j0 = 0; j0 < A.R; j0 += kMmJC) { + __syncthreads(); /* the last step's readers are done */ + /* t: 128 rows x 32 j, one row's 32 a pair of lanes */ + for (int i = tid; i < kMmMT * 2; i += kMmThreads) { + const int r = i >> 1, h = (i & 1) * 16; + const bool on = mm_slot[r] == s; + const long long row = (long long)(mb + r) * A.t_rs; + for (int e = 0; e < 16; ++e) { + const int j = j0 + h + e; + ts[r][h + e] = on && j < A.R ? f2bf(A.t[row + (long long)j * A.t_cs]) : (uint16_t)0; + } + } + /* B[s]: 256 columns x 32 j, one column's 32 a pair of lanes */ + for (int i = tid; i < kMmNT * 2; i += kMmThreads) { + const int c = i >> 1, h = (i & 1) * 16; + const long long n = nb + c; + lr_v8s f[2]; + ld_pool16(bp + (n < A.N ? n : 0) * A.lb_s1, j0 + h, A.R, A.lb_s2, n < A.N, f); + for (int e = 0; e < 16; ++e) bs[c][h + e] = (uint16_t)f[e >> 3][e & 7]; + } + __syncthreads(); + lr_v8s tf[2][2]; + for (int b = 0; b < 2; ++b) + for (int q = 0; q < 2; ++q) + for (int e = 0; e < 8; ++e) + tf[b][q][e] = (short)ts[wm + 16 * b + col][16 * half + 8 * q + e]; + for (int a = 0; a < 8; ++a) { + lr_v8s bf[2]; + for (int q = 0; q < 2; ++q) + for (int e = 0; e < 8; ++e) + bf[q][e] = (short)bs[wn + 16 * a + col][16 * half + 8 * q + e]; + for (int b = 0; b < 2; ++b) { + acc[b][a] = wmma_bf16(bf[0], tf[b][0], acc[b][a]); + acc[b][a] = wmma_bf16(bf[1], tf[b][1], acc[b][a]); + } + } + } + for (int b = 0; b < 2; ++b) { + const int ml = wm + 16 * b + col; + if (mm_slot[ml] != s) continue; + const long long m = mb + ml; + for (int a = 0; a < 8; ++a) { + const long long n0 = nb + wn + 16 * a + 8 * half; + const long long o = m * A.y_rs + n0 * A.y_cs; + const float* scp = A.sc + (long long)s * A.sc_rs; + if (YDT == kBF16 && A.y_cs == 1 && n0 + 8 <= A.N && (((uintptr_t)A.y + 2 * o) & 15) == 0) { + lr_v8s* yp = (lr_v8s*)((uint16_t*)A.y + o); + lr_v8s yv = *yp; + for (int e = 0; e < 8; ++e) + yv[e] = (short)f2bf(bf2f((uint16_t)yv[e]) + scp[(n0 + e) * A.sc_cs] * acc[b][a][e]); + *yp = yv; + continue; + } + for (int e = 0; e < 8; ++e) { + const long long n = n0 + e; + if (n >= A.N) continue; + const float d = scp[n * A.sc_cs] * acc[b][a][e]; + const long long oe = m * A.y_rs + n * A.y_cs; + if (YDT == kBF16) { + uint16_t* y = (uint16_t*)A.y + oe; + *y = f2bf(bf2f(*y) + d); + } else if (YDT == kF16) { + uint16_t* y = (uint16_t*)A.y + oe; + *y = f32_to_f16(f16_to_f32(*y) + d); + } else { + float* y = (float*)A.y + oe; + *y = *y + d; + } + } + } + } + } +} + /* ---------------------------------------------------------------- operand reading (host) */ /* `t` read as [rows, cols]: the trailing axes that span `cols` must be one dense run, the leading @@ -885,6 +1003,13 @@ static void launch_expand_tiled(const ExpandTArgs& P, dim3 grid, RadStream strea (hipStream_t)stream, P); } +template +static void launch_expand_mm(const ExpandTArgs& P, dim3 grid, RadStream stream) { + (void)stream; + R4D_KLAUNCH(R4D_KNAME(lora_expand_mm_kernel), grid, dim3(kMmThreads), + (hipStream_t)stream, P); +} + } /* namespace r4d_lora */ extern "C" { @@ -1003,4 +1128,32 @@ int r4d_rad_lora_expand_tiled(const RadArgs* a, RadStream stream) { return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } +/* lora_expand_mm: one block a (256 columns, 128 rows); expand_operands reads the same operands. */ +int r4d_rad_lora_expand_mm(const RadArgs* a, RadStream stream) { + using namespace r4d_lora; + ExpandArgs P{}; + int ydt = 0; + int64_t M = 0; + const int rc = expand_operands(a, &P, &ydt, &M); + if (rc != RAD_OK || M <= 0) return rc; + const int64_t rt = (M + kMmMT - 1) / kMmMT, nt = (P.N + kMmNT - 1) / kMmNT; + if (rt > 65535 || nt > 0x7fffffff) return RAD_E_SHAPE; + ExpandTArgs T{}; + T.b = P; + T.M = (int)M; + T.Z = 1; + const bool v = P.lb_s2 == 1 && (uintptr_t)P.lb % 16 == 0 && P.lb_s1 % 8 == 0 && + P.lb_s0 % 8 == 0; + const dim3 grid((unsigned)nt, (unsigned)rt, 1u); + switch (ydt) { + case kBF16: v ? launch_expand_mm(T, grid, stream) + : launch_expand_mm(T, grid, stream); break; + case kF16: v ? launch_expand_mm(T, grid, stream) + : launch_expand_mm(T, grid, stream); break; + default: v ? launch_expand_mm(T, grid, stream) + : launch_expand_mm(T, grid, stream); break; + } + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + } /* extern "C" */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 6b74b26f..18c7625a 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -156,6 +156,7 @@ int r4d_rad_lora_expand (const RadArgs*, RadStream); int r4d_rad_lora_shrink_wmma (const RadArgs*, RadStream); int64_t r4d_rad_lora_shrink_wmma_scratch(const RadArgs*); int r4d_rad_lora_expand_tiled (const RadArgs*, RadStream); +int r4d_rad_lora_expand_mm (const RadArgs*, RadStream); int r4d_rad_attn_vit (const RadArgs*, RadStream); int r4d_rad_attn_dense (const RadArgs*, RadStream); int r4d_rad_seg_sinusoid (const RadArgs*, RadStream); @@ -179,13 +180,17 @@ int r4d_rad_lane_gather (const RadArgs*, RadStream); int r4d_rad_lane_store (const RadArgs*, RadStream); int r4d_rad_randn_lanes (const RadArgs*, RadStream); int r4d_rad_flow_euler (const RadArgs*, RadStream); +int r4d_rad_kd_input (const RadArgs*, RadStream); +int r4d_rad_kd_step (const RadArgs*, RadStream); int r4d_rad_chan_affine (const RadArgs*, RadStream); int r4d_rad_conv2d_nhwc (const RadArgs*, RadStream); +int r4d_rad_im2col_nhwc (const RadArgs*, RadStream); int r4d_rad_l2norm_chan (const RadArgs*, RadStream); int r4d_rad_d2s_add (const RadArgs*, RadStream); int r4d_rad_s2d_avg_add (const RadArgs*, RadStream); int r4d_rad_to_rgba8 (const RadArgs*, RadStream); int r4d_rad_gelu_tanh (const RadArgs*, RadStream); +int r4d_rad_gelu_quick (const RadArgs*, RadStream); int r4d_rad_scatter_add_rows (const RadArgs*, RadStream); /* r4d_audio.hip */ int r4d_rad_conv1d (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 4cd29805..a2930559 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2318,6 +2318,21 @@ static const RadOperandSpec oFlowEuler[] = { { "inp_lat", RAD_OPD_IN, 1 }, { "inp_mask", RAD_OPD_IN, 1 }, { "state", RAD_OPD_INOUT, 0 }, { "preview", RAD_OPD_INOUT, 1 }, }; +/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */ +static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"), + P_STR("dtype") }; +static const RadOperandSpec oKdInput[] = { + { "sigma", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, + { "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, + { "state", RAD_OPD_INOUT, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +static const RadOperandSpec oKdStep[] = { + { "out", RAD_OPD_IN, 0 }, { "sigma", RAD_OPD_IN, 0 }, { "sigma_next", RAD_OPD_IN, 0 }, + { "sigma_prev", RAD_OPD_IN, 0 }, { "cfg", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, + { "lane", RAD_OPD_IN, 0 }, { "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, + { "sampler", RAD_OPD_IN, 0 }, { "step", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, + { "state", RAD_OPD_INOUT, 0 }, { "hist", RAD_OPD_INOUT, 0 }, { "preview", RAD_OPD_INOUT, 1 }, +}; /* `round` 0 keeps the lists and the arithmetic in f32 (default 1, bf16 lists and roundings). */ static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), P_STR("mode"), P_STR("dtype"), P_INTO("round") }; @@ -2329,6 +2344,8 @@ static const RadOperandSpec oConvNhwc[] = { { "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"), + P_STR("pad"), P_INT("up"), P_STR("dtype") }; static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; static const RadOperandSpec oL2Norm[] = { { "x", RAD_OPD_IN, 0 }, { "gamma", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, @@ -3231,6 +3248,11 @@ static const RadOpSchema kSchemas[] = { "y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * lora_b[s, n, j] for each row m " "whose s = slot[m] is in [0, S), f32 accumulate, one rounding to y's dtype. A base " "row's `y` is neither read nor written."), + SCHEMA("lora_expand_mm", pLoraExpand, oLoraExpand, + "lora_expand with t rounded to bf16 and the sum over j in any order: y[m, n] = y[m, n] " + "+ scale[s, n] * sum_j bf16(t[m, j]) * lora_b[s, n, j], f32 accumulate, one rounding " + "to y's dtype; a base row's `y` is neither read nor written. A row's bytes may depend " + "on M."), SCHEMA("ln_mod", pLnMod, oLnMod, "y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the " "row's sequence's modulation row of `s`."), @@ -3258,17 +3280,30 @@ static const RadOpSchema kSchemas[] = { "an image's first step: its lane's rows become its seed's normal stream."), SCHEMA("flow_euler", pLane, oFlowEuler, "one Euler step of a flow-matching sampler per entry that moves a lane."), + SCHEMA("kd_input", pLane, oKdInput, + "a k-diffusion sampler's model input per entry that moves a lane: a first step's noise " + "times sqrt(1 + sigma^2) into the lane, then rd(x / sqrt(sigma^2 + 1)) at its rows and " + "its pair's."), + SCHEMA("kd_step", pKdStep, oKdStep, + "one k-diffusion sampler step per entry that moves a lane: the guided clean estimate " + "from an eps or v output, then Euler, Euler ancestral or DPM++ 2M; the lanes f32."), SCHEMA("chan_affine", pChanAffine, oGenUnary, "a per-channel affine from two parameter lists of n values; `round` 0 keeps the lists " "and the arithmetic in f32, rounded once into y."), SCHEMA("conv2d_nhwc", pConvNhwc, oConvNhwc, "an image convolution, channels innermost, the sizes read off the operands."), + SCHEMA("im2col_nhwc", pIm2col, oGenUnary, + "conv2d_nhwc's receptive fields as rows: y [Ho * Wo, cin * k * k], column " + "(ci * k + i) * k + j of row oy * Wo + ox the input conv2d_nhwc multiplies weight[o, ci, " + "i, j] by, 0 in the padding."), SCHEMA("l2norm_chan", pL2Norm, oL2Norm, "unit-L2 per row, times sqrt(n), times gamma, then `act`: an image decoder's norm."), SCHEMA("d2s_add", pSpaceDepth, oSpaceDepth, "an upsampling shortcut added in."), SCHEMA("s2d_avg_add", pSpaceDepth, oSpaceDepth, "a downsampling shortcut added in."), SCHEMA("to_rgba8", pGenMn, oGenUnary, "decoded pixels in [-1, 1] to bytes."), SCHEMA("gelu_tanh", pGenMn, oGenUnary, "the tanh approximation of gelu."), + SCHEMA("gelu_quick", pGenMn, oGenUnary, + "CLIP's quick_gelu: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)."), SCHEMA("scatter_add_rows", pGenMn, oScatterAdd, "x[idx[i]] += v[i]; a negative index adds nothing."), SCHEMA("attn_prefix_self", pAttnPS, oAttnPS, "attention over a paged prefix and the step's own rows, causal over the own rows or not. " @@ -4784,14 +4819,14 @@ static const RadConstraint cPatchUnfold[] = { C_IN("dtype", "f32"), C_LE("C", 64 static const RadConstraint cGenAnyFloat[] = { C_IN("dtype", "bf16 f32") }; static const RadConstraint cSnakeAa[] = { C_IN("dtype", "f32"), C_LE("k", 32) }; /* ---- a video latent upscaler (r4d_upscaler.hip). The convolution decodes 3 x 3 x 3 taps as - * constants and reads 16-byte chunks of a voxel row; the group norm puts a thread on an 8-channel - * chunk inside one group, a row's chunks a power of two dividing the 256-thread block (the shim - * checks that and n / groups % 8), and merges at most 256 groups; the temporal convolution keeps + * constants and reads 16-byte chunks of a voxel row; the group norm puts a thread on chunks of 8, 4 + * or 2 channels inside one group, a row's chunks spread over at most the 256-thread block (the + * shim checks an even group width), and merges at most 256 groups; the temporal convolution keeps * its 5-frame window in registers; the fold's lists are kernel arguments, 64 floats at most. */ static const RadConstraint cConv3d[] = { C_IN("dtype", "bf16"), C_EQ("k", 3), C_EQ("kt", 3), C_DIV("cin", 8) }; static const RadConstraint cGroupNorm[] = { C_IN("dtype", "bf16 f32"), C_DIV("n", 8), - C_LE("n", 2048), C_LE("groups", 256) }; + C_LE("n", 8192), C_LE("groups", 256) }; static const RadConstraint cTconvDw[] = { C_IN("dtype", "bf16"), C_EQ("k", 5), C_DIV("n", 8) }; static const RadConstraint cResizeBil[] = { C_IN("dtype", "bf16 f32"), C_DIV("n", 8) }; static const RadConstraint cPatchFold[] = { C_IN("dtype", "bf16 f32"), C_LE("C", 64) }; @@ -4799,6 +4834,8 @@ static const RadConstraint cLnModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_EQ("group", 128) }; /* The lane copies move 32-bit words, so any row of whole words: bf16 latents and an f32 mask. */ static const RadConstraint cGenLanes[] = { C_IN("dtype", "bf16 f32") }; +/* gelu_quick: x and y of one dtype, any width and pitch. */ +static const RadConstraint cGeluQuick[] = { C_IN("dtype", "bf16 f32") }; /* The two lists are kernel arguments, 64 floats each at most (r4d_gen.hip). */ static const RadConstraint cGenAffine[] = { C_IN("dtype", "bf16"), C_LE("n", 64) }; static const RadConstraint cGenAffineF32[] = { C_IN("dtype", "f32"), C_LE("n", 64) }; @@ -7868,6 +7905,17 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, RAD_DOMAIN_DEVICE, R4D_PRIO_LORA_TILED, ROW(cLoraExpand), NOTUNE, nullptr, nullptr, r4d_rad_lora_expand_tiled }, +/* The generators' expand (lora_expand_mm): the same delta on the WMMA, for passes of many rows of + * one adapter, where the exact row's scalar sum is most of the adapter's cost. */ +{ "lora_expand_mm_wmma", "lora_expand_mm", "gemm", + "y += scale * (bf16(t) B[slot]^T) per row, base rows neither read nor written: WMMA bf16 over " + "64-row x 64-column tiles, four waves of 2 x 2 16 x 16 tiles, one pass a distinct slot of a tile", + "any M and N, 1 <= R <= 65536, 1 <= S <= 2^20; row and column strides of t and y honoured, " + "16-byte pool loads where B's rows are aligned", + "f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", + RAD_DOMAIN_DEVICE, R4D_PRIO_LORA_TILED, + ROW(cLoraExpand), NOTUNE, + nullptr, nullptr, r4d_rad_lora_expand_mm }, { "attn_prefix_self_h128_bf16", "attn_prefix_self", "attn", "attention over a paged prefix and the pass's own rows, causal over the own rows or not", "head_dim 128, 1/2/4/8 query heads a KV head, a flat grid over the sequences' query blocks; " @@ -8062,6 +8110,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGenBf16), NOTUNE, nullptr, nullptr, r4d_rad_flow_euler }, +{ "kd_input_bf16", "kd_input", "elem", + "a k-diffusion sampler's model input: a first step's noise into the f32 lane, c_in x out", + "any M, row pitches honoured; a thread an element of an entry", + "f32 lanes, bf16 y", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_kd_input }, + +{ "kd_step_bf16", "kd_step", "elem", + "a k-diffusion sampler step with guidance and preview: Euler, Euler ancestral or DPM++ 2M", + "any M, row pitches honoured; a thread an element of an entry", + "bf16 model output, f32 lanes, history and preview, f32 arithmetic", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_kd_step }, + { "chan_affine_bf16", "chan_affine", "elem", "a per-channel affine from parameter lists; `round` 0 keeps the lists and arithmetic f32", "any M, row pitches honoured", @@ -8118,6 +8182,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cGenRows8), NOTUNE, nullptr, nullptr, r4d_rad_gelu_tanh }, +{ "gelu_quick_bf16", "gelu_quick", "elem", + "CLIP's quick_gelu, libref's three roundings", + "any M and n, row pitches honoured", + "bf16 or f32 in and out (one dtype), f32 arithmetic", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGeluQuick), NOTUNE, + nullptr, nullptr, r4d_rad_gelu_quick }, + { "scatter_add_rows_bf16", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", "any M, row pitches honoured", @@ -8135,6 +8207,15 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_conv2d_nhwc, nullptr, r4d_rad_layout_conv_tap, r4d_rad_relayout_conv_tap, nullptr, r4d_rad_unrelayout_conv_tap }, +{ "im2col_nhwc_bf16", "im2col_nhwc", "elem", + "a convolution's receptive fields as GEMM rows in the weight's (cin, kh, kw) order: 32 output " + "pixels by 64 channels a block, the input rows staged in LDS, coalesced loads and stores", + "k <= 7, stride and up 1 or 2; x rows at their own pitch; y exactly Ho * Wo rows at its pitch", + "bf16 in and out, copied bit for bit", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGenBf16), NOTUNE, + nullptr, nullptr, r4d_rad_im2col_nhwc }, + /* -------------------------------------------------------------------------- audio generation */ { "conv1d_bf16", "conv1d", "conv", "a 1-D convolution over sequences as an implicit GEMM over (tap, cin), the weight tap-major", @@ -8392,9 +8473,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, { "group_norm", "group_norm", "norm", "GroupNorm over all rows in three launches: per-part (count, mean, M2), their merge to mean and " - "rstd, then the affine, modulation and SiLU a thread an 8-channel chunk", - "n % 8 == 0 with n / 8 a power of two up to 256, n / groups % 8 == 0, groups <= 256, M n / " - "groups < 2^24; row pitches honoured, y may alias x", + "rstd, then the affine, modulation and SiLU a thread an 8-, 4- or 2-channel chunk", + "n % 8 == 0 up to 8192, an even n / groups, groups <= 256, M n / groups < 2^31; row pitches " + "honoured, y may alias x", "bf16 or f32 rows, bf16 or f32 gain, bias and modulation, f32 statistics", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGroupNorm), NOTUNE, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 1e7e0e69..afb0e265 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -8004,6 +8004,60 @@ void conv2d_cases(const Plugin& pl) { } } +/* im2col_nhwc against a host unfold, bit for bit: SDXL's widths (a tail of channels past the + * 64-channel chunks, the upsample, both stride-2 paddings), an input whose channels are not a + * multiple of eight (the element loads), a 1x1 and a 5x5 (k at run time), x at a row pitch, and an + * odd output width (the narrowest stores). The y rows past the unfold must stay as they were. */ +void im2col_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "im2col_nhwc_bf16"); + if (!r) { ok("im2col_nhwc_bf16", false, "row absent"); return; } + struct Case { const char* pad; int64_t cin, k, stride, up, H, W, xpad; }; + for (const Case c : { Case{ "same", 320, 3, 1, 1, 40, 37, 0 }, Case{ "same", 200, 3, 1, 2, 9, 13, 0 }, + Case{ "same", 640, 3, 2, 1, 22, 17, 0 }, Case{ "down", 64, 3, 2, 1, 10, 14, 0 }, + Case{ "same", 4, 3, 1, 1, 33, 35, 0 }, Case{ "same", 6, 3, 1, 1, 7, 9, 2 }, + Case{ "same", 96, 1, 1, 1, 11, 7, 8 }, Case{ "same", 72, 5, 1, 1, 12, 15, 0 }, + Case{ "causal", 24, 3, 1, 1, 8, 5, 0 } }) { + const bool down = !std::strcmp(c.pad, "down"), causal = !std::strcmp(c.pad, "causal"); + const int64_t Hv = c.H * c.up, Wv = c.W * c.up; + const int64_t pt = down ? 0 : causal ? c.k - 1 : c.k / 2, pb = down ? 1 : causal ? 0 : c.k / 2; + const int64_t pl0 = down ? 0 : c.k / 2, pr = down ? 1 : c.k / 2; + const int64_t Ho = (Hv + pt + pb - c.k) / c.stride + 1, Wo = (Wv + pl0 + pr - c.k) / c.stride + 1; + const int64_t KK = c.cin * c.k * c.k, ld = c.W * c.cin + c.xpad; + const std::string nm = fmt("im2col_nhwc_bf16 %s, %lld channels, k %lld, stride %lld, up %lld, " + "%lldx%lld", c.pad, (long long)c.cin, (long long)c.k, + (long long)c.stride, (long long)c.up, (long long)c.H, + (long long)c.W); + std::vector x = randv((size_t)(c.H * ld), 1.0f); + void* dx = up_bf16(x); + std::vector pre((size_t)((Ho * Wo + 1) * KK), -7.5f); + void* dy = up_bf16(pre); + RadTensor tx = T(dx, RAD_BF16, { c.H, c.W * c.cin }); + tx.stride[0] = ld; + const int rc = launch(r, { tx, T(dy, RAD_BF16, { Ho * Wo, KK }) }, + { PI("M", Ho * Wo), PI("cin", c.cin), PI("k", c.k), + PI("stride", c.stride), PS("pad", c.pad), PI("up", c.up), + PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } + const std::vector got = down_bf16(dy, pre.size()); + int64_t bad = 0; + for (int64_t oy = 0; oy < Ho; ++oy) + for (int64_t ox = 0; ox < Wo; ++ox) + for (int64_t ci = 0; ci < c.cin; ++ci) + for (int64_t i = 0; i < c.k; ++i) + for (int64_t j = 0; j < c.k; ++j) { + const int64_t iy = oy * c.stride + i - pt, ix = ox * c.stride + j - pl0; + const float v = iy < 0 || iy >= Hv || ix < 0 || ix >= Wv + ? 0.0f + : x[(size_t)((iy / c.up) * ld + (ix / c.up) * c.cin + ci)]; + const int64_t at = (oy * Wo + ox) * KK + (ci * c.k + i) * c.k + j; + bad += got[(size_t)at] != v; + } + for (int64_t e = Ho * Wo * KK; e < (Ho * Wo + 1) * KK; ++e) + bad += got[(size_t)e] != -7.5f; + ok(nm.c_str(), bad == 0, fmt("%lld elements differ", (long long)bad)); + } +} + } /* namespace ltx */ /* ---- a video latent upscaler's ops, at MiniMax-H3's shapes --------------------------------------- @@ -8287,6 +8341,7 @@ void group_norm_cases(const Plugin& pl) { bool silu, inplace; float offset; /* added to every value: a mean far from zero */ int64_t pad; + float eps = 1e-5f; }; for (const G& g : { /* The target size modulated with SiLU (a block's second norm), then plain with SiLU @@ -8306,6 +8361,17 @@ void group_norm_cases(const Plugin& pl) { G{ "2 channels a group", 48 * 8 * 8, 64, 32, false, false, false, 0, true, false, 0.0f, 0 }, G{ "2 channels a group, f32 rows", 777, 64, 32, true, true, true, 2, false, false, 5.0f, 8 }, G{ "4 channels a group, f32", 777, 128, 32, true, true, true, 2, false, false, 20.0f, 8 }, + /* SDXL's UNet: 10 to 80 channels a group, a row's chunks not a power of two (160), + * or more than the block (480 and 320 chunks, three and two to a thread); a + * resnet's norm with SiLU at eps 1e-5, a transformer's without at 1e-6. */ + G{ "SDXL 320", 128 * 128, 320, 32, false, false, false, 0, true, false, 0.0f, 0 }, + G{ "SDXL 640, eps 1e-6", 64 * 64, 640, 32, false, false, false, 0, false, false, 3.0f, 8, 1e-6f }, + G{ "SDXL 960 in place", 128 * 128, 960, 32, false, false, false, 0, true, true, 0.0f, 0 }, + G{ "SDXL 1280, eps 1e-6", 32 * 32, 1280, 32, false, false, false, 0, false, false, 0.0f, 0, 1e-6f }, + G{ "SDXL 1920", 64 * 64, 1920, 32, false, false, false, 0, true, false, -2.0f, 16 }, + G{ "SDXL 2560", 32 * 32 + 7, 2560, 32, false, false, true, 2, true, false, 0.0f, 8 }, + /* A group of more than 2^24 values: the counts past f32's integers. */ + G{ "2^24 values a group", 600 * 1024, 64, 2, false, false, false, 0, true, false, 1.0f, 0 }, }) { const int64_t M = g.M, n = g.n, ld = n + g.pad, rows = M + 2; const std::string nm = fmt("group_norm %s: %lld x %lld in %lld groups", g.what, @@ -8343,12 +8409,12 @@ void group_norm_cases(const Plugin& pl) { T(db, g.wf ? RAD_F32 : RAD_BF16, { n }), tm, T(ds, RAD_F32, { g.groups * (2 + 3 * 1024) }), pitched(dy, ydt, M, n, ld) }; const std::vector ps = { PI("M", M), PI("n", n), PI("groups", g.groups), - PF("eps", 1e-5), PS("act", g.silu ? "silu" : "none"), + PF("eps", g.eps), PS("act", g.silu ? "silu" : "none"), PS("dtype", g.xf ? "f32" : "bf16") }; const int rc = launch(r, ts, ps); if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; } std::vector want, mean, rstd; - gn_ref(x, M, n, g.groups, w, b, g.mod ? &mod : nullptr, g.silu, 1e-5f, !g.yf, &want, + gn_ref(x, M, n, g.groups, w, b, g.mod ? &mod : nullptr, g.silu, g.eps, !g.yf, &want, &mean, &rstd); const size_t yel = (size_t)(rows * ld); const std::vector yall = g.yf ? down_f32(dy, yel) : down_bf16(dy, yel); @@ -8395,10 +8461,10 @@ void group_norm_cases(const Plugin& pl) { } RadTensor nomod = T(nullptr, RAD_BF16, { 1 }); absent(nomod); - ok("group_norm refuses 12 channels a group", + ok("group_norm refuses 3 channels a group", launch(r, { TA(RAD_BF16, { 4, 96 }), TA(RAD_BF16, { 96 }), TA(RAD_BF16, { 96 }), nomod, - TA(RAD_F32, { 8 * 3074 }), TA(RAD_BF16, { 4, 96 }) }, - { PI("M", 4), PI("n", 96), PI("groups", 8), PF("eps", 1e-5), PS("act", "none"), + TA(RAD_F32, { 32 * 3074 }), TA(RAD_BF16, { 4, 96 }) }, + { PI("M", 4), PI("n", 96), PI("groups", 32), PF("eps", 1e-5), PS("act", "none"), PS("dtype", "bf16") }) == RAD_E_SHAPE); } @@ -9474,6 +9540,165 @@ void attn_long_case(const Plugin& pl, const char* name, int64_t hd, int64_t nh, check(nm + " numerics", got, want, 2e-2); } +/* ---- SDXL's: CLIP-L's activation and the k-diffusion sampler, against a host port of libref's + * arithmetic (libref/ref_gen.cpp). */ +void gelu_quick_cases(const Plugin& pl) { + const RadKernelInfo* r = find(pl, "gelu_quick_bf16"); + if (!r) { ok("gelu_quick_bf16", false, "row absent"); return; } + const int64_t M = 77, n = 3072, ld = 3080; + std::vector x = randv((size_t)(M * ld), 4.0f); + void* dx = up_bf16(x); + void* dy = dalloc((size_t)(M * n) * 2); + RadTensor tx = T(dx, RAD_BF16, { M, n }); + tx.stride[0] = ld; + const int rc = launch(r, { tx, T(dy, RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("gelu_quick_bf16", false, "rc " + std::to_string(rc)); return; } + std::vector want((size_t)(M * n)); + for (int64_t m = 0; m < M; ++m) + for (int64_t c = 0; c < n; ++c) { + const float v = x[(size_t)(m * ld + c)]; + const float a = bfr(1.702f * v), s = bfr(1.0f / (1.0f + std::exp(-a))); + want[(size_t)(m * n + c)] = bfr(v * s); + } + check("gelu_quick_bf16 over pitched rows", down_bf16(dy, want.size()), want, 4e-3); +} + +/* The host port of kd_step's per-element arithmetic for one entry. */ +struct KdHost { + float s, sn, w, cskip, cout, sup = 0, sdown = 0, ratio = 0, em = 0, c1 = 0, c2 = 0; + bool second = false; + KdHost(float s_, float sn_, float sp, float w_, int sampler, bool first) + : s(s_), sn(sn_), w(w_) { + const float s2p = s * s + 1.0f; + cskip = 1.0f / s2p; + cout = s / std::sqrt(s2p); + if (sampler == 1) { + const float s2 = s * s, sn2 = sn * sn; + float u = std::sqrt(sn2 * (s2 - sn2) / s2); + if (!(u < sn)) u = sn; + sup = u; + const float d2 = sn2 - u * u; + sdown = std::sqrt(d2 > 0.0f ? d2 : 0.0f); + } else if (sampler == 2 && sn > 0.0f) { + const float t = -std::log(s), h = -std::log(sn) - t; + ratio = sn / s; + em = std::expm1(-h); + if (!first) { + const float rr = (t + std::log(sp)) / h; + c2 = 1.0f / (2.0f * rr); + c1 = 1.0f + c2; + second = true; + } + } + } + float den(bool v, float x, float o) const { return v ? x * cskip - o * cout : x - s * o; } + float next(int sampler, float x, float D, float hist, float nz) const { + if (sampler == 0) return x + (sn - s) * ((x - D) / s); + if (sampler == 1) return x + ((x - D) / s) * (sdown - s) + (sn > 0.0f ? nz * sup : 0.0f); + if (sn == 0.0f) return D; + return ratio * x - em * (second ? c1 * D - c2 * hist : D); + } +}; + +/* Five entries over lanes of 300 rows by 4 channels, an image of 280 latent rows each: entry 0 a + * first step guided against entry 1 (parked), entries 2-4 unguided at later steps. kd_input fills + * entry 0's lane and writes both entries' rows; kd_step takes every sampler at each prediction. */ +void kd_cases(const Plugin& pl) { + const RadKernelInfo* ri = find(pl, "kd_input_bf16"); + const RadKernelInfo* rs = find(pl, "kd_step_bf16"); + if (!ri || !rs) { ok("kd_input_bf16 / kd_step_bf16", false, "row absent"); return; } + const int64_t n = 4, stride = 300, len = 280, S = 5, R = S * len, LR = S * stride; + const std::vector pair = { 1, -2, -1, -1, -1 }, lane = { 3, 0, 1, 4, 2 }; + std::vector cu(S + 1); + for (int64_t e = 0; e <= S; ++e) cu[(size_t)e] = (int32_t)(e * len); + const std::vector seeds = { 0x9e3779b9u, 7u, 0, 0, 5u, 1u, 77u, 0, 0xdeadbeefu, 3u }; + std::vector sdw(seeds.begin(), seeds.end()); + const std::vector sg = { 14.6f, 14.6f, 3.5f, 1.25f, 0.4f }; + const std::vector sgn = { 11.0f, 11.0f, 2.0f, 0.7f, 0.0f }; + const std::vector sgp = { 0.0f, 0.0f, 5.0f, 2.0f, 0.9f }; + const std::vector cfg = { 6.0f, 1.0f, 1.0f, 1.0f, 1.0f }; + const std::vector step = { 0, 0, 7, 4, 20 }; + std::vector st0 = randv((size_t)(LR * n), 2.0f); + + /* ---- kd_input */ + void* dst = up_f32(st0); + void* dy = dalloc((size_t)(R * n) * 2); + const std::vector fl_in = { 1, 0, 0, 0, 0 }; + int rc = launch(ri, { T(up_f32(sg), RAD_F32, { S }), TI32({ S }, pair), TI32({ S }, lane), + TI32({ S }, fl_in), T(up_i32(sdw), RAD_U32, { 2 * S }), + TI32({ S + 1 }, cu), T(dst, RAD_F32, { LR, n }), + T(dy, RAD_BF16, { R, n }) }, + { PI("M", R), PI("n", n), PI("stride", stride), PS("dtype", "bf16") }); + if (rc != RAD_OK) { ok("kd_input_bf16", false, "rc " + std::to_string(rc)); return; } + std::vector st1 = st0, ywant((size_t)(R * n), 0.0f); + for (int64_t e = 0; e < S; ++e) { + if (pair[(size_t)e] == -2) continue; + const float s = sg[(size_t)e]; + const uint64_t sd = (uint64_t)seeds[(size_t)(2 * e)] | ((uint64_t)seeds[(size_t)(2 * e + 1)] << 32); + for (int64_t k = 0; k < len; ++k) + for (int64_t c = 0; c < n; ++c) { + float& x = st1[(size_t)(((int64_t)lane[(size_t)e] * stride + k) * n + c)]; + if (fl_in[(size_t)e] & 1) + x = rad_philox_normal(sd, (uint64_t)(k * n + c)) * std::sqrt(1.0f + s * s); + const float v = x * (1.0f / std::sqrt(s * s + 1.0f)); + ywant[(size_t)((cu[(size_t)e] + k) * n + c)] = v; + if (pair[(size_t)e] >= 0) ywant[(size_t)((cu[(size_t)pair[(size_t)e]] + k) * n + c)] = v; + } + } + check_f32("kd_input_bf16 lanes", down_f32(dst, st1.size()), st1, 1e-6); + check("kd_input_bf16 model input", down_bf16(dy, ywant.size()), ywant, 4e-3); + + /* ---- kd_step, each sampler for every entry, both predictions */ + for (const bool v_pred : { false, true }) + for (int smp = 0; smp < 3; ++smp) { + std::vector out = randv((size_t)(R * n), 1.5f), hs = randv((size_t)(LR * n), 1.0f); + void* ds = up_f32(st1); + void* dh = up_f32(hs); + void* dp = dalloc((size_t)(LR * n) * 4); + const std::vector fl = { 5, 0, 0, 1, 0 }; + const std::vector sm(S, smp); + const int rc2 = launch(rs, { T(up_bf16(out), RAD_BF16, { R, n }), + T(up_f32(sg), RAD_F32, { S }), T(up_f32(sgn), RAD_F32, { S }), + T(up_f32(sgp), RAD_F32, { S }), T(up_f32(cfg), RAD_F32, { S }), + TI32({ S }, pair), TI32({ S }, lane), TI32({ S }, fl), + T(up_i32(sdw), RAD_U32, { 2 * S }), TI32({ S }, sm), + TI32({ S }, step), TI32({ S + 1 }, cu), + T(ds, RAD_F32, { LR, n }), T(dh, RAD_F32, { LR, n }), + T(dp, RAD_F32, { LR, n }) }, + { PI("M", R), PI("n", n), PI("stride", stride), + PS("pred", v_pred ? "v" : "eps"), PS("dtype", "bf16") }); + const std::string nm = fmt("kd_step_bf16 sampler %d %s", smp, v_pred ? "v" : "eps"); + if (rc2 != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc2)); return; } + std::vector sw = st1, hw = hs, pw((size_t)(LR * n), 0.0f); + for (int64_t e = 0; e < S; ++e) { + const int32_t pr = pair[(size_t)e]; + if (pr == -2) continue; + const KdHost K(sg[(size_t)e], sgn[(size_t)e], sgp[(size_t)e], cfg[(size_t)e], smp, + (fl[(size_t)e] & 1) != 0); + const uint64_t sd = (uint64_t)seeds[(size_t)(2 * e)] | ((uint64_t)seeds[(size_t)(2 * e + 1)] << 32); + for (int64_t k = 0; k < len; ++k) + for (int64_t c = 0; c < n; ++c) { + const size_t li = (size_t)(((int64_t)lane[(size_t)e] * stride + k) * n + c); + const float x = sw[li]; + float D = K.den(v_pred, x, out[(size_t)((cu[(size_t)e] + k) * n + c)]); + if (pr >= 0) { + const float Du = K.den(v_pred, x, out[(size_t)((cu[(size_t)pr] + k) * n + c)]); + D = Du + K.w * (D - Du); + } + if (fl[(size_t)e] & 4) pw[li] = D; + const float nz = rad_philox_normal_s(sd, (uint64_t)(uint32_t)(1 + step[(size_t)e]), + (uint64_t)(k * n + c)); + sw[li] = K.next(smp, x, D, hw[li], nz); + hw[li] = D; + } + } + check_f32(nm + " lanes", down_f32(ds, sw.size()), sw, 1e-5); + check_f32(nm + " history", down_f32(dh, hw.size()), hw, 1e-5); + if (smp == 0) check_f32(nm + " preview", down_f32(dp, pw.size()), pw, 1e-5); + } +} + } /* namespace vg */ /* ---- video sparse attention: vsa_select and attn_vsa against a host port of their contract @@ -16227,6 +16452,96 @@ static void attn_perf(const Plugin& pl, int64_t M, int64_t H, int iters) { dfree_all(); } +/* SDXL's UNet convolutions at 1024 x 1024 (a 128 x 128 latent): the implicit GEMM against the + * unfold and a GEMM over the checkpoint's own weight, which runtime LoRA can attach to. */ +static void conv_perf(const Plugin& pl, int iters) { + if (iters <= 0) iters = 20; + const RadKernelInfo* rc = find(pl, "conv2d_nhwc_bf16"); + const RadKernelInfo* ri = find(pl, "im2col_nhwc_bf16"); + const RadKernelInfo* rg = find(pl, "gemm_bf16_nt_bias_tiled"); + if (!rc || !ri || !rg) { std::printf("conv timing: a row is absent\n"); return; } + auto rand_fill = [](void* d, size_t bytes) { + const size_t chunk = std::min(bytes, (size_t)16 << 20); + std::vector h(chunk / 2); + for (size_t i = 0; i < h.size(); ++i) h[i] = st_rand_bf16((uint32_t)i); + for (size_t off = 0; off < bytes; off += chunk) + st_memcpy((uint8_t*)d + off, h.data(), std::min(chunk, bytes - off), hipMemcpyHostToDevice); + }; + auto time_row = [&](const RadKernelInfo* r, std::vector ts, std::vector ps) + -> double { + 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; + const int code = r->launch(&a, nullptr); + if (code != RAD_OK) return (double)code; + if (st_stream_sync(nullptr) != hipSuccess) return -1000.0; + return st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + }; + struct C { int64_t side, cin, cout, stride, up; }; + static const C kC[] = { + { 128, 320, 320, 1, 1 }, { 128, 960, 320, 1, 1 }, { 128, 640, 320, 1, 1 }, + { 64, 640, 640, 1, 2 }, { 128, 320, 320, 2, 1 }, + { 64, 320, 640, 1, 1 }, { 64, 640, 640, 1, 1 }, { 64, 1920, 640, 1, 1 }, + { 64, 1280, 640, 1, 1 }, { 64, 960, 640, 1, 1 }, { 32, 1280, 1280, 1, 2 }, + { 64, 640, 640, 2, 1 }, + { 32, 640, 1280, 1, 1 }, { 32, 1280, 1280, 1, 1 }, { 32, 2560, 1280, 1, 1 }, + { 32, 1920, 1280, 1, 1 }, + }; + std::printf("SDXL's 3x3 convolutions at 1024 x 1024, %d launches each: conv2d_nhwc_bf16 " + "against im2col_nhwc_bf16 + gemm_bf16_nt_bias_tiled\n", iters); + std::printf(" %-28s %10s %10s %10s %10s %7s\n", "input -> output, channels", "conv us", + "im2col us", "gemm us", "sum us", "ratio"); + double tc = 0, ti = 0, tg = 0; + for (const C& c : kC) { + const int64_t Hin = c.side, Hv = Hin * c.up, Ho = (Hv + 2 - 3) / c.stride + 1, k = 3; + const int64_t P = Ho * Ho, K = c.cin * k * k; + void* dx = dalloc((size_t)(Hin * Hin * c.cin) * 2); + void* dw = dalloc((size_t)(c.cout * K) * 2); + void* db = dalloc((size_t)c.cout * 2); + void* dc = dalloc((size_t)(P * K) * 2); + void* dy = dalloc((size_t)(P * c.cout) * 2); + if (!dx || !dw || !db || !dc || !dy) { std::printf(" hipMalloc failed\n"); dfree_all(); continue; } + rand_fill(dx, (size_t)(Hin * Hin * c.cin) * 2); + rand_fill(dw, (size_t)(c.cout * K) * 2); + rand_fill(db, (size_t)c.cout * 2); + const std::vector pc = { PI("M", P), PI("cin", c.cin), PI("cout", c.cout), + PI("k", k), PI("stride", c.stride), PS("pad", "same"), + PI("up", c.up), PS("dtype", "bf16") }; + const double uc = time_row(rc, { T(dx, RAD_BF16, { Hin, Hin * c.cin }), + T(dw, RAD_BF16, { c.cout, c.cin, k, k }), + T(db, RAD_BF16, { c.cout }), T(dy, RAD_BF16, { Ho, Ho * c.cout }) }, + pc); + const std::vector pi = { PI("M", P), PI("cin", c.cin), PI("k", k), + PI("stride", c.stride), PS("pad", "same"), PI("up", c.up), + PS("dtype", "bf16") }; + const double ui = time_row(ri, { T(dx, RAD_BF16, { Hin, Hin * c.cin }), + T(dc, RAD_BF16, { P, K }) }, pi); + RadTensor tres = T(nullptr, RAD_BF16, { 1 }); + absent(tres); + const double ug = time_row(rg, { T(dc, RAD_BF16, { P, K }), T(dw, RAD_BF16, { c.cout, K }), + T(db, RAD_BF16, { c.cout }), tres, + T(dy, RAD_BF16, { P, c.cout }) }, + { PI("M", P), PI("N", c.cout), PI("K", K), PS("dtype", "bf16") }); + const std::string nm = fmt("%lldx%lld%s -> %lldx%lld, %lld -> %lld", (long long)Hin, + (long long)Hin, c.up == 2 ? " up2" : "", (long long)Ho, + (long long)Ho, (long long)c.cin, (long long)c.cout); + if (uc < 0 || ui < 0 || ug < 0) { + std::printf(" %-28s rc %d / %d / %d\n", nm.c_str(), (int)uc, (int)ui, (int)ug); + } else { + std::printf(" %-28s %10.1f %10.1f %10.1f %10.1f %7.2f\n", nm.c_str(), uc, ui, ug, + ui + ug, (ui + ug) / uc); + tc += uc; + ti += ui; + tg += ug; + } + dfree_all(); + } + std::printf(" %-28s %10.1f %10.1f %10.1f %10.1f %7.2f\n", "total", tc, ti, tg, ti + tg, + (ti + tg) / tc); +} + static void video_perf(const Plugin& pl, int iters, const char* only) { if (iters <= 0) iters = 10; /* One section by name, or every one. */ @@ -24719,6 +25034,7 @@ static void device_phase(const Plugin& pl) { if (sel("stft_logmel")) ltx::stft_cases(pl); if (sel("bwe_up")) ltx::bwe_cases(pl); if (sel("conv2d_nhwc_bf16")) ltx::conv2d_cases(pl); + if (sel("im2col_nhwc_bf16")) ltx::im2col_cases(pl); if (sel("int_affine")) ltx::int_affine_cases(pl); if (sel("vsa_select_h128_bf16")) vsa::select_cases(pl); if (sel("attn_vsa_h128_bf16")) vsa::attn_cases(pl); @@ -24738,6 +25054,8 @@ static void device_phase(const Plugin& pl) { if (sel("layernorm_bf16")) vg::norm_f32_rows_cases(pl, true); if (sel("timestep_embed_f32")) vg::timestep_f32_case(pl); if (sel("randn_lanes_f32")) vg::randn_f32_case(pl); + if (sel("gelu_quick_bf16")) vg::gelu_quick_cases(pl); + if (sel("kd_input_bf16") || sel("kd_step_bf16")) vg::kd_cases(pl); if (sel("interleave2_bf16")) vg::interleave2_f32_case(pl); if (sel("chan_affine_f32")) vg::chan_affine_cases(pl, "chan_affine_f32"); if (sel("chan_affine_bf16")) vg::chan_affine_cases(pl, "chan_affine_bf16"); @@ -25518,6 +25836,8 @@ static void usage(void) { " decoder's tiles), upscaler (a latent upscaler's 3D convolutions\n" " beside the bf16 GEMM at the same M, N and K, then its norm and\n" " elementwise ops); every section without one.\n" + " --perfconv [iters]: SDXL's 3x3 convolutions at 1024 x 1024, conv2d_nhwc against\n" + " im2col_nhwc and the biased GEMM over the unfolded rows.\n" " --perfvsa [iters] [local]: vsa_select and attn_vsa at 1344 x 768 (38010\n" " rows, 28 heads), sparsity 0.8 and 0, beside attn_dense over the same\n" " rows. `local` gives q and k features of the row's grid position, so a\n" @@ -25591,6 +25911,7 @@ int main(int argc, char** argv) { long long m16_m = 0, m16_e = 256, m16_k = 10, m16_d = 0; int m16_it = 20; int video_it = 0; + int conv_it = 0; long long attn_m = 0, attn_h = 0; int attn_it = 5; int vsa_it = 0; @@ -25778,6 +26099,9 @@ int main(int argc, char** argv) { video_it = 10; if (i + 1 < argc && argv[i + 1][0] != '-') video_it = (int)std::strtol(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') video_sec = argv[++i]; + } else if (!std::strcmp(argv[i], "--perfconv")) { + conv_it = 20; + if (i + 1 < argc && argv[i + 1][0] != '-') conv_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfvsa")) { vsa_it = 5; if (i + 1 < argc && argv[i + 1][0] != '-' && std::strcmp(argv[i + 1], "local")) @@ -25813,6 +26137,16 @@ int main(int argc, char** argv) { attn_perf(pl, attn_m, attn_h, attn_it); #else skip("attention timing", "built without HIP"); +#endif + return 0; + } + if (conv_it) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + conv_perf(pl, conv_it); + dfree_all(); +#else + skip("convolution timing", "built without HIP"); #endif return 0; } diff --git a/libr4d/r4d_upscaler.hip b/libr4d/r4d_upscaler.hip index 6e51b0ec..1fcd604b 100644 --- a/libr4d/r4d_upscaler.hip +++ b/libr4d/r4d_upscaler.hip @@ -412,12 +412,15 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel( // give the same bytes: // // 1. parts: block p takes rows [p rpp, (p + 1) rpp) and writes each group's (count, mean, M2) -// of them to the scratch. A thread keeps one 8-channel chunk of one group over every -// `slots`-th row, summing deviations from its first value (the shift keeps the f32 sums of -// squares from cancelling against a large mean); the block merges its threads' triples per -// group in thread order (Chan's parallel update). +// of them to the scratch. A row is `tpr` threads, each owning `cpt` consecutive CW-channel +// chunks of one group, and the block holds `slots` = 256 / tpr rows at a time (the threads +// past slots * tpr idle). A thread keeps its chunks over every `slots`-th row, summing +// deviations from its first value (the shift keeps the f32 sums of squares from cancelling +// against a large mean); the block merges its threads' triples per group in thread order +// (Chan's parallel update). // 2. final: block g merges group g's parts, 256 strided runs then a fixed tree, and writes -// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps). +// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps), the count the +// group's exact M n / groups. // 3. apply: a thread an 8-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in // f32, one rounding. // @@ -436,31 +439,33 @@ __device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, flo n = nab; } -/* `cpr_log`: log2 of the chunks a row (n / CW, a power of two dividing the block); `gs8` the - * chunks a group. A chunk is CW channels: 8, or 4 for groups of 4 channels. */ +/* A chunk is CW channels (8, 4 or 2: the widest dividing a group). `tpr` threads a row, each over + * `cpt` chunks; `tpg` threads a group (its chunks / cpt). */ template __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x, float* __restrict__ stats, int M, int groups, - int cpr_log, int gs8, int ldx, int rpp) { + int tpr, int cpt, int tpg, int ldx, int rpp) { __shared__ float sh[3][kT]; const int tid = threadIdx.x; - const int cpr = 1 << cpr_log, slots = kT >> cpr_log; - const int c = tid & (cpr - 1), slot = tid >> cpr_log; + const int slots = kT / tpr; + const int c = tid % tpr, slot = tid / tpr; const int p = blockIdx.x; const int r0 = p * rpp, r1 = min(M, r0 + rpp); float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f; - for (int r = r0 + slot; r < r1; r += slots) { - float v[CW]; - ldc(x + (size_t)r * ldx + c * CW, v); - if (cnt == 0.0f) shift = v[0]; + if (slot < slots) + for (int r = r0 + slot; r < r1; r += slots) + for (int q = 0; q < cpt; ++q) { + float v[CW]; + ldc(x + (size_t)r * ldx + (c * cpt + q) * CW, v); + if (cnt == 0.0f) shift = v[0]; #pragma unroll - for (int j = 0; j < CW; ++j) { - const float d = v[j] - shift; - s1 += d; - s2 += d * d; - } - cnt += (float)CW; - } + for (int j = 0; j < CW; ++j) { + const float d = v[j] - shift; + s1 += d; + s2 += d * d; + } + cnt += (float)CW; + } float mean = 0.0f, m2 = 0.0f; if (cnt > 0.0f) { const float q = s1 / cnt; @@ -474,8 +479,8 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x, for (int g = tid; g < groups; g += kT) { float N = 0.0f, Mn = 0.0f, Q = 0.0f; for (int s = 0; s < slots; ++s) - for (int k = 0; k < gs8; ++k) { - const int t = (s << cpr_log) + g * gs8 + k; + for (int k = 0; k < tpg; ++k) { + const int t = s * tpr + g * tpg + k; chan_merge(N, Mn, Q, sh[0][t], sh[1][t], sh[2][t]); } float* o = stats + 2 * groups + ((size_t)g * kGnParts + p) * 3; @@ -486,7 +491,7 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x, } __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, int groups, - int parts, float eps) { + int parts, float count, float eps) { __shared__ float sh[3][kT]; const int g = blockIdx.x, tid = threadIdx.x; const float* P = stats + 2 * groups + (size_t)g * kGnParts * 3; @@ -507,24 +512,24 @@ __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, __syncthreads(); } if (tid == 0) { - const float var = sh[2][0] / sh[0][0]; + const float var = sh[2][0] / count; stats[2 * g] = sh[1][0]; stats[2 * g + 1] = 1.0f / sqrtf(var + eps); } } /* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32 - * one. x and y may be the same memory: a thread reads its chunk before it writes it. */ + * one. A thread is chunk `i % cpr` of row `i / cpr`, `gs8` chunks a group. x and y may be the same + * memory: a thread reads its chunk before it writes it. */ template __global__ __launch_bounds__(kT) void gn_apply_kernel( const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b, - const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log, + const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr, int gs8, int ldx, int ldy, int wf, int bf, int modk, int silu) { - const int slots = kT >> cpr_log; - const int tid = threadIdx.x; - const int r = blockIdx.x * slots + (tid >> cpr_log); + const long long i = (long long)blockIdx.x * kT + threadIdx.x; + const int r = (int)(i / cpr); if (r >= M) return; - const int ck = tid & ((1 << cpr_log) - 1), c = ck * CW; + const int ck = (int)(i - (long long)r * cpr), c = ck * CW; const int g = ck / gs8; const float mean = stats[2 * g], rstd = stats[2 * g + 1]; float v[CW], wv[CW], bv[CW]; @@ -741,12 +746,6 @@ int parse_f32_list(const char* s, float* out, int max) { return n; } -inline int log2_exact(long long v) { - int l = 0; - while ((1ll << l) < v) ++l; - return (1ll << l) == v ? l : -1; -} - } // namespace // ============================================================== the plugin ABI entry points @@ -833,14 +832,18 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { if (!std::strcmp(act, "silu")) silu = 1; else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL); } - /* A thread a chunk of CW channels inside one group (8; 4 for groups of 4 channels, the - * FLUX.2 VAE's 128 channels in 32 groups; 2 for groups of 2), a row's chunks a power of two - * dividing the 256-thread block. */ + /* A chunk is CW channels inside one group: 8, 4 or 2, the widest dividing the group (the + * FLUX.2 VAE's 128 channels in 32 groups take 4, SDXL's 320 in 32 take 2). A row's chunks are + * split over at most 256 threads, each taking `cpt` consecutive chunks of one group, `cpt` + * the smallest divisor of the group's chunks that fits the row in the block. */ if (groups <= 0 || groups > kT || n <= 0 || n % groups || (n / groups) % 2) return R4D_NO(RAD_E_SHAPE); - const int CW = (n / groups) % 8 == 0 ? 8 : (n / groups) % 4 == 0 ? 4 : 2; - const int cpr_log = log2_exact(n / CW); - if (cpr_log < 0 || n / CW > kT) return R4D_NO(RAD_E_SHAPE); + const long long cg = n / groups; + const int CW = cg % 8 == 0 ? 8 : cg % 4 == 0 ? 4 : 2; + const int cpr = (int)(n / CW), gs8 = (int)(cg / CW); + int cpt = 1; + while (cpr / cpt > kT || gs8 % cpt) ++cpt; + const int tpr = cpr / cpt, tpg = gs8 / cpt; if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) || r4d_numel(st) < groups * (2 + 3 * kGnParts)) return R4D_NO(RAD_E_SHAPE); @@ -849,22 +852,22 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { return R4D_NO(RAD_E_STRIDE); long long rx = 0, ldx = 0, ry = 0, ldy = 0; if (!rows8(x, n, &rx, &ldx) || !rows8(y, n, &ry, &ldy)) return R4D_NO(RAD_E_STRIDE); - /* Over y's rows, as libref's (x may hold more); M is not read. Counts are f32 sums: exact - * while a group's M n / groups values stay under 2^24. */ + /* Over y's rows, as libref's (x may hold more); M is not read. A part's count is exact in f32 + * (rpp cg <= 2^24); the merged counts only weigh the merges, and the variance divides by the + * group's exact count. */ const long long M = ry; - if (M <= 0 || M > rx || M > ry || M * (n / groups) >= (1ll << 24)) return R4D_NO(RAD_E_SHAPE); - const int slots = kT >> cpr_log; + if (M <= 0 || M > rx || M > ry || M * cg >= (1ll << 31)) return R4D_NO(RAD_E_SHAPE); + const int slots = kT / tpr; /* Whole passes of the block a part, as few parts as fill the scratch. */ long long rpp = (M + kGnParts - 1) / kGnParts; rpp = (rpp + slots - 1) / slots * slots; const int parts = (int)((M + rpp - 1) / rpp); - const int gs8 = (int)(n / groups / CW); float* S = (float*)r4d_wp(st); const float eps = (float)r4d_getf(a, "eps", 1e-5); int rc; #define GN_P(TX, C4) \ rc = R4D_EMIT(stream, (gn_part_kernel), dim3((unsigned)parts), dim3(kT), 0, \ - (const TX*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, (int)rpp) + (const TX*)r4d_p(x), S, (int)M, (int)groups, tpr, cpt, tpg, (int)ldx, (int)rpp) if (is_f32(x)) { if (CW == 8) GN_P(float, 8); else if (CW == 4) GN_P(float, 4); @@ -877,14 +880,14 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) { #undef GN_P if (rc != RAD_OK) return R4D_NO(rc); rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups, - parts, eps); + parts, (float)(M * cg), eps); if (rc != RAD_OK) return R4D_NO(rc); const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1; - const dim3 grid((unsigned)((M + slots - 1) / slots)); + const dim3 grid((unsigned)((M * cpr + kT - 1) / kT)); #define GN_A2(TX, TY, C4) \ return R4D_EMIT(stream, (gn_apply_kernel), grid, dim3(kT), 0, (const TX*)r4d_p(x),\ (TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \ - (int)n, cpr_log, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \ + (int)n, cpr, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \ modk, silu) #define GN_A(TX, TY) \ do { if (CW == 8) GN_A2(TX, TY, 8); if (CW == 4) GN_A2(TX, TY, 4); GN_A2(TX, TY, 2); } while (0) diff --git a/libref/ref_gen.cpp b/libref/ref_gen.cpp index 4c42ed12..16d662b5 100644 --- a/libref/ref_gen.cpp +++ b/libref/ref_gen.cpp @@ -532,6 +532,221 @@ int ref_flow_x0_step(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ kd_input, kd_step */ +/* A k-diffusion sampler over a discrete-time (VP-trained) denoiser, run in the variance-exploding + * form x = x0 + sigma eps: the lane holds x in f32, the model reads c_in x with + * c_in = 1 / sqrt(sigma^2 + 1), and a step turns the model's output into the clean estimate D and + * moves x along the schedule (docs/OPS.md, "Image generation"). Every product and sum is one f32 + * rounding in the order written; libm's log, expm1 and sqrt. */ + +namespace { + +enum { kSamplerEuler = 0, kSamplerEulerAncestral = 1, kSamplerDpmpp2m = 2 }; + +/* One entry's per-step constants, from its sigmas and guidance. */ +struct KdEntry { + float s = 0, sn = 0, w = 0; + float cskip = 0, cout = 0; /* v-prediction's c_skip and c_out */ + float sup = 0, sdown = 0; /* the ancestral step's split of sigma_next */ + float ratio = 0, em = 0; /* DPM++ 2M: sigma_next / sigma, expm1(-h) */ + float c1 = 0, c2 = 0; /* DPM++ 2M's second-order blend of D and the last D */ + bool second = false; +}; + +KdEntry kd_entry(float s, float sn, float sp, float w, int64_t sampler, bool first) { + KdEntry k; + k.s = s; + k.sn = sn; + k.w = w; + const float s2p = s * s + 1.0f; + k.cskip = 1.0f / s2p; + k.cout = s / std::sqrt(s2p); + if (sampler == kSamplerEulerAncestral) { + const float s2 = s * s, sn2 = sn * sn; + const float up2 = sn2 * (s2 - sn2) / s2; + float sup = std::sqrt(up2); + if (!(sup < sn)) sup = sn; + const float dn2 = sn2 - sup * sup; + k.sup = sup; + k.sdown = std::sqrt(dn2 > 0.0f ? dn2 : 0.0f); + } else if (sampler == kSamplerDpmpp2m && sn > 0.0f) { + const float t = -std::log(s), tn = -std::log(sn); + const float h = tn - t; + k.ratio = sn / s; + k.em = std::expm1(-h); + if (!first) { + const float hl = t - (-std::log(sp)); + const float r = hl / h; + k.c2 = 1.0f / (2.0f * r); + k.c1 = 1.0f + k.c2; + k.second = true; + } + } + return k; +} + +/* The clean estimate from the model's output `o` at x. */ +inline float kd_denoised(const KdEntry& k, bool v_pred, float x, float o) { + return v_pred ? x * k.cskip - o * k.cout : x - k.s * o; +} + +/* x after the step, from x, the guided estimate D, the lane's last estimate and the noise. */ +inline float kd_next(const KdEntry& k, int64_t sampler, float x, float D, float hist, float nz) { + if (sampler == kSamplerEuler) { + const float d = (x - D) / k.s; + return x + (k.sn - k.s) * d; + } + if (sampler == kSamplerEulerAncestral) { + const float d = (x - D) / k.s; + float xn = x + d * (k.sdown - k.s); + if (k.sn > 0.0f) xn = xn + nz * k.sup; + return xn; + } + if (k.sn == 0.0f) return D; + const float Dd = k.second ? k.c1 * D - k.c2 * hist : D; + return k.ratio * x - k.em * Dd; +} + +inline uint64_t kd_seed(const RadTensor* seed, int64_t e) { + return (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) | + ((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32); +} + +} /* namespace */ + +/* The model's input for every entry that moves a lane (pair != -2): on a first step the lane + * becomes the seed's normal stream times sqrt(1 + sigma^2) (k-diffusion's start at the schedule's + * largest sigma), then y = rd(x / sqrt(sigma^2 + 1)) at the entry's rows and, when it is guided, at + * its pair's rows too (the negative entry reads the same latent). */ +int ref_kd_input(const RadArgs* a, RadStream) { + if (!have(a, 8)) return RAD_E_INVAL; + const RadTensor *sg = &a->t[0], *pair = &a->t[1], *lane = &a->t[2], *fl = &a->t[3]; + const RadTensor *seed = &a->t[4], *cu = &a->t[5], *st = &a->t[6], *y = &a->t[7]; + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), y_rows = rows_of(y, n); + if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; + if (numel(sg) < n_seq || numel(pair) < n_seq || numel(lane) < n_seq || numel(fl) < n_seq || + numel(seed) < 2 * n_seq) + return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > y_rows) + return RAD_E_SHAPE; + if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len || + cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > y_rows))) + return RAD_E_SHAPE; + if (ld_int(fl->dtype, fl->data, offlin(fl, e)) & kInpaint) return RAD_E_UNSUPPORTED; + } + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0; + const float s = ldt(sg, offlin(sg, e)); + const float init = std::sqrt(1.0f + s * s), cin = 1.0f / std::sqrt(s * s + 1.0f); + const bool first = (ld_int(fl->dtype, fl->data, offlin(fl, e)) & kFirst) != 0; + const uint64_t sd = kd_seed(seed, e); + REF_PAR_FOR(len * n * 8) + for (int64_t k = 0; k < len; ++k) { + const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st); + const int64_t yb = rowoff(y, b0 + k, n), ys = laststride(y); + const int64_t pb = pr >= 0 ? rowoff(y, p0 + k, n) : 0; + for (int64_t c = 0; c < n; ++c) { + if (first) stt(st, sb + c * ss, rad_philox_normal(sd, (uint64_t)(k * n + c)) * init); + const float v = ldt(st, sb + c * ss) * cin; + stt(y, yb + c * ys, v); + if (pr >= 0) stt(y, pb + c * ys, v); + } + } + } + return RAD_OK; +} + +/* One sampler step for every entry that moves a lane (pair != -2), x the lane's f32 state: + * + * D = eps: x - sigma o v: x / (sigma^2 + 1) - o sigma / sqrt(sigma^2 + 1) + * D = pair >= 0 ? D(o_u) + cfg (D(o_c) - D(o_u)) : D(o_c) + * + * then by the entry's sampler: 0 Euler, x + (sigma_next - sigma)(x - D) / sigma; 1 Euler ancestral + * (eta 1): the step to sigma_down plus sigma_up times the seed's stream 1 + step; 2 DPM++ 2M: + * (sigma_next / sigma) x - expm1(-h) D', D' blending D with the lane's last estimate after the first + * step, and D itself at sigma_next 0. Flag 4 writes D to the preview; every step leaves D in + * `hist` for the next. */ +int ref_kd_step(const RadArgs* a, RadStream) { + if (!have(a, 14)) return RAD_E_INVAL; + const RadTensor *O = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *sgp = &a->t[3]; + const RadTensor *cfg = &a->t[4], *pair = &a->t[5], *lane = &a->t[6], *fl = &a->t[7]; + const RadTensor *seed = &a->t[8], *smp = &a->t[9], *stp = &a->t[10], *cu = &a->t[11]; + const RadTensor *st = &a->t[12], *hs = &a->t[13], *pv = t_in(a, 14); + const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0); + const char* pred = p_str(a, "pred", "eps"); + const bool v_pred = pred && !std::strcmp(pred, "v"); + if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return RAD_E_INVAL; + if (n <= 0 || stride <= 0) return RAD_E_SHAPE; + const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), o_rows = rows_of(O, n); + if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; + for (const RadTensor* t : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp }) + if (numel(t) < n_seq) return RAD_E_SHAPE; + if (numel(seed) < 2 * n_seq || rows_of(hs, n) < st_rows || (pv && rows_of(pv, n) < st_rows)) + return RAD_E_SHAPE; + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > o_rows) + return RAD_E_SHAPE; + if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len || + cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > o_rows))) + return RAD_E_SHAPE; + const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e)); + const int64_t sm = ld_int(smp->dtype, smp->data, offlin(smp, e)); + if ((f & kInpaint) || sm < kSamplerEuler || sm > kSamplerDpmpp2m) return RAD_E_UNSUPPORTED; + if ((f & kPreview) && !pv) return RAD_E_INVAL; + } + for (int64_t e = 0; e < n_seq; ++e) { + const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e)); + if (pr == -2) continue; + const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e)); + const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0; + const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0; + const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e)); + const int64_t sm = ld_int(smp->dtype, smp->data, offlin(smp, e)); + const uint64_t stream = (uint64_t)(uint32_t)(1 + ld_int(stp->dtype, stp->data, offlin(stp, e))); + const KdEntry K = kd_entry(ldt(sg, offlin(sg, e)), ldt(sgn, offlin(sgn, e)), + ldt(sgp, offlin(sgp, e)), ldt(cfg, offlin(cfg, e)), sm, + (f & kFirst) != 0); + const uint64_t sd = kd_seed(seed, e); + REF_PAR_FOR(len * n * 8) + for (int64_t k = 0; k < len; ++k) { + const int64_t ob = rowoff(O, b0 + k, n), os = laststride(O); + const int64_t ub = pr >= 0 ? rowoff(O, p0 + k, n) : 0; + const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st); + const int64_t hb = rowoff(hs, L * stride + k, n), hss = laststride(hs); + for (int64_t c = 0; c < n; ++c) { + const float x = ldt(st, sb + c * ss); + float D = kd_denoised(K, v_pred, x, ldt(O, ob + c * os)); + if (pr >= 0) { + const float Du = kd_denoised(K, v_pred, x, ldt(O, ub + c * os)); + D = Du + K.w * (D - Du); + } + if (f & kPreview) + stt(pv, rowoff(pv, L * stride + k, n) + c * laststride(pv), D); + const float nz = sm == kSamplerEulerAncestral && K.sn > 0.0f + ? rad_philox_normal_s(sd, stream, (uint64_t)(k * n + c)) : 0.0f; + stt(st, sb + c * ss, kd_next(K, sm, x, D, ldt(hs, hb + c * hss), nz)); + stt(hs, hb + c * hss, D); + } + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ chan_affine */ /* A per-channel affine from two parameter lists (a latent's mean and deviation are configuration, * not weights), each value rounded to bf16 as upstream holds it: mode `fma` is @@ -621,6 +836,50 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ im2col_nhwc */ +/* conv2d_nhwc's receptive fields as rows, so a convolution is a GEMM against its own weight read as + * [cout, cin k k]: x is [Hin, Win * cin] (rows at their own pitch), y [Ho * Wo, cin * k * k], and + * row oy * Wo + ox, column (ci k + i) k + j holds the value conv2d_nhwc multiplies weight + * [o, ci, i, j] by -- x at the tap's position read through `up` and `pad` as conv2d_nhwc reads it, + * 0 in the padding. The output size follows from x's; y must have exactly Ho * Wo rows. A copy: + * the values are stored as they are (rounded only when y is narrower than x). */ +int ref_im2col_nhwc(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t cin = p_int(a, "cin", 0), k = p_int(a, "k", 0); + const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1); + const char* pad = p_str(a, "pad", "same"); + const bool down = pad && !std::strcmp(pad, "down"); + const bool causal = pad && !std::strcmp(pad, "causal"); + if (cin <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE; + if (x->rank != 2 || x->shape[1] % cin) return RAD_E_SHAPE; + const int64_t Hin = x->shape[0], Win = x->shape[1] / cin, kk = cin * k * k; + if (Hin <= 0 || Win <= 0) return RAD_E_SHAPE; + const int64_t Hv = Hin * up, Wv = Win * up; + const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2; + const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2; + const int64_t Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1; + if (Ho <= 0 || Wo <= 0 || rows_of(y, kk) != Ho * Wo) return RAD_E_SHAPE; + const int64_t xr = x->stride[0], xs = laststride(x), ys = laststride(y); + REF_PAR_FOR(Ho * Wo * kk) + for (int64_t oy = 0; oy < Ho; ++oy) + for (int64_t ox = 0; ox < Wo; ++ox) { + const int64_t yb = rowoff(y, oy * Wo + ox, kk); + for (int64_t ci = 0; ci < cin; ++ci) + for (int64_t i = 0; i < k; ++i) { + const int64_t iy = oy * stride + i - pt; + for (int64_t j = 0; j < k; ++j) { + const int64_t ix = ox * stride + j - pl; + const bool in = iy >= 0 && iy < Hv && ix >= 0 && ix < Wv; + const float v = in ? ldt(x, (iy / up) * xr + ((ix / up) * cin + ci) * xs) + : 0.0f; + stt(y, yb + ((ci * k + i) * k + j) * ys, v); + } + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ l2norm_chan */ /* An image norm over each pixel's channels, as upstream's three bf16 tensors: * n1 = bf16(x / max(||x||, 1e-12)), n2 = bf16(n1 * sqrt(n)), y = bf16(n2 * gamma), then `act` @@ -761,6 +1020,31 @@ int ref_gelu_tanh(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ gelu_quick */ +/* CLIP's quick_gelu as torch evaluates it in a reduced dtype, three stored tensors: + * a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s). */ +int ref_gelu_quick(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n); + if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE; + const uint32_t dt = y->dtype; + REF_PAR_FOR(rows * n) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t c = 0; c < n; ++c) { + const float v = ldt(x, xb + c * xs); + const float t = round_dt(dt, 1.702f * v); + const float s = round_dt(dt, 1.0f / (1.0f + std::exp(-t))); + stt(y, yb + c * ys, v * s); + } + } + return RAD_OK; +} + /* x[idx[i]] = x[idx[i]] + v[i], rounded to x's dtype; a negative index is a skip. */ int ref_scatter_add_rows(const RadArgs* a, RadStream) { if (!have(a, 3)) return RAD_E_INVAL; diff --git a/libref/ref_lora.cpp b/libref/ref_lora.cpp index de8b521c..54ec5046 100644 --- a/libref/ref_lora.cpp +++ b/libref/ref_lora.cpp @@ -101,8 +101,8 @@ int ref_lora_shrink(const RadArgs* a, RadStream) { return RAD_OK; } -/* operands: t, slot, lora_b, scale, y (inout) */ -int ref_lora_expand(const RadArgs* a, RadStream) { +/* operands: t, slot, lora_b, scale, y (inout). `bf16_t`: lora_expand_mm, t rounded to bf16. */ +static int lora_expand_impl(const RadArgs* a, bool bf16_t) { if (!have(a, 5)) return RAD_E_INVAL; const RadTensor *T = &a->t[0], *SL = &a->t[1], *LB = &a->t[2], *SC = &a->t[3], *Y = &a->t[4]; const int64_t N = p_int(a, "N", 0), R = p_int(a, "R", 0), S = p_int(a, "S", 0); @@ -127,9 +127,11 @@ int ref_lora_expand(const RadArgs* a, RadStream) { if (s < 0) continue; /* a base row: not read, not written */ const int64_t t0 = m * mt.rs, b0 = s * pb.s0 + n * pb.s1; float acc = 0.0f; - for (int64_t j = 0; j < R; ++j) - acc += ((const float*)T->data)[t0 + j * mt.cs] * - ld_dt(LB->dtype, LB->data, b0 + j * pb.s2); + for (int64_t j = 0; j < R; ++j) { + float tv = ((const float*)T->data)[t0 + j * mt.cs]; + if (bf16_t) tv = rad_bf16_to_f32(rad_f32_to_bf16(tv)); + acc += tv * ld_dt(LB->dtype, LB->data, b0 + j * pb.s2); + } const float sc = ((const float*)SC->data)[s * sc_r + n * sc_c]; const int64_t o = m * ys_r + n * ys_c; /* `sc * acc` and then the add, each rounded: the order is the definition. */ @@ -138,3 +140,9 @@ int ref_lora_expand(const RadArgs* a, RadStream) { } return RAD_OK; } + +int ref_lora_expand(const RadArgs* a, RadStream) { return lora_expand_impl(a, false); } + +/* lora_expand with t rounded to bf16; the order of the sum is free, so j ascending is one of the + * answers it allows. */ +int ref_lora_expand_mm(const RadArgs* a, RadStream) { return lora_expand_impl(a, true); } diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 3c72d4cc..4c164a65 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -137,6 +137,7 @@ int ref_gemm_nt_q_bias (const RadArgs*, RadStream); /* Runtime LoRA's two halves, per-row adapter slot (ref_lora.cpp). */ int ref_lora_shrink (const RadArgs*, RadStream); int ref_lora_expand (const RadArgs*, RadStream); +int ref_lora_expand_mm (const RadArgs*, RadStream); int ref_embed_lookup (const RadArgs*, RadStream); int ref_embed_lookup_q (const RadArgs*, RadStream); int ref_logits_gemm (const RadArgs*, RadStream); @@ -162,6 +163,8 @@ int ref_lane_gather(const RadArgs*, RadStream); int ref_lane_store(const RadArgs*, RadStream); int ref_randn_lanes(const RadArgs*, RadStream); int ref_flow_euler(const RadArgs*, RadStream); +int ref_kd_input(const RadArgs*, RadStream); +int ref_kd_step(const RadArgs*, RadStream); int ref_rms_mod(const RadArgs*, RadStream); int ref_rms_mod_quant_fp8(const RadArgs*, RadStream); int ref_flow_x0_step(const RadArgs*, RadStream); @@ -219,11 +222,13 @@ int ref_cu_repeat(const RadArgs*, RadStream); int ref_int_affine(const RadArgs*, RadStream); int ref_chan_affine(const RadArgs*, RadStream); int ref_conv2d_nhwc(const RadArgs*, RadStream); +int ref_im2col_nhwc(const RadArgs*, RadStream); int ref_l2norm_chan(const RadArgs*, RadStream); int ref_d2s_add(const RadArgs*, RadStream); int ref_s2d_avg_add(const RadArgs*, RadStream); int ref_to_rgba8(const RadArgs*, RadStream); int ref_gelu_tanh(const RadArgs*, RadStream); +int ref_gelu_quick(const RadArgs*, RadStream); int ref_scatter_add_rows(const RadArgs*, RadStream); int ref_attn_prefix_self(const RadArgs*, RadStream); int ref_qsa_block_key (const RadArgs*, RadStream); @@ -379,6 +384,7 @@ REF_SHAPE_FN(ref_gemm_nt_q); REF_SHAPE_FN(ref_gemm_nt_q_bias); REF_SHAPE_FN(ref_lora_shrink); REF_SHAPE_FN(ref_lora_expand); +REF_SHAPE_FN(ref_lora_expand_mm); REF_SHAPE_FN(ref_embed_lookup); REF_SHAPE_FN(ref_embed_lookup_q); REF_SHAPE_FN(ref_logits_gemm); @@ -402,6 +408,8 @@ REF_SHAPE_FN(ref_lane_gather); REF_SHAPE_FN(ref_lane_store); REF_SHAPE_FN(ref_randn_lanes); REF_SHAPE_FN(ref_flow_euler); +REF_SHAPE_FN(ref_kd_input); +REF_SHAPE_FN(ref_kd_step); REF_SHAPE_FN(ref_rms_mod); REF_SHAPE_FN(ref_rms_mod_quant_fp8); REF_SHAPE_FN(ref_flow_x0_step); @@ -453,11 +461,13 @@ REF_SHAPE_FN(ref_cu_repeat); REF_SHAPE_FN(ref_int_affine); REF_SHAPE_FN(ref_chan_affine); REF_SHAPE_FN(ref_conv2d_nhwc); +REF_SHAPE_FN(ref_im2col_nhwc); REF_SHAPE_FN(ref_l2norm_chan); REF_SHAPE_FN(ref_d2s_add); REF_SHAPE_FN(ref_s2d_avg_add); REF_SHAPE_FN(ref_to_rgba8); REF_SHAPE_FN(ref_gelu_tanh); +REF_SHAPE_FN(ref_gelu_quick); REF_SHAPE_FN(ref_scatter_add_rows); REF_SHAPE_FN(ref_attn_prefix_self); REF_SHAPE_FN(ref_qsa_block_key); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index fbf5cbe3..827188ca 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -741,12 +741,25 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"), OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"), INOUT("state"), INOUT_O("preview") }; +/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */ +static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"), + P_STR("dtype") }; +static const RadOperandSpec oKdInput[] = { OPD("sigma"), OPD("pair"), OPD("lane"), OPD("flags"), + OPD("seed"), OPD("cu_seqlens"), INOUT("state"), + OUT("y") }; +static const RadOperandSpec oKdStep[] = { OPD("out"), OPD("sigma"), OPD("sigma_next"), + OPD("sigma_prev"), OPD("cfg"), OPD("pair"), OPD("lane"), + OPD("flags"), OPD("seed"), OPD("sampler"), OPD("step"), + OPD("cu_seqlens"), INOUT("state"), INOUT("hist"), + INOUT_O("preview") }; /* `round` 0 keeps the lists and the arithmetic in f32 (default 1, bf16 lists and roundings). */ static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"), P_STR("mode"), P_STR("dtype"), P_INTO("round") }; static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"), P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") }; static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") }; +static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"), + P_STR("pad"), P_INT("up"), P_STR("dtype") }; static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") }; static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"), @@ -1265,6 +1278,11 @@ static const RadOpSchema kSchemas[] = { "slot[m] is in [0, S), f32 accumulate, j ascending, one rounding to y's dtype. A base row's `y` " "is neither read nor written, so it stays bit for bit what the GEMM wrote (not y + 0: that " "turns -0 into +0)." }, +{ "lora_expand_mm", ARR(pLoraExpand), ARR(oLoraExpand), + "lora_expand with t rounded to bf16 and the sum over j in any order: y[m, n] = y[m, n] + " + "scale[s, n] * sum_j bf16(t[m, j]) * lora_b[s, n, j], f32 accumulate, one rounding to y's dtype. " + "A base row's `y` is neither read nor written. A row's bytes may depend on M: the generators' " + "expand, whose passes are many rows of one adapter." }, { "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged), "Paged attention over kv_cache[num_blocks, kv_heads, block_size, 2*head_dim] (K then V per " @@ -1550,6 +1568,15 @@ static const RadOpSchema kSchemas[] = { "one Euler step of a flow-matching sampler per entry that moves a lane: guidance against the " "paired entry, x' = bf16(x + bf16(bf16(sigma_next - sigma) * v)), a preview of the clean " "latent with flag 4, the kept region of a repaint restored with flag 2 (docs/OPS.md)." }, +{ "kd_input", ARR(pLane), ARR(oKdInput), + "a k-diffusion sampler's model input per entry that moves a lane: on a first step the lane " + "becomes its seed's normal stream times sqrt(1 + sigma^2); y = rd(x / sqrt(sigma^2 + 1)) at the " + "entry's rows and at its pair's (docs/OPS.md)." }, +{ "kd_step", ARR(pKdStep), ARR(oKdStep), + "one k-diffusion sampler step over a discrete-time denoiser per entry that moves a lane: the " + "clean estimate D from an eps or v output, guided against the pair, then Euler, Euler ancestral " + "or DPM++ 2M by the entry's sampler, the lane f32; flag 4 previews D, `hist` keeps it " + "(docs/OPS.md)." }, { "chan_affine", ARR(pChanAffine), ARR(oUnary), "a per-channel affine from two parameter lists of n values (rounded to bf16): `fma` is " "bf16(bf16(x * mul) + add), `inv` bf16(bf16(x - add) / mul). `round` 0 keeps the lists and " @@ -1559,6 +1586,11 @@ static const RadOpSchema kSchemas[] = { "the sizes read off them; PyTorch's [cout, cin, k, k] weight and a bias; `up` 2 reads the input " "upsampled nearest-neighbour; `pad` same (k/2 a side) or down (0 above and left, 1 below and " "right)." }, +{ "im2col_nhwc", ARR(pIm2col), ARR(oUnary), + "conv2d_nhwc's receptive fields as rows: x [Hin, Win * cin], y [Hout * Wout, cin * k * k], row " + "oy * Wout + ox and column (ci * k + i) * k + j the value conv2d_nhwc multiplies weight[o, ci, " + "i, j] by (0 in the padding), so y @ w.reshape(cout, cin * k * k)^T + b is the convolution; " + "`up`, `pad` and `stride` as conv2d_nhwc reads them." }, { "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm), "each row normalised to unit L2 (eps 1e-12), times sqrt(n), times gamma -- three bf16 roundings " "-- then `act` none or silu: an image decoder's channel norm." }, @@ -1572,6 +1604,8 @@ static const RadOpSchema kSchemas[] = { "decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them: " "round(clamp(bf16(bf16(clamp(x) / 2) + 0.5), 0, 1) * 255), u8 out." }, { "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." }, +{ "gelu_quick", ARR(pMnD), ARR(oUnary), + "CLIP's quick_gelu, three roundings: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)." }, { "scatter_add_rows", ARR(pMnD), ARR(oScatterRows), "x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." }, { "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS), @@ -2072,6 +2106,9 @@ SIMPLE("ref_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base SIMPLE("ref_lora_expand", "lora_expand", "gemm", "y += scale * (t B[slot]^T) per row, base rows untouched", "f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", ref_lora_expand), +SIMPLE("ref_lora_expand_mm", "lora_expand_mm", "gemm", + "y += scale * (bf16(t) B[slot]^T) per row, base rows untouched", + "f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", ref_lora_expand_mm), ROW("ref_attn_paged", "attn_paged", "attn", "paged causal / sliding-window attention, any query length", @@ -2209,10 +2246,16 @@ SIMPLE("ref_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's DT_FLOAT, ref_randn_lanes), SIMPLE("ref_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance", DT_FLOAT, ref_flow_euler), +SIMPLE("ref_kd_input", "kd_input", "elem", "a k-diffusion sampler's model input", DT_FLOAT, + ref_kd_input), +SIMPLE("ref_kd_step", "kd_step", "elem", "a k-diffusion sampler step with guidance", DT_FLOAT, + ref_kd_step), SIMPLE("ref_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists", DT_FLOAT, ref_chan_affine), SIMPLE("ref_conv2d_nhwc", "conv2d_nhwc", "elem", "an image convolution, channels innermost", DT_FLOAT, ref_conv2d_nhwc), +SIMPLE("ref_im2col_nhwc", "im2col_nhwc", "elem", "a convolution's receptive fields as rows", + DT_FLOAT, ref_im2col_nhwc), SIMPLE("ref_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu", DT_FLOAT, ref_l2norm_chan), SIMPLE("ref_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT, @@ -2221,6 +2264,7 @@ SIMPLE("ref_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added ref_s2d_avg_add), SIMPLE("ref_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, ref_to_rgba8), SIMPLE("ref_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, ref_gelu_tanh), +SIMPLE("ref_gelu_quick", "gelu_quick", "elem", "quick gelu", DT_FLOAT, ref_gelu_quick), SIMPLE("ref_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT, ref_scatter_add_rows), SIMPLE("ref_attn_prefix_self", "attn_prefix_self", "attn", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index efa78320..f1fd4d8a 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1254,6 +1254,10 @@ int ref_lora_expand_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o return o.finish("lora_expand", operand, out); } +int ref_lora_expand_mm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return ref_lora_expand_shape(p, n_p, operand, out); +} + /* ================================================================== attention * * The paged layout (ref_ops.h): @@ -2602,6 +2606,53 @@ int ref_flow_euler_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("flow_euler", operand, out); } +/* The k-diffusion sampler's two ops over flow_euler's entries: two equal-length entries where M + * allows, the lanes f32, sigmas drawn in (0, 1) so every logarithm and root is of a positive + * value. Flags draw only the first step (bit 1): the preview needs its optional operand and + * neither op repaints; the hand-written cases take the rest. */ +int ref_kd_input_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), st = gi(p, n_p, "stride", 0); + if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = (M % 2 == 0 && M / 2 <= st) ? 2 : 1; + if (M > S * st) return RAD_E_UNSUPPORTED; + const uint32_t F = (uint32_t)RAD_F32; + Opd o; + o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */ + o.t_idx({ S }, S, -1, 0); /* pair */ + o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t_idx({ S }, 2, -1, 0); /* flags */ + o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(F, { REF_LANES * st, n }); /* state, INOUT */ + o.t(act_dt(p, n_p), { M, n }); /* y */ + return o.finish("kd_input", operand, out); +} + +int ref_kd_step_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), st = gi(p, n_p, "stride", 0); + if (M <= 0 || n <= 0 || st <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = (M % 2 == 0 && M / 2 <= st) ? 2 : 1; + if (M > S * st) return RAD_E_UNSUPPORTED; + const uint32_t F = (uint32_t)RAD_F32; + Opd o; + o.t(act_dt(p, n_p), { M, n }); /* out */ + o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma */ + o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma_next */ + o.t_fill(F, { S }, (uint32_t)RAD_FILL_SIGMOID, 0); /* sigma_prev */ + o.t(F, { S }); /* cfg */ + o.t_idx({ S }, S, -1, 0); /* pair */ + o.t_idx({ S }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */ + o.t_idx({ S }, 2, -1, 0); /* flags */ + o.t_idx({ 2 * S }, (int64_t)1 << 30, -1, 0); /* seed */ + o.t_idx({ S }, 3, -1, 0); /* sampler */ + o.t_idx({ S }, 64, -1, 0); /* step */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(F, { REF_LANES * st, n }); /* state, INOUT */ + o.t(F, { REF_LANES * st, n }); /* hist, INOUT */ + o.t(F, { REF_LANES * st, n }); /* preview, INOUT */ + return o.finish("kd_step", operand, out); +} + /* ---- an image decoder's convolutions and shortcuts. Sizes are read off the operands and M counts * output pixels, so this picks eight columns where M allows (a row with both edges and an interior) * and the input that produces that output; otherwise it declines. */ @@ -2636,6 +2687,27 @@ int ref_conv2d_nhwc_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* o return o.finish("conv2d_nhwc", operand, out); } +/* conv2d_nhwc's geometry with the receptive fields as y's rows: M output pixels of cin k k values. */ +int ref_im2col_nhwc_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), k = gi(p, n_p, "k", 0); + const int64_t stride = gi(p, n_p, "stride", 1), up = gi(p, n_p, "up", 1); + const char* pad = gs(p, n_p, "pad"); + if (M <= 0 || cin <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_UNSUPPORTED; + const bool down = pad && !std::strcmp(pad, "down"); + const int64_t pads = down ? 1 : 2 * (k / 2); + const int64_t Wo = cols_for(M, 1), Ho = Wo ? M / Wo : 0; + if (!Wo) return RAD_E_UNSUPPORTED; + const int64_t Hv = (Ho - 1) * stride + k - pads, Wv = (Wo - 1) * stride + k - pads; + if (Hv <= 0 || Wv <= 0 || Hv % up || Wv % up) return RAD_E_UNSUPPORTED; + if ((Hv + pads - k) / stride + 1 != Ho || (Wv + pads - k) / stride + 1 != Wo) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { Hv / up, (Wv / up) * cin }); /* x */ + o.t(D, { Ho * Wo, cin * k * k }); /* y */ + return o.finish("im2col_nhwc", operand, out); +} + int ref_d2s_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0); if (M <= 0 || cin <= 0 || cout <= 0) return RAD_E_UNSUPPORTED; @@ -2745,6 +2817,14 @@ int ref_gelu_tanh_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out o.t(D, { M, n }); return o.finish("gelu_tanh", operand, out); } +int ref_gelu_quick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); + o.t(D, { M, n }); + return o.finish("gelu_quick", operand, out); +} int ref_scatter_add_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); diff --git a/scripts/README.md b/scripts/README.md index 1133f833..591a6198 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -23,6 +23,7 @@ and `agentreplay.py` need `python3`. Scripts find each other through `$(dirname | `convdspark.sh` | Rebuilds the container `mcserve.sh` serves, with the drafter merged, as `minicpm5-2b-dspark.new.rad` beside it. The checkpoint and drafter paths are fixed; `RECIPE=` overrides the recipe. | | `convfn.sh` | Rebuilds the container `fnserve.sh` serves, as `w4nl64-i8lm.new.rad` beside it, from `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`. Needs `CALIB=`: the recipe's expert rule runs GPTQ against the calibration Grams there (`docs/MOE-W4.md`). | | `hfget.sh` | Fetches a Hugging Face repo with `curl` and `jq`. Resumable, and skips the duplicate weight formats a repo often carries beside its safetensors. `radiance --model ` runs it. | +| `krea2_native.py` | Rewrites a Krea 2 DiT single file in Krea's own key names (`turbo.safetensors`, civitai and ComfyUI finetunes) as diffusers' transformer file, bytes unchanged, so it converts as the `transformer/` of a Krea 2 pipeline directory (`docs/GUIDE.md`). | ## Measuring diff --git a/scripts/krea2_native.py b/scripts/krea2_native.py new file mode 100755 index 00000000..d4e8a0cb --- /dev/null +++ b/scripts/krea2_native.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +# krea2_native.py -- a Krea 2 DiT single file in the reference code's key names, as diffusers' +# Krea2Transformer2DModel file, so rad-convert reads it as the transformer/ of a pipeline directory. +# +# krea2_native.py /transformer/diffusion_pytorch_model.safetensors +# +# Krea's own turbo.safetensors / raw.safetensors, and the finetunes civitai and ComfyUI ship, name +# the DiT by krea-ai/krea-2 mmdit.py (`blocks.N.attn.wq`, `txtfusion.refiner_blocks.N.mlp.up`, +# `tproj.1`) and carry no text encoder or VAE. Each tensor maps to one diffusers tensor, the same +# bytes under a new name; the blocks' modulation tables are flat ([6 * D]) where diffusers stores +# them [6, D], so only their shape is restated. Checked against krea/Krea-2-Turbo, whose turbo.safetensors +# and diffusers shards hold byte-identical tensors under this map (norms, tables, embedders, linears). +# +# The rest of the pipeline directory (model_index.json, scheduler/, text_encoder/, tokenizer/, vae/, +# transformer/config.json) is the release's: Raw and Turbo ship identical parts but for +# model_index.json, whose `is_distilled` selects Turbo's sampling (8 steps, no guidance). A finetune +# stored as plain fp8 converts with data/recipes/krea-2-fp8-unscaled.recipe. +# +# Needs only python3; the data is copied, never decoded. +import json +import os +import re +import shutil +import struct +import sys + +RULES = [ + (r"^blocks\.(\d+)\.", r"transformer_blocks.\1."), + (r"^txtfusion\.", r"text_fusion."), + (r"\.attn\.wq\.", ".attn.to_q."), (r"\.attn\.wk\.", ".attn.to_k."), (r"\.attn\.wv\.", ".attn.to_v."), + (r"\.attn\.wo\.", ".attn.to_out.0."), (r"\.attn\.gate\.", ".attn.to_gate."), + (r"\.attn\.qknorm\.qnorm\.scale$", ".attn.norm_q.weight"), + (r"\.attn\.qknorm\.knorm\.scale$", ".attn.norm_k.weight"), + (r"\.mlp\.(gate|up|down)\.", r".ff.\1."), + (r"\.prenorm\.scale$", ".norm1.weight"), (r"\.postnorm\.scale$", ".norm2.weight"), + (r"\.mod\.lin$", ".scale_shift_table"), + (r"^first\.", "img_in."), + (r"^last\.linear\.", "final_layer.linear."), (r"^last\.norm\.scale$", "final_layer.norm.weight"), + (r"^last\.modulation\.lin$", "final_layer.scale_shift_table"), + (r"^tmlp\.0\.", "time_embed.linear_1."), (r"^tmlp\.2\.", "time_embed.linear_2."), + (r"^tproj\.1\.", "time_mod_proj."), + (r"^txtmlp\.0\.scale$", "txt_in.norm.weight"), + (r"^txtmlp\.1\.", "txt_in.linear_1."), (r"^txtmlp\.3\.", "txt_in.linear_2."), +] + + +def to_diffusers(k): + for a, b in RULES: + k = re.sub(a, b, k) + return k + + +def main(): + if len(sys.argv) != 3: + sys.exit("usage: krea2_native.py ") + src, dst = sys.argv[1], sys.argv[2] + with open(src, "rb") as f: + n = struct.unpack(" {dst}") + + +if __name__ == "__main__": + main() diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 9d8dcd1f..0abae8bf 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -362,6 +362,16 @@ ABI_FIELD(RadGenBatch, mode_src) ABI_FIELD(RadGenBatch, mode_ccu) ABI_FIELD(RadGenBatch, n_mode_h) ABI_FIELD(RadGenBatch, mode_rope_f) +ABI_FIELD(RadGenBatch, n_aux) +ABI_FIELD(RadGenBatch, aux_ids) +ABI_FIELD(RadGenBatch, aux_cu) +ABI_FIELD(RadGenBatch, sigma_prev) +ABI_FIELD(RadGenBatch, timestep) +ABI_FIELD(RadGenBatch, sampler) +ABI_FIELD(RadGenBatch, step) +ABI_FIELD(RadGenBatch, size_px) +ABI_FIELD(RadGenBatch, entry_h) +ABI_FIELD(RadGenBatch, tokens_h) ABI_STRUCT(RadGeneratorDecl) ABI_FIELD(RadGeneratorDecl, name) ABI_FIELD(RadGeneratorDecl, layout) @@ -403,6 +413,21 @@ ABI_FIELD(RadGeneratorDecl, pad_token) ABI_FIELD(RadGeneratorDecl, cfg_original) ABI_FIELD(RadGeneratorDecl, default_negative) ABI_FIELD(RadGeneratorDecl, ref_shrink_only) +ABI_FIELD(RadGeneratorDecl, aux_max_tokens) +ABI_FIELD(RadGeneratorDecl, sigma_grid) +ABI_FIELD(RadGeneratorDecl, min_tokens) +ABI_FIELD(RadGeneratorDecl, aux_tokens) +ABI_FIELD(RadGeneratorDecl, beta_start) +ABI_FIELD(RadGeneratorDecl, beta_end) +ABI_FIELD(RadGeneratorDecl, train_steps) +ABI_FIELD(RadGeneratorDecl, beta_schedule) +ABI_FIELD(RadGeneratorDecl, zero_snr) +ABI_FIELD(RadGeneratorDecl, samplers) +ABI_FIELD(RadGeneratorDecl, default_sampler) +ABI_FIELD(RadGeneratorDecl, default_scheduler) +ABI_FIELD(RadGeneratorDecl, chunk_tokens) +ABI_FIELD(RadGeneratorDecl, chunk_bos) +ABI_FIELD(RadGeneratorDecl, chunk_eos) ABI_STRUCT(RadKVGroupBatch) ABI_FIELD(RadKVGroupBatch, group) ABI_FIELD(RadKVGroupBatch, slot_mapping) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 6fc89cfb..9ff6bc7a 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,4 +1,4 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 24 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 25 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ @@ -315,7 +315,7 @@ { "RadFuseStep", "n_p", 584, 4 }, { "RadFuseStep", "from", 588, 32 }, { "RadFuseStep", "n_from", 620, 4 }, -{ "RadGenBatch", "", 0, 320 }, +{ "RadGenBatch", "", 0, 400 }, { "RadGenBatch", "rows", 0, 8 }, { "RadGenBatch", "src", 8, 8 }, { "RadGenBatch", "rope", 16, 8 }, @@ -359,7 +359,17 @@ { "RadGenBatch", "mode_ccu", 296, 8 }, { "RadGenBatch", "n_mode_h", 304, 8 }, { "RadGenBatch", "mode_rope_f", 312, 8 }, -{ "RadGeneratorDecl", "", 0, 296 }, +{ "RadGenBatch", "n_aux", 320, 8 }, +{ "RadGenBatch", "aux_ids", 328, 8 }, +{ "RadGenBatch", "aux_cu", 336, 8 }, +{ "RadGenBatch", "sigma_prev", 344, 8 }, +{ "RadGenBatch", "timestep", 352, 8 }, +{ "RadGenBatch", "sampler", 360, 8 }, +{ "RadGenBatch", "step", 368, 8 }, +{ "RadGenBatch", "size_px", 376, 8 }, +{ "RadGenBatch", "entry_h", 384, 8 }, +{ "RadGenBatch", "tokens_h", 392, 8 }, +{ "RadGeneratorDecl", "", 0, 376 }, { "RadGeneratorDecl", "name", 0, 8 }, { "RadGeneratorDecl", "layout", 8, 4 }, { "RadGeneratorDecl", "tmpl_text", 16, 8 }, @@ -400,6 +410,21 @@ { "RadGeneratorDecl", "cfg_original", 276, 4 }, { "RadGeneratorDecl", "default_negative", 280, 8 }, { "RadGeneratorDecl", "ref_shrink_only", 288, 4 }, +{ "RadGeneratorDecl", "aux_max_tokens", 296, 8 }, +{ "RadGeneratorDecl", "sigma_grid", 304, 4 }, +{ "RadGeneratorDecl", "min_tokens", 308, 4 }, +{ "RadGeneratorDecl", "aux_tokens", 312, 4 }, +{ "RadGeneratorDecl", "beta_start", 320, 8 }, +{ "RadGeneratorDecl", "beta_end", 328, 8 }, +{ "RadGeneratorDecl", "train_steps", 336, 4 }, +{ "RadGeneratorDecl", "beta_schedule", 340, 4 }, +{ "RadGeneratorDecl", "zero_snr", 344, 4 }, +{ "RadGeneratorDecl", "samplers", 348, 4 }, +{ "RadGeneratorDecl", "default_sampler", 352, 4 }, +{ "RadGeneratorDecl", "default_scheduler", 356, 4 }, +{ "RadGeneratorDecl", "chunk_tokens", 360, 4 }, +{ "RadGeneratorDecl", "chunk_bos", 364, 4 }, +{ "RadGeneratorDecl", "chunk_eos", 368, 4 }, { "RadKVGroupBatch", "", 0, 72 }, { "RadKVGroupBatch", "group", 0, 4 }, { "RadKVGroupBatch", "slot_mapping", 8, 8 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index bc51ff46..76e49048 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -8,7 +8,7 @@ * * Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every * struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and - * the layout agrees with the table below, taken at RAD_ABI_VERSION 24 and RAD_FORMAT_VER 2. Under + * the layout agrees with the table below, taken at RAD_ABI_VERSION 25 and RAD_FORMAT_VER 2. Under * those versions a listed field may not move or change size, an ABI struct may only grow by fields * past its old end, and an on-disk struct may not change at all. The table is a snapshot of the * headers: nothing else states the layout. When it disagrees the test prints the live table. @@ -57,8 +57,8 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 24 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 24, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 25 / RAD_FORMAT_VER 2 (see the file header). */ +constexpr uint32_t kTableAbi = 25, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 39ba088c..8d34b009 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -128,6 +128,12 @@ struct RadBuilder { RadGeneratorDecl generator{}; std::string generator_name; + /* Adapter key names (rad_lora_root, rad_lora_alias): (native, spellings), and each alias as + * (native, from, to, from_lo, from_hi, to_lo). */ + std::vector> lora_roots; + struct LoraAliasRec { std::string native, from, to; int64_t from_lo, from_hi, to_lo; }; + std::vector lora_aliases; + /* What rad_weight_encoding answers: the first entry whose key the source name contains. Empty * means no model, so every weight is plain in its declared dtype. */ std::vector> encs; @@ -269,6 +275,19 @@ extern "C" int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) { return RAD_OK; } +/* Recorded: a generator's adapter key names. */ +extern "C" int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) { + if (!b || !native || !*native) return RAD_E_INVAL; + b->lora_roots.push_back({ native, spellings ? spellings : "" }); + return RAD_OK; +} +extern "C" int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to, + int64_t from_lo, int64_t from_hi, int64_t to_lo) { + if (!b || !native || !from || !to) return RAD_E_INVAL; + b->lora_aliases.push_back({ native, from, to, from_lo, from_hi, to_lo }); + return RAD_OK; +} + /* Recorded: gemma4's prefill overlap names the buffers its second lane reduces in place. */ extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { if (!b || !buf) return RAD_E_INVAL; @@ -482,6 +501,8 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s #include "../arch/embgemma2/embgemma2.cpp" /* Qwen-Image 2.1: a generator conditioned by Qwen3-VL. */ #include "../arch/qwenimage21/qwenimage21.cpp" +/* Anima: a cross-attention generator conditioned through two tokenizers. */ +#include "../arch/anima/anima.cpp" /* GLM-5.3-Flash: its connection, router, attention and cache blocks, and the plugin. */ #include #include @@ -8428,6 +8449,30 @@ TEST(qwenimage21_declares_a_generator_with_one_shared_modulation) { /* Every collective follows --tp-wire: exact unless the lossy wire was accepted, and the floor * under which a message stays exact is the deployment's. */ +/* The DiT's adapter names: one root before any GEMM, and every alias lands on a checkpoint tensor + * the plugin maps, with the gate half of ComfyUI's `gate_up` on `gate_layer`. */ +TEST(qwenimage21_names_its_adapter_keys_onto_mapped_tensors) { + MetaKV mk = qimg_meta(); + RadBuilder b; + const RadBuildCtx ctx = qimg_ctx(0, 1); + REQUIRE_EQ(qwenimage21::declare(&b, mk.meta(), &ctx), RAD_OK); + REQUIRE_EQ(b.lora_roots.size(), (size_t)1); + CHECK_EQ(b.lora_roots[0].first, std::string("transformer.")); + CHECK(b.lora_roots[0].second.find("lora_unet_") != std::string::npos); + std::set srcs; + for (const RecMap& m : b.maps) for (const std::string& x : m.src) srcs.insert(x); + REQUIRE_EQ(b.lora_aliases.size(), (size_t)2); + for (const auto& a : b.lora_aliases) { + std::string to = a.native + a.to; + const size_t h = to.find('#'); + if (h != std::string::npos) to.replace(h, 1, "0"); + CHECK(srcs.count(to + ".weight")); + } + CHECK(b.lora_aliases[0].to.find("gate_layer") != std::string::npos); + CHECK_EQ(b.lora_aliases[0].from_lo, (int64_t)0); + CHECK_EQ(b.lora_aliases[1].from_lo, b.lora_aliases[0].from_hi); +} + TEST(qwenimage21_collectives_follow_the_tp_wire) { MetaKV mk = qimg_meta(); for (int lossy : { 0, 1 }) { @@ -8473,6 +8518,314 @@ TEST(qwenimage21_generator_passes_lint_clean) { } } +/* ==================================================================== anima */ + +namespace { + +/* Anima's text encoder (Qwen3-0.6B-Base) as the container's config states it; the DiT, adapter + * and VAE are the plugin's own constants. */ +MetaKV anima_meta(const char* variant) { + RadModelMeta m{}; + m.arch_id = "anima"; m.name = "test-anima"; m.quant = ""; + m.n_layers = 28; m.n_embd = 1024; m.n_head = 16; m.n_head_kv = 8; m.head_dim = 128; + m.n_ff = 3072; m.n_vocab = 151936; m.n_ctx_train = 32768; + m.rms_eps = 1e-6f; m.rope_theta = 1e6f; m.rope_scale = 1.0f; + MetaKV k(m); + k.set("num_hidden_layers", "28").set("hidden_size", "1024").set("anima.variant", variant); + return k; +} + +RadBuildCtx anima_ctx() { + RadBuildCtx c = build_ctx(0, 1); + c.max_tok = 2 * (4096 + 512); + c.max_seqs = 4; + return c; +} + +/* A JOINT_STEP pass as the driver lays one out for Anima: COND over a prompt of `nq` Qwen3 tokens + * (padded to 512) and `nt` T5 ids, DENOISE over `entries` entries of 512 context rows and `ni` + * image rows each, or DECODE of a 64 x 64 picture. */ +struct AnimaKit { + std::vector tok, pos, cu, src, lane, flags, pair, aux, aux_cu, valid_cu; + std::vector img_cu, img_rows, mode_cu, mode_rows, mode_src, mode_ccu; + std::vector n_mode; + std::vector seed; + std::vector sigma, sigma_next, cfg, rope_f, mode_rope_f; + RadGenBatch g{}; + RadBatch b{}; +}; + +std::unique_ptr anima_pass(int pass, int64_t nq = 12, int64_t nt = 9, int64_t ni = 16, + int64_t entries = 1) { + auto k = std::make_unique(); + RadGenBatch& g = k->g; + RadBatch& b = k->b; + b.gen = pass; + b.gen_b = &k->g; + if (pass == RAD_GEN_PASS_COND) { + for (int64_t i = 0; i < 512; ++i) { + k->tok.push_back(i < nq ? (int32_t)(100 + i) : 151643); + k->pos.push_back(i < nq ? (int32_t)i : 1); + } + for (int64_t i = 0; i < nt; ++i) k->aux.push_back((int32_t)(3 + i)); + k->aux_cu = { 0, (int32_t)nt }; + k->valid_cu = { 0, (int32_t)nq }; + k->cu = { 0, 512 }; + k->lane = { 0, 1 }; + k->sigma = { 0.0f }; + b.n_tok = 512; + b.n_seq = 1; + b.token_ids = k->tok.data(); + b.positions = k->pos.data(); + b.cu_seqlens = k->cu.data(); + g.rows = 512; + g.n_pad = (int32_t)(512 - nq); + g.valid_cu = k->valid_cu.data(); + g.n_lane = 2; + g.lane = k->lane.data(); + g.lane_h = k->lane.data(); + g.branch = 1; + g.sigma = k->sigma.data(); + g.n_aux = nt; + g.aux_ids = k->aux.data(); + g.aux_cu = k->aux_cu.data(); + return k; + } + if (pass == RAD_GEN_PASS_DECODE) { + k->cu = { 0, 16 }; + b.n_tok = 16; + b.n_seq = 1; + b.cu_seqlens = k->cu.data(); + g.dec_lane = 1; + g.dec_height = g.dec_width = 64; + return k; + } + const int64_t S = entries, N = S * (512 + ni); + k->cu.push_back(0); + k->img_cu.push_back(0); + for (int64_t s = 0; s < S; ++s) { + k->mode_cu.push_back((int32_t)(s * (512 + ni))); + k->mode_cu.push_back((int32_t)(s * (512 + ni) + 512)); + k->mode_cu.push_back((int32_t)(s * (512 + ni) + 512)); + for (int64_t r = 0; r < 512; ++r) k->src.push_back((int32_t)(s * 512 + r)); + for (int64_t r = 0; r < ni; ++r) { + k->src.push_back((int32_t)(-1 - (s * ni + r))); + k->img_rows.push_back((int32_t)(s * (512 + ni) + 512 + r)); + } + k->cu.push_back((int32_t)((s + 1) * (512 + ni))); + k->img_cu.push_back((int32_t)((s + 1) * ni)); + k->lane.push_back((int32_t)(s / 2)); + k->pair.push_back(S > 1 ? (s % 2 ? -2 : (int32_t)(s + 1)) : -1); + } + k->mode_cu.push_back((int32_t)N); + for (int64_t s = 0; s < S; ++s) + for (int64_t r = 0; r < 512; ++r) { + k->mode_rows.push_back((int32_t)(s * (512 + ni) + r)); + k->mode_src.push_back((int32_t)(s * 512 + r)); + } + for (int64_t s = 0; s < S; ++s) + for (int64_t r = 0; r < ni; ++r) { + k->mode_rows.push_back((int32_t)(s * (512 + ni) + 512 + r)); + k->mode_src.push_back((int32_t)(-1 - (s * ni + r))); + } + k->n_mode = { 512 * S, 0, ni * S }; + for (int m = 0; m < 3; ++m) + for (int64_t s = 0; s <= S; ++s) + k->mode_ccu.push_back((int32_t)(s * (m == 0 ? 512 : m == 1 ? 0 : ni))); + k->rope_f.assign((size_t)(4 * N), 0.0f); + k->mode_rope_f.assign((size_t)(4 * N), 0.0f); + k->tok.assign((size_t)N, 0); + k->pos.assign((size_t)N, 0); + k->sigma.assign((size_t)S, 0.75f); + k->sigma_next.assign((size_t)S, 0.5f); + k->cfg.assign((size_t)S, 4.0f); + k->flags.assign((size_t)S, RAD_GEN_F_FIRST); + k->seed.assign((size_t)(2 * S), 7u); + b.n_tok = N; + b.n_seq = S; + b.token_ids = k->tok.data(); + b.positions = k->pos.data(); + b.cu_seqlens = k->cu.data(); + g.src = k->src.data(); + g.n_img = ni * S; + g.img_cu = k->img_cu.data(); + g.img_rows = k->img_rows.data(); + g.mode_cu = k->mode_cu.data(); + g.rope_f = k->rope_f.data(); + g.mode_rows = k->mode_rows.data(); + g.mode_src = k->mode_src.data(); + g.mode_ccu = k->mode_ccu.data(); + g.n_mode_h = k->n_mode.data(); + g.mode_rope_f = k->mode_rope_f.data(); + g.sigma = k->sigma.data(); + g.sigma_next = k->sigma_next.data(); + g.cfg = k->cfg.data(); + g.pair = k->pair.data(); + g.lane = k->lane.data(); + g.lane_dh = k->lane.data(); + g.flags = k->flags.data(); + g.seed = k->seed.data(); + return k; +} + +/* The linears a LoRA for Anima names: every DiT block's attention, MLP and modulation linears + * and the text encoder's. */ +bool anima_lora_target(const std::string& w) { + for (const char* t : { "attn_qkv", "attn_output", "cross_q", "cross_k", "cross_v", + "cross_output", "mlp_layer1", "mlp_layer2", ".mod_", "ffn_gate_up", + "ffn_down" }) + if (has(w, t) && !has(w, ".scale")) return true; + return false; +} + +} /* namespace */ + +/* A JOINT_STEP generator that reads a second tokenizer, pads an empty prompt to one token and + * samples on ComfyUI's simple schedule; the variant sets its defaults and the DiT keys' prefix is + * the checkpoint's, `model.diffusion_model.` here and `net.` for Base. */ +TEST(anima_declares_a_two_tokenizer_generator_under_the_checkpoints_prefix) { + const RadEncoding plain = rad_enc_plain(RAD_BF16); + RadBuildCtx ctx = anima_ctx(); + MetaKV mk = anima_meta("aesthetic"); + RadBuilder b; + b.encs = { { "dit.t_norm.mdm", plain }, { "dit.blk.0.attn_qkv", plain } }; + REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK_EQ(b.logits, (rad_buf)0); + CHECK_EQ(b.generator_name, std::string("anima-aesthetic")); + const RadGeneratorDecl& d = b.generator; + CHECK_EQ(d.layout, (int32_t)RAD_GEN_LAYOUT_JOINT_STEP); + CHECK_EQ(d.aux_tokens, 1); + CHECK_EQ(d.aux_max_tokens, (int64_t)512); + CHECK_EQ(d.min_tokens, 1); + CHECK_EQ(d.pad_multiple, 512); + CHECK_EQ(d.cond_rows, (int64_t)512); + CHECK_EQ(d.sigma_grid, 1000); + CHECK_EQ(d.shift, 3.0); + CHECK_EQ(d.dyn_shift, 0); + CHECK_EQ(d.cfg_original, 0); + CHECK_EQ(d.default_steps, (int64_t)30); + CHECK_EQ(d.default_cfg, 4.0); + CHECK_EQ(d.latent_channels, (int64_t)64); + CHECK(b.kv_groups.empty()); + const RecMap* q = find_map(b, "dit.blk.27.attn_qkv.weight"); + REQUIRE(q != nullptr); + REQUIRE_EQ(q->src.size(), (size_t)3); + CHECK_EQ(q->src[0], std::string("model.diffusion_model.blocks.27.self_attn.q_proj.weight")); + const RecMap* te = find_map(b, "te.blk.3.ffn_gate_up.weight"); + REQUIRE(te != nullptr); + CHECK_EQ(te->src[1], std::string("model.layers.3.mlp.up_proj.weight")); + /* The patch embedding over its first 64 columns, the final linear's rows in eight pieces. */ + const RecMap* xe = find_map(b, "dit.x_embed.weight"); + REQUIRE(xe != nullptr); + CHECK_EQ(xe->mode, (int)RAD_MAP_COLS); + int final_maps = 0; + for (const auto& m : b.maps) + if (m.declared == "dit.final.weight") { ++final_maps; CHECK_EQ(m.mode, (int)RAD_MAP_ROWS); } + CHECK_EQ(final_maps, 8); + /* The DiT's rotary: 22, 21 and 21 pairs, NeoX, over (frame, row, column). */ + int axial = 0; + for (const auto& o : b.ops) + if (o.op == "qk_norm_rope" && pstr(&o, "mode") == "axial") { + CHECK_EQ(pstr(&o, "sections"), std::string("22 21 21")); + ++axial; + } + CHECK_EQ(axial, 28); + + MetaKV turbo = anima_meta("turbo"); + RadBuilder bt; + bt.encs = { { "dit.t_norm.mdm", plain } }; + REQUIRE_EQ(anima::declare(&bt, turbo.meta(), &ctx), RAD_OK); + CHECK_EQ(bt.generator_name, std::string("anima-turbo")); + CHECK_EQ(bt.generator.default_steps, (int64_t)10); + CHECK_EQ(bt.generator.default_cfg, 1.0); + + MetaKV base = anima_meta("base"); + RadBuilder bb; + bb.encs = { { "dit.t_norm.net", plain } }; + REQUIRE_EQ(anima::declare(&bb, base.meta(), &ctx), RAD_OK); + const RecMap* nq = find_map(bb, "dit.blk.0.mlp_layer1.weight"); + REQUIRE(nq != nullptr); + CHECK_EQ(nq->src[0], std::string("net.blocks.0.mlp.layer1.weight")); + + /* Neither spelling, or an unknown variant, is refused. */ + RadBuilder none; + CHECK(anima::declare(&none, mk.meta(), &ctx) < 0); + MetaKV odd = anima_meta("deluxe"); + RadBuilder bo; + bo.encs = { { "dit.t_norm.mdm", plain } }; + CHECK(anima::declare(&bo, odd.meta(), &ctx) < 0); +} + +/* Every linear a LoRA for Anima names is read by a plain GEMM a runtime LoRA can follow: gemm_nt + * in a bf16 container, gemm_nt_q without rotated parts in a block-fp8 one, its activation a + * separate op. */ +TEST(anima_lora_targets_are_plain_gemms) { + const RadEncoding plain = rad_enc_plain(RAD_BF16); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + RadBuildCtx ctx = anima_ctx(); + MetaKV mk = anima_meta("base"); + for (bool q : { false, true }) { + RadBuilder b; + b.encs = { { "dit.t_norm.net", plain } }; + if (!q) b.encs.push_back({ "dit.blk.0.attn_qkv", plain }); + if (q) + for (const char* t : { "attn_qkv", "attn_output", "cross_q", "cross_k", "cross_v", + "cross_output", "mlp_layer1", "mlp_layer2", "ffn_gate_up", + "ffn_down" }) + b.encs.push_back({ t, fp8 }); + REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK); + int targets = 0; + for (const auto& o : b.ops) + for (rad_weight w : o.w) { + const std::string& n = b.weights[w - 1].name; + if (!anima_lora_target(n)) continue; + ++targets; + const bool ok = o.op == "gemm_nt" || (q && o.op == "gemm_nt_q" && + pint(&o, "pb1") <= 0 && pint(&o, "pb2") <= 0); + if (!ok) fprintf(stderr, " '%s' read by %s\n", n.c_str(), o.op.c_str()); + CHECK(ok); + CHECK(o.op != "gemm_nt_bias"); + } + /* 28 blocks of 8 linears (two views a block-fp8 one) and 6 modulation linears; 28 text + * encoder layers of 4. */ + CHECK(targets >= 28 * (8 + 6) + 28 * 4); + } +} + +/* The three passes the core drives (a conditioning with its T5 ids, denoising one image or a + * guided pair, decoding one) lint clean in a bf16 and a block-fp8 container. */ +TEST(anima_generator_passes_lint_clean) { + const RadEncoding plain = rad_enc_plain(RAD_BF16); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + RadBuildCtx ctx = anima_ctx(); + MetaKV mk = anima_meta("aesthetic"); + for (bool q : { false, true }) { + RadBuilder b; + b.encs = { { "dit.t_norm.mdm", plain } }; + if (!q) b.encs.push_back({ "dit.blk.0.attn_qkv", plain }); + if (q) b.encs.push_back({ "attn_qkv", fp8 }), b.encs.push_back({ "attn_output", fp8 }), + b.encs.push_back({ "cross_", fp8 }), b.encs.push_back({ "mlp_layer", fp8 }), + b.encs.push_back({ "ffn_", fp8 }); + REQUIRE_EQ(anima::declare(&b, mk.meta(), &ctx), RAD_OK); + for (const auto& k : { anima_pass(RAD_GEN_PASS_COND, 12, 9), + anima_pass(RAD_GEN_PASS_COND, 3, 40), + anima_pass(RAD_GEN_PASS_DENOISE, 12, 9, 16, 1), + anima_pass(RAD_GEN_PASS_DENOISE, 12, 9, 16, 2), + anima_pass(RAD_GEN_PASS_DECODE) }) { + RadCtx c{ .b = &b, .batch = &k->b, .rank = 0, .world = 1 }; + anima::step(&c, &k->b); + CHECK(c.step_fail.empty()); + if (!c.step_fail.empty()) fprintf(stderr, " %s\n", c.step_fail.c_str()); + CHECK(!c.issues.empty()); + CHECK_LINT(b, &c); + } + const auto tok = kit(b, { 1 }, {}); + RadCtx c{ .b = &b, .batch = &tok->b, .rank = 0, .world = 1 }; + anima::step(&c, &tok->b); + CHECK(!c.step_fail.empty()); + } +} + /* ======================================================== the conventional vocabulary */ namespace { diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index ffa42b6c..88ccbc51 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -180,6 +180,78 @@ TEST(a_plain_tensor_is_its_own_encoding_and_reads_back_as_itself) { CHECK_EQ(std::memcmp(raw.data(), (const uint8_t*)ck.find("a.weight")->data + 32, 16), 0); } +/* A single-file SDXL checkpoint (Stability's sgm layout) is read under the names its adapters use: + * the UNet and CLIP ViT-L as they are, OpenCLIP bigG in transformers' names with its fused + * in_proj split into q/k/v rows and its (in, out) text_projection transposed, the VAE decoder in + * diffusers' names with up blocks counted the other way, a v_pred marker as the prediction type, + * and bigG's dimensions as the model's. */ +TEST(a_single_file_sdxl_checkpoint_is_read_in_its_adapters_names) { + const std::string g = "conditioner.embedders.1.model."; + T proj{ g + "text_projection", "F32", { 2, 3 }, {} }; + proj.bytes.resize(6 * 4); + for (int i = 0; i < 6; ++i) rad_store_f32(proj.bytes.data(), RAD_F32, i, (float)i); + const std::string dir = fresh_dir(); + const std::string file = dir + "/sdxl.safetensors"; + write_shard(file, { + bf16("model.diffusion_model.label_emb.0.0.weight", { 2, 4 }, 1.0f), + bf16("conditioner.embedders.0.transformer.text_model.final_layer_norm.weight", { 4 }, 2.0f), + bf16(g + "transformer.resblocks.3.attn.in_proj_weight", { 6, 4 }, 0.0f), + bf16(g + "transformer.resblocks.3.attn.in_proj_bias", { 6 }, 0.0f), + bf16(g + "transformer.resblocks.3.mlp.c_fc.weight", { 8, 4 }, 3.0f), + bf16(g + "transformer.resblocks.3.ln_2.bias", { 4 }, 4.0f), + bf16(g + "ln_final.weight", { 4 }, 5.0f), + bf16(g + "token_embedding.weight", { 16, 4 }, 0.0f), + bf16(g + "transformer.resblocks.0.ln_1.weight", { 4 }, 0.0f), + bf16(g + "transformer.resblocks.0.mlp.c_fc.weight", { 8, 4 }, 0.0f), + bf16(g + "positional_embedding", { 77, 4 }, 6.0f), + proj, + bf16("first_stage_model.decoder.up.0.block.2.nin_shortcut.weight", { 4, 8, 1, 1 }, 7.0f), + bf16("first_stage_model.decoder.up.3.upsample.conv.bias", { 4 }, 8.0f), + bf16("first_stage_model.decoder.mid.attn_1.proj_out.weight", { 4, 4, 1, 1 }, 9.0f), + bf16("first_stage_model.encoder.conv_in.weight", { 4, 3, 3, 3 }, 10.0f), + T{ "v_pred", "F32", { 0 }, {} }, + }); + Checkpoint ck; + REQUIRE_EQ(ck.open(file), RAD_OK); + CHECK_EQ(ck.meta().arch, std::string("sdxl")); + REQUIRE(ck.meta().get("sdxl.prediction") != nullptr); + CHECK_EQ(std::string(ck.meta().get("sdxl.prediction")), std::string("v")); + /* The typed dimensions are bigG's: its width, vocabulary and feed-forward off its tensors, + * its layers counted from 0 while they run on. */ + CHECK_EQ(ck.meta().m.n_embd, (int64_t)4); + CHECK_EQ(ck.meta().m.n_vocab, (int64_t)16); + CHECK_EQ(ck.meta().m.n_ff, (int64_t)8); + CHECK_EQ(ck.meta().m.n_layers, (int64_t)1); + CHECK(ck.find("model.diffusion_model.label_emb.0.0.weight") != nullptr); + CHECK(ck.find("conditioner.embedders.0.transformer.text_model.final_layer_norm.weight") != nullptr); + const std::string t = "conditioner.embedders.1.transformer."; + const std::string l = t + "text_model.encoder.layers.3."; + const SrcTensor* q = ck.find(l + "self_attn.q_proj.weight"); + const SrcTensor* v = ck.find(l + "self_attn.v_proj.weight"); + const SrcTensor* vb = ck.find(l + "self_attn.v_proj.bias"); + REQUIRE(q && v && vb); + CHECK(q->shape == std::vector({ 2, 4 })); + /* v is rows 4..5 of in_proj: elements 16..23, each its index (mod 64) in bf16. */ + CHECK_EQ(rad_load_f32(v->data, RAD_BF16, 0), 16.0f); + CHECK_EQ(rad_load_f32(vb->data, RAD_BF16, 1), 5.0f); + CHECK(ck.find(g + "transformer.resblocks.3.attn.in_proj_weight") == nullptr); + CHECK(ck.find(l + "mlp.fc1.weight") != nullptr); + CHECK(ck.find(l + "layer_norm2.bias") != nullptr); + CHECK(ck.find(t + "text_model.final_layer_norm.weight") != nullptr); + CHECK(ck.find(t + "text_model.embeddings.position_embedding.weight") != nullptr); + const SrcTensor* p = ck.find(t + "text_projection.weight"); + REQUIRE(p != nullptr); + CHECK(p->shape == std::vector({ 3, 2 })); + /* P^T: element (j, i) is P(i, j) = 3 i + j. */ + for (int j = 0; j < 3; ++j) + for (int i = 0; i < 2; ++i) + CHECK_EQ(rad_load_f32(p->data, RAD_F32, j * 2 + i), (float)(3 * i + j)); + CHECK(ck.find("vae.decoder.up_blocks.3.resnets.2.conv_shortcut.weight") != nullptr); + CHECK(ck.find("vae.decoder.up_blocks.0.upsamplers.0.conv.bias") != nullptr); + CHECK(ck.find("vae.decoder.mid_block.attentions.0.to_out.0.weight") != nullptr); + CHECK(ck.find("first_stage_model.encoder.conv_in.weight") != nullptr); +} + /* Block-scaled FP8 is one weight of two planes; each value is its code times the scale of the * block containing it along both axes. */ TEST(block_fp8_is_the_codes_and_their_scale_plane) { @@ -2735,4 +2807,82 @@ TEST(a_companion_folder_is_read_under_its_name) { CHECK_EQ(mget("codec.decoder_config.dim"), std::string("7")); } +namespace { + +/* A RAD_MAP_ROWS or RAD_MAP_COLS map: source k starts at index[k] and spans rows[k]. */ +RadNameMap ranged(const char* declared, int mode, std::vector src, + std::vector index, std::vector rows) { + RadNameMap m = map(declared, mode, std::move(src), std::move(index)); + for (size_t i = 0; i < rows.size(); ++i) m.src_rows[i] = rows[i]; + return m; +} + +} /* namespace */ + +/* A column range of the last dimension, in every leading slice; a range past the end is + * refused. */ +TEST(a_column_range_is_those_columns_of_every_row) { + const std::string dir = write_checkpoint({ bf16("x.weight", { 3, 5 }, 0.0f) }, kConfig); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + Program prog; + prog.name_map.push_back(ranged("xc", RAD_MAP_COLS, { "x.weight" }, { 1 }, { 3 })); + prog.name_map.push_back(ranged("far", RAD_MAP_COLS, { "x.weight" }, { 3 }, { 3 })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "xc", false, &w, &why), RAD_OK); + CHECK(!w.trivial); + REQUIRE_EQ(w.rank, (uint32_t)2); + CHECK_EQ(w.shape[0], (int64_t)3); + CHECK_EQ(w.shape[1], (int64_t)3); + std::vector f(9); + REQUIRE_EQ(ckpt_rows_f32(w, 0, 3, f.data(), &why), RAD_OK); + for (int r = 0; r < 3; ++r) + for (int c = 0; c < 3; ++c) CHECK_EQ(f[(size_t)(r * 3 + c)], (float)(r * 5 + 1 + c)); + CHECK_EQ(ckpt_resolve(ck, prog, "far", false, &w, &why), (int)RAD_E_SHAPE); +} + +/* Row pieces declared over several maps of one name join in declaration order, so a permutation + * of a weight's rows can be stated one row at a time. */ +TEST(row_pieces_over_several_maps_join_in_order) { + const std::string dir = write_checkpoint({ bf16("w", { 4, 3 }, 0.0f) }, kConfig); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + Program prog; + prog.name_map.push_back(ranged("p", RAD_MAP_ROWS, { "w" }, { 2 }, { 1 })); + prog.name_map.push_back(ranged("p", RAD_MAP_ROWS, { "w", "w" }, { 0, 3 }, { 1, 1 })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "p", false, &w, &why), RAD_OK); + CHECK_EQ(w.shape[0], (int64_t)3); + CHECK_EQ(w.shape[1], (int64_t)3); + std::vector f(9); + REQUIRE_EQ(ckpt_rows_f32(w, 0, 3, f.data(), &why), RAD_OK); + const int order[3] = { 2, 0, 3 }; + for (int r = 0; r < 3; ++r) + for (int c = 0; c < 3; ++c) CHECK_EQ(f[(size_t)(r * 3 + c)], (float)(order[r] * 3 + c)); +} + +/* A release split into single files merges them under their own names; a name two files share + * is refused. The metadata and tokenizer come from the directory set before open(). */ +TEST(single_files_merge_by_name_and_read_their_metadata_elsewhere) { + const std::string dir = fresh_dir(); + write_shard(dir + "/dit.safetensors", { bf16("net.a", { 2, 2 }, 1.0f) }); + write_shard(dir + "/te.safetensors", { bf16("model.b", { 2, 2 }, 2.0f) }); + write_shard(dir + "/dup.safetensors", { bf16("net.a", { 2, 2 }, 3.0f) }); + const std::string meta = fresh_dir(); + write_file(meta + "/config.json", "{\"model_type\":\"qwen3\",\"hidden_size\":64}"); + write_file(meta + "/tokenizer.json", "{}"); + Checkpoint ck; + ck.set_meta_dir(meta); + REQUIRE_EQ(ck.open(dir + "/dit.safetensors"), RAD_OK); + REQUIRE_EQ(ck.add_file(dir + "/te.safetensors"), RAD_OK); + CHECK(ck.find("net.a") != nullptr); + CHECK(ck.find("model.b") != nullptr); + CHECK(ck.add_file(dir + "/dup.safetensors") < 0); + const char* mt = ck.meta().get("model_type"); + CHECK_EQ(std::string(mt ? mt : ""), std::string("qwen3")); + CHECK_EQ(ck.tok_dir(), meta); +} + RAD_TEST_MAIN() diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 78af66f2..49883424 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -129,7 +130,8 @@ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) { /* Runtime LoRA: the adapters reach their fields in order, the targets as sorted leaf names, and a * combination that would size slots no adapter uses, or name an adapter that is not served, is - * refused by name. */ + * refused by name. A text model's slot count against its adapters, and its targets, are checked + * at startup, where the engine knows whether the model generates text. */ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) { Config c; CHECK_OK(parse({ "--lora", "b=/ad/b", "--lora", "a=/ad/a", "--max-loras", "3", @@ -144,6 +146,15 @@ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) { Config d; CHECK_OK(parse({}, &d)); CHECK(!d.lora.enabled()); + CHECK_EQ(d.lora.rank(false), 16); + CHECK_EQ(d.lora.rank(true), 64); + Config e; + const std::string dir = radtest::tmp_path("loradir"); + mkdir(dir.c_str(), 0755); + CHECK_OK(parse({ "--lora-dir", dir.c_str() }, &e)); + CHECK(e.lora.enabled()); + CHECK_EQ(e.lora.slots(), 2); + CHECK_EQ(e.lora.rank(true), 64); auto refused = [](std::initializer_list v, const char* why) { int st = RAD_OK; @@ -157,10 +168,9 @@ TEST(the_lora_flags_reach_their_fields_and_refuse_what_serves_no_adapter) { refused({ "--lora", "/ad/a" }, "NAME=PATH"); refused({ "--lora", "a=" }, "NAME=PATH"); refused({ "--lora", "a=/x", "--lora", "a=/y" }, "names the adapter 'a' twice"); - refused({ "--lora", "a=/x", "--lora", "b=/y", "--max-loras", "1" }, "fewer adapters"); refused({ "--max-lora-rank", "32" }, "--max-lora-rank sizes runtime LoRA slots"); refused({ "--lora-target-modules", "q_proj" }, "--lora-target-modules sizes"); - refused({ "--max-loras", "2" }, "names no module an adapter may target"); + refused({ "--lora-dir", "/no/such/dir" }, "is not a directory"); refused({ "--lora", "a=/x", "--lora-target-modules", "self_attn.q_proj" }, "leaf names"); refused({ "--lora", "a=/x", "--lora-target-modules", ".*proj" }, "leaf names"); refused({ "--lora", "a=/x", "--lora-target-modules", " , " }, "names no module"); @@ -454,6 +464,7 @@ const std::map>& legal_values() { { "--kld-corpus", { "/c.jsonl", "--kld-record", "/r" } }, { "--kld-out", { "/o.json", "--kld-ref", "/r" } }, { "--lora", { "a=/adapters/a" } }, + { "--lora-dir", { "/" } }, { "--max-loras", { "2", "--lora-target-modules", "q_proj" } }, { "--max-lora-rank", { "32", "--lora", "a=/adapters/a" } }, { "--lora-target-modules", { "q_proj,v_proj", "--max-loras", "1" } }, diff --git a/tests/gen_lora_test.cpp b/tests/gen_lora_test.cpp new file mode 100644 index 00000000..5fb7eece --- /dev/null +++ b/tests/gen_lora_test.cpp @@ -0,0 +1,585 @@ +/* gen_lora_test.cpp -- runtime LoRA for generators: adapter files in every spelling and kind + * (core/lora/adapter.h), their keys mapped through a generator's declared names, stacked at + * strengths, packed per rank; and the request fields that name them (core/server/loras.h). + * + * Host only, no kernel plugin: the Program is made by the core Builder over an empty Registry, as + * lora_test.cpp makes its own, with the generator's names declared through the builder (the calls + * rad_lora_root / rad_lora_alias make). The reference is the test's own dense delta of every + * checkpoint module, placed by model semantics -- which rows of which tensor a rank's declared + * weight holds -- never by anything adapter.cpp or lora.cpp computes. + */ +#include "rad_test.h" + +#include "build/rad_build.h" +#include "lora/adapter.h" +#include "lora/lora.h" +#include "plugin/registry.h" +#include "rad_plugin.h" +#include "server/loras.h" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rad; +namespace AR = rad::arch; +using ojson = nlohmann::ordered_json; + +namespace { + +Registry& empty_registry() { + static Registry r; + return r; +} + +float val(uint32_t seed, uint64_t i) { + uint64_t x = (uint64_t)seed * 0x9E3779B97F4A7C15ull + i * 0xBF58476D1CE4E5B9ull + 1; + x ^= x >> 31; x *= 0x94D049BB133111EBull; x ^= x >> 29; + return (float)((double)(x >> 11) / (double)(1ull << 53) - 0.5) * 0.5f; +} + +/* ------------------------------------------------------------------ safetensors */ +struct TW { + std::string name, dtype; + std::vector shape; + std::vector v; /* written as dtype */ +}; +void write_st(const std::string& path, const std::vector& ts) { + ojson h = ojson::object(); + std::vector> bytes; + uint64_t off = 0; + for (const TW& t : ts) { + std::vector b; + if (t.dtype == "I64") { const int64_t v = 4; b.resize(8); std::memcpy(b.data(), &v, 8); } + for (float f : t.v) { + if (t.dtype == "F32") { uint8_t x[4]; std::memcpy(x, &f, 4); b.insert(b.end(), x, x + 4); } + else { + const uint16_t u = t.dtype == "F16" ? rad_f32_to_f16(f) : rad_f32_to_bf16(f); + uint8_t x[2]; std::memcpy(x, &u, 2); b.insert(b.end(), x, x + 2); + } + } + h[t.name] = { { "dtype", t.dtype }, { "shape", t.shape }, + { "data_offsets", { off, off + b.size() } } }; + off += b.size(); + bytes.push_back(std::move(b)); + } + h["__metadata__"] = { { "format", "pt" } }; + std::string s = h.dump(); + while (s.size() % 8) s += ' '; + std::ofstream f(path, std::ios::binary); + const uint64_t n = s.size(); + f.write((const char*)&n, 8); + f.write(s.data(), (std::streamsize)s.size()); + for (const auto& b : bytes) f.write((const char*)b.data(), (std::streamsize)b.size()); +} +/* A tensor of seeded values, and the values as the file holds them. */ +TW tensor(const std::string& name, const std::string& dt, std::vector shape, uint32_t seed, + float mul = 1.0f) { + TW t{ name, dt, shape, {} }; + int64_t n = 1; + for (int64_t d : shape) n *= d; + for (int64_t i = 0; i < n; ++i) { + float f = val(seed, (uint64_t)i) * mul; + if (dt == "F16") f = rad_f16_to_f32(rad_f32_to_f16(f)); + else if (dt == "BF16") f = rad_bf16_to_f32(rad_f32_to_bf16(f)); + t.v.push_back(f); + } + return t; +} +TW scalar(const std::string& name, float f) { return TW{ name, "F32", {}, { f } }; } + +/* ------------------------------------------------------------------ dense helpers */ +struct Dense { + int64_t N = 0, K = 0; + std::vector d; + void add(const Dense& o, double w) { + if (d.empty()) { N = o.N; K = o.K; d.assign(o.d.size(), 0.0); } + for (size_t i = 0; i < d.size(); ++i) d[i] += w * o.d[i]; + } +}; +Dense mul(const std::vector& B, const std::vector& A, int64_t N, int64_t r, int64_t K, + double s) { + Dense o{ N, K, std::vector((size_t)(N * K), 0.0) }; + for (int64_t n = 0; n < N; ++n) + for (int64_t j = 0; j < r; ++j) + for (int64_t k = 0; k < K; ++k) + o.d[(size_t)(n * K + k)] += s * (double)B[(size_t)(n * r + j)] * A[(size_t)(j * K + k)]; + return o; +} + +/* ------------------------------------------------------------------ the generator */ +/* A two-block DiT under "transformer.", as an image generator's plugin declares one: a fused + * [q|k|v] (row parts, ROW), the output (COL), a SwiGLU re-laid from one checkpoint tensor whose + * value half comes first (RAD_MAP_ROWS: the gate half moved first), the down projection (COL); a + * text encoder's linear outside the root; and a DiT weight a fused GEMM reads. */ +const int64_t kD = 128, kHD = 32, kNH = 8, kF = 512, kQ = kNH * kHD; + +RadModelMeta gen_meta() { + RadModelMeta m{}; + m.arch_id = "gentest"; m.name = "lora-test-gen"; m.quant = "fp8_e4m3"; + m.n_layers = 2; m.n_embd = kD; m.n_head = kNH; m.n_head_kv = kNH; m.head_dim = kHD; + m.n_ff = kF; m.n_vocab = 512; m.n_ctx_train = 1024; + m.rms_eps = 1e-5f; m.rope_theta = 1e4f; m.rope_scale = 1.0f; + return m; +} + +OpInfo gemm_op(const char* name, int64_t N, int64_t K, const char* dtype, int64_t hi, + std::vector w, std::vector opd) { + OpInfo o; + o.op = name; + o.base.set_i("N", N); + o.base.set_i("K", K); + o.base.set_i("group", AR::RAD_FP8_BLOCK); + o.base.set_s("dtype", dtype); + o.ranged_key = "M"; + o.range_lo = 1; + o.range_hi = hi; + o.weights = std::move(w); + o.weight_opd = std::move(opd); + return o; +} +void push_op(Builder& b, OpInfo o) { + o.index = (int32_t)b.program().ops.size(); + b.program().ops.push_back(std::move(o)); +} + +int linear(Builder& b, AR::Names& nm, const AR::Geom& g, const char* base, int64_t N, int64_t K, + int shard, int layer, std::initializer_list src, + std::initializer_list parts = {}, bool mapped = false, + const char* op = "gemm_nt_q") { + AR::LinearFP8 lin{}; + AR::ActFP8 act{}; + lin.mapped = mapped; + const int st = lin.declare((RadBuilder*)&b, nm, g, base, N, K, shard, AR::grp_layer(layer), src, + act, 0, 0, parts); + if (st < 0 || !lin.w || !lin.ws) return st < 0 ? st : RAD_E_INVAL; + push_op(b, gemm_op(op, N, K, "fp8a8", g.max_tok, { lin.w, lin.ws }, { 2, 3 })); + return RAD_OK; +} + +RadBuildCtx ctx_for(int rank, int world) { + RadBuildCtx c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 256; + c.max_seqs = 8; + c.max_ctx = 1024; + c.scope = ""; + return c; +} + +/* Where a declared weight's rows on one rank come from: (checkpoint module, its full rows) per + * row of y, and the full K columns of x. */ +struct Truth { + std::vector> rows; + std::vector cols; +}; + +int build_gen(int rank, int world, Program* out, std::map* truth) { + const RadModelMeta meta = gen_meta(); + const RadBuildCtx ctx = ctx_for(rank, world); + AR::Geom g{}; + RAD_ARCH_TRY(AR::geom_from(g, &meta, &ctx, "bf16", RAD_BF16)); + Builder b(empty_registry(), meta, ctx); + b.program().generator.layout = RAD_GEN_LAYOUT_JOINT_STEP; + RAD_ARCH_TRY(AR::lora_names((RadBuilder*)&b, "transformer.", AR::kLoraDiffusionSpellings, + { { "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_q", 0, kQ, 0 }, + { "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_k", kQ, 2 * kQ, 0 }, + { "blocks.#.attn.qkv", "transformer_blocks.#.attn.to_v", 2 * kQ, 3 * kQ, 0 }, + { "blocks.#.attn.out_proj", "transformer_blocks.#.attn.to_out.0" }, + { "blocks.#.mlp.fc1", "transformer_blocks.#.ff.net.0.proj", 0, kF, kF }, + { "blocks.#.mlp.fc1", "transformer_blocks.#.ff.net.0.proj", kF, 2 * kF, 0 }, + { "blocks.#.mlp.fc2", "transformer_blocks.#.ff.net.2" } })); + AR::Names nm(""); + const int64_t qr = g.q_dim(), fr = g.n_ff; + for (int l = 0; l < 2; ++l) { + const std::string P = "transformer.transformer_blocks." + std::to_string(l) + "."; + auto ck = [&](const char* leaf) { return nm.ckpt("%s%s.weight", P.c_str(), leaf); }; + RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.qkv", l), 3 * qr, kD, RAD_SHARD_ROW, l, + { ck("attn.to_q"), ck("attn.to_k"), ck("attn.to_v") }, { qr, qr, qr })); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.o", l), kD, qr, RAD_SHARD_COL, l, + { ck("attn.to_out.0") })); + const char* fsrc = ck("ff.net.0.proj"); + RAD_ARCH_TRY(AR::map_rows((RadBuilder*)&b, nm.f("dit.%d.gate_up.weight", l), + { { fsrc, (int)kF, kF }, { fsrc, 0, kF } })); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.gate_up", l), 2 * fr, kD, RAD_SHARD_ROW, l, + { fsrc }, { fr, fr }, true)); + RAD_ARCH_TRY(linear(b, nm, g, nm.f("dit.%d.down", l), kD, fr, RAD_SHARD_COL, l, + { ck("ff.net.2") })); + + Truth q, o, gu, dn; + const char* part[3] = { "attn.to_q", "attn.to_k", "attn.to_v" }; + for (const char* p : part) + for (int64_t i = rank * qr; i < (rank + 1) * qr; ++i) q.rows.push_back({ P + p, i }); + for (int64_t k = 0; k < kD; ++k) q.cols.push_back(k); + for (int64_t i = 0; i < kD; ++i) o.rows.push_back({ P + "attn.to_out.0", i }); + for (int64_t k = rank * qr; k < (rank + 1) * qr; ++k) o.cols.push_back(k); + for (int64_t i = rank * fr; i < (rank + 1) * fr; ++i) gu.rows.push_back({ P + "ff.net.0.proj", kF + i }); + for (int64_t i = rank * fr; i < (rank + 1) * fr; ++i) gu.rows.push_back({ P + "ff.net.0.proj", i }); + for (int64_t k = 0; k < kD; ++k) gu.cols.push_back(k); + for (int64_t i = 0; i < kD; ++i) dn.rows.push_back({ P + "ff.net.2", i }); + for (int64_t k = rank * fr; k < (rank + 1) * fr; ++k) dn.cols.push_back(k); + const std::string L = std::to_string(l); + (*truth)["dit." + L + ".qkv.weight"] = q; + (*truth)["dit." + L + ".o.weight"] = o; + (*truth)["dit." + L + ".gate_up.weight"] = gu; + (*truth)["dit." + L + ".down.weight"] = dn; + } + /* Outside the root: a text encoder's projection. */ + RAD_ARCH_TRY(linear(b, nm, g, "te.0.q", kD, kD, RAD_SHARD_NONE, 0, + { "text_encoder.layers.0.q_proj.weight" })); + /* Under the root, read by a fused GEMM: it stays the base. */ + RAD_ARCH_TRY(linear(b, nm, g, "dit.fused", kD, kD, RAD_SHARD_NONE, 0, + { "transformer.proj_out.weight" }, {}, false, "gemm_nt_q_swiglu")); + *out = std::move(b.program()); + return RAD_OK; +} + +std::string new_dir(const std::string& name) { + const std::string d = radtest::tmp_path(name); + mkdir(d.c_str(), 0755); + return d; +} + +/* ------------------------------------------------------------------ the adapter files */ +/* Two files, every spelling and kind, and the dense delta of every checkpoint module they reach + * (strength 1). File 1: kohya LoRA on block 0's fused qkv; ComfyUI LoRA on block 0's fc1 (gate + * half first); PEFT LoRA on block 1's down projection under the checkpoint's own name; LoHa on + * block 1's out_proj; a full delta on block 0's fc2; a module of no model; a bias delta. File 2: + * LoKr on block 1's qkv; a bare-keyed LoRA on block 0's qkv, stacking with file 1's. */ +struct Files { + std::string f1, f2; + std::map d1, d2; /* by checkpoint module, full rows */ +}; + +void place(std::map* m, const std::string& mod, int64_t N_full, const Dense& d, + int64_t from_lo, int64_t n, int64_t to_lo) { + Dense& t = (*m)[mod]; + if (t.d.empty()) { t.N = N_full; t.K = d.K; t.d.assign((size_t)(N_full * d.K), 0.0); } + for (int64_t r = 0; r < n; ++r) + for (int64_t k = 0; k < d.K; ++k) + t.d[(size_t)((to_lo + r) * d.K + k)] += d.d[(size_t)((from_lo + r) * d.K + k)]; +} + +Files make_files() { + Files f; + const std::string dir = new_dir("genlora"); + const std::string B0 = "transformer.transformer_blocks.0.", B1 = "transformer.transformer_blocks.1."; + std::vector ts; + { /* kohya LoRA, rank 8, alpha 4: qkv of block 0 */ + TW dn = tensor("lora_unet_blocks_0_attn_qkv.lora_down.weight", "F16", { 8, kD }, 1); + TW up = tensor("lora_unet_blocks_0_attn_qkv.lora_up.weight", "BF16", { 3 * kQ, 8 }, 2); + const Dense d = mul(up.v, dn.v, 3 * kQ, 8, kD, 4.0 / 8.0); + place(&f.d1, B0 + "attn.to_q", kQ, d, 0, kQ, 0); + place(&f.d1, B0 + "attn.to_k", kQ, d, kQ, kQ, 0); + place(&f.d1, B0 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0); + ts.push_back(dn); ts.push_back(up); + TW al{ "lora_unet_blocks_0_attn_qkv.alpha", "I64", {}, {} }; /* as kohya writes some */ + ts.push_back(al); + } + { /* ComfyUI LoRA, rank 4, no alpha: fc1 of block 0, [gate; up] */ + TW a = tensor("diffusion_model.blocks.0.mlp.fc1.lora_A.weight", "BF16", { 4, kD }, 3); + TW b = tensor("diffusion_model.blocks.0.mlp.fc1.lora_B.weight", "F32", { 2 * kF, 4 }, 4); + const Dense d = mul(b.v, a.v, 2 * kF, 4, kD, 1.0); + place(&f.d1, B0 + "ff.net.0.proj", 2 * kF, d, 0, kF, kF); + place(&f.d1, B0 + "ff.net.0.proj", 2 * kF, d, kF, kF, 0); + ts.push_back(a); ts.push_back(b); + } + { /* PEFT LoRA under the checkpoint's own name, rank 6, alpha 12 */ + TW a = tensor(B1 + "ff.net.2.lora_A.default.weight", "F32", { 6, kF }, 5); + TW b = tensor(B1 + "ff.net.2.lora_B.default.weight", "F32", { kD, 6 }, 6); + place(&f.d1, B1 + "ff.net.2", kD, mul(b.v, a.v, kD, 6, kF, 12.0 / 6.0), 0, kD, 0); + ts.push_back(a); ts.push_back(b); ts.push_back(scalar(B1 + "ff.net.2.alpha", 12.0f)); + } + { /* LoHa, ranks 4 and 3, alpha 2: out_proj of block 1 */ + const std::string k = "diffusion_model.blocks.1.attn.out_proj."; + TW w1a = tensor(k + "hada_w1_a", "F32", { kD, 4 }, 7), w1b = tensor(k + "hada_w1_b", "F32", { 4, kQ }, 8); + TW w2a = tensor(k + "hada_w2_a", "F32", { kD, 3 }, 9), w2b = tensor(k + "hada_w2_b", "F32", { 3, kQ }, 10); + const Dense p1 = mul(w1a.v, w1b.v, kD, 4, kQ, 1.0), p2 = mul(w2a.v, w2b.v, kD, 3, kQ, 1.0); + Dense d{ kD, kQ, std::vector(p1.d.size()) }; + for (size_t i = 0; i < d.d.size(); ++i) d.d[i] = 0.5 * p1.d[i] * p2.d[i]; + place(&f.d1, B1 + "attn.to_out.0", kD, d, 0, kD, 0); + ts.insert(ts.end(), { w1a, w1b, w2a, w2b, scalar(k + "alpha", 2.0f) }); + } + { /* a full delta: fc2 of block 0 */ + TW df = tensor("diffusion_model.blocks.0.mlp.fc2.diff", "F32", { kD, kF }, 11, 0.1f); + Dense d{ kD, kF, std::vector(df.v.begin(), df.v.end()) }; + place(&f.d1, B0 + "ff.net.2", kD, d, 0, kD, 0); + ts.push_back(df); + } + ts.push_back(tensor("diffusion_model.nowhere.lora_A.weight", "F32", { 2, 8 }, 12)); + ts.push_back(tensor("diffusion_model.nowhere.lora_B.weight", "F32", { 8, 2 }, 13)); + ts.push_back(tensor("diffusion_model.blocks.0.mlp.fc2.diff_b", "F32", { kD }, 14)); + f.f1 = dir + "/one.safetensors"; + write_st(f.f1, ts); + + ts.clear(); + { /* LoKr: w1 [3, 2] full, w2 = w2_a [kQ, 4] @ w2_b [4, kD / 2], alpha 8 (scale 8 / 4) */ + const std::string k = "lora_unet_blocks_1_attn_qkv."; + TW w1 = tensor(k + "lokr_w1", "F32", { 3, 2 }, 15); + TW w2a = tensor(k + "lokr_w2_a", "F32", { kQ, 4 }, 16), w2b = tensor(k + "lokr_w2_b", "F32", { 4, kD / 2 }, 17); + const Dense w2 = mul(w2a.v, w2b.v, kQ, 4, kD / 2, 1.0); + Dense d{ 3 * kQ, kD, std::vector((size_t)(3 * kQ * kD)) }; + for (int64_t i1 = 0; i1 < 3; ++i1) + for (int64_t j1 = 0; j1 < 2; ++j1) + for (int64_t i2 = 0; i2 < kQ; ++i2) + for (int64_t j2 = 0; j2 < kD / 2; ++j2) + d.d[(size_t)((i1 * kQ + i2) * kD + j1 * (kD / 2) + j2)] = + 2.0 * w1.v[(size_t)(i1 * 2 + j1)] * w2.d[(size_t)(i2 * (kD / 2) + j2)]; + place(&f.d2, B1 + "attn.to_q", kQ, d, 0, kQ, 0); + place(&f.d2, B1 + "attn.to_k", kQ, d, kQ, kQ, 0); + place(&f.d2, B1 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0); + ts.insert(ts.end(), { w1, w2a, w2b, scalar(k + "alpha", 8.0f) }); + } + { /* bare keys, rank 8: qkv of block 0, stacked on file 1's */ + TW a = tensor("blocks.0.attn.qkv.lora_A.weight", "BF16", { 8, kD }, 18); + TW b = tensor("blocks.0.attn.qkv.lora_B.weight", "BF16", { 3 * kQ, 8 }, 19); + const Dense d = mul(b.v, a.v, 3 * kQ, 8, kD, 1.0); + place(&f.d2, B0 + "attn.to_q", kQ, d, 0, kQ, 0); + place(&f.d2, B0 + "attn.to_k", kQ, d, kQ, kQ, 0); + place(&f.d2, B0 + "attn.to_v", kQ, d, 2 * kQ, kQ, 0); + ts.push_back(a); ts.push_back(b); + } + f.f2 = dir + "/two.safetensors"; + write_st(f.f2, ts); + return f; +} + +/* A packed slot's product, [N_r, K_r]. */ +std::vector slot_delta(const lora::Site& s, const lora::PackedSite& p) { + std::vector d((size_t)(s.N_r * s.K_r), 0.0); + for (int64_t y = 0; y < s.N_r; ++y) { + for (int64_t j = 0; j < s.R; ++j) { + const double b = rad_bf16_to_f32(p.b[(size_t)(y * s.R + j)]); + if (b == 0.0) continue; + for (int64_t k = 0; k < s.K_r; ++k) + d[(size_t)(y * s.K_r + k)] += b * rad_bf16_to_f32(p.a[(size_t)(j * s.K_r + k)]); + } + for (int64_t k = 0; k < s.K_r; ++k) d[(size_t)(y * s.K_r + k)] *= p.scale[(size_t)y]; + } + return d; +} + +} /* namespace */ + +/* ================================================================== the files */ +TEST(adapter_files_group_by_module_and_refuse_what_they_cannot_reproduce) { + const Files f = make_files(); + lora::AdapterFile a; + std::string err; + REQUIRE_EQ(a.open(f.f1, &err), RAD_OK); + CHECK_EQ(a.modules().size(), (size_t)6); + CHECK_EQ(a.skipped().size(), (size_t)1); + CHECK_EQ(std::string(a.kind_name()), std::string("LoRA")); + const std::string dir = new_dir("genlora_bad"); + write_st(dir + "/dora.safetensors", { tensor("m.lora_A.weight", "F32", { 2, 4 }, 1), + tensor("m.lora_B.weight", "F32", { 4, 2 }, 2), + tensor("m.dora_scale", "F32", { 4, 1 }, 3) }); + CHECK_EQ(a.open(dir + "/dora.safetensors", &err), (int)RAD_E_UNSUPPORTED); + CHECK(err.find("DoRA") != std::string::npos); + write_st(dir + "/half.safetensors", { tensor("m.lora_A.weight", "F32", { 2, 4 }, 1) }); + CHECK_EQ(a.open(dir + "/half.safetensors", &err), (int)RAD_E_FORMAT); +} + +/* A delta given as an operator truncates to its best rank-r form: exact at or above its rank, and + * otherwise keeping what the sketch says it keeps. */ +TEST(truncation_is_exact_within_the_rank_and_honest_past_it) { + const int64_t N = 96, K = 80; + std::vector D((size_t)(N * K)); + /* rank 12 */ + std::vector U((size_t)(N * 12)), V((size_t)(12 * K)); + for (size_t i = 0; i < U.size(); ++i) U[i] = val(21, i); + for (size_t i = 0; i < V.size(); ++i) V[i] = val(22, i); + const Dense ref = mul(U, V, N, 12, K, 1.0); + for (size_t i = 0; i < D.size(); ++i) D[i] = (float)ref.d[i]; + lora::Delta d; + d.N = N; d.K = K; d.rank_bound = std::min(N, K); + d.apply = [&](const float* X, int64_t l, float* Y) { + for (int64_t n = 0; n < N; ++n) + for (int64_t j = 0; j < l; ++j) { + double a = 0; + for (int64_t k = 0; k < K; ++k) a += (double)D[(size_t)(n * K + k)] * X[k * l + j]; + Y[n * l + j] = (float)a; + } + }; + d.apply_t = [&](const float* Y, int64_t l, float* X) { + for (int64_t k = 0; k < K; ++k) + for (int64_t j = 0; j < l; ++j) { + double a = 0; + for (int64_t n = 0; n < N; ++n) a += (double)D[(size_t)(n * K + k)] * Y[n * l + j]; + X[k * l + j] = (float)a; + } + }; + std::vector B, A; + double kept = 0; + lora::truncate(d, 16, &B, &A, &kept); + const Dense got = mul(B, A, N, 16, K, 1.0); + double e = 0, t = 0; + for (size_t i = 0; i < got.d.size(); ++i) { e += std::pow(got.d[i] - ref.d[i], 2); t += ref.d[i] * ref.d[i]; } + CHECK(e / t < 1e-8); + CHECK_NEAR(kept, 1.0, 1e-6); + /* rank 6 of a rank-12 matrix: what is lost is what the report says is lost */ + lora::truncate(d, 6, &B, &A, &kept); + const Dense g6 = mul(B, A, N, 6, K, 1.0); + e = 0; + for (size_t i = 0; i < g6.d.size(); ++i) e += std::pow(g6.d[i] - ref.d[i], 2); + CHECK(kept < 0.99 && kept > 0.2); + CHECK_NEAR(1.0 - e / t, kept, 0.02); +} + +/* ================================================================== the names */ +TEST(keys_resolve_through_spellings_aliases_and_kohya) { + Program P; + std::map truth; + REQUIRE_EQ(build_gen(0, 1, &P, &truth), RAD_OK); + std::vector sites; + std::string err; + REQUIRE_EQ(lora::build_sites(P, { "*" }, 16, &sites, &err), RAD_OK); + /* 2 blocks x 4 weights; the text encoder's and the fused GEMM's are not sites */ + CHECK_EQ(sites.size(), (size_t)8); + for (const lora::Site& s : sites) CHECK(s.weight.rfind("dit.", 0) == 0 && s.weight != "dit.fused.weight"); + const lora::KeyMap km(P, sites); + std::string why; + auto one = [&](const std::string& k) { return km.resolve(k, &why); }; + std::vector t = one("lora_unet_blocks_1_attn_qkv"); + REQUIRE_EQ(t.size(), (size_t)3); + CHECK_EQ(t[1].module, std::string("transformer.transformer_blocks.1.attn.to_k")); + CHECK_EQ(t[1].from_lo, kQ); + CHECK_EQ(t[1].from_hi, 2 * kQ); + t = one("diffusion_model.blocks.0.mlp.fc2"); + REQUIRE_EQ(t.size(), (size_t)1); + CHECK_EQ(t[0].module, std::string("transformer.transformer_blocks.0.ff.net.2")); + t = one("transformer.transformer_blocks.0.attn.to_out.0"); + REQUIRE_EQ(t.size(), (size_t)1); + t = one("lora_unet_transformer_blocks_0_attn_to_out_0"); + REQUIRE_EQ(t.size(), (size_t)1); + CHECK_EQ(t[0].module, std::string("transformer.transformer_blocks.0.attn.to_out.0")); + t = one("blocks.1.mlp.fc1"); + CHECK_EQ(t.size(), (size_t)2); + CHECK(one("diffusion_model.proj_out").empty()); + CHECK(why.find("no adapter path") != std::string::npos); + CHECK(one("text_encoder.layers.0.q_proj").empty()); + CHECK(one("diffusion_model.blocks.7.attn.qkv").empty()); +} + +/* ================================================================== stacked, packed */ +/* Packed compact, as the engine packs a generator's slot: every pool's product is the dense delta, + * and its ranks are taken from 0. */ +TEST(stacked_adapters_of_every_kind_pack_to_their_dense_delta_on_every_rank) { + const Files f = make_files(); + auto a1 = std::make_shared(), a2 = std::make_shared(); + std::string err; + REQUIRE_EQ(a1->open(f.f1, &err), RAD_OK); + REQUIRE_EQ(a2->open(f.f2, &err), RAD_OK); + const double w1 = 0.8, w2 = -0.5; + std::map want; + for (const auto& [k, d] : f.d1) want[k].add(d, w1); + for (const auto& [k, d] : f.d2) want[k].add(d, w2); + const int R = 24; + for (int world : { 1, 2 }) { + for (int rank = 0; rank < world; ++rank) { + Program P; + std::map truth; + REQUIRE_EQ(build_gen(rank, world, &P, &truth), RAD_OK); + std::vector sites; + std::vector pools; + REQUIRE_EQ(lora::build_sites(P, { "*" }, R, &sites, &err, &pools), RAD_OK); + const lora::KeyMap km(P, sites); + std::map comp; + lora::ComposeReport rep; + const int cs = lora::compose(km, { { "one", a1, w1 }, { "two", a2, w2 } }, R, &comp, &rep, &err); + if (cs != RAD_OK) fprintf(stderr, " world %d rank %d: %s\n", world, rank, err.c_str()); + REQUIRE_EQ(cs, RAD_OK); + CHECK_EQ(rep.unplaced.size(), (size_t)1); + CHECK_EQ(rep.skipped.size(), (size_t)1); + /* block 0's fc2 (a full delta, rank 128) is the one module past rank 24 */ + CHECK_EQ(rep.modules - rep.exact, (int64_t)1); + CHECK_EQ(rep.worst_module, std::string("transformer.transformer_blocks.0.ff.net.2")); + const std::map mods = lora::as_modules(comp, km); + lora::AdapterInfo info; + std::vector packed; + const int ps = lora::pack_modules(sites, R, mods, &info, &packed, &err, /*compact=*/true); + if (ps != RAD_OK) fprintf(stderr, " world %d rank %d: %s\n", world, rank, err.c_str()); + REQUIRE_EQ(ps, RAD_OK); + REQUIRE_EQ(packed.size(), pools.size()); + for (size_t p = 0; p < pools.size(); ++p) { + const lora::Site* sp = nullptr; + for (const lora::Site& x : sites) if (x.pool == (int32_t)p && !sp) sp = &x; + REQUIRE(sp != nullptr); + const lora::Site& s = *sp; + const Truth& t = truth.at(s.weight); + /* compact: the ranks taken from 0, within the pool's R */ + const lora::PackedSite& pk = packed[(size_t)s.pool]; + CHECK(pk.empty || (pk.r_used > 0 && pk.r_used <= s.R)); + for (int64_t y = 0; y < s.N_r && !pk.empty; ++y) + for (int64_t j = pk.r_used; j < s.R; ++j) + CHECK_EQ(pk.b[(size_t)(y * s.R + j)], (uint16_t)0); + REQUIRE_EQ((int64_t)t.rows.size(), s.N_r); + REQUIRE_EQ((int64_t)t.cols.size(), s.K_r); + const std::vector got = slot_delta(s, packed[(size_t)s.pool]); + double e = 0, tot = 0, mx = 0; + bool truncated = false; + for (int64_t y = 0; y < s.N_r; ++y) { + const auto& [mod, row] = t.rows[(size_t)y]; + truncated = truncated || mod == "transformer.transformer_blocks.0.ff.net.2"; + auto it = want.find(mod); + for (int64_t k = 0; k < s.K_r; ++k) { + const double ref = it == want.end() ? 0.0 + : it->second.d[(size_t)(row * it->second.K + t.cols[(size_t)k])]; + const double g = got[(size_t)(y * s.K_r + k)]; + e += (g - ref) * (g - ref); + tot += ref * ref; + mx = std::max(mx, std::fabs(g - ref) / (std::fabs(ref) + 1e-3)); + } + } + const double rel = tot > 0 ? std::sqrt(e / tot) : std::sqrt(e); + if (rel > (truncated ? 0.9 : 0.01)) + fprintf(stderr, " world %d rank %d %s: relative error %.4g\n", world, rank, + s.weight.c_str(), rel); + /* bf16 factors hold a delta to ~0.5%; the truncated one to what its rank keeps */ + CHECK(rel <= (truncated ? 0.9 : 0.01)); + if (truncated && world == 1) + CHECK_NEAR(1.0 - rel * rel, rep.worst_kept, 0.03); + } + } + } +} + +/* ================================================================== the request fields */ +TEST(requests_name_adapters_in_a_field_or_in_prompt_tags) { + std::vector> out; + std::string field, why; + std::string prompt = "a cat, , sitting "; + nlohmann::json body = { { "loras", { "style", "ink:0.5", { { "name", "x:y" }, { "weight", 2 } } } } }; + REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK); + REQUIRE_EQ(out.size(), (size_t)5); + CHECK_EQ(out[0].first, std::string("style")); + CHECK_EQ(out[0].second, 1.0); + CHECK_EQ(out[1].first, std::string("ink")); + CHECK_EQ(out[1].second, 0.5); + CHECK_EQ(out[2].first, std::string("x:y")); + CHECK_EQ(out[2].second, 2.0); + CHECK_EQ(out[3].first, std::string("pixel art")); + CHECK_NEAR(out[3].second, 0.7, 1e-12); + CHECK_EQ(out[4].first, std::string("detail")); + CHECK_EQ(prompt, std::string("a cat, sitting")); + body = { { "lora", { { "a", 0.25 }, { "b", 1 } } } }; + prompt = "p"; + REQUIRE_EQ(server::parse_loras(body, &prompt, &out, &field, &why), RAD_OK); + CHECK_EQ(out.size(), (size_t)2); + body = { { "loras", { 3 } } }; + CHECK_EQ(server::parse_loras(body, &prompt, &out, &field, &why), (int)RAD_E_INVAL); + CHECK_EQ(field, std::string("loras")); +} + +RAD_TEST_MAIN() diff --git a/tests/gen_test.cpp b/tests/gen_test.cpp index 8a2ea500..c31d5549 100644 --- a/tests/gen_test.cpp +++ b/tests/gen_test.cpp @@ -88,6 +88,29 @@ TEST(the_schedule_is_diffusers_flow_match_euler) { CHECK_EQ(gen::schedule(d, {}, 0, 64).size(), (size_t)d.default_steps + 1); } +/* A schedule off a table of timesteps is ComfyUI's `simple` scheduler over its discrete flow + * sampling (1000 timesteps, shift 3, multiplier 1): the sigmas below are what ComfyUI hands its + * sampler, as f32. */ +TEST(a_sigma_grid_is_comfyui_simple_schedule) { + RadGeneratorDecl d = decl_base(); + d.dyn_shift = 0; d.shift_terminal = 0; d.shift = 3.0; + d.sigma_grid = 1000; + const double want30[] = { 1, 0.988752544, 0.976987481, 0.964285672, 0.951353252, 0.937781036, + 0.923076987, 0.908050597, 0.892220497, 0.87499994, 0.857326388, + 0.838624299, 0.818181813, 0.797094703, 0.774661541, 0.75, + 0.724405408, 0.697002113, 0.666666687, 0.634948134, 0.600719392, + 0.5625, 0.522164285, 0.478201658, 0.428571463, 0.375562221, + 0.317034721, 0.25, 0.177248672, 0.095505625, 0 }; + const std::vector s = gen::schedule(d, {}, 30, 4096); + REQUIRE_EQ(s.size(), (size_t)31); + for (size_t i = 0; i < s.size(); ++i) CHECK_NEAR(s[i], want30[i], 1e-8); + const double want7[] = { 1, 0.94771713, 0.882716119, 0.800373137, 0.69268024, 0.54580152, + 0.333592534, 0 }; + const std::vector s7 = gen::schedule(d, {}, 7, 1024); + REQUIRE_EQ(s7.size(), (size_t)8); + for (size_t i = 0; i < s7.size(); ++i) CHECK_NEAR(s7[i], want7[i], 1e-8); +} + /* A fixed schedule is taken as declared (with shift 1), then closed with 0. */ TEST(a_fixed_schedule_is_used_as_declared) { RadGeneratorDecl d = decl_base(); @@ -96,6 +119,146 @@ TEST(a_fixed_schedule_is_used_as_declared) { CHECK_EQ(s[0], 0.9f); CHECK_EQ(s[1], 0.5f); CHECK_EQ(s[2], 0.125f); CHECK_EQ(s[3], 0.0f); } +/* ================================================================== a discrete-time schedule */ +/* Stable Diffusion XL's: 1000 timesteps, scaled-linear betas 0.00085..0.012. */ +RadGeneratorDecl decl_discrete() { + RadGeneratorDecl d = decl_base(); + d.train_steps = 1000; + d.beta_schedule = RAD_GEN_BETAS_SCALED_LINEAR; + d.beta_start = 0.00085; + d.beta_end = 0.012; + d.samplers = (1u << RAD_GEN_SAMPLER_COUNT) - 1; + d.default_steps = 5; + return d; +} + +/* Each scheduler places five sigmas as ComfyUI's ModelSamplingDiscrete does (reference values + * from its schedulers over the same table), and each sigma is conditioned at the timestep + * ComfyUI picks for it. The table's ends are SDXL's sigma_min and sigma_max. */ +TEST(a_discrete_schedule_is_comfyuis) { + const RadGeneratorDecl d = decl_discrete(); + gen::DiscreteTable t; + std::string why; + REQUIRE_EQ(gen::discrete_table(d, &t, &why), (int)RAD_OK); + CHECK_NEAR(t.sigma_min(), 0.0291671585, 1e-8); + CHECK_NEAR(t.sigma_max(), 14.6146412, 2e-5); + struct Want { int32_t sched; double s[5]; int32_t ts[5]; }; + const Want want[] = { + { RAD_GEN_SCHED_NORMAL, { 14.6146402, 4.08608103, 1.61558032, 0.695149541, 0.0291671604 }, + { 999, 749, 500, 250, 0 } }, + { RAD_GEN_SCHED_KARRAS, { 14.6146431, 4.79653454, 1.27410078, 0.247949973, 0.0291671772 }, + { 999, 786, 427, 59, 0 } }, + { RAD_GEN_SCHED_EXPONENTIAL, + { 14.6146402, 3.08897638, 0.652891755, 0.137996376, 0.0291671604 }, + { 999, 681, 233, 20, 0 } }, + { RAD_GEN_SCHED_SGM_UNIFORM, + { 14.6146402, 5.09240818, 2.27973056, 1.16286457, 0.571188867 }, + { 999, 799, 599, 400, 200 } }, + { RAD_GEN_SCHED_SIMPLE, { 14.6146412, 5.08776331, 2.27646303, 1.16057837, 0.569284916 }, + { 999, 799, 599, 399, 199 } }, + }; + for (const Want& w : want) { + const std::vector s = gen::schedule_discrete(d, t, w.sched, 0); + REQUIRE_EQ(s.size(), (size_t)6); + for (int i = 0; i < 5; ++i) { + CHECK_NEAR(s[(size_t)i], w.s[i], 2e-6 * w.s[i] + 1e-7); + CHECK_EQ(t.timestep(s[(size_t)i]), w.ts[i]); + } + CHECK_EQ(s[5], 0.0f); + CHECK_EQ(std::string(gen::scheduler_name(w.sched)).empty(), false); + CHECK_EQ(gen::scheduler_id(gen::scheduler_name(w.sched)), w.sched); + } + /* Zero terminal SNR keeps the smallest sigma and makes the largest ComfyUI's 4518.76. */ + RadGeneratorDecl z = d; + z.zero_snr = 1; + gen::DiscreteTable tz; + REQUIRE_EQ(gen::discrete_table(z, &tz, &why), (int)RAD_OK); + CHECK_NEAR(tz.sigma_min(), 0.0291671585, 1e-8); + CHECK_NEAR(tz.sigma_max(), 4518.76367, 0.01); + CHECK_EQ(gen::sampler_id("dpmpp_2m"), (int32_t)RAD_GEN_SAMPLER_DPMPP_2M); + CHECK_EQ(gen::sampler_id("ddim"), (int32_t)-1); +} + +/* A discrete-time model's step carries, per entry, its sigmas (the one before included), the + * timestep, the request's sampler, the step, the image's size, and on the host the entry's + * conditioning rows, size and branch; the conditioning pass carries its tokens on the host. */ +TEST(a_discrete_step_carries_its_sampler_and_each_entrys_geometry) { + Program prog; + prog.generator = decl_discrete(); + RadGeneratorDecl& d = prog.generator; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.latent_scale = 8; + d.cond_rows = 2 * 77; + d.rope_hw_scale = 1.0; + d.chunk_tokens = 75; + d.chunk_bos = 49406; + d.chunk_eos = 49407; + d.pad_token = 49407; + prog.ctx.max_tok = 4096; + prog.ctx.max_seqs = 8; + prog.kv_groups.emplace_back(); + gen::Driver drv; + REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK); + auto r = std::make_unique(); + r->width = 64; + r->height = 32; + r->steps = 3; + r->sampler = RAD_GEN_SAMPLER_DPMPP_2M; + r->scheduler = RAD_GEN_SCHED_KARRAS; + r->pos.tokens.assign(77, 5); + r->has_neg = true; + r->neg.tokens.assign(77, 6); + r->cfg = 6.0f; + r->ticket = std::make_shared(); + std::string why; + REQUIRE_EQ(drv.submit(std::move(r), &why), (int)RAD_OK); + const RadBatch* b = drv.next(0); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND); + REQUIRE(b->gen_b->tokens_h != nullptr); + CHECK_EQ(b->gen_b->tokens_h[76], (int32_t)5); + CHECK_OK(drv.done()); + REQUIRE(drv.next(1) != nullptr); + CHECK_OK(drv.done()); + gen::DiscreteTable t; + REQUIRE_EQ(gen::discrete_table(d, &t, &why), (int)RAD_OK); + const std::vector s = gen::schedule_discrete(d, t, RAD_GEN_SCHED_KARRAS, 3); + for (int step = 0; step < 3; ++step) { + b = drv.next(2 + step); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE); + const RadGenBatch* G = b->gen_b; + REQUIRE_EQ(b->n_seq, (int64_t)2); + CHECK_EQ(b->n_tok, (int64_t)(2 * (77 + 32))); + for (int e = 0; e < 2; ++e) { + CHECK_EQ(G->sigma[e], s[(size_t)step]); + CHECK_EQ(G->sigma_next[e], s[(size_t)step + 1]); + CHECK_EQ(G->sigma_prev[e], step ? s[(size_t)step - 1] : 0.0f); + CHECK_EQ(G->timestep[e], (float)t.timestep(s[(size_t)step])); + CHECK_EQ(G->sampler[e], (int32_t)RAD_GEN_SAMPLER_DPMPP_2M); + CHECK_EQ(G->step[e], (int32_t)step); + CHECK_EQ(G->size_px[2 * e], 32.0f); + CHECK_EQ(G->size_px[2 * e + 1], 64.0f); + CHECK_EQ(G->entry_h[4 * e], (int32_t)77); + CHECK_EQ(G->entry_h[4 * e + 1], (int32_t)32); + CHECK_EQ(G->entry_h[4 * e + 2], (int32_t)64); + CHECK_EQ(G->entry_h[4 * e + 3], (int32_t)e); + } + CHECK_OK(drv.done()); + } + /* A sampler the model does not serve is refused at submit. */ + d.samplers = 1u << RAD_GEN_SAMPLER_EULER; + gen::Driver drv2; + REQUIRE_EQ(drv2.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK); + auto r2 = std::make_unique(); + r2->width = 64; + r2->height = 32; + r2->sampler = RAD_GEN_SAMPLER_EULER_ANCESTRAL; + r2->pos.tokens.assign(77, 5); + r2->ticket = std::make_shared(); + CHECK_EQ(drv2.submit(std::move(r2), &why), (int)RAD_E_INVAL); +} + /* ================================================================== the sequence */ /* An h x w image at frame `pos`: every row at that frame, height and width centred on zero. */ TEST(image_rotary_positions_centre_the_grid_on_its_frame) { @@ -422,4 +585,65 @@ TEST(the_joint_layout_carries_the_conditioning_in_every_step) { CHECK_OK(drv.done()); } +/* A generator that reads its prompt through a second tokenizer (RadGeneratorDecl::aux_tokens): + * each branch's COND pass carries that branch's ids and {0, n} on the device, and no other pass + * does; a branch with none, or more than declared, is refused at submission. */ +TEST(a_second_tokenizers_ids_ride_in_each_conditioning) { + Program prog; + prog.generator = decl_base(); + RadGeneratorDecl& d = prog.generator; + d.layout = RAD_GEN_LAYOUT_JOINT_STEP; + d.cond_rows = 16; + d.pad_multiple = 16; + d.pad_token = 99; + d.aux_tokens = 1; + d.aux_max_tokens = 6; + prog.ctx.max_tok = 2048; + prog.ctx.max_seqs = 8; + prog.kv_groups.emplace_back(); + gen::Driver drv; + REQUIRE_EQ(drv.init(prog, nullptr, { gen::Driver::RankIO{} }), (int)RAD_OK); + auto mk = [](std::vector aux, std::vector neg_aux) { + auto r = std::make_unique(); + r->width = 64; + r->height = 64; + r->pos.tokens = { 1, 2, 3 }; + r->pos.aux = std::move(aux); + r->has_neg = true; + r->neg.tokens = { 5 }; + r->neg.aux = std::move(neg_aux); + r->cfg = 4.0f; + r->ticket = std::make_shared(); + return r; + }; + std::string why; + CHECK_EQ(drv.submit(mk({ 7, 8 }, {}), &why), (int)RAD_E_INVAL); + CHECK(has(why, "second tokenizer")); + CHECK_EQ(drv.submit(mk({ 1, 2, 3, 4, 5, 6, 7 }, { 1 }), &why), (int)RAD_E_INVAL); + REQUIRE_EQ(drv.submit(mk({ 7, 8, 1 }, { 1 }), &why), (int)RAD_OK); + + const RadBatch* b = drv.next(0); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_COND); + const RadGenBatch* G = b->gen_b; + REQUIRE_EQ(G->n_aux, (int64_t)3); + CHECK_EQ(G->aux_ids[0], (int32_t)7); + CHECK_EQ(G->aux_ids[2], (int32_t)1); + CHECK_EQ(G->aux_cu[0], (int32_t)0); + CHECK_EQ(G->aux_cu[1], (int32_t)3); + CHECK_OK(drv.done()); + b = drv.next(1); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen_b->n_aux, (int64_t)1); + CHECK_EQ(b->gen_b->aux_ids[0], (int32_t)1); + CHECK_EQ(b->gen_b->aux_cu[1], (int32_t)1); + CHECK_OK(drv.done()); + b = drv.next(2); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->gen, (int32_t)RAD_GEN_PASS_DENOISE); + CHECK_EQ(b->gen_b->n_aux, (int64_t)0); + CHECK(b->gen_b->aux_ids == nullptr); + CHECK_OK(drv.done()); +} + RAD_TEST_MAIN() diff --git a/tests/images_test.cpp b/tests/images_test.cpp index 2cc5b814..b7ad1fd6 100644 --- a/tests/images_test.cpp +++ b/tests/images_test.cpp @@ -169,6 +169,78 @@ TEST(usage_counts_each_pictures_tokens_in_every_branch) { CHECK(s.last().has_neg); } +/* A model that reads its prompt through a second tokenizer gets the user's prompt as that tokenizer + * encodes it, in each branch, and a prompt longer than it reads is refused under `prompt`. A + * prompt shorter than the model's minimum after the fixed prefix is padded with its padding token + * (an empty prompt is one, and is not turned into " " first). */ +TEST(a_second_tokenizer_and_a_minimum_prompt_reach_the_generator) { + Images s; + s.img.inf.aux_tokens = true; + s.img.inf.aux_max_tokens = 4; + s.img.inf.min_tokens = 2; + s.img.inf.pad_token = 9; + s.gen({ { "prompt", "ab" }, { "negative_prompt", "c" }, { "true_cfg_scale", 4.0 } }); + REQUIRE(!s.img.got.empty()); + CHECK(s.last().pos.aux == std::vector({ 100 + 'a', 100 + 'b', 1 })); + CHECK(s.last().neg.aux == std::vector({ 100 + 'c', 1 })); + /* "c" is one token after the prefix, padded to two. */ + const gen::Branch& n = s.last().neg; + REQUIRE((int64_t)n.tokens.size() - n.n_drop == 2); + CHECK_EQ(n.tokens[(size_t)n.n_drop], (int32_t)'c'); + CHECK_EQ(n.tokens.back(), (int32_t)9); + s.gen({ { "prompt", "" } }); + const gen::Branch& p = s.last().pos; + REQUIRE((int64_t)p.tokens.size() - p.n_drop == 2); + CHECK_EQ(p.tokens[(size_t)p.n_drop], (int32_t)9); + CHECK(p.aux == std::vector({ 1 })); + /* An empty negative prompt stays empty for such a model: all padding. */ + s.gen({ { "prompt", "x" }, { "negative_prompt", "" }, { "true_cfg_scale", 4.0 } }); + const gen::Branch& e = s.last().neg; + REQUIRE((int64_t)e.tokens.size() - e.n_drop == 2); + CHECK_EQ(e.tokens[(size_t)e.n_drop], (int32_t)9); + CHECK(e.aux == std::vector({ 1 })); + const json longp = s.gen({ { "prompt", "abcd" } }, 400); + CHECK_EQ(str_at(longp["error"], "param"), std::string("prompt")); +} + +/* A discrete-time model takes `sampler` and `scheduler` by ComfyUI's names, defaulting to its + * own, and refuses one it does not serve; a flow-matching model refuses both. A prompt read in + * windows reaches the generator cut into runs between their markers, each padded to the window, + * after the template's fixed prefix, and a prompt that fills its last window exactly takes no + * empty one after it. */ +TEST(a_discrete_model_takes_its_sampler_and_reads_the_prompt_in_windows) { + Images s; + const json flow = s.gen({ { "prompt", "x" }, { "sampler", "euler" } }, 400); + CHECK_EQ(str_at(flow["error"], "param"), std::string("sampler")); + s.img.inf.samplers = (1u << RAD_GEN_SAMPLER_EULER) | (1u << RAD_GEN_SAMPLER_DPMPP_2M); + s.img.inf.default_sampler = RAD_GEN_SAMPLER_EULER; + s.img.inf.default_scheduler = RAD_GEN_SCHED_NORMAL; + s.img.inf.chunk_tokens = 4; + s.img.inf.chunk_bos = 2; + s.img.inf.chunk_eos = 3; + s.img.inf.chunk_pad = 9; + s.gen({ { "prompt", "abcdefghij" } }); + REQUIRE(!s.img.got.empty()); + CHECK_EQ(s.last().sampler, (int32_t)RAD_GEN_SAMPLER_EULER); + CHECK_EQ(s.last().scheduler, (int32_t)RAD_GEN_SCHED_NORMAL); + const std::vector want = { '<', 's', '>', 2, 'a', 'b', 'c', 'd', 3, + 2, 'e', 'f', 'g', 'h', 3, 2, 'i', 'j', 3, 9, 9 }; + CHECK(s.last().pos.tokens == want); + CHECK_EQ(s.last().pos.n_drop, (int32_t)3); + s.gen({ { "prompt", "x" }, { "sampler", "dpmpp_2m" }, { "scheduler", "karras" } }); + CHECK_EQ(s.last().sampler, (int32_t)RAD_GEN_SAMPLER_DPMPP_2M); + CHECK_EQ(s.last().scheduler, (int32_t)RAD_GEN_SCHED_KARRAS); + /* A prompt that fills a window takes no second one. */ + s.gen({ { "prompt", "abcd" } }); + const std::vector one = { '<', 's', '>', 2, 'a', 'b', 'c', 'd', 3 }; + CHECK(s.last().pos.tokens == one); + const json bad = s.gen({ { "prompt", "x" }, { "sampler", "euler_ancestral" } }, 400); + CHECK_EQ(str_at(bad["error"], "param"), std::string("sampler")); + CHECK(bad["error"]["supported"] == json::array({ "euler", "dpmpp_2m" })); + const json badk = s.gen({ { "prompt", "x" }, { "scheduler", "ddim_uniform" } }, 400); + CHECK_EQ(str_at(badk["error"], "param"), std::string("scheduler")); +} + /* `background: auto` keeps an edited picture's transparency and is opaque otherwise; a mask must * be the first picture's size. */ /* A model whose card states guidance as cond + s (cond - uncond) and guides by default (Krea 2): diff --git a/tests/lora_test.cpp b/tests/lora_test.cpp index c214b381..59584686 100644 --- a/tests/lora_test.cpp +++ b/tests/lora_test.cpp @@ -1032,8 +1032,9 @@ TEST(a_transformed_or_rotated_weight_is_not_a_site) { CHECK(has(lora::explain_module(b.program(), t, "model.layers.0.self_attn.q_proj"), "perm")); } -/* Adapters serve the token steps of a model that writes logits: declare refuses a generator, an - * embedding model and a program with no logits by name, and lets a text model through. */ +/* Adapters serve the token steps of a model that writes logits, or a generator that names its + * adapter keys: declare refuses a generator that names none, an embedding model and a program with + * no logits by name, and lets a text model through. */ TEST(declare_refuses_a_model_that_does_not_generate_text) { const RadModelMeta meta = llama_meta(); const RadBuildCtx ctx = ctx_for(0, 1); @@ -1044,7 +1045,7 @@ TEST(declare_refuses_a_model_that_does_not_generate_text) { d.cfg = &cfg; d.targets = { "q_proj" }; const struct { const char* what; void (*set)(Program&); } kinds[] = { - { "is an image, audio or video generator", + { "declares no adapter key names", [](Program& p) { p.logits_buf = 1; p.generator.layout = 1; } }, { "makes embeddings", [](Program& p) { p.pooled_buf = 1; } }, { "declares no logits", [](Program&) {} }, diff --git a/tests/mk_precompiled_goldens.py b/tests/mk_precompiled_goldens.py new file mode 100644 index 00000000..6b1412fa --- /dev/null +++ b/tests/mk_precompiled_goldens.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Writes tests/precompiled_golden.h: expected outputs for precompiled_test.cpp. + + - Unicode 16.0.0's GraphemeBreakTest.txt cases, each a codepoint sequence and the boundaries + UAX #29 puts in it (core/text/tokenizer_grapheme.h's grapheme_end); + - a small SentencePiece character map and what HuggingFace `tokenizers`' Precompiled normaliser + makes of a set of strings through it, clusters that map whole and clusters that do not among + them (PrecompiledMap::normalize). + +The map below was built with sentencepiece 0.2 from the rules + A -> a, U+FF21 -> A, U+FF41 -> a, e U+0301 -> U+00E9, LF -> space, U+2160 -> I +and is kept as base64 so regenerating needs only `tokenizers` (0.23.3 produced the current file): + + python3 tests/mk_precompiled_goldens.py GraphemeBreakTest.txt > tests/precompiled_golden.h +""" +import base64 +import sys + +import tokenizers +from tokenizers import normalizers + +CHARSMAP = ( + "AAQAAAAsAAAKDQAAAAAAgAYAAIDMAAIAgQ0AAAgAAICFvAIAoAUAAAQAAIC8nAIAvRACAKEFAAACAACAgTUAAA4AAAARAA" + "AAEAAAABMAAAASAAAAFQAAABQAAAAXAAAAFgAAABkAAAAYAAAAGwAAABoAAAAdAAAAHAAAAB8AAAAeAAAAIQAAACAAAAAj" + "AAAAIgAAACUAAAAkAAAAJwAAACYAAAApAAAAKAAAACsAAAAqAAAALQAAACwAAAAvAAAALgAAADEAAAAwAAAAMwAAADIAAA" + "A1AAAANAAAADcAAAA2AAAAOQAAADgAAAA7AAAAOgAAAD0AAAA8AAAAPwAAAD4AAABBAAAAQAAAAEMAAABCAAAARQAAAEQA" + "AABHAAAARgAAAEkAAABIAAAAQSUBAEoAAABNAAAATAAAAE8AAABOAAAAUQAAAFAAAABTAAAAUgAAAFUAAABUAAAAVwAAAF" + "YAAABZAAAAWAAAAFsAAABaAAAAXQAAAFwAAABfAAAAXgAAAGEAAABgAAAAYwAAAGIAAABlAAAAZAAAAGcAAABmAAAAaQAA" + "AGgAAABrAAAAagAAAG0AAABsAAAAZZgCAG4AAABxAAAAcAAAAHMAAAByAAAAdQAAAHQAAAB3AAAAdgAAAHkAAAB4AAAAew" + "AAAHoAAAB9AAAAfAAAAH8AAAB+AAAAgQAAAIAAAACDAAAAggAAAIUAAACEAAAAhwAAAIYAAACJAAAAiAAAAIsAAACKAAAA" + "jQAAAIwAAACPAAAAjgAAAJEAAACQAAAAkwAAAJIAAACVAAAAlAAAAJcAAACWAAAAmQAAAJgAAACbAAAAmgAAAJ0AAACcAA" + "AAnwAAAJ4AAAChAAAAoAAAAKMAAACiAAAApQAAAKQAAACnAAAApgAAAKkAAACoAAAAqwAAAKoAAACtAAAArAAAAK8AAACu" + "AAAAsQAAALAAAACzAAAAsgAAALUAAAC0AAAAtwAAALYAAAC5AAAAuAAAALsAAAC6AAAAvQAAALwAAAC/AAAAvgAAAMEAAA" + "DAAAAAwwAAAMIAAADFAAAAxAAAAMcAAADGAAAAyQAAAMgAAADLAAAAygAAAM0AAADMAAAAzwAAAM4AAADRAAAA0AAAANMA" + "AADSAAAA1QAAANQAAADXAAAA1gAAANkAAADYAAAA2wAAANoAAADdAAAA3AAAAN8AAADeAAAA4QAAAOAAAADjAAAA4gAAAO" + "9IAQDkAAAA5wAAAOYAAADpAAAA4qwBAOsAAADqAAAA7QAAAOwAAADvAAAA7gAAAPEAAADwAAAA8wAAAPIAAAD1AAAA9AAA" + "APcAAAD2AAAA+QAAAPgAAAD7AAAA+gAAAP0AAAD8AAAA/wAAAP4AAAAgAEEASQBhAMOpAA==" +) + +INPUTS = [ + "", "plain ascii", "A big Apple", "Abc a", "line one\nline two\n", + "café", "éé", "Áx", "Á", "Ⅰ Ⅰ́", + "é vs é", "1️⃣ keycap", "\U0001F469‍\U0001F4BB", + "\U0001F1EF\U0001F1F5\U0001F1FA", "각 jamo", "\r\nCRLF\r\n", + "क्ष conjunct", "a‍‍b", "tab\there", "กำ thai", + "ẍ̈̈̈", "Ä̈", +] + + +def cstr(s): + out = '"' + prev_hex = False + for b in s.encode("utf-8"): + c = chr(b) + if c == '"': + out += '\\"'; prev_hex = False + elif c == "\\": + out += "\\\\"; prev_hex = False + elif 0x20 <= b < 0x7F: + if prev_hex and c in "0123456789abcdefABCDEF": + out += '" "' + out += c; prev_hex = False + else: + out += "\\x%02x" % b; prev_hex = True + return out + '"' + + +def grapheme_cases(path): + """(codepoints, bitmask of the positions a cluster starts at, beyond the first).""" + cases = [] + for line in open(path, encoding="utf-8"): + line = line.split("#", 1)[0].strip() + if not line: + continue + toks = line.split() + cps, mask = [], 0 + for t in toks[1:-1]: + if t in ("÷", "×"): + if t == "÷": + mask |= 1 << len(cps) + continue + cps.append(int(t, 16)) + cases.append((cps, mask)) + return cases + + +def main(): + pc = normalizers.Precompiled(base64.b64decode(CHARSMAP)) + w = sys.stdout.write + w("/* precompiled_golden.h -- GENERATED by mk_precompiled_goldens.py from tokenizers %s and " + "the\n * Unicode 16.0.0 GraphemeBreakTest.txt; do not edit. */\n" % tokenizers.__version__) + w("#pragma once\n#include \n\n") + w("static const char* kPcCharsmap =\n") + for i in range(0, len(CHARSMAP), 96): + w(" \"%s\"\n" % CHARSMAP[i:i + 96]) + w(" ;\n\n") + w("struct PcCase { const char* in; const char* out; };\n") + w("static const PcCase kPcCases[] = {\n") + for s in INPUTS: + w(" { %s, %s },\n" % (cstr(s), cstr(pc.normalize_str(s)))) + w("};\n\n") + cases = grapheme_cases(sys.argv[1]) + w("/* A cluster starts at codepoint i (i > 0) where bit i of `starts` is set. */\n") + w("struct GbCase { uint32_t cp[8]; uint32_t n; uint32_t starts; };\n") + w("static const GbCase kGbCases[] = {\n") + for cps, mask in cases: + if len(cps) > 8: + continue + w(" { { %s }, %d, 0x%x },\n" % (", ".join("0x%X" % c for c in cps), len(cps), + mask & ~1)) + w("};\n") + + +if __name__ == "__main__": + main() diff --git a/tests/mk_tokenizer_goldens.py b/tests/mk_tokenizer_goldens.py index b8f8a7d5..4305d51e 100644 --- a/tests/mk_tokenizer_goldens.py +++ b/tests/mk_tokenizer_goldens.py @@ -246,6 +246,104 @@ def metaspace_specials(scheme): "vocab": vocab, "merges": [[MS, "H"], ["H", "i"], [MS + "H", "i"]]}} +# ---------------------------------------------------------------------------- CLIP-shaped + +CLIP_SPLIT = r"""'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""" + + +def gpt2_alphabet(): + """GPT-2's byte -> character map, in CLIP's vocabulary order.""" + bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("\xa1"), ord("\xac") + 1)) + \ + list(range(ord("\xae"), ord("\xff") + 1)) + cs = bs[:] + n = 0 + for b in range(256): + if b not in bs: + bs.append(b) + cs.append(256 + n) + n += 1 + return [chr(c) for c in cs] + + +CLIP_TRAIN = ("a photo of a cat, a painting of a dog, best quality, masterpiece, 1girl, solo, " + "looking at viewer, it's a photograph of the mountains at sunset, don't stop, " + "highly detailed digital art, portrait of an astronaut riding a horse, ") * 3 + + +def clip_like(): + """CLIP ViT-L/14's tokenizer.json with its vocabulary cut down: the real normaliser, Split, + ByteLevel, RobertaProcessing and decoder, the 512 byte tokens with and without the "" + end-of-word suffix in CLIP's order, and merges trained here (most frequent pair, then the + smallest) over a few prompts, each merged token's id 512 + its rank as in CLIP's own file.""" + from tokenizers import normalizers, pre_tokenizers, Regex + norm = normalizers.Sequence([normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "), + normalizers.Lowercase()]) + pre = pre_tokenizers.Sequence([ + pre_tokenizers.Split(Regex(CLIP_SPLIT), behavior="removed", invert=True), + pre_tokenizers.ByteLevel(add_prefix_space=False)]) + alpha = gpt2_alphabet() + vocab = alpha + [c + "" for c in alpha] + words = {} + for w, _ in pre.pre_tokenize_str(norm.normalize_str(CLIP_TRAIN)): + sym = tuple(list(w[:-1]) + [w[-1] + ""]) + words[sym] = words.get(sym, 0) + 1 + merges = [] + for _ in range(160): + pairs = {} + for sym, n in words.items(): + for a, b in zip(sym, sym[1:]): + pairs[(a, b)] = pairs.get((a, b), 0) + n + if not pairs: + break + best = min(pairs, key=lambda k: (-pairs[k], k)) + merges.append(best) + vocab.append(best[0] + best[1]) + nw = {} + for sym, n in words.items(): + out, i = [], 0 + while i < len(sym): + if i + 1 < len(sym) and (sym[i], sym[i + 1]) == best: + out.append(sym[i] + sym[i + 1]) + i += 2 + else: + out.append(sym[i]) + i += 1 + nw[tuple(out)] = nw.get(tuple(out), 0) + n + words = nw + bos, eos = len(vocab), len(vocab) + 1 + vocab += ["<|startoftext|>", "<|endoftext|>"] + return { + "added_tokens": [ + {"id": bos, "content": "<|startoftext|>", "single_word": False, "lstrip": False, + "rstrip": False, "normalized": True, "special": True}, + {"id": eos, "content": "<|endoftext|>", "single_word": False, "lstrip": False, + "rstrip": False, "normalized": False, "special": True}], + "normalizer": {"type": "Sequence", "normalizers": [ + {"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": r"\s+"}, "content": " "}, + {"type": "Lowercase"}]}, + "pre_tokenizer": {"type": "Sequence", "pretokenizers": [ + {"type": "Split", "pattern": {"Regex": CLIP_SPLIT}, "behavior": "Removed", + "invert": True}, + {"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": True}]}, + "post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", eos], + "cls": ["<|startoftext|>", bos], "trim_offsets": False, + "add_prefix_space": False}, + "decoder": {"type": "ByteLevel", "add_prefix_space": True, "trim_offsets": True}, + "model": {"type": "BPE", "dropout": None, "unk_token": "<|endoftext|>", + "continuing_subword_prefix": "", "end_of_word_suffix": "", + "fuse_unk": False, "vocab": {t: i for i, t in enumerate(vocab)}, + "merges": [a + " " + b for a, b in merges]}, + } + + +CLIP_TEXTS = ["a photo of a cat", "1girl, solo, masterpiece, best quality, (absurdres:1.2), " + "looking_at_viewer, hatsune_miku", "A Photograph of the Mountains, it's DON'T stop", + "1024x1024 2.5 v1.0", "Café naïve 東京タワー 서울 🍣👩‍👩‍👧 İstanbul ΣΊΣΥΦΟΣ", + " many spaces\t\ttabs\n\nnewlines ", "...!!!??? ((()))[[]]", "", "a", + "<|startoftext|>a cat<|endoftext|>", "x<|StartOfText|>y", "ab catcat", + "photographphotograph", "it'sit's'll"] + + SPECIAL_TEXTS = ["Hi", "[INST]Hi", "[INST] Hi", "Hi[INST]Hi", "Hi", "Hi Hi[INST]Hi"] GEMMA_TEXTS = ["hello", " hello", "hello world", "hello world", "the cat", "\nthe\n\ncat", @@ -341,6 +439,30 @@ def main(): print(" return v;") print("}") print() + c = clip_like() + tok = Tokenizer.from_str(json.dumps(c)) + print("const char* const kClipLike = R\"JSON(%s)JSON\";" % json.dumps(c, ensure_ascii=False)) + print() + print("const std::vector& clip_goldens() {") + print(" static const std::vector v = {") + for t in CLIP_TEXTS: + a = tok.encode(t, add_special_tokens=False).ids + b = tok.encode(t, add_special_tokens=True).ids + print(" { %s, %s, %s }," % (cstr(t), ids_cpp(a), ids_cpp(b))) + print(" };") + print(" return v;") + print("}") + print() + print("/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */") + print("const std::vector& clip_decoded() {") + print(" static const std::vector v = {") + for t in CLIP_TEXTS: + print(" %s," % cstr(tok.decode(tok.encode(t, add_special_tokens=True).ids, + skip_special_tokens=True))) + print(" };") + print(" return v;") + print("}") + print() print("/* END generated by mk_tokenizer_goldens.py */") diff --git a/tests/precompiled_golden.h b/tests/precompiled_golden.h new file mode 100644 index 00000000..3acddb40 --- /dev/null +++ b/tests/precompiled_golden.h @@ -0,0 +1,1146 @@ +/* precompiled_golden.h -- GENERATED by mk_precompiled_goldens.py from tokenizers 0.23.3 and the + * Unicode 16.0.0 GraphemeBreakTest.txt; do not edit. */ +#pragma once +#include + +static const char* kPcCharsmap = + "AAQAAAAsAAAKDQAAAAAAgAYAAIDMAAIAgQ0AAAgAAICFvAIAoAUAAAQAAIC8nAIAvRACAKEFAAACAACAgTUAAA4AAAARAAAA" + "EAAAABMAAAASAAAAFQAAABQAAAAXAAAAFgAAABkAAAAYAAAAGwAAABoAAAAdAAAAHAAAAB8AAAAeAAAAIQAAACAAAAAjAAAA" + "IgAAACUAAAAkAAAAJwAAACYAAAApAAAAKAAAACsAAAAqAAAALQAAACwAAAAvAAAALgAAADEAAAAwAAAAMwAAADIAAAA1AAAA" + "NAAAADcAAAA2AAAAOQAAADgAAAA7AAAAOgAAAD0AAAA8AAAAPwAAAD4AAABBAAAAQAAAAEMAAABCAAAARQAAAEQAAABHAAAA" + "RgAAAEkAAABIAAAAQSUBAEoAAABNAAAATAAAAE8AAABOAAAAUQAAAFAAAABTAAAAUgAAAFUAAABUAAAAVwAAAFYAAABZAAAA" + "WAAAAFsAAABaAAAAXQAAAFwAAABfAAAAXgAAAGEAAABgAAAAYwAAAGIAAABlAAAAZAAAAGcAAABmAAAAaQAAAGgAAABrAAAA" + "agAAAG0AAABsAAAAZZgCAG4AAABxAAAAcAAAAHMAAAByAAAAdQAAAHQAAAB3AAAAdgAAAHkAAAB4AAAAewAAAHoAAAB9AAAA" + "fAAAAH8AAAB+AAAAgQAAAIAAAACDAAAAggAAAIUAAACEAAAAhwAAAIYAAACJAAAAiAAAAIsAAACKAAAAjQAAAIwAAACPAAAA" + "jgAAAJEAAACQAAAAkwAAAJIAAACVAAAAlAAAAJcAAACWAAAAmQAAAJgAAACbAAAAmgAAAJ0AAACcAAAAnwAAAJ4AAAChAAAA" + "oAAAAKMAAACiAAAApQAAAKQAAACnAAAApgAAAKkAAACoAAAAqwAAAKoAAACtAAAArAAAAK8AAACuAAAAsQAAALAAAACzAAAA" + "sgAAALUAAAC0AAAAtwAAALYAAAC5AAAAuAAAALsAAAC6AAAAvQAAALwAAAC/AAAAvgAAAMEAAADAAAAAwwAAAMIAAADFAAAA" + "xAAAAMcAAADGAAAAyQAAAMgAAADLAAAAygAAAM0AAADMAAAAzwAAAM4AAADRAAAA0AAAANMAAADSAAAA1QAAANQAAADXAAAA" + "1gAAANkAAADYAAAA2wAAANoAAADdAAAA3AAAAN8AAADeAAAA4QAAAOAAAADjAAAA4gAAAO9IAQDkAAAA5wAAAOYAAADpAAAA" + "4qwBAOsAAADqAAAA7QAAAOwAAADvAAAA7gAAAPEAAADwAAAA8wAAAPIAAAD1AAAA9AAAAPcAAAD2AAAA+QAAAPgAAAD7AAAA" + "+gAAAP0AAAD8AAAA/wAAAP4AAAAgAEEASQBhAMOpAA==" + ; + +struct PcCase { const char* in; const char* out; }; +static const PcCase kPcCases[] = { + { "", "" }, + { "plain ascii", "plain ascii" }, + { "A big Apple", "a big apple" }, + { "\xef\xbc\xa1\xef\xbd\x82\xef\xbd\x83 \xef\xbd\x81", "A\xef\xbd\x82\xef\xbd\x83 a" }, + { "line one\x0aline two\x0a", "line one line two " }, + { "cafe\xcc\x81", "caf\xc3\xa9" }, + { "e\xcc\x81" "e\xcc\x81", "\xc3\xa9\xc3\xa9" }, + { "\xef\xbc\xa1\xcc\x81x", "Ax" }, + { "A\xcc\x81", "a" }, + { "\xe2\x85\xa0 \xe2\x85\xa0\xcc\x81", "I I" }, + { "\xc3\xa9 vs e\xcc\x81", "\xc3\xa9 vs \xc3\xa9" }, + { "1\xef\xb8\x8f\xe2\x83\xa3 keycap", "1\xef\xb8\x8f\xe2\x83\xa3 keycap" }, + { "\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb", "\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x92\xbb" }, + { "\xf0\x9f\x87\xaf\xf0\x9f\x87\xb5\xf0\x9f\x87\xba", "\xf0\x9f\x87\xaf\xf0\x9f\x87\xb5\xf0\x9f\x87\xba" }, + { "\xe1\x84\x80\xe1\x85\xa1\xe1\x86\xa8 jamo", "\xe1\x84\x80\xe1\x85\xa1\xe1\x86\xa8 jamo" }, + { "\x0d\x0a" "CRLF\x0d\x0a", "\x0d CRLF\x0d " }, + { "\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7 conjunct", "\xe0\xa4\x95\xe0\xa5\x8d\xe0\xa4\xb7 conjunct" }, + { "a\xe2\x80\x8d\xe2\x80\x8d" "b", "a\xe2\x80\x8d\xe2\x80\x8d" "b" }, + { "tab\x09here", "tab\x09here" }, + { "\xe0\xb8\x81\xe0\xb8\xb3 thai", "\xe0\xb8\x81\xe0\xb8\xb3 thai" }, + { "x\xcc\x88\xcc\x88\xcc\x88\xcc\x88", "x\xcc\x88\xcc\x88\xcc\x88\xcc\x88" }, + { "\xef\xbc\xa1\xcc\x88\xcc\x88", "A\xcc\x88\xcc\x88" }, +}; + +/* A cluster starts at codepoint i (i > 0) where bit i of `starts` is set. */ +struct GbCase { uint32_t cp[8]; uint32_t n; uint32_t starts; }; +static const GbCase kGbCases[] = { + { { 0x20, 0x20 }, 2, 0x2 }, + { { 0x20, 0x308, 0x20 }, 3, 0x4 }, + { { 0x20, 0xD }, 2, 0x2 }, + { { 0x20, 0x308, 0xD }, 3, 0x4 }, + { { 0x20, 0xA }, 2, 0x2 }, + { { 0x20, 0x308, 0xA }, 3, 0x4 }, + { { 0x20, 0x1 }, 2, 0x2 }, + { { 0x20, 0x308, 0x1 }, 3, 0x4 }, + { { 0x20, 0x200C }, 2, 0x0 }, + { { 0x20, 0x308, 0x200C }, 3, 0x0 }, + { { 0x20, 0x1F1E6 }, 2, 0x2 }, + { { 0x20, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x20, 0x600 }, 2, 0x2 }, + { { 0x20, 0x308, 0x600 }, 3, 0x4 }, + { { 0x20, 0xA03 }, 2, 0x0 }, + { { 0x20, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x20, 0x1100 }, 2, 0x2 }, + { { 0x20, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x20, 0x1160 }, 2, 0x2 }, + { { 0x20, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x20, 0x11A8 }, 2, 0x2 }, + { { 0x20, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x20, 0xAC00 }, 2, 0x2 }, + { { 0x20, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x20, 0xAC01 }, 2, 0x2 }, + { { 0x20, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x20, 0x903 }, 2, 0x0 }, + { { 0x20, 0x308, 0x903 }, 3, 0x0 }, + { { 0x20, 0x904 }, 2, 0x2 }, + { { 0x20, 0x308, 0x904 }, 3, 0x4 }, + { { 0x20, 0xD4E }, 2, 0x2 }, + { { 0x20, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x20, 0x915 }, 2, 0x2 }, + { { 0x20, 0x308, 0x915 }, 3, 0x4 }, + { { 0x20, 0x231A }, 2, 0x2 }, + { { 0x20, 0x308, 0x231A }, 3, 0x4 }, + { { 0x20, 0x300 }, 2, 0x0 }, + { { 0x20, 0x308, 0x300 }, 3, 0x0 }, + { { 0x20, 0x900 }, 2, 0x0 }, + { { 0x20, 0x308, 0x900 }, 3, 0x0 }, + { { 0x20, 0x94D }, 2, 0x0 }, + { { 0x20, 0x308, 0x94D }, 3, 0x0 }, + { { 0x20, 0x200D }, 2, 0x0 }, + { { 0x20, 0x308, 0x200D }, 3, 0x0 }, + { { 0x20, 0x378 }, 2, 0x2 }, + { { 0x20, 0x308, 0x378 }, 3, 0x4 }, + { { 0xD, 0x20 }, 2, 0x2 }, + { { 0xD, 0x308, 0x20 }, 3, 0x6 }, + { { 0xD, 0xD }, 2, 0x2 }, + { { 0xD, 0x308, 0xD }, 3, 0x6 }, + { { 0xD, 0xA }, 2, 0x0 }, + { { 0xD, 0x308, 0xA }, 3, 0x6 }, + { { 0xD, 0x1 }, 2, 0x2 }, + { { 0xD, 0x308, 0x1 }, 3, 0x6 }, + { { 0xD, 0x200C }, 2, 0x2 }, + { { 0xD, 0x308, 0x200C }, 3, 0x2 }, + { { 0xD, 0x1F1E6 }, 2, 0x2 }, + { { 0xD, 0x308, 0x1F1E6 }, 3, 0x6 }, + { { 0xD, 0x600 }, 2, 0x2 }, + { { 0xD, 0x308, 0x600 }, 3, 0x6 }, + { { 0xD, 0xA03 }, 2, 0x2 }, + { { 0xD, 0x308, 0xA03 }, 3, 0x2 }, + { { 0xD, 0x1100 }, 2, 0x2 }, + { { 0xD, 0x308, 0x1100 }, 3, 0x6 }, + { { 0xD, 0x1160 }, 2, 0x2 }, + { { 0xD, 0x308, 0x1160 }, 3, 0x6 }, + { { 0xD, 0x11A8 }, 2, 0x2 }, + { { 0xD, 0x308, 0x11A8 }, 3, 0x6 }, + { { 0xD, 0xAC00 }, 2, 0x2 }, + { { 0xD, 0x308, 0xAC00 }, 3, 0x6 }, + { { 0xD, 0xAC01 }, 2, 0x2 }, + { { 0xD, 0x308, 0xAC01 }, 3, 0x6 }, + { { 0xD, 0x903 }, 2, 0x2 }, + { { 0xD, 0x308, 0x903 }, 3, 0x2 }, + { { 0xD, 0x904 }, 2, 0x2 }, + { { 0xD, 0x308, 0x904 }, 3, 0x6 }, + { { 0xD, 0xD4E }, 2, 0x2 }, + { { 0xD, 0x308, 0xD4E }, 3, 0x6 }, + { { 0xD, 0x915 }, 2, 0x2 }, + { { 0xD, 0x308, 0x915 }, 3, 0x6 }, + { { 0xD, 0x231A }, 2, 0x2 }, + { { 0xD, 0x308, 0x231A }, 3, 0x6 }, + { { 0xD, 0x300 }, 2, 0x2 }, + { { 0xD, 0x308, 0x300 }, 3, 0x2 }, + { { 0xD, 0x900 }, 2, 0x2 }, + { { 0xD, 0x308, 0x900 }, 3, 0x2 }, + { { 0xD, 0x94D }, 2, 0x2 }, + { { 0xD, 0x308, 0x94D }, 3, 0x2 }, + { { 0xD, 0x200D }, 2, 0x2 }, + { { 0xD, 0x308, 0x200D }, 3, 0x2 }, + { { 0xD, 0x378 }, 2, 0x2 }, + { { 0xD, 0x308, 0x378 }, 3, 0x6 }, + { { 0xA, 0x20 }, 2, 0x2 }, + { { 0xA, 0x308, 0x20 }, 3, 0x6 }, + { { 0xA, 0xD }, 2, 0x2 }, + { { 0xA, 0x308, 0xD }, 3, 0x6 }, + { { 0xA, 0xA }, 2, 0x2 }, + { { 0xA, 0x308, 0xA }, 3, 0x6 }, + { { 0xA, 0x1 }, 2, 0x2 }, + { { 0xA, 0x308, 0x1 }, 3, 0x6 }, + { { 0xA, 0x200C }, 2, 0x2 }, + { { 0xA, 0x308, 0x200C }, 3, 0x2 }, + { { 0xA, 0x1F1E6 }, 2, 0x2 }, + { { 0xA, 0x308, 0x1F1E6 }, 3, 0x6 }, + { { 0xA, 0x600 }, 2, 0x2 }, + { { 0xA, 0x308, 0x600 }, 3, 0x6 }, + { { 0xA, 0xA03 }, 2, 0x2 }, + { { 0xA, 0x308, 0xA03 }, 3, 0x2 }, + { { 0xA, 0x1100 }, 2, 0x2 }, + { { 0xA, 0x308, 0x1100 }, 3, 0x6 }, + { { 0xA, 0x1160 }, 2, 0x2 }, + { { 0xA, 0x308, 0x1160 }, 3, 0x6 }, + { { 0xA, 0x11A8 }, 2, 0x2 }, + { { 0xA, 0x308, 0x11A8 }, 3, 0x6 }, + { { 0xA, 0xAC00 }, 2, 0x2 }, + { { 0xA, 0x308, 0xAC00 }, 3, 0x6 }, + { { 0xA, 0xAC01 }, 2, 0x2 }, + { { 0xA, 0x308, 0xAC01 }, 3, 0x6 }, + { { 0xA, 0x903 }, 2, 0x2 }, + { { 0xA, 0x308, 0x903 }, 3, 0x2 }, + { { 0xA, 0x904 }, 2, 0x2 }, + { { 0xA, 0x308, 0x904 }, 3, 0x6 }, + { { 0xA, 0xD4E }, 2, 0x2 }, + { { 0xA, 0x308, 0xD4E }, 3, 0x6 }, + { { 0xA, 0x915 }, 2, 0x2 }, + { { 0xA, 0x308, 0x915 }, 3, 0x6 }, + { { 0xA, 0x231A }, 2, 0x2 }, + { { 0xA, 0x308, 0x231A }, 3, 0x6 }, + { { 0xA, 0x300 }, 2, 0x2 }, + { { 0xA, 0x308, 0x300 }, 3, 0x2 }, + { { 0xA, 0x900 }, 2, 0x2 }, + { { 0xA, 0x308, 0x900 }, 3, 0x2 }, + { { 0xA, 0x94D }, 2, 0x2 }, + { { 0xA, 0x308, 0x94D }, 3, 0x2 }, + { { 0xA, 0x200D }, 2, 0x2 }, + { { 0xA, 0x308, 0x200D }, 3, 0x2 }, + { { 0xA, 0x378 }, 2, 0x2 }, + { { 0xA, 0x308, 0x378 }, 3, 0x6 }, + { { 0x1, 0x20 }, 2, 0x2 }, + { { 0x1, 0x308, 0x20 }, 3, 0x6 }, + { { 0x1, 0xD }, 2, 0x2 }, + { { 0x1, 0x308, 0xD }, 3, 0x6 }, + { { 0x1, 0xA }, 2, 0x2 }, + { { 0x1, 0x308, 0xA }, 3, 0x6 }, + { { 0x1, 0x1 }, 2, 0x2 }, + { { 0x1, 0x308, 0x1 }, 3, 0x6 }, + { { 0x1, 0x200C }, 2, 0x2 }, + { { 0x1, 0x308, 0x200C }, 3, 0x2 }, + { { 0x1, 0x1F1E6 }, 2, 0x2 }, + { { 0x1, 0x308, 0x1F1E6 }, 3, 0x6 }, + { { 0x1, 0x600 }, 2, 0x2 }, + { { 0x1, 0x308, 0x600 }, 3, 0x6 }, + { { 0x1, 0xA03 }, 2, 0x2 }, + { { 0x1, 0x308, 0xA03 }, 3, 0x2 }, + { { 0x1, 0x1100 }, 2, 0x2 }, + { { 0x1, 0x308, 0x1100 }, 3, 0x6 }, + { { 0x1, 0x1160 }, 2, 0x2 }, + { { 0x1, 0x308, 0x1160 }, 3, 0x6 }, + { { 0x1, 0x11A8 }, 2, 0x2 }, + { { 0x1, 0x308, 0x11A8 }, 3, 0x6 }, + { { 0x1, 0xAC00 }, 2, 0x2 }, + { { 0x1, 0x308, 0xAC00 }, 3, 0x6 }, + { { 0x1, 0xAC01 }, 2, 0x2 }, + { { 0x1, 0x308, 0xAC01 }, 3, 0x6 }, + { { 0x1, 0x903 }, 2, 0x2 }, + { { 0x1, 0x308, 0x903 }, 3, 0x2 }, + { { 0x1, 0x904 }, 2, 0x2 }, + { { 0x1, 0x308, 0x904 }, 3, 0x6 }, + { { 0x1, 0xD4E }, 2, 0x2 }, + { { 0x1, 0x308, 0xD4E }, 3, 0x6 }, + { { 0x1, 0x915 }, 2, 0x2 }, + { { 0x1, 0x308, 0x915 }, 3, 0x6 }, + { { 0x1, 0x231A }, 2, 0x2 }, + { { 0x1, 0x308, 0x231A }, 3, 0x6 }, + { { 0x1, 0x300 }, 2, 0x2 }, + { { 0x1, 0x308, 0x300 }, 3, 0x2 }, + { { 0x1, 0x900 }, 2, 0x2 }, + { { 0x1, 0x308, 0x900 }, 3, 0x2 }, + { { 0x1, 0x94D }, 2, 0x2 }, + { { 0x1, 0x308, 0x94D }, 3, 0x2 }, + { { 0x1, 0x200D }, 2, 0x2 }, + { { 0x1, 0x308, 0x200D }, 3, 0x2 }, + { { 0x1, 0x378 }, 2, 0x2 }, + { { 0x1, 0x308, 0x378 }, 3, 0x6 }, + { { 0x200C, 0x20 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x20 }, 3, 0x4 }, + { { 0x200C, 0xD }, 2, 0x2 }, + { { 0x200C, 0x308, 0xD }, 3, 0x4 }, + { { 0x200C, 0xA }, 2, 0x2 }, + { { 0x200C, 0x308, 0xA }, 3, 0x4 }, + { { 0x200C, 0x1 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x1 }, 3, 0x4 }, + { { 0x200C, 0x200C }, 2, 0x0 }, + { { 0x200C, 0x308, 0x200C }, 3, 0x0 }, + { { 0x200C, 0x1F1E6 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x200C, 0x600 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x600 }, 3, 0x4 }, + { { 0x200C, 0xA03 }, 2, 0x0 }, + { { 0x200C, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x200C, 0x1100 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x200C, 0x1160 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x200C, 0x11A8 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x200C, 0xAC00 }, 2, 0x2 }, + { { 0x200C, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x200C, 0xAC01 }, 2, 0x2 }, + { { 0x200C, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x200C, 0x903 }, 2, 0x0 }, + { { 0x200C, 0x308, 0x903 }, 3, 0x0 }, + { { 0x200C, 0x904 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x904 }, 3, 0x4 }, + { { 0x200C, 0xD4E }, 2, 0x2 }, + { { 0x200C, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x200C, 0x915 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x915 }, 3, 0x4 }, + { { 0x200C, 0x231A }, 2, 0x2 }, + { { 0x200C, 0x308, 0x231A }, 3, 0x4 }, + { { 0x200C, 0x300 }, 2, 0x0 }, + { { 0x200C, 0x308, 0x300 }, 3, 0x0 }, + { { 0x200C, 0x900 }, 2, 0x0 }, + { { 0x200C, 0x308, 0x900 }, 3, 0x0 }, + { { 0x200C, 0x94D }, 2, 0x0 }, + { { 0x200C, 0x308, 0x94D }, 3, 0x0 }, + { { 0x200C, 0x200D }, 2, 0x0 }, + { { 0x200C, 0x308, 0x200D }, 3, 0x0 }, + { { 0x200C, 0x378 }, 2, 0x2 }, + { { 0x200C, 0x308, 0x378 }, 3, 0x4 }, + { { 0x1F1E6, 0x20 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x20 }, 3, 0x4 }, + { { 0x1F1E6, 0xD }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xD }, 3, 0x4 }, + { { 0x1F1E6, 0xA }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xA }, 3, 0x4 }, + { { 0x1F1E6, 0x1 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x1 }, 3, 0x4 }, + { { 0x1F1E6, 0x200C }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x200C }, 3, 0x0 }, + { { 0x1F1E6, 0x1F1E6 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x1F1E6, 0x600 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x600 }, 3, 0x4 }, + { { 0x1F1E6, 0xA03 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x1F1E6, 0x1100 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x1F1E6, 0x1160 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x1F1E6, 0x11A8 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x1F1E6, 0xAC00 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x1F1E6, 0xAC01 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x1F1E6, 0x903 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x903 }, 3, 0x0 }, + { { 0x1F1E6, 0x904 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x904 }, 3, 0x4 }, + { { 0x1F1E6, 0xD4E }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x1F1E6, 0x915 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x915 }, 3, 0x4 }, + { { 0x1F1E6, 0x231A }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x231A }, 3, 0x4 }, + { { 0x1F1E6, 0x300 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x300 }, 3, 0x0 }, + { { 0x1F1E6, 0x900 }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x900 }, 3, 0x0 }, + { { 0x1F1E6, 0x94D }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x94D }, 3, 0x0 }, + { { 0x1F1E6, 0x200D }, 2, 0x0 }, + { { 0x1F1E6, 0x308, 0x200D }, 3, 0x0 }, + { { 0x1F1E6, 0x378 }, 2, 0x2 }, + { { 0x1F1E6, 0x308, 0x378 }, 3, 0x4 }, + { { 0x600, 0x20 }, 2, 0x0 }, + { { 0x600, 0x308, 0x20 }, 3, 0x4 }, + { { 0x600, 0xD }, 2, 0x2 }, + { { 0x600, 0x308, 0xD }, 3, 0x4 }, + { { 0x600, 0xA }, 2, 0x2 }, + { { 0x600, 0x308, 0xA }, 3, 0x4 }, + { { 0x600, 0x1 }, 2, 0x2 }, + { { 0x600, 0x308, 0x1 }, 3, 0x4 }, + { { 0x600, 0x200C }, 2, 0x0 }, + { { 0x600, 0x308, 0x200C }, 3, 0x0 }, + { { 0x600, 0x1F1E6 }, 2, 0x0 }, + { { 0x600, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x600, 0x600 }, 2, 0x0 }, + { { 0x600, 0x308, 0x600 }, 3, 0x4 }, + { { 0x600, 0xA03 }, 2, 0x0 }, + { { 0x600, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x600, 0x1100 }, 2, 0x0 }, + { { 0x600, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x600, 0x1160 }, 2, 0x0 }, + { { 0x600, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x600, 0x11A8 }, 2, 0x0 }, + { { 0x600, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x600, 0xAC00 }, 2, 0x0 }, + { { 0x600, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x600, 0xAC01 }, 2, 0x0 }, + { { 0x600, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x600, 0x903 }, 2, 0x0 }, + { { 0x600, 0x308, 0x903 }, 3, 0x0 }, + { { 0x600, 0x904 }, 2, 0x0 }, + { { 0x600, 0x308, 0x904 }, 3, 0x4 }, + { { 0x600, 0xD4E }, 2, 0x0 }, + { { 0x600, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x600, 0x915 }, 2, 0x0 }, + { { 0x600, 0x308, 0x915 }, 3, 0x4 }, + { { 0x600, 0x231A }, 2, 0x0 }, + { { 0x600, 0x308, 0x231A }, 3, 0x4 }, + { { 0x600, 0x300 }, 2, 0x0 }, + { { 0x600, 0x308, 0x300 }, 3, 0x0 }, + { { 0x600, 0x900 }, 2, 0x0 }, + { { 0x600, 0x308, 0x900 }, 3, 0x0 }, + { { 0x600, 0x94D }, 2, 0x0 }, + { { 0x600, 0x308, 0x94D }, 3, 0x0 }, + { { 0x600, 0x200D }, 2, 0x0 }, + { { 0x600, 0x308, 0x200D }, 3, 0x0 }, + { { 0x600, 0x378 }, 2, 0x0 }, + { { 0x600, 0x308, 0x378 }, 3, 0x4 }, + { { 0xA03, 0x20 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x20 }, 3, 0x4 }, + { { 0xA03, 0xD }, 2, 0x2 }, + { { 0xA03, 0x308, 0xD }, 3, 0x4 }, + { { 0xA03, 0xA }, 2, 0x2 }, + { { 0xA03, 0x308, 0xA }, 3, 0x4 }, + { { 0xA03, 0x1 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x1 }, 3, 0x4 }, + { { 0xA03, 0x200C }, 2, 0x0 }, + { { 0xA03, 0x308, 0x200C }, 3, 0x0 }, + { { 0xA03, 0x1F1E6 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0xA03, 0x600 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x600 }, 3, 0x4 }, + { { 0xA03, 0xA03 }, 2, 0x0 }, + { { 0xA03, 0x308, 0xA03 }, 3, 0x0 }, + { { 0xA03, 0x1100 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x1100 }, 3, 0x4 }, + { { 0xA03, 0x1160 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x1160 }, 3, 0x4 }, + { { 0xA03, 0x11A8 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0xA03, 0xAC00 }, 2, 0x2 }, + { { 0xA03, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0xA03, 0xAC01 }, 2, 0x2 }, + { { 0xA03, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0xA03, 0x903 }, 2, 0x0 }, + { { 0xA03, 0x308, 0x903 }, 3, 0x0 }, + { { 0xA03, 0x904 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x904 }, 3, 0x4 }, + { { 0xA03, 0xD4E }, 2, 0x2 }, + { { 0xA03, 0x308, 0xD4E }, 3, 0x4 }, + { { 0xA03, 0x915 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x915 }, 3, 0x4 }, + { { 0xA03, 0x231A }, 2, 0x2 }, + { { 0xA03, 0x308, 0x231A }, 3, 0x4 }, + { { 0xA03, 0x300 }, 2, 0x0 }, + { { 0xA03, 0x308, 0x300 }, 3, 0x0 }, + { { 0xA03, 0x900 }, 2, 0x0 }, + { { 0xA03, 0x308, 0x900 }, 3, 0x0 }, + { { 0xA03, 0x94D }, 2, 0x0 }, + { { 0xA03, 0x308, 0x94D }, 3, 0x0 }, + { { 0xA03, 0x200D }, 2, 0x0 }, + { { 0xA03, 0x308, 0x200D }, 3, 0x0 }, + { { 0xA03, 0x378 }, 2, 0x2 }, + { { 0xA03, 0x308, 0x378 }, 3, 0x4 }, + { { 0x1100, 0x20 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x20 }, 3, 0x4 }, + { { 0x1100, 0xD }, 2, 0x2 }, + { { 0x1100, 0x308, 0xD }, 3, 0x4 }, + { { 0x1100, 0xA }, 2, 0x2 }, + { { 0x1100, 0x308, 0xA }, 3, 0x4 }, + { { 0x1100, 0x1 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x1 }, 3, 0x4 }, + { { 0x1100, 0x200C }, 2, 0x0 }, + { { 0x1100, 0x308, 0x200C }, 3, 0x0 }, + { { 0x1100, 0x1F1E6 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x1100, 0x600 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x600 }, 3, 0x4 }, + { { 0x1100, 0xA03 }, 2, 0x0 }, + { { 0x1100, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x1100, 0x1100 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x1100, 0x1160 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x1100, 0x11A8 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x1100, 0xAC00 }, 2, 0x0 }, + { { 0x1100, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x1100, 0xAC01 }, 2, 0x0 }, + { { 0x1100, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x1100, 0x903 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x903 }, 3, 0x0 }, + { { 0x1100, 0x904 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x904 }, 3, 0x4 }, + { { 0x1100, 0xD4E }, 2, 0x2 }, + { { 0x1100, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x1100, 0x915 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x915 }, 3, 0x4 }, + { { 0x1100, 0x231A }, 2, 0x2 }, + { { 0x1100, 0x308, 0x231A }, 3, 0x4 }, + { { 0x1100, 0x300 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x300 }, 3, 0x0 }, + { { 0x1100, 0x900 }, 2, 0x0 }, + { { 0x1100, 0x308, 0x900 }, 3, 0x0 }, + { { 0x1100, 0x94D }, 2, 0x0 }, + { { 0x1100, 0x308, 0x94D }, 3, 0x0 }, + { { 0x1100, 0x200D }, 2, 0x0 }, + { { 0x1100, 0x308, 0x200D }, 3, 0x0 }, + { { 0x1100, 0x378 }, 2, 0x2 }, + { { 0x1100, 0x308, 0x378 }, 3, 0x4 }, + { { 0x1160, 0x20 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x20 }, 3, 0x4 }, + { { 0x1160, 0xD }, 2, 0x2 }, + { { 0x1160, 0x308, 0xD }, 3, 0x4 }, + { { 0x1160, 0xA }, 2, 0x2 }, + { { 0x1160, 0x308, 0xA }, 3, 0x4 }, + { { 0x1160, 0x1 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x1 }, 3, 0x4 }, + { { 0x1160, 0x200C }, 2, 0x0 }, + { { 0x1160, 0x308, 0x200C }, 3, 0x0 }, + { { 0x1160, 0x1F1E6 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x1160, 0x600 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x600 }, 3, 0x4 }, + { { 0x1160, 0xA03 }, 2, 0x0 }, + { { 0x1160, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x1160, 0x1100 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x1160, 0x1160 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x1160, 0x11A8 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x1160, 0xAC00 }, 2, 0x2 }, + { { 0x1160, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x1160, 0xAC01 }, 2, 0x2 }, + { { 0x1160, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x1160, 0x903 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x903 }, 3, 0x0 }, + { { 0x1160, 0x904 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x904 }, 3, 0x4 }, + { { 0x1160, 0xD4E }, 2, 0x2 }, + { { 0x1160, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x1160, 0x915 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x915 }, 3, 0x4 }, + { { 0x1160, 0x231A }, 2, 0x2 }, + { { 0x1160, 0x308, 0x231A }, 3, 0x4 }, + { { 0x1160, 0x300 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x300 }, 3, 0x0 }, + { { 0x1160, 0x900 }, 2, 0x0 }, + { { 0x1160, 0x308, 0x900 }, 3, 0x0 }, + { { 0x1160, 0x94D }, 2, 0x0 }, + { { 0x1160, 0x308, 0x94D }, 3, 0x0 }, + { { 0x1160, 0x200D }, 2, 0x0 }, + { { 0x1160, 0x308, 0x200D }, 3, 0x0 }, + { { 0x1160, 0x378 }, 2, 0x2 }, + { { 0x1160, 0x308, 0x378 }, 3, 0x4 }, + { { 0x11A8, 0x20 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x20 }, 3, 0x4 }, + { { 0x11A8, 0xD }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xD }, 3, 0x4 }, + { { 0x11A8, 0xA }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xA }, 3, 0x4 }, + { { 0x11A8, 0x1 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x1 }, 3, 0x4 }, + { { 0x11A8, 0x200C }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x200C }, 3, 0x0 }, + { { 0x11A8, 0x1F1E6 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x11A8, 0x600 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x600 }, 3, 0x4 }, + { { 0x11A8, 0xA03 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x11A8, 0x1100 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x11A8, 0x1160 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x11A8, 0x11A8 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x11A8, 0xAC00 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x11A8, 0xAC01 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x11A8, 0x903 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x903 }, 3, 0x0 }, + { { 0x11A8, 0x904 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x904 }, 3, 0x4 }, + { { 0x11A8, 0xD4E }, 2, 0x2 }, + { { 0x11A8, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x11A8, 0x915 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x915 }, 3, 0x4 }, + { { 0x11A8, 0x231A }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x231A }, 3, 0x4 }, + { { 0x11A8, 0x300 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x300 }, 3, 0x0 }, + { { 0x11A8, 0x900 }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x900 }, 3, 0x0 }, + { { 0x11A8, 0x94D }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x94D }, 3, 0x0 }, + { { 0x11A8, 0x200D }, 2, 0x0 }, + { { 0x11A8, 0x308, 0x200D }, 3, 0x0 }, + { { 0x11A8, 0x378 }, 2, 0x2 }, + { { 0x11A8, 0x308, 0x378 }, 3, 0x4 }, + { { 0xAC00, 0x20 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x20 }, 3, 0x4 }, + { { 0xAC00, 0xD }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xD }, 3, 0x4 }, + { { 0xAC00, 0xA }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xA }, 3, 0x4 }, + { { 0xAC00, 0x1 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x1 }, 3, 0x4 }, + { { 0xAC00, 0x200C }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x200C }, 3, 0x0 }, + { { 0xAC00, 0x1F1E6 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0xAC00, 0x600 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x600 }, 3, 0x4 }, + { { 0xAC00, 0xA03 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0xA03 }, 3, 0x0 }, + { { 0xAC00, 0x1100 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x1100 }, 3, 0x4 }, + { { 0xAC00, 0x1160 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x1160 }, 3, 0x4 }, + { { 0xAC00, 0x11A8 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0xAC00, 0xAC00 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0xAC00, 0xAC01 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0xAC00, 0x903 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x903 }, 3, 0x0 }, + { { 0xAC00, 0x904 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x904 }, 3, 0x4 }, + { { 0xAC00, 0xD4E }, 2, 0x2 }, + { { 0xAC00, 0x308, 0xD4E }, 3, 0x4 }, + { { 0xAC00, 0x915 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x915 }, 3, 0x4 }, + { { 0xAC00, 0x231A }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x231A }, 3, 0x4 }, + { { 0xAC00, 0x300 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x300 }, 3, 0x0 }, + { { 0xAC00, 0x900 }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x900 }, 3, 0x0 }, + { { 0xAC00, 0x94D }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x94D }, 3, 0x0 }, + { { 0xAC00, 0x200D }, 2, 0x0 }, + { { 0xAC00, 0x308, 0x200D }, 3, 0x0 }, + { { 0xAC00, 0x378 }, 2, 0x2 }, + { { 0xAC00, 0x308, 0x378 }, 3, 0x4 }, + { { 0xAC01, 0x20 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x20 }, 3, 0x4 }, + { { 0xAC01, 0xD }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xD }, 3, 0x4 }, + { { 0xAC01, 0xA }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xA }, 3, 0x4 }, + { { 0xAC01, 0x1 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x1 }, 3, 0x4 }, + { { 0xAC01, 0x200C }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x200C }, 3, 0x0 }, + { { 0xAC01, 0x1F1E6 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0xAC01, 0x600 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x600 }, 3, 0x4 }, + { { 0xAC01, 0xA03 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0xA03 }, 3, 0x0 }, + { { 0xAC01, 0x1100 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x1100 }, 3, 0x4 }, + { { 0xAC01, 0x1160 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x1160 }, 3, 0x4 }, + { { 0xAC01, 0x11A8 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0xAC01, 0xAC00 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0xAC01, 0xAC01 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0xAC01, 0x903 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x903 }, 3, 0x0 }, + { { 0xAC01, 0x904 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x904 }, 3, 0x4 }, + { { 0xAC01, 0xD4E }, 2, 0x2 }, + { { 0xAC01, 0x308, 0xD4E }, 3, 0x4 }, + { { 0xAC01, 0x915 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x915 }, 3, 0x4 }, + { { 0xAC01, 0x231A }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x231A }, 3, 0x4 }, + { { 0xAC01, 0x300 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x300 }, 3, 0x0 }, + { { 0xAC01, 0x900 }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x900 }, 3, 0x0 }, + { { 0xAC01, 0x94D }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x94D }, 3, 0x0 }, + { { 0xAC01, 0x200D }, 2, 0x0 }, + { { 0xAC01, 0x308, 0x200D }, 3, 0x0 }, + { { 0xAC01, 0x378 }, 2, 0x2 }, + { { 0xAC01, 0x308, 0x378 }, 3, 0x4 }, + { { 0x903, 0x20 }, 2, 0x2 }, + { { 0x903, 0x308, 0x20 }, 3, 0x4 }, + { { 0x903, 0xD }, 2, 0x2 }, + { { 0x903, 0x308, 0xD }, 3, 0x4 }, + { { 0x903, 0xA }, 2, 0x2 }, + { { 0x903, 0x308, 0xA }, 3, 0x4 }, + { { 0x903, 0x1 }, 2, 0x2 }, + { { 0x903, 0x308, 0x1 }, 3, 0x4 }, + { { 0x903, 0x200C }, 2, 0x0 }, + { { 0x903, 0x308, 0x200C }, 3, 0x0 }, + { { 0x903, 0x1F1E6 }, 2, 0x2 }, + { { 0x903, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x903, 0x600 }, 2, 0x2 }, + { { 0x903, 0x308, 0x600 }, 3, 0x4 }, + { { 0x903, 0xA03 }, 2, 0x0 }, + { { 0x903, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x903, 0x1100 }, 2, 0x2 }, + { { 0x903, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x903, 0x1160 }, 2, 0x2 }, + { { 0x903, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x903, 0x11A8 }, 2, 0x2 }, + { { 0x903, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x903, 0xAC00 }, 2, 0x2 }, + { { 0x903, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x903, 0xAC01 }, 2, 0x2 }, + { { 0x903, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x903, 0x903 }, 2, 0x0 }, + { { 0x903, 0x308, 0x903 }, 3, 0x0 }, + { { 0x903, 0x904 }, 2, 0x2 }, + { { 0x903, 0x308, 0x904 }, 3, 0x4 }, + { { 0x903, 0xD4E }, 2, 0x2 }, + { { 0x903, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x903, 0x915 }, 2, 0x2 }, + { { 0x903, 0x308, 0x915 }, 3, 0x4 }, + { { 0x903, 0x231A }, 2, 0x2 }, + { { 0x903, 0x308, 0x231A }, 3, 0x4 }, + { { 0x903, 0x300 }, 2, 0x0 }, + { { 0x903, 0x308, 0x300 }, 3, 0x0 }, + { { 0x903, 0x900 }, 2, 0x0 }, + { { 0x903, 0x308, 0x900 }, 3, 0x0 }, + { { 0x903, 0x94D }, 2, 0x0 }, + { { 0x903, 0x308, 0x94D }, 3, 0x0 }, + { { 0x903, 0x200D }, 2, 0x0 }, + { { 0x903, 0x308, 0x200D }, 3, 0x0 }, + { { 0x903, 0x378 }, 2, 0x2 }, + { { 0x903, 0x308, 0x378 }, 3, 0x4 }, + { { 0x904, 0x20 }, 2, 0x2 }, + { { 0x904, 0x308, 0x20 }, 3, 0x4 }, + { { 0x904, 0xD }, 2, 0x2 }, + { { 0x904, 0x308, 0xD }, 3, 0x4 }, + { { 0x904, 0xA }, 2, 0x2 }, + { { 0x904, 0x308, 0xA }, 3, 0x4 }, + { { 0x904, 0x1 }, 2, 0x2 }, + { { 0x904, 0x308, 0x1 }, 3, 0x4 }, + { { 0x904, 0x200C }, 2, 0x0 }, + { { 0x904, 0x308, 0x200C }, 3, 0x0 }, + { { 0x904, 0x1F1E6 }, 2, 0x2 }, + { { 0x904, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x904, 0x600 }, 2, 0x2 }, + { { 0x904, 0x308, 0x600 }, 3, 0x4 }, + { { 0x904, 0xA03 }, 2, 0x0 }, + { { 0x904, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x904, 0x1100 }, 2, 0x2 }, + { { 0x904, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x904, 0x1160 }, 2, 0x2 }, + { { 0x904, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x904, 0x11A8 }, 2, 0x2 }, + { { 0x904, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x904, 0xAC00 }, 2, 0x2 }, + { { 0x904, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x904, 0xAC01 }, 2, 0x2 }, + { { 0x904, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x904, 0x903 }, 2, 0x0 }, + { { 0x904, 0x308, 0x903 }, 3, 0x0 }, + { { 0x904, 0x904 }, 2, 0x2 }, + { { 0x904, 0x308, 0x904 }, 3, 0x4 }, + { { 0x904, 0xD4E }, 2, 0x2 }, + { { 0x904, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x904, 0x915 }, 2, 0x2 }, + { { 0x904, 0x308, 0x915 }, 3, 0x4 }, + { { 0x904, 0x231A }, 2, 0x2 }, + { { 0x904, 0x308, 0x231A }, 3, 0x4 }, + { { 0x904, 0x300 }, 2, 0x0 }, + { { 0x904, 0x308, 0x300 }, 3, 0x0 }, + { { 0x904, 0x900 }, 2, 0x0 }, + { { 0x904, 0x308, 0x900 }, 3, 0x0 }, + { { 0x904, 0x94D }, 2, 0x0 }, + { { 0x904, 0x308, 0x94D }, 3, 0x0 }, + { { 0x904, 0x200D }, 2, 0x0 }, + { { 0x904, 0x308, 0x200D }, 3, 0x0 }, + { { 0x904, 0x378 }, 2, 0x2 }, + { { 0x904, 0x308, 0x378 }, 3, 0x4 }, + { { 0xD4E, 0x20 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x20 }, 3, 0x4 }, + { { 0xD4E, 0xD }, 2, 0x2 }, + { { 0xD4E, 0x308, 0xD }, 3, 0x4 }, + { { 0xD4E, 0xA }, 2, 0x2 }, + { { 0xD4E, 0x308, 0xA }, 3, 0x4 }, + { { 0xD4E, 0x1 }, 2, 0x2 }, + { { 0xD4E, 0x308, 0x1 }, 3, 0x4 }, + { { 0xD4E, 0x200C }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x200C }, 3, 0x0 }, + { { 0xD4E, 0x1F1E6 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0xD4E, 0x600 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x600 }, 3, 0x4 }, + { { 0xD4E, 0xA03 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0xA03 }, 3, 0x0 }, + { { 0xD4E, 0x1100 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x1100 }, 3, 0x4 }, + { { 0xD4E, 0x1160 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x1160 }, 3, 0x4 }, + { { 0xD4E, 0x11A8 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0xD4E, 0xAC00 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0xD4E, 0xAC01 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0xD4E, 0x903 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x903 }, 3, 0x0 }, + { { 0xD4E, 0x904 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x904 }, 3, 0x4 }, + { { 0xD4E, 0xD4E }, 2, 0x0 }, + { { 0xD4E, 0x308, 0xD4E }, 3, 0x4 }, + { { 0xD4E, 0x915 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x915 }, 3, 0x4 }, + { { 0xD4E, 0x231A }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x231A }, 3, 0x4 }, + { { 0xD4E, 0x300 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x300 }, 3, 0x0 }, + { { 0xD4E, 0x900 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x900 }, 3, 0x0 }, + { { 0xD4E, 0x94D }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x94D }, 3, 0x0 }, + { { 0xD4E, 0x200D }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x200D }, 3, 0x0 }, + { { 0xD4E, 0x378 }, 2, 0x0 }, + { { 0xD4E, 0x308, 0x378 }, 3, 0x4 }, + { { 0x915, 0x20 }, 2, 0x2 }, + { { 0x915, 0x308, 0x20 }, 3, 0x4 }, + { { 0x915, 0xD }, 2, 0x2 }, + { { 0x915, 0x308, 0xD }, 3, 0x4 }, + { { 0x915, 0xA }, 2, 0x2 }, + { { 0x915, 0x308, 0xA }, 3, 0x4 }, + { { 0x915, 0x1 }, 2, 0x2 }, + { { 0x915, 0x308, 0x1 }, 3, 0x4 }, + { { 0x915, 0x200C }, 2, 0x0 }, + { { 0x915, 0x308, 0x200C }, 3, 0x0 }, + { { 0x915, 0x1F1E6 }, 2, 0x2 }, + { { 0x915, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x915, 0x600 }, 2, 0x2 }, + { { 0x915, 0x308, 0x600 }, 3, 0x4 }, + { { 0x915, 0xA03 }, 2, 0x0 }, + { { 0x915, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x915, 0x1100 }, 2, 0x2 }, + { { 0x915, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x915, 0x1160 }, 2, 0x2 }, + { { 0x915, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x915, 0x11A8 }, 2, 0x2 }, + { { 0x915, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x915, 0xAC00 }, 2, 0x2 }, + { { 0x915, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x915, 0xAC01 }, 2, 0x2 }, + { { 0x915, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x915, 0x903 }, 2, 0x0 }, + { { 0x915, 0x308, 0x903 }, 3, 0x0 }, + { { 0x915, 0x904 }, 2, 0x2 }, + { { 0x915, 0x308, 0x904 }, 3, 0x4 }, + { { 0x915, 0xD4E }, 2, 0x2 }, + { { 0x915, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x915, 0x915 }, 2, 0x2 }, + { { 0x915, 0x308, 0x915 }, 3, 0x4 }, + { { 0x915, 0x231A }, 2, 0x2 }, + { { 0x915, 0x308, 0x231A }, 3, 0x4 }, + { { 0x915, 0x300 }, 2, 0x0 }, + { { 0x915, 0x308, 0x300 }, 3, 0x0 }, + { { 0x915, 0x900 }, 2, 0x0 }, + { { 0x915, 0x308, 0x900 }, 3, 0x0 }, + { { 0x915, 0x94D }, 2, 0x0 }, + { { 0x915, 0x308, 0x94D }, 3, 0x0 }, + { { 0x915, 0x200D }, 2, 0x0 }, + { { 0x915, 0x308, 0x200D }, 3, 0x0 }, + { { 0x915, 0x378 }, 2, 0x2 }, + { { 0x915, 0x308, 0x378 }, 3, 0x4 }, + { { 0x231A, 0x20 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x20 }, 3, 0x4 }, + { { 0x231A, 0xD }, 2, 0x2 }, + { { 0x231A, 0x308, 0xD }, 3, 0x4 }, + { { 0x231A, 0xA }, 2, 0x2 }, + { { 0x231A, 0x308, 0xA }, 3, 0x4 }, + { { 0x231A, 0x1 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x1 }, 3, 0x4 }, + { { 0x231A, 0x200C }, 2, 0x0 }, + { { 0x231A, 0x308, 0x200C }, 3, 0x0 }, + { { 0x231A, 0x1F1E6 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x231A, 0x600 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x600 }, 3, 0x4 }, + { { 0x231A, 0xA03 }, 2, 0x0 }, + { { 0x231A, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x231A, 0x1100 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x231A, 0x1160 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x231A, 0x11A8 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x231A, 0xAC00 }, 2, 0x2 }, + { { 0x231A, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x231A, 0xAC01 }, 2, 0x2 }, + { { 0x231A, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x231A, 0x903 }, 2, 0x0 }, + { { 0x231A, 0x308, 0x903 }, 3, 0x0 }, + { { 0x231A, 0x904 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x904 }, 3, 0x4 }, + { { 0x231A, 0xD4E }, 2, 0x2 }, + { { 0x231A, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x231A, 0x915 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x915 }, 3, 0x4 }, + { { 0x231A, 0x231A }, 2, 0x2 }, + { { 0x231A, 0x308, 0x231A }, 3, 0x4 }, + { { 0x231A, 0x300 }, 2, 0x0 }, + { { 0x231A, 0x308, 0x300 }, 3, 0x0 }, + { { 0x231A, 0x900 }, 2, 0x0 }, + { { 0x231A, 0x308, 0x900 }, 3, 0x0 }, + { { 0x231A, 0x94D }, 2, 0x0 }, + { { 0x231A, 0x308, 0x94D }, 3, 0x0 }, + { { 0x231A, 0x200D }, 2, 0x0 }, + { { 0x231A, 0x308, 0x200D }, 3, 0x0 }, + { { 0x231A, 0x378 }, 2, 0x2 }, + { { 0x231A, 0x308, 0x378 }, 3, 0x4 }, + { { 0x300, 0x20 }, 2, 0x2 }, + { { 0x300, 0x308, 0x20 }, 3, 0x4 }, + { { 0x300, 0xD }, 2, 0x2 }, + { { 0x300, 0x308, 0xD }, 3, 0x4 }, + { { 0x300, 0xA }, 2, 0x2 }, + { { 0x300, 0x308, 0xA }, 3, 0x4 }, + { { 0x300, 0x1 }, 2, 0x2 }, + { { 0x300, 0x308, 0x1 }, 3, 0x4 }, + { { 0x300, 0x200C }, 2, 0x0 }, + { { 0x300, 0x308, 0x200C }, 3, 0x0 }, + { { 0x300, 0x1F1E6 }, 2, 0x2 }, + { { 0x300, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x300, 0x600 }, 2, 0x2 }, + { { 0x300, 0x308, 0x600 }, 3, 0x4 }, + { { 0x300, 0xA03 }, 2, 0x0 }, + { { 0x300, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x300, 0x1100 }, 2, 0x2 }, + { { 0x300, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x300, 0x1160 }, 2, 0x2 }, + { { 0x300, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x300, 0x11A8 }, 2, 0x2 }, + { { 0x300, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x300, 0xAC00 }, 2, 0x2 }, + { { 0x300, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x300, 0xAC01 }, 2, 0x2 }, + { { 0x300, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x300, 0x903 }, 2, 0x0 }, + { { 0x300, 0x308, 0x903 }, 3, 0x0 }, + { { 0x300, 0x904 }, 2, 0x2 }, + { { 0x300, 0x308, 0x904 }, 3, 0x4 }, + { { 0x300, 0xD4E }, 2, 0x2 }, + { { 0x300, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x300, 0x915 }, 2, 0x2 }, + { { 0x300, 0x308, 0x915 }, 3, 0x4 }, + { { 0x300, 0x231A }, 2, 0x2 }, + { { 0x300, 0x308, 0x231A }, 3, 0x4 }, + { { 0x300, 0x300 }, 2, 0x0 }, + { { 0x300, 0x308, 0x300 }, 3, 0x0 }, + { { 0x300, 0x900 }, 2, 0x0 }, + { { 0x300, 0x308, 0x900 }, 3, 0x0 }, + { { 0x300, 0x94D }, 2, 0x0 }, + { { 0x300, 0x308, 0x94D }, 3, 0x0 }, + { { 0x300, 0x200D }, 2, 0x0 }, + { { 0x300, 0x308, 0x200D }, 3, 0x0 }, + { { 0x300, 0x378 }, 2, 0x2 }, + { { 0x300, 0x308, 0x378 }, 3, 0x4 }, + { { 0x900, 0x20 }, 2, 0x2 }, + { { 0x900, 0x308, 0x20 }, 3, 0x4 }, + { { 0x900, 0xD }, 2, 0x2 }, + { { 0x900, 0x308, 0xD }, 3, 0x4 }, + { { 0x900, 0xA }, 2, 0x2 }, + { { 0x900, 0x308, 0xA }, 3, 0x4 }, + { { 0x900, 0x1 }, 2, 0x2 }, + { { 0x900, 0x308, 0x1 }, 3, 0x4 }, + { { 0x900, 0x200C }, 2, 0x0 }, + { { 0x900, 0x308, 0x200C }, 3, 0x0 }, + { { 0x900, 0x1F1E6 }, 2, 0x2 }, + { { 0x900, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x900, 0x600 }, 2, 0x2 }, + { { 0x900, 0x308, 0x600 }, 3, 0x4 }, + { { 0x900, 0xA03 }, 2, 0x0 }, + { { 0x900, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x900, 0x1100 }, 2, 0x2 }, + { { 0x900, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x900, 0x1160 }, 2, 0x2 }, + { { 0x900, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x900, 0x11A8 }, 2, 0x2 }, + { { 0x900, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x900, 0xAC00 }, 2, 0x2 }, + { { 0x900, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x900, 0xAC01 }, 2, 0x2 }, + { { 0x900, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x900, 0x903 }, 2, 0x0 }, + { { 0x900, 0x308, 0x903 }, 3, 0x0 }, + { { 0x900, 0x904 }, 2, 0x2 }, + { { 0x900, 0x308, 0x904 }, 3, 0x4 }, + { { 0x900, 0xD4E }, 2, 0x2 }, + { { 0x900, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x900, 0x915 }, 2, 0x2 }, + { { 0x900, 0x308, 0x915 }, 3, 0x4 }, + { { 0x900, 0x231A }, 2, 0x2 }, + { { 0x900, 0x308, 0x231A }, 3, 0x4 }, + { { 0x900, 0x300 }, 2, 0x0 }, + { { 0x900, 0x308, 0x300 }, 3, 0x0 }, + { { 0x900, 0x900 }, 2, 0x0 }, + { { 0x900, 0x308, 0x900 }, 3, 0x0 }, + { { 0x900, 0x94D }, 2, 0x0 }, + { { 0x900, 0x308, 0x94D }, 3, 0x0 }, + { { 0x900, 0x200D }, 2, 0x0 }, + { { 0x900, 0x308, 0x200D }, 3, 0x0 }, + { { 0x900, 0x378 }, 2, 0x2 }, + { { 0x900, 0x308, 0x378 }, 3, 0x4 }, + { { 0x94D, 0x20 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x20 }, 3, 0x4 }, + { { 0x94D, 0xD }, 2, 0x2 }, + { { 0x94D, 0x308, 0xD }, 3, 0x4 }, + { { 0x94D, 0xA }, 2, 0x2 }, + { { 0x94D, 0x308, 0xA }, 3, 0x4 }, + { { 0x94D, 0x1 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x1 }, 3, 0x4 }, + { { 0x94D, 0x200C }, 2, 0x0 }, + { { 0x94D, 0x308, 0x200C }, 3, 0x0 }, + { { 0x94D, 0x1F1E6 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x94D, 0x600 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x600 }, 3, 0x4 }, + { { 0x94D, 0xA03 }, 2, 0x0 }, + { { 0x94D, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x94D, 0x1100 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x94D, 0x1160 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x94D, 0x11A8 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x94D, 0xAC00 }, 2, 0x2 }, + { { 0x94D, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x94D, 0xAC01 }, 2, 0x2 }, + { { 0x94D, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x94D, 0x903 }, 2, 0x0 }, + { { 0x94D, 0x308, 0x903 }, 3, 0x0 }, + { { 0x94D, 0x904 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x904 }, 3, 0x4 }, + { { 0x94D, 0xD4E }, 2, 0x2 }, + { { 0x94D, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x94D, 0x915 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x915 }, 3, 0x4 }, + { { 0x94D, 0x231A }, 2, 0x2 }, + { { 0x94D, 0x308, 0x231A }, 3, 0x4 }, + { { 0x94D, 0x300 }, 2, 0x0 }, + { { 0x94D, 0x308, 0x300 }, 3, 0x0 }, + { { 0x94D, 0x900 }, 2, 0x0 }, + { { 0x94D, 0x308, 0x900 }, 3, 0x0 }, + { { 0x94D, 0x94D }, 2, 0x0 }, + { { 0x94D, 0x308, 0x94D }, 3, 0x0 }, + { { 0x94D, 0x200D }, 2, 0x0 }, + { { 0x94D, 0x308, 0x200D }, 3, 0x0 }, + { { 0x94D, 0x378 }, 2, 0x2 }, + { { 0x94D, 0x308, 0x378 }, 3, 0x4 }, + { { 0x200D, 0x20 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x20 }, 3, 0x4 }, + { { 0x200D, 0xD }, 2, 0x2 }, + { { 0x200D, 0x308, 0xD }, 3, 0x4 }, + { { 0x200D, 0xA }, 2, 0x2 }, + { { 0x200D, 0x308, 0xA }, 3, 0x4 }, + { { 0x200D, 0x1 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x1 }, 3, 0x4 }, + { { 0x200D, 0x200C }, 2, 0x0 }, + { { 0x200D, 0x308, 0x200C }, 3, 0x0 }, + { { 0x200D, 0x1F1E6 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x200D, 0x600 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x600 }, 3, 0x4 }, + { { 0x200D, 0xA03 }, 2, 0x0 }, + { { 0x200D, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x200D, 0x1100 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x200D, 0x1160 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x200D, 0x11A8 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x200D, 0xAC00 }, 2, 0x2 }, + { { 0x200D, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x200D, 0xAC01 }, 2, 0x2 }, + { { 0x200D, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x200D, 0x903 }, 2, 0x0 }, + { { 0x200D, 0x308, 0x903 }, 3, 0x0 }, + { { 0x200D, 0x904 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x904 }, 3, 0x4 }, + { { 0x200D, 0xD4E }, 2, 0x2 }, + { { 0x200D, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x200D, 0x915 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x915 }, 3, 0x4 }, + { { 0x200D, 0x231A }, 2, 0x2 }, + { { 0x200D, 0x308, 0x231A }, 3, 0x4 }, + { { 0x200D, 0x300 }, 2, 0x0 }, + { { 0x200D, 0x308, 0x300 }, 3, 0x0 }, + { { 0x200D, 0x900 }, 2, 0x0 }, + { { 0x200D, 0x308, 0x900 }, 3, 0x0 }, + { { 0x200D, 0x94D }, 2, 0x0 }, + { { 0x200D, 0x308, 0x94D }, 3, 0x0 }, + { { 0x200D, 0x200D }, 2, 0x0 }, + { { 0x200D, 0x308, 0x200D }, 3, 0x0 }, + { { 0x200D, 0x378 }, 2, 0x2 }, + { { 0x200D, 0x308, 0x378 }, 3, 0x4 }, + { { 0x378, 0x20 }, 2, 0x2 }, + { { 0x378, 0x308, 0x20 }, 3, 0x4 }, + { { 0x378, 0xD }, 2, 0x2 }, + { { 0x378, 0x308, 0xD }, 3, 0x4 }, + { { 0x378, 0xA }, 2, 0x2 }, + { { 0x378, 0x308, 0xA }, 3, 0x4 }, + { { 0x378, 0x1 }, 2, 0x2 }, + { { 0x378, 0x308, 0x1 }, 3, 0x4 }, + { { 0x378, 0x200C }, 2, 0x0 }, + { { 0x378, 0x308, 0x200C }, 3, 0x0 }, + { { 0x378, 0x1F1E6 }, 2, 0x2 }, + { { 0x378, 0x308, 0x1F1E6 }, 3, 0x4 }, + { { 0x378, 0x600 }, 2, 0x2 }, + { { 0x378, 0x308, 0x600 }, 3, 0x4 }, + { { 0x378, 0xA03 }, 2, 0x0 }, + { { 0x378, 0x308, 0xA03 }, 3, 0x0 }, + { { 0x378, 0x1100 }, 2, 0x2 }, + { { 0x378, 0x308, 0x1100 }, 3, 0x4 }, + { { 0x378, 0x1160 }, 2, 0x2 }, + { { 0x378, 0x308, 0x1160 }, 3, 0x4 }, + { { 0x378, 0x11A8 }, 2, 0x2 }, + { { 0x378, 0x308, 0x11A8 }, 3, 0x4 }, + { { 0x378, 0xAC00 }, 2, 0x2 }, + { { 0x378, 0x308, 0xAC00 }, 3, 0x4 }, + { { 0x378, 0xAC01 }, 2, 0x2 }, + { { 0x378, 0x308, 0xAC01 }, 3, 0x4 }, + { { 0x378, 0x903 }, 2, 0x0 }, + { { 0x378, 0x308, 0x903 }, 3, 0x0 }, + { { 0x378, 0x904 }, 2, 0x2 }, + { { 0x378, 0x308, 0x904 }, 3, 0x4 }, + { { 0x378, 0xD4E }, 2, 0x2 }, + { { 0x378, 0x308, 0xD4E }, 3, 0x4 }, + { { 0x378, 0x915 }, 2, 0x2 }, + { { 0x378, 0x308, 0x915 }, 3, 0x4 }, + { { 0x378, 0x231A }, 2, 0x2 }, + { { 0x378, 0x308, 0x231A }, 3, 0x4 }, + { { 0x378, 0x300 }, 2, 0x0 }, + { { 0x378, 0x308, 0x300 }, 3, 0x0 }, + { { 0x378, 0x900 }, 2, 0x0 }, + { { 0x378, 0x308, 0x900 }, 3, 0x0 }, + { { 0x378, 0x94D }, 2, 0x0 }, + { { 0x378, 0x308, 0x94D }, 3, 0x0 }, + { { 0x378, 0x200D }, 2, 0x0 }, + { { 0x378, 0x308, 0x200D }, 3, 0x0 }, + { { 0x378, 0x378 }, 2, 0x2 }, + { { 0x378, 0x308, 0x378 }, 3, 0x4 }, + { { 0xD, 0xA, 0x61, 0xA, 0x308 }, 5, 0x1c }, + { { 0x61, 0x308 }, 2, 0x0 }, + { { 0x20, 0x200D, 0x646 }, 3, 0x4 }, + { { 0x646, 0x200D, 0x20 }, 3, 0x4 }, + { { 0x1100, 0x1100 }, 2, 0x0 }, + { { 0xAC00, 0x11A8, 0x1100 }, 3, 0x4 }, + { { 0xAC01, 0x11A8, 0x1100 }, 3, 0x4 }, + { { 0x1F1E6, 0x1F1E7, 0x1F1E8, 0x62 }, 4, 0xc }, + { { 0x61, 0x1F1E6, 0x1F1E7, 0x1F1E8, 0x62 }, 5, 0x1a }, + { { 0x61, 0x1F1E6, 0x1F1E7, 0x200D, 0x1F1E8, 0x62 }, 6, 0x32 }, + { { 0x61, 0x1F1E6, 0x200D, 0x1F1E7, 0x1F1E8, 0x62 }, 6, 0x2a }, + { { 0x61, 0x1F1E6, 0x1F1E7, 0x1F1E8, 0x1F1E9, 0x62 }, 6, 0x2a }, + { { 0x61, 0x200D }, 2, 0x0 }, + { { 0x61, 0x308, 0x62 }, 3, 0x4 }, + { { 0x61, 0x903, 0x62 }, 3, 0x4 }, + { { 0x61, 0x600, 0x62 }, 3, 0x2 }, + { { 0x1F476, 0x1F3FF, 0x1F476 }, 3, 0x4 }, + { { 0x61, 0x1F3FF, 0x1F476 }, 3, 0x4 }, + { { 0x61, 0x1F3FF, 0x1F476, 0x200D, 0x1F6D1 }, 5, 0x4 }, + { { 0x1F476, 0x1F3FF, 0x308, 0x200D, 0x1F476, 0x1F3FF }, 6, 0x0 }, + { { 0x1F6D1, 0x200D, 0x1F6D1 }, 3, 0x0 }, + { { 0x61, 0x200D, 0x1F6D1 }, 3, 0x4 }, + { { 0x2701, 0x200D, 0x2701 }, 3, 0x0 }, + { { 0x61, 0x200D, 0x2701 }, 3, 0x4 }, + { { 0x915, 0x924 }, 2, 0x2 }, + { { 0x915, 0x94D, 0x924 }, 3, 0x0 }, + { { 0x915, 0x94D, 0x94D, 0x924 }, 4, 0x0 }, + { { 0x915, 0x94D, 0x200D, 0x924 }, 4, 0x0 }, + { { 0x915, 0x93C, 0x200D, 0x94D, 0x924 }, 5, 0x0 }, + { { 0x915, 0x93C, 0x94D, 0x200D, 0x924 }, 5, 0x0 }, + { { 0x915, 0x94D, 0x924, 0x94D, 0x92F }, 5, 0x0 }, + { { 0x915, 0x94D, 0x61 }, 3, 0x4 }, + { { 0x61, 0x94D, 0x924 }, 3, 0x4 }, + { { 0x3F, 0x94D, 0x924 }, 3, 0x4 }, + { { 0x915, 0x94D, 0x94D, 0x924 }, 4, 0x0 }, +}; diff --git a/tests/precompiled_test.cpp b/tests/precompiled_test.cpp new file mode 100644 index 00000000..5b3b85b3 --- /dev/null +++ b/tests/precompiled_test.cpp @@ -0,0 +1,103 @@ +/* precompiled_test.cpp -- extended grapheme clusters and SentencePiece's precompiled normaliser + * (core/text/tokenizer_grapheme.h) against Unicode's own test file and HuggingFace tokenizers' + * Precompiled normaliser (goldens: mk_precompiled_goldens.py). */ +#include "rad_test.h" +#include "text/tokenizer.h" +#include "text/tokenizer_grapheme.h" + +#include "precompiled_golden.h" + +#include +#include + +using namespace rad; + +/* Every case of Unicode 16.0.0's GraphemeBreakTest.txt: the clusters grapheme_end walks out of the + * sequence start where the file breaks it. */ +TEST(grapheme_clusters_follow_uax29) { + int bad = 0; + for (const GbCase& g : kGbCases) { + uint32_t starts = 0; + for (size_t i = 0; i < g.n;) { + if (i) starts |= 1u << i; + const size_t e = grapheme_end(g.cp, g.n, i); + if (e <= i || e > g.n) { ++bad; break; } + i = e; + } + if (starts != g.starts) { + if (++bad <= 5) { + std::string s; + for (uint32_t k = 0; k < g.n; ++k) s += fmt(" %04X", g.cp[k]); + fprintf(stderr, " [%s ] starts 0x%x, want 0x%x\n", s.c_str(), starts, g.starts); + } + } + } + CHECK_EQ(bad, 0); + CHECK(sizeof kGbCases / sizeof kGbCases[0] > 1000); +} + +/* A cluster under six bytes goes whole to its shortest mapped prefix's replacement (a combining + * accent after a mapped letter is dropped); otherwise each character goes to its own. */ +TEST(precompiled_normaliser_matches_tokenizers) { + PrecompiledMap pm; + std::string why; + REQUIRE_EQ(pm.load(kPcCharsmap, &why), (int)RAD_OK); + for (const PcCase& c : kPcCases) { + const std::string got = pm.normalize(c.in); + if (got != c.out) fprintf(stderr, " '%s' -> '%s', want '%s'\n", c.in, got.c_str(), c.out); + CHECK(got == c.out); + } +} + +TEST(precompiled_map_refuses_what_does_not_decode) { + PrecompiledMap pm; + std::string why; + CHECK_EQ(pm.load("not base64!", &why), RAD_E_FORMAT); + CHECK_EQ(pm.load("AAA=", &why), RAD_E_FORMAT); + /* A trie byte count past the map's end. */ + CHECK_EQ(pm.load("AAEAAA==", &why), RAD_E_FORMAT); + CHECK(!pm.ready()); +} + +/* The normaliser inside a Unigram vocabulary, as T5's tokenizer.json declares it: Precompiled, + * a right Strip and a Replace of space runs, then Metaspace. With no tokenizer_config.json beside + * it the end token's id is unset, so encoding adds none (HuggingFace's ids: the same pieces, then + * ). */ +TEST(precompiled_runs_in_a_tokenizer_json_chain) { + const std::string json = std::string(R"({ + "version": "1.0", "added_tokens": [ + {"id": 0, "content": "", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}, + {"id": 1, "content": "", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}, + {"id": 2, "content": "", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}], + "normalizer": {"type": "Sequence", "normalizers": [ + {"type": "Precompiled", "precompiled_charsmap": ")") + kPcCharsmap + R"("}, + {"type": "Strip", "strip_left": false, "strip_right": true}, + {"type": "Replace", "pattern": {"Regex": " {2,}"}, "content": "▁"}]}, + "pre_tokenizer": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "first", "split": true}, + "post_processor": {"type": "TemplateProcessing", + "single": [{"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "", "type_id": 0}}], + "pair": [{"Sequence": {"id": "A", "type_id": 0}}, {"SpecialToken": {"id": "", "type_id": 0}}], + "special_tokens": {"": {"id": "", "ids": [1], "tokens": [""]}}}, + "decoder": {"type": "Metaspace", "replacement": "▁", "prepend_scheme": "always", "split": true}, + "model": {"type": "Unigram", "unk_id": 2, "vocab": [ + ["", 0.0], ["", 0.0], ["", 0.0], ["▁", -2.0], ["▁a", -3.0], ["a", -4.0], + ["▁big", -3.0], ["b", -5.0], ["i", -5.0], ["g", -5.0], ["▁apple", -3.0], ["p", -5.0], + ["l", -5.0], ["e", -5.0], ["é", -5.0], ["▁café", -3.0], ["c", -5.0], ["f", -5.0]]} + })"; + VocabBuild vb; + REQUIRE_EQ(parse_tokenizer_json_buf(json, "t5-like", vb), (int)RAD_OK); + auto v = std::make_shared(); + REQUIRE_EQ(v->load(std::move(vb)), (int)RAD_OK); + Tokenizer tok; + REQUIRE_EQ(tok.init(v), (int)RAD_OK); + std::vector ids; + REQUIRE_EQ(tok.encode("A big Apple", ids, true, true), (int)RAD_OK); + CHECK(ids == std::vector({ 4, 6, 10 })); + ids.clear(); + /* The fullwidth A normalises to an A the vocabulary lacks, and the decomposed accent to the + * piece it holds. */ + REQUIRE_EQ(tok.encode("\xef\xbc\xa1 cafe\xcc\x81", ids, true, true), (int)RAD_OK); + CHECK(ids == std::vector({ 3, 2, 15 })); +} + +RAD_TEST_MAIN() diff --git a/tests/r4d_emu/test_lora.cpp b/tests/r4d_emu/test_lora.cpp index 5440bb25..6f398751 100644 --- a/tests/r4d_emu/test_lora.cpp +++ b/tests/r4d_emu/test_lora.cpp @@ -511,6 +511,74 @@ static void test_codes() { checked); } +/* lora_expand_mm (the generators' expand): t rounded to bf16 and summed on the WMMA in its own + * order, so each output is held to the double sum over bf16(t) within one rounding of y plus the + * f32 sum's bound; base rows and everything outside the slice untouched, bit for bit. Mixed slots + * in a tile, an odd M and N, R not a multiple of 32, every y dtype, aligned and not. */ +static void test_expand_mm() { + std::mt19937 rng(41); + struct Sh { int M, N, R, S; uint32_t ydt; bool al; int base_pct; }; + const Sh shapes[] = { + { 1, 20, 16, 1, RAD_BF16, true, 0 }, + { 64, 64, 32, 1, RAD_BF16, true, 0 }, + { 130, 300, 48, 2, RAD_BF16, false, 20 }, + { 77, 9216, 192, 1, RAD_BF16, true, 0 }, /* a fused qkv, one adapter */ + { 200, 1000, 64, 3, RAD_F32, false, 30 }, + { 65, 257, 24, 2, RAD_F16, true, 10 }, + { 512, 2048, 128, 1, RAD_BF16, true, 0 }, + }; + int64_t worst_n = 0; + double worst = 0; + for (const Sh& sh : shapes) { + const std::vector slot = rand_slots(rng, sh.M, sh.S, sh.base_pct); + Expand E = make_expand(rng, sh.M, sh.N, sh.R, sh.S, sh.ydt, slot, sh.al); + std::vector got; + if (run_expand(E, r4d_rad_lora_expand_mm, &got) != RAD_OK) { + fail("expand_mm", fmt("rc (M %d N %d R %d)", sh.M, sh.N, sh.R)); + continue; + } + const size_t e = esz(sh.ydt), ny = (size_t)E.yoff + (size_t)sh.M * E.ldy; + int64_t bad_base = 0, bad_val = 0; + for (size_t i = 0; i < ny; ++i) { + const long long q = (long long)i - E.yoff; + const int m = q < 0 ? -1 : (int)(q / E.ldy), n = q < 0 ? -1 : (int)(q % E.ldy); + const int sl = m >= 0 && m < sh.M ? slot[(size_t)m] : -1; + if (m < 0 || m >= sh.M || n >= sh.N || sl < 0 || sl >= sh.S) { + bad_base += std::memcmp(&got[i * e], &E.y0[i * e], e) != 0; + continue; + } + double acc = 0, terms = 0; + for (int j = 0; j < sh.R; ++j) { + const double tv = rad_bf16_to_f32(rad_f32_to_bf16(E.t[(size_t)m * sh.R + j])); + const double bv = rad_bf16_to_f32(E.lb[((size_t)sl * sh.N + n) * sh.R + j]); + acc += tv * bv; + terms += std::fabs(tv * bv); + } + const double sc = E.sc[(size_t)sl * sh.N + n]; + const double y0 = lora_cases::get(sh.ydt, E.y0.data(), i); + const double want = y0 + sc * acc; + const double g = lora_cases::get(sh.ydt, got.data(), i); + if (std::isnan(y0)) { bad_val += !std::isnan(g); continue; } + const double ulp = sh.ydt == RAD_BF16 ? std::ldexp(1.0, -8) + : sh.ydt == RAD_F16 ? std::ldexp(1.0, -10) : std::ldexp(1.0, -23); + const double tol = std::fabs(want) * ulp + sc * terms * (sh.R + 2) * std::ldexp(1.0, -24) + + 1e-30; + const double r = std::fabs(g - want) / tol; + worst = std::max(worst, r); + if (r > 1.0) ++bad_val; + ++worst_n; + } + if (bad_base) + fail("expand_mm", fmt("touched %lld base-row / outside bytes (M %d N %d R %d %s)", + (long long)bad_base, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt))); + if (bad_val) + fail("expand_mm", fmt("%lld outputs outside the bound (M %d N %d R %d %s)", + (long long)bad_val, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt))); + } + std::printf("lora expand_mm: %zu shapes, %lld outputs, worst |err|/bound %.3f\n", + sizeof(shapes) / sizeof(shapes[0]), (long long)worst_n, worst); +} + int main() { LaunchFn rs = nullptr, re = nullptr; load_libref(&rs, &re); @@ -532,6 +600,7 @@ int main() { test_invariance(); test_all_base(); test_codes(); + test_expand_mm(); std::printf("lora tiled rows: %d failure(s)\n", g_fails); return (T.fails != 0 || g_fails != 0) ? 1 : 0; } diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 052f5835..844b5be8 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -939,7 +939,7 @@ TEST(op_vocabulary) { "dequant", "gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed", /* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */ - "lora_shrink", "lora_expand", + "lora_shrink", "lora_expand", "lora_expand_mm", "grid_embed_aa", "attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key", /* The rest of the QSA indexer and DFlash2's convolution: not fusions, so a model that @@ -958,9 +958,12 @@ TEST(op_vocabulary) { /* The image generator's (arch/qwenimage21): a DiT's modulation and gates, the per-lane * sampler state, the VAE's convolutions and shortcuts, attention over a cached prefix. */ "ln_mod", "gate_add", "timestep_embed", "gather_rows2", "lane_gather", "lane_store", - "randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "l2norm_chan", "d2s_add", - "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self", + "randn_lanes", "flow_euler", "chan_affine", "conv2d_nhwc", "im2col_nhwc", "l2norm_chan", + "d2s_add", "s2d_avg_add", "to_rgba8", "gelu_tanh", "scatter_add_rows", "attn_prefix_self", "ln_mod_quant_fp8", + /* SDXL's (arch/sdxl): CLIP-L's activation and the k-diffusion sampler over a + * discrete-time denoiser. */ + "gelu_quick", "kd_input", "kd_step", /* The music generator's (arch/minimaxmusic3): the codec's convolutions and activation, the * guided frame sampler and the frame embeddings, the window states of the latent * denoiser, and the index helpers that feed them. */ @@ -5554,6 +5557,136 @@ TEST(flow_euler_guides_previews_and_repaints_as_stated) { CHECK_EQ(state.at(8), 7.0f); CHECK_EQ(state.at(9), 8.0f); } +/* kd_input: entry 0's first step fills its lane with the seed's stream times sqrt(1 + sigma^2) + * and writes x / sqrt(sigma^2 + 1) to its rows and its pair's (entry 1, pair -2, writes nothing of + * its own); entry 2 reads its lane as it is. */ +TEST(kd_input_starts_the_lane_and_scales_by_c_in) { + const int64_t n = 2, st = 2; + const uint64_t seed = 0xabcdef12345ull; + T sg(RAD_F32, {3}); sg.f({3, 3, 1}); + T pair(RAD_I32, {3}); pair.n({1, -2, -1}); + T lane(RAD_I32, {3}); lane.n({0, 1, 2}); + T fl(RAD_I32, {3}); fl.n({1, 0, 0}); + T sd(RAD_U32, {3, 2}); sd.n({(int64_t)(seed & 0xffffffffu), (int64_t)(seed >> 32), 0, 0, 5, 0}); + T cu(RAD_I32, {4}); cu.n({0, 2, 4, 5}); + T state(RAD_F32, {3 * st, n}); state.f({0, 0, 0, 0, 7, 7, 7, 7, 4, -2, 9, 9}); + T y(RAD_F32, {5, n}); + A a; a.t(sg).t(pair).t(lane).t(fl).t(sd).t(cu).t(state).t(y).i("M", 5).i("n", n) + .i("stride", st).s("dtype", "f32"); + CHECK_OK(run("kd_input", a)); + const float init = std::sqrt(1.0f + 9.0f), cin = 1.0f / std::sqrt(9.0f + 1.0f); + for (int64_t k = 0; k < 2; ++k) + for (int64_t c = 0; c < n; ++c) { + const float x0 = rad_philox_normal(seed, (uint64_t)(k * n + c)) * init; + CHECK_EQ(state.at(k * n + c), x0); + CHECK_EQ(y.at(k * n + c), x0 * cin); + CHECK_EQ(y.at((2 + k) * n + c), x0 * cin); + CHECK_EQ(state.at((st + k) * n + c), 7.0f); /* the parked entry's lane */ + } + CHECK_NEAR(y.at(8), 4.0f / std::sqrt(2.0f), 1e-6); CHECK_NEAR(y.at(9), -2.0f / std::sqrt(2.0f), 1e-6); + /* A repaint is refused. */ + T fl2(RAD_I32, {3}); fl2.n({2, 0, 0}); + A b; b.t(sg).t(pair).t(lane).t(fl2).t(sd).t(cu).t(state).t(y).i("M", 5).i("n", n) + .i("stride", st).s("dtype", "f32"); + CHECK_EQ(run("kd_input", b), RAD_E_UNSUPPORTED); +} + +/* kd_step, one element an entry: Euler guided against a parked entry with a preview; Euler + * ancestral at sigma_next 0 and above it; DPM++ 2M's first step, its second-order step and its + * last step; and a v-prediction model. */ +TEST(kd_step_denoises_guides_and_steps_each_sampler) { + const int64_t n = 1, st = 1; + /* entry: 0 euler guided, 1 parked, 2 ancestral to 0, 3 ancestral, 4 dpm first, 5 dpm second, + * 6 dpm last */ + T o(RAD_F32, {7, n}); o.f({0.5f, 0.25f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f}); + T sg(RAD_F32, {7}); sg.f({2, 2, 2, 2, 2, 2, 2}); + T sgn(RAD_F32, {7}); sgn.f({1, 1, 0, 1, 1, 1, 0}); + T sgp(RAD_F32, {7}); sgp.f({0, 0, 0, 0, 0, 4, 4}); + T cfg(RAD_F32, {7}); cfg.f({3, 1, 1, 1, 1, 1, 1}); + T pair(RAD_I32, {7}); pair.n({1, -2, -1, -1, -1, -1, -1}); + T lane(RAD_I32, {7}); lane.n({0, 1, 2, 3, 4, 5, 6}); + T fl(RAD_I32, {7}); fl.n({4, 0, 0, 0, 1, 0, 0}); + T sd(RAD_U32, {7, 2}); sd.n({0, 0, 0, 0, 0, 0, 77, 0, 0, 0, 0, 0, 0, 0}); + T smp(RAD_I32, {7}); smp.n({0, 0, 1, 1, 2, 2, 2}); + T stp(RAD_I32, {7}); stp.n({0, 0, 0, 5, 0, 1, 2}); + T cu(RAD_I32, {8}); cu.n({0, 1, 2, 3, 4, 5, 6, 7}); + T state(RAD_F32, {7, n}); state.f({2, 9, 2, 2, 2, 2, 2}); + T hist(RAD_F32, {7, n}); hist.f({0, 0, 0, 0, 0, 0.5f, 0}); + T prev(RAD_F32, {7, n}); + A a; a.t(o).t(sg).t(sgn).t(sgp).t(cfg).t(pair).t(lane).t(fl).t(sd).t(smp).t(stp).t(cu) + .t(state).t(hist).t(prev).i("M", 7).i("n", n).i("stride", st).s("pred", "eps") + .s("dtype", "f32"); + CHECK_OK(run("kd_step", a)); + /* D = x - sigma o: 1 for the positive entry, 1.5 for its negative, guided 1.5 + 3 (1 - 1.5) = + * 0; Euler: x + (1 - 2)(2 - 0) / 2 = 1. */ + CHECK_EQ(prev.at(0), 0.0f); + CHECK_EQ(state.at(0), 1.0f); + CHECK_EQ(hist.at(0), 0.0f); + CHECK_EQ(state.at(1), 9.0f); /* parked */ + CHECK_EQ(state.at(2), 1.0f); /* ancestral to 0: D */ + { + /* sigma_up = min(1, sqrt(1 (4 - 1) / 4)) = sqrt(0.75), sigma_down = sqrt(1 - 0.75). */ + const float sup = std::sqrt(0.75f), sdown = std::sqrt(1.0f - sup * sup); + const float d = (2.0f - 1.0f) / 2.0f; + const float want = 2.0f + d * (sdown - 2.0f) + rad_philox_normal_s(77, 6, 0) * sup; + CHECK_NEAR(state.at(3), want, 1e-6); + } + /* DPM++ 2M: h = ln 2, so x' = x / 2 - expm1(-ln 2) D = 1 + 0.5 D' with D = 1. */ + CHECK_NEAR(state.at(4), 1.5f, 1e-6); + /* r = (ln 4 - ln 2) / ln 2 = 1: D' = 1.5 D - 0.5 hist = 1.25. */ + CHECK_NEAR(state.at(5), 1.625f, 1e-6); + CHECK_EQ(state.at(6), 1.0f); /* to sigma 0: D */ + CHECK_EQ(hist.at(5), 1.0f); + + /* v-prediction at sigma 1: D = x / 2 - o / sqrt(2), so o = sqrt(2) at x = 2 gives D = 0, and + * Euler to 0 lands on it. */ + T ov(RAD_F32, {1, 1}); ov.f({std::sqrt(2.0f)}); + T s1(RAD_F32, {1}); s1.f({1}); + T z1(RAD_F32, {1}); z1.f({0}); + T c1(RAD_F32, {1}); c1.f({1}); + T p1(RAD_I32, {1}); p1.n({-1}); + T l1(RAD_I32, {1}); l1.n({0}); + T f1(RAD_I32, {1}); f1.n({0}); + T d1(RAD_U32, {1, 2}); d1.n({0, 0}); + T m1(RAD_I32, {1}); m1.n({0}); + T cu1(RAD_I32, {2}); cu1.n({0, 1}); + T x1(RAD_F32, {1, 1}); x1.f({2}); + T h1(RAD_F32, {1, 1}); + A b; b.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f1).t(d1).t(m1).t(m1).t(cu1).t(x1).t(h1) + .i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32"); + CHECK_OK(run("kd_step", b)); + CHECK_NEAR(x1.at(0), 0.0f, 1e-6); + + /* An unknown sampler is refused, and so is a preview without its operand. */ + T bad(RAD_I32, {1}); bad.n({3}); + A c; c.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f1).t(d1).t(bad).t(m1).t(cu1).t(x1).t(h1) + .i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32"); + CHECK_EQ(run("kd_step", c), RAD_E_UNSUPPORTED); + T f4(RAD_I32, {1}); f4.n({4}); + A d; d.t(ov).t(s1).t(z1).t(z1).t(c1).t(p1).t(l1).t(f4).t(d1).t(m1).t(m1).t(cu1).t(x1).t(h1) + .i("M", 1).i("n", 1).i("stride", 1).s("pred", "v").s("dtype", "f32"); + CHECK_EQ(run("kd_step", d), RAD_E_INVAL); +} + +/* gelu_quick rounds the scaled input and the sigmoid to y's dtype before the product. */ +TEST(gelu_quick_rounds_like_torch_in_bf16) { + T x(RAD_BF16, {1, 3}); x.f({1.0f, -2.0f, 0.375f}); + T y(RAD_BF16, {1, 3}); + A a; a.t(x).t(y).i("M", 1).i("n", 3).s("dtype", "bf16"); + CHECK_OK(run("gelu_quick", a)); + for (int i = 0; i < 3; ++i) { + const float v = x.at(i); + const float t = round_dt(RAD_BF16, 1.702f * v); + const float s = round_dt(RAD_BF16, 1.0f / (1.0f + std::exp(-t))); + CHECK_EQ(y.at(i), round_dt(RAD_BF16, v * s)); + } + T xf(RAD_F32, {1, 1}); xf.f({0.5f}); + T yf(RAD_F32, {1, 1}); + A b; b.t(xf).t(yf).i("M", 1).i("n", 1).s("dtype", "f32"); + CHECK_OK(run("gelu_quick", b)); + CHECK_EQ(yf.at(0), 0.5f * (1.0f / (1.0f + std::exp(-0.851f)))); +} + /* chan_affine: lists are bf16 values; fma is bf16(bf16(x * mul) + add) and inv its inverse. */ TEST(chan_affine_reads_bf16_lists_and_inverts) { T x(RAD_BF16, {1, 3}); x.f({1, 1, 1}); @@ -5628,6 +5761,56 @@ TEST(conv2d_nhwc_pads_and_upsamples) { for (int i = 0; i < 16; ++i) CHECK_EQ(y2.at(i), want[i]); } +/* im2col_nhwc: its rows times the weight read as [cout, cin k k] are conv2d_nhwc, at both paddings + * of a stride-2 conv, the upsample and a 1x1, with x at a row pitch. Small integers keep every sum + * exact, so the two orders of accumulation agree to the bit. */ +TEST(im2col_nhwc_times_the_weight_is_the_convolution) { + struct Case { const char* pad; int64_t cin, cout, k, stride, up, H, W; }; + for (const Case& c : { Case{ "same", 3, 4, 3, 1, 1, 5, 6 }, Case{ "same", 2, 3, 3, 2, 1, 7, 5 }, + Case{ "down", 3, 2, 3, 2, 1, 6, 8 }, Case{ "same", 2, 3, 3, 1, 2, 3, 4 }, + Case{ "same", 5, 2, 1, 1, 1, 4, 3 } }) { + const bool down = !std::strcmp(c.pad, "down"); + const int64_t Hv = c.H * c.up, Wv = c.W * c.up, pads = down ? 1 : 2 * (c.k / 2); + const int64_t Ho = (Hv + pads - c.k) / c.stride + 1, Wo = (Wv + pads - c.k) / c.stride + 1; + const int64_t KK = c.cin * c.k * c.k, ld = c.W * c.cin + 3; + std::vector xv((size_t)(c.H * ld)), wv((size_t)(c.cout * KK)), bv((size_t)c.cout); + for (size_t i = 0; i < xv.size(); ++i) xv[i] = (float)((int)(i * 7 % 11) - 5); + for (size_t i = 0; i < wv.size(); ++i) wv[i] = (float)((int)(i * 5 % 7) - 3); + for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)i - 1.0f; + T xbuf(RAD_F32, {c.H, ld}); xbuf.f(xv); + T x = xbuf; + x.t.shape[1] = c.W * c.cin; /* [H, W cin] at a row pitch of ld */ + T w(RAD_F32, {c.cout, c.cin, c.k, c.k}); w.f(wv); + T w2(RAD_F32, {c.cout, KK}); w2.f(wv); + T b(RAD_F32, {c.cout}); b.f(bv); + T y(RAD_F32, {Ho, Wo * c.cout}); + A a; a.t(x).t(w).t(b).t(y).i("M", Ho * Wo).i("cin", c.cin).i("cout", c.cout).i("k", c.k) + .i("stride", c.stride).s("pad", c.pad).i("up", c.up).s("dtype", "f32"); + CHECK_OK(run("conv2d_nhwc", a)); + T u(RAD_F32, {Ho * Wo, KK}); + A d; d.t(x).t(u).i("M", Ho * Wo).i("cin", c.cin).i("k", c.k).i("stride", c.stride) + .s("pad", c.pad).i("up", c.up).s("dtype", "f32"); + CHECK_OK(run("im2col_nhwc", d)); + T g(RAD_F32, {Ho * Wo, c.cout}); + A e; e.t(u).t(w2).t(b).tnull().t(g).i("M", Ho * Wo).i("N", c.cout).i("K", KK) + .s("dtype", "f32"); + CHECK_OK(run("gemm_nt_bias", e)); + for (int64_t i = 0; i < Ho * Wo * c.cout; ++i) CHECK_EQ(g.at(i), y.at(i)); + /* Spot the column order: (ci, i, j), the weight's own. */ + const int64_t oy = Ho - 1, ox = 0, ci = c.cin - 1, i = c.k - 1, j = 0; + const int64_t iy = oy * c.stride + i - (down ? 0 : c.k / 2); + const int64_t ix = ox * c.stride + j - (down ? 0 : c.k / 2); + const float want = iy < 0 || iy >= Hv || ix < 0 || ix >= Wv + ? 0.0f : xv[(size_t)((iy / c.up) * ld + (ix / c.up) * c.cin + ci)]; + CHECK_EQ(u.at((oy * Wo + ox) * KK + (ci * c.k + i) * c.k + j), want); + } + /* y must be exactly the output pixels. */ + T x(RAD_F32, {3, 3}), y(RAD_F32, {8, 9}); + A a; a.t(x).t(y).i("M", 8).i("cin", 1).i("k", 3).i("stride", 1).s("pad", "same").i("up", 1) + .s("dtype", "f32"); + CHECK_EQ(run("im2col_nhwc", a), RAD_E_SHAPE); +} + /* l2norm_chan: each pixel to unit L2, times sqrt(n), times gamma, then the optional silu; an * all-zero pixel stays zero (the 1e-12 floor). */ TEST(l2norm_chan_normalises_each_pixel) { @@ -7797,6 +7980,7 @@ std::vector geometries() { .s("dtype", "fp8a8")), G("lora_shrink", "M", 3, a.i("M", R).i("K", 40).i("R", 8).i("S", 2).s("dtype", "f32")), G("lora_expand", "M", 3, a.i("M", R).i("N", 20).i("R", 8).i("S", 2).s("dtype", "f32")), + G("lora_expand_mm", "M", 3, a.i("M", R).i("N", 20).i("R", 8).i("S", 2).s("dtype", "f32")), G("attn_paged", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4) .i("causal", 1).i("window", 0).s("q_dtype", "f32") .s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)), @@ -7886,15 +8070,21 @@ std::vector geometries() { G("lane_store", "M", 4, a.i("M", R).i("n", 8).i("stride", 8).s("dtype", "bf16")), G("randn_lanes", "M", 4, a.i("M", R).i("n", 8).i("stride", 4).s("dtype", "bf16")), G("flow_euler", "M", 4, a.i("M", R).i("n", 8).i("stride", 4).s("dtype", "bf16")), + G("kd_input", "M", 4, a.i("M", R).i("n", 4).i("stride", 4).s("dtype", "bf16")), + G("kd_step", "M", 4, a.i("M", R).i("n", 4).i("stride", 4).s("pred", "eps") + .s("dtype", "bf16")), G("chan_affine", "M", 2, a.i("M", R).i("n", 3).s("mul", "1 2 3").s("add", "0 1 2") .s("mode", "fma").s("dtype", "bf16")), G("conv2d_nhwc", "M", 16, a.i("M", R).i("cin", 2).i("cout", 3).i("k", 3).i("stride", 1) .s("pad", "same").i("up", 1).s("dtype", "bf16")), + G("im2col_nhwc", "M", 16, a.i("M", R).i("cin", 2).i("k", 3).i("stride", 1) + .s("pad", "same").i("up", 1).s("dtype", "bf16")), G("l2norm_chan", "M", 3, a.i("M", R).i("n", 8).s("act", "silu").s("dtype", "f32")), G("d2s_add", "M", 16, a.i("M", R).i("cin", 4).i("cout", 2).i("ft", 1).s("dtype", "bf16")), G("s2d_avg_add", "M", 16, a.i("M", R).i("cin", 2).i("cout", 4).i("ft", 1).s("dtype", "bf16")), G("to_rgba8", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("gelu_tanh", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), + G("gelu_quick", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("scatter_add_rows", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("attn_prefix_self", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2) .i("block_size", 4).i("causal", 1).s("q_dtype", "bf16") diff --git a/tests/runtime_test.cpp b/tests/runtime_test.cpp index da6fbd01..20464eea 100644 --- a/tests/runtime_test.cpp +++ b/tests/runtime_test.cpp @@ -918,7 +918,7 @@ TEST(raw_operand_carries_the_pointer_and_refuses_an_offset) { * lora_shrink and lora_expand over its own activation, output and rows, but only on a step that * has an adapter row (RadBatch::lora_slot non-null). A step without one, or a draft pass, issues * the gemm alone, the pass an engine without adapters runs; an encoder pass reaching a site is - * refused by name. */ + * refused by name; a generator pass runs its one slot in every row. */ static int k_gemm (const RadArgs* a, RadStream s) { return record("gemm", a, s); } static int k_shrink(const RadArgs* a, RadStream s) { return record("shrink", a, s); } static int k_expand(const RadArgs* a, RadStream s) { return record("expand", a, s); } @@ -933,6 +933,7 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) { const rad_buf ps = f.add_buffer("lora.scale", RAD_F32, 2, 8, 1536); const rad_buf t0 = f.add_buffer("lora.t0", RAD_F32, 16, 4, 2048); const rad_buf t1 = f.add_buffer("lora.t1", RAD_F32, 16, 4, 2304); + const rad_buf rows = f.add_buffer("lora.rows", RAD_I32, 32, 1, 2560); /* [S * 16] */ const rad_op g = f.add_op("gemm_nt", "M", { 64 }, { k_gemm }, { "gemm" }, &g_gemm_schema, { w }); const rad_op sh = f.add_op("lora_shrink", "M", { 64 }, { k_shrink }, { "shrink" }, nullptr, {}); const rad_op ex = f.add_op("lora_expand", "M", { 64 }, { k_expand }, { "expand" }, nullptr, {}); @@ -955,6 +956,8 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) { scr.R = 4; scr.lane[0] = t0; scr.lane[1] = t1; f.P.lora_t.push_back(scr); + f.P.lora_rows = rows; + f.P.lora_rows_n = 16; CHECK_OK(f.start()); auto body = [&](Ctx& c) { @@ -1002,8 +1005,38 @@ TEST(adapter_ops_follow_a_lora_site_only_on_a_step_with_an_adapter_row) { c.issue(g, opd, 3, RAD_N_BATCH); }); CHECK_EQ(s, RAD_E_UNSUPPORTED); - CHECK(std::strstr(f.ctx.step_error(), "encoder or generator pass") != nullptr); + CHECK(std::strstr(f.ctx.step_error(), "encoder pass") != nullptr); CHECK_EQ(names(), std::string("gemm")); + + /* A generator pass runs one slot in every row, whatever the gemm's rows are: its slot operand + * is that slot's run of the slot-row table; with no slot, the gemm alone. */ + f.batch.enc = 0; + f.batch.gen = RAD_GEN_PASS_DENOISE; + f.batch.lora_slot = nullptr; + f.ctx.set_gen_lora_slot(-1); + g_rec.clear(); + CHECK_OK(f.step(4, 4, body)); + CHECK_EQ(names(), std::string("gemm")); + f.ctx.set_gen_lora_slot(1); + g_rec.clear(); + CHECK_OK(f.step(4, 5, body)); + REQUIRE_EQ(names(), std::string("gemm shrink expand")); + CHECK(g_rec[1].t[2].data == (void*)((char*)f.ctx.buf_ptr(rows) + 1 * 16 * 4)); + CHECK_EQ(g_rec[1].t[2].shape[0], (int64_t)4); + CHECK(g_rec[2].t[1].data == g_rec[1].t[2].data); + /* Rows past the slot table's run are issued in chunks of it, each over its own rows. */ + f.P.lora_rows_n = 3; + g_rec.clear(); + CHECK_OK(f.step(4, 6, body)); + REQUIRE_EQ(names(), std::string("gemm shrink expand shrink expand")); + CHECK_EQ(g_rec[1].t[0].shape[0], (int64_t)3); + CHECK_EQ(g_rec[3].t[0].shape[0], (int64_t)1); + CHECK(g_rec[3].t[0].data == (void*)((char*)g_rec[1].t[0].data + 3 * 4 * 2)); /* x row 3 */ + CHECK(g_rec[4].t[4].data == (void*)((char*)g_rec[2].t[4].data + 3 * 8 * 2)); /* y row 3 */ + CHECK(g_rec[3].t[2].data == (void*)((char*)f.ctx.buf_ptr(rows) + 1 * 3 * 4)); + f.P.lora_rows_n = 16; + f.ctx.set_gen_lora_slot(-1); + f.batch.gen = 0; } /* Site is a property of the weights (spec §5.1). A domain with no kernel in some band is refused, diff --git a/tests/server_fakes.h b/tests/server_fakes.h index 51f183d0..9ccaad88 100644 --- a/tests/server_fakes.h +++ b/tests/server_fakes.h @@ -594,6 +594,14 @@ struct FakeImageGen : IImageGen { } int64_t queued() const override { return 0; } int64_t running() const override { return 0; } + /* The second tokenizer: one id a byte, then 1 (an end token). */ + int encode_aux(const std::string& text, std::vector* out) const override { + if (!inf.aux_tokens) return RAD_E_UNSUPPORTED; + out->clear(); + for (unsigned char c : text) out->push_back(100 + c); + out->push_back(1); + return RAD_OK; + } }; /* An audio generator that finishes every request on submit: `windows` windows of `per_window` diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index 78a8a144..a5a6967b 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -88,13 +88,14 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { CHECK(keys.emplace(std::make_pair(p.arch_id, p.arch_quant), p.name).second); } const std::set> want = { - { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, { "flux3distilled", "" }, + { "anima", "" }, { "breeze", "" }, { "embeddinggemma2", "" }, { "flux3", "" }, + { "flux3distilled", "" }, { "gemma3", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "lfm2", "" }, { "llama", "" }, { "llama", "fp8_e4m3" }, { "qwen35", "" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, { "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" }, - { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" } }; + { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" }, { "sdxl", "" } }; std::set> got; for (const auto& [k, name] : keys) got.insert(k); if (got != want) diff --git a/tests/text_test.cpp b/tests/text_test.cpp index 9e7e9c45..ebbda93d 100644 --- a/tests/text_test.cpp +++ b/tests/text_test.cpp @@ -869,6 +869,40 @@ struct TestStrings : StringSink { }; } /* namespace */ +namespace { + +/* `in` through the .rad's vocab section and back into `out`. */ +int round_trip(const VocabBuild& in, VocabBuild* out) { + TestStrings strings; + std::vector section; + /* Lay the file out as rad-convert does: header, string blob, vocab section. The serialiser + * writes absolute offsets, so the section must know where it lands before it is written, and + * it lands 8-aligned, as the writer places it, because the reader takes the header as a typed + * pointer into the file. */ + const uint64_t str_off = sizeof(RadFileHeader); + RAD_TRY(vocab_serialize(in, strings, 0, section)); /* pass 1: sizes only */ + const uint64_t sec_off = (str_off + strings.blob.size() + 7) & ~(uint64_t)7; + + TestStrings strings2; + section.clear(); + RAD_TRY(vocab_serialize(in, strings2, sec_off, section)); + + std::vector file(sec_off + section.size(), 0); + RadFileHeader* fh = reinterpret_cast(file.data()); + fh->magic = RAD_MAGIC; + fh->version = RAD_FORMAT_VER; + fh->str_off = str_off; + fh->str_bytes = strings2.blob.size(); + fh->vocab_off = sec_off; + fh->vocab_bytes = section.size(); + std::memcpy(file.data() + str_off, strings2.blob.data(), strings2.blob.size()); + std::memcpy(file.data() + sec_off, section.data(), section.size()); + return vocab_deserialize(file.data(), file.size(), + reinterpret_cast(file.data() + sec_off), *out); +} + +} /* namespace */ + TEST(vocab_section_round_trip) { VocabBuild in; in.kind = RAD_TOK_BPE; @@ -885,35 +919,8 @@ TEST(vocab_section_round_trip) { VocabStep s2; s2.kind = RAD_PRE_BYTELEVEL; s2.flags = 2; in.steps.push_back(s2); VocabStep s3; s3.kind = RAD_DEC_BYTELEVEL; in.steps.push_back(s3); - TestStrings strings; - std::vector section; - /* Lay the file out as rad-convert does: header, string blob, vocab section. The serialiser - * writes absolute offsets, so the section must know where it lands before it is written, and - * it lands 8-aligned, as the writer places it, because the reader takes the header as a typed - * pointer into the file. */ - const uint64_t str_off = sizeof(RadFileHeader); - CHECK_OK(vocab_serialize(in, strings, 0, section)); /* pass 1: sizes only */ - const uint64_t sec_off = (str_off + strings.blob.size() + 7) & ~(uint64_t)7; - - TestStrings strings2; - section.clear(); - CHECK_OK(vocab_serialize(in, strings2, sec_off, section)); - - std::vector file(sec_off + section.size(), 0); - RadFileHeader* fh = reinterpret_cast(file.data()); - fh->magic = RAD_MAGIC; - fh->version = RAD_FORMAT_VER; - fh->str_off = str_off; - fh->str_bytes = strings2.blob.size(); - fh->vocab_off = sec_off; - fh->vocab_bytes = section.size(); - std::memcpy(file.data() + str_off, strings2.blob.data(), strings2.blob.size()); - std::memcpy(file.data() + sec_off, section.data(), section.size()); - VocabBuild out; - CHECK_OK(vocab_deserialize(file.data(), file.size(), - reinterpret_cast(file.data() + sec_off), - out)); + CHECK_OK(round_trip(in, &out)); CHECK_EQ(out.kind, in.kind); CHECK(out.tokens == in.tokens); @@ -985,7 +992,7 @@ TEST(parse_tokenizer_json_chain) { * interpreted rather than hashed. */ TEST(parse_tokenizer_json_refuses_unknown_components) { const char* js = R"JSON({ - "normalizer": { "type": "Precompiled", "precompiled_charsmap": "AAAA" }, + "normalizer": { "type": "StripAccents" }, "pre_tokenizer": { "type": "ByteLevel" }, "model": { "type": "BPE", "vocab": {"a": 0}, "merges": [] } })JSON"; @@ -995,7 +1002,7 @@ TEST(parse_tokenizer_json_refuses_unknown_components) { /* A step the tokenizer does not run is refused at load, not passed over on every encode. */ TEST(a_vocab_with_an_unknown_step_does_not_load) { - for (uint32_t kind : { 9u, 39u, 70u, 200u }) { + for (uint32_t kind : { 10u, 41u, 70u, 200u }) { VocabBuild vb; vb.kind = RAD_TOK_BPE; vb.tokens = { "a" }; @@ -1498,7 +1505,7 @@ TEST(decompose_and_compose_are_inverses_over_the_canonical_forms) { namespace { -/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers 0.23.2) */ +/* BEGIN generated by mk_tokenizer_goldens.py (tokenizers 0.23.3) */ struct DecodeGolden { const char* fixture; std::vector ids; const char* text; }; struct PretokGolden { const char* name; const char* json; std::vector ids; }; @@ -1676,6 +1683,49 @@ const std::vector>& metaspace_special_golde return v; } +const char* const kClipLike = R"JSON({"added_tokens": [{"id": 620, "content": "<|startoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "special": true}, {"id": 621, "content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": false, "special": true}], "normalizer": {"type": "Sequence", "normalizers": [{"type": "NFC"}, {"type": "Replace", "pattern": {"Regex": "\\s+"}, "content": " "}, {"type": "Lowercase"}]}, "pre_tokenizer": {"type": "Sequence", "pretokenizers": [{"type": "Split", "pattern": {"Regex": "'s|'t|'re|'ve|'m|'ll|'d|[\\p{L}]+|[\\p{N}]|[^\\s\\p{L}\\p{N}]+"}, "behavior": "Removed", "invert": true}, {"type": "ByteLevel", "add_prefix_space": false, "trim_offsets": true}]}, "post_processor": {"type": "RobertaProcessing", "sep": ["<|endoftext|>", 621], "cls": ["<|startoftext|>", 620], "trim_offsets": false, "add_prefix_space": false}, "decoder": {"type": "ByteLevel", "add_prefix_space": true, "trim_offsets": true}, "model": {"type": "BPE", "dropout": null, "unk_token": "<|endoftext|>", "continuing_subword_prefix": "", "end_of_word_suffix": "", "fuse_unk": false, "vocab": {"!": 0, "\"": 1, "#": 2, "$": 3, "%": 4, "&": 5, "'": 6, "(": 7, ")": 8, "*": 9, "+": 10, ",": 11, "-": 12, ".": 13, "/": 14, "0": 15, "1": 16, "2": 17, "3": 18, "4": 19, "5": 20, "6": 21, "7": 22, "8": 23, "9": 24, ":": 25, ";": 26, "<": 27, "=": 28, ">": 29, "?": 30, "@": 31, "A": 32, "B": 33, "C": 34, "D": 35, "E": 36, "F": 37, "G": 38, "H": 39, "I": 40, "J": 41, "K": 42, "L": 43, "M": 44, "N": 45, "O": 46, "P": 47, "Q": 48, "R": 49, "S": 50, "T": 51, "U": 52, "V": 53, "W": 54, "X": 55, "Y": 56, "Z": 57, "[": 58, "\\": 59, "]": 60, "^": 61, "_": 62, "`": 63, "a": 64, "b": 65, "c": 66, "d": 67, "e": 68, "f": 69, "g": 70, "h": 71, "i": 72, "j": 73, "k": 74, "l": 75, "m": 76, "n": 77, "o": 78, "p": 79, "q": 80, "r": 81, "s": 82, "t": 83, "u": 84, "v": 85, "w": 86, "x": 87, "y": 88, "z": 89, "{": 90, "|": 91, "}": 92, "~": 93, "¡": 94, "¢": 95, "£": 96, "¤": 97, "¥": 98, "¦": 99, "§": 100, "¨": 101, "©": 102, "ª": 103, "«": 104, "¬": 105, "®": 106, "¯": 107, "°": 108, "±": 109, "²": 110, "³": 111, "´": 112, "µ": 113, "¶": 114, "·": 115, "¸": 116, "¹": 117, "º": 118, "»": 119, "¼": 120, "½": 121, "¾": 122, "¿": 123, "À": 124, "Á": 125, "Â": 126, "Ã": 127, "Ä": 128, "Å": 129, "Æ": 130, "Ç": 131, "È": 132, "É": 133, "Ê": 134, "Ë": 135, "Ì": 136, "Í": 137, "Î": 138, "Ï": 139, "Ð": 140, "Ñ": 141, "Ò": 142, "Ó": 143, "Ô": 144, "Õ": 145, "Ö": 146, "×": 147, "Ø": 148, "Ù": 149, "Ú": 150, "Û": 151, "Ü": 152, "Ý": 153, "Þ": 154, "ß": 155, "à": 156, "á": 157, "â": 158, "ã": 159, "ä": 160, "å": 161, "æ": 162, "ç": 163, "è": 164, "é": 165, "ê": 166, "ë": 167, "ì": 168, "í": 169, "î": 170, "ï": 171, "ð": 172, "ñ": 173, "ò": 174, "ó": 175, "ô": 176, "õ": 177, "ö": 178, "÷": 179, "ø": 180, "ù": 181, "ú": 182, "û": 183, "ü": 184, "ý": 185, "þ": 186, "ÿ": 187, "Ā": 188, "ā": 189, "Ă": 190, "ă": 191, "Ą": 192, "ą": 193, "Ć": 194, "ć": 195, "Ĉ": 196, "ĉ": 197, "Ċ": 198, "ċ": 199, "Č": 200, "č": 201, "Ď": 202, "ď": 203, "Đ": 204, "đ": 205, "Ē": 206, "ē": 207, "Ĕ": 208, "ĕ": 209, "Ė": 210, "ė": 211, "Ę": 212, "ę": 213, "Ě": 214, "ě": 215, "Ĝ": 216, "ĝ": 217, "Ğ": 218, "ğ": 219, "Ġ": 220, "ġ": 221, "Ģ": 222, "ģ": 223, "Ĥ": 224, "ĥ": 225, "Ħ": 226, "ħ": 227, "Ĩ": 228, "ĩ": 229, "Ī": 230, "ī": 231, "Ĭ": 232, "ĭ": 233, "Į": 234, "į": 235, "İ": 236, "ı": 237, "IJ": 238, "ij": 239, "Ĵ": 240, "ĵ": 241, "Ķ": 242, "ķ": 243, "ĸ": 244, "Ĺ": 245, "ĺ": 246, "Ļ": 247, "ļ": 248, "Ľ": 249, "ľ": 250, "Ŀ": 251, "ŀ": 252, "Ł": 253, "ł": 254, "Ń": 255, "!": 256, "\"": 257, "#": 258, "$": 259, "%": 260, "&": 261, "'": 262, "(": 263, ")": 264, "*": 265, "+": 266, ",": 267, "-": 268, ".": 269, "/": 270, "0": 271, "1": 272, "2": 273, "3": 274, "4": 275, "5": 276, "6": 277, "7": 278, "8": 279, "9": 280, ":": 281, ";": 282, "<": 283, "=": 284, ">": 285, "?": 286, "@": 287, "A": 288, "B": 289, "C": 290, "D": 291, "E": 292, "F": 293, "G": 294, "H": 295, "I": 296, "J": 297, "K": 298, "L": 299, "M": 300, "N": 301, "O": 302, "P": 303, "Q": 304, "R": 305, "S": 306, "T": 307, "U": 308, "V": 309, "W": 310, "X": 311, "Y": 312, "Z": 313, "[": 314, "\\": 315, "]": 316, "^": 317, "_": 318, "`": 319, "a": 320, "b": 321, "c": 322, "d": 323, "e": 324, "f": 325, "g": 326, "h": 327, "i": 328, "j": 329, "k": 330, "l": 331, "m": 332, "n": 333, "o": 334, "p": 335, "q": 336, "r": 337, "s": 338, "t": 339, "u": 340, "v": 341, "w": 342, "x": 343, "y": 344, "z": 345, "{": 346, "|": 347, "}": 348, "~": 349, "¡": 350, "¢": 351, "£": 352, "¤": 353, "¥": 354, "¦": 355, "§": 356, "¨": 357, "©": 358, "ª": 359, "«": 360, "¬": 361, "®": 362, "¯": 363, "°": 364, "±": 365, "²": 366, "³": 367, "´": 368, "µ": 369, "¶": 370, "·": 371, "¸": 372, "¹": 373, "º": 374, "»": 375, "¼": 376, "½": 377, "¾": 378, "¿": 379, "À": 380, "Á": 381, "Â": 382, "Ã": 383, "Ä": 384, "Å": 385, "Æ": 386, "Ç": 387, "È": 388, "É": 389, "Ê": 390, "Ë": 391, "Ì": 392, "Í": 393, "Î": 394, "Ï": 395, "Ð": 396, "Ñ": 397, "Ò": 398, "Ó": 399, "Ô": 400, "Õ": 401, "Ö": 402, "×": 403, "Ø": 404, "Ù": 405, "Ú": 406, "Û": 407, "Ü": 408, "Ý": 409, "Þ": 410, "ß": 411, "à": 412, "á": 413, "â": 414, "ã": 415, "ä": 416, "å": 417, "æ": 418, "ç": 419, "è": 420, "é": 421, "ê": 422, "ë": 423, "ì": 424, "í": 425, "î": 426, "ï": 427, "ð": 428, "ñ": 429, "ò": 430, "ó": 431, "ô": 432, "õ": 433, "ö": 434, "÷": 435, "ø": 436, "ù": 437, "ú": 438, "û": 439, "ü": 440, "ý": 441, "þ": 442, "ÿ": 443, "Ā": 444, "ā": 445, "Ă": 446, "ă": 447, "Ą": 448, "ą": 449, "Ć": 450, "ć": 451, "Ĉ": 452, "ĉ": 453, "Ċ": 454, "ċ": 455, "Č": 456, "č": 457, "Ď": 458, "ď": 459, "Đ": 460, "đ": 461, "Ē": 462, "ē": 463, "Ĕ": 464, "ĕ": 465, "Ė": 466, "ė": 467, "Ę": 468, "ę": 469, "Ě": 470, "ě": 471, "Ĝ": 472, "ĝ": 473, "Ğ": 474, "ğ": 475, "Ġ": 476, "ġ": 477, "Ģ": 478, "ģ": 479, "Ĥ": 480, "ĥ": 481, "Ħ": 482, "ħ": 483, "Ĩ": 484, "ĩ": 485, "Ī": 486, "ī": 487, "Ĭ": 488, "ĭ": 489, "Į": 490, "į": 491, "İ": 492, "ı": 493, "IJ": 494, "ij": 495, "Ĵ": 496, "ĵ": 497, "Ķ": 498, "ķ": 499, "ĸ": 500, "Ĺ": 501, "ĺ": 502, "Ļ": 503, "ļ": 504, "Ľ": 505, "ľ": 506, "Ŀ": 507, "ŀ": 508, "Ł": 509, "ł": 510, "Ń": 511, "in": 512, "of": 513, "at": 514, "ho": 515, "ing": 516, "st": 517, "ta": 518, "ast": 519, "do": 520, "gi": 521, "hot": 522, "ie": 523, "it": 524, "phot": 525, "ra": 526, "un": 527, "'s": 528, "'t": 529, "ain": 530, "al": 531, "an": 532, "ar": 533, "au": 534, "aint": 535, "ainting": 536, "ali": 537, "alit": 538, "ality": 539, "art": 540, "aste": 541, "astr": 542, "aster": 543, "asterp": 544, "asterpie": 545, "asterpiec": 546, "asterpiece": 547, "astro": 548, "astron": 549, "astronau": 550, "astronaut": 551, "be": 552, "bes": 553, "best": 554, "cat": 555, "de": 556, "di": 557, "ding": 558, "deta": 559, "detai": 560, "detail": 561, "detaile": 562, "detailed": 563, "digi": 564, "digita": 565, "digital": 566, "dog": 567, "don": 568, "er": 569, "et": 570, "gh": 571, "gra": 572, "ghl": 573, "ghly": 574, "gir": 575, "girl": 576, "grap": 577, "graph": 578, "he": 579, "hi": 580, "highly": 581, "hor": 582, "hors": 583, "horse": 584, "iding": 585, "iew": 586, "iewer": 587, "ins": 588, "king": 589, "lo": 590, "lo": 591, "loo": 592, "looking": 593, "masterpiece": 594, "mo": 595, "moun": 596, "mounta": 597, "mountains": 598, "ograph": 599, "olo": 600, "op": 601, "or": 602, "ort": 603, "ortra": 604, "ortrait": 605, "painting": 606, "portrait": 607, "photo": 608, "photograph": 609, "qu": 610, "quality": 611, "riding": 612, "set": 613, "solo": 614, "sun": 615, "stop": 616, "sunset": 617, "the": 618, "viewer": 619, "<|startoftext|>": 620, "<|endoftext|>": 621}, "merges": ["i n", "o f", "a t", "h o", "in g", "s t", "t a", "a st", "d o", "g i", "ho t", "i e", "i t", "p hot", "r a", "u n", "' s", "' t", "a in", "a l", "a n", "a r", "a u", "ain t", "aint ing", "al i", "ali t", "alit y", "ar t", "ast e", "ast r", "aste r", "aster p", "asterp ie", "asterpie c", "asterpiec e", "astr o", "astro n", "astron au", "astronau t", "b e", "be s", "bes t", "c at", "d e", "d i", "d ing", "de ta", "deta i", "detai l", "detail e", "detaile d", "di gi", "digi ta", "digita l", "do g", "do n", "e r", "e t", "g h", "g ra", "gh l", "ghl y", "gi r", "gir l", "gra p", "grap h", "h e", "h i", "hi ghly", "ho r", "hor s", "hors e", "i ding", "ie w", "iew er", "in s", "k ing", "l o", "l o", "lo o", "loo king", "m asterpiece", "m o", "mo un", "moun ta", "mounta ins", "o graph", "o lo", "o p", "o r", "or t", "ort ra", "ortra it", "p ainting", "p ortrait", "phot o", "phot ograph", "q u", "qu ality", "r iding", "s et", "s olo", "s un", "st op", "sun set", "t he", "v iewer"]}})JSON"; + +const std::vector& clip_goldens() { + static const std::vector v = { + { "a photo of a cat", { 320, 608, 513, 320, 555 }, { 620, 320, 608, 513, 320, 555, 621 } }, + { "1girl, solo, masterpiece, best quality, (absurdres:1.2), looking_at_viewer, hatsune_miku", { 272, 576, 267, 614, 267, 594, 267, 554, 611, 267, 263, 64, 65, 82, 84, 81, 67, 81, 68, 338, 281, 272, 269, 273, 8, 267, 593, 318, 514, 318, 619, 267, 71, 64, 83, 615, 324, 318, 76, 72, 74, 340 }, { 620, 272, 576, 267, 614, 267, 594, 267, 554, 611, 267, 263, 64, 65, 82, 84, 81, 67, 81, 68, 338, 281, 272, 269, 273, 8, 267, 593, 318, 514, 318, 619, 267, 71, 64, 83, 615, 324, 318, 76, 72, 74, 340, 621 } }, + { "A Photograph of the Mountains, it's DON'T stop", { 320, 609, 513, 618, 598, 267, 524, 528, 568, 529, 616 }, { 620, 320, 609, 513, 618, 598, 267, 524, 528, 568, 529, 616, 621 } }, + { "1024x1024 2.5 v1.0", { 272, 271, 273, 275, 343, 272, 271, 273, 275, 273, 269, 276, 341, 272, 269, 271 }, { 620, 272, 271, 273, 275, 343, 272, 271, 273, 275, 273, 269, 276, 341, 272, 269, 271, 621 } }, + { "Caf\xc3\xa9 na\xc3\xafve \xe6\x9d\xb1\xe4\xba\xac\xe3\x82\xbf\xe3\x83\xaf\xe3\x83\xbc \xec\x84\x9c\xec\x9a\xb8 \xf0\x9f\x8d\xa3\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7 \xc4\xb0stanbul \xce\xa3\xce\x8a\xce\xa3\xce\xa5\xce\xa6\xce\x9f\xce\xa3", { 66, 64, 69, 127, 358, 77, 64, 127, 107, 85, 324, 162, 251, 109, 160, 118, 105, 159, 224, 123, 159, 225, 107, 159, 225, 376, 168, 226, 250, 168, 248, 372, 172, 253, 235, 96, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 356, 328, 136, 485, 517, 64, 77, 65, 84, 331, 139, 225, 138, 107, 139, 225, 139, 227, 139, 228, 138, 123, 139, 481 }, { 620, 66, 64, 69, 127, 358, 77, 64, 127, 107, 85, 324, 162, 251, 109, 160, 118, 105, 159, 224, 123, 159, 225, 107, 159, 225, 376, 168, 226, 250, 168, 248, 372, 172, 253, 235, 96, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 102, 158, 222, 235, 172, 253, 239, 356, 328, 136, 485, 517, 64, 77, 65, 84, 331, 139, 225, 138, 107, 139, 225, 139, 227, 139, 228, 138, 123, 139, 481, 621 } }, + { " many spaces\t\ttabs\n\nnewlines ", { 76, 64, 77, 344, 82, 79, 64, 66, 68, 338, 518, 65, 338, 77, 68, 86, 75, 512, 68, 338 }, { 620, 76, 64, 77, 344, 82, 79, 64, 66, 68, 338, 518, 65, 338, 77, 68, 86, 75, 512, 68, 338, 621 } }, + { "...!!!??? ((()))[[]]", { 13, 13, 13, 0, 0, 0, 30, 30, 286, 7, 7, 7, 8, 8, 8, 58, 58, 60, 316 }, { 620, 13, 13, 13, 0, 0, 0, 30, 30, 286, 7, 7, 7, 8, 8, 8, 58, 58, 60, 316, 621 } }, + { "", { }, { 620, 621 } }, + { "a", { 320 }, { 620, 320, 621 } }, + { "<|startoftext|>a cat<|endoftext|>", { 620, 320, 555, 621 }, { 620, 620, 320, 555, 621, 621 } }, + { "x<|StartOfText|>y", { 343, 620, 344 }, { 620, 343, 620, 344, 621 } }, + { "ab catcat", { 320, 27, 270, 342, 285, 321, 66, 64, 83, 555 }, { 620, 320, 27, 270, 342, 285, 321, 66, 64, 83, 555, 621 } }, + { "photographphotograph", { 525, 78, 577, 71, 609 }, { 620, 525, 78, 577, 71, 609, 621 } }, + { "it'sit's'll", { 524, 528, 524, 528, 6, 75, 331 }, { 620, 524, 528, 524, 528, 6, 75, 331, 621 } }, + }; + return v; +} + +/* The decode of every CLIP golden with special tokens skipped, as HF reports it. */ +const std::vector& clip_decoded() { + static const std::vector v = { + "aphotoofacat", + "1girl,solo,masterpiece,bestquality,(absurdres:1.2),looking_at_viewer,hatsune_miku", + "aphotographofthemountains,it'sdon'tstop", + "1024x10242.5v1.0", + "caf\xc3\xa9na\xc3\xafve\xe6\x9d\xb1\xe4\xba\xac\xe3\x82\xbf\xe3\x83\xaf\xe3\x83\xbc\xec\x84\x9c\xec\x9a\xb8\xf0\x9f\x8d\xa3\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa9\xe2\x80\x8d\xf0\x9f\x91\xa7i\xcc\x87stanbul\xcf\x83\xce\xaf\xcf\x83\xcf\x85\xcf\x86\xce\xbf\xcf\x83", + "manyspacestabsnewlines", + "...!!!???((()))[[]]", + "", + "a", + "acat", + "xy", + "aw>bcatcat", + "photographphotograph", + "it'sit's'll", + }; + return v; +} + /* END generated by mk_tokenizer_goldens.py */ } /* namespace */ @@ -1794,6 +1844,58 @@ TEST(the_gemma_shaped_tokenizer_encodes_as_huggingface) { CHECK_EQ(k, gemma_decoded().size()); } +/* CLIP's shape (Stable Diffusion's text encoders): an NFC / whitespace-collapse / Lowercase + * normaliser, a Split that keeps letter runs, single digits and punctuation runs, ByteLevel, BPE + * whose word-final symbols carry the "" suffix, RobertaProcessing `<|startoftext|> $A + * <|endoftext|>`, and `<|startoftext|>` matched in the normalised text (so `<|StartOfText|>` is it + * too). Encoded with and without the framing and decoded, against HuggingFace. */ +TEST(the_clip_shaped_tokenizer_encodes_as_huggingface) { + VocabBuild vb; + REQUIRE(parse_tokenizer_json_buf(kClipLike, "clip_like", vb) >= 0); + CHECK(vb.add_bos); + CHECK(vb.add_eos); + CHECK_EQ(vb.bos, 620); + CHECK_EQ(vb.eos, 621); + /* Served as a container holds it: the suffix and the normalised added token are steps. */ + VocabBuild baked; + REQUIRE(round_trip(vb, &baked) == RAD_OK); + auto v = std::make_shared(); + REQUIRE(v->load(std::move(baked)) >= 0); + Tokenizer t; + CHECK_OK(t.init(v)); + size_t k = 0; + for (const EncodeGolden& g : clip_goldens()) { + std::vector plain, special; + CHECK_OK(t.encode(g.text, plain, /*add_special=*/false, /*parse_special=*/true)); + CHECK_OK(t.encode(g.text, special, /*add_special=*/true, /*parse_special=*/true)); + CHECK(plain == g.ids); + /* A text opening with the BOS token gets a second one, as in HuggingFace: CLIP's BOS + * is matched in the normalised text, after Tokenizer::encode decides on adding one. */ + CHECK(special == g.with_special); + if (plain != g.ids) { + std::string got; + for (int32_t id : plain) got += std::to_string(id) + ","; + fprintf(stderr, " \"%s\": %s\n", g.text, got.c_str()); + } + CHECK_EQ(t.decode(g.with_special), std::string(clip_decoded()[k])); + CHECK_EQ(streamed(v, g.with_special), std::string(clip_decoded()[k])); + ++k; + } + CHECK_EQ(k, clip_decoded().size()); + + /* A token matched in the normalised text follows parse_special as the raw ones do, through + * the segment cache as well: the same long text with it off and then on. */ + std::string text; + for (int i = 0; i < 30; ++i) text += "a photo of a cat <|StartOfText|> "; + for (int pass = 0; pass < 2; ++pass) { + std::vector off, on; + CHECK_OK(t.encode(text, off, false, /*parse_special=*/false)); + CHECK_OK(t.encode(text, on, false, /*parse_special=*/true)); + CHECK_EQ(std::count(off.begin(), off.end(), 620), (ptrdiff_t)0); + CHECK_EQ(std::count(on.begin(), on.end(), 620), (ptrdiff_t)30); + } +} + /* Metaspace's "first" scheme prepends the replacement only where the text starts: a segment after * a special token ("[INST]Hi", "Hi") has a non-zero original offset in HuggingFace and gets * none, where "always" gives every segment one. Encoded through the segment cache both cold and @@ -1851,7 +1953,6 @@ TEST(parse_tokenizer_json_refuses_values_it_cannot_honour) { bpe(ws, R"(, "decoder": {"type": "Sequence", "decoders": [{"type": "Fuse"},)" R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0},)" R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0}]})"), - bpe(ws, "", R"(, "end_of_word_suffix": "")"), bpe(ws, "", R"(, "continuing_subword_prefix": "##")"), bpe(ws, "", R"(, "dropout": 0.1)"), bpe(ws, added(R"("single_word": true, "lstrip": false, "rstrip": false, "normalized": false)")), @@ -1878,6 +1979,11 @@ TEST(parse_tokenizer_json_refuses_values_it_cannot_honour) { bpe(ws, R"(, "decoder": {"type": "Sequence", "decoders": [{"type": "Fuse"},)" R"( {"type": "Strip", "content": " ", "start": 1, "stop": 0}]})"), bpe(ws, "", R"(, "dropout": null, "continuing_subword_prefix": null, "end_of_word_suffix": null)"), + bpe(ws, "", R"(, "continuing_subword_prefix": "", "end_of_word_suffix": "")"), + /* Lower case already, so the Lowercase normaliser leaves its spelling alone. */ + bpe(ws, R"(, "normalizer": {"type": "Lowercase"}, "added_tokens": [{"id": 3, "content": "x",)" + R"( "special": true, "single_word": false, "lstrip": false, "rstrip": false,)" + R"( "normalized": true}])"), }; for (const std::string& js : accepted) { VocabBuild vb; diff --git a/tools/gen_grapheme_ucd.py b/tools/gen_grapheme_ucd.py new file mode 100644 index 00000000..c30fcb0f --- /dev/null +++ b/tools/gen_grapheme_ucd.py @@ -0,0 +1,76 @@ +"""gen_grapheme_ucd.py -- writes core/text/tokenizer_grapheme_ucd.cpp, the Unicode properties the +extended grapheme cluster rules (UAX #29) read. + +HuggingFace tokenizers' `Precompiled` normaliser walks its text by extended grapheme clusters +(the unicode-segmentation crate, Unicode 16.0.0), so the cluster boundaries are part of what a +SentencePiece-derived tokenizer.json means. The tables come from the UCD files of that version: + + https://www.unicode.org/Public/16.0.0/ucd/auxiliary/GraphemeBreakProperty.txt + https://www.unicode.org/Public/16.0.0/ucd/emoji/emoji-data.txt + https://www.unicode.org/Public/16.0.0/ucd/DerivedCoreProperties.txt + + python3 tools/gen_grapheme_ucd.py > core/text/tokenizer_grapheme_ucd.cpp +""" +import os +import sys + +GCB = ["Other", "CR", "LF", "Control", "Extend", "ZWJ", "Regional_Indicator", "Prepend", + "SpacingMark", "L", "V", "T", "LV", "LVT"] +INCB = ["None", "Linker", "Consonant", "Extend"] + + +def ranges(path, want): + """(first, last, value) for every line whose property is `want(prop)` (a value or None).""" + out = [] + for line in open(path, encoding="utf-8"): + line = line.split("#", 1)[0].strip() + if not line: + continue + f = [x.strip() for x in line.split(";")] + v = want(f[1:]) + if v is None: + continue + a = f[0].split("..") + lo = int(a[0], 16) + hi = int(a[1], 16) if len(a) > 1 else lo + out.append((lo, hi, v)) + out.sort() + merged = [] + for lo, hi, v in out: + if merged and merged[-1][2] == v and merged[-1][1] + 1 == lo: + merged[-1] = (merged[-1][0], hi, v) + else: + merged.append((lo, hi, v)) + return merged + + +def main(): + d = sys.argv[1] + gcb = ranges(os.path.join(d, "GraphemeBreakProperty.txt"), + lambda f: GCB.index(f[0]) if f[0] in GCB else None) + pict = ranges(os.path.join(d, "emoji-data.txt"), + lambda f: 1 if f[0] == "Extended_Pictographic" else None) + incb = ranges(os.path.join(d, "DerivedCoreProperties.txt"), + lambda f: INCB.index(f[1]) if f[0] == "InCB" and f[1] in INCB else None) + w = sys.stdout.write + w("/* tokenizer_grapheme_ucd.cpp -- GENERATED by tools/gen_grapheme_ucd.py from the Unicode " + "16.0.0 UCD;\n * do not edit. The properties UAX #29's extended grapheme cluster rules read " + "(tokenizer_grapheme.h). */\n") + w('#include "text/tokenizer_grapheme.h"\n\nnamespace rad {\nnamespace ucd {\n\n') + w("const GbRange k_gcb[] = {\n") + for lo, hi, v in gcb: + w(" { 0x%X, 0x%X, %d },\n" % (lo, hi, v)) + w("};\nconst size_t k_gcb_n = sizeof k_gcb / sizeof k_gcb[0];\n\n") + w("const GbRange k_ext_pict[] = {\n") + for lo, hi, v in pict: + w(" { 0x%X, 0x%X, %d },\n" % (lo, hi, v)) + w("};\nconst size_t k_ext_pict_n = sizeof k_ext_pict / sizeof k_ext_pict[0];\n\n") + w("const GbRange k_incb[] = {\n") + for lo, hi, v in incb: + w(" { 0x%X, 0x%X, %d },\n" % (lo, hi, v)) + w("};\nconst size_t k_incb_n = sizeof k_incb / sizeof k_incb[0];\n\n") + w("} /* namespace ucd */\n} /* namespace rad */\n") + + +if __name__ == "__main__": + main() diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index b56b93ca..1b5a282f 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -121,6 +121,13 @@ void usage() { " Declare checks the recipe against the kernels it resolves\n" " --tokenizer F tokenizer.json; its declared chain is baked instead of being\n" " reconstructed from a pre-tokenizer name\n" + " --tokenizer2 F a second tokenizer.json, baked as the container's second vocab:\n" + " a generator that reads its prompt through two tokenizers\n" + " --add FILE one more .safetensors file merged into the checkpoint, its tensor\n" + " names kept: a release shipped as separate single files (a\n" + " diffusion model, a text encoder and a VAE). Repeatable\n" + " --config DIR read config.json, generation_config.json and tokenizer.json from\n" + " DIR, for a single-file checkpoint that ships none of them\n" " --imatrix F llama.cpp imatrix: the expert-popularity profile, the column\n" " importances handed to each quantiser, and the weighting of the\n" " error report\n" @@ -180,6 +187,8 @@ int for_row_pieces(int64_t n, bool parallel, std::string* why, F fn) { int main(int argc, char** argv) { std::string in, out, arch_override, home = rad_home(), tokjson, imat_path, draft_dir; + std::string tokjson2, config_dir; + std::vector add_files; std::vector hierarchy = rad_hierarchy_from_env(); std::vector recipe_files, quant_flags; int64_t max_tok = 8192; @@ -214,6 +223,9 @@ int main(int argc, char** argv) { else if (a == "--home") home = next("--home"); else if (a == "--kernels") hierarchy = rad_split_list(next("--kernels")); else if (a == "--tokenizer") tokjson = next("--tokenizer"); + else if (a == "--tokenizer2") tokjson2 = next("--tokenizer2"); + else if (a == "--add") add_files.push_back(next("--add")); + else if (a == "--config") config_dir = next("--config"); else if (a == "--imatrix") imat_path = next("--imatrix"); else if (a == "--set") { const std::string kv = next("--set"); @@ -331,7 +343,12 @@ int main(int argc, char** argv) { /* ---------------------------------------------------------------- source */ Checkpoint ck; + if (!config_dir.empty()) ck.set_meta_dir(config_dir); if (ck.open(in) < 0) return 1; + for (const std::string& f : add_files) { + if (ck.add_file(f) < 0) return 1; + RAD_INFO("added %s", f.c_str()); + } MetaOwn& meta = ck.meta(); /* Merge the drafter before declare: the architecture plugin declares a draft block only if * `draft.architectures` is present. */ @@ -900,6 +917,17 @@ int main(int argc, char** argv) { w.abort(); return 1; } + if (!tokjson2.empty()) { + VocabBuild vb2; + RAD_INFO("vocab 2 %s", tokjson2.c_str()); + if (parse_tokenizer_json(tokjson2.c_str(), vb2) < 0) { w.abort(); return 1; } + std::vector blob2; + if (vocab_serialize(vb2, sink, 0, blob2) < 0 || + w.set_aux_vocab_section(blob2.data(), (int64_t)blob2.size()) < 0) { + w.abort(); + return 1; + } + } /* ---------------------------------------------------------------- expert profile */ if (im.entries().size()) { diff --git a/tools/rad_info.cpp b/tools/rad_info.cpp index 46d9d948..b76c0d91 100644 --- a/tools/rad_info.cpp +++ b/tools/rad_info.cpp @@ -65,6 +65,8 @@ const char* step_name(uint32_t k) { case RAD_PRE_PUNCTUATION: return "pre.Punctuation"; case RAD_PRE_DIGITS: return "pre.Digits"; case RAD_PRE_BYTE_FALLBACK: return "pre.ByteFallback"; + case RAD_PRE_END_OF_WORD: return "pre.EndOfWordSuffix"; + case RAD_PRE_ADDED_NORMALIZED: return "pre.AddedNormalized"; case RAD_DEC_BYTELEVEL: return "dec.ByteLevel"; case RAD_DEC_METASPACE: return "dec.Metaspace"; case RAD_DEC_REPLACE: return "dec.Replace"; diff --git a/tools/rad_tokcheck.cpp b/tools/rad_tokcheck.cpp index a4911ac6..e5621934 100644 --- a/tools/rad_tokcheck.cpp +++ b/tools/rad_tokcheck.cpp @@ -94,9 +94,11 @@ bool report_diff(const Tokenizer& tok, const char* what, const std::vector 60 ? byte - 60 : 0; + /* The pieces' bytes overshoot the text where a piece spells more than it covers (an + * end-of-word suffix), so the window is clamped to the text. */ + const size_t t0 = std::min(text.size(), byte > 60 ? byte - 60 : 0); std::printf(" text '%s'\n", - printable(text.substr(t0, std::min(120, text.size() - std::min(t0, text.size())))).c_str()); + printable(text.substr(t0, std::min(120, text.size() - t0))).c_str()); return true; } diff --git a/tools/tokref.cpp b/tools/tokref.cpp index 0f513d12..ea26a17d 100644 --- a/tools/tokref.cpp +++ b/tools/tokref.cpp @@ -146,7 +146,11 @@ void apply_norm(std::string& text, const VocabStep& s) { std::vector cpts = unicode_cpts_from_utf8(text); std::string out; out.reserve(text.size()); - for (uint32_t c : cpts) out += unicode_cpt_to_utf8(unicode_tolower(c)); + /* Rust's char::to_lowercase, as HuggingFace runs it: U+0130 is "i" U+0307. */ + for (uint32_t c : cpts) { + if (c == 0x130) out += "i\xcc\x87"; + else out += unicode_cpt_to_utf8(unicode_tolower(c)); + } text.swap(out); break; } From 5f78a1d0cd7b1434af666ae4496c54d53d324762 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 11:45:35 -0500 Subject: [PATCH 066/152] libr4d, arch/gemma4_bf16: at four ranks the 31B's junctions carry the all-reduce in front of them ar_rmsnorm_quant_i8_4rank is the wide family's exact four-rank one-shot with the junction (the residual add, the sandwich norm and the int8 quantiser) as its epilogue, as ar_hc_write_4rank is that one-shot with hc_write. The reduce is the standalone exact all-reduce's arithmetic element by element (fp32 from zero, ranks ascending, one rounding to bf16), so the reduced row matches it to the bit, and the junction is rmsnorm_quant_i8's over that row. It shares the standalone all-reduce's transport and instance and ends the engine's link hold itself, as docs/TP4.md asks of a new collective row. Every block takes one handshake, a system-scope release by its first thread and a system-scope acquire by every wave. Both fences are needed: on 4x R9700 behind an EPYC root complex, dropping either left the readers with stale scratch on nearly every element. `nblocks` 2 and 4 (fewer handshakes, each block owning several rows) are tune points, off by default. r4d_selftest's case of the same name holds every rank's reduced row, residual, output, codes and scales byte for byte to all_reduce followed by rmsnorm_quant_i8 on four cards, at 1, 8, 40 and 97 rows of 5376 and 64 rows of 2816. r4d_selftest is now installed in the image, so a card box can run the rows' checks without a build tree. At four ranks a 31B decode step issued 121 standalone all-reduces, 119 of them followed by a separate norm launch. The plugin now declares ar_rmsnorm_quant_i8_4rank for steps of up to 4 rows (kAr4FoldRows), where it serves every junction but the last layer's feed-forward one: a decode step issues 2 standalone reductions. Taller steps, every speculative verify among them, issue the pair (the all-reduce, then rmsnorm_quant_i8): a one-shot sends three times the message a rank, and at 16 rows the standalone all-reduce's exact two-shot beats the fold's per-row handshakes. On 4x R9700 (the w4a8 container, tp 4, two rounds): plain decode 90 / 90 / 89-90 tok/s against 86 / 87 / 86 for code / prose / story, and 85 against 82 after a 6442-token prompt, +4.7%; a DFlash verify at 16 rows measured 300 tok/s on the pair against 276 on the fold, hence the band. Both paths give the same bytes. Where no library declares the fold, every step issues the pair. Co-Authored-By: Claude Opus 5.5 --- arch/gemma4_bf16/gemma4_bf16.cpp | 62 ++++++-- docs/ARCHITECTURES.md | 13 ++ docs/OPS.md | 8 + libr4d/CMakeLists.txt | 4 + libr4d/r4d.h | 11 ++ libr4d/r4d_ar_entry.hip | 101 ++++++++++--- libr4d/r4d_ar_wide.h | 15 +- libr4d/r4d_plugin.h | 1 + libr4d/r4d_rmsnorm_quant_i8.hip | 174 +++++++++++++++++++++ libr4d/r4d_rows.cpp | 52 ++++++- libr4d/r4d_selftest.cpp | 252 +++++++++++++++++++++++++++++++ tests/arch_test.cpp | 81 ++++++++++ 12 files changed, 737 insertions(+), 37 deletions(-) diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 5a1345a4..a5e4c9bc 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -546,9 +547,25 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai /* ---- one residual junction as one op: [post-norm of the branch `x`, the add into `res`, the * layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). With * `res` null it is the plain norm of `x`, the first block's entry. */ +/* The four-rank fold's band. libr4d's exact all-reduce is a one-shot up to this many elements + * (R4D_AR_WIDE_ONESHOT_MAX_ELEMS) and a two-shot above, and the fused junction at four ranks is + * that one-shot with the junction as its epilogue: three times the message per rank on the link, + * which pays at decode heights and not at a prefill's. So at four ranks op_ar serves the rows a + * one-shot would, 97 at 5376, and a taller step issues the all-reduce and the junction apart. + * + * Within that band the fold pays only at the bottom. On 4x R9700 (2026-10-17, same image) a plain + * decode step (1 row) ran 5.6% slower without it (89 against 94 tok/s), and a DFlash verify + * (16 rows) 9% faster (300 against 276): at 16 rows the standalone all-reduce is the exact + * two-shot, while the fold's one block a row each takes a fenced handshake. The per-row costs + * cross near 4-5 rows, so the fold serves up to kAr4FoldRows rows and a taller step issues the + * pair. */ +static constexpr int64_t kArOneShotElems = 524288; +static constexpr int64_t kAr4FoldRows = 4; + struct G4Junction { rad_op op = 0; - rad_op op_ar = 0; /* the same with the two-rank exact all-reduce of `x` in front, or 0 */ + rad_op op_ar = 0; /* the same with the exact all-reduce of `x` in front, or 0 */ + int64_t ar_rows = 0; /* the most rows op_ar serves: the step's at two ranks, a band at four */ rad_buf x = 0, res = 0, q8 = 0, s8 = 0; rad_weight w = 0, wp = 0, sc = 0; @@ -571,11 +588,16 @@ struct G4Junction { const rad_buf wr[3] = { q8, s8, res }; rad_op_reads (b, op, rd, res ? 2 : 1); rad_op_writes(b, op, wr, res ? 3 : 2); - /* With the all-reduce in front, at two ranks on the exact wire: `x` is then a rank's - * partial sum of a column-sharded linear. With the lossy wire allowed, the standalone - * all-reduce is kept, since it may choose that wire. */ - if (res && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_quant_i8")) { - const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + /* With the all-reduce in front, at two or four ranks on the exact wire: `x` is then a + * rank's partial sum of a column-sharded linear. With the lossy wire allowed, the + * standalone all-reduce is kept, since it may choose that wire. At four ranks the fold is + * the one-shot's and serves only its band (kArOneShotElems, kAr4FoldRows). */ + const bool four = g.world == 4; + const int64_t hi = four ? std::min(kAr4FoldRows, std::min(g.max_tok, kArOneShotElems / g.n_embd)) + : g.max_tok; + if (res && g.wire_exact && (g.world == 2 || four) && hi >= 1 && + rad_op_declared(b, "ar_rmsnorm_quant_i8")) { + const RadParam pa[] = { RAD_RANGE("M", 1, hi), RAD_INT("n", g.n_embd), RAD_F64("eps", g.eps), RAD_INT("world_size", g.world), RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) }; op_ar = rad_decl_op(b, "ar_rmsnorm_quant_i8", pa, (int)(sizeof pa / sizeof pa[0]), ws, nw); @@ -583,6 +605,7 @@ struct G4Junction { const rad_buf wa[4] = { x, q8, s8, res }; rad_op_reads (b, op_ar, rd, 2); rad_op_writes(b, op_ar, wa, 4); + ar_rows = hi; } } return RAD_OK; @@ -1098,6 +1121,7 @@ struct Model { G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */ bool fuse = false; bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */ + int64_t ar_rows = 0; /* ...in a step of at most this many rows (G4Junction::ar_rows) */ }; static Model g_model[MAX_RANKS]; @@ -1320,12 +1344,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } } m.fuse = ok; - bool ar = ok && g.world == 2; + bool ar = ok && (g.world == 2 || g.world == 4); + int64_t rows = g.max_tok; for (int64_t l = 0; ar && l < m.n_main; ++l) { const Layer& lay = m.layers[(size_t)l]; ar = lay.j_am.op_ar != 0 && (l + 1 >= m.n_main || lay.j_ma.op_ar != 0); + if (ar) rows = std::min(rows, lay.j_am.ar_rows); + if (ar && l + 1 < m.n_main) rows = std::min(rows, lay.j_ma.ar_rows); } m.fuse_ar = ar; + m.ar_rows = ar ? rows : 0; } /* ---- the tail: final norm, the sampled rows, the lm_head, and the soft-cap. */ @@ -1385,6 +1413,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.rank, g.world, (long long)g.n_layer, (long long)n_global, (long long)(g.n_layer - n_global), (long long)sliding_win, (long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g); + if (m.fuse && (g.world == 2 || g.world == 4)) { + if (!m.fuse_ar) + rad_note(b, "residual junctions: the all-reduce in front of each issued apart"); + else if (g.world == 4) + rad_note(b, "residual junctions: the all-reduce in front of each folded in at steps of " + "%lld rows or fewer (the four-rank one-shot), issued apart above", + (long long)m.ar_rows); + else + rad_note(b, "residual junctions: the all-reduce in front of each folded in"); + } return RAD_OK; } @@ -1420,15 +1458,17 @@ static void step(RadCtx* c, const RadBatch* batch) { const int64_t T = batch->n_tok; if (m.fuse) m.j0.step(c, T); + /* the junctions carry the reductions in front of them in a step their fold serves */ + const bool far = m.fuse_ar && T <= m.ar_rows; for (size_t li = 0; li < m.layers.size(); ++li) { const Layer& l = m.layers[li]; const bool last = li + 1 == m.layers.size(); - l.attn.step(c, batch, m.fuse, m.fuse, m.fuse_ar); - if (m.fuse) l.j_am.step(c, T, m.fuse_ar); - l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar); + l.attn.step(c, batch, m.fuse, m.fuse, far); + if (m.fuse) l.j_am.step(c, T, far); + l.mlp.step(c, batch, m.fuse, m.fuse && !last, far); if (m.fuse && !last) { /* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */ - l.j_ma.step(c, T, m.fuse_ar); + l.j_ma.step(c, T, far); continue; } /* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after the diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 9c11fd90..5fd529f9 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -698,6 +698,19 @@ the bytes, for 176 MiB per rank more. Drafts are verified, so the coarser logits proposed, never what is accepted; `draft_n_accepted` shows whether they propose worse. Without the copy the head reads the bf16 table, and the startup note names which head is in use. +**The 31B's junctions at four ranks.** At two ranks every junction carries the all-reduce in front +of it (`ar_rmsnorm_quant_i8`). At four it does too, at decode heights. libr4d's +`ar_rmsnorm_quant_i8_4rank` is the exact four-rank one-shot with the junction as its epilogue, +byte-identical to `all_reduce` + `rmsnorm_quant_i8`. A one-shot sends three times the message per +rank, so the plugin declares it only up to 4 rows and issues the pair in a taller step. On 4x +R9700 the fold made plain decode 5.6% faster (94 against 89 tok/s) and a DFlash verify (16 rows) +9% slower (276 against 300), where the standalone all-reduce is the exact two-shot. A decode step +at tp 4 then has two standalone reductions (the embedding's and the last feed-forward's) where it +had 121. It gives the pair's greedy text byte for byte. At sixteen rows of 5376 the junction is +55 us against 22 at one row (--profile-ops): its handshakes, not its bytes, set it. +`r4d_selftest --case ar_rmsnorm_quant_i8_4rank` checks it on four cards, and the startup note says +which form a deployment takes. + **FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up `[1408, 2816]` is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not (the fp8 grouped diff --git a/docs/OPS.md b/docs/OPS.md index 0897ac51..e432d00a 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2122,6 +2122,14 @@ so the gather half writes `y` before it is reduced in place, and the five gather mean what they mean on `moe_gather`. `wire` is `ar_hc_write`'s. On either wire it is byte-identical to the three kernels it replaces. +`ar_rmsnorm_quant_i8` is the exact `all_reduce` of `x` followed by `rmsnorm_quant_i8`'s junction +over the reduced sum, at two ranks and at four. At four it is the exact one-shot's transport with +the junction as its epilogue: a block owns whole rows, and the fold is element by element in the +norm's partition, each element the one-shot's arithmetic (fp32 from zero, ascending rank order, +one rounding to bf16), so it is byte-identical to `all_reduce` + `rmsnorm_quant_i8`. A one-shot +sends (ranks - 1) times the message a rank, so it is for decode heights; above them a caller +issues the pair, whose `all_reduce` goes two-shot. + ## Vocabulary edges | op | params | operands | diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index e8ccd9ad..8efe1975 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -223,6 +223,10 @@ add_executable(r4d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r4d_selftest.cpp) target_link_libraries(r4d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME}) target_include_directories(r4d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) set_target_properties(r4d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +# Installed beside the tools, so the image can run the rows' own card checks without a build tree: +# r4d_selftest /opt/radiance/share/radiance/kernels/libr4d.so [--case ] +# The collective cases need every card of the box in the container. +install(TARGETS r4d_selftest RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) # C++17: at C++20 clang tightens the address-space check on # __builtin_amdgcn_global_load_tr_b128_v8i16 in r4d_common.h. Kernel cost figures are for C++17. diff --git a/libr4d/r4d.h b/libr4d/r4d.h index aa4c8509..adc78ab3 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -747,6 +747,17 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags long sc, int sc_f32, long y, long q, long s, int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks, int drain, int acq); +// ...and at four ranks, on the wide family's transport: r4d_ar_oneshot_4rank_exact's IPC +// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, and +// the engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h). +int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_flags0, long peer_flags1, long peer_flags2, + long my_scratch, long my_flags, long seq_ctrs, + long slot_stride16, long x, long res, long w, long wp, long sc, + int sc_f32, long y, long q, long s, int M, int n, float eps, + float wadd, int w_f32, int r_ld, int y_ld, int rank, + long stream, int nblocks, int drain, int acq, int pub, + long gate, long gate_ctr); // ---- sampling ---------------------------------------------------------------------------------- // diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 7a76627a..4c532109 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -602,11 +602,11 @@ extern "C" int r4d_rad_ar_ln_host_init(const RadParam* p, int n_p, int rank, int return ar_ln_init(p, n_p, rank, world, 1, out); } -/* The four-rank ar_hc_write and ar_gather_hc_write. The key is {rank, 4, bf16, M_hi * n}, shared - * with a standalone all_reduce band only where the bounds agree. Either way is safe on one stream: - * every wide kernel advances the instance's seq counters once per all-reduce and writes only its - * (parity, source) slot (r4d_ar_wide.h), so ops on one instance interleave in any order all ranks - * share. Exact wire only; `wire` 6 is refused. */ +/* The four-rank ar_hc_write, ar_gather_hc_write and ar_rmsnorm_quant_i8 (the norm declares no + * `wire`). The key is {rank, 4, bf16, M_hi * n}, shared with a standalone all_reduce band only where + * the bounds agree. Either way is safe on one stream: every wide kernel advances the instance's seq + * counters once per all-reduce and writes only its (parity, source) slot (r4d_ar_wide.h), so ops on + * one instance interleave in any order all ranks share. Exact wire only; `wire` 6 is refused. */ static int ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, int host, void** out) { if (!out) return RAD_E_INVAL; @@ -1345,18 +1345,22 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { * all-reduce. Width and block count as in ar_rmsnorm_quant_fp8. */ enum { AQ8_X = 0, AQ8_RES, AQ8_W, AQ8_Q, AQ8_S, AQ8_Y, AQ8_WP, AQ8_SC }; -extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { - const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); - if (!in) return RAD_E_STATE; - if (in->world != 2) return RAD_E_SHAPE; - const RadTensor* x = r4d_opt(a, AQ8_X); - const RadTensor* rs = r4d_opt(a, AQ8_RES); - const RadTensor* w = r4d_opt(a, AQ8_W); - const RadTensor* q = r4d_opt(a, AQ8_Q); - const RadTensor* sc = r4d_opt(a, AQ8_S); - const RadTensor* ob = r4d_opt(a, AQ8_Y); - const RadTensor* wp = r4d_opt(a, AQ8_WP); - const RadTensor* sl = r4d_opt(a, AQ8_SC); +/* The operands and their rules, the same at every width. */ +struct ArQ8Args { + const RadTensor *x = nullptr, *rs = nullptr, *w = nullptr, *q = nullptr, *sc = nullptr; + const RadTensor *ob = nullptr, *wp = nullptr, *sl = nullptr; + long long M = 0, K = 0, yp = 0, rp = 0; +}; + +static int ar_q8_args(const RadArgs* a, const ArInst* in, ArQ8Args* o) { + const RadTensor* x = o->x = r4d_opt(a, AQ8_X); + const RadTensor* rs = o->rs = r4d_opt(a, AQ8_RES); + const RadTensor* w = o->w = r4d_opt(a, AQ8_W); + const RadTensor* q = o->q = r4d_opt(a, AQ8_Q); + const RadTensor* sc = o->sc = r4d_opt(a, AQ8_S); + const RadTensor* ob = o->ob = r4d_opt(a, AQ8_Y); + const RadTensor* wp = o->wp = r4d_opt(a, AQ8_WP); + const RadTensor* sl = o->sl = r4d_opt(a, AQ8_SC); if (!x || !w || !q || !sc) return RAD_E_INVAL; if ((wp || sl) && !rs) return RAD_E_INVAL; if (!r4d_contig(w) || (wp && !r4d_contig(wp))) return RAD_E_STRIDE; @@ -1375,6 +1379,18 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { const long long xp = r4d_row_pitch(x), yp = ob ? r4d_row_pitch(ob) : 0, rp = rs ? r4d_row_pitch(rs) : 0; if (xp != K || yp < 0 || rp < 0) return RAD_E_STRIDE; /* x is the message: tight */ if (r4d_geti_or(a, "wire", 0) != 0) return RAD_E_INVAL; + o->M = M; o->K = K; o->yp = yp; o->rp = rp; + return RAD_OK; +} + +extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { + const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); + if (!in) return RAD_E_STATE; + if (in->world != 2) return RAD_E_SHAPE; + ArQ8Args v; + const int arc = ar_q8_args(a, in, &v); + if (arc != RAD_OK) return arc; + const long long M = v.M, K = v.K; R4dArCfg cfgv; r4d_cfg_ar(a, &cfgv); @@ -1385,13 +1401,56 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { if (nblocks < 1) nblocks = 1; const int e = r4d_ar_rmsnorm_quant_i8( in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, - in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(wp), r4d_addr(sl), - sl ? (sl->dtype == RAD_F32) : 0, r4d_addr(ob), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, - (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), w->dtype == RAD_F32, - (int)rp, (int)yp, (long)(uintptr_t)s, nblocks, cfgv.drain, cfgv.acq); + in->slot16, r4d_addr(v.x), r4d_addr(v.rs), r4d_addr(v.w), r4d_addr(v.wp), r4d_addr(v.sl), + v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)M, + (int)K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), + v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (long)(uintptr_t)s, nblocks, cfgv.drain, + cfgv.acq); return e == 0 ? RAD_OK : RAD_E_SHAPE; } +/* The same at four ranks, on the wide family's one-shot transport (r4d_rmsnorm_quant_i8.hip's + * ar_rmsnorm_quant_i8_wide_kernel), the one ar_hc_write_4rank rides, with the junction as its + * epilogue. The operands and the norm's width are the two-rank form's. The block count is one per + * row, capped by the wide family's flag array in the launcher and by the instance here. The + * instance is the four-rank family's {rank, 4, bf16, M_hi * n} (ar_hc_wide_init), so it is a + * standalone all_reduce band's where the two bounds agree, which is safe on one stream for the + * reason that init gives. The plugin issues it only at one-shot heights: each rank sends three + * times the message, which the two-shot the standalone takes above them does not. */ +extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) { + const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); + if (!in) return RAD_E_STATE; + if (in->world != 4) return RAD_E_SHAPE; + if (in->dtype != 0) return RAD_E_DTYPE; + ArQ8Args v; + const int arc = ar_q8_args(a, in, &v); + if (arc != RAD_OK) return arc; + + R4dArCfg cfgv; + r4d_cfg_ar(a, &cfgv); + /* The fence-free forms rest on fine-grained P2P scratch and a store drain; the host mailbox + * (pinned host memory, cached on the way) keeps both fences. */ + if (in->host || cfgv.drain != 3) { + if (cfgv.pub == 2) cfgv.pub = 1; + if (cfgv.acq == 2) cfgv.acq = 0; + } + int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : (int)v.M; + if (nblocks > in->max_blocks) nblocks = in->max_blocks; + /* One handshake, the junction after it local: the release is the one-shot's. */ + const long gate = link_gate(a), early = in->host ? 0L : gate; + const int e = r4d_ar_rmsnorm_quant_i8_4rank( + in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], + in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], + in->my_scratch, in->my_flags, in->my_seq, in->slot16, + r4d_addr(v.x), r4d_addr(v.rs), r4d_addr(v.w), r4d_addr(v.wp), r4d_addr(v.sl), + v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), + (int)v.M, (int)v.K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), + v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (int)in->rank, (long)(uintptr_t)s, nblocks, + cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L); + if (e != 0) return RAD_E_SHAPE; + return early ? RAD_LINK_ENDED : RAD_OK; +} + /* The all-reduce with the gated residual write: `all_reduce` of `y`, then `hc_write` of the reduced * `y` into `h`, in one kernel. A block whose output feeds a hyper-connection write skips its own * collective when this runs. diff --git a/libr4d/r4d_ar_wide.h b/libr4d/r4d_ar_wide.h index ab0d8e93..97089d3c 100644 --- a/libr4d/r4d_ar_wide.h +++ b/libr4d/r4d_ar_wide.h @@ -54,7 +54,9 @@ __device__ __forceinline__ void r4d_ar_drain(int drain) { else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); } // acq: 0 acquire-only fence (global_inv, no writeback half), 1 full threadfence_system, -// 2 none -- fine-grained scratch only. +// 2 none -- fine-grained scratch only. Every thread of the block runs it after the handshake, so at +// 0 or 1 that is one system-scope invalidate a wave. The P2P scratch is fine-grained (the reads +// bypass L2; r4d_ar_entry.hip's allocation says why), so 2 is the documented design there. __device__ __forceinline__ void r4d_ar_acquire(int acq) { if (acq == 1) __threadfence_system(); else if (acq != 2) __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, ""); @@ -74,7 +76,16 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers const int tid = threadIdx.x; if (tid == 0) { if (drain == 2) __threadfence_system(); - if (pub) { + if (pub == 2) { + // No release fence: the flags go out behind the data with nothing written back. Meant for + // a P2P instance with drain 3, on the reasoning that fine-grained scratch stores reach past + // L2. They do not: on 4x R9700 the readers saw stale scratch on nearly every element + // (r4d_selftest, 2026-10-17), so no tuned point selects pub 2 (tArQ84); it is kept only + // as the measured negative. +#pragma unroll + for (int p = 0; p < NPEERS; ++p) + r4d_ar_store_sys_rlx(&peers.flags[p][(size_t)b * WS + rank], val); + } else if (pub) { // One system writeback for the whole publish, then relaxed stores. Per-peer release stores // would add writebacks that order nothing, since the flags go to different peers. __builtin_amdgcn_fence(__ATOMIC_RELEASE, ""); diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 18c7625a..9868aab9 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -461,6 +461,7 @@ int r4d_rad_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream); int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream); +int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs*, RadStream); int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream); int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index 8e9bfc48..30b24824 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -33,6 +33,7 @@ #include "r4d_emit.h" #include "r4d_common.h" #include "r4d_ar_seq.h" +#include "r4d_ar_wide.h" #include namespace { @@ -223,6 +224,97 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( } } +// --------------------------------------------------------------------------------------------- +// The same junction with the four-rank all-reduce in front: the wide family's exact one-shot +// (r4d_ar_oneshot_Nrank_exact.hip) with the junction as its epilogue, as ar_hc_write_4rank is that +// one-shot with hc_write. Up to the reduce it is that one-shot's transport step for step (the same +// seq take over R4D_AR_WIDE_MAX_BLOCKS counters, the same handshake value 2*s, the same (parity, +// source) slots), so it shares an instance with the standalone all_reduce on one stream +// (r4d_ar_wide.h). Two things differ, both for the junction: +// +// * A block owns whole rows, the two-rank fused form's partition, since a post-norm's sum of +// squares closes over one row. Every rank runs the same grid over the same M, so block b's +// words are the same words on every rank and the per-block handshake pairs them. +// * The reduce is element by element in the norm's partition (thread t folds columns t, t+THR, +// ...), so the post-norm's sum of squares is the standalone norm's. Each element is ar_vsum's +// arithmetic exactly: fp32 from 0.0f, the ranks in ascending order, one rounding to bf16 as the +// __hip_bfloat16 cast rounds (bf16_hi_rne_nan). So the reduced row is the standalone exact +// all-reduce's to the bit, and what follows is rmsnorm_quant_i8's junction over it. +// +// In place is safe for the reason the hc_write form gives: a thread reads every source of an element +// before it stores it, its block pushed that element to every peer before the handshake, and no peer +// reads this rank's `x`. +template +__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel( + uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, + signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, + R4DArWidePeers peers, const int4* __restrict__ my_base, + unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, int M, uint32_t n, + float eps, float wadd, uint32_t r_ld, uint32_t y_ld, int slot_stride16, int rank, int drain, + int acq, int pub, long long* gate, unsigned int* gate_ctr) { + constexpr int NPEERS = WS - 1; + extern __shared__ uint16_t ybuf[]; + __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; + __shared__ unsigned int s_seq, s_slot; + const int b = (int)blockIdx.x, nb = (int)gridDim.x; + const uint32_t tid = threadIdx.x; + const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb); + const long long gate_word = r4d_ar_link_word(gate, tid); + + r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); /* device-resident, replay-safe */ + const unsigned int s = s_seq; + const int parity = (int)s_slot; + + /* push my rows into every peer's (parity, my rank) slot; `x` is a tight [M][n] of bf16 */ + int4* ps[NPEERS]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) + ps[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16; + const int wpr = (int)(n >> 3); + const int4* const in4 = (const int4*)x; + for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) { + const int4 v = in4[k]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) ps[p][k] = v; + } + + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + /* The one-shot's release: the fold and the junction behind it are local VRAM traffic, so the + * last block past its handshake ends the engine's hold on the link (r4d_ar_seq.h). Every block + * owns at least one row and takes exactly one handshake, so every path reaches it. */ + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, tid); + + /* the sources in ascending global rank, this rank's own from `x` (its own slot is never + * written), the peers' from their slots in my scratch */ + const uint16_t* src[WS]; +#pragma unroll + for (int r = 0; r < WS; ++r) + src[r] = r == rank ? (const uint16_t*)x + : (const uint16_t*)(my_base + ((size_t)parity * WS + r) * + (size_t)slot_stride16); + const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f; + for (int row = r0; row < r1; ++row) { + const size_t o = (size_t)row * n; + uint16_t* __restrict__ xr = x + o; + float ss = 0.0f; + for (uint32_t i = tid; i < n; i += THR) { + float acc = 0.0f; +#pragma unroll + for (int r = 0; r < WS; ++r) acc += bf2f(src[r][o + i]); + const uint16_t a = (uint16_t)(bf16_hi_rne_nan(acc) >> 16); + xr[i] = a; + if (POST) { const float v = bf2f(a); ss += v * v; } + } + float s1 = 0.0f; + if (POST) s1 = rsqrtf(block_sum(ss, l1) / (float)n + eps); + junction_row( + xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sv, q + (size_t)row * n, S + row, + yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, ybuf, l2, lm); + __syncthreads(); /* the planes and ybuf are re-used by the next row this block owns */ + } +} + } // namespace // ============================================================== the plugin ABI entry point @@ -350,3 +442,85 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long #undef R4D_ARQ8_T return hipGetLastError() == hipSuccess ? 0 : -4; } + +// The four-rank form's launch. The IPC arguments are r4d_ar_oneshot_4rank_exact's -- each peer's +// scratch and flags in ascending peer rank, this rank's own, the device-resident sequence counters +// and the per-source slot stride -- and the rest is the junction's. The checks are the wide +// launchers' (rank range, the message inside one slot, the grid inside the flag array, every +// allocation's extent), returned as codes rather than thrown, for the reason this file gives. +extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, + long peer_scratch2, long peer_flags0, + long peer_flags1, long peer_flags2, long my_scratch, + long my_flags, long seq_ctrs, long slot_stride16, + long x, long res, long w, long wp, long sc, + int sc_f32, long y, long q, long s, int M, int n, + float eps, float wadd, int w_f32, int r_ld, int y_ld, + int rank, long stream, int nblocks, int drain, int acq, + int pub, long gate, long gate_ctr) { + constexpr int WS = 4, NPEERS = WS - 1; + const long ps[NPEERS] = { peer_scratch0, peer_scratch1, peer_scratch2 }; + const long pf[NPEERS] = { peer_flags0, peer_flags1, peer_flags2 }; + if (!x || !w || !q || !s) return -1; + if (!my_scratch || !my_flags || !seq_ctrs) return -1; + if (gate && !gate_ctr) return -1; /* the release counts blocks in the instance's counter */ + if (rank < 0 || rank >= WS) return -1; + if (M <= 0 || n <= 0) return -2; + if (n % 16) return -3; + if ((wp || sc) && !res) return -5; + if ((size_t)n * sizeof(uint16_t) > 60 * 1024) return -6; + if ((long)M * n / 8 > slot_stride16) return -7; /* the message inside one source slot */ + if (!r_ld) r_ld = n; + if (!y_ld) y_ld = n; + + R4DArWidePeers peers{}; + for (int i = 0; i < NPEERS; ++i) { + if (!ps[i] || !pf[i]) return -1; + peers.scratch[i] = (int4*)ps[i]; + peers.flags[i] = (unsigned int*)pf[i]; + peers.rank[i] = i < rank ? i : i + 1; /* ascending global rank, this one removed */ + } + int nb = nblocks < 1 ? 1 : nblocks; + if (nb > M) nb = M; /* a block owns whole rows */ + if (nb > R4D_AR_WIDE_MAX_BLOCKS) nb = R4D_AR_WIDE_MAX_BLOCKS; + try { + const long slot_bytes = 2L * WS * slot_stride16 * 16; + const long flag_bytes = (long)nb * WS * (long)sizeof(unsigned int); + r4d_ar_check_extent(my_scratch, slot_bytes, "ar_rmsnorm_quant_i8", "my_scratch"); + r4d_ar_check_extent(my_flags, flag_bytes, "ar_rmsnorm_quant_i8", "my_flags"); + r4d_ar_check_extent(seq_ctrs, 2L * R4D_AR_WIDE_MAX_BLOCKS * (long)sizeof(unsigned int), + "ar_rmsnorm_quant_i8", "seq_ctrs"); + for (int i = 0; i < NPEERS; ++i) { + r4d_ar_check_extent(ps[i], slot_bytes, "ar_rmsnorm_quant_i8", "peer scratch"); + r4d_ar_check_extent(pf[i], flag_bytes, "ar_rmsnorm_quant_i8", "peer flags"); + } + } catch (...) { + return -8; + } + + const int thr = r4d_act_threads(M, n); + const size_t lds = (size_t)n * sizeof(uint16_t); +#define R4D_ARQ8W_T(WF, RS, PO, SC, T) \ + hipLaunchKernelGGL((ar_rmsnorm_quant_i8_wide_kernel), dim3((uint32_t)nb), \ + dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \ + (const void*)w, (const void*)wp, (const void*)sc, (uint32_t)sc_f32, \ + (signed char*)q, (float*)s, (uint16_t*)y, peers, (const int4*)my_scratch, \ + (unsigned int*)my_flags, (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, \ + wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, rank, drain, acq, \ + pub, (long long*)gate, (unsigned int*)gate_ctr) +#define R4D_ARQ8W(WF, RS, PO, SC) \ + do { if (thr == 1024) R4D_ARQ8W_T(WF, RS, PO, SC, 1024); \ + else if (thr == 512) R4D_ARQ8W_T(WF, RS, PO, SC, 512); \ + else R4D_ARQ8W_T(WF, RS, PO, SC, 256); } while (0) +#define R4D_ARQ8W_W(WF) \ + do { if (!res) R4D_ARQ8W(WF, false, false, false); \ + else if (!wp && !sc) R4D_ARQ8W(WF, true, false, false); \ + else if (wp && !sc) R4D_ARQ8W(WF, true, true, false); \ + else if (wp && sc) R4D_ARQ8W(WF, true, true, true); \ + else R4D_ARQ8W(WF, true, false, true); } while (0) + if (w_f32) R4D_ARQ8W_W(true); + else R4D_ARQ8W_W(false); +#undef R4D_ARQ8W_W +#undef R4D_ARQ8W +#undef R4D_ARQ8W_T + return hipGetLastError() == hipSuccess ? 0 : -4; +} diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index a2930559..b85668ae 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -3080,7 +3080,7 @@ static const RadOpSchema kSchemas[] = { "gelu(gate) * up (tanh form) and the per-row int8 quantiser the w4a8 skinny GEMM reads, in " "one pass."), SCHEMA("ar_rmsnorm_quant_i8", pArRmsNormQuantI8, oArRmsNormQuantI8, - "the two-rank exact all-reduce of x and rmsnorm_quant_i8 after it, in one kernel."), + "the two- or four-rank exact all-reduce of x and rmsnorm_quant_i8 after it, in one kernel."), SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, "silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."), SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, @@ -4452,6 +4452,10 @@ static const RadConstraint cGeluMulQuantI8[] = { static const RadConstraint cArRmsNormQuantI8[] = { C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 2), C_P2P, }; +/* The same at four ranks, on the wide family's transport. */ +static const RadConstraint cArRmsNormQuantI84[] = { + C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 4), C_P2P, +}; static const RadConstraint cHadQuantActI8[] = { C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"), }; @@ -4662,7 +4666,8 @@ static const RadTunable tAttnSplit[] = { /* ------------------------------------------------------------------- all-reduce launch geometry * * Four independent axes of the handshake: nblocks, nthreads, drain and acq. (`pub` is 1 in every - * arm, a constant in r4d_ar_entry.hip.) nblocks 0 scales with the message and clamps; drain 3 is + * arm but the four-rank junction's, tArQ84, where it is an axis.) nblocks 0 scales with the message + * and clamps; drain 3 is * s_wait_storecnt, the correct wait for the fine-grained uncached IPC scratch. * * rad-tune cannot reach these rows: the two-rank kernels need a real peer over IPC and rad-tune @@ -4683,6 +4688,28 @@ static const RadTunable tAr[] = { { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, }; +/* The four-rank fused junction (ar_rmsnorm_quant_i8_4rank): tAr's axes, its own value sets. + * On 4x R9700 over PCIe P2P a junction costs about 22 us at one row of 5376 and 57 us at sixteen + * (--profile-ops): it is bound by its handshakes, not its bytes. + * + * Every block takes one handshake, a system-scope release by its first + * thread and a system-scope acquire by every wave. Both are needed: on 4x R9700 behind an EPYC + * root complex, dropping either (an acq 2 and a pub 2 that were here, r4d_selftest 2026-10-16 and + * -17) left the readers with stale scratch on nearly every element, so the peers' stores do not + * reach them past the writer's L2 without the writeback. What can move is how many handshakes a + * call takes: fewer blocks (2 or 4, each owning several rows) take fewer. The defaults are the + * forms that have run on cards; the others are for RADIANCE_TUNE until they have. None of them + * changes the result. */ +static const int64_t kArQ84Nblocks[] = { 0, 2, 4, 8, 16, 24 }; +static const int64_t kArQ84Acq[] = { 0, 1 }; +static const int64_t kArQ84Pub[] = { 1 }; +static const RadTunable tArQ84[] = { + { "nblocks", kArQ84Nblocks, NELEM(kArQ84Nblocks), 0, "blocks in the grid. 0 = one a row, clamped" }, + { "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "unused: the norm's width sets the block for bit-exactness" }, + { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, + { "acq", kArQ84Acq, NELEM(kArQ84Acq), 0, "acquire after the flag read: 0 system invalidate a wave, 1 full fence" }, + { "pub", kArQ84Pub, NELEM(kArQ84Pub), 1, "release before the flag store: 1 one system writeback" }, +}; /* The four-rank two-shots beside compute: four blocks of 1024. A pipelined Flash-Next prefill at * TP4 (qwen4exp_fp8) runs each all-reduce of a 2048-row piece beside the other piece's MoE passes, * where the size-chosen 24 blocks hold a third of the card while they wait on the link. With every @@ -7563,6 +7590,23 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cArRmsNormQuantI8), ROW(tAr), nullptr, r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8 }, +/* Its arithmetic is the four-rank exact one-shot's fold followed by the two-rank form's junction, + * each the code those two run. r4d_selftest's case of the same name holds it byte for byte to + * all_reduce + rmsnorm_quant_i8 on a four-card box, and the engine to a decode step's text against + * a build that issues the pair. Both have run on cards that way (the 31B's fused junctions, and + * r4d_selftest on four R9700s). */ +{ "ar_rmsnorm_quant_i8_4rank", "ar_rmsnorm_quant_i8", "quant", + "the four-rank exact one-shot all-reduce and the junction after it -- post-norm of the reduced " + "sum, residual add, scalar, RMS norm and quant_act_i8's quantiser -- in one kernel", + "exactly 4 ranks; n a multiple of 16, x unpitched (it is the message); a block owns whole rows; " + "exact wire; one-shot, so (ranks - 1) x the message a rank -- for decode heights", + "bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale; the reduced sum " + "rounded to bf16 as the standalone exact all-reduce stores it", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cArRmsNormQuantI84), ROW(tArQ84), nullptr, + r4d_rad_ar_hc_wide_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8_4rank, nullptr, nullptr, + nullptr, nullptr }, + { "had_quant_act_i8", "had_quant_act_i8", "quant", "block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes " "int8 activations usable at all: unrotated, the per-row absmax is set by a few outlier channels " @@ -8783,6 +8827,7 @@ extern "C" int rad_kernel_collective(int i) { r4d_rad_ar_oneshot_4rank_exact, r4d_rad_ar_twoshot_4rank_exact, r4d_rad_ar_twoshot_4rank_ti8, r4d_rad_ar_gather_4rank, r4d_rad_ar_hc_write_4rank, r4d_rad_ar_gather_hc_write_4rank, + r4d_rad_ar_rmsnorm_quant_i8_4rank, }; for (RadLaunchFn f : kReleasing) if (k->launch == f) return 2; @@ -8862,7 +8907,8 @@ extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) { out->nthreads = TUNE(a, tAr, "nthreads"); out->drain = TUNE(a, tAr, "drain"); out->acq = TUNE(a, tAr, "acq"); - out->pub = 1; /* not an axis; see the note at tAr */ + /* An axis of the four-rank junction only (tArQ84); 1 for every other row, as before. */ + out->pub = TUNE(a, tArQ84, "pub"); } extern "C" void r4d_cfg_topk(const RadArgs* a, R4dTopkCfg* out) { out->rc = 0; /* derived from pt1 at issue; see the note at tTopk */ diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index afb0e265..905f6dee 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -22508,6 +22508,251 @@ static void ar_hc_write_case(const Plugin& pl, const std::vector& devs, con } } +/* ------------------------------------------------------------------ the fused junction (ar_rmsnorm_quant_i8_4rank) */ +/* The four-rank all-reduce with the sandwich-norm junction as its epilogue, against the chain it + * replaces: the exact all-reduce (ar_vsum's f32 ascending-rank fold rounded once to bf16, as + * ar_hc_write_case's oracle folds it), then the single-rank `rmsnorm_quant_i8` row over that sum on + * the first card. The fused row's epilogue is that row's device function, so the check is + * byte-exact on everything it leaves: the reduced x on every rank, the residual, the bf16 norm + * output, the codes and the per-row scales. + * + * Tensor parallel replicates the residual stream, so every rank gets the same one, and x is each + * rank's own partial sum. The three forms the single-rank check walks (the plain norm, the + * junction, the junction with its scalar) run at decode heights, at the one-shot limit of the 31B's + * width (97 rows of 5376, more rows than the wide family has blocks), and at the 26B's width. + * + * The scalar form is also launched as the engine launches a collective it holds the link for, with + * an odd `link_gate` word on each card (rad_abi.h, rad_kernel_collective): over P2P the row must + * end the hold itself, leaving the word even and returning RAD_LINK_ENDED, and through the host + * mailbox it must leave the word alone and return RAD_OK. */ +struct ArQ8 { + const RadKernelInfo* row = nullptr; + int rank = 0, dev = 0; + int64_t M = 0, K = 0; + bool res = false, scal = false; + bool gated = false; /* hand the launch an odd `link_gate` word */ + long long gate_after = -1; /* ...and what the launch left in it */ + void* inst = nullptr; + int rc_init = RAD_E_STATE, rc_launch = RAD_OK; + const std::vector* r_in = nullptr; /* the replicated residual, w and w_post */ + const std::vector* w = nullptr; + const std::vector* wp = nullptr; + uint16_t sc = 0; + std::vector x_in; /* this rank's partial sum */ + std::vector x_out, r_out, y_out; /* what it leaves behind */ + std::vector q_out; + std::vector s_out; +}; + +static void ar_q8_worker(ArQ8* t) { + if (st_set_device(t->dev) != hipSuccess) { t->rc_init = RAD_E_DEVICE; return; } + const int64_t M = t->M, K = t->K; + std::vector ps = { PI("world_size", 4), PI("M", M), PI("n", K), PF("eps", 1e-6), + PS("dtype", "bf16"), PF("wadd", 0.0) }; + t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, 4, &t->inst); + if (t->rc_init != RAD_OK) return; + + /* Allocated here and not through dalloc, whose list four rank threads would race on. */ + void* x = nullptr; void* r = nullptr; void* w = nullptr; void* wp = nullptr; void* sc = nullptr; + void* q = nullptr; void* s = nullptr; void* y = nullptr; void* gw = nullptr; + const size_t xb = (size_t)(M * K * 2), wb = (size_t)K * 2; + const bool mem = hipMalloc(&x, xb) == hipSuccess && hipMalloc(&r, xb) == hipSuccess && + hipMalloc(&w, wb) == hipSuccess && hipMalloc(&wp, wb) == hipSuccess && + hipMalloc(&sc, 4) == hipSuccess && hipMalloc(&q, (size_t)(M * K)) == hipSuccess && + hipMalloc(&s, (size_t)M * 4) == hipSuccess && hipMalloc(&y, xb) == hipSuccess && + (!t->gated || hipMalloc(&gw, 8) == hipSuccess); + if (!mem) { + t->rc_launch = RAD_E_NOMEM; + } else { + /* The engine's hold, as the engine sets it: an odd word on this card for the launch. */ + if (gw) { + const long long one = 1; + st_memcpy(gw, &one, 8, hipMemcpyHostToDevice); + ps.push_back(PI("link_gate", (long long)(uintptr_t)gw)); + } + st_memcpy(x, t->x_in.data(), xb, hipMemcpyHostToDevice); + st_memcpy(r, t->r_in->data(), xb, hipMemcpyHostToDevice); + st_memcpy(w, t->w->data(), wb, hipMemcpyHostToDevice); + st_memcpy(wp, t->wp->data(), wb, hipMemcpyHostToDevice); + st_memcpy(sc, &t->sc, 2, hipMemcpyHostToDevice); + std::vector ts = { + T(x, RAD_BF16, { M, K }), T(r, RAD_BF16, { M, K }), T(w, RAD_BF16, { K }), + T(q, RAD_I8, { M, K }), T(s, RAD_F32, { M }), T(y, RAD_BF16, { M, K }), + T(wp, RAD_BF16, { K }), T(sc, RAD_BF16, { 1 }) }; + if (!t->res) { absent(ts[1]); absent(ts[6]); } + if (!t->scal) absent(ts[7]); + 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.instance = t->inst; + a.rank = t->rank; + a.world_size = 4; + t->rc_launch = t->row->launch(&a, nullptr); + st_stream_sync(nullptr); + t->x_out.resize((size_t)(M * K)); + t->r_out.resize((size_t)(M * K)); + t->y_out.resize((size_t)(M * K)); + t->q_out.resize((size_t)(M * K)); + t->s_out.resize((size_t)M); + st_memcpy(t->x_out.data(), x, xb, hipMemcpyDeviceToHost); + st_memcpy(t->r_out.data(), r, xb, hipMemcpyDeviceToHost); + st_memcpy(t->y_out.data(), y, xb, hipMemcpyDeviceToHost); + st_memcpy(t->q_out.data(), q, (size_t)(M * K), hipMemcpyDeviceToHost); + st_memcpy(t->s_out.data(), s, (size_t)M * 4, hipMemcpyDeviceToHost); + if (gw) st_memcpy(&t->gate_after, gw, 8, hipMemcpyDeviceToHost); + } + for (void* p : { x, r, w, wp, sc, q, s, y, gw }) if (p) st_free(p); +} + +static bool nm_ends_with(const char* s, const char* tail) { + const size_t n = std::strlen(s), k = std::strlen(tail); + return n >= k && std::strcmp(s + n - k, tail) == 0; +} + +static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector& devs, + const char* name) { + const RadKernelInfo* row = find(pl, name); + const RadKernelInfo* rq = find(pl, "rmsnorm_quant_i8"); + if (!row || !rq) { ok(name, false, "row absent"); return; } + if ((int)devs.size() < 4) { skip(name, "needs 4 gfx1201 cards"); return; } + const int world = 4; + const bool host = nm_ends_with(name, "_host"); /* the mailbox twin leaves the hold alone */ + struct Shape { int64_t M, K; }; + const Shape shapes[] = { { 1, 5376 }, { 8, 5376 }, { 40, 5376 }, { 97, 5376 }, { 64, 2816 } }; + const std::string nm(name); + for (const Shape& sh : shapes) { + const int64_t M = sh.M, K = sh.K; + std::vector hr((size_t)(M * K)), hw((size_t)K), hp((size_t)K); + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < K; ++c) + hr[(size_t)(i * K + c)] = h_to_bf16(0.019f * (float)((i * 13 + c * 29) % 67) - 0.6f); + for (int64_t c = 0; c < K; ++c) { + hw[(size_t)c] = h_to_bf16(0.004f * (float)((c * 19) % 51) - 0.1f); + hp[(size_t)c] = h_to_bf16(0.9f + 0.003f * (float)((c * 7) % 41)); + } + const uint16_t hs = h_to_bf16(0.373f); + /* Each rank's partial sum, with per-group magnitudes an order apart and one outlier a row, + * as the single-rank check makes them, shifted by rank so the four differ. */ + std::vector> hx((size_t)world, std::vector((size_t)(M * K))); + for (int r = 0; r < world; ++r) + for (int64_t i = 0; i < M; ++i) + for (int64_t c = 0; c < K; ++c) { + const float m = std::ldexp(1.0f, (int)((c / 384) % 6) - 3); + const float v = m * (0.037f * (float)((i * 29 + c * 13 + r * 17) % 71) - 1.3f); + hx[(size_t)r][(size_t)(i * K + c)] = + h_to_bf16(c == (i * 37 + r * 11) % K ? v * 19.0f : v); + } + /* The fold: f32, ascending rank, rounded once. */ + std::vector xsum((size_t)(M * K)); + for (int64_t i = 0; i < M * K; ++i) { + float acc = 0.0f; + for (int r = 0; r < world; ++r) acc += h_bf16(hx[(size_t)r][(size_t)i]); + xsum[(size_t)i] = h_to_bf16(acc); + } + + for (const int form : { 0, 1, 2 }) { /* the plain norm, the junction, with the scalar */ + const bool res = form > 0, scal = form == 2; + const std::string at = " M=" + std::to_string(M) + " n=" + std::to_string(K) + + (form == 0 ? ", plain" : form == 1 ? ", junction" + : ", junction with scalar"); + + /* The chain on the first card: rmsnorm_quant_i8 over the reduced sum. */ + st_set_device(devs[0]); + const size_t xb = (size_t)(M * K * 2), wb = (size_t)K * 2; + void* d_x = dalloc(xb); void* d_r = dalloc(xb); void* d_w = dalloc(wb); + void* d_p = dalloc(wb); void* d_sc = dalloc(4); void* d_q = dalloc((size_t)(M * K)); + void* d_s = dalloc((size_t)M * 4); void* d_y = dalloc(xb); + if (!d_x || !d_r || !d_w || !d_p || !d_sc || !d_q || !d_s || !d_y) { + ok((nm + at + " alloc").c_str(), false, "hipMalloc failed"); + return; + } + st_memcpy(d_x, xsum.data(), xb, hipMemcpyHostToDevice); + st_memcpy(d_r, hr.data(), xb, hipMemcpyHostToDevice); + st_memcpy(d_w, hw.data(), wb, hipMemcpyHostToDevice); + st_memcpy(d_p, hp.data(), wb, hipMemcpyHostToDevice); + st_memcpy(d_sc, &hs, 2, hipMemcpyHostToDevice); + const std::vector pn = { PI("M", M), PI("n", K), PF("eps", 1e-6), + PS("dtype", "bf16"), PF("wadd", 0.0) }; + const int rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), + res ? T(d_r, RAD_BF16, { M, K }) : T(nullptr, RAD_BF16, {}), + T(d_w, RAD_BF16, { K }), T(d_q, RAD_I8, { M, K }), + T(d_s, RAD_F32, { M }), T(d_y, RAD_BF16, { M, K }), + res ? T(d_p, RAD_BF16, { K }) : T(nullptr, RAD_BF16, {}), + scal ? T(d_sc, RAD_BF16, { 1 }) : T(nullptr, RAD_BF16, {}) }, + pn); + if (rc != RAD_OK) { + ok((nm + at + ": the single-rank chain").c_str(), false, "rc=" + std::to_string(rc)); + continue; + } + std::vector want_r((size_t)(M * K)), want_y((size_t)(M * K)); + std::vector want_q((size_t)(M * K)); + std::vector want_s((size_t)M); + st_memcpy(want_r.data(), d_r, xb, hipMemcpyDeviceToHost); + st_memcpy(want_y.data(), d_y, xb, hipMemcpyDeviceToHost); + st_memcpy(want_q.data(), d_q, (size_t)(M * K), hipMemcpyDeviceToHost); + st_memcpy(want_s.data(), d_s, (size_t)M * 4, hipMemcpyDeviceToHost); + + std::vector t((size_t)world); + std::vector th; + for (int r = 0; r < world; ++r) { + ArQ8& x = t[(size_t)r]; + x.row = row; x.rank = r; x.dev = devs[(size_t)r]; + x.M = M; x.K = K; x.res = res; x.scal = scal; x.gated = scal; + x.r_in = &hr; x.w = &hw; x.wp = &hp; x.sc = hs; + x.x_in = hx[(size_t)r]; + th.emplace_back(ar_q8_worker, &x); + } + for (std::thread& x : th) x.join(); + st_set_device(devs[0]); + + bool up = true, ran = true; + std::string rcs; + const int want_rc = scal && !host ? RAD_LINK_ENDED : RAD_OK; + bool released = true; + for (const ArQ8& x : t) { + up = up && x.rc_init == RAD_OK; ran = ran && x.rc_launch == want_rc; + rcs += std::to_string(x.rc_init) + "/" + std::to_string(x.rc_launch) + " "; + if (scal) released = released && x.gate_after == (host ? 1 : 0); + } + ok((nm + at + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); + if (!up) return; + ok((nm + at + " launch").c_str(), ran, "init/launch rc " + rcs + "(want " + + std::to_string(want_rc) + ")"); + if (scal) { + std::string g; + for (const ArQ8& x : t) g += std::to_string(x.gate_after) + " "; + ok((nm + at + (host ? ": the mailbox twin leaves the engine's link hold alone" + : ": the launch ends the engine's link hold itself")).c_str(), + released, "link_gate words after the launch: " + g); + } + if (ran) { + int64_t bx = 0, br = 0, by = 0, bq = 0, bs = 0, nz = 0; + for (const ArQ8& x : t) { + for (int64_t i = 0; i < M * K; ++i) { + bx += x.x_out[(size_t)i] != xsum[(size_t)i]; + if (res) br += x.r_out[(size_t)i] != want_r[(size_t)i]; + by += x.y_out[(size_t)i] != want_y[(size_t)i]; + bq += x.q_out[(size_t)i] != want_q[(size_t)i]; + } + for (int64_t i = 0; i < M; ++i) + bs += std::memcmp(&x.s_out[(size_t)i], &want_s[(size_t)i], 4) != 0; + } + for (int64_t i = 0; i < M * K; ++i) nz += want_q[(size_t)i] != 0; + char d[200]; + std::snprintf(d, sizeof d, "over four ranks: reduced x %lld, residual %lld, bf16 %lld, " + "codes %lld, scales %lld differ; %lld of %lld codes nonzero", + (long long)bx, (long long)br, (long long)by, (long long)bq, + (long long)bs, (long long)nz, (long long)(M * K)); + ok((nm + at + ": every rank holds the bytes of the all-reduce and the " + "single-rank junction").c_str(), + bx == 0 && br == 0 && by == 0 && bq == 0 && bs == 0 && nz > M * K / 2, d); + } + if (row->fini) for (ArQ8& x : t) if (x.inst) row->fini(x.inst); + } + } +} + /* ------------------------------------------------------------------ the device sweep */ /* embed_lookup_q against a host gather of the same bytes, through the host side's own conversions. @@ -25695,6 +25940,13 @@ static void device_phase(const Plugin& pl) { } /* The wide rows at every width are dispatched above and skip themselves, naming the width * they need, on a box with fewer cards. */ + /* The junction's fused all-reduce at four ranks, and its host twin. */ + for (const char* n : { "ar_rmsnorm_quant_i8_4rank", "ar_rmsnorm_quant_i8_4rank_host" }) { + if (!sel(n)) continue; + if (!g_case) std::printf("\ncross-rank, fused with the sandwich-norm junction\n"); + std::printf(" %s\n", n); + ar_rmsnorm_quant_i8_wide_case(pl, devs, n); + } auto skip_pair = [](const char* base, const char* why) { for (const std::string& n : { std::string(base), std::string(base) + "_host" }) if (sel(n.c_str())) skip(n.c_str(), why); diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 8d34b009..09c6a90c 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -6702,6 +6702,87 @@ TEST(gemma4_attention_join_writes_the_routed_inputs_on_fp8_experts) { CHECK_EQ(count_issued(issued_ops(b, c), "rmsnorm_quant_fp8"), 0); } +/* At four ranks the junctions carry their reductions at decode heights, in the same issue order as + * at two ranks (only the embedding's and the last layer's feed-forward reduction stand alone), + * through ar_rmsnorm_quant_i8 declared at world_size 4 up to 4 rows (kAr4FoldRows: where the fold + * still beats the pair, inside libr4d's one-shot band of 524288 / 5376 = 97). A taller step, a DFlash + * verify's 16 rows included, issues each reduction and its junction apart, and where no library + * declares the fold every step issues the pair. */ +TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_decode_heights) { + const int L = 12; + std::vector folded = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" }; + std::vector apart = folded; + for (int l = 0; l < L; ++l) { + const bool global = (l + 1) % 6 == 0; + for (int i = 0; i < (global ? 2 : 3); ++i) { folded.push_back("gemm_nt_q"); apart.push_back("gemm_nt_q"); } + for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + "ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) + folded.push_back(s); + for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", + "gemm_nt_q", "all_reduce" }) + apart.push_back(s); + if (l < L - 1) { + folded.push_back("ar_rmsnorm_quant_i8"); + apart.push_back("rmsnorm_quant_i8"); + } else { + for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) folded.push_back(s); + for (const char* s : { "rmsnorm", "add", "scale" }) apart.push_back(s); + } + } + for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) { + folded.push_back(s); + apart.push_back(s); + } + /* a decode step folds */ + CHECK_EQ(join(gemma4_w4_step({}, 4)), join(folded)); + + auto declare4 = [](RadBuilder& b) { + const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); + b.encs = { { "attn_q.", w4 }, { "attn_k.", w4 }, { "attn_v.", w4 }, { "attn_o.", w4 }, + { "ffn_gate_up.", w4 }, { "ffn_down.", w4 } }; + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(0, 4); + return gemma4_bf16::declare(&b, &meta, &ctx); + }; + RadBuilder b; + CHECK_OK(declare4(b)); + CHECK(noted(b, "folded in at steps of 4 rows or fewer")); + auto fold_hi = [](const RadBuilder& bb, int* n) { + int64_t hi = -1; + *n = 0; + for (const auto& o : bb.ops) { + if (o.op != "ar_rmsnorm_quant_i8") continue; + ++*n; + CHECK_EQ(pint(&o, "world_size"), 4); + for (const auto& p : o.p) + if (p.key == "M") hi = p.ihi; + } + return hi; + }; + int n_ar = 0; + CHECK_EQ(fold_hi(b, &n_ar), 4); + CHECK_EQ(n_ar, 2 * L - 1); + + /* a verify's height and a step past the one-shot's band both issue the pair */ + const int32_t out[1] = { 127 }; + for (int rows : { 16, 128 }) { + RadBatch tall = one_prompt(rows, out); + RadCtx c; c.b = &b; c.rank = 0; c.world = 4; c.batch = &tall; + gemma4_bf16::step(&c, &tall); + CHECK(c.step_fail.empty()); + CHECK_EQ(join(issued_ops(b, c)), join(apart)); + } + + + /* no library declares the fold: none declared, every step issues the pair */ + RadBuilder off; + off.undeclared.insert("ar_rmsnorm_quant_i8"); + CHECK_OK(declare4(off)); + CHECK(noted(off, "issued apart")); + for (const auto& o : off.ops) CHECK(o.op != "ar_rmsnorm_quant_i8"); +} + /* ==================================================================== the step lint, checked */ namespace { From 21d6b7836ed639736e3a974ae75d3b535a613962 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Tue, 20 Oct 2026 21:29:07 +0800 Subject: [PATCH 067/152] tests: place_test takes the VRAM readings once they hold still (#124) a_mover_gives_back_every_event_and_device_byte compares the process's KFD VRAM after two identical runs. Each stream is a hardware queue, and KFD gives every queue a context save area (the topology's cwsr_size + ctl_stack_size, 29.3 MiB on a 64-CU RDNA4 card) that can be released a few milliseconds after the queue is destroyed. A reading straight after the test's streams are torn down sometimes still held it: on 2x R9700 the check failed about 1 run in 5, by exactly 30765056 bytes, and polling showed the figure back within 10 ms. settled_vram reads process_vram every 10 ms until 100 ms pass without a change, for at most 2 s, and both readings use it. The warm-up run and the 2 MiB + 4 KiB allowance stay. Back to back on the card, place_test -perf_ passed 17 of 20 runs before and 20 of 20 after; the host backend passes. Co-Authored-By: Claude Opus 5.5 --- tests/place_test.cpp | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/tests/place_test.cpp b/tests/place_test.cpp index 728c59c1..80daea7b 100644 --- a/tests/place_test.cpp +++ b/tests/place_test.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include using namespace rad; @@ -3829,16 +3830,36 @@ int process_vram(int64_t* out) { return RAD_OK; } +/* process_vram once it holds still. A stream is a hardware queue, and KFD gives each queue a + * context save area (the topology's cwsr_size + ctl_stack_size: 29.3 MiB on a 64-CU RDNA4 card) + * that can be released a few milliseconds after the queue is destroyed, so a reading straight + * after a stream's destruction may still include it (#124). Reads every 10 ms until 100 ms pass + * without a change, for at most 2 s. */ +int settled_vram(int64_t* out) { + int64_t v = 0; + RAD_TRY(process_vram(&v)); + const auto end = std::chrono::steady_clock::now() + std::chrono::seconds(2); + for (int still = 0; still < 10 && std::chrono::steady_clock::now() < end;) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + int64_t w = 0; + RAD_TRY(process_vram(&w)); + still = w == v ? still + 1 : 0; + v = w; + } + *out = v; + return RAD_OK; +} + } /* namespace */ /* Tools and tests build and tear down movers repeatedly, and on a card every event or stream is * a hardware queue and VRAM. A mover that staged, promoted and filled a loan gives back every * event and every byte of device memory it took. */ /* The runtime and the driver keep some memory for the life of the process once a path is first - * used: page tables for address ranges first mapped (a page, or a page and a 2 MiB directory), and - * on some hosts about 30 MiB the first copy sets up (#124: 2 MiB, 2 MiB + 4 KiB and 31 MiB + 348 - * KiB across runs on one host). So the work runs once before the count is taken, and the count - * after a second run may differ by a page and a directory, never by a buffer. */ + * used: page tables for address ranges first mapped (a page, or a page and a 2 MiB directory). So + * the work runs once before the count is taken, and the count after a second run may differ by a + * page and a directory, never by a buffer. Both counts are taken once the figure holds still: a + * destroyed stream's queue save area can outlive it by a few milliseconds (settled_vram, #124). */ TEST(a_mover_gives_back_every_event_and_device_byte) { auto run = [&]() { const int64_t events0 = rad_dev_live_events(); @@ -3881,9 +3902,9 @@ TEST(a_mover_gives_back_every_event_and_device_byte) { }; run(); int64_t vram0 = 0, vram1 = 0; - CHECK_OK(process_vram(&vram0)); + CHECK_OK(settled_vram(&vram0)); run(); - CHECK_OK(process_vram(&vram1)); + CHECK_OK(settled_vram(&vram1)); CHECK(vram1 - vram0 <= 2 * MiB + 4096); } From 32519753842792e49078b5882916a04210c737e1 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Fri, 16 Oct 2026 12:48:57 -0500 Subject: [PATCH 068/152] arch/gemma4_bf16: the embedding scale as the reference rounds it, 73.5 and not 73.32 Gemma4TextScaledWordEmbedding multiplies the looked-up rows by `embed_scale.to(weight.dtype)`, which is sqrt(5376) rounded to bf16: 73.5. gemma4_bf16 multiplied the trunk's embedding by the unrounded 73.32, and the assistant head's entry, which reads the trunk's embedding module, did the same. The first layer's norm hides a 0.25% scale, but the residual stream every later layer adds to does not. arch/gemma4 has taken the bf16 value since it was written (53.0 at 2816). Both now take embed_scale(n_embd), the bf16-rounded value. arch_test's two checks of the scale expect 73.5, and its three pinned gemma4_bf16 graphs move with the `mult` they record; no other model's pin moves. On 4x R9700 at tp 4 the replies move against main's, as a 0.25% scale on the residual stream would (7 of 7 long prompts, drafter off). A drafter trained on the reference's hidden states tracks the corrected stream better: z-lab's DFlash drafter (the next change) accepts 2.88 tokens a step over seven 2-6K-token prompts against 2.71 with the scale unrounded, and 5.21 against 4.91 on a code prompt (270 against 259 tok/s). Co-Authored-By: Claude Opus 5.5 --- arch/gemma4_bf16/gemma4_bf16.cpp | 15 ++++++++++++--- tests/arch_test.cpp | 16 +++++++++------- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index a5e4c9bc..7b2cabbe 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -20,6 +20,12 @@ #include #include +/* sqrt(n_embd) rounded to bf16: the reference's embedding module multiplies the looked-up rows by + * `embed_scale.to(bf16)`, 73.5 at 5376 and not 73.32. */ +static double embed_scale(int64_t n) { + return rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)n))); +} + namespace gemma4_bf16 { using namespace rad::arch; @@ -828,7 +834,7 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_embd", n_trunk), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), RAD_INT("vocab_offset", g.vocab_off), - RAD_F64("mult", std::sqrt((double)n_trunk))), + RAD_F64("mult", embed_scale(n_trunk))), RAD_WEIGHTS(w_tok)), {}, {b_e}); if (g.world > 1) @@ -1264,12 +1270,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* The embedding is scaled by sqrt(n_embd) at the lookup, not in the table (as in llama.cpp's * build_inp_embd and HF's ScaledWordEmbedding), so the plain table stays tied to the head. - * Without it the token signal in the residual stream would be ~73x too small. */ + * Without it the token signal in the residual stream would be ~73x too small. The scale is + * sqrt(n_embd) rounded to bf16, as the reference multiplies by it (embed_scale: 73.5 + * at 5376, not 73.32). The first norm hides the difference but the residual stream does not, + * and the DFlash drafter was trained on the reference's hidden states. */ m.op_embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), RAD_INT("vocab_offset", g.vocab_off), - RAD_F64("mult", std::sqrt((double)g.n_embd))), + RAD_F64("mult", embed_scale(g.n_embd))), RAD_WEIGHTS(m.w_tok)), {}, {m.b_x}); if (g.world > 1) diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 09c6a90c..c57ac30c 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -5502,10 +5502,11 @@ TEST(gemma4_final_norm_softcap_and_vocab) { CHECK(find_map(b, "output.weight") != nullptr); /* The embedding is scaled by sqrt(n_embd) at lookup (as the reference's build_inp_embd and - * HF's ScaledWordEmbedding do), not baked into the table, so the table stays tied to the head. */ + * HF's ScaledWordEmbedding do), not baked into the table, so the table stays tied to the head. + * HF multiplies by `embed_scale.to(bf16)`, so sqrt(5376) = 73.32 is 73.5. */ const RecOp* el = find_op(b, "embed_lookup", 0); CHECK(el != nullptr); - CHECK_NEAR(pflt(el, "mult"), std::sqrt(5376.0), 1e-9); + CHECK_NEAR(pflt(el, "mult"), 73.5, 1e-9); } TEST(gemma4_every_op_declares_the_buffers_it_touches) { @@ -5806,11 +5807,12 @@ TEST(gemma4_assistant_is_a_serial_head_with_no_cache_of_its_own) { REQUIRE(mpre != nullptr); CHECK_EQ(mpre->src[0], std::string("draft.pre_projection.weight")); - /* The entry embeds through the trunk's table with the trunk's scale. */ + /* The entry embeds through the trunk's table with the trunk's scale, sqrt(5376) rounded to + * bf16 as the reference's embedding module holds it. */ const RecOp* el = find_op(b, "embed_lookup", 1); REQUIRE(el != nullptr); CHECK_EQ(pint(el, "n_embd"), 5376); - CHECK_NEAR(pflt(el, "mult"), std::sqrt(5376.0), 1e-9); + CHECK_NEAR(pflt(el, "mult"), 73.5, 1e-9); CHECK(el->w.size() == 1 && find_op(b, "embed_lookup", 0)->w == el->w); for (const auto& o : b.ops) @@ -9017,13 +9019,13 @@ struct ArchCases { lfm2_bf16::step, 0, {}, 0x1775b188dc4a5120ull); add("gemma4_bf16", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x0cbeb3ccf57a622cull); + gemma4_bf16::step, 0, {}, 0xafc23087c634a537ull); add("gemma4_bf16, w4a8", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x0fbef815d409efd1ull); + gemma4_bf16::step, 0, {}, 0x719fa07788f8b98aull); add("gemma4_bf16, w4a8, two ranks", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, - nullptr, 0, {}, 0x3d3d4c65aeefe59aull); + nullptr, 0, {}, 0x93b174ab52cc0d31ull); add("gemma4", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4::declare(b, &g4m, &c); }, gemma4::step, 0, {}, 0x0f227f5853b6488cull); From 13a917910f7baf21b9f993798176521d264bad92 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sat, 17 Oct 2026 13:09:19 -0500 Subject: [PATCH 069/152] libr4d: rmsnorm_quant_i8 at decode heights loads the row's operands before its reductions The kernel re-read its row from memory in each of three passes, each behind a barrier, so a row cost three dependent round trips: 11 us a launch at any height on gfx1201 against a 4.2 us launch floor. Every pass partitions the row the same way, so at 1024 threads (M <= 32, n <= 8192) each thread now loads its own columns of the branch row, the residual and both gains in one go and keeps them in registers; only the fragment-order store crosses threads, through LDS as before. Same sums in the same order and the same per-element arithmetic, so the same bytes. 8.2 us a launch in a four-card microbenchmark at 1, 4, 8 and 16 rows of 5376. The row gains a reg axis (1 the new form and the default, 0 the old), and the selftest checks both forms against the unfused chain at M=8. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_args.h | 3 + libr4d/r4d_rmsnorm_quant_i8.hip | 113 +++++++++++++++++++++++++++++++- libr4d/r4d_rows.cpp | 13 +++- libr4d/r4d_selftest.cpp | 21 ++++-- 4 files changed, 141 insertions(+), 9 deletions(-) diff --git a/libr4d/r4d_args.h b/libr4d/r4d_args.h index 31187233..7be88687 100644 --- a/libr4d/r4d_args.h +++ b/libr4d/r4d_args.h @@ -359,6 +359,9 @@ void r4d_cfg_split (const RadArgs*, struct R4dSplitCfg*); void r4d_cfg_ar (const RadArgs*, struct R4dArCfg*); void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*); void r4d_cfg_mv (const RadArgs*, struct R4dMvCfg*); +/* rmsnorm_quant_i8's decode form: 1 the row's operands in registers before the reductions, 0 the + * pass-per-read kernel; the row's `reg` axis. */ +int r4d_cfg_rmsq8_reg(const RadArgs*); } /* extern "C" */ diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index 30b24824..1fade643 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -149,6 +149,104 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel( ybuf, l2, lm); } +// The same kernel at decode heights (THR 1024, n <= 1024 * EPT), with every operand of the row +// loaded in one go before the first reduction. The kernel above reads the row again in each pass, +// each read behind a barrier, so a row costs three dependent memory round trips; on gfx1201 that +// held the kernel at 11 us at any height against a 4.2 us launch floor, and this form at 8.2 us +// (4x R9700, 1 to 16 rows of 5376, 2026-10-17). Every pass partitions the row the same way (thread +// t takes columns t, t+THR, ...), so each thread keeps its own columns in registers and none needs +// another's; only the fragment-order store crosses threads, through `ybuf` as before. The sums, +// the order they are taken in and every element's arithmetic are junction_row's, so the bytes are. +template +__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, + signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, + uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) { + extern __shared__ uint16_t ybuf[]; + __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; + const uint32_t row = blockIdx.x, tid = threadIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; + uint16_t* __restrict__ rr = RES ? res + (size_t)row * r_ld : nullptr; + uint16_t* __restrict__ yr = yo ? yo + (size_t)row * y_ld : nullptr; + + uint16_t xv[EPT], rv[EPT]; + float gp[EPT], gw[EPT]; +#pragma unroll + for (uint32_t e = 0; e < EPT; ++e) { + const uint32_t i = tid + e * THR; + xv[e] = 0; rv[e] = 0; gp[e] = 0.0f; gw[e] = 0.0f; + if (i < n) { + xv[e] = xr[i]; + if (RES) rv[e] = rr[i]; + if (POST) gp[e] = gain(wp, i, WF32) + wadd; + gw[e] = gain(w, i, WF32) + wadd; + } + } + const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f; + + // ---- the post-norm's sum of squares, over the branch output + float s1 = 0.0f; + if (POST) { + float ss = 0.0f; +#pragma unroll + for (uint32_t e = 0; e < EPT; ++e) + if (tid + e * THR < n) { const float v = bf2f(xv[e]); ss += v * v; } + s1 = rsqrtf(block_sum(ss, l1) / (float)n + eps); + } + + // ---- the junction (post-norm, add, scalar), stored, and the norm's sum of squares over it + float ss2 = 0.0f; +#pragma unroll + for (uint32_t e = 0; e < EPT; ++e) { + const uint32_t i = tid + e * THR; + if (i < n) { + uint16_t v = xv[e]; + if (RES) { + if (POST) v = f32_to_bf16(bf2f(v) * s1 * gp[e]); + v = f32_to_bf16(bf2f(rv[e]) + bf2f(v)); + if (SCL) v = f32_to_bf16(bf2f(v) * sv); + rr[i] = v; + } + xv[e] = v; + const float f = bf2f(v); + ss2 += f * f; + } + } + const float s2 = rsqrtf(block_sum(ss2, l2) / (float)n + eps); + + // ---- the norm output, rounded to bf16 as the standalone norm stores it, and its absmax + float m = 0.0f; +#pragma unroll + for (uint32_t e = 0; e < EPT; ++e) { + const uint32_t i = tid + e * THR; + if (i < n) { + const uint16_t y = f32_to_bf16(bf2f(xv[e]) * s2 * gw[e]); + ybuf[i] = y; + if (yr) yr[i] = y; + m = fmaxf(m, fabsf(bf2f(y))); + } + } + m = r4d_wave_max(m); + if ((tid & 31) == 0) lm[tid >> 5] = m; + __syncthreads(); // also publishes ybuf to every thread + m = lm[0]; +#pragma unroll + for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]); + const float scale = fmaxf(m, 1e-8f) / 127.f; + const float inv = 1.f / scale; + if (tid == 0) S[row] = scale; + + // ---- the codes, in junction_row's fragment order + signed char* __restrict__ qr = q + (size_t)row * n; + for (uint32_t i = tid; i < n; i += THR) { + const uint32_t s = i >> 4, j = i & 15; + const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); + const int t = __float2int_rn(bf2f(ybuf[src]) * inv); + qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); + } +} + // --------------------------------------------------------------------------------------------- // The same junction with the two-rank all-reduce that precedes it: the branch output is a rank's // partial sum of a column-sharded linear (o_proj, down_proj), and the post-norm is of the whole @@ -368,13 +466,25 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) { const float wadd = (float)r4d_getf(a, "wadd", 0.0); const uint32_t scf = sc ? (sc->dtype == RAD_F32) : 0u; + // The decode form keeps a thread's columns in registers: at 1024 threads, EPT of them. + const int ept = (thr != 1024 || !r4d_cfg_rmsq8_reg(a)) ? 0 + : n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0; + #define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(stream, \ (rmsnorm_quant_i8_kernel), dim3((uint32_t)M), dim3(T), lds, \ (const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \ (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \ (uint32_t)xp, (uint32_t)rp, (uint32_t)yp) +#define R4D_RQI8_R(WF, RS, PO, SC, E) emit_rc = R4D_EMIT(stream, \ + (rmsnorm_quant_i8_reg_kernel), dim3((uint32_t)M), dim3(1024), lds, \ + (const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \ + (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \ + (uint32_t)xp, (uint32_t)rp, (uint32_t)yp) #define R4D_RQI8(WF, RS, PO, SC) \ - do { if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024); \ + do { if (ept == 4) R4D_RQI8_R(WF, RS, PO, SC, 4); \ + else if (ept == 6) R4D_RQI8_R(WF, RS, PO, SC, 6); \ + else if (ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 8); \ + else if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024); \ else if (thr == 512) R4D_RQI8_T(WF, RS, PO, SC, 512); \ else if (thr == 256) R4D_RQI8_T(WF, RS, PO, SC, 256); \ else return R4D_NO(RAD_E_INVAL); } while (0) @@ -388,6 +498,7 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) { else R4D_RQI8_W(false); #undef R4D_RQI8_W #undef R4D_RQI8 +#undef R4D_RQI8_R #undef R4D_RQI8_T return emit_rc; } diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index b85668ae..e27aa13e 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4754,6 +4754,14 @@ static const RadTunable tMv[] = { { "rb", kMvRb, NELEM(kMvRb), 0, "rows of the weight one wave owns. 0 = libr4d's own rule" }, }; +/* rmsnorm_quant_i8 at decode heights (1024 threads, n <= 8192): 1 loads every operand of the row + * into registers before the first reduction (rmsnorm_quant_i8_reg_kernel), 0 re-reads the row in + * each pass. The same bytes either way; on 4x R9700 the first is 8.2 us a launch, the second 11. */ +static const int64_t kRmsQ8Reg[] = { 1, 0 }; +static const RadTunable tRmsQ8[] = { + { "reg", kRmsQ8Reg, NELEM(kRmsQ8Reg), 1, "decode heights: 1 = the row's operands loaded before the reductions, 0 = re-read each pass" }, +}; + /* ==================================================================================== the rows */ /* ------------------------------------------- the small model ops and the sampler chain ------- @@ -7546,7 +7554,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale, optional bf16 " "out; every stored intermediate rounded to bf16 as the unfused chain stores it", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, - ROW(cRmsNormQuantI8), NOTUNE, + ROW(cRmsNormQuantI8), ROW(tRmsQ8), nullptr, nullptr, nullptr, r4d_rad_rmsnorm_quant_i8 }, { "qkv_norm_rope_bf16", "qkv_norm_rope", "attn", @@ -8918,3 +8926,6 @@ extern "C" void r4d_cfg_topk(const RadArgs* a, R4dTopkCfg* out) { extern "C" void r4d_cfg_mv(const RadArgs* a, R4dMvCfg* out) { out->rb = TUNE(a, tMv, "rb"); } +extern "C" int r4d_cfg_rmsq8_reg(const RadArgs* a) { + return TUNE(a, tRmsQ8, "reg"); +} diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 905f6dee..1046df5b 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -10961,7 +10961,7 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { * feed-forward) and with one (feed-forward -> next layer). The unfused chain, kernel by kernel, is * rmsnorm(x; w_post) -> add(residual) -> scale -> rmsnorm(residual; w) -> quant_act_i8. bf16 gains * (as Gemma's checkpoint stores), and two batch heights covering both r4d_act_threads widths a - * decode step meets (1024 at M <= 32, 512 above). */ + * decode step meets (1024 at M <= 32, 512 above), the first in both of its forms. */ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); const RadKernelInfo* ad = find(pl, "add_bf16"); @@ -10969,7 +10969,12 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { const RadKernelInfo* qz = find(pl, "quant_act_i8"); const RadKernelInfo* rq = find(pl, "rmsnorm_quant_i8"); if (!nrm || !ad || !scl || !qz || !rq) { ok("rmsnorm_quant_i8 vs its chain", false, "rows absent"); return; } - for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)40 }) { + /* The row's reg axis at 1024 threads: 1 (the default) holds a thread's columns in registers, + * 0 re-reads the row each pass; both must leave the chain's bytes. */ + struct RqCase { int64_t M; int reg; }; + for (const RqCase rqc : { RqCase{ 1, 1 }, RqCase{ 8, 1 }, RqCase{ 8, 0 }, RqCase{ 40, 1 } }) { + const int64_t M = rqc.M; + const std::string form = rqc.reg ? "" : " (re-read form)"; const int64_t K = 5376; /* Gemma 4 31B's hidden width: 336 sixteen-byte k steps */ std::vector hx((size_t)M * K), hr((size_t)M * K), hw((size_t)K), hp((size_t)K); for (int64_t r = 0; r < M; ++r) @@ -11005,6 +11010,8 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { const std::vector pn = { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }; const std::vector pe = { PI("M", M), PI("n", K), PS("dtype", "bf16") }; const std::vector pq = { PI("M", M), PI("n", K), PI("group", K), PS("dtype", "bf16") }; + std::vector prq = pn; + prq.push_back(PI("reg", rqc.reg)); auto compare = [&](const std::string& what, bool res) { std::vector y0((size_t)M * K), y1((size_t)M * K), r0((size_t)M * K), r1((size_t)M * K); @@ -11041,9 +11048,9 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { if (rc == RAD_OK) rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(nullptr, RAD_BF16, {}), T(d_w, RAD_BF16, { K }), T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M }), T(d_y[1], RAD_BF16, { M, K }), - T(nullptr, RAD_BF16, {}), T(nullptr, RAD_BF16, {}) }, pn); - if (rc != RAD_OK) ok("rmsnorm_quant_i8 vs rmsnorm + quant_act_i8", false, "rc=" + std::to_string(rc)); - else compare("rmsnorm_quant_i8 is byte-identical to rmsnorm + quant_act_i8", false); + T(nullptr, RAD_BF16, {}), T(nullptr, RAD_BF16, {}) }, prq); + if (rc != RAD_OK) ok(("rmsnorm_quant_i8 vs rmsnorm + quant_act_i8" + form).c_str(), false, "rc=" + std::to_string(rc)); + else compare("rmsnorm_quant_i8 is byte-identical to rmsnorm + quant_act_i8" + form, false); /* --- the junction, without and with the scalar --- */ for (const bool with_sc : { false, true }) { @@ -11059,8 +11066,8 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(d_r[1], RAD_BF16, { M, K }), T(d_w, RAD_BF16, { K }), T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M }), T(d_y[1], RAD_BF16, { M, K }), T(d_p, RAD_BF16, { K }), - with_sc ? T(d_sc, RAD_BF16, { 1 }) : T(nullptr, RAD_BF16, {}) }, pn); - const std::string what = with_sc ? "rmsnorm_quant_i8 junction with scalar" : "rmsnorm_quant_i8 junction"; + with_sc ? T(d_sc, RAD_BF16, { 1 }) : T(nullptr, RAD_BF16, {}) }, prq); + const std::string what = (with_sc ? "rmsnorm_quant_i8 junction with scalar" : "rmsnorm_quant_i8 junction") + form; if (rc != RAD_OK) ok((what + " vs rmsnorm + add + scale + rmsnorm + quant_act_i8").c_str(), false, "rc=" + std::to_string(rc)); else compare(what + " is byte-identical to its chain", true); } From dffec0b770c211c0773dda3a7b429192c35b8f66 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sat, 17 Oct 2026 12:03:10 -0500 Subject: [PATCH 070/152] libr4d: step past the full-card launch cliff in qkv_norm_rope and the row norms On gfx1201 a launch whose wavefronts fall in the last 32 before a multiple of 2048 (every wave slot of the R9700's 64 CUs x 2 SIMDs x 16) runs about five times slower than the same work one workgroup wider, whatever the kernel does. A launch-count sweep on one card (2026-10-17): 256-thread workgroups take 27.6 us at 253 to 256 of them and 5.2 us at 252 or 257, for a norm, an LDS-only kernel and a plain copy alike; 128- and 512-thread workgroups hit it at the same wavefront counts. An empty kernel does not, and moving the data does not move it. The 31B lands on it: qkv_norm_rope at a tp-4 verify is 16 rows x 16 heads of 8 wavefronts, exactly a full card (21 us a call against ~6 expected; kbench's one-card 4-row point, 256 workgroups, 17.4 us against 5.3 at 8 rows), and a drafter's 256-row head norm through rmsnorm likewise (21.9 us). r4d_cliff_rows(rows, per_row, waves) is the row count to launch: `rows` when clear of the window, else the first count past it. qkv_norm_rope, rmsnorm and rmsnorm_p launch that many and return at once in a row at or past the real count, so every result is the same bytes. r4d_selftest's qkv_norm_rope case gains 8 rows of the head-256 class (32 heads a row: 256 workgroups, padded). The window's two numbers are the R9700's, named as such in r4d_common.h, and apply on every target libr4d builds for (RDNA4 only). They are not derived from the device: no other card has been measured, and HIP's multiProcessorCount counts WGPs, not CUs, on RDNA. On an RDNA4 part with fewer CUs a launch padded here costs one idle row and gives the same bytes. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_common.h | 28 ++++++++++++++++++++++++++++ libr4d/r4d_model_bf16.hip | 19 ++++++++++++------- libr4d/r4d_qkv_norm_rope.hip | 12 +++++++++--- libr4d/r4d_selftest.cpp | 4 +++- 4 files changed, 52 insertions(+), 11 deletions(-) diff --git a/libr4d/r4d_common.h b/libr4d/r4d_common.h index 4ceeed76..3f0bae03 100644 --- a/libr4d/r4d_common.h +++ b/libr4d/r4d_common.h @@ -282,3 +282,31 @@ __host__ __device__ __forceinline__ int r4d_act_threads(int M, int K) { const int lim = K >= 8192 ? (1 << 24) : (K >= 4096 ? 120 : 72); return M <= lim ? 512 : 256; } + +// The full-card cliff, measured on the R9700 (gfx1201, 64 CUs). A launch whose wavefronts fall +// in the last 32 before a multiple of 2048 runs about five times slower than the same work one +// workgroup wider, whatever the kernel does: 256-thread workgroups take 27.6 us at 253 to 256 of +// them and 5.2 us at 252 or 257, a norm, an LDS-only kernel and a copy alike. The 31B's +// qkv_norm_rope at a tp-4 verify is exactly 256 such workgroups (16 rows x 16 heads), and a +// drafter's 256-row head norm too. +// +// 2048 is every wave slot of the R9700 (64 CUs x 2 SIMDs x 16). Both numbers are that card's and +// apply on every target libr4d builds for; they are not derived from the device, since no other +// card has been measured and HIP's multiProcessorCount counts WGPs, not CUs, on RDNA. On an RDNA4 +// part with fewer CUs a launch padded here costs one idle row and gives the same bytes, and a +// cliff at that part's own full-card size, if it has one, is not stepped past. +// +// r4d_cliff_rows() is the row count to launch for a grid of `rows` x `per_row` workgroups of +// `waves` wavefronts each: `rows` where that is clear of the window, else the first count past it. +// The kernel returns at once in a row at or past `rows`, so the result is unchanged. +constexpr uint32_t kR4dCliffWaves = 2048; // the R9700's wave slots: 64 CUs x 2 SIMDs x 16 +constexpr uint32_t kR4dCliffWindow = 32; // the slow window, below each multiple of it +__host__ __device__ __forceinline__ uint32_t r4d_cliff_rows(uint32_t rows, uint32_t per_row, + uint32_t waves) { + uint32_t r = rows; + for (int i = 0; i < 64; ++i, ++r) { + const uint64_t w = (uint64_t)r * per_row * waves % kR4dCliffWaves; + if (w != 0 && w <= kR4dCliffWaves - kR4dCliffWindow) break; + } + return r; +} diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 084a76e6..d1952c80 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -209,9 +209,10 @@ __device__ __forceinline__ float act_f32(float v) { return v; } template __global__ __launch_bounds__(THR) void rmsnorm_kernel( const TX* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, - uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld) { + uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld, uint32_t M) { __shared__ float lds[THR / kWave]; const uint32_t m = blockIdx.x; + if (m >= M) return; // a row the launch added past the full-card cliff (r4d_cliff_rows) const TX* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; @@ -231,9 +232,10 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel( // rmsnorm does, so the two agree bit for bit where rmsnorm's gain is one. __global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ y, - uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) { + uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld, uint32_t M) { __shared__ float lds[kThreads / kWave]; const uint32_t m = blockIdx.x; + if (m >= M) return; // a row the launch added past the full-card cliff (r4d_cliff_rows) const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; uint16_t* __restrict__ yr = y + (size_t)m * y_ld; float ss = 0.0f; @@ -771,10 +773,12 @@ extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float // columns a thread folds into the sum of squares and the fused kernel must be byte-identical // to this one followed by the quantiser. const int thr = r4d_act_threads(M, n); + // A drafter's 256-row head norm at 256 threads is exactly a full card; step past the cliff. #define R4D_RN_T(wf, T) \ - hipLaunchKernelGGL((rmsnorm_kernel), dim3((uint32_t)M), dim3(T), 0, \ + hipLaunchKernelGGL((rmsnorm_kernel), dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), \ + dim3(T), 0, \ (hipStream_t)stream, (const uint16_t*)x, (const void*)w, (uint16_t*)y, \ - (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld) + (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M) #define R4D_RN(wf) \ do { if (thr == 1024) R4D_RN_T(wf, 1024); \ else if (thr == 512) R4D_RN_T(wf, 512); \ @@ -800,9 +804,10 @@ extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, if (M <= 0 || n <= 0) return -2; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(rmsnorm_p_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, + hipLaunchKernelGGL(rmsnorm_p_kernel, dim3(r4d_cliff_rows((uint32_t)M, 1, kThreads / kWave)), + dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y, (uint32_t)n, eps, - (uint32_t)x_ld, (uint32_t)y_ld); + (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M); return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -1351,7 +1356,7 @@ static int rmsnorm_x_f32(const float* x, const void* w, uint16_t* y, int M, int #define R4D_RNF_T(wf, T) \ hipLaunchKernelGGL((rmsnorm_kernel), dim3((uint32_t)M), dim3(T), 0, \ (hipStream_t)stream, x, w, y, (uint32_t)n, eps, wadd, mult, \ - (uint32_t)x_ld, (uint32_t)y_ld) + (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M) #define R4D_RNF(wf) \ do { if (thr == 1024) R4D_RNF_T(wf, 1024); \ else if (thr == 512) R4D_RNF_T(wf, 512); \ diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip index 0ebf24d9..f620efe9 100644 --- a/libr4d/r4d_qkv_norm_rope.hip +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -78,10 +78,12 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, - uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos) { + uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos, + uint32_t m_rows) { __shared__ float l1[HD / kWave], l2[HD / kWave]; __shared__ uint16_t nb[HD]; const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x; + if (m >= m_rows) return; // a row the launch added past the full-card cliff (r4d_cliff_rows) const float div = rscale != 0.0f ? rscale : 1.0f; // rope rotates only the rows its positions cover; a row past them is normed and not rotated const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f; @@ -172,12 +174,16 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { const float wadd = (float)r4d_getf(a, "wadd", 0.0); const float theta = (float)r4d_getf(a, "theta", 10000.0); const float rsc = (float)r4d_getf(a, "scale", 1.0); - const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + ((vk || !vn) ? 0 : nkv))); + const uint32_t heads = (uint32_t)(nq + nkv + ((vk || !vn) ? 0 : nkv)); + // A tp-4 verify of the 31B is 16 rows x 16 heads of 8 wavefronts: exactly a full card, the + // cliff r4d_cliff_rows steps past with one idle row. + const dim3 grid(r4d_cliff_rows((uint32_t)M, heads, (uint32_t)(hd / kWave)), heads); #define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ (uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \ r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \ - (uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp) + (uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp, \ + (uint32_t)M) #define R4D_QNR(HD) \ do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \ else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0) diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 1046df5b..ecbe6124 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -10884,7 +10884,9 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false, true }, Cls{ 512, 16, 2, 128, "head", 1000000.0, true, true }, Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false } }) { - for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40 }) { + /* 8 rows of the head-256 class are 8 x 32 workgroups of 8 wavefronts, a full card: the + * launch adds an idle row past the cliff (r4d_cliff_rows), which must not change a byte. */ + for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)8, (int64_t)40 }) { const int64_t QD = cl.nq * cl.hd, KD = cl.nkv * cl.hd; std::vector hq((size_t)M * QD), hk((size_t)M * KD), hv((size_t)M * KD); std::vector hqw((size_t)cl.hd), hkw((size_t)cl.hd); From 82aec1766c69f5ef1803e7e4d55e75b3cce2a5a6 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 11:45:36 -0500 Subject: [PATCH 071/152] libr4d: the windowed attention's split merge loads a group ahead, and its WMMA prefill does less work a key tile The merge: the 31B's global layers merge their split-KV partials in merge_body (r4d_attn_paged_window.hip), one wave a row, four splits at a time into one accumulator chain: ~9.4 us a layer on 4x R9700 in the decode timeline. Each group's loads went out only after the previous group's FMAs, so a row paid one L2 round trip a group. Group g + 1's loads now go out before group g's FMAs (two register groups in turn; 175 VGPRs at head_dim 512, no spill). The FMAs and their order are unchanged, so the bytes are too. The prefill kernel: attn_wmma_kernel (the 31B's global layers at prefill, ~1.1-1.5 ms a 1024-row slice on 4x R9700) does three things a tile that change no byte: - fp8 V widens to its f16 pairs with v_cvt_pkrtz: every e4m3 value is exact in f16, so the pack's rounding and f16_bits' clamp (unreachable under 448) leave the same bits, for 2 instructions a pair instead of ~10. - A tile wholly inside [lo, hi) and, causal, at or before the block's first position is visible to every valid row, so it takes its scores without the per-key masks. - With an fp8 cache, a wave whose rows all kept their running max (corr exactly 1) skips the rescale of O^T: x * 1 = x. One-card microbenchmark of the three with the skip on both caches (the kernel against the shipped one, random operands, a 1024-row slice at the end of the context): head_dim 512 gqa 8 fp8 cache 1481 -> 1295 us at context 4096, 657 -> 531 at 2048, 2220 -> 1785 at 6144; head_dim 256 gqa 2 fp8 675 -> 544, bf16 589 -> 511. Every output byte-identical to the shipped kernel's at all four instantiations (512/8 and 256/2, fp8 and bf16). The skip measured ~4% at head_dim 512 with an fp8 cache, but with bf16 its split loop ran ~10% slower than the fused one (1634 against 1427 us at context 4096; v_cvt and the interior path alone: 1318), so bf16 keeps the fused loop. fp8x16_f16, left with no caller, is removed. The pack is f16x2_exact: v_cvt_pkrtz on gfx12, f16_bits elsewhere (the host SIMT emulator, tests/r4d_emu, compiles this unit as C++), the same bits since neither rounds a value exact in f16; r4d_emu_attn passes. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_attn_paged_window.hip | 104 +++++++++++++++++++++++-------- 1 file changed, 77 insertions(+), 27 deletions(-) diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip index 7a1056a5..1e66221d 100644 --- a/libr4d/r4d_attn_paged_window.hip +++ b/libr4d/r4d_attn_paged_window.hip @@ -499,15 +499,14 @@ __device__ __forceinline__ unsigned f16_bits(float f) { if (f == f) f = __builtin_fminf(__builtin_fmaxf(f, -65504.0f), 65504.0f); return (unsigned)__builtin_bit_cast(unsigned short, (_Float16)f); } -__device__ __forceinline__ void fp8x16_f16(const uint4 w, unsigned (&h)[16]) { - const unsigned in[4] = {w.x, w.y, w.z, w.w}; -#pragma unroll - for (int q = 0; q < 4; ++q) { - float f[4]; - fp8x4(in[q], f); -#pragma unroll - for (int e = 0; e < 4; ++e) h[q * 4 + e] = f16_bits(f[e]); - } +/* Two f32 values exact in f16 as an f16 pair, `a` low: v_cvt_pkrtz on gfx12, f16_bits elsewhere + * (the host emulator), the same bits either way since neither rounds an exact value. */ +__device__ __forceinline__ unsigned f16x2_exact(float a, float b) { +#if defined(__GFX12__) + return __builtin_bit_cast(unsigned, __builtin_amdgcn_cvt_pkrtz(a, b)); +#else + return f16_bits(a) | f16_bits(b) << 16; +#endif } __device__ __forceinline__ void bf16x8_f16(const uint4 w, unsigned (&h)[8]) { const unsigned in[4] = {w.x, w.y, w.z, w.w}; @@ -684,11 +683,17 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { const uint4 wb = (tok && kb1 >= lo && kb1 < hi) ? pv[j][1] : make_uint4(0u, 0u, 0u, 0u); unsigned d[CW]; /* f16 pairs: key 2kp low, 2kp + 1 high */ if constexpr (KV8) { - unsigned ha[16], hb2[16]; - fp8x16_f16(wa, ha); - fp8x16_f16(wb, hb2); + /* every e4m3 value is exact in f16 (|v| <= 448, subnormals 2^-9 up), so the + * pack's round-toward-zero and f16_bits' clamp leave the same bits */ + const unsigned ia[4] = {wa.x, wa.y, wa.z, wa.w}, ib[4] = {wb.x, wb.y, wb.z, wb.w}; #pragma unroll - for (int e = 0; e < CW; ++e) d[e] = ha[e] | hb2[e] << 16; + for (int q = 0; q < 4; ++q) { + float fa[4], fb[4]; + fp8x4(ia[q], fa); + fp8x4(ib[q], fb); +#pragma unroll + for (int e = 0; e < 4; ++e) d[q * 4 + e] = f16x2_exact(fa[e], fb[e]); + } } else { unsigned ha[8], hb2[8]; bf16x8_f16(wa, ha); @@ -747,14 +752,26 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { /* ---- online softmax, row n: eight keys here, eight in lane ^ 16 */ float sv[8], mx = -__builtin_inff(); + /* A tile wholly inside [lo, hi) and, causal, at or before the block's first position + * (every row's pos >= qbase) is visible to every valid row: the same scores, unmasked. */ + const bool interior = window <= 0 && k0 >= lo && k0 + 16 <= hi && (!causal || k0 + 15 <= qbase); + if (interior) { + const bool vis = rval && tok; #pragma unroll - for (int e = 0; e < 8; ++e) { - const int kk = k0 + 8 * h + e; - bool vis = rval && tok && kk >= lo && kk < hi; - if (causal) vis = vis && kk <= pos; - if (window > 0) vis = vis && (pos - kk < window) && (causal || kk - pos < window); - sv[e] = vis ? tot[e] * sscale : -__builtin_inff(); - mx = __builtin_fmaxf(mx, sv[e]); + for (int e = 0; e < 8; ++e) { + sv[e] = vis ? tot[e] * sscale : -__builtin_inff(); + mx = __builtin_fmaxf(mx, sv[e]); + } + } else { +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int kk = k0 + 8 * h + e; + bool vis = rval && tok && kk >= lo && kk < hi; + if (causal) vis = vis && kk <= pos; + if (window > 0) vis = vis && (pos - kk < window) && (causal || kk - pos < window); + sv[e] = vis ? tot[e] * sscale : -__builtin_inff(); + mx = __builtin_fmaxf(mx, sv[e]); + } } mx = __builtin_fmaxf(mx, shfl_xor(mx, 16)); const float mn = __builtin_fmaxf(m, mx); @@ -773,10 +790,23 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { /* ---- O^T += V^T * P^T in f16: A = V^T rows (dim n of the chunk), keys 8h .. 8h + 7 */ const unsigned char* va = vb + (sl * kDQ + n) * VS + h * 16; + if constexpr (KV8) { + /* x * 1 = x, so a wave whose rows all kept their max skips the rescale. With an fp8 + * cache that is ~4% at head_dim 512; with bf16 the split loop measured ~10% slower, + * so it keeps the fused one. */ + if (__builtin_amdgcn_ballot_w32(corr != 1.0f) != 0) { #pragma unroll - for (int mc = 0; mc < kDQ / 16; ++mc) { - oacc[mc] *= corr; - oacc[mc] = wmma_f16(__builtin_bit_cast(win_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]); + for (int mc = 0; mc < kDQ / 16; ++mc) oacc[mc] *= corr; + } +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) + oacc[mc] = wmma_f16(__builtin_bit_cast(win_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]); + } else { +#pragma unroll + for (int mc = 0; mc < kDQ / 16; ++mc) { + oacc[mc] *= corr; + oacc[mc] = wmma_f16(__builtin_bit_cast(win_v8h, *(const uint4*)(va + mc * 16 * VS)), pf, oacc[mc]); + } } } @@ -840,9 +870,9 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { * (a written split, so 0 * finite). An empty split's accumulator is never read. */ uint64_t live = (uint64_t)__builtin_amdgcn_ballot_w32(w0 != 0.0f) | ((uint64_t)__builtin_amdgcn_ballot_w32(w1 != 0.0f) << 32); - while (live) { - int zi[4]; - float wj[4]; + /* Group g + 1's loads go out before group g's FMAs, so a group's wait overlaps the one + * before it instead of following it; the FMAs keep their order, so the bytes do too. */ + auto take = [&](int (&zi)[4], float (&wj)[4]) { #pragma unroll for (int j = 0; j < 4; ++j) { const bool have = live != 0; @@ -851,13 +881,16 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { wj[j] = readlane(zi[j] < 32 ? w0 : w1, zi[j] & 31); if (!have) wj[j] = 0.0f; } - float4 v[4][NC]; + }; + auto load = [&](const int (&zi)[4], float4 (&v)[4][NC]) { #pragma unroll for (int j = 0; j < 4; ++j) { const float* pp = A.part + (base + (long long)zi[j] * R) * (HD + 4); #pragma unroll for (int c = 0; c < NC; ++c) v[j][c] = *(const float4*)(pp + c * 128 + lane * 4); } + }; + auto fold = [&](const float (&wj)[4], const float4 (&v)[4][NC]) { #pragma unroll for (int j = 0; j < 4; ++j) #pragma unroll @@ -867,6 +900,23 @@ __global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { acc[c][2] = __builtin_fmaf(wj[j], v[j][c].z, acc[c][2]); acc[c][3] = __builtin_fmaf(wj[j], v[j][c].w, acc[c][3]); } + }; + if (live) { + int za[4], zb[4]; + float wa[4], wb[4]; + float4 va[4][NC], vb[4][NC]; + take(za, wa); + load(za, va); + while (true) { + const bool more_b = live != 0; + if (more_b) { take(zb, wb); load(zb, vb); } + fold(wa, va); + if (!more_b) break; + const bool more_a = live != 0; + if (more_a) { take(za, wa); load(za, va); } + fold(wb, vb); + if (!more_a) break; + } } #pragma unroll for (int c = 0; c < NC; ++c) From 104c81f005afd55a77c9648725b2dde414091840 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 11:45:36 -0500 Subject: [PATCH 072/152] libr4d, core: two first-launch races that could change a fresh server's first reply Counter blocks: the per-(stream, output) counter blocks of the fp8a8 split-K finisher (split_ctr), the gated delta-net conv (ru_conv_ctr), the mxfp4a8 decode GEMM and the hc mix are zeroed with hipMemset, which queues on HIP's null stream and returns before it lands. The engine launches on queues of its own that need not wait for that stream, so the first launch on a new block could run beside its own zeroing: a split-K finisher counting arrivals while the memset reset the count gives that one launch a wrong output. r4d_moe.hip's router counters and the all-reduce's IPC allocations already wait; these four now do too (hipDeviceSynchronize, once per block). Seen as a greedy reply that differed on the first request of a freshly started 31B DFlash2 server (2 of 13 fresh starts on 4x R9700, 2026-10-17; every later request matched): the drafter's fp8a8 GEMMs take split_ctr blocks on their first launch, and a draft that differs moves the verify blocks, whose rounding the target's greedy choice can feel at a near-tie. No value changes otherwise. Weight transfers: resolve_weight puts the mover's `ready` wait on the issuing lane's stream, but remembered the generation it waited on per weight for the whole context. A weight resolved first on lane 1 then had its wait on lane 1 only, and the lane-0 GEMM resolving it next skipped its own and could read the slot before the copy landed. The Gemma 4 26B-A4B's dense arm is such a weight: a decode step issues it on lane 1, beside the routed arm, and an overlapped prefill on lane 0. waited_gen_ is now per lane, one record for each of the context's two lanes (set_lane admits 0 and 1 only), indexed by lane_ like the other per-lane state: at worst one more stream wait. Inert where no transfer is in flight (static weights, the 31B on four cards); it matters wherever weights stream. Co-Authored-By: Claude Opus 5.5 --- core/runtime/ctx.cpp | 2 +- core/runtime/ctx.h | 7 ++++++- core/runtime/issue.cpp | 10 ++++++---- ...d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip | 5 ++++- libr4d/r4d_gemm_fp8a8.hip | 5 ++++- libr4d/r4d_gemm_mxfp4a8_decode.hip | 7 ++++++- libr4d/r4d_hc_bf16.hip | 5 ++++- 7 files changed, 31 insertions(+), 10 deletions(-) diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index da0d20ce..64487a86 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -271,7 +271,7 @@ int Ctx::bind_weights() { Program& P = *program_; w_tmpl_.assign(P.weights.size(), RadTensor{}); w_bits_.assign(P.weights.size(), 0); - waited_gen_.assign(P.weights.size(), UINT32_MAX); + for (auto& g : waited_gen_) g.assign(P.weights.size(), UINT32_MAX); w_direct_.assign(P.weights.size(), 0); for (size_t i = 1; i < P.weights.size(); ++i) { diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 95ea0caf..36f4057b 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -685,7 +685,12 @@ private: int level_ = 0; std::vector w_tmpl_; std::vector w_bits_; - std::vector waited_gen_; /* the generation we last made the stream wait on */ + /* The generation each lane's stream was last made to wait on, a weight. Per lane: the wait + * orders only the stream it is put on, so a weight resolved on lane 1 (the Gemma 4 26B-A4B's + * dense arm, which a decode step issues on lane 1 and an overlapped prefill on lane 0) must + * still be waited on when lane 0 resolves it. Indexed by lane_, like the other per-lane state + * here: set_lane admits lanes 0 and 1 only. */ + std::vector waited_gen_[2]; std::vector plans_; /* Ops not yet seen issued. flush_issued walks only these and drops each once it fires. */ diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 086dc7b7..84228622 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -82,15 +82,17 @@ void* Ctx::resolve_weight(rad_weight w) { const WeightSlot* s = residency_->lookup(w); /* never blocks -- residency.h */ if (s) { p = s->ptr; - /* Wait once per generation, not per issue; a stream wait orders everything issued after - * it. Sound because the mover bumps `generation` per transfer (residency.h). */ - if (s->ready && waited_gen_[w] != s->generation) { + /* Wait once per generation and lane, not per issue; a stream wait orders everything + * issued after it on that stream, and nothing on the other lane. Sound because the mover + * bumps `generation` per transfer (residency.h). */ + std::vector& waited = waited_gen_[lane_]; + if (s->ready && waited[w] != s->generation) { /* Kept out of a recording: it orders every later play too, and moving a weight a * pass names directly re-keys the pass. */ if (rec_) tape_pause(true); rad_event_wait(cur_stream(), s->ready); /* the stream waits, not the host */ if (rec_) tape_pause(false); - waited_gen_[w] = s->generation; + waited[w] = s->generation; ++n_stream_waits_; } } diff --git a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip index df5c79fd..40f01a1d 100644 --- a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip +++ b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip @@ -850,7 +850,10 @@ static unsigned int* ru_conv_ctr(RadStream s, const void* out) { if (auto it = blocks.find(key); it != blocks.end()) return it->second; void* p = nullptr; if (hipMalloc(&p, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess) return nullptr; - if (hipMemset(p, 0, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess) { + // Zero before any launch reads it: the memset is on the null stream, which the engine's streams + // need not wait for, so wait here (as r4d_moe.hip's router counters do). + if (hipMemset(p, 0, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess || + hipDeviceSynchronize() != hipSuccess) { (void)hipFree(p); return nullptr; } diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index bbaf0964..970ed3b3 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -824,7 +824,10 @@ unsigned int* split_ctr(RadStream s, const void* out) { if (auto it = blocks.find(key); it != blocks.end()) return it->second; void* p = nullptr; if (hipMalloc(&p, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess) return nullptr; - if (hipMemset(p, 0, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess) { + /* Zero before any launch reads it: the memset is on the null stream, which the engine's + * streams need not wait for, so wait here (as r4d_moe.hip's router counters do). */ + if (hipMemset(p, 0, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess || + hipDeviceSynchronize() != hipSuccess) { (void)hipFree(p); return nullptr; } diff --git a/libr4d/r4d_gemm_mxfp4a8_decode.hip b/libr4d/r4d_gemm_mxfp4a8_decode.hip index eaab1ce8..feb173c3 100644 --- a/libr4d/r4d_gemm_mxfp4a8_decode.hip +++ b/libr4d/r4d_gemm_mxfp4a8_decode.hip @@ -472,7 +472,12 @@ unsigned* mxd_out_ctr(const void* out) { const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16); unsigned* p = nullptr; if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr; - if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess) { (void)hipFree(p); return nullptr; } + // Zero before any launch reads it: the memset is on the null stream, which the engine's streams + // need not wait for, so wait here (as r4d_moe.hip's router counters do). + if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) { + (void)hipFree(p); + return nullptr; + } blocks.emplace(key, p); return p; } diff --git a/libr4d/r4d_hc_bf16.hip b/libr4d/r4d_hc_bf16.hip index 0614b06c..a7d2a5e1 100644 --- a/libr4d/r4d_hc_bf16.hip +++ b/libr4d/r4d_hc_bf16.hip @@ -2153,7 +2153,10 @@ unsigned int* hc_mix_ctr(RadStream s) { if (fi < 0) return nullptr; void* p = nullptr; if (hipMalloc(&p, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess) return nullptr; - if (hipMemset(p, 0, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess) { + /* Zero before any launch reads it: the memset is on the null stream, which the engine's + * streams need not wait for, so wait here (as r4d_moe.hip's router counters do). */ + if (hipMemset(p, 0, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess || + hipDeviceSynchronize() != hipSuccess) { (void)hipFree(p); return nullptr; } From 3ef9ce33ae395841e7aea71851a4990b373d7273 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 18 Oct 2026 15:37:40 -0500 Subject: [PATCH 073/152] core/sample: issue sample_temp only where some row is scaled The decode timeline shows sample_temp at ~10 us a step on the 31B at tp 4: a launch over every row's whole vocabulary shard (up to 256 workgroups a row) whose rows all return at once, since a greedy request under a split vocabulary has temperature 0 and a plain sampled one 1, and the kernel leaves both as they are. Sampler::run now issues it only when a chain row has another temperature; every other row's logits are untouched either way, so the tokens are the same. The request check's note on greedy chain rows now says when run() issues the stage. Co-Authored-By: Claude Opus 5.5 --- core/sample/sampler.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index 7a16de8b..3f320b83 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -438,8 +438,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const { }; /* Under a split vocabulary, or when it asks for logprobs, a greedy request is staged as a * top-1 chain row (see build_step), so it needs the chain ops (temperature, top-k, pick) - * rather than the argmax. run() issues the temperature stage for any chain row, even though - * it leaves a temperature-0 row unchanged. */ + * rather than the argmax. run() issues the temperature stage only when some chain row has a + * temperature other than 0 or 1, the two the stage leaves as they are. */ const bool lp = sp.n_probs >= 0; const bool greedy_chain = sp.greedy() && (vocab_parallel() || lp); const char* missing = nullptr; @@ -905,7 +905,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { bool any_mask = false, any_greedy = false, any_chain = false; bool any_penalty = false, any_dry = false, any_xtc = false; - bool any_topp = false, any_minp = false, any_typ = false; + bool any_topp = false, any_minp = false, any_typ = false, any_temp = false; for (int64_t i = 0; i < n_seq_; ++i) { const DeviceSampleParams& p = cur_stage_[i]; any_mask |= (p.flags & RAD_SP_MASK) != 0; @@ -915,6 +915,8 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { if (p.flags & RAD_SP_GREEDY) any_greedy = true; else { any_chain = true; + /* sample_temp leaves a row at temperature <= 0 or exactly 1 as it is */ + any_temp |= p.temp > 0.0f && p.temp != 1.0f; any_topp |= p.top_p < 1.0f; any_minp |= p.min_p > 0.0f; any_typ |= p.typical_p < 1.0f; @@ -993,7 +995,10 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { if (!any_chain) return RAD_OK; - RAD_TRY(issue(op_temp_, { o_logits, o_params })); + /* Only where some row is scaled: a greedy request under a split vocabulary (temperature 0) + * and a plain T=1 one are left alone, and the launch over the whole vocabulary still costs + * ~10 us a step (4x R9700). */ + if (any_temp) RAD_TRY(issue(op_temp_, { o_logits, o_params })); if (any_mask && !any_greedy) RAD_TRY(issue(op_mask_, { o_logits, o_params, o_mask })); From d999524054e08e48d5fcdd12b6564107fcadea04 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Tue, 20 Oct 2026 22:33:28 +0800 Subject: [PATCH 074/152] libr4d: rmsnorm_had_quant_i8g, ar_rmsnorm_had_quant_i8g, gated_had_quant_i8g -- producers that write rotated int8 codes An i8a8h linear quantises its own input from the bf16 plane with had_quant_act_i8g, so a decode step of the int8 Qwen3.8-27B issues 288 of them after the norms and the silu product. These three device ops write those codes from the producer instead: - rmsnorm_had_quant_i8g and ar_rmsnorm_had_quant_i8g (exact and wire=6): norm_quant_row gains an HI8 form, r4d_fwht_wave<128> and then quant_group, on the lane mapping, rotation and rounding had_quant_act_i8g uses. - gated_had_quant_i8g: the gated kernel's existing ROT && I8 instance, which the shim refused. Each writes the bytes its producer followed by had_quant_act_i8g writes. They are ops of their own, not a flag on the fp8 forms, as gated_had_quant_fp8 is: a rotated and a plain quantiser must not be substitutable. n % 128 == 0; device only, so a graph falls back to the pair where they are not declared. r4d_selftest checks each against its pair byte for byte (plain, with the residual add and the residual it leaves, and the gated product) and that each refuses E4M3 codes. The all-reduce form is skipped like ar_rmsnorm_quant_fp8, since it needs a peer rank. Co-Authored-By: Claude Opus 5.5 --- docs/OPS.md | 14 +++ libr4d/r4d.h | 18 ++++ libr4d/r4d_ar_entry.hip | 42 ++++++-- libr4d/r4d_fused_quant_fp8.hip | 173 +++++++++++++++++++++++++-------- libr4d/r4d_plugin.h | 6 ++ libr4d/r4d_rows.cpp | 70 +++++++++++++ libr4d/r4d_selftest.cpp | 102 ++++++++++++++++++- libr4d/r4d_shapes.cpp | 55 +++++++++++ 8 files changed, 430 insertions(+), 50 deletions(-) diff --git a/docs/OPS.md b/docs/OPS.md index e432d00a..cf02fa96 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -635,6 +635,8 @@ copy. |---|---|---| | `had_quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `gated_had_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | +| `gated_had_quant_i8g` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | +| `rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gate_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? | | `rmsnorm_quant_i8` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? | | `gelu_mul_quant_i8` | `M` `n` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? | @@ -642,6 +644,15 @@ copy. `gelu_mul_quant_i8` is `gelu_mul` with `rmsnorm_quant_i8`'s quantiser on its pass, byte-identical to the pair. +`gated_had_quant_i8g` and `rmsnorm_had_quant_i8g` are `gated_quant_fp8` and `rmsnorm_quant_fp8` +with `had_quant_act_i8g`'s quantiser on their pass: the `group`-wide rotation of the bf16-rounded +value, then int8 codes per (row, `group`), byte-identical to the producer followed by +`had_quant_act_i8g`. They feed a weight at `i8a8h` without the activation quantiser of its own: +one launch for a norm read by three projections (q, k and v), and none between the gated product and +the down projection. `out_bf16` receives the unrotated value, for a bf16 consumer. `n` is a +multiple of `group`. A rotated code read as a plain one, or the reverse, gives a model that runs +and is wrong, so these are separate ops, as `gated_had_quant_fp8` is. + `rmsnorm_quant_i8` is `rmsnorm` with `quant_act_i8`'s quantiser on its pass: step-order int8 codes and one f32 scale per row, what `gemm_nt_q` reads at `dtype=w4a8` and `w8a8`. With `residual` the norm is of `residual + x`, stored back; `w_post` normalises `x` before that add and `scalar` (`[1]`) @@ -2097,6 +2108,7 @@ device code. |---|---|---| | `ar_rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `ar_rmsnorm_post_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w | +| `ar_rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? | | `ar_hc_write` | `M`(range) `n` `hc` `world_size` `dtype` `wire`/opt | `y`:inout, `inj`, `h`:inout | | `ar_gather_hc_write` | `M`(range) `n` `hc` `top_k` `world_size` `dtype` `act`/opt `wire`/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`?, `y`:inout, `inj`, `h`:inout | @@ -2106,6 +2118,8 @@ device code. `wire` is the payload width on the link: 0 is exact bf16, 6 the rotated six-bit form. It is a parameter for the same reason as `min_bytes`. `x` is inout on `ar_rmsnorm_quant_fp8`: it is both the message and the input, and the reduced sum lands in it. +`ar_rmsnorm_had_quant_i8g` is `ar_rmsnorm_quant_fp8` with `rmsnorm_had_quant_i8g`'s quantiser: +`x` and the residual are the same bytes, and the codes are int8 for a weight at `i8a8h`. The norm-carrying forms are two-rank only. `ar_hc_write` and `ar_gather_hc_write` also have an exact-wire four-rank form. At other widths the arch blocks issue the plain ops. diff --git a/libr4d/r4d.h b/libr4d/r4d.h index adc78ab3..e62ee672 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -713,6 +713,15 @@ int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, long s, int int q_ld, int s_ld, long stream); int r4d_gated_quant_fp8(long gu, long y, long q, long s, int M, int n, int mode, int gu_ld, int y_ld, int q_ld, int s_ld, long stream); +// The two above with had_quant_act_i8g's quantiser on the pass instead (the `_had_quant_i8g` +// forms): the width-128 Hadamard, then int8 codes at amax / 127 per (row, 128), for a weight at +// i8a8h. `q` is int8, `n` a multiple of 128, and `y` keeps the unrotated bf16 value. The codes +// are the producer + had_quant_act_i8g pair's bytes. +int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long q, long s, int M, int n, + float eps, float wadd, int w_f32, int x_ld, int r_ld, int y_ld, + int q_ld, int s_ld, long stream); +int r4d_gated_had_quant_i8g(long gu, long y, long q, long s, int M, int n, int mode, + int gu_ld, int y_ld, int q_ld, int s_ld, long stream); // The activation is rounded to bf16 before the product, matching the unfused `sigmoid` then `mul` // pair with a bf16 buffer between them. // The same epilogue with the gate in a different buffer from what it scales, as in gated @@ -738,6 +747,15 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag int nblocks, int nthreads, int drain, int acq, int wire, long loc_pack, long loc_scale_off, long wp = 0); int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void); +// Its rotated int8 form, as r4d_rmsnorm_had_quant_i8g: the reduction and the norm unchanged, the +// norm's pass quantised by had_quant_act_i8g's rule. No post-norm. +int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_flags, + long my_flags, long seq_ctrs, long slot_stride16, + long x, long res, long w, long y, long q, long s, + int M, int n, float eps, float wadd, int w_f32, + int r_ld, int y_ld, int q_ld, int s_ld, long stream, + int nblocks, int nthreads, int drain, int acq, int wire, + long loc_pack, long loc_scale_off); // The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of // the reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8 diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 4c532109..f735b5b9 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -1240,7 +1240,9 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { * chooses it as the standalone `all_reduce` row would (lossy wire allowed, group tiles the message, * size above --tp-wire-min-kb), and both ranks decide on the same T. A wire-6 chunk that would * straddle a row is refused as a shape. */ -extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { +/* `hi8`: ar_rmsnorm_had_quant_i8g, the same with had_quant_act_i8g's quantiser on the norm's pass + * (int8 codes, K whole 128s, no post-norm). */ +static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); if (!in) return RAD_E_STATE; if (in->world != 2) return RAD_E_SHAPE; @@ -1252,9 +1254,11 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const RadTensor* sc = r4d_opt(a, AL_SCALE); const RadTensor* ob = r4d_opt(a, AL_OUTBF16); /* ar_rmsnorm_quant_fp8's optional post-norm (Gemma 3's sandwich); ar_ln_had_quant_i8 has no - * seventh operand, and this function serves only the fp8 op. */ + * seventh operand, and this function serves only the fp8 op and its rotated int8 twin. */ const RadTensor* wpo = r4d_opt(a, AL_WPOST); if (!x || !w || !q || !sc) return RAD_E_INVAL; + if (hi8 && q->dtype != RAD_I8) return RAD_E_DTYPE; + if (hi8 && wpo) return RAD_E_UNSUPPORTED; if (!r4d_contig(w)) return RAD_E_STRIDE; if (wpo && (!rs || !r4d_contig(wpo) || r4d_numel(wpo) != r4d_numel(w) || wpo->dtype != w->dtype)) return RAD_E_SHAPE; @@ -1272,6 +1276,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const long long grp = r4d_quant_act_fp8_group(); const long long nkb = (K + grp - 1) / grp; if (r4d_geti_or(a, "group", grp) != grp) return RAD_E_SHAPE; + if (hi8 && K % grp) return RAD_E_SHAPE; if (r4d_numel(w) != K) return RAD_E_SHAPE; if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return RAD_E_DTYPE; if (q->shape[0] != M || q->shape[1] != K) return RAD_E_SHAPE; @@ -1327,17 +1332,34 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { if (nblocks > in->max_blocks) nblocks = in->max_blocks; if (nblocks < 1) nblocks = 1; - const int e = r4d_ar_rmsnorm_quant_fp8( - in->peer_scratch[0], in->my_scratch, - in->peer_flags[0], in->my_flags, in->my_seq, - in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(ob), r4d_addr(q), - r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32, - (int)rp, (int)yp, (int)qp, (int)sp, - (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire, - in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0); + const int e = hi8 + ? r4d_ar_rmsnorm_had_quant_i8g( + in->peer_scratch[0], in->my_scratch, + in->peer_flags[0], in->my_flags, in->my_seq, + in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(ob), r4d_addr(q), + r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32, + (int)rp, (int)yp, (int)qp, (int)sp, + (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire, + in->locpack, in->slot_bytes / 2) + : r4d_ar_rmsnorm_quant_fp8( + in->peer_scratch[0], in->my_scratch, + in->peer_flags[0], in->my_flags, in->my_seq, + in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(ob), r4d_addr(q), + r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32, + (int)rp, (int)yp, (int)qp, (int)sp, + (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire, + in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0); return e == 0 ? RAD_OK : RAD_E_SHAPE; } +extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { + return rad_ar_rmsnorm_quant(a, s, false); +} + +extern "C" int r4d_rad_ar_rmsnorm_had_quant_i8g(const RadArgs* a, RadStream s) { + return rad_ar_rmsnorm_quant(a, s, true); +} + /* The all-reduce and the sandwich-norm junction after it, int8 out: exact `all_reduce` of `x`, then * `rmsnorm_quant_i8` (post-norm of the reduced x, residual add, scalar, norm and the per-row int8 * quantiser the w4a8 skinny GEMM reads). Operands are rmsnorm_quant_i8's with `x` inout, since the diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index ea31d0dd..4f9853f0 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -101,7 +101,13 @@ __device__ __forceinline__ void quant_group(const float v[4], float* __restrict_ // consecutive columns, so the group's amax is a wave reduction and the store a single dword. `nr` // is the row the norm is taken of, already in memory (see the bit-identity note above). Shared so // the fused all-reduce cannot drift from the standalone norm. -template +// +// HI8 is had_quant_act_i8g's form (the `_had_quant_i8g` ops): the width-128 Hadamard between the +// bf16-rounded norm output and the absmax, then int8 codes, as gated_quant_fp8_kernel's ROT and I8 +// together. r4d_quant_act_fp8's kernel has the same mapping, rotation and rounding, so the codes +// are the norm + had_quant_act_i8g pair's bytes. `y` still receives the unrotated norm output. +// The launchers require n % 128 == 0, so no rotated group contains padding. +template __device__ __forceinline__ void norm_quant_row( const uint16_t* __restrict__ nr, const void* __restrict__ w, uint16_t* __restrict__ yr, uint8_t* __restrict__ qr, float* __restrict__ s, size_t s_row, uint32_t n, uint32_t nkb, @@ -128,13 +134,14 @@ __device__ __forceinline__ void norm_quant_row( v[j] = bf2f(h); } } - quant_group(v, s, qr, s_row + kb, c0, n, lane); + if constexpr (HI8) r4d_fwht_wave<(int)kGroup>(v, (int)lane); + quant_group(v, s, qr, s_row + kb, c0, n, lane); } } // ---------------------------------------------------------------------------- rmsnorm -> quant // One block per row. Pass one is the block-wide sum of squares; pass two is norm_quant_row. -template +template __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, uint16_t* __restrict__ y, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, @@ -178,8 +185,8 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel( } const float rs = rsqrtf(block_sum(ss, lds) / (float)n + eps); - norm_quant_row(nr, w, y ? y + (size_t)row * y_ld : nullptr, q + (size_t)row * q_ld, - s, (size_t)row * s_ld, n, nkb, rs, wadd); + norm_quant_row(nr, w, y ? y + (size_t)row * y_ld : nullptr, + q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs, wadd); } // ---------------------------------------------------------------------------- gate -> quant @@ -366,7 +373,10 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) { // POST: a sandwich-norm junction (Gemma 3): the reduced sum is post-normed against `wp` before the // residual add, `v = bf16(sum * s1 * (wp + wadd))` with s1 the sum's own rms, as rmsnorm_quant_i8's // POST computes it. `x` still receives the reduced sum. Exact wire and a residual only. -template +// +// HI8: ar_rmsnorm_had_quant_i8g, pass two in norm_quant_row's rotated int8 form. The reduction and +// the norm are untouched, so `x`, the residual and `y` are ar_rmsnorm_quant_fp8's bytes. +template __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, const void* __restrict__ wp, @@ -584,8 +594,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( } /* block_sum's barrier is also what publishes pass one's stores to pass two's reads. */ const float rs = rsqrtf(block_sum(ss, lds) / (float)n + eps); - norm_quant_row(nr, w, y ? y + (size_t)row * y_ld : nullptr, - q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs, wadd); + norm_quant_row(nr, w, y ? y + (size_t)row * y_ld : nullptr, + q + (size_t)row * q_ld, s, (size_t)row * s_ld, n, nkb, rs, + wadd); /* lds is reused by this block's next row; without the barrier a thread still reading it * would race the next row's write. */ __syncthreads(); @@ -606,14 +617,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( // res [M][n] bf16, `r_ld` elements a row (0 = n), optional, read and written // w [n] f32 or bf16 // y [M][n] bf16, `y_ld` elements a row (0 = n), optional -// q [M][n] E4M3, `q_ld` bytes a row (0 = n), rounded up to 4 +// q [M][n] E4M3 (rotated int8 when `hi8`), `q_ld` bytes a row (0 = n), rounded +// up to 4 // s [M][ceil(n/128)] f32, `s_ld` elements a row (0 = ceil(n/128)) -extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, long s, int M, int n, - float eps, float wadd, int w_f32, int x_ld, int r_ld, - int y_ld, int q_ld, int s_ld, long stream) { +// +// `hi8` additionally requires n % 128 == 0, as gated_quant_fp8_launch's `rot`. +static int rmsnorm_quant_launch(long x, long res, long w, long y, long q, long s, int M, int n, + float eps, float wadd, int w_f32, int x_ld, int r_ld, int y_ld, + int q_ld, int s_ld, long stream, bool hi8) { if (!x || !w || !q || !s) return -1; if (M <= 0 || n <= 0) return -2; if (n % 4) return -3; // a lane owns four columns; see the kernel + if (hi8 && (n % (int)kGroup)) return -6; if (!x_ld) x_ld = n; if (!r_ld) r_ld = n; if (!y_ld) y_ld = n; @@ -627,12 +642,14 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l // rmsnorm_bf16 must pick the same width from the same function: the width decides which // columns a thread sums, so a different width changes the last bits and breaks bit identity. const int thr = r4d_act_threads(M, n); -#define R4D_RQ_T(wf, rs, T) \ - hipLaunchKernelGGL((rmsnorm_quant_fp8_kernel), dim3((uint32_t)M), dim3(T), 0, \ +#define R4D_RQ_H(wf, rs, T, H) \ + hipLaunchKernelGGL((rmsnorm_quant_fp8_kernel), dim3((uint32_t)M), dim3(T), 0, \ (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)res, (const void*)w, \ (uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, eps, \ wadd, (uint32_t)x_ld, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \ (uint32_t)s_ld) +#define R4D_RQ_T(wf, rs, T) \ + do { if (hi8) R4D_RQ_H(wf, rs, T, true); else R4D_RQ_H(wf, rs, T, false); } while (0) #define R4D_RQ(wf, rs) \ do { if (thr == 1024) R4D_RQ_T(wf, rs, 1024); \ else if (thr == 512) R4D_RQ_T(wf, rs, 512); \ @@ -641,9 +658,26 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l else { if (res) R4D_RQ(false, true); else R4D_RQ(false, false); } #undef R4D_RQ #undef R4D_RQ_T +#undef R4D_RQ_H return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, long s, int M, int n, + float eps, float wadd, int w_f32, int x_ld, int r_ld, + int y_ld, int q_ld, int s_ld, long stream) { + return rmsnorm_quant_launch(x, res, w, y, q, s, M, n, eps, wadd, w_f32, x_ld, r_ld, y_ld, + q_ld, s_ld, stream, false); +} + +// The same norm with had_quant_act_i8g's quantiser on its pass: the width-128 Hadamard, then int8 +// codes at amax / 127 per (row, 128). For a rotated int8 linear (dtype i8a8h); `q` is int8. +extern "C" int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long q, long s, int M, + int n, float eps, float wadd, int w_f32, int x_ld, + int r_ld, int y_ld, int q_ld, int s_ld, long stream) { + return rmsnorm_quant_launch(x, res, w, y, q, s, M, n, eps, wadd, w_f32, x_ld, r_ld, y_ld, + q_ld, s_ld, stream, true); +} + // `mode` is 0 for silu (down_proj's input) and 1 for sigmoid (a gated attention o_proj's), as in // r4d_gated_had_quant_i8. // @@ -654,6 +688,8 @@ extern "C" int r4d_rmsnorm_quant_fp8(long x, long res, long w, long y, long q, l // // `rot` additionally requires n % 128 == 0: a ragged last group is fine unrotated (zero-padded, // masked by the GEMM) but a butterfly mixing real values with padding has no matching weight block. +// `rot` with `i8` is had_quant_act_i8g's form (gated_had_quant_i8g), for a rotated int8 down +// projection; `rot` alone pairs with a rotated four-bit expert, which reads E4M3. static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, int mode, int gu_ld, int y_ld, int q_ld, int s_ld, RadStream stream, bool rot, bool i8 = false) { @@ -663,8 +699,6 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, if (n % 4) return -3; if (mode != 0 && mode != 1) return -5; if (rot && (n % (int)kGroup)) return -6; - // The rotated codes pair with a rotated four-bit expert, which reads E4M3 only. - if (rot && i8) return -7; if (!gu_ld) gu_ld = 2 * n; if (!y_ld) y_ld = n; if (!q_ld) q_ld = n; @@ -679,7 +713,8 @@ static int gated_quant_fp8_launch(long gu, long y, long q, long s, int M, int n, (float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)gu_ld, (uint32_t)y_ld, \ (uint32_t)q_ld, (uint32_t)s_ld) #define R4D_GQ(a) \ - do { if (rot) R4D_GQ_R(a, true, false); \ + do { if (rot && i8) R4D_GQ_R(a, true, true); \ + else if (rot) R4D_GQ_R(a, true, false); \ else if (i8) R4D_GQ_R(a, false, true); \ else R4D_GQ_R(a, false, false); } while (0) if (mode == 0) R4D_GQ(0); @@ -702,6 +737,13 @@ extern "C" int r4d_gated_had_quant_fp8(long gu, long y, long q, long s, int M, i (RadStream)(uintptr_t)stream, true); } +// The same product with had_quant_act_i8g's quantiser: `q` is int8. +extern "C" int r4d_gated_had_quant_i8g(long gu, long y, long q, long s, int M, int n, int mode, + int gu_ld, int y_ld, int q_ld, int s_ld, long stream) { + return gated_quant_fp8_launch(gu, y, q, s, M, n, mode, gu_ld, y_ld, q_ld, s_ld, + (RadStream)(uintptr_t)stream, true, true); +} + // act . x with the gate and x in separate buffers; see the kernel for why a row is a (token, head) // pair and why the activation is rounded to bf16 before the product. `mode` as in // r4d_gated_quant_fp8. @@ -760,15 +802,19 @@ extern "C" int r4d_gate_quant_fp8(long g, long x, long y, long q, long s, int M, // `res` behaves as in r4d_rmsnorm_quant_fp8. Returns 0, or a negative code for an unserved shape. extern "C" int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void) { return ARQ_CE; } -extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags, - long my_flags, long seq_ctrs, long slot_stride16, - long x, long res, long w, long y, long q, long s, - int M, int n, float eps, float wadd, int w_f32, - int r_ld, int y_ld, int q_ld, int s_ld, long stream, - int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off, long wp) { +// `hi8` is the rotated int8 form (ar_rmsnorm_had_quant_i8g): `q` is int8, n % 128 == 0, and there +// is no post-norm. +static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer_flags, + long my_flags, long seq_ctrs, long slot_stride16, + long x, long res, long w, long y, long q, long s, + int M, int n, float eps, float wadd, int w_f32, + int r_ld, int y_ld, int q_ld, int s_ld, long stream, + int nblocks, int nthreads, int drain, int acq, int wire, + long loc_pack, long loc_scale_off, long wp, bool hi8) { if (!x || !w || !q || !s) return -1; if (wp && (!res || wire != 0)) return -10; // a post-norm needs the stream and the exact wire + if (hi8 && wp) return -11; + if (hi8 && (n % (int)kGroup)) return -12; if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1; if (M <= 0 || n <= 0) return -2; // n % 8: n bf16 is a whole number of 16B words (see the push), which also gives every lane its @@ -791,9 +837,9 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long // The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order). const int thr = nthreads ? nthreads : r4d_act_threads(M, n); if (thr != 256 && thr != 512 && thr != 1024) return -6; -#define R4D_ARQ_P(wf, rs, T, W, PO) \ - hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel), dim3((uint32_t)nb), dim3(T), \ - 0, \ +#define R4D_ARQ_H(wf, rs, T, W, PO, H) \ + hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel), dim3((uint32_t)nb), \ + dim3(T), 0, \ (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, (const void*)w, \ (const void*)wp, \ (uint16_t*)y, (uint8_t*)q, (float*)s, (int4*)peer_scratch, \ @@ -802,7 +848,10 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long (long)loc_scale_off, M, (uint32_t)n, \ (uint32_t)nkb, eps, wadd, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \ (uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw) -#define R4D_ARQ_T(wf, rs, T, W) R4D_ARQ_P(wf, rs, T, W, false) +#define R4D_ARQ_P(wf, rs, T, W, PO) R4D_ARQ_H(wf, rs, T, W, PO, false) +#define R4D_ARQ_T(wf, rs, T, W) \ + do { if (hi8) R4D_ARQ_H(wf, rs, T, W, false, true); \ + else R4D_ARQ_P(wf, rs, T, W, false); } while (0) #define R4D_ARQ_W(wf, rs, T) \ do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \ else if (rs && wp) R4D_ARQ_P(wf, rs, T, 0, true); \ @@ -817,9 +866,37 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long #undef R4D_ARQ_W #undef R4D_ARQ_T #undef R4D_ARQ_P +#undef R4D_ARQ_H return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags, + long my_flags, long seq_ctrs, long slot_stride16, + long x, long res, long w, long y, long q, long s, + int M, int n, float eps, float wadd, int w_f32, + int r_ld, int y_ld, int q_ld, int s_ld, long stream, + int nblocks, int nthreads, int drain, int acq, int wire, + long loc_pack, long loc_scale_off, long wp) { + return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs, + slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32, + r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq, + wire, loc_pack, loc_scale_off, wp, false); +} + +// The same with had_quant_act_i8g's quantiser on the norm's pass (no post-norm). +extern "C" int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_flags, + long my_flags, long seq_ctrs, long slot_stride16, + long x, long res, long w, long y, long q, long s, + int M, int n, float eps, float wadd, int w_f32, + int r_ld, int y_ld, int q_ld, int s_ld, long stream, + int nblocks, int nthreads, int drain, int acq, + int wire, long loc_pack, long loc_scale_off) { + return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs, + slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32, + r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq, + wire, loc_pack, loc_scale_off, 0, true); +} + // ============================================================== the plugin ABI entry points // // The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h. @@ -828,7 +905,9 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long * The standalone quantiser's shape rules, applied to the operand that produces the row. The bf16 * output is optional so a layer without a bf16 consumer skips the store. */ -extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { +/* `hi8`: rmsnorm_had_quant_i8g, whose codes are int8 and whose row is whole 128s (the rotation's + * width). Separate ops for the reason given at r4d_rad_gated_had_quant_fp8. */ +static int rad_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) { const RadTensor* x = r4d_opt(a, RQ_X); const RadTensor* rs = r4d_opt(a, RQ_RES); const RadTensor* w = r4d_opt(a, RQ_W); @@ -836,7 +915,7 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { const RadTensor* sc = r4d_opt(a, RQ_S); const RadTensor* y = r4d_opt(a, RQ_Y); if (!x || !w || !q || !sc) return R4D_NO(RAD_E_INVAL); - if (q->dtype != RAD_F8E4M3) return R4D_NO(RAD_E_DTYPE); + if (q->dtype != (hi8 ? RAD_I8 : RAD_F8E4M3)) return R4D_NO(RAD_E_DTYPE); /* Rank 2 on the input too, unlike the standalone quantiser: a norm has one gain per channel, * and folding trailing dims would spread a gain across heads. */ if (x->rank != 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE); @@ -850,21 +929,30 @@ extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { if (q->shape[0] != M || q->shape[1] != K) return R4D_NO(RAD_E_SHAPE); if (sc->shape[0] != M || sc->shape[1] != nkb) return R4D_NO(RAD_E_SHAPE); if (y && (y->shape[0] != M || y->shape[1] != K)) return R4D_NO(RAD_E_SHAPE); + if (hi8 && K % grp) return R4D_NO(RAD_E_SHAPE); /* The residual has the input's extent and is read and written. It may alias `out_bf16` (see * the note at the top of the file). */ if (rs && (rs->rank != 2 || rs->shape[0] != M || rs->shape[1] != K)) return R4D_NO(RAD_E_SHAPE); const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); const long long yp = y ? r4d_row_pitch(y) : 0, rp = rs ? r4d_row_pitch(rs) : 0; if (xp < 0 || qp < 0 || sp < 0 || yp < 0 || rp < 0) return R4D_NO(RAD_E_STRIDE); - const int e = r4d_rmsnorm_quant_fp8(r4d_addr(x), rs ? r4d_addr(rs) : 0, r4d_addr(w), - y ? r4d_addr(y) : 0, r4d_addr(q), r4d_addr(sc), - (int)M, (int)K, - (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), - w->dtype == RAD_F32, (int)xp, (int)rp, (int)yp, (int)qp, - (int)sp, (long)(uintptr_t)s); + const int e = rmsnorm_quant_launch(r4d_addr(x), rs ? r4d_addr(rs) : 0, r4d_addr(w), + y ? r4d_addr(y) : 0, r4d_addr(q), r4d_addr(sc), + (int)M, (int)K, + (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), + w->dtype == RAD_F32, (int)xp, (int)rp, (int)yp, (int)qp, + (int)sp, (long)(uintptr_t)s, hi8); return e == 0 ? RAD_OK : RAD_E_SHAPE; } +extern "C" int r4d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { + return rad_rmsnorm_quant(a, s, false); +} + +extern "C" int r4d_rad_rmsnorm_had_quant_i8g(const RadArgs* a, RadStream s) { + return rad_rmsnorm_quant(a, s, true); +} + /* The gate's activation: `act` by name overrides `mode` (libr4d's integer: 0 silu, 1 sigmoid) when * both are given, as for r4d_gated_had_quant_i8. Returns -1 for an unknown name. */ static int act_mode(const RadArgs* a, int dflt) { @@ -875,15 +963,17 @@ static int act_mode(const RadArgs* a, int dflt) { return -1; } -static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot) { +/* `hi8` (with `rot`): gated_had_quant_i8g, int8 codes only. */ +static int rad_gated_quant_fp8(const RadArgs* a, RadStream stream, bool rot, bool hi8 = false) { const RadTensor* gu = r4d_opt(a, GQ_GU); const RadTensor* q = r4d_opt(a, GQ_Q); const RadTensor* sc = r4d_opt(a, GQ_S); const RadTensor* y = r4d_opt(a, GQ_Y); if (!gu || !q || !sc) return R4D_NO(RAD_E_INVAL); - /* The codes' dtype picks the quantiser: E4M3, or int8 for an int8 down projection. */ + /* The codes' dtype picks the quantiser: E4M3, or int8 for an int8 down projection. The two + * rotated ops each take one: E4M3 for a four-bit expert, int8 for a rotated int8 weight. */ if (q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE); - if (rot && q->dtype == RAD_I8) return R4D_NO(RAD_E_DTYPE); + if (rot && q->dtype != (hi8 ? RAD_I8 : RAD_F8E4M3)) return R4D_NO(RAD_E_DTYPE); if (gu->rank != 2 || q->rank != 2 || sc->rank != 2) return R4D_NO(RAD_E_SHAPE); if (y && y->rank != 2) return R4D_NO(RAD_E_SHAPE); const long long M = gu->shape[0], K = q->shape[1]; @@ -916,6 +1006,11 @@ extern "C" int r4d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream stream) { return rad_gated_quant_fp8(a, stream, true); } +/* Its int8 twin, had_quant_act_i8g's codes: pairs only with a weight stored at dtype i8a8h. */ +extern "C" int r4d_rad_gated_had_quant_i8g(const RadArgs* a, RadStream stream) { + return rad_gated_quant_fp8(a, stream, true, true); +} + /* Elements between consecutive `width`-wide rows, as r4d_gdn.cpp's gn_row_pitch: a * [.., heads, width] operand steps by the stride of the second-to-last axis; a flattened one is * contiguous and steps by `width`. This reads a column view of an interleaved projection (a gated diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 9868aab9..689f39cf 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -381,6 +381,7 @@ int r4d_rad_ar_twoshot_4rank_ti8 (const RadArgs*, RadStream); int r4d_rad_ar_ln_init(const RadParam*, int, int rank, int world, void** out); int r4d_rad_ar_ln_had_quant_i8(const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs*, RadStream); +int r4d_rad_ar_rmsnorm_had_quant_i8g(const RadArgs*, RadStream); int r4d_rad_ar_hc_write(const RadArgs*, RadStream); /* ar_hc_write at four ranks, exact wire only, on an instance of the wide family keyed by its own * M bound. */ @@ -493,8 +494,10 @@ int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_had_quant_act_fp8 (const RadArgs*, RadStream); int r4d_rad_givens_rotate (const RadArgs*, RadStream); int r4d_rad_rmsnorm_quant_fp8(const RadArgs*, RadStream); +int r4d_rad_rmsnorm_had_quant_i8g(const RadArgs*, RadStream); int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream); int r4d_rad_gated_had_quant_fp8(const RadArgs*, RadStream); +int r4d_rad_gated_had_quant_i8g(const RadArgs*, RadStream); int r4d_rad_gate_quant_fp8 (const RadArgs*, RadStream); int r4d_rad_gram_accum (const RadArgs*, RadStream); /* The same accumulator over a plain bf16 activation, no scale operand. */ @@ -783,6 +786,7 @@ int r4d_shape_all_reduce (const RadParam*, int, int operand, RadOpdDes int r4d_shape_all_gather (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_ar_ln_had_quant_i8 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_ar_rmsnorm_quant_fp8 (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_ar_rmsnorm_had_quant_i8g (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_ar_hc_write (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_ar_gather_hc_write (const RadParam*, int, int operand, RadOpdDesc*); @@ -813,6 +817,8 @@ int r4d_shape_gdn_gated_norm_had_quant_i8(const RadParam*, int, int operand, int r4d_shape_quant_act_fp8 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_rmsnorm_quant_fp8 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gated_quant_fp8 (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_rmsnorm_had_quant_i8g (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_gated_had_quant_i8g (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gate_quant_fp8 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gram_accum (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_block_key (const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index e27aa13e..bf59cad7 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -3070,6 +3070,11 @@ static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm_quant_fp8", pRmsNormQuantFp8, oRmsNormQuantFp8, "RMS norm and the fp8 activation quantiser in one pass over the row. The bf16 norm " "output the unfused pair wrote is still written, and the codes are taken over it."), + SCHEMA("rmsnorm_had_quant_i8g", pRmsNormQuantFp8, oRmsNormQuantFp8, + "rmsnorm_quant_fp8 with had_quant_act_i8g's quantiser on its pass: a `group`-wide " + "Hadamard of the bf16 norm output, then int8 codes per (row, `group`). `out_bf16` " + "receives the UNROTATED norm output. Pairs only with an i8 weight stored rotated " + "(dtype i8a8h); byte-identical to the norm and had_quant_act_i8g."), SCHEMA("rmsnorm_quant_i8", pRmsNormQuantI8, oRmsNormQuantI8, "RMS norm and the per-row int8 quantiser the w4a8 skinny GEMM reads, in one pass; with " "a residual the norm is of residual + x (+ a post-norm of x, x a scalar), stored back."), @@ -3089,6 +3094,11 @@ static const RadOpSchema kSchemas[] = { "the rotation is a property of the quantised pair alone. Pairs with a weight stored at " "dtype w4a8h; substituting it for gated_quant_fp8, or the reverse, produces a model " "that runs and is wrong."), + SCHEMA("gated_had_quant_i8g", pGatedQuantFp8, oGatedQuantFp8, + "gated_had_quant_fp8 at int8 codes: silu(a)*b or sigmoid(a)*b, a `group`-wide Hadamard " + "and had_quant_act_i8g's quantiser, in one pass. `out_bf16` receives the UNROTATED " + "product. Pairs only with an i8 weight stored rotated (dtype i8a8h); byte-identical " + "to the product and had_quant_act_i8g."), SCHEMA("gemm_nt_q_gated", pGemmNtQGated, oGemmNtQGated, "gemm_nt_q over a [2n, K] gate_up plane with gated_quant_fp8's pass folded into the " "epilogue: the outputs are the quantiser's E4M3 codes, its scale per (row, `group` " @@ -3206,6 +3216,9 @@ static const RadOpSchema kSchemas[] = { SCHEMA("ar_rmsnorm_quant_fp8", pArRmsNormQuantFp8, oArRmsNormQuantFp8, "the two-rank all-reduce and the residual add, RMS norm and block-scaled fp8 " "quantisation that always follow it, in one kernel. Both wires."), + SCHEMA("ar_rmsnorm_had_quant_i8g", pArRmsNormQuantFp8, oArRmsNormQuantFp8, + "the two-rank all-reduce of x and rmsnorm_had_quant_i8g after it, in one kernel; " + "either wire, as ar_rmsnorm_quant_fp8."), SCHEMA("ar_hc_write", pArHcWrite, oArHcWrite, "the all-reduce and the gated residual's write that follows it, in one kernel. Both " "wires at two ranks, the exact one at four."), @@ -4368,6 +4381,16 @@ static const RadConstraint cArRmsNormQuantFp8[] = { C_EQ("world_size", 2), C_P2P, }; +/* The rotated int8 twins: `n DIV 128`, since a rotation block cannot straddle the end of a row + * (which also gives the all-reduce's 16B words). */ +static const RadConstraint cRmsNormHadQuantI8g[] = { + C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), +}; +static const RadConstraint cArRmsNormHadQuantI8g[] = { + C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), + C_EQ("world_size", 2), + C_P2P, +}; /* hc_write's own bounds plus the all-reduce's: `n DIV 8` because `y` is pushed as 16B words, and * world_size 2 because the handshake is one peer flag per block. */ static const RadConstraint cArHcWrite[] = { @@ -7472,6 +7495,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, /* `add` + `rmsnorm` + `quant_act_fp8`, not `rmsnorm_add` (r4d_fuse.cpp). */ r4d_fuse_rmsnorm_quant_fp8 }, +/* The rotated int8 twin, for a trunk of weights stored at i8a8h: the same kernel with + * had_quant_act_i8g's quantiser on its second pass. No fusion hook: the architecture declares it. */ +{ "rmsnorm_had_quant_i8g", "rmsnorm_had_quant_i8g", "quant", + "RMS norm, a 128-wide Hadamard and the per-(row, 128) int8 quantiser in one pass over the row, " + "plus the bf16 norm output", + "n a multiple of 128 -- a rotation block cannot straddle the end of a row; one workgroup per row " + "and two passes over it, as rmsnorm_quant_fp8; the gain is f32 or bf16; group 128, both the " + "rotation width and the scale's block width; an optional residual may ALIAS out_bf16", + "bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out that " + "receives the UNROTATED norm output; the codes are taken over the rotated BF16-ROUNDED norm " + "output, byte-identical to rmsnorm + had_quant_act_i8g", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRmsNormHadQuantI8g), NOTUNE, + nullptr, nullptr, r4d_rad_rmsnorm_had_quant_i8g, nullptr, nullptr, nullptr, + r4d_shape_rmsnorm_had_quant_i8g }, + { "gated_quant_fp8", "gated_quant_fp8", "quant", "an elementwise gated product and the fp8 activation quantiser in one pass; `act` silu is " "down_proj's input and sigmoid is a gated o_proj's", @@ -7502,6 +7541,21 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gated_had_quant_fp8, nullptr, nullptr, nullptr, r4d_shape_gated_quant_fp8 }, +/* Its int8 twin, for a down projection whose weight is stored at i8a8h. */ +{ "gated_had_quant_i8g", "gated_had_quant_i8g", "quant", + "an elementwise gated product, a 128-wide Hadamard along n, and the per-(row, 128) int8 " + "quantiser, in one pass", + "n a multiple of 128 -- a rotation block cannot straddle the end of a row; the gated operand is " + "[M][2n], gate then up; no reduction across the row, so no barrier; group 128, both the " + "rotation width and the scale's block width; strides in elements", + "bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out that " + "receives the UNROTATED product; the codes are taken over the rotated BF16-ROUNDED product, " + "byte-identical to the product + had_quant_act_i8g", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGatedHadQuantFp8), NOTUNE, + nullptr, nullptr, r4d_rad_gated_had_quant_i8g, nullptr, nullptr, nullptr, + r4d_shape_gated_had_quant_i8g }, + { "gate_quant_fp8", "gate_quant_fp8", "quant", "an elementwise gated product and the fp8 activation quantiser in one pass, with the gate in " "its own operand: a gated attention's gate is a column slice of the [q|gate] projection and " @@ -7671,6 +7725,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, /* `all_reduce` + `rmsnorm_quant_fp8`, both wires (r4d_fuse.cpp). */ r4d_fuse_ar_rmsnorm_quant_fp8 }, +{ "ar_rmsnorm_had_quant_i8g", "ar_rmsnorm_had_quant_i8g", "quant", + "the two-rank all-reduce and the residual add, RMS norm, 128-wide Hadamard and per-(row, 128) " + "int8 quantisation that always follow it, in one kernel; the all-reduce's output is never read " + "back", + "exactly 2 ranks; n a multiple of 128 (a rotation block cannot straddle a row) and x unpitched; " + "group 128; a block owns whole ROWS, so the block count is clamped to M; either wire, chosen by " + "`wire` -- the rotated 6-bit payload additionally needs n to be a multiple of 512; residual and " + "out_bf16 may be null", + "bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out of the " + "UNROTATED norm output; x and the residual are ar_rmsnorm_quant_fp8's bytes, and the codes " + "rmsnorm_had_quant_i8g's over the same norm output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cArRmsNormHadQuantI8g), ROW(tAr), nullptr, + r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_had_quant_i8g, nullptr, nullptr, nullptr, + r4d_shape_ar_rmsnorm_had_quant_i8g }, + { "ar_rmsnorm_post_quant_fp8", "ar_rmsnorm_post_quant_fp8", "quant", "the two-rank all-reduce, a post-norm of the reduced sum, the residual add, RMS norm and " "block-scaled fp8 quantisation in one kernel: a sandwich-norm junction (Gemma 3)", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index ecbe6124..227b8914 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -10764,6 +10764,62 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { } } + /* --- the rotated int8 twins, against their producer and had_quant_act_i8g --- + * + * For a trunk stored at i8a8h: the bf16 output must not move (it is unrotated), and codes and + * scales must equal had_quant_act_i8g's over it. K is whole 128s, as the rotation needs. */ + if (const RadKernelInfo* qh = find(pl, "had_quant_act_i8g")) { + if (const RadKernelInfo* rh = find(pl, "rmsnorm_had_quant_i8g")) { + rc = launch_row(nrm, { T(d_x, RAD_BF16, { M, K }), T(d_w, RAD_F32, { K }), + T(d_y[0], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), + PF("wadd", wadd) }); + if (rc == RAD_OK) + rc = launch_row(qh, { T(d_y[0], RAD_BF16, { M, K }), T(d_q[0], RAD_I8, { M, K }), + T(d_s[0], RAD_F32, { M, nkb }) }, + { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(rh, { T(d_x, RAD_BF16, { M, K }), T(nullptr, RAD_BF16, {}), + T(d_w, RAD_F32, { K }), + T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M, nkb }), + T(d_y[1], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PI("group", 128), + PS("dtype", "bf16"), PF("wadd", wadd) }); + if (rc != RAD_OK) ok("rmsnorm_had_quant_i8g vs rmsnorm + had_quant_act_i8g", false, + "rc=" + std::to_string(rc)); + else same("rmsnorm_had_quant_i8g is byte-identical to rmsnorm + had_quant_act_i8g"); + + rc = launch_row(rh, { T(d_x, RAD_BF16, { M, K }), T(nullptr, RAD_BF16, {}), + T(d_w, RAD_F32, { K }), + T(d_q[1], RAD_F8E4M3, { M, K }), T(d_s[1], RAD_F32, { M, nkb }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PI("group", 128), + PS("dtype", "bf16"), PF("wadd", wadd) }); + ok("rmsnorm_had_quant_i8g refuses E4M3 codes", rc != RAD_OK, "rc=" + std::to_string(rc)); + } + if (const RadKernelInfo* gh = find(pl, "gated_had_quant_i8g")) { + rc = launch_row(smu, { T(d_gu, RAD_BF16, { M, 2 * K }), T(d_y[0], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(qh, { T(d_y[0], RAD_BF16, { M, K }), T(d_q[0], RAD_I8, { M, K }), + T(d_s[0], RAD_F32, { M, nkb }) }, + { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(gh, { T(d_gu, RAD_BF16, { M, 2 * K }), T(d_q[1], RAD_I8, { M, K }), + T(d_s[1], RAD_F32, { M, nkb }), T(d_y[1], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"), + PS("act", "silu") }); + if (rc != RAD_OK) ok("gated_had_quant_i8g vs silu_mul + had_quant_act_i8g", false, + "rc=" + std::to_string(rc)); + else same("gated_had_quant_i8g is byte-identical to silu_mul + had_quant_act_i8g"); + + rc = launch_row(gh, { T(d_gu, RAD_BF16, { M, 2 * K }), T(d_q[1], RAD_F8E4M3, { M, K }), + T(d_s[1], RAD_F32, { M, nkb }) }, + { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16"), + PS("act", "silu") }); + ok("gated_had_quant_i8g refuses E4M3 codes", rc != RAD_OK, "rc=" + std::to_string(rc)); + } + } + /* --- add + rmsnorm + quant_act_fp8, against the same three fused --- * * The residual sum is f32, and the replaced pair rounds it to bf16 in `add`'s store before @@ -10814,6 +10870,47 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { ok("rmsnorm_quant_fp8 leaves the same residual behind", nd == 0, "differs " + std::to_string(nd)); } + + /* --- add + rmsnorm + had_quant_act_i8g, against rmsnorm_had_quant_i8g's residual form --- */ + const RadKernelInfo* qh = find(pl, "had_quant_act_i8g"); + const RadKernelInfo* rh = find(pl, "rmsnorm_had_quant_i8g"); + if (!qh || !rh) return; + st_memcpy(d_r[0], hr.data(), hr.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_r[1], hr.data(), hr.size() * 2, hipMemcpyHostToDevice); + rc = launch_row(ad, { T(d_r[0], RAD_BF16, { M, K }), T(d_x, RAD_BF16, { M, K }), + T(d_r[0], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(nrm, { T(d_r[0], RAD_BF16, { M, K }), T(d_w, RAD_F32, { K }), + T(d_y[0], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), + PF("wadd", wadd) }); + if (rc == RAD_OK) + rc = launch_row(qh, { T(d_y[0], RAD_BF16, { M, K }), T(d_q[0], RAD_I8, { M, K }), + T(d_s[0], RAD_F32, { M, nkb }) }, + { PI("M", M), PI("n", K), PI("group", 128), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(rh, { T(d_x, RAD_BF16, { M, K }), T(d_r[1], RAD_BF16, { M, K }), + T(d_w, RAD_F32, { K }), + T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M, nkb }), + T(d_y[1], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PI("group", 128), + PS("dtype", "bf16"), PF("wadd", wadd) }); + if (rc != RAD_OK) { + ok("rmsnorm_had_quant_i8g residual vs add + rmsnorm + had_quant_act_i8g", false, + "rc=" + std::to_string(rc)); + return; + } + same("rmsnorm_had_quant_i8g residual is byte-identical to add + rmsnorm + had_quant_act_i8g"); + { + std::vector r0((size_t)M * K), r1((size_t)M * K); + st_memcpy(r0.data(), d_r[0], r0.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(r1.data(), d_r[1], r1.size() * 2, hipMemcpyDeviceToHost); + int nd = 0; + for (size_t i = 0; i < r0.size(); ++i) nd += r0[i] != r1[i]; + ok("rmsnorm_had_quant_i8g leaves the same residual behind", nd == 0, + "differs " + std::to_string(nd)); + } } /* ---- gelu_mul_quant_i8, against gelu_mul + quant_act_i8 ------------------------------------- @@ -25849,7 +25946,8 @@ static void device_phase(const Plugin& pl) { /* The fused quantisers are checked against the kernels they replace, gated on their own * rows. */ - if (sel("rmsnorm_quant_fp8") || sel("gated_quant_fp8") || sel("gate_quant_fp8")) { + if (sel("rmsnorm_quant_fp8") || sel("gated_quant_fp8") || sel("gate_quant_fp8") || + sel("rmsnorm_had_quant_i8g") || sel("gated_had_quant_i8g")) { if (!g_case) std::printf("\nthe fp8 fusions, against the pair each one replaces\n"); fused_quant_fp8_numeric(pl); } @@ -25965,6 +26063,8 @@ static void device_phase(const Plugin& pl) { /* Also skipped: the norm half is rmsnorm_quant_fp8's device function, checked there, and the * handshake and reduced sum need a peer rank. */ skip_pair("ar_rmsnorm_quant_fp8", "two-rank fusion: needs a peer rank"); + /* The same for its rotated int8 twin, whose norm half is rmsnorm_had_quant_i8g's. */ + skip_pair("ar_rmsnorm_had_quant_i8g", "two-rank fusion: needs a peer rank"); skip_pair("ar_rmsnorm_quant_i8", "two-rank fusion: needs a peer rank"); dfree_all(); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 880482b3..7bc5a417 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1178,6 +1178,24 @@ extern "C" int r4d_shape_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, int op R4D_PICK(l); } +extern "C" int r4d_shape_ar_rmsnorm_had_quant_i8g(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + + const int64_t M = pi(p, n_p, "M"); + const int64_t n = pi(p, n_p, "n"); + const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK); + if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd((uint32_t)RAD_BF16, M, n), /* inout: the message and the input */ + opd((uint32_t)RAD_BF16, M, n), + opd((uint32_t)RAD_F32, n), /* f32 or bf16; the shim reads the operand's own */ + opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, (n + g - 1) / g), + opd((uint32_t)RAD_BF16, M, n), + }; + R4D_PICK(l); +} + /* ========================================================================================== * GEMM, dequant and the row top-R (shims in the r4d_gemm_*.hip units, r4d_dequant_w4_bf16.hip and * r4d_rowtopk_bf16.hip). @@ -1891,6 +1909,43 @@ extern "C" int r4d_shape_gated_quant_fp8(const RadParam* p, int n_p, int operand R4D_PICK(l); } +/* The `_had_quant_i8g` twins: the same operands with int8 codes (had_quant_act_i8g's). */ +extern "C" int r4d_shape_rmsnorm_had_quant_i8g(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + + const int64_t M = pi(p, n_p, "M"); + const int64_t n = pi(p, n_p, "n"); + const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK); + const uint32_t D = dt_act(p, n_p, "dtype"); + if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd(D, M, n), + opd(D, M, n), + opd((uint32_t)RAD_F32, n), + opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, (n + g - 1) / g), + opd(D, M, n), + }; + R4D_PICK(l); +} + +extern "C" int r4d_shape_gated_had_quant_i8g(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + + const int64_t M = pi(p, n_p, "M"); + const int64_t n = pi(p, n_p, "n"); + const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK); + const uint32_t D = dt_act(p, n_p, "dtype"); + if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd(D, M, 2 * n), /* gate then up in one buffer */ + opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, (n + g - 1) / g), + opd(D, M, n), + }; + R4D_PICK(l); +} + extern "C" int r4d_shape_gate_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { From e28e2d89f81713d77755e68e830ba3e10eb11e04 Mon Sep 17 00:00:00 2001 From: eddie168168 Date: Tue, 20 Oct 2026 22:33:28 +0800 Subject: [PATCH 075/152] qwen35_w8a8: the int8 linears take their rotated codes from the norm and silu producers - ActFP8::q8_rot marks fed codes as rotated. NormQuantFP8 declares (ar_)rmsnorm_had_quant_i8g and GateQuantFP8 declares gated_had_quant_i8g when an activation is fed and rotated. LinearFP8 takes fed codes on an i8a8h weight only if their rotation is the weight's. - The MLP no longer writes the bf16 silu product when the down projection is fed. - qwen35_w8a8 feeds the normed input and the FFN activation only where libr4d declares the ops (at TP2 the all-reduce form too), so the CPU graphs are unchanged. A decode step's had_quant_act_i8g launches fall from 288 to 64; the 64 left quantise the attention and delta-net outputs. The codes are the same bytes. On 2x R9700, against 1.9.0 with the RTN container: - KL rows are identical, and greedy answers are byte-identical at TP2 and TP1, with acceptance unchanged. - TP2: 33.98 -> 32.87 ms a decode step, 111.2 -> 114.9 tok/s. - TP1: 55.81 -> 54.59 ms, 62.7 -> 64.1 tok/s. - Prefill: +2%. arch_test pins the unfused chain where the ops are undeclared, and the fed path where they are (had_quant_act_i8g 8, rmsnorm_had_quant_i8g 16, gated_had_quant_i8g 8). The every-op-declared graph hashes are re-pinned. Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_block_mlp_fp8.h | 8 ++++-- arch/common/rad_fp8.h | 49 +++++++++++++++++++++++---------- arch/qwen35_fp8/qwen35_fp8.cpp | 14 ++++++++++ tests/arch_test.cpp | 45 +++++++++++++++++++++++++----- 4 files changed, 91 insertions(+), 25 deletions(-) diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index 9849e43b..aea3c883 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -96,12 +96,14 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co { src.gate, src.up }, w.h, w.gate_up, 0, { g.n_ff, g.n_ff })); /* The bf16 silu product is written only if the down projection reads the bf16 plane - * (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales. */ + * (LinearFP8::reads_x); a block-fp8 down_proj reads only codes and scales, and so does an + * int8 one fed its codes (ActFP8::q8_fed). */ const char* down_base = nm.f("blk.%d.ffn_down", l); RAD_ARCH_TRY(down.probe(b, nm, g, down_base, { src.down })); gq_ffn.fuse_clamped = swiglu_quant; - RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, down.reads_x, - false, swiglu_limit)); + RAD_ARCH_TRY(gq_ffn.declare(b, g, w.gate_up, w.ffn, g.n_ff, "silu", 0, + down.reads_x && !(w.ffn.q8_fed && down.probed_i8), false, + swiglu_limit)); /* The fold (decl_gated_fold), an fp8a8 tile, so bf16, f32-scaled, MXFP4, rotated 5-bit, 4-bit * and int8 gate_up weights take the pair, and so does a clamped (swiglu_limit) product. diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 13ab6679..8a262e4d 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -68,6 +68,10 @@ struct ActFP8 { * epilogue), so an int8 linear reading it declares no quantiser. Set by the model when it * declares the pair, before the wires are copied. */ bool q8_fed = false; + /* With q8_fed: the producer's int8 codes are rotated, had_quant_act_i8g's (a `_had_quant_i8g` + * producer), so only a weight stored rotated (LinearFP8 at i8a8h) reads them, and it declares + * no quantiser of its own. Set by the model with q8_fed. */ + bool q8_rot = false; /* The code pair the producer writes: int8 when the model fed it, E4M3 otherwise. */ rad_buf cq() const { return q8_fed ? q8 : q; } @@ -368,6 +372,8 @@ struct NormQuantFP8 { * (the T * n_embd * 2-byte message then crosses --tp-wire-min-kb). The wire is a declare-time * parameter, hence a separate op. */ rad_op op_arn6 = 0; + /* The ops write had_quant_act_i8g's rotated int8 codes into the int8 pair (ActFP8::q8_rot). */ + bool hi8 = false; Geom gm{}; /* The row width, for turning a row slice into element offsets. */ int64_t n = 0; @@ -401,8 +407,12 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, "linears are bf16; its blocks take a prepared input instead\n"); return RAD_E_UNSUPPORTED; } - if (!src || !a.x || !a.q || !a.s || !w || n <= 0) return RAD_E_INVAL; - op = RAD_OP(b, "rmsnorm_quant_fp8", + /* Rotated int8 codes (ActFP8::q8_rot) come from the `_had_quant_i8g` twins, into the int8 + * pair; the model checked they are declared before feeding. Otherwise E4M3, as always. */ + hi8 = a.q8_fed && a.q8_rot; + const rad_buf cq = hi8 ? a.q8 : a.q, cs = hi8 ? a.s8 : a.s; + if (!src || !a.x || !cq || !cs || !w || n <= 0) return RAD_E_INVAL; + op = RAD_OP(b, hi8 ? "rmsnorm_had_quant_i8g" : "rmsnorm_quant_fp8", RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), @@ -413,7 +423,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, * lifetime-extended. `residual` is INOUT, so it is in both sets; otherwise the planner could * reorder a reader around it. */ rad_buf rd[2] = { src, res }; - rad_buf wr[4] = { a.q, a.s, a.x, res }; + rad_buf wr[4] = { cq, cs, a.x, res }; rad_op_reads (b, op, rd, res ? 2 : 1); rad_op_writes(b, op, wr, res ? 4 : 3); @@ -425,7 +435,7 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, * with `x` the stream and no residual. The kernel supports it (r4d_fused_quant_fp8.hip) and the * schema marks `residual` optional. */ if (fuse_ar && g.world == 2) { - op_arn = RAD_OP(b, "ar_rmsnorm_quant_fp8", + op_arn = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8", RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), @@ -433,14 +443,14 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd)), RAD_WEIGHTS(w)); if (!op_arn) return RAD_E_INVAL; - rad_buf wr_ar[4] = { a.q, a.s, a.x, res ? res : src }; + rad_buf wr_ar[4] = { cq, cs, a.x, res ? res : src }; rad_op_reads (b, op_arn, rd, res ? 2 : 1); rad_op_writes(b, op_arn, wr_ar, 4); /* Only where the compressed wire is reachable and servable: a lossy payload accepted, and * the width tiled by the chunk (otherwise a fatal step-time shape refusal). */ if (fuse_ar != kArExact && !g.wire_exact && (n % kArWire6Chunk) == 0) { - op_arn6 = RAD_OP(b, "ar_rmsnorm_quant_fp8", + op_arn6 = RAD_OP(b, hi8 ? "ar_rmsnorm_had_quant_i8g" : "ar_rmsnorm_quant_fp8", RAD_PARAMS(RAD_RANGE("M", 1, max_rows > 0 ? max_rows : g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), @@ -464,8 +474,8 @@ inline void NormQuantFP8::step(RadCtx* c, int64_t T, int64_t r0, int64_t rows) c if (rows <= 0) rows = T - r0; RAD_ISSUE_N(c, pick(rows), rows, brow_slice(src, r0, rows, n), res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w), - brow_slice(a.q, r0, rows, n), - brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK), + brow_slice(hi8 ? a.q8 : a.q, r0, rows, n), + brow_slice(hi8 ? a.s8 : a.s, r0, rows, n / RAD_FP8_BLOCK), brow_slice(a.x, r0, rows, n)); } @@ -521,7 +531,10 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, clamped_fused = false; if (!std::isfinite(limit) || limit < 0) return RAD_E_INVAL; if (clipped) { - if (!gate_up || !a.x || n <= 0 || rot || std::strcmp(act_name, "silu")) return RAD_E_INVAL; + /* No rotated int8 form: its quantiser would be quant_act_i8g, unrotated. */ + if (!gate_up || !a.x || n <= 0 || rot || (a.q8_fed && a.q8_rot) || + std::strcmp(act_name, "silu")) + return RAD_E_INVAL; const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; if (fuse_clamped && !bf16 && !a.q8_fed && a.cq() && a.cs() && rad_op_declared(b, "swiglu_clamped_quant_fp8")) { @@ -575,9 +588,13 @@ inline int GateQuantFP8::declare(RadBuilder* b, const Geom& g, rad_buf gate_up, if (!gate_up || !a.x || !a.cq() || !a.cs() || n <= 0) return RAD_E_INVAL; /* Rotated codes feed a four-bit expert, which reads E4M3 only. */ if (rot && a.q8_fed) return RAD_E_INVAL; + /* Rotated int8 codes (ActFP8::q8_rot) feed a down projection stored at i8a8h: + * gated_had_quant_i8g, which the model checked is declared before feeding. */ + const bool hi8 = a.q8_fed && a.q8_rot; const int64_t rows = max_rows > 0 ? max_rows : g.max_tok; + const char* gq = hi8 ? "gated_had_quant_i8g" : rot ? "gated_had_quant_fp8" : "gated_quant_fp8"; if (!rot || rad_op_declared(b, "gated_had_quant_fp8")) - op = RAD_OP(b, rot ? "gated_had_quant_fp8" : "gated_quant_fp8", + op = RAD_OP(b, gq, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype), RAD_STR("act", act_name)), @@ -1064,14 +1081,16 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * of 128. The codes come from the producer (ActFP8::q8_fed) or from op_q over `a.x` (probe() * set reads_x). The model must have declared the pair (ActFP8::declare_qs's `i8`). * - * A rotated weight (i8a8h) takes had_quant_act_i8g instead, so it always quantises its own - * input: a producer's codes are unrotated. */ + * A rotated weight (i8a8h) takes had_quant_act_i8g instead. It reads a producer's codes only + * when they are rotated too (ActFP8::q8_rot, a `_had_quant_i8g` producer); a plain int8 weight + * only when they are not. */ const bool rot8 = known && linear_is_w8h(enc); i8 = known && (linear_is_w8(enc) || rot8); if (i8) { - if (rot8 && a.q8_fed) { - fprintf(stderr, "radiance: '%s' is a rotated int8 weight and its input is fed codes " - "its producer wrote unrotated\n", wn); + if (a.q8_fed && rot8 != a.q8_rot) { + fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its " + "producer wrote %s\n", wn, rot8 ? " rotated" : " plain", + rot8 ? "unrotated" : "rotated"); return RAD_E_DTYPE; } if (!a.x || !a.q8 || !a.s8) { diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 915e7238..0ceffff0 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -750,6 +750,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.trunk_i8)); #endif +#if QWEN35_W8A8 + /* ---- the rotated trunk's quantisers in their producers. Every reader of `h`'s codes is a + * rotated int8 projection (q, k, v; the delta net's qkv|z; gate_up), and of `ffn`'s the down + * projection, so where libr4d serves the `_had_quant_i8g` forms the norms and the gated + * product write had_quant_act_i8g's codes themselves (ActFP8::q8_rot) and those projections + * declare no quantiser: one launch for q, k and v instead of three, and none before down. The + * codes are the same bytes. Where the forms are not declared (the CPU kernels), each + * projection quantises its own input from the bf16 plane, as before. */ + if (rad_op_declared(b, "rmsnorm_had_quant_i8g") && + (g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g"))) + m.a_h.q8_fed = m.a_h.q8_rot = true; + if (rad_op_declared(b, "gated_had_quant_i8g")) m.a_ffn.q8_fed = m.a_ffn.q8_rot = true; +#endif + m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd}); /* The auxiliary taps, only when the container carries the drafter and the deployment diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index c57ac30c..253b8486 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -7675,15 +7675,21 @@ int w8a8_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx } /* namespace */ -/* Every trunk linear of a rotated int8 container is an i8a8h GEMM right behind its own - * had_quant_act_i8g, at one rank and two: 2 attention layers of four linears, 6 delta-net layers - * of two and 8 feed-forwards of two. None is left at fp8, which is what a linear that missed the - * encoding falls back to, and the MLP declares no gated fold (an fp8a8 tile over E4M3 codes). The - * four trunk activations carry an int8 pair; the delta net's `gdn_in` feeds no int8 linear. */ +/* The `_had_quant_i8g` producers, which libr4d serves and libref does not. */ +const char* const kW8a8Fused[] = { "rmsnorm_had_quant_i8g", "ar_rmsnorm_had_quant_i8g", + "gated_had_quant_i8g" }; + +/* Where the `_had_quant_i8g` producers are not served, every trunk linear of a rotated int8 + * container is an i8a8h GEMM right behind its own had_quant_act_i8g, at one rank and two: 2 + * attention layers of four linears, 6 delta-net layers of two and 8 feed-forwards of two. None is + * left at fp8, which is what a linear that missed the encoding falls back to, and the MLP declares + * no gated fold (an fp8a8 tile over E4M3 codes). The four trunk activations carry an int8 pair; + * the delta net's `gdn_in` feeds no int8 linear. */ TEST(qwen35_w8a8_serves_every_trunk_linear_rotated_int8) { MetaKV mk = q35w8a8_meta(); for (int world : { 1, 2 }) { RadBuilder b; + for (const char* op : kW8a8Fused) b.undeclared.insert(op); w8a8_encs(&b); RadBuildCtx ctx = build_ctx(0, world); REQUIRE_EQ(qwen35_w8a8::declare(&b, mk.meta(), &ctx), RAD_OK); @@ -7706,6 +7712,31 @@ TEST(qwen35_w8a8_serves_every_trunk_linear_rotated_int8) { } } +/* Where they are served, the norms and the gated product write had_quant_act_i8g's codes into the + * int8 pair, and the projections reading them declare no quantiser: had_quant_act_i8g is left only + * before the attention and delta-net output projections (2 + 6), every norm is the rotated twin (at + * two ranks with its fused all-reduce form beside it), and every feed-forward's product is + * gated_had_quant_i8g. No E4M3 norm or gated quantiser is left, and the 36 GEMMs are unchanged. */ +TEST(qwen35_w8a8_feeds_its_rotated_codes_from_the_producers_where_libr4d_serves_them) { + MetaKV mk = q35w8a8_meta(); + for (int world : { 1, 2 }) { + RadBuilder b; + w8a8_encs(&b); + RadBuildCtx ctx = build_ctx(0, world); + REQUIRE_EQ(qwen35_w8a8::declare(&b, mk.meta(), &ctx), RAD_OK); + int rot = 0; + for (const RecOp& o : b.ops) rot += o.op == "gemm_nt_q" && pstr(&o, "dtype") == "i8a8h"; + CHECK_EQ(rot, 2 * 4 + 6 * 2 + 8 * 2); + CHECK_EQ(count_op(b, "had_quant_act_i8g"), 2 + 6); + CHECK_EQ(count_op(b, "rmsnorm_had_quant_i8g"), 8 + 8); + CHECK_EQ(count_op(b, "gated_had_quant_i8g"), 8); + for (const char* op : { "rmsnorm_quant_fp8", "ar_rmsnorm_quant_fp8", "gated_quant_fp8", + "quant_act_i8g" }) + CHECK_EQ(count_op(b, op), 0); + CHECK_EQ(count_op(b, "ar_rmsnorm_had_quant_i8g") > 0, world == 2); + } +} + /* What the int8 build refuses: a trunk that is not int8 (no stated encoding, which a block-fp8 * plugin reads as fp8), a plain int8 trunk (the descriptor names the rotation, and a plain weight * served behind the rotated quantiser would be wrong), and a container stated for another format @@ -8994,10 +9025,10 @@ struct ArchCases { qwen35_fp8::step, 7, {}, 0xb5691456a0ce7e9dull); add("qwen35_w8a8 + DFlash2", [this, sc](RadBuilder* b) { auto c = sc(1, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, - qwen35_w8a8::step, 7, {}, 0x88e964c824896422ull); + qwen35_w8a8::step, 7, {}, 0xed8219da9fcc0ceaull); add("qwen35_w8a8 + DFlash2, two ranks", [this, sc](RadBuilder* b) { auto c = sc(2, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, - nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x7c73e987c475e40dull); + nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x2c00f131709dedcfull); add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) { auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); }, qwen35moe_fp8::step, 3, {}, 0x3157a986f13a9a72ull); From 6908377f3dbd7392debf1cf016e2396401048a3a Mon Sep 17 00:00:00 2001 From: keptn42 Date: Mon, 19 Oct 2026 18:34:03 +0000 Subject: [PATCH 076/152] qwen35moe: read the experts' stored format, serve four-bit experts, calibration tap Probe the expert encoding as qwen4exp does, declare the rotated input pair, set the GPTQ calibration tap, and read expert sources stacked or per expert. --- arch/qwen35_fp8/qwen35_fp8.cpp | 25 +++++++++++++++++++++++-- tests/arch_test.cpp | 6 +++--- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 0ceffff0..b781fe71 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -151,6 +151,8 @@ struct Model { ActFP8 a_eff{}; rad_buf b_sgu = 0, b_sout = 0, b_sgate = 0; ActFP8 a_sff{}; + /* Rotated codes of the expert input, for rotated four-bit experts (MoeFP8::Config::expert_rot). */ + ActFP8 a_hr{}; #endif /* The DFlash2 drafter, declared only when the container carries one and the deployment @@ -713,6 +715,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c (long long)mc.top_k, (long long)mc.n_expert); return RAD_E_INVAL; } + /* GPTQ calibration run (MoeFP8::Config::calib), on when the output directory is set. */ + mc.calib = calib_dir() != nullptr ? 1 : 0; + /* The experts' stored format, read from layer 0's first expert as qwen4exp does, so a + * container with four-bit experts is served in that format. */ + { + MoeFP8::Src ps{}; + RAD_ARCH_TRY(moe_expert_sources(b, nm, "format", + "model.language_model.layers.0.mlp.experts", &ps)); + RAD_ARCH_TRY(MoeFP8::probe(b, nm, 0, ps, &mc)); + } + if (mc.expert_bf16) { + fprintf(stderr, "radiance: qwen35moe: plain bf16 experts are not served by this " + "plugin; convert with a quantising recipe\n"); + return RAD_E_UNSUPPORTED; + } } { /* The step's height for everything with one row per token, and a pass's height only for @@ -743,6 +760,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd}); m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1}); } + if (mc.expert_rot) RAD_ARCH_TRY(m.a_hr.declare_qs(b, nm, g, "moe_hr", g.n_embd)); } #else m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff}); @@ -865,6 +883,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt; mw.egu = m.b_egu; mw.eff = m.a_eff; mw.edn = m.b_edn; mw.moe = m.b_emoe; mw.sgu = m.b_sgu; mw.sff = m.a_sff; mw.sout = m.b_sout; mw.sgate = m.b_sgate; + mw.hr = m.a_hr; #else mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn; #endif @@ -916,7 +935,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c ms.cfg = m.moecfg; ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l); ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l); - ms.experts = nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l); + RAD_ARCH_TRY(moe_expert_sources(b, nm, "layer", + nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l), &ms)); if (m.moecfg.n_ff_shared > 0) { ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l); ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l); @@ -1019,7 +1039,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * MtpBlockFP8 is a template over the feed-forward. */ ts.mlp.cfg = m.moecfg; ts.mlp.router = nm.ckpt("mtp.layers.0.mlp.gate.weight"); - ts.mlp.experts = nm.ckpt("mtp.layers.0.mlp.experts"); + RAD_ARCH_TRY(moe_expert_sources(b, nm, "mtp", nm.ckpt("mtp.layers.0.mlp.experts"), + &ts.mlp)); if (m.moecfg.n_ff_shared > 0) { ts.mlp.shared = nm.ckpt("mtp.layers.0.mlp.shared_expert"); ts.mlp.shared_gate = nm.ckpt("mtp.layers.0.mlp.shared_expert_gate.weight"); diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 253b8486..a3bd4457 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -9031,7 +9031,7 @@ struct ArchCases { nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x2c00f131709dedcfull); add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) { auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); }, - qwen35moe_fp8::step, 3, {}, 0x3157a986f13a9a72ull); + qwen35moe_fp8::step, 3, {}, 0x1bd3b53543cd06eeull); add("qwen4exp_fp8", [this](RadBuilder* b) { auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); }, qwen4exp_fp8::step, 3, {}, 0xbe74d476c7fd04b8ull); @@ -9811,8 +9811,8 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { { "qwen4exp_fp8", 4, 3, 0x6669aa0573931943ull, 0x36df57cac613c6cfull }, { "qwen35_fp8", 1, 0, 0xcfc82ca915ec549dull, 0x4d6fca823d1e97efull }, { "qwen35_fp8", 2, 1, 0x36da8d762194e24eull, 0xe4022daff02ec8bdull }, - { "qwen35moe_fp8", 1, 0, 0xb7c4d121acb388b3ull, 0x3fcf71676e558d79ull }, - { "qwen35moe_fp8", 2, 0, 0x5c02b2d6cd49ed0cull, 0x05e0778848bf416cull }, + { "qwen35moe_fp8", 1, 0, 0x7fa7b015e1bc8873ull, 0x3fcf71676e558d79ull }, + { "qwen35moe_fp8", 2, 0, 0xf60c9508dd197370ull, 0x05e0778848bf416cull }, }; for (const Case& cs : cases) { RadBuilder b; From 1431838a9afabb63a0cd2595d0b9c3be9d0235d4 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Tue, 20 Oct 2026 09:50:12 +0000 Subject: [PATCH 077/152] deploy/compose, README: Ornith-1.5-35B-A3B w4a8 container Two compose files (two cards, one card) and a row in the models table. --- README.md | 1 + deploy/compose/ornith-1.5-35b-a3b-w4a8-tp1.yaml | 13 +++++++++++++ deploy/compose/ornith-1.5-35b-a3b-w4a8.yaml | 14 ++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 deploy/compose/ornith-1.5-35b-a3b-w4a8-tp1.yaml create mode 100644 deploy/compose/ornith-1.5-35b-a3b-w4a8.yaml diff --git a/README.md b/README.md index 3b980f2a..5d2bcbc1 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` | | Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` | | Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` | +| Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` | | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | diff --git a/deploy/compose/ornith-1.5-35b-a3b-w4a8-tp1.yaml b/deploy/compose/ornith-1.5-35b-a3b-w4a8-tp1.yaml new file mode 100644 index 00000000..1578ae0b --- /dev/null +++ b/deploy/compose/ornith-1.5-35b-a3b-w4a8-tp1.yaml @@ -0,0 +1,13 @@ +# Ornith-1.5-35B-A3B w4a8 on one card: every weight stays in VRAM, no host pool. At 8 sequences the +# cache holds 1,057,824 tokens, four full 262,144-token sessions. +name: radiance-ornith-1.5-35b-a3b-w4a8-tp1 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-35b-a3b-w4a8-tp1 + command: > + --model /models/ornith-1.5-35b-a3b-w4a8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/ornith-1.5-35b-a3b-w4a8.yaml b/deploy/compose/ornith-1.5-35b-a3b-w4a8.yaml new file mode 100644 index 00000000..54d19373 --- /dev/null +++ b/deploy/compose/ornith-1.5-35b-a3b-w4a8.yaml @@ -0,0 +1,14 @@ +# Ornith-1.5-35B-A3B with four-bit experts (w4nl64, GPTQ), the trunk block-FP8, an int8 lm_head, its own MTP +# head and the vision tower: 20 GiB, so it also runs on one card (ornith-1.5-35b-a3b-w4a8-tp1.yaml). +# Sampling as ornith-1.5-35b-a3b.yaml. +name: radiance-ornith-1.5-35b-a3b-w4a8 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-ornith-1.5-35b-a3b-w4a8 + command: > + --model /models/ornith-1.5-35b-a3b-w4a8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 262144 --kv-cache-dtype fp8 + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 From aa12f79579d29df39e9e7327d0cf5590f1589a6f Mon Sep 17 00:00:00 2001 From: Deadcode Date: Mon, 19 Oct 2026 16:22:35 +1000 Subject: [PATCH 078/152] device: run cards with a small PCI BAR by keeping kernel arguments in host memory A card whose PCI BAR spans less than its VRAM was refused at startup, because the kernel argument ring is written by the host and the runtime maps such VRAM PROT_NONE. Instead, place the ring, and a recorded pass's argument blocks, in a pinned host memory pool and grant them to the card, as HIP's own launches do; every dispatch then reads its arguments across the link. A card whose BAR spans its VRAM keeps its arguments in VRAM, unchanged. RADIANCE_DEBUG_AQL_HOST_KARGS forces the host-memory path on a card that needs no fallback, to measure the cost. --- README.md | 4 ++- core/device/aql.cpp | 70 ++++++++++++++++++++++++++++---------------- core/diag/checks.cpp | 4 ++- docs/GUIDE.md | 2 +- 4 files changed, 52 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 5d2bcbc1..5e99c450 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,9 @@ only. ## Run with Docker The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The -card needs Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The image +card works best with Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup); +without it the engine keeps kernel arguments in pinned host memory, and every dispatch reads them +over the link. The image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a model from one of them: diff --git a/core/device/aql.cpp b/core/device/aql.cpp index c8f252ae..23fd93f8 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -16,8 +16,9 @@ * * Fences: kernels on one queue see each other's writes through the L2 with an agent-scope fence. * System scope is needed only for memory the L2 does not see: - * - the kernel argument ring is in VRAM and written by the host through the BAR, which the L2 - * does not snoop. A slot is rewritten one lap after it was last read, so a system-scope + * - the kernel argument ring is written by the host: into VRAM through the BAR when the BAR + * spans the card's memory, into pinned host memory otherwise. The L2 caches neither without + * an invalidation. A slot is rewritten one lap after it was last read, so a system-scope * acquire is placed at least once per half lap; without it every kernel after the first lap * reads its predecessor's arguments. Slots are 1 KiB so no argument fetch shares a cache line * with the next slot; @@ -210,6 +211,7 @@ struct Dev { hsa_amd_memory_pool_t vram{}; bool has_vram = false; uint32_t kfd_id = 0; /* the driver's gpu_id: its sysfs and ioctls name it so */ + bool host_kargs = false; /* no large BAR: the argument ring lives in host memory */ }; struct Global { @@ -282,8 +284,8 @@ int topo_node(uint32_t gpu_id) { /* Whether the CPU can write the card's VRAM: 1 yes, 0 no, -1 unknown. The driver maps VRAM for * the CPU only when the PCI BAR spans all of it. With a smaller BAR (Resizable BAR off or * unsupported) the topology reports a private frame buffer heap and the runtime maps every VRAM - * allocation PROT_NONE, including the kernel argument rings. The heap type is what the runtime - * itself decides from. */ + * allocation PROT_NONE, so argument rings go to host memory instead (init_devices). The heap type + * is what the runtime itself decides from. */ int vram_host_writable(uint32_t gpu_id) { constexpr unsigned long long kHeapFbPrivate = 2; /* HSA_HEAPTYPE_FRAME_BUFFER_PRIVATE */ const int n = gpu_id ? topo_node(gpu_id) : -1; @@ -405,14 +407,26 @@ bool init_devices() { g.why = fmt("HIP device %d (%s) has no matching HSA agent with a VRAM pool", i, bus); return false; } - /* The host writes every dispatch's arguments into VRAM (a_stream_create), so a card the - * CPU cannot write is refused here instead of at the first launch's SIGSEGV. */ + /* The host writes every dispatch's arguments (a_stream_create), in VRAM when the BAR + * spans it. A smaller BAR makes the runtime map VRAM for the CPU PROT_NONE, which would + * fault at the first launch; the ring goes to pinned host memory instead, as HIP's own + * launches do, at the cost of the card reading each dispatch's arguments over the link. */ if (vram_host_writable(g.dev[(size_t)i].kfd_id) == 0) { - g.why = fmt("card %d (%s) does not let the CPU write its VRAM: its PCI BAR is smaller " - "than its memory. The AQL backend needs Resizable BAR -- turn on Above 4G " - "Decoding and Resizable BAR in the firmware setup; `lspci -vv` then shows " - "the card's first region as large as its VRAM", i, bus); - return false; + g.dev[(size_t)i].host_kargs = true; + RAD_WARN("device: card %d (%s) has a PCI BAR smaller than its VRAM (Resizable BAR " + "off, or the slot's window too small), so kernel arguments stay in pinned host " + "memory and every dispatch reads them across the link, which costs launch " + "rate. Above 4G Decoding and Resizable BAR in the firmware setup remove the " + "difference where the slot allows it", + i, bus); + } + /* The fallback on a card that needs none, to measure what reading each dispatch's + * arguments across the link costs against the same card's VRAM rings. */ + const char* force_host_kargs = std::getenv("RADIANCE_DEBUG_AQL_HOST_KARGS"); + if (force_host_kargs && *force_host_kargs && *force_host_kargs != '0') { + g.dev[(size_t)i].host_kargs = true; + RAD_WARN("device: card %d (%s): RADIANCE_DEBUG_AQL_HOST_KARGS puts the kernel argument " + "rings in host memory", i, bus); } } /* Without the handler a fault falls back to the runtime's own handling, which the @@ -570,7 +584,7 @@ struct Stream { hsa_agent_t agent{}; hsa_queue_t* q = nullptr; uint64_t mask = 0; - char* karg = nullptr; /* VRAM, CPU-mapped through the BAR */ + char* karg = nullptr; /* VRAM the CPU writes through the BAR, or host memory */ std::atomic busy{false}; uint64_t wr = 0; /* next packet index */ uint64_t rd = 0; /* last read index seen */ @@ -906,7 +920,7 @@ inline int reserve(Stream* s, uint64_t* out) { inline void publish(Stream* s, uint64_t idx, uint16_t header, uint16_t setup) { s->wr = idx + 1; hsa_queue_store_write_index_relaxed(s->q, idx + 1); - _mm_sfence(); /* the argument slot is write-combined VRAM */ + _mm_sfence(); /* the argument slot, written before the header */ __atomic_store_n(reinterpret_cast( static_cast(s->q->base_address) + (idx & s->mask)), @@ -947,7 +961,7 @@ struct Tape { uint64_t magic = kTapeMagic; std::vector rec; std::vector karg_host; /* the argument blocks, kept to compare tapes by */ - char* karg = nullptr; /* VRAM, CPU-mapped, from the end of the capture on */ + char* karg = nullptr; /* placed at the end of the capture */ std::string bad; /* why this tape cannot be played, if it cannot */ /* Last packet the latest play wrote on each queue; the argument block is freed only after * all of them are consumed. */ @@ -1083,7 +1097,7 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t * doorbell once per kPlayRing packets: the doorbell is an uncached write across the link and a * pass is over a thousand dispatches. Each body is copied as recorded; the header is decided now * as in dispatch(), since its acquire scope depends on host writes since recording. Argument - * blocks were written to VRAM when the tape was made, so no fence precedes the header. Ring + * blocks were placed when the tape was made, so no fence precedes the header. Ring * before a reserve that would wait: the packet processor only takes announced packets. */ constexpr int kPlayRing = 64; @@ -1407,12 +1421,14 @@ int a_stream_create(RadStream* out, int high_priority) { hsa_amd_profiling_set_profiler_enabled(s->q, 1); if (high_priority) hsa_amd_queue_set_priority(s->q, HSA_AMD_QUEUE_PRIORITY_HIGH); void* ka = nullptr; - if (hsa_amd_memory_pool_allocate(d.vram, (size_t)(s->mask + 1) * kKargSlot, 0, &ka) != + hsa_amd_memory_pool_t kpool = d.host_kargs ? G().host_fine : d.vram; + hsa_agent_t kpeer = d.host_kargs ? d.agent : G().cpu; + if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 1) * kKargSlot, 0, &ka) != HSA_STATUS_SUCCESS || - hsa_amd_agents_allow_access(1, &G().cpu, nullptr, ka) != HSA_STATUS_SUCCESS) { + hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) { hsa_queue_destroy(s->q); - device_set_error("rad_stream_create: the kernel argument ring could not be placed in VRAM " - "the host can write -- the AQL backend needs a large BAR"); + device_set_error("rad_stream_create: the kernel argument ring could not be placed in %s", + d.host_kargs ? "pinned host memory" : "VRAM the host can write"); return RAD_E_DEVICE; } s->karg = static_cast(ka); @@ -1758,8 +1774,9 @@ void a_tape_pause(int on) { else if (t_tape_pause > 0) --t_tape_pause; } -/* Moves the argument blocks to VRAM on the tape's card, where the packet processor reads them as - * it reads the ring; the packets are then final except for the header. */ +/* Moves the argument blocks to the tape's card, into the memory the stream ring uses there: VRAM + * the host writes through the BAR, or pinned host memory without one. The packets are then final + * except for the header. */ RadTape a_tape_end(int keep) { Tape* t = t_tape; t_tape = nullptr; @@ -1783,13 +1800,16 @@ RadTape a_tape_end(int keep) { } } if (!t->karg_host.empty()) { + const Dev& d = G().dev[(size_t)ord]; void* ka = nullptr; - if (hsa_amd_memory_pool_allocate(G().dev[(size_t)ord].vram, t->karg_host.size(), 0, &ka) != - HSA_STATUS_SUCCESS || - hsa_amd_agents_allow_access(1, &G().cpu, nullptr, ka) != HSA_STATUS_SUCCESS) { + hsa_amd_memory_pool_t pool = d.host_kargs ? G().host_fine : d.vram; + hsa_agent_t peer = d.host_kargs ? d.agent : G().cpu; + if (hsa_amd_memory_pool_allocate(pool, t->karg_host.size(), 0, &ka) != HSA_STATUS_SUCCESS || + hsa_amd_agents_allow_access(1, &peer, nullptr, ka) != HSA_STATUS_SUCCESS) { if (ka) hsa_amd_memory_pool_free(ka); device_set_error("the pass cannot be recorded: %zu bytes of kernel arguments could " - "not be placed in VRAM", t->karg_host.size()); + "not be placed in %s", t->karg_host.size(), + d.host_kargs ? "pinned host memory" : "VRAM"); tape_free(t); return nullptr; } diff --git a/core/diag/checks.cpp b/core/diag/checks.cpp index 14702b5d..79d8c67a 100644 --- a/core/diag/checks.cpp +++ b/core/diag/checks.cpp @@ -203,7 +203,9 @@ void check_small_bar(const Facts& f, std::vector* out) { fmt("%s: the host and the other cards see %s of its %s of VRAM", card_name(*c).c_str(), humanb(c->vram_visible).c_str(), humanb(c->vram_total).c_str()), "without Resizable BAR a peer can address only a window of the card's memory, which " - "limits peer-to-peer collectives and copies into VRAM from the host", + "limits peer-to-peer collectives and copies into VRAM from the host; the engine also " + "keeps that card's kernel arguments in pinned host memory, and every dispatch reads " + "them across the link", "enable Resizable BAR (\"Re-Size BAR Support\" and \"Above 4G Decoding\") in the " "firmware setup"); } diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 6c89aebb..9cb334bc 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -50,7 +50,7 @@ driver. [`DOCKER.md`](DOCKER.md) covers it, with compose files per model. |---|---| | Required | Linux, a C++20 compiler, CMake 3.21+, Ninja, pthreads | | Optional | ROCm with `hipcc`, for AMD device kernels; without it you get the host backend. Set `ROCM_PATH` if ROCm is not at `/opt/rocm` | -| With a card | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The host writes every dispatch's arguments into VRAM, and startup refuses a card whose memory the CPU cannot reach | +| With a card | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The host writes every dispatch's arguments into VRAM there; without a large BAR they stay in pinned host memory and every dispatch reads them over the link, which costs launch rate | | Optional | OpenMP, used by the host kernel libraries if present | | Optional | `clang++` (or ROCm's), for `tests/r4d_emu` when the C++ compiler is g++; CMake 3.25+ for `CMakePresets.json` | | Shell harnesses | `curl` and `jq` | From 64adee3ecea74c2907def844d2dac6699341766f Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Tue, 20 Oct 2026 14:39:19 +0700 Subject: [PATCH 079/152] core: a control vector loaded from a controlvector GGUF, discovered per model family A control vector is one unit direction per layer, applied to the residual stream while the model runs (llama.cpp's --cvec-mode project). This is the loader and its ABI, with no configuration surface: a vector is a property of the model family, so the engine looks for one beside the container, in its directory or in $RADIANCE_HOME/vectors, and uses it when it fits the container. The operation's parameters (layer range, scale, mode) come from the package's own JSON. Validation is against the container, never the file's provenance: architecture hint, direction width against n_embd, every layer in the range present, F32 rows. A discovered file that does not fit is reported and skipped; the switch stays off until a request asks for it. The ABI grows by one trailing, zero-defaulted field (RadBuildCtx::cvec), so an architecture plugin that ignores it is unchanged, and the cache gains a salt (0 without a vector) that keeps blocks and linear-state snapshots of one mode from being reused by the other. --- abi/rad_builder.h | 40 +++++ core/cvec.cpp | 313 +++++++++++++++++++++++++++++++++++++++ core/cvec.h | 100 +++++++++++++ core/engine.cpp | 49 +++++- core/engine.h | 33 +++++ core/engine_bringup.cpp | 63 ++++++++ core/rad_core.h | 8 + tests/abi_layout_rows.h | 6 + tests/abi_layout_table.h | 8 +- tests/cvec_test.cpp | 241 ++++++++++++++++++++++++++++++ 10 files changed, 859 insertions(+), 2 deletions(-) create mode 100644 core/cvec.cpp create mode 100644 core/cvec.h create mode 100644 tests/cvec_test.cpp diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 3e33597d..c439ee0e 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -173,8 +173,48 @@ typedef struct RadBuildCtx { * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int kv_quant; + + /* A control vector loaded from a GGUF `controlvector` file (--speed-projection), or null. + * + * The engine loads and validates it once, at bringup, and the plugin only reads it: the + * direction table lives in device memory on every rank, in the activations' own float form, + * and a per-request switch reaches the step through a derived buffer the plugin declares + * itself (a row mask, `projection_on_rows`). Nothing is reloaded to turn the feature on or + * off, and with the mask zero the model computes what it computes without a vector. + * + * The plugin decides where in its own graph the projection applies; for the gated-residual + * architectures that is after each block's write into the wide stream, which is the point + * llama.cpp's control-vector hook uses for `qwen4exp`. A plugin that does not declare an op + * reading this table ignores it. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + const struct RadControlVector* cvec; } RadBuildCtx; +/* ================================================================== control vectors */ +/* A direction per layer, in the shape llama.cpp's `--cvec-mode project` applies it: + * + * h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| (times the user scale) + * + * with `v_l` unit and `s_l` the norm the file stored (so a unit vector's scale is 1). The engine + * normalises the rows when it uploads them, so a kernel reads `dir` as the unit direction and + * takes `s` from `scales`; a zero scale means "this layer is not steered". + * + * `dir` is [n_layers, n_embd] f32, row `l` that layer's direction, row 0 unused (layer 0 has no + * direction in the format). Each rank has its own copy: the pointer a plugin receives is that + * rank's, and the residual stream is replicated, so no collective is involved. + * + * `n_layers` is the model's layer count, which may be longer than the file's (the published + * Flash-Next vector carries 47 of 48 rows). The steered range is not a separate field: a layer is + * steered exactly when its `scales` entry is nonzero, so a plugin asks that and cannot disagree + * with the loader. */ +typedef struct RadControlVector { + const float* dir; /* device, [n_layers, n_embd] f32, unit rows */ + const float* scales; /* host, [n_layers] f32, |d_l| * user scale; 0 = not steered */ + int64_t n_embd; + int64_t n_layers; +} RadControlVector; + /* ================================================================== weights */ /* Access class, declared per weight because only the architecture plugin knows it. It tells the * placement planner whether prefetch can be exact (spec §5.2). */ diff --git a/core/cvec.cpp b/core/cvec.cpp new file mode 100644 index 00000000..4a59059c --- /dev/null +++ b/core/cvec.cpp @@ -0,0 +1,313 @@ +/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h). + * + * The format is llama.cpp's `controlvector` package: one `direction.` tensor of unit f32 per + * layer, plus three metadata keys. The reader is core/text/gguf.cpp, which already mmaps a GGUF + * and computes tensor byte sizes, so nothing here parses bytes by hand. + * + * The published package (hf.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection) is what the checks + * below are written against, and its own JSON states the operation's parameters: + * + * {"mode": "project", "dir": "per-layer", "scale": 1.0, "layer_range": [4, 44], ...} + * + * so a file is only accepted for a model whose hidden size equals the directions' width and whose + * architecture the file names. Everything else is refused at startup, by name, rather than + * steered along a direction from another residual basis. + */ +#include "cvec.h" + +#include "text/gguf.h" + +#include +#include +#include +#include + +#include + +namespace rad { +namespace { + +/* FNV-1a over the table, so two different vectors never share a cache partition. */ +uint64_t hash_table(const ControlVector& cv) { + uint64_t h = 1469598103934665603ull; + const auto mix = [&h](const void* p, size_t n) { + const uint8_t* b = (const uint8_t*) p; + for (size_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; } + }; + mix(cv.dir.data(), cv.dir.size() * sizeof(float)); + mix(cv.scales.data(), cv.scales.size() * sizeof(float)); + return h ? h : 1ull; +} + +} /* namespace */ + +std::string control_vector_sidecar_path(const std::string& model_path) { + const size_t slash = model_path.find_last_of("/\\"); + const size_t dot = model_path.find_last_of('.'); + const bool has_ext = dot != std::string::npos && (slash == std::string::npos || dot > slash); + return (has_ext ? model_path.substr(0, dot) : model_path) + ".control-vector.gguf"; +} + +namespace { + +bool file_present(const std::string& p) { + std::ifstream f(p, std::ios::binary); + if (!f) return false; + f.seekg(0, std::ios::end); + return f.tellg() > 0; +} + +} /* namespace */ + +int control_vector_discover(const std::string& model_path, const std::string& arch, + const std::string& radiance_home, std::string* found, + std::string* tried) { + if (!found) return RAD_E_INVAL; + found->clear(); + if (tried) tried->clear(); + + std::vector cand; + const size_t slash = model_path.find_last_of("/\\"); + const std::string dir = slash == std::string::npos ? std::string(".") : model_path.substr(0, slash); + if (!model_path.empty()) { + cand.push_back(control_vector_sidecar_path(model_path)); + /* One file for a directory of containers: each quant of the family shares the directions, + * since the file names the architecture and its width, not the quantisation. */ + cand.push_back(dir + "/control-vector.gguf"); + } + if (!arch.empty() && !radiance_home.empty()) { + size_t at = 0; + while (at <= radiance_home.size()) { + const size_t colon = radiance_home.find(':', at); + const std::string home = radiance_home.substr( + at, colon == std::string::npos ? std::string::npos : colon - at); + if (!home.empty()) + cand.push_back(home + "/vectors/" + arch + "-control-vector.gguf"); + if (colon == std::string::npos) break; + at = colon + 1; + } + } + + for (const std::string& p : cand) { + if (tried) { + if (!tried->empty()) *tried += ", "; + *tried += p; + } + if (file_present(p)) { *found = p; return RAD_OK; } + } + return RAD_OK; +} + + +/* The package's own JSON, if it is beside the vector: `{"mode": "project", "scale": 1.0, + * "layer_range": [4, 44]}` is what the published Flash-Next vector ships. It is the only place + * the operation's parameters are stated, so they are read from there rather than configured; a + * malformed or absent file only means the defaults below. */ +namespace { + +struct PackageJson { + int first = 0, last = -1; /* -1: not stated */ + float scale = 1.0f; +}; + +PackageJson read_package_json(const std::string& gguf_path) { + PackageJson out; + std::string stem = gguf_path; + const size_t dot = stem.find_last_of('.'); + const size_t slash = stem.find_last_of("/\\"); + if (dot != std::string::npos && (slash == std::string::npos || dot > slash)) + stem = stem.substr(0, dot); + const std::string path = stem + ".json"; + std::ifstream f(path); + if (!f) return out; + try { + const nlohmann::json j = nlohmann::json::parse(f); + if (const auto m = j.find("mode"); m != j.end() && m->is_string() && + m->get() != "project") { + RAD_WARN("control vector: %s says mode '%s'; only 'project' is implemented, so the " + "defaults apply", path.c_str(), m->get().c_str()); + return out; + } + if (const auto r = j.find("layer_range"); r != j.end() && r->is_array() && r->size() == 2 && + (*r)[0].is_number_integer() && + (*r)[1].is_number_integer()) { + out.first = (*r)[0].get(); + out.last = (*r)[1].get(); + } + if (const auto s = j.find("scale"); s != j.end() && s->is_number()) + out.scale = (float) s->get(); + } catch (const std::exception& e) { + RAD_WARN("control vector: %s is not readable JSON (%s); the defaults apply", path.c_str(), + e.what()); + } + return out; +} + +} /* namespace */ + +int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd, + int64_t n_model_layers, ControlVector* out, std::string* err) { + const auto fail = [err](const std::string& why) { + if (err) *err = why; + return RAD_E_INVAL; + }; + if (!out) return RAD_E_INVAL; + *out = ControlVector{}; + + GgufFile f; + const int rc = f.open(path.c_str()); + if (rc != RAD_OK) + return fail("control vector " + path + ": cannot read it as a GGUF container"); + + std::string a; + if (!f.get_str("general.architecture", &a) || a != "controlvector") + return fail("control vector " + path + ": general.architecture is '" + a + + "', not 'controlvector' -- this is not a control vector"); + + /* The hint is optional in llama.cpp's generator, but when a file states one it must be this + * model's architecture: a direction is a basis vector inferred from that architecture's + * residual stream, and nothing else. */ + std::string hint; + if (f.get_str("controlvector.model_hint", &hint) && !hint.empty() && !arch.empty() && + hint != arch) + return fail("control vector " + path + ": the vector is for architecture '" + hint + + "', this container is '" + arch + "' -- a direction from another model's " + "residual basis would move hidden states along a meaningless axis"); + + /* The file's directions: direction., one dimensional, F32, n_embd wide. Anything else is + * refused rather than skipped, because a quietly missing layer is a differently steered model. */ + int64_t n_dir = 0, dir_first = -1, dir_last = -1; + for (const GgufTensor& t : f.tensors()) { + if (t.name.rfind("direction.", 0) != 0) + return fail("control vector " + path + ": tensor '" + t.name + + "' is not a direction. entry"); + int64_t layer = 0; + try { + layer = std::stoll(t.name.substr(10)); + } catch (...) { + return fail("control vector " + path + ": tensor name '" + t.name + + "' does not end in a layer number"); + } + if (layer < 1 || layer > n_model_layers) + return fail("control vector " + path + ": direction." + std::to_string(layer) + + " is outside this model's " + std::to_string(n_model_layers) + " layers"); + if (t.n_dims != 1 || t.ne[0] != n_embd) + return fail("control vector " + path + ": " + t.name + " is shape [" + + std::to_string(t.ne[0]) + "] with rank " + std::to_string(t.n_dims) + + "; this model's residual streams are " + std::to_string(n_embd) + + " wide and a direction is one row of that"); + if (gguf_to_rad_dtype(t.ggml_type) != RAD_F32) + return fail("control vector " + path + ": " + t.name + + " is not F32 -- only an f32 direction is read"); + if (dir_first < 0 || layer < dir_first) dir_first = layer; + if (layer > dir_last) dir_last = layer; + ++n_dir; + } + if (n_dir == 0) return fail("control vector " + path + ": the file holds no directions"); + + /* The package's parameters: its JSON, else the published selection where the file covers it, + * else every direction the file carries. A deployment therefore has nothing to configure, and + * a file published with a different selection states it itself. */ + const PackageJson pj = read_package_json(path); + int first = pj.first, last = pj.last; + float scale = pj.scale; + if (last < 0) { + if (n_model_layers >= 45 && dir_last >= 44) { first = 4; last = 44; } + else { first = (int) dir_first; last = (int) dir_last; } + } + if (first < 1 || last < first) + return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" + + std::to_string(last) + " is empty"); + if (last > n_model_layers) + return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" + + std::to_string(last) + " runs past this model's " + + std::to_string(n_model_layers) + " layers"); + if (!(scale > 0.0f) || !std::isfinite(scale)) + return fail("control vector " + path + ": its scale is not a positive number"); + + out->n_embd = n_embd; + /* Indexed by layer: rows 0..n_layers-1. Row 0 stays zero, the format carrying no direction + * for layer 0, and every row a model can name exists. */ + out->n_layers = n_model_layers; + out->first = first; + out->last = last; + out->user_scale = scale; + out->path = path; + out->dir.assign((size_t) (out->n_layers * n_embd), 0.0f); + out->scales.assign((size_t) out->n_layers, 0.0f); + + double worst = 0.0; + for (int64_t l = 1; l <= n_model_layers; ++l) { + const GgufTensor* t = f.tensor("direction." + std::to_string(l)); + if (!t) continue; + const float* d = (const float*) f.tensor_data(*t); + if (!d) return fail("control vector " + path + ": " + t->name + " lies outside the file"); + + double nn = 0.0; + for (int64_t i = 0; i < n_embd; ++i) nn += (double) d[i] * (double) d[i]; + const double norm = std::sqrt(nn); + if (!(norm > 0.0) || !std::isfinite(norm)) + return fail("control vector " + path + ": " + t->name + " has no direction"); + + float* dst = &out->dir[(size_t) (l * n_embd)]; + const float inv = (float) (1.0 / norm); + for (int64_t i = 0; i < n_embd; ++i) dst[i] = d[i] * inv; + out->scales[(size_t) l] = (float) norm * scale; + + /* A layer inside the range with no direction would silently be unsteered. */ + if (l >= first && l <= last) worst = std::max(worst, std::fabs(norm - 1.0)); + } + for (int64_t l = first; l <= last; ++l) + if (out->scales[(size_t) l] == 0.0f) + return fail("control vector " + path + ": the range " + std::to_string(first) + ":" + + std::to_string(last) + " includes layer " + std::to_string(l) + + ", which has no direction in the file"); + + if (worst > 1e-2) + RAD_WARN("control vector: %s: the directions are not unit-normalised (worst |norm - 1| " + "= %.4f); each is divided by its own norm, so the operation is unchanged", + path.c_str(), worst); + return RAD_OK; +} + +RadControlVector control_vector_view(const ControlVector& cv, const float* dir_device) { + RadControlVector v{}; + v.dir = dir_device; + v.scales = cv.scales.data(); + v.n_embd = cv.n_embd; + v.n_layers = cv.n_layers; + return v; +} + +const float* control_vector_upload(const ControlVector& cv, int rank) { + if (!cv.loaded()) return nullptr; + const int64_t bytes = (int64_t) cv.dir.size() * 4; + void* d = rad_dev_alloc(bytes, RAD_MEM_DEVICE); + if (!d) { + RAD_ERR("speed projection: rank %d: could not allocate %.2f MiB on the card for the " + "directions", rank, (double) bytes / (1024.0 * 1024.0)); + return nullptr; + } + RadStream s = nullptr; + if (rad_stream_create(&s, 0) < 0) { + rad_dev_free(d, RAD_MEM_DEVICE); + return nullptr; + } + const int rc = rad_memcpy_async(d, cv.dir.data(), bytes, s); + rad_stream_sync(s); + rad_stream_destroy(s); + if (rc < 0) { + RAD_ERR("speed projection: rank %d: uploading the directions failed: %s", rank, + rad_dev_last_error()); + rad_dev_free(d, RAD_MEM_DEVICE); + return nullptr; + } + return (const float*) d; +} + +uint64_t control_vector_salt(const ControlVector& cv) { + if (!cv.loaded()) return 0; + return hash_table(cv) | 1ull; +} + +} /* namespace rad */ diff --git a/core/cvec.h b/core/cvec.h new file mode 100644 index 00000000..cf86e773 --- /dev/null +++ b/core/cvec.h @@ -0,0 +1,100 @@ +/* cvec.h -- the experimental speed projection: a GGUF control vector on the residual stream. + * + * ============================== what it is ============================== + * + * The package at huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection carries one unit + * direction per layer (`direction.1` .. `direction.47`, 2560 f32 each) and the configuration its + * authors selected: the llama.cpp `--cvec-mode project` operation + * + * h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| + * + * over layers 4..44, applied to every stream of the gated residual. Strata ports the same + * package (`data/experimental-speed-projection`) with the same operation, range and per-request + * switch; this is that port for radiance, which has its own graph and cannot use llama.cpp's + * patch (arch/qwen4exp_fp8 issues `hc_project` from the op vocabulary instead). + * + * The vector is a refusal-direction projection: with it on the model declines far fewer requests. + * Removing refusals removes a safety behaviour, so the default is OFF and every request names its + * own choice, and the file is only read when the engine finds one for this container. + * + * ============================== compatibility, checked, not assumed ============================== + * + * Nothing here trusts the file's provenance. A vector is refused unless + * + * - `general.architecture` is `controlvector`, + * - `controlvector.model_hint`, when present, names this model's architecture plugin + * (`qwen4exp`), since a direction from another architecture's residual basis is noise, + * - every tensor is `direction.`, F32, one dimension, and exactly the model's `n_embd`, + * - the layer range lies inside the model and every layer in it has a direction. + * + * The published Flash-Next vector passes all four against a Flash-Next container: 47 tensors of + * 2560 f32, hint `qwen4exp`, range 4..44 of 48 layers. A 27B, Gemma or Qwen3.6 container refuses + * it at startup with the reason, rather than serving a model whose hidden states are moved along + * an unrelated direction. + */ +#pragma once +#include "rad_internal.h" + +#include +#include + +namespace rad { + +/* What a loaded vector keeps on the host, before it is uploaded per rank. `dir` is + * [n_layers * n_embd] f32, unit rows, row 0 unused (the format has no direction for layer 0); + * `scales[l]` is |d_l| * user scale, or 0 where the layer is outside the loaded range. */ +struct ControlVector { + std::vector dir; + std::vector scales; + int64_t n_embd = 0; + int64_t n_layers = 0; + int first = -1, last = -1; /* inclusive layer range */ + float user_scale = 1.0f; + std::string path; + + bool loaded() const { return n_layers > 0 && n_embd > 0; } + /* Whether layer `l` is steered, i.e. a kernel has something to project. Mirror of the loader's + * range check, used by the architecture plugin at declare. */ + bool covers(int64_t l) const { + return loaded() && l >= first && l <= last && l < (int64_t) scales.size() && + scales[(size_t) l] != 0.0f; + } +}; + +/* Read and validate `path` against a model of `n_embd` and `n_model_layers`. + * + * The operation's parameters come with the package, never from a command line: `path`'s own + * `.json` (the JSON the vector is published with) supplies `layer_range` and `scale` when it + * says `"mode": "project"`. Without one, the range is the published Qwen3.8-Flash-Next selection + * (4..44) where the file has directions there, else every layer the file carries, at scale 1. */ +int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd, + int64_t n_model_layers, ControlVector* out, std::string* err); + +/* Where a vector for `model_path` is looked for: + * the container's sidecar, then one generic name in the container's directory, then each + * $RADIANCE_HOME's `vectors/` directory. Mirrors gen_sidecar_path's naming so an operator who + * already knows the generation-config convention knows this one. */ +std::string control_vector_sidecar_path(const std::string& model_path); + +/* Resolve `auto`: sets *found to the first candidate that exists and is non-empty, or to "" when + * none does. *tried receives the candidates, for the log line that says why the feature is + * unavailable on this deployment. Discovery is a filesystem test only; whether the file is + * compatible is control_vector_load's answer. */ +int control_vector_discover(const std::string& model_path, const std::string& arch, + const std::string& radiance_home, std::string* found, + std::string* tried); + +/* Build the ABI view for one rank. `dir_device` is that rank's [n_layers, n_embd] f32 copy. */ +RadControlVector control_vector_view(const ControlVector& cv, const float* dir_device); + +/* Upload the host table to a fresh device buffer on rank `rank`, or null on failure. The caller + * owns the buffer and frees it with rad_dev_free. */ +const float* control_vector_upload(const ControlVector& cv, int rank); + +/* The layer salt a cache uses so that blocks and linear-state snapshots computed with the mode on + * are never handed to a request with it off (or to another vector's). 0 for "off", which is also + * the value the engine uses with no vector loaded, so a deployment without the feature hashes + * exactly as it did before it existed. */ +uint64_t control_vector_salt(const ControlVector& cv); + +} /* namespace rad */ diff --git a/core/engine.cpp b/core/engine.cpp index 3256f380..ba865d38 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -58,6 +58,18 @@ Engine::Readback::~Readback() { } Engine::~Engine() { + /* The control vector's per-rank direction copies. Uploaded at declare, outside any arena, so + * nothing else frees them; each rank's copy is freed with that rank's device bound, since the + * allocator is per device. */ + for (const auto& r : ranks_) { + if (!r || (size_t) r->index >= cvec_views_.size()) continue; + const float* d = cvec_views_[(size_t) r->index].dir; + if (!d) continue; + if (rad_dev_set(r->device) < 0) continue; + rad_dev_free((void*) d, RAD_MEM_DEVICE); + cvec_views_[(size_t) r->index].dir = nullptr; + } + cvec_views_.clear(); /* --profile-ops prints its final table here, the last point where the program still holds * the op table the rows name. */ if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile(); @@ -1444,6 +1456,11 @@ int Engine::serve(std::unique_ptr watch) { kv_iface_ = std::make_unique>(&ranks_[0]->kv); pc_iface_ = std::make_unique>(&ranks_[0]->prefix); + /* The control vector's identity partitions the block cache (PCBinding::salt_id): a request + * that runs with the projection on never adopts a block or a linear-state snapshot produced + * without it, or the other way round. Zero with no vector loaded, and then every chain hashes + * exactly as it did before the feature existed. */ + static_cast*>(pc_iface_.get())->salt_id = cvec_salt_; /* The restore path, installed only when the tiers are on. The scheduler calls it before the * admission lookup without knowing about tiers, so it is a callable rather than an include in * core/sched. @@ -1460,7 +1477,8 @@ int Engine::serve(std::unique_ptr watch) { PrefixCache& pc = ranks_[0]->prefix; std::vector mk; media_keys(req, &mk); - const std::vector want = pc.restorable_from(req.prompt, mk); + const std::vector want = + pc.restorable_from(req.prompt, mk, cvec_salt_for(req.sp.use_control_vector)); if (want.empty()) return; /* The whole chain in one restore. With 4-token blocks a long conversation is tens of * thousands of entries; batched, it is one launch per (group, layer) per staging batch @@ -1615,6 +1633,25 @@ bool Engine::state_slots_of(uint64_t seq, std::vector* out) const { /* The engine's part of /server_info: model, cards, KV, drafting and wire, for a running process. * The server holds only interfaces, so the engine renders this object and the server splices it in * verbatim. */ +/* The experimental speed projection, for /stats, /v1/models and /server_info. `available` is + * what a client should test before sending the field: without a loaded vector a request that asks + * for it is refused, so a UI can hide the control rather than offer a switch that fails. */ +std::string Engine::cvec_json() const { + nlohmann::ordered_json o; + o["available"] = cvec_.loaded(); + o["default"] = cvec_default_.load(); + if (cvec_.loaded()) { + o["first"] = cvec_.first; + o["last"] = cvec_.last; + o["n_embd"] = cvec_.n_embd; + o["n_layers"] = cvec_.n_layers > 0 ? cvec_.n_layers - 1 : 0; + o["scale"] = cvec_.user_scale; + o["file"] = cvec_.path; + o["mode"] = "project"; + } + return o.dump(); +} + std::string Engine::engine_info() const { nlohmann::ordered_json e; e["arch"] = meta_.arch_id ? meta_.arch_id : ""; @@ -1638,6 +1675,7 @@ std::string Engine::engine_info() const { e["vision_tower_placement"] = { { "asked", table_placement_name(cfg_.tower_placement) }, { "resolved", table_placement_name(cfg_.tower_resolved) } }; e["prefix_cache"] = cfg_.prefix_cache; + e["control_vector"] = nlohmann::ordered_json::parse(cvec_json()); e["checkpoint_slots"] = cfg_.checkpoint_slots; e["deterministic"] = cfg_.deterministic; @@ -1992,6 +2030,15 @@ int Engine::run_server() { d.tok = &tok_bridge; d.grammar = &grammar_bridge; d.live = snap; + /* The experimental speed projection, when a vector was loaded. The admin endpoint flips the + * default through this; nothing rebuilds a graph, so a toggle takes effect on the next request + * and leaves the running ones alone. */ + if (cvec_.loaded()) { + d.control_vector.available = [this] { return cvec_loaded(); }; + d.control_vector.get_default = [this] { return cvec_default_on(); }; + d.control_vector.set_default = [this](bool on) { set_cvec_default(on); }; + d.control_vector.json = [this] { return cvec_json(); }; + } /* An embedding model serves /v1/embeddings and no chat. Its named prompts are the checkpoint's * sentence-transformers configuration (`sentence_transformers.prompts.*`); a `messages` input diff --git a/core/engine.h b/core/engine.h index 4b07a680..56c57d47 100644 --- a/core/engine.h +++ b/core/engine.h @@ -19,6 +19,7 @@ */ #pragma once #include "rad_core.h" +#include "cvec.h" #include #include #include "build/startup.h" @@ -88,6 +89,24 @@ public: std::string diagnostics_json() const; bool startup_report_printed() const { return report_printed_; } + /* ---- the control vector's public surface (core/cvec.h). + * + * `cvec_loaded` is whether a vector was found and validated for this container; a request + * asking for the feature on a deployment without one is refused by name rather than silently + * served unprojected. `cvec_default_on` is the runtime default for requests that name no + * choice, and the setter is what POST /admin/control-vector calls: it flips a flag, builds + * nothing, reloads nothing, and leaves every running request alone. */ + bool cvec_loaded() const { return cvec_.loaded(); } + bool cvec_default_on() const { return cvec_default_.load(); } + void set_cvec_default(bool on) { cvec_default_.store(on); } + /* {available, default, mode, first, last, n_embd, n_layers, scale, file} for /stats, the + * admin route and the dashboard. */ + std::string cvec_json() const; + /* The value the block cache is keyed by for a step with this mode: the vector's identity when + * on, 0 when off. Zero with no vector loaded, so a deployment without the feature hashes + * exactly as before. */ + uint64_t cvec_salt_for(bool on) const { return on ? cvec_salt_ : 0; } + private: /* One thread per tensor-parallel rank, each owning one device. Ranks share the address * space, so there is no IPC or serialisation and the step batch is shared by pointer rather @@ -463,6 +482,20 @@ private: std::string p2p_blocked_; bool has_ngram_ = false; /* the model carries an n-gram table */ std::string prefix_off_why_; /* why the engine itself turned prefix caching off, or "" */ + + /* ---- the experimental speed projection (core/cvec.h). `cvec_` is the host table, loaded + * once at bringup and empty when the feature is off; `cvec_views_` is, per rank, that table + * uploaded to the rank's card and the ABI view build_ctx hands to a declaring plugin (the + * view's `dir` is the allocation, so one vector holds both). `cvec_salt_` partitions the + * prefix cache between the mode on and off, so a conversation's KV and linear state are never + * reused by a step that would compute different hidden states from the same tokens. */ + ControlVector cvec_; + std::vector cvec_views_; + uint64_t cvec_salt_ = 0; + /* Runtime default for requests that name no choice (flippable through + * POST /admin/control-vector). Atomic: the server's admin thread writes it while + * request threads read it; nothing about the graph changes with it. */ + std::atomic cvec_default_{false}; std::vector env_set_; /* the RADIANCE_* names set when the engine was made */ bool report_printed_ = false; /* Runtime device identity (PCI address, name, integrated flag, runtime version), read once in diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 7192f0a0..521f98fe 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -895,6 +895,12 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { /* Under --prefill-span every step but a lone prefill is planned at the shared budget * (Scheduler::step), so a wider step is one sequence; 0 without a span. */ bc.max_mixed_tok = cfg_.prefill_span > 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0; + /* The control vector, when one is loaded: this rank's view, or null. A plugin reads it at + * declare only (the direction table never changes); the per-request switch rides the derived + * mask, not this struct. */ + if (cvec_.loaded() && rank >= 0 && rank < (int) cvec_views_.size() && + cvec_views_[(size_t) rank].dir) + bc.cvec = &cvec_views_[(size_t) rank]; return bc; } @@ -1063,6 +1069,52 @@ int Engine::declare() { * a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each * thread binds its device first, because the current device is thread-local and the init * allocates on it. */ + /* Control vectors are resolved here, before any rank declares: the plugin reads the direction + * table from RadBuildCtx, so a table that failed validation must stop the server before a graph + * is built around it. + * + * There is nothing to configure. A vector is a property of the model family, so the engine + * looks for one beside the container (or in the directory, or in $RADIANCE_HOME/vectors) and + * uses it if it is compatible with this container; its operation parameters come from the + * package's own JSON. A file that does not fit is reported and skipped -- a sidecar must never + * stop a server nobody pointed at it -- while the switch itself stays off until a request (or + * the dashboard) asks for it. */ + const std::string arch = meta_.arch_id ? meta_.arch_id : ""; + if (!arch.empty()) { + std::string proj_path, tried; + (void) control_vector_discover(cfg_.model, arch, cfg_.radiance_home, &proj_path, &tried); + if (proj_path.empty()) { + RAD_INFO("control vectors: none found (%s)", tried.c_str()); + } else if (arch != "qwen4exp") { + RAD_WARN("control vectors: %s is for this family only (qwen4exp, whose gated residual " + "carries the projection op); this container is '%s' -- ignoring it", + proj_path.c_str(), arch.c_str()); + } else { + std::string why; + const int rc = control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers, + &cvec_, &why); + if (rc != RAD_OK) { + RAD_WARN("%s -- serving without it", why.c_str()); + cvec_ = ControlVector{}; + } + } + } + if (cvec_.loaded()) { + cvec_views_.assign(ranks_.size(), RadControlVector{}); + cvec_salt_ = control_vector_salt(cvec_); + cvec_default_.store(false); + RAD_INFO("control vectors: %s: %lld directions of %lld, layers %d..%d, scale %.3f -- " + "off until a request asks for it (the dashboard's switch, or a request's `control_vector` " + "field)", + cvec_.path.c_str(), (long long) (cvec_.n_layers > 0 ? cvec_.n_layers - 1 : 0), + (long long) cvec_.n_embd, cvec_.first, cvec_.last, (double) cvec_.user_scale); + decide("control vectors", cvec_.path, + "found beside the container, in its directory, or in $RADIANCE_HOME/vectors; " + "requests opt in"); + } else { + cvec_default_.store(false); + } + std::vector st(ranks_.size(), RAD_OK); std::vector th; th.reserve(ranks_.size()); @@ -1076,6 +1128,17 @@ int Engine::declare() { st[(size_t)ri] = RAD_E_DEVICE; return; } + /* This rank's copy of the control vector's directions, on the device the thread has + * just bound. Uploaded outside the program's arena: it is not a weight (it is not in + * the container) and not an activation (it lives for the deployment). */ + if (cvec_.loaded()) { + const float* d = control_vector_upload(cvec_, ri); + if (!d) { + st[(size_t)ri] = RAD_E_DEVICE; + return; + } + cvec_views_[(size_t)ri] = control_vector_view(cvec_, d); + } const RadBuildCtx bc = build_ctx(ri, cfg_.max_tok); LoraDeclare ld; ld.cfg = &cfg_.lora; diff --git a/core/rad_core.h b/core/rad_core.h index 6185bf76..c23c9f55 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -614,6 +614,14 @@ struct SamplingParams { * scheduler thread where every other request's step waits; held here, starting is a lookup. * Null for a request not admitted through the server; the sampler then compiles. */ std::shared_ptr grammar_program; + + /* The control vector (core/cvec.h): whether this request's steps project the vector found for + * this deployment out of the residual stream. The server sets it from the request's + * `control_vector` field (`experimental_speed_projection` is Strata's spelling of the same + * switch), or from the deployment's runtime default when the request names none; it needs no + * reload and leaves the graph untouched. A deployment with no vector refuses `true` at + * admission rather than serving the stock model. */ + bool use_control_vector = false; }; /* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 0abae8bf..8fa48a77 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -101,6 +101,7 @@ ABI_FIELD(RadBuildCtx, max_out_rows) ABI_FIELD(RadBuildCtx, max_audio_frames) ABI_FIELD(RadBuildCtx, max_mixed_tok) ABI_FIELD(RadBuildCtx, kv_quant) +ABI_FIELD(RadBuildCtx, cvec) ABI_STRUCT(RadAudioGenBatch) ABI_FIELD(RadAudioGenBatch, n_lane) ABI_FIELD(RadAudioGenBatch, lane) @@ -169,6 +170,11 @@ ABI_FIELD(RadAudioGenDecl, prompt_whole) ABI_FIELD(RadAudioGenDecl, first_frame) ABI_FIELD(RadAudioGenDecl, voc_chunk) ABI_FIELD(RadAudioGenDecl, voc_context) +ABI_STRUCT(RadControlVector) +ABI_FIELD(RadControlVector, dir) +ABI_FIELD(RadControlVector, scales) +ABI_FIELD(RadControlVector, n_embd) +ABI_FIELD(RadControlVector, n_layers) ABI_STRUCT(RadAudioFormat) ABI_FIELD(RadAudioFormat, struct_size) ABI_FIELD(RadAudioFormat, audio_open) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index 9ff6bc7a..70fa21a3 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -80,7 +80,7 @@ { "RadBufDecl", "domain", 60, 4 }, { "RadBufDecl", "derive", 64, 8 }, { "RadBufDecl", "kv", 72, 4 }, -{ "RadBuildCtx", "", 0, 112 }, +{ "RadBuildCtx", "", 0, 120 }, { "RadBuildCtx", "rank", 0, 4 }, { "RadBuildCtx", "world_size", 4, 4 }, { "RadBuildCtx", "max_tok", 8, 8 }, @@ -98,6 +98,7 @@ { "RadBuildCtx", "max_audio_frames", 88, 8 }, { "RadBuildCtx", "max_mixed_tok", 96, 8 }, { "RadBuildCtx", "kv_quant", 104, 4 }, +{ "RadBuildCtx", "cvec", 112, 8 }, { "RadAudioGenBatch", "", 0, 264 }, { "RadAudioGenBatch", "n_lane", 0, 8 }, { "RadAudioGenBatch", "lane", 8, 8 }, @@ -166,6 +167,11 @@ { "RadAudioGenDecl", "first_frame", 204, 4 }, { "RadAudioGenDecl", "voc_chunk", 208, 8 }, { "RadAudioGenDecl", "voc_context", 216, 8 }, +{ "RadControlVector", "", 0, 32 }, +{ "RadControlVector", "dir", 0, 8 }, +{ "RadControlVector", "scales", 8, 8 }, +{ "RadControlVector", "n_embd", 16, 8 }, +{ "RadControlVector", "n_layers", 24, 8 }, { "RadAudioFormat", "", 0, 72 }, { "RadAudioFormat", "struct_size", 0, 4 }, { "RadAudioFormat", "audio_open", 8, 8 }, diff --git a/tests/cvec_test.cpp b/tests/cvec_test.cpp new file mode 100644 index 00000000..a6ad220a --- /dev/null +++ b/tests/cvec_test.cpp @@ -0,0 +1,241 @@ +/* cvec_test.cpp -- the experimental speed projection's loader (core/cvec.h). + * + * The vector is the published package's format: a GGUF `controlvector` with one unit f32 + * `direction.` per layer and three metadata keys. These cases write such a file, then check + * both what the loader accepts and, just as important, what it refuses: a vector from another + * architecture, one of the wrong width, and a layer range with a gap must stop startup rather than + * steer a model along a direction that does not describe its residual stream. + * + * The compatibility question the port turns on is answered here rather than assumed: the file's + * directions are 2560 wide and a Flash-Next container's stream is 2560, and the file states + * `qwen4exp` as its architecture hint. + */ +#include "rad_test.h" + +#include "cvec.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +/* A minimal GGUF writer, just enough for a control vector: the header, a string/int KV table, one + * F32 one-dimensional tensor per direction, and the data blob at the file's alignment. */ +struct GgufWriter { + struct T { std::string name; std::vector data; }; + std::vector> strs; + std::vector> ints; + std::vector tensors; + + static void u32(std::string& out, uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back((char) ((v >> (8 * i)) & 0xff)); + } + static void u64(std::string& out, uint64_t v) { + for (int i = 0; i < 8; ++i) out.push_back((char) ((v >> (8 * i)) & 0xff)); + } + static void str(std::string& out, const std::string& s) { + u64(out, s.size()); + out += s; + } + + void write(const std::string& path, uint64_t alignment = 32) const { + std::string h; + h += "GGUF"; + u32(h, 3); + u64(h, tensors.size()); + u64(h, strs.size() + ints.size() + 1); /* + general.alignment */ + for (const auto& [k, v] : strs) { + str(h, k); + u32(h, 8); /* GGUF_STR */ + str(h, v); + } + for (const auto& [k, v] : ints) { + str(h, k); + u32(h, 5); /* GGUF_I32 */ + u32(h, (uint32_t) v); + } + str(h, "general.alignment"); + u32(h, 4); /* GGUF_U32 */ + u32(h, (uint32_t) alignment); + + uint64_t off = 0; + std::string dir; + for (const T& t : tensors) { + str(dir, t.name); + u32(dir, 1); /* n_dims */ + u64(dir, (uint64_t) t.data.size()); /* ne[0] */ + u32(dir, 0); /* ggml type 0 = F32 */ + const uint64_t padded = t.data.size() * 4; + u64(dir, off); + off += (padded + alignment - 1) / alignment * alignment; + } + h += dir; + while (h.size() % alignment) h.push_back('\0'); + for (const T& t : tensors) { + const size_t at = h.size(); + (void) at; + h.append((const char*) t.data.data(), t.data.size() * 4); + while (h.size() % alignment) h.push_back('\0'); + } + std::ofstream f(path, std::ios::binary | std::ios::trunc); + f.write(h.data(), (std::streamsize) h.size()); + } +}; + +/* A vector with the published package's shape: `layers` directions of `n` values, each a unit + * vector, plus the metadata its header carries. */ +GgufWriter make_vector(int64_t n, int layers, const char* arch = "controlvector", + const char* hint = "qwen4exp") { + GgufWriter w; + w.strs.push_back({ "general.architecture", arch }); + w.strs.push_back({ "controlvector.model_hint", hint }); + w.ints.push_back({ "controlvector.layer_count", (int32_t) layers }); + for (int l = 1; l <= layers; ++l) { + std::vector d((size_t) n); + for (int64_t i = 0; i < n; ++i) d[(size_t) i] = (float) std::sin(0.001 * (double) (l + 1) * + (double) i + 0.1 * l); + double ss = 0.0; + for (float v : d) ss += (double) v * v; + const float inv = (float) (1.0 / std::sqrt(ss)); + for (float& v : d) v *= inv; + w.tensors.push_back({ "direction." + std::to_string(l), std::move(d) }); + } + return w; +} + +struct Loaded { + rad::ControlVector cv; + std::string err; + int rc = 0; +}; + +/* A vector file, optionally with the package's JSON beside it (which is where the operation's + * parameters live: there is no flag for them). */ +Loaded load(const GgufWriter& w, int64_t n_embd, int64_t model_layers, const std::string& leaf, + const std::string& json = std::string()) { + const std::string path = radtest::tmp_path(leaf); + w.write(path); + if (!json.empty()) { + const std::string side = path.substr(0, path.find_last_of('.')) + ".json"; + std::ofstream f(side, std::ios::binary | std::ios::trunc); + f << json; + } + Loaded out; + out.rc = rad::control_vector_load(path, "qwen4exp", n_embd, model_layers, &out.cv, &out.err); + return out; +} + +} // namespace + +TEST(the_published_shape_loads_and_is_normalised) { + /* 47 directions of 2560 for a 48-layer model, the range the package's own JSON states. */ + /* Nothing states a range, so the loader takes the published selection, 4..44. */ + const Loaded f = load(make_vector(2560, 47), 2560, 48, "flash-next.gguf"); + CHECK_OK(f.rc); + CHECK_EQ(f.cv.n_embd, (int64_t) 2560); + CHECK_EQ(f.cv.first, 4); + CHECK_EQ(f.cv.last, 44); + /* Indexed by layer, so row 0 exists (the format has no direction for it) and 47 rows follow. */ + CHECK_EQ(f.cv.n_layers, (int64_t) 48); + + for (int l = 1; l <= 47; ++l) { + double ss = 0.0; + for (int64_t i = 0; i < 2560; ++i) + ss += (double) f.cv.dir[(size_t) (l * 2560 + i)] * + (double) f.cv.dir[(size_t) (l * 2560 + i)]; + CHECK_NEAR(std::sqrt(ss), 1.0, 1e-5); + /* Unit rows, so the stored norm -- what llama.cpp keeps as `scales[il]` -- is 1. */ + CHECK_NEAR(f.cv.scales[(size_t) l], 1.0f, 1e-5); + } + /* Outside the range nothing is steered: the plugin declares no op there. */ + CHECK_EQ(f.cv.covers(3), false); + CHECK_EQ(f.cv.covers(4), true); + CHECK_EQ(f.cv.covers(44), true); + CHECK_EQ(f.cv.covers(45), false); + + /* The cache partition: nonzero with a vector loaded, and stable across loads of one file. */ + const Loaded again = load(make_vector(2560, 47), 2560, 48, "flash-next-2.gguf"); + CHECK_OK(again.rc); + CHECK(rad::control_vector_salt(f.cv) != 0); + CHECK_EQ(rad::control_vector_salt(f.cv), rad::control_vector_salt(again.cv)); +} + +TEST(a_vector_for_another_architecture_is_refused) { + /* A direction inferred from another model's residual basis is noise here. The hint is the one + * place the file names its architecture, so it is checked when present. */ + const Loaded l = load(make_vector(2560, 47, "controlvector", "gemma4"), 2560, 48, + "wrong-arch.gguf"); + CHECK(l.rc < 0); + CHECK(l.err.find("gemma4") != std::string::npos); +} + +TEST(a_vector_of_the_wrong_width_is_refused) { + /* 2048-wide directions in a 2560-wide model: the kernel would read past the row. */ + const Loaded l = load(make_vector(2048, 47), 2560, 48, "wrong-width.gguf"); + CHECK(l.rc < 0); + CHECK(l.err.find("2560") != std::string::npos); +} + +TEST(a_layer_range_with_a_gap_is_refused) { + /* A vector with no direction for layer 30 while the range covers it would serve a model that + * is silently unsteered on that layer -- a different model from the one the file describes. */ + GgufWriter w = make_vector(2560, 47); + std::vector kept; + for (auto& t : w.tensors) + if (t.name != "direction.30") kept.push_back(t); + w.tensors = std::move(kept); + const Loaded l = load(w, 2560, 48, "gap.gguf"); + CHECK(l.rc < 0); + CHECK(l.err.find("30") != std::string::npos); +} + +TEST(not_a_control_vector_is_refused) { + const Loaded l = load(make_vector(2560, 47, "qwen4exp", "qwen4exp"), 2560, 48, + "wrong-kind.gguf"); + CHECK(l.rc < 0); + CHECK(l.err.find("controlvector") != std::string::npos); +} + +/* The operation's parameters come from the package's own JSON, not a command line: the published + * Flash-Next vector ships {"mode":"project","scale":1.0,"layer_range":[4,44]}. A JSON that states a + * different range or scale is honoured; one that says another mode, or is malformed, only means the + * defaults (the vector itself is still valid). */ +TEST(the_packages_json_sets_the_range_and_scale) { + const Loaded a = load(make_vector(2560, 47), 2560, 48, "json-range.gguf", + R"({"mode":"project","scale":0.5,"layer_range":[8,20]})"); + CHECK_OK(a.rc); + CHECK_EQ(a.cv.first, 8); + CHECK_EQ(a.cv.last, 20); + CHECK_NEAR(a.cv.scales[(size_t) 8], 0.5f, 1e-5); + CHECK_EQ(a.cv.covers(7), false); + CHECK_EQ(a.cv.covers(21), false); + + /* Another mode is not implemented: the file's directions still load, with the defaults. */ + const Loaded b = load(make_vector(2560, 47), 2560, 48, "json-add.gguf", + R"({"mode":"add","scale":0.1,"layer_range":[16,32]})"); + CHECK_OK(b.rc); + CHECK_EQ(b.cv.first, 4); + CHECK_EQ(b.cv.last, 44); + CHECK_NEAR(b.cv.user_scale, 1.0f, 1e-6); + + /* Malformed JSON is reported, not fatal. */ + const Loaded c = load(make_vector(2560, 47), 2560, 48, "json-broken.gguf", "{ not json"); + CHECK_OK(c.rc); + CHECK_EQ(c.cv.first, 4); +} + +TEST(a_unit_vector_gives_scale_one_at_every_steered_layer) { + const std::string path = radtest::tmp_path("scaled.gguf"); + make_vector(2560, 47).write(path); + rad::ControlVector cv; + std::string why; + CHECK_OK(rad::control_vector_load(path, "qwen4exp", 2560, 48, &cv, &why)); + CHECK_NEAR(cv.scales[(size_t) 4], 1.0f, 1e-5); + CHECK_NEAR(cv.scales[(size_t) 44], 1.0f, 1e-5); +} + +RAD_TEST_MAIN() From 459dd4f42d487eea4c4de5dd25501b1d996e9483 Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Tue, 20 Oct 2026 14:39:19 +0700 Subject: [PATCH 080/152] vocabulary: hc_project -- a control vector's direction, projected out of the wide stream h[s] -= scale * (h[s] . v) * v for each of the hyper-connection streams s llama.cpp's --cvec-mode project semantics: the dot is per stream, because the patch applies it to the [n_embd, hc, tokens] view where mul_mat(v, cur) reduces over dim 0. v is one layer's unit direction (f32), scale is the norm its file stored, and 'on' is a per-row int32 switch: a zero row is skipped without a read or a write, so an unprojected request is byte-identical to a deployment with no vector loaded. libref is the oracle and the host fallback, libavx carries it at every ISA level, libr4d (one workgroup per (row, stream), LDS reduction) serves the card. docs/OPS.md gains the row and the operation's three facts. --- docs/OPS.md | 8 +++ libavx/avx_cases.cpp | 7 ++ libavx/avx_hc.cpp | 58 +++++++++++++++ libavx/avx_isa.h | 22 +++--- libavx/avx_registry.cpp | 10 +++ libr4d/CMakeLists.txt | 3 + libr4d/r4d_hc_project.hip | 144 ++++++++++++++++++++++++++++++++++++++ libr4d/r4d_plugin.h | 2 + libr4d/r4d_rows.cpp | 25 +++++++ libr4d/r4d_shapes.cpp | 13 ++++ libref/ref_hc.cpp | 53 ++++++++++++++ libref/ref_ops.h | 2 + libref/ref_registry.cpp | 15 ++++ libref/ref_shapes.cpp | 11 +++ 14 files changed, 362 insertions(+), 11 deletions(-) create mode 100644 libr4d/r4d_hc_project.hip diff --git a/docs/OPS.md b/docs/OPS.md index cf02fa96..b8be4ef2 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -199,6 +199,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `mhc_contract` | `M`(range) `n` `hc` `dtype` | `h` → `x` | | `hc_read` | `M`(range) `n` `hc` `lowrank` `eps`:f64 `dtype` `wadd`:f64/opt `inject`/opt `group`/opt `rotate`/opt `mix`/opt | `h`, `w`w, `mix_down`w, `mix_up`w, `inject_w`w? → `x`, `inj`?, `q`?, `scale`?, `rq`?, `rscale`? | | `hc_write` | `M`(range) `n` `hc` `dtype` | `y`, `inj`, `h`:inout | +| `hc_project` | `M`(range) `n` `hc` `scale`:f64 `dtype` | `h`:inout, `v`, `on` | | `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` | | `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | | `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | @@ -307,6 +308,13 @@ so a different op rather than a mode a library could ignore. ### Hyper-connections +`hc_project` is the control vector's projection (core/cvec.h): `h[s] -= +scale * (h[s] . v) * v` for each of the `hc` streams of a row whose `on` flag (an int32 per row) is +1, `v` being that layer's unit direction and `scale` the norm the file stored. It is llama.cpp's +`--cvec-mode project`, applied after a layer's write into the stream. A row whose flag is 0 is +neither read nor written, so an unprojected request's stream is the stock model's; the direction table is f32 and the op is issued only by an architecture that was +declared with one (`RadBuildCtx::cvec`). + `hc_read` and `hc_write` are the gated residual pair a hyper-connection model has instead of a pre-norm and a residual add. The stream is `hc` times the model width; every block reads a mix of the `hc` sub-streams and writes back into all of them, both gated by data: diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index cdc34b1b..1ec95836 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -147,6 +147,13 @@ std::vector build_cases() { HF("lower_bound", -5), HF("scale", 0.1767766952966369), HF("l2_eps", 1e-6), HS("mode", mode), HS("dtype", dt) }); add("hc_write", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) }); + add("hc_project",{ HI("M", 5), HI("n", 128), HI("hc", 4), HF("scale", 1.0), + HS("dtype", dt) }); + /* The model's own width: Qwen3.8-Flash-Next's stream is 2560 wide with hc 4, and a decode + * step is one row per sequence (with speculation, up to 1 + depth). One case at that + * geometry is what says whether 41 of these a step is affordable. */ + add("hc_project",{ HI("M", 4), HI("n", 2560), HI("hc", 4), HF("scale", 1.0), + HS("dtype", "bf16") }); add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8), HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 1), HI("inject", 1), HI("group", 0) }); diff --git a/libavx/avx_hc.cpp b/libavx/avx_hc.cpp index a2462447..4c7cea3c 100644 --- a/libavx/avx_hc.cpp +++ b/libavx/avx_hc.cpp @@ -331,6 +331,64 @@ AVX_KERNEL(hc_write) { return RAD_OK; } +/* ------------------------------------------------------------------ hc_project */ +/* The experimental speed projection (core/cvec.h): h[s] -= scale * (h[s] . v) * v for each of the + * hc streams of a row whose switch is on. v is f32, the stream may be bf16/f16/f32; a row with a + * zero switch is skipped without a read, so an unprojected request is byte-identical to one on a + * deployment with no vector. */ +AVX_KERNEL(hc_project) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor* h = &a->t[0]; + const RadTensor* v = &a->t[1]; + const RadTensor* on = &a->t[2]; + + const int64_t n = p_int(a, "n", 0); + const int64_t hc = p_int(a, "hc", 0); + const float sc = p_f32(a, "scale", 1.0f); + if (n <= 0 || hc <= 1 || numel(v) < n) return RAD_E_SHAPE; + const int64_t hn = hc * n; + const int64_t rows = numel(h) / hn; + if (rows <= 0 || numel(on) < rows) return RAD_E_SHAPE; + + const int64_t vb = rowoff(v, 0, n); + float* vbuf = scratch_f32_c((size_t) n); + const float* vec = in_row(v, vb, n, vbuf); + + AVX_PARALLEL_FOR_IF(rows * hn >= AVX_PAR_MIN) + for (int64_t k = 0; k < rows * hc; ++k) { + const int64_t r = k / hc, c = k % hc; + if (ldi(on, offlin(on, r)) == 0) continue; + const int64_t hb = rowoff(h, r, hn), hs = laststride(h); + const int64_t base = hb + c * n; + float* hv = scratch_f32((size_t) n); + const float* row = in_row(h, base, n, hv); + if (hs != 1) { + float dot = 0.0f; + for (int64_t i = 0; i < n; ++i) dot += row[i] * vec[i]; + const float g = dot * sc; + for (int64_t i = 0; i < n; ++i) + stt(h, base + i * hs, row[i] - g * vec[i]); + continue; + } + if (row != hv) std::memcpy(hv, row, (size_t) n * sizeof(float)); + /* The dot reads the row and the direction; the update then rewrites the same elements, so + * the direction's own copy is not needed (it is never written). */ + vf acc = vf_zero(); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) + acc = vf_fma(vf_loadu(hv + i), vf_loadu(vec + i), acc); + float dot = vf_hsum(acc); + for (; i < n; ++i) dot += hv[i] * vec[i]; + const vf vg = vf_set1(dot * sc); + i = 0; + for (; i + VF_N <= n; i += VF_N) + vf_storeu(hv + i, vf_sub(vf_loadu(hv + i), vf_mul(vg, vf_loadu(vec + i)))); + for (; i < n; ++i) hv[i] -= (dot * sc) * vec[i]; + out_row(h, base, n, hv); + } + return RAD_OK; +} + /* ================================================================== mtp_enter * * Entry of the multi-token-prediction head for a model with an `hc`-wide residual stream. diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 57fac4df..ddff5118 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -70,17 +70,17 @@ int avx_par_force(int threads); #define AVX_OP_LIST(X) \ /* ---- elementwise and norms */ \ X(rmsnorm) X(rmsnorm_p) X(rmsnorm_add) X(hc_enter) \ - X(hc_read) X(hc_write) X(mtp_enter) X(layernorm) \ - X(mhc_pre) X(mhc_post) X(mhc_contract) X(kda_update) \ - X(mhc_pre_partial) X(mhc_pre_finish) \ - X(swiglu_clamped) \ - X(router_sigmoid_topk) \ - X(dsa_pool) \ - X(dsa_query) \ - X(gemm_nt_f32) \ - X(mla_project) \ - X(dsa_score) \ - X(mla_attn) \ + X(hc_read) X(hc_write) X(hc_project) X(mtp_enter) \ + X(layernorm) X(mhc_pre) X(mhc_post) X(mhc_contract) \ + X(kda_update) X(mhc_pre_partial) X(mhc_pre_finish) \ + X(swiglu_clamped) \ + X(router_sigmoid_topk) \ + X(dsa_pool) \ + X(dsa_query) \ + X(gemm_nt_f32) \ + X(mla_project) \ + X(dsa_score) \ + X(mla_attn) \ X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \ X(mul) X(silu_mul) X(gelu_mul) X(gelu) \ X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 11470960..0d98407c 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -114,6 +114,10 @@ static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_st static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") }; static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") }; static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") }; +/* The speed projection: one unit direction per layer (f32) and an int32 per-row switch. */ +static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"), + P_STR("dtype") }; +static const RadOperandSpec oHcProject[] = { INOUT("h"), OPD("v"), OPD("on") }; static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("eps"), P_STR("dtype"), P_F64O("wadd"), P_INTO("ngroup"), @@ -826,6 +830,9 @@ static const RadOpSchema kSchemas[] = { "gate argument, and hc_write adds into the UNNORMED h). `mix` names the matrices' stored " "format; a host kernel reads them as the dense tensors it is handed." }, { "hc_write", ARR(pHcWrite), ARR(oHcWrite), "h[s] += inj[s] * y, into the unnormed stream." }, +{ "hc_project", ARR(pHcProject), ARR(oHcProject), + "The experimental speed projection (llama.cpp's `--cvec-mode project`): h[s] -= scale * " + "(h[s] . v) * v for each of the hc streams of a row whose flag is on. A zero flag is not read." }, { "mtp_enter", ARR(pMtpEnter), ARR(oMtpEnter), "MTP head entry: two norms, a per-sub-stream fc and a broadcast fc. `fc` names the two " "matrices' stored format; a host kernel reads them as the dense tensors it is handed." }, @@ -1362,6 +1369,9 @@ ROWL("avx_hc_read", "hc_read", "norm", avx_layout_hc), SIMPLE("avx_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y", DT_FLOAT, L(hc_write)), +SIMPLE("avx_hc_project", "hc_project", "norm", + "speed projection: h[s] -= scale * (h[s] . v) * v where the row's flag is on", DT_FLOAT, + L(hc_project)), ROWL("avx_mtp_enter", "mtp_enter", "norm", "MTP head entry: two norms, a per-sub-stream fc and a broadcast fc", DT_FLOAT ", or fc matrices of E4M3 / int8 codes with a scale plane, joined", L(mtp_enter), diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 8efe1975..beab445c 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -175,6 +175,9 @@ set(R4D_UNITS # Gemma 4's sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and # expert_scale, each one kernel for a chain of small ones. "r4d_norm_join_bf16|" + # The experimental speed projection (core/cvec.h): one pass of h[s] -= s (h[s].v) v over the wide + # stream, with a per-row switch. + "r4d_hc_project|" "r4d_expert_scale_bf16|" # Runtime LoRA's two halves (lora_shrink, lora_expand), per-row adapter slot: scalar and tiled rows. "r4d_lora_bf16|" diff --git a/libr4d/r4d_hc_project.hip b/libr4d/r4d_hc_project.hip new file mode 100644 index 00000000..4609a513 --- /dev/null +++ b/libr4d/r4d_hc_project.hip @@ -0,0 +1,144 @@ +// r4d_hc_project.hip -- the experimental speed projection on the gated residual's wide stream. +// +// The operation is llama.cpp's `--cvec-mode project`, which the Qwen3.8-Flash-Next control-vector +// package publishes and Strata ports (data/experimental-speed-projection): for each of the hc +// streams of a token's residual row, +// +// h[s] -= scale * (h[s] . v) * v +// +// with `v` that layer's UNIT direction and `scale` the norm the file stored for it. The dot is +// taken per stream, not on the stream mean: llama.cpp's patch applies `build_cvec` to the +// [n_embd, hc, tokens] residual view, where `mul_mat(v, cur)` reduces over dim 0 alone. +// +// The op is issued after a layer's feed-forward write into the stream, which is where the patch's +// `build_cvec(res_hc, il)` sits in the `qwen4exp` graph. +// +// ============================== the per-row switch ============================== +// +// `on` is an int32 per row (core derive.cpp's `projection_on_rows`: the request's own choice, +// expanded across its tokens once a step). A zero row is skipped before any load: no read, no +// write. That is what makes a request without the vector byte-identical to a deployment with no +// vector loaded -- not merely close -- and it costs one load per row per layer. +// +// ============================== shape ============================== +// +// One workgroup per (token row, stream): it holds the whole of `v`'s stream in no memory at all +// (it streams `h` and `v` together), reduces the dot in LDS, and then rewrites the row. Grid +// (rows, hc). At the model's shape (n 2560, hc 4) that is 2560 f32 of `v` re-read per (row, +// stream): 40 KB per token per layer, against 40 KB of `h` -- the same traffic as the write it +// follows, within a fraction of the step's expert traffic. +#include + +#include +#include + +#include "r4d.h" +#include "r4d_args.h" + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kMaxWave = 64; + +__device__ __forceinline__ float bf2f(uint16_t h) { + const uint32_t u = (uint32_t) h << 16; + float f; + std::memcpy(&f, &u, 4); + return f; +} + +__device__ __forceinline__ uint16_t f2bf(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return (uint16_t) ((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +/* One workgroup per (row, stream). `h` is the row's stream at `h + row*h_ld + stream*n`, `v` the + * layer's unit direction (f32, `v_ld` may exceed n for a slice of a wider plane). */ +__global__ __launch_bounds__(kThreads) void hc_project_kernel(uint16_t* __restrict__ h, + const float* __restrict__ v, + const int32_t* __restrict__ on, + uint32_t n, uint32_t h_ld, + uint32_t v_ld, float scale) { + const uint32_t row = blockIdx.x; + if (on[row] == 0) return; // this token's request did not ask for the projection + + uint16_t* __restrict__ hr = h + (size_t) row * h_ld + (size_t) blockIdx.y * n; + const float* __restrict__ vr = v + (size_t) blockIdx.y * v_ld; + + float acc = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) acc += bf2f(hr[i]) * vr[i]; + + __shared__ float red[kMaxWave]; + const uint32_t lane = threadIdx.x % kMaxWave; + const uint32_t wave = threadIdx.x / kMaxWave; + for (uint32_t off = kMaxWave / 2; off > 0; off >>= 1) { + acc += __shfl_down(acc, off, kMaxWave); + } + if (lane == 0) red[wave] = acc; + __syncthreads(); + if (threadIdx.x == 0) { + float total = 0.0f; + const uint32_t nw = (blockDim.x + kMaxWave - 1) / kMaxWave; + for (uint32_t w = 0; w < nw; ++w) total += red[w]; + red[0] = total * scale; + } + __syncthreads(); + + const float g = red[0]; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) + hr[i] = f2bf(bf2f(hr[i]) - g * vr[i]); +} + +} // namespace + +/* Host form: rows and the stream count come from the caller (the entry point below, which reads + * them from the operands). */ +extern "C" int r4d_hc_project_bf16(long h, long v, long on, int rows, int n, int hc, int h_ld, + int v_ld, float scale, long stream) { + if (!h || !v || !on) return -1; + if (rows <= 0 || n <= 0 || hc <= 0) return -2; + if (h_ld <= 0) h_ld = hc * n; + if (v_ld <= 0) v_ld = n; + hipLaunchKernelGGL(hc_project_kernel, dim3((uint32_t) rows, (uint32_t) hc), dim3(kThreads), 0, + (hipStream_t) stream, (uint16_t*) h, (const float*) v, + (const int32_t*) on, (uint32_t) n, (uint32_t) h_ld, (uint32_t) v_ld, + scale); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ============================== the entry point ============================== + * + * Operands: h (inout, bf16, [rows, hc*n]), v (f32, [n]), on (int32, [rows]). Parameters: n, hc, + * scale, dtype. `rows` is derived from h's extent, as every per-row op here does: the kernel owns + * whole rows. */ +extern "C" int r4d_rad_hc_project(const RadArgs* a, RadStream s) { + const RadTensor* h = r4d_opt(a, 0); + const RadTensor* v = r4d_opt(a, 1); + const RadTensor* on = r4d_opt(a, 2); + if (!h || !v || !on) return R4D_NO(RAD_E_INVAL); + if (h->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (v->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (on->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + + const long long n = r4d_geti_or(a, "n", 0); + const long long hc = r4d_geti_or(a, "hc", 0); + if (n <= 0 || hc <= 1) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(v) < n) return R4D_NO(RAD_E_SHAPE); + + long long rows = 0, row_n = 0; + if (r4d_rows_of(h, &rows, &row_n) < 0) return R4D_NO(RAD_E_SHAPE); + if (row_n != hc * n || rows <= 0) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(on) < rows) return R4D_NO(RAD_E_SHAPE); + + /* No pitch handling: the architecture passes the model's own wide stream, contiguous rows of + * hc*n. A strided view is refused rather than silently read as contiguous. */ + const long long h_ld = r4d_stride(h, (int) h->rank - 2); + const long long v_ld = r4d_stride(v, (int) v->rank - 1); + if (h_ld != hc * n || v_ld != 1) return R4D_NO(RAD_E_STRIDE); + + const float scale = (float) r4d_getf(a, "scale", 1.0); + return r4d_hc_project_bf16(r4d_addr(h), r4d_addr(v), r4d_addr(on), (int) rows, (int) n, + (int) hc, (int) h_ld, 0, scale, (long) (uintptr_t) s) == 0 + ? RAD_OK : RAD_E_DEVICE; +} diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 689f39cf..337717be 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -339,6 +339,7 @@ int r4d_rad_dflash_select (const RadArgs*, RadStream); /* -- the gated residual (r4d_hc_bf16.hip) -- */ int r4d_rad_hc_enter (const RadArgs*, RadStream); +int r4d_rad_hc_project (const RadArgs*, RadStream); int r4d_rad_mhc_pre(const RadArgs*, RadStream); int r4d_rad_mhc_pre_partial(const RadArgs*, RadStream); int r4d_rad_mhc_pre_finish(const RadArgs*, RadStream); @@ -751,6 +752,7 @@ int r4d_shape_mhc_contract(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_read (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_write (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_hc_project (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_binary (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_mul_weight (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scatter_rows_bf16(const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index bf59cad7..59f47cbc 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -480,6 +480,16 @@ static const RadOperandSpec oGdnConvRecurrentUpdate[] = { /* The gated residual. `hc_enter` and `hc_write` share a parameter list; `hc_read` adds the two * switches its operand list depends on: `inject` 0 is the final mixer and `group` 0 a read whose * consumer wants bf16. Both default on, as every trunk connection uses both. */ +/* The experimental speed projection (libr4d/r4d_hc_project.hip): a bf16 stream, one unit f32 + * direction per layer, an int32 switch per row. */ +static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"), + P_STR("dtype") }; +static const RadOperandSpec oHcProject[] = { + { "h", RAD_OPD_INOUT, 0 }, { "v", RAD_OPD_IN, 0 }, { "on", RAD_OPD_IN, 0 }, +}; +static const RadConstraint cHcProject[] = { + C_GE("M", 1), C_GE("n", 1), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), +}; static const RadParamSpec pHcPlain[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype"), }; @@ -2934,6 +2944,12 @@ static const RadOpSchema kSchemas[] = { "the read half of a gated residual: a grouped rmsnorm, a low-rank sigmoid gate, and " "the mean of the gated streams -- plus the per-branch write gains and, optionally, " "the block-scaled fp8 form of the block input and its Hadamard-rotated twin."), + SCHEMA("hc_project", pHcProject, oHcProject, + "the experimental speed projection (llama.cpp's `--cvec-mode project`): for each of the " + "hc streams of a row whose `on` flag is 1, h[s] -= scale * (h[s] . v) * v, v that " + "layer's unit direction and scale its stored norm. A row whose flag is 0 is neither read " + "nor written, so an unprojected request is byte-identical to a deployment with no " + "vector loaded."), SCHEMA("hc_write", pHcPlain, oHcWrite, "the write half: h[s] += inj[s] * y, into the UNNORMED stream."), SCHEMA("mtp_enter", pMtpEnter, oMtpEnter, @@ -6510,6 +6526,15 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_hc_write, nullptr, nullptr, nullptr, r4d_shape_hc_write }, +{ "hc_project_bf16", "hc_project", "norm", + "speed projection: h[s] -= scale * (h[s] . v) * v where the row's flag is on", + "any M, any n, hc 2..8", + "bf16 stream, f32 direction, i32 switch", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cHcProject), NOTUNE, + nullptr, nullptr, r4d_rad_hc_project, nullptr, nullptr, nullptr, + r4d_shape_hc_project }, + { "mtp_enter_bf16", "mtp_enter", "norm", "MTP head entry: two norms, a per-sub-stream fc and one broadcast fc", "any M, n 128..5734, hc 2..4", diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 7bc5a417..5f8edd16 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -480,6 +480,19 @@ extern "C" int r4d_shape_hc_write(const RadParam* p, int n_p, int operand, RadOp R4D_PICK(l); } +/* hc_project's three: the bf16 stream (in place), the layer's unit f32 direction, and the int32 + * per-row switch. The switch is an index domain: 0 or 1. */ +extern "C" int r4d_shape_hc_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { + opd(D, M, hc * n), /* h, in place */ + opd((uint32_t) RAD_F32, n), /* v */ + opd_idx(M, 1, 1, 0), /* on: 0 or 1 */ + }; + R4D_PICK(l); +} + /* hc_write's operands with the all-reduce in front; `y` is also the message. */ extern "C" int r4d_shape_ar_hc_write(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return r4d_shape_hc_write(p, n_p, operand, out); diff --git a/libref/ref_hc.cpp b/libref/ref_hc.cpp index 287b96fe..70a58d3c 100644 --- a/libref/ref_hc.cpp +++ b/libref/ref_hc.cpp @@ -252,6 +252,59 @@ int ref_hc_write(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ hc_project */ +/* The experimental speed projection: h[row, s*n + i] -= scale * (h . v) * v, for each of the hc + * streams s, on the rows whose `on` flag is 1. + * + * `v` is one layer's unit direction (the engine normalises the file's rows when it uploads them) + * and `scale` is the norm the file stored for that layer, so this is exactly llama.cpp's + * `--cvec-mode project` with its `llama_adapter_cvec` (the package's 02-cvec-projection-mode + * patch): the dot is taken per hyper-connection stream, as `mul_mat` over a [n, hc, tokens] view + * gives it, and not on the stream mean. + * + * A row whose flag is 0 is not touched: no read, no write, so a request that did not ask for the + * vector's activations are the stock model's: no read, no write. (A deployment that merely *has* the + * table loaded is not bit-identical to one without it -- the table's VRAM moves the expert/KV plan -- + * but that is placement, not this op.) + * + * `on` is an int32 per row (core derive.cpp's `projection_on_rows`); the direction is f32. */ +int ref_hc_project(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor* h = &a->t[0]; + const RadTensor* v = &a->t[1]; + const RadTensor* on = &a->t[2]; + + const int64_t n = p_int(a, "n", 0); + const int64_t hc = p_int(a, "hc", 0); + const float sc = p_f32(a, "scale", 1.0f); + if (n <= 0 || hc <= 1) return RAD_E_SHAPE; + if (numel(v) < n) return RAD_E_SHAPE; + const int64_t hn = hc * n; + + const int64_t rows = rows_of(h, hn); + if (rows <= 0 || numel(on) < rows) return RAD_E_SHAPE; + + /* Rows are independent: each dot is over one row's own streams. The parallel index is the + * (row, stream) pair, so one row's hc streams may run on different threads without sharing an + * accumulator. */ + REF_PAR_FOR(rows * hc) + for (int64_t k = 0; k < rows * hc; ++k) { + const int64_t r = k / hc, c = k % hc; + if (ld_int(on->dtype, on->data, offlin(on, r)) == 0) continue; + const int64_t hb = rowoff(h, r, hn), hs = laststride(h); + const int64_t vb = rowoff(v, 0, n), vl = laststride(v); + double acc = 0.0; + for (int64_t i = 0; i < n; ++i) + acc += (double) ldt(h, hb + (c * n + i) * hs) * (double) ldt(v, vb + i * vl); + const float g = (float) (acc * (double) sc); + for (int64_t i = 0; i < n; ++i) { + const int64_t j = hb + (c * n + i) * hs; + stt(h, j, ldt(h, j) - g * ldt(v, vb + i * vl)); + } + } + return RAD_OK; +} + /* ================================================================== mtp_enter * * The multi-token-prediction head's entry for a model whose residual stream is `hc` wide. diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 4c164a65..1f3e078f 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -67,6 +67,7 @@ int ref_mhc_contract (const RadArgs*, RadStream); int ref_kda_update (const RadArgs*, RadStream); int ref_hc_read (const RadArgs*, RadStream); int ref_hc_write (const RadArgs*, RadStream); +int ref_hc_project (const RadArgs*, RadStream); int ref_mtp_enter (const RadArgs*, RadStream); int ref_layernorm (const RadArgs*, RadStream); int ref_grid_embed (const RadArgs*, RadStream); @@ -317,6 +318,7 @@ REF_SHAPE_FN(ref_mhc_contract); REF_SHAPE_FN(ref_kda_update); REF_SHAPE_FN(ref_hc_read); REF_SHAPE_FN(ref_hc_write); +REF_SHAPE_FN(ref_hc_project); REF_SHAPE_FN(ref_mtp_enter); REF_SHAPE_FN(ref_layernorm); REF_SHAPE_FN(ref_grid_embed); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 827188ca..72837cb8 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -118,6 +118,12 @@ static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_st OPD_O("num_accepted"), OUT("y") }; static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") }; +/* The speed projection (libref/ref_hc.cpp, core/cvec.h): one unit direction per layer and a + * per-row switch. `v` is f32 whatever the stream's dtype is, because the engine uploads the table + * in f32; `on` is an int32 row mask (core derive.cpp's `projection_on_rows`). */ +static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"), + P_STR("dtype") }; +static const RadOperandSpec oHcProject[] = { INOUT("h"), OPD("v"), OPD("on") }; static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") }; static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") }; static const RadParamSpec pMhcPre[] = { P_INT("M"), P_INT("n"), P_INT("hc"), @@ -1003,6 +1009,12 @@ static const RadOpSchema kSchemas[] = { { "hc_write", ARR(pHcWrite), ARR(oHcWrite), "The write half: h[s] += inj[s] * y, for each of the hc streams of h. In place, and `h` is the " "UNNORMED stream the paired hc_read was handed -- the normalisation never enters the residual." }, +{ "hc_project", ARR(pHcProject), ARR(oHcProject), + "The experimental speed projection (llama.cpp's `--cvec-mode project`): for each of the hc " + "streams of a row whose `on` flag is 1, h[s] -= scale * (h[s] . v) * v, with v that layer's unit " + "direction and scale the norm the file stored. The dot is per stream, not on the stream mean. A " + "row whose flag is 0 is not read and not written, so an unprojected request is byte-identical to " + "a deployment with no vector loaded." }, { "mtp_enter", ARR(pMtpEnter), ARR(oMtpEnter), "The MTP head's entry for a wide residual stream: x[k*n+i] = fc_h[i] . grouped_norm(h)[k] " "+ fc_e[i] . norm(e), for each of the hc sub-streams k. `ngroup` == hc is one rsqrt per " @@ -1957,6 +1969,9 @@ ROWL("ref_mtp_enter", "mtp_enter", "norm", ref_check_dtypes, ref_mtp_enter, ref::ref_layout_mtp), SIMPLE("ref_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y", DT_FLOAT, ref_hc_write), +SIMPLE("ref_hc_project", "hc_project", "norm", + "speed projection: h[s] -= scale * (h[s] . v) * v where the row's flag is on", + DT_FLOAT, ref_hc_project), SIMPLE("ref_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT_FLOAT, ref_layernorm), SIMPLE("ref_grid_embed", "grid_embed", "elem", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index f1fd4d8a..cb0d7f21 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -436,6 +436,17 @@ int ref_hc_write_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("hc_write", operand, out); } +int ref_hc_project_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t hc = gi(p, n_p, "hc", 0); + Opd o; + o.t(D, { M, hc * n }); /* h, in place */ + o.t((uint32_t) RAD_F32, { n }); /* v: one layer's unit direction */ + o.t((uint32_t) RAD_I32, { M }); /* on: 1 = this row takes the projection */ + return o.finish("hc_project", operand, out); +} + int ref_mtp_enter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); From 809257e393bba4dc1a2f5a177e9e7a469e813f79 Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Tue, 20 Oct 2026 14:39:19 +0700 Subject: [PATCH 081/152] arch/qwen4exp: the control vector's projection after every block's write HcProject in arch/common/rad_block_hc.h owns the block: its per-token switch buffer (`projection_on_rows`, a derived buffer), the per-layer op and the issue point. The plugin declares it with one call per layer and issues it with one call after the feed-forward write -- the place llama.cpp's build_cvec(res_hc, il) sits in the qwen4exp graph, in both the serial and the pipelined step. An unsteered layer, or a deployment with no vector, declares nothing and issues nothing. --- arch/common/rad_block_hc.h | 98 ++++++++++++++++++++++++++++++ arch/qwen4exp_fp8/qwen4exp_fp8.cpp | 17 ++++++ 2 files changed, 115 insertions(+) diff --git a/arch/common/rad_block_hc.h b/arch/common/rad_block_hc.h index 44c538f7..523f1f3d 100644 --- a/arch/common/rad_block_hc.h +++ b/arch/common/rad_block_hc.h @@ -368,6 +368,104 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con /* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to: * every block leaves its delta in the activation its norm produced, and the input is dead by * then. */ +/* ================================================================== the control-vector projection + * + * A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). Turned on + * for a request, a steered layer's wide stream is projected off that layer's direction right after + * the feed-forward's write: + * + * h[s] -= scale * (h[s] . v) * v for each of the hc streams s + * + * which is llama.cpp's `--cvec-mode project` and the operation the Qwen3.8-Flash-Next package + * documents. The dot is per stream, not on the stream mean: the patch applies it to the + * [n_embd, hc, tokens] view where `mul_mat(v, cur)` reduces over dim 0 alone. + * + * Two properties the architecture plugin does not have to think about, both here: + * + * - **the switch is per request.** `on` is a derived buffer of one int32 per token row + * (core/sched/derive.cpp's `projection_on_rows`), so a step that mixes a projected + * conversation with a stock one projects exactly the rows that asked for it. All zeros is the + * stock model: the kernel skips a zero row without reading or writing it, so an unprojected + * request's stream is the one the stock model computes. (The *deployment* is not bit-identical + * to one with no vector: the direction table's VRAM can move an expert or a KV block, which is + * the tie-level variance radiance documents elsewhere. Measured, docs/GUIDE.md 4.10.) + * - **the parameters travel with the file.** `scale` is the norm the file stored for that layer + * (times the package's own `scale`, read from its JSON), and the direction row is sliced from + * the table at issue, so nothing is configured per deployment or scanned per layer. + * + * One instance per layer: `declare` emits an op only when the vector steers that layer, so a + * deployment without a vector declares no op, no buffer and no branch in the step. */ +struct HcProject { + rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */ + const float* dir = nullptr; /* this layer's row of the device direction table */ + rad_buf on = 0; /* [rows] int32: 1 = project this row */ + rad_buf h = 0; /* the model's wide stream */ + int64_t n = 0, hc = 0; + + bool steered() const { return op != 0; } + + /* The per-token switch, declared once per model as a derived buffer. 0 when the deployment has + * no vector (or one of another width), which leaves every layer unsteered. */ + static rad_buf declare_mask(RadBuilder* b, const char* name, const Geom& g, + const RadControlVector* cv) { + if (!b || g.n_embd <= 0 || g.max_tok <= 0) return 0; + if (!cv || !cv->dir || cv->n_layers <= 0) return 0; + if (cv->n_embd != g.n_embd) { + fprintf(stderr, "radiance: %s: the control vector is %lld wide and this model's " + "residual streams are %lld; not steering it\n", + name, (long long) cv->n_embd, (long long) g.n_embd); + return 0; + } + RadBufDecl d{}; + d.dtype = RAD_I32; + d.rank = 1; + d.shape[0] = g.max_tok; + d.kind = RAD_BUF_DERIVED; + d.domain = RAD_DOMAIN_DEVICE; + d.derive = "projection_on_rows"; + return rad_decl_buffer(b, name, &d); + } + + /* `layer`'s projection, when the vector steers it. Called for every layer; the unsteered ones + * (outside the file, outside the range, or no vector at all) declare nothing. */ + int declare(RadBuilder* b, const char* name, const Geom& g, int64_t layer, + const RadControlVector* cv, rad_buf mask, rad_buf stream, int64_t hc_streams) { + if (!b || !mask || !stream || !cv || !cv->dir || hc_streams <= 1) return RAD_OK; + if (layer <= 0 || layer >= cv->n_layers || layer >= g.n_layer) return RAD_OK; + const float scale = cv->scales ? cv->scales[(size_t) layer] : 0.0f; + if (scale == 0.0f) return RAD_OK; + + n = g.n_embd; + hc = hc_streams; + on = mask; + h = stream; + dir = cv->dir + (size_t) layer * (size_t) n; + + op = rw(b, RAD_OP(b, "hc_project", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_INT("hc", hc), + RAD_F64("scale", (double) scale), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {h, mask}, {h}); + if (!op) { + fprintf(stderr, "radiance: %s: hc_project resolves to no kernel at n %lld, hc %lld -- " + "this rank cannot serve the control vector\n", + name, (long long) n, (long long) hc); + return RAD_E_INVAL; + } + return RAD_OK; + } + + /* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one + * call per piece, in the same place in the graph. */ + void step(RadCtx* c_, int64_t r0, int64_t rows) const { + if (!op) return; + RAD_ISSUE_N(c_, op, rows, + brow_slice(h, r0, rows, hc * n), + praw(dir, RAD_F32, n), + praw((const int32_t*) rad_buf_ptr(c_, on) + r0, RAD_I32, rows)); + } +}; + inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const { if (!op_write) return; if (takes_gather(T)) { diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index d30c4b58..002d48f9 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -109,6 +109,11 @@ struct Layer { QsaIndexer qsa; /* full-attention layers only; inert when the checkpoint has none */ GdnFP8 gdn; MoeFP8 mlp; + /* The control vector's projection, applied to the wide stream right after this layer's + * feed-forward write -- where llama.cpp's `build_cvec(res_hc, il)` sits in the `qwen4exp` + * graph. Inert (no op) when the deployment has no vector or this layer is outside its range + * (arch/common/rad_block_hc.h). */ + HcProject proj; }; struct Model { @@ -941,6 +946,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* The stream's initial value: hc identical copies of the embedding. */ RAD_ARCH_TRY(m.enter.declare(b, g, m.hccfg.hc, m.a_x.x, m.b_h)); + /* The control vector's per-token switch, when this deployment found one (HcProject). All zeros + * is the stock model, so a request that does not ask for the vector is unaffected. */ + const rad_buf proj_on = HcProject::declare_mask(b, nm.f("projection_on"), g, ctx->cvec); + /* ---- the layers. * * Declaration order is the buffer planner's liveness: a transient lives over [first @@ -1170,6 +1179,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c lay.mlp.gather_out_rows = lay.hc_ffn.gather_rows; lay.mlp.gather_out_rows6 = lay.hc_ffn.gather_rows6; } + + /* The control vector's projection for this layer, if the vector steers it. */ + RAD_ARCH_TRY(lay.proj.declare(b, nm.f("blk.%lld.proj", (long long) l), g, l, ctx->cvec, + proj_on, m.b_h, m.hccfg.hc)); } /* Each routed layer predicts the next one's experts at its router input (MoeFP8::xp_next). */ @@ -1541,6 +1554,8 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int for (int64_t p = 0; p < K; ++p) { if (p == K - 1) wait1(); l.hc_ffn.write(c, T, r0(p), rn(p)); + /* The projection of this piece, before the next layer reads it. */ + l.proj.step(c, r0(p), rn(p)); if (nx && !ple_next) nx->hc_mix.read(c, T, r0(p), rn(p)); } if (ple_next) { @@ -1584,6 +1599,8 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_ l.hc_ffn.read_pieces(c, T); l.mlp.step(c, batch); l.hc_ffn.write(c, T, 0, T); + /* The request's control vector, on the stream the write just finished. */ + l.proj.step(c, 0, T); dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x); } } From 66c6d7125445f3a51815d01a54df99fdf4734407 Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Tue, 20 Oct 2026 14:39:19 +0700 Subject: [PATCH 082/152] sched, mem: the per-request switch reaches the device, and the cache keeps the modes apart `projection_on_rows` expands each request's choice across its tokens once per step, into the int32 mask hc_project reads; rows outside every sequence are zeroed first, so the reused arena region can never carry a previous step's flag. The prefix cache keys a projected request's blocks on the vector itself, through the same extension point the runtime LoRA adapter uses: one content key spanning the whole sequence, pushed into `media_keys` beside the adapter's, so every block overlaps it. Blocks and linear-state checkpoints (whose keys are the same chained hash) therefore never cross modes; an unprojected request, or a deployment with no vector, adds no span and hashes exactly as before, and an adapter and a vector compose. --- core/engine.cpp | 4 ++-- core/sched/derive.cpp | 31 +++++++++++++++++++++++++++++++ core/sched/mem_iface.h | 29 ++++++++++++++++++++++++----- 3 files changed, 57 insertions(+), 7 deletions(-) diff --git a/core/engine.cpp b/core/engine.cpp index ba865d38..1d0019e2 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1476,9 +1476,9 @@ int Engine::serve(std::unique_ptr watch) { const uint64_t t0 = rad_mono_ns(); PrefixCache& pc = ranks_[0]->prefix; std::vector mk; - media_keys(req, &mk); + media_keys(req, &mk, cvec_salt_for(req.sp.use_control_vector)); const std::vector want = - pc.restorable_from(req.prompt, mk, cvec_salt_for(req.sp.use_control_vector)); + pc.restorable_from(req.prompt, mk); if (want.empty()) return; /* The whole chain in one restore. With 4-token blocks a long conversation is tens of * thousands of entries; batched, it is one launch per (group, layer) per staging batch diff --git a/core/sched/derive.cpp b/core/sched/derive.cpp index 2b7a6d97..9ce1b007 100644 --- a/core/sched/derive.cpp +++ b/core/sched/derive.cpp @@ -2,6 +2,8 @@ */ #include "derive.h" +#include "rad_core.h" + #include namespace rad { @@ -81,6 +83,32 @@ static int d_state_chunk_seq(const DeriveInput& in, int32_t* out, int64_t cap, i return chunk_walk(in, out, cap, n_out); } +/* ------------------------------------------------------- projection_on_rows */ +/* [n_tok] -- whether each token's residual stream takes the control vector this step. + * + * The switch itself is a per-request choice (SamplingParams::use_control_vector) and the step + * kernel reads one row's flag, so the mask is expanded here once per step from the plan rather + * than searched per layer: an architecture issues one projection op after every block's write, and + * a per-layer search over the sequence bounds would repeat on every one of them. + * + * All zeros is the ordinary model, byte for byte: the op skips a zero row without writing, so a + * request that did not ask for the vector computes what it computes with no vector loaded. */ +static int d_projection_on_rows(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) { + if (in.n_tok > cap) return RAD_E_FULL; + /* Zero first. The ranges below cover every row a step carries today, but the region is reused + * across steps and a row outside them would otherwise keep the previous step's flag -- which + * would project a request that did not ask for it. The fill is a memset of a few KiB. */ + std::memset(out, 0, (size_t) in.n_tok * sizeof(int32_t)); + for (int64_t i = 0; i < in.n_seq; ++i) { + const StepEntry& e = in.plan->e[(size_t) i]; + const int32_t on = (e.req && e.req->sp.use_control_vector) ? 1 : 0; + const int64_t b = in.cu_seqlens[i], end = in.cu_seqlens[i + 1]; + for (int64_t k = b; k < end && k < in.n_tok; ++k) out[k] = on; + } + *n_out = in.n_tok; + return RAD_OK; +} + /* ------------------------------------------------------------------ the table */ static const DeriveRow g_rows[] = { { "seq_start_index", d_seq_start_index, @@ -91,6 +119,9 @@ static const DeriveRow g_rows[] = { "[n_chunks+1] token indices bounding each linear-state chunk; never crosses a sequence" }, { "state_chunk_seq", d_state_chunk_seq, "[n_chunks] the sequence each chunk belongs to" }, + { "projection_on_rows", d_projection_on_rows, + "[n_tok] 1 where this token's request applies the loaded control vector, 0 for the stock " + "model" }, }; int derive_index(const char* name) { diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index caaa16be..40c3fc90 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -282,7 +282,8 @@ struct KVBinding final : IKVManager { /* Content keys for a request's media runs. Placeholder ids are identical for every picture, so * the prefix cache also hashes each run's item content key (core/mm, over the processed patches) * and segment: the same picture at the same place hits, two pictures never alias. */ -inline void media_keys(const Request& r, std::vector* out) { +inline void media_keys(const Request& r, std::vector* out, + uint64_t control_vector_salt = 0) { out->clear(); /* The runtime LoRA adapter is part of every block's key: KV written under an adapter is not * the base's. It enters the chain as one span over the whole sequence, keyed by the adapter's @@ -295,6 +296,18 @@ inline void media_keys(const Request& r, std::vector* out) { k.hash = (r.lora_uid * 0x9e3779b97f4a7c15ull) ^ 0x4c6f5241ull; /* "LoRA" */ out->push_back(k); } + /* A control vector is part of every block's key for the same reason: a projected step's hidden + * states are not the stock model's, so its KV is not the stock model's either. The vector's own + * identity rides in as one span over the whole sequence, so every block overlaps it, and a + * request that runs without the vector (or a deployment with none) adds no span and hashes + * exactly as it did. An adapter and a vector are independent spans and compose. */ + if (control_vector_salt != 0 && r.sp.use_control_vector) { + MMContentKey k; + k.tok_begin = 0; + k.tok_end = INT32_MAX; + k.hash = control_vector_salt ^ 0x43455643ull; /* "CVEC" */ + out->push_back(k); + } if (!r.media) return; const mm::PromptMedia& pm = *r.media; for (const mm::RopeLayout::Run& run : pm.rope.runs) { @@ -311,13 +324,19 @@ inline void media_keys(const Request& r, std::vector* out) { template struct PCBinding final : IPrefixCache { PC* m; + /* The control vector's identity (Engine::cvec_salt_for), or 0 with none loaded. A request that + * runs with it on keys its blocks and its linear-state snapshots under a chain that includes it, + * so its KV is never handed to a request that runs without it: the hidden states differ, and + * the cache stores hidden states' consequences. Per request, not per cache: two sequences of one + * step may differ. */ + uint64_t salt_id = 0; /* Scratch for a request's media keys, reused so a text request's lookup allocates nothing. */ mutable std::vector mm_; explicit PCBinding(PC* p) : m(p) {} CacheHit lookup(const Request& r, std::vector>* out, const HitCap* cap) const override { - media_keys(r, &mm_); + media_keys(r, &mm_, salt_id); /* r.id: the admission takes its conversation's snapshots over. */ return m->lookup(r.prompt, mm_, out, cap, r.id); } @@ -329,7 +348,7 @@ struct PCBinding final : IPrefixCache { } void begin_step() override { m->begin_step(); } void hold(const Request& r) override { - media_keys(r, &mm_); + media_keys(r, &mm_, salt_id); m->hold(r.id, r.prompt, mm_); } void release(const Request& r) override { m->release(r.id); } @@ -345,7 +364,7 @@ struct PCBinding final : IPrefixCache { toks.insert(toks.end(), r.output.begin(), r.output.end()); if (n_tokens > (int64_t)toks.size()) n_tokens = (int64_t)toks.size(); /* r.id is the session, the same id reserve_checkpoint keys its snapshots by. */ - media_keys(r, &mm_); + media_keys(r, &mm_, salt_id); return m->insert(r.id, toks, mm_, blocks, n_tokens, r.session_label); } /* Installed by the engine when the idle tiers are on: lands every pending host copy now and @@ -409,7 +428,7 @@ private: /* The chain reserve_checkpoint and commit_checkpoint both key on; shared so they cannot * drift apart. */ BlockHash prefix_hash(const Request& r, int64_t pos) const { - media_keys(r, &mm_); + media_keys(r, &mm_, salt_id); const int64_t bs = m->block_size(); BlockHash h{}; if (bs <= 0) return h; From 6f26cdb5f499d59e73725b91235ef291e869b97a Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Tue, 20 Oct 2026 14:39:20 +0700 Subject: [PATCH 083/152] server: a control_vector request field, its admin switch and the Model-view panel The field is per request, with the deployment's runtime default when absent, and a deployment with no vector refuses 'true' by name rather than serving the stock model. Strata's `experimental_speed_projection` is accepted as an alias. The dashboard's Model view carries a "Control vectors" panel with the switch for that default; GET/POST /admin/control-vector is its endpoint, behind the API key like every other route. The state is in /stats and /server_info. Nothing here reloads the model: the directions are uploaded once and each step carries a per-request mask. The panel stays visible when the page has no API key, with the reason, instead of disappearing -- a control that vanishes because the page has not signed in reads exactly like a build without the feature. --- core/server/dashboard.cpp | 129 +++++++++++++++++++++++++++++++++++++- core/server/oai.cpp | 12 ++++ core/server/oai.h | 5 ++ core/server/server.cpp | 26 ++++++++ core/server/server.h | 17 +++++ docs/GUIDE.md | 60 +++++++++++++++++- tests/server_test.cpp | 66 +++++++++++++++++++ 7 files changed, 312 insertions(+), 3 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index eb52ea51..7732e9cf 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -30,6 +30,47 @@ namespace server { * Derived rates are the page's job: they are counter differences over wall time, and only the * browser holds both ends of its poll interval. Computing them here would need per-client state. */ +/* ------------------------------------------------------------------ /admin/control-vector + * + * The control vector's runtime switch (core/cvec.h). Turning it on for the next + * request costs a boolean: the direction table was uploaded at startup and the per-request mask + * is a derived buffer the core fills every step, so there is nothing to rebuild and nothing to + * reload. The engine's own log records the load; this records the flip, because a deployment's + * answer to "was that text produced with the vector" should not depend on a browser's memory. + * + * GET reports the state (and is what the Model view renders); POST takes {"enabled": true|false} + * and answers with the same object. A deployment with no vector loaded answers 404 on both: it has + * no such feature, and its requests refuse `control_vector: true` by name. */ +HttpResponse Server::handle_control_vector(const HttpRequest& req) { + const bool have = deps_.control_vector.available && deps_.control_vector.available(); + if (!have) + return error_response(err_not_implemented( + "this deployment found no control vector for its model; there is nothing to switch"), + req.peer); + + if (req.method == "POST") { + json body; + try { + body = json::parse(req.body.empty() ? "{}" : req.body); + } catch (const std::exception& e) { + return error_response(err_bad("body", std::string("not JSON: ") + e.what()), req.peer); + } + const auto it = body.find("enabled"); + if (it == body.end() || !it->is_boolean()) + return error_response(err_bad("enabled", "a boolean is required"), req.peer); + const bool on = it->get(); + if (deps_.control_vector.set_default) deps_.control_vector.set_default(on); + RAD_INFO("control vector: default %s by an admin request%s", on ? "ON" : "OFF", + req.peer.empty() ? "" : (" from " + req.peer).c_str()); + } else if (req.method != "GET") { + return HttpResponse::json_body(405, err_bad("method", "GET or POST").dump()); + } + + metrics_.observe_http(200); + return HttpResponse::json_body( + 200, deps_.control_vector.json ? deps_.control_vector.json() : std::string("{}")); +} + /* ------------------------------------------------------------------ /sessions * * A separate route, not a /stats field: /stats is polled every second, while a stored session @@ -124,6 +165,16 @@ HttpResponse Server::handle_stats(const HttpRequest&) { json o; o["model"] = opt_.model_id; o["version"] = opt_.version; + /* The control vector (core/cvec.h), when this deployment has one: `available` is what a UI + * tests before offering the control, `default` what a request that names no choice runs. The + * dashboard's own control asks /admin/control-vector, which also reports this. */ + if (deps_.control_vector.json) { + try { + o["control_vector"] = json::parse(deps_.control_vector.json()); + } catch (const std::exception&) { + /* A malformed snapshot is not worth failing /stats over; the field is omitted. */ + } + } o["uptime_s"] = unix_now() - started_at_; /* Seconds this process took to come up, the cost of a restart; 0 before the server listens. */ o["startup_s"] = startup_s_; @@ -643,7 +694,8 @@ th + th, td + td { padding-left:14px; } it as a dot, because on a server with long-lived agent clients the second group is most of the table and none of it needs reading to understand the first. */ #view-sess .cell { height:auto; padding-bottom:12px; } -#view-sess .panel + .panel { margin-top:14px; } +/* Stacked panels in one view are 14px apart, the same gap the strip's own margin-bottom gives. */ +#view-sess .panel + .panel, #view-model .panel + .panel { margin-top:14px; } .stbl td, .stbl th { width:1%; } /* The two text columns take the slack and read left to right; the figures stay narrow. */ .stbl .l { text-align:left; width:auto; } @@ -1177,6 +1229,22 @@ nav button.on { color:var(--fg); background:var(--track); }
@@ -1472,6 +1472,116 @@ function setMetric(key, value, text) { spark(key, hist[key]); } +/* BEST / RECENT / NOW ON THE OTHER FOUR TILES, in the shape the decode step established. + * + * WHAT THESE ARE NOT: engine figures. The engine publishes a floor and a recent window for the + * decode step alone (step_ns_decode_best / _recent); for tok/s, requests in flight and acceptance + * it publishes ONE figure per poll and nothing older. So these three figures are page-side, and + * they mean: + * best / highest - the extreme this page session has seen AT THE CURRENT CONCURRENCY. + * Resets on reload, not on restart. + * recent - the mean over the last 15 s at that concurrency; 5 s on prefill, whose + * events are shorter than the window that would fit them. Shorter + * than the sparkline on purpose: + * a 60 s mean still read 31 tok/s fifty seconds after the lane went + * quiet, which is the lane being remembered rather than measured. + * now - the current value as a percentage of that extreme. + * "highest" rather than "best" on the two tiles where more is not better: a lane at its highest + * request count is busy, not good. The word carries a direction the number alone does not. + * + * PER-CONCURRENCY BUCKETS, the decode step's structure: a c8 rate read against the + * single-stream best reports the batch arriving as a level change -- the mistake that took + * the old drift line out. Every figure on the line describes the current concurrency, and + * past c1 the line says so ("@c8"). Requests in flight is the exception: its value IS the + * concurrency, so bucketing it by concurrency would pin "highest" to the current number + * forever -- it keeps one session-wide bucket. While the lane is idle nothing new is + * recorded and the line keeps the last active concurrency's figures: frozen, no now clause, + * which is what the Decode Step tile does at idle. + * + * NO ~99 CAP HERE, unlike the decode step. That cap exists because `now` there is a 500 ms poll + * mean measured against a 32-step window mean -- different instruments, so a fast stretch can read + * faster than the floor without being one. Here the extreme is computed FROM the same series as + * `now`, so exceeding it is arithmetically impossible and 100% is exact: you are at your best. + */ +/* RECENT'S OWN WINDOW, deliberately shorter than the sparkline's. HIST is 60 s and that is right + * for a picture -- a sparkline wants the whole minute to show shape. It is wrong for a number: + * measured over real traffic (two 5 s bursts inside a quiet minute), a 60 s mean still read 31.7 + * tok/s fifty seconds after the lane went quiet, and 30 s only brought that to 26.9. Fifteen + * seconds decays to zero within a quarter-minute of silence while still tracking the running mean + * mid-burst (52.8 against an actual 53.3). Ten and five overshoot -- 79 and 144 against that same + * 53 -- which is the current value wearing a different name, and the big number above already is + * that. `best`/`highest` stay full-session: an extreme wants every chance to be broken. + * Idle polls do not enter an active bucket -- the lane is not at that concurrency while it + * sleeps -- but they DO count in requests in flight's window, whose value is meaningful + * while nothing runs. + * + * PREFILL GETS ITS OWN WINDOW (RECENT_PREFILL, 5 s). Measured: small prompts prefill in 1.5-6 s + * above 100 tok/s; the operator's compaction reload -- the big one -- runs 7-15 s by his own + * count. A 15 s mean cannot report a 7 s event while it is running: it reaches barely half the + * peak by the event's end, then spends a quarter-minute averaging it down. Five seconds is + * shorter than the shortest event, so `recent` rides the prefill while it happens instead of + * diluting it. The engine's own figure is already a windowed rate (its help text: "over the + * scheduler's recent window"), so this window sits on top of the engine's smoothing -- it + * decides how long the page remembers, not how sharply the engine measures. */ +const RECENT = 30; /* 15 s at the 500 ms poll */ +const RECENT_PREFILL = 10; /* 5 s: shorter than the shortest prefill event (see above) */ +const extAt = {}, winAt = {}; +let lastActiveC = 0; +function noteSample(key, c, value, cap) { + if (value == null || !finite(value)) return; + const e = extAt[key] || (extAt[key] = {}); + const w = winAt[key] || (winAt[key] = {}); + if (!(c in e) || value > e[c]) e[c] = value; + const s = w[c] || (w[c] = []); + s.push(value); if (s.length > (cap || RECENT)) s.shift(); +} +function triple(key, c, label, fmt, showNow) { + /* RECENT IS A WINDOW MEAN, not a window maximum -- a maximum would sit equal to `best` on + * any steady lane, and two figures that always agree read as a broken instrument. */ + const e = extAt[key]; + if (!e || !(c in e)) return ""; + /* A bucket whose extreme is zero still has a story -- requests in flight has seen nothing yet -- + * so it renders. Only the `now` clause needs a nonzero extreme to divide by. */ + const s = winAt[key][c]; + let sum = 0; + for (const v of s) sum += v; + const recent = sum / s.length; + const now = s[s.length - 1]; + const tag = typeof c === "number" && c > 1 ? "@c" + c : ""; + let out = label + " " + fmt(e[c]) + " · recent " + fmt(recent); + /* THE SAME GUARD THE DECODE STEP USES: no `now` clause while nothing is running. A rate of + * zero is the lane being idle, not the lane being slow, and "now 0% of best" reads as a + * fault. The "@cN" tag rides the tail, exactly where the decode step puts it. */ + if (showNow !== false && e[c] > 0) out += " · now " + Math.round(100 * now / e[c]) + "% of " + label + tag; + return out; +} +/* WINDOWED ACCEPTANCE. The engine's figure is cumulative and exact -- tot_accepted_/tot_drafted_ + * over the life of the process -- so a best/recent/now line built on it would print the same + * number three times and call it a trend. The per-position counters the acceptance chart already + * reads are cumulative too, and the DIFFERENCE between two polls is exact acceptance over that + * interval, which is the only figure a detail line can move on. Each sample covers 10 s of + * drafting; `recent` averages the last RECENT samples AT THAT CONCURRENCY and `now` is + * the newest one -- different windows, free to disagree. + * The counters go backwards when the engine restarts; that poll resets the window rather than + * reporting a negative draft. */ +const ACC_WIN = 20; /* 10 s of drafting at the 500 ms poll */ +let accPrev = null; +const accDelta = []; +function accWindow(s) { + let reach = 0, hit = 0; + for (const p of (s.draft_positions || [])) { reach += p.reached || 0; hit += p.accepted || 0; } + if (accPrev === null || reach < accPrev.r || hit < accPrev.a) { + accPrev = { r: reach, a: hit }; accDelta.length = 0; return null; + } + const dr = reach - accPrev.r, da = hit - accPrev.a; + accPrev = { r: reach, a: hit }; + if (dr <= 0) return null; + accDelta.push({ r: dr, a: da }); if (accDelta.length > ACC_WIN) accDelta.shift(); + let R = 0, A = 0; + for (const d of accDelta) { R += d.r; A += d.a; } + return R > 0 ? A / R : null; +} + /* ---------------------------------------------------------------- the batch * @@ -1517,7 +1627,14 @@ function kvPanel(host, keys) { return out; } const totals = kvPanel($("totals"), ["Requests", "Steps"]); -const spec = kvPanel($("spec"), ["Drafter", "Depth"]); +/* "Average" is the LIFETIME MARGINAL ratio -- upstream's figure, unchanged, and the one this + * panel used to carry as its headline. A bullet now rather than the big number: see the note at + * the accept tile. It divides by every token DRAFTED, so it is not comparable with the live + * figure above it, which divides by the positions actually REACHED -- the two bases are worked + * through in the GUIDE, and both are derivable from the log. Deliberately not spelled out on the + * face of the panel: the distinction is an analysis-time concern, and a tooltip is invisible on + * the phone anyway. */ +const spec = kvPanel($("spec"), ["Drafter", "Depth", "Average"]); /* ---------------------------------------------------------------- meters */ /* `split` gives the track a second segment for a fill that is two things -- see setSplit. */ @@ -1809,6 +1926,17 @@ function update(s, dt) { setMetric("decode", s.decode_tps, tps(s.decode_tps)); setMetric("prefill", s.prefill_tps, tps(s.prefill_tps)); setMetric("flight", s.in_flight, String(s.in_flight)); + const busy = s.running > 0; + if (busy) { + lastActiveC = s.running; + noteSample("decode", s.running, s.decode_tps); + noteSample("prefill", s.running, s.prefill_tps, RECENT_PREFILL); + } + noteSample("flight", "*", s.in_flight); + const cNow = busy ? s.running : lastActiveC; + $("m-decodedet").textContent = triple("decode", cNow, "best", tps, busy); + $("m-prefilldet").textContent = triple("prefill", cNow, "best", tps, busy); + $("m-flightdet").textContent = triple("flight", "*", "highest", (v) => String(Math.round(v)), s.in_flight > 0); /* THE MERGED POOL, not the maximum over groups. The max is the right preemption signal and the * wrong headline: the drafter's own window group is sized one block-run per slot and therefore * sits at 100% for the whole life of the server, so a headline reading the max reads 100% on a @@ -1834,9 +1962,23 @@ function update(s, dt) { + cnt3(s.kv_tokens_used) + " tok" + (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "") : ""; - setMetric("accept", 100 * s.draft_accept, - s.draft_positions && s.draft_positions.length - ? pctn(s.draft_accept, 0) : DASH); + const aw = accWindow(s); + if (aw != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, aw); + /* THE HEADLINE IS THE LIVE WINDOW, not the cumulative ratio. The engine's figure is exact but + * cumulative, so on a process that has been up for hours it cannot move: 559 fresh drafts moved + * it one point against a 33,000-draft denominator, and it froze outright the moment the lane + * went quiet. Every other tile's big number is the current value, and feeding the cumulative one + * here also fed the sparkline a quantity that is flat by construction. + * Polls with no new drafts push NOTHING and the headline freezes with them: acceptance is + * UNDEFINED when nothing was drafted, so neither 0 (reads as failure) nor the last value (reads + * as stable) is the truth. A server with no draft head shows the dash -- there is no such figure + * to show. The lifetime ratio stays on /stats and /metrics; what the tile answers is "what is it + * accepting now". + * THE SPARKLINE'S SCALE DIFFERS from the other tiles: its samples are 10 s drafting windows, not + * 500 ms polls, so this box spans up to 120 windows of actual drafting rather than 60 s. */ + if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH); + else if (aw != null) setMetric("accept", 100 * aw, pctn(aw, 0)); + $("m-acceptdet").textContent = triple("accept", cNow, "highest", (v) => pct(v, 0), busy); M.flight.u.textContent = "/ " + s.queue_cap; const list = s.requests || []; @@ -1922,10 +2064,22 @@ function update(s, dt) { const perStep = sps > 0 && s.decode_tps > 0 ? s.decode_tps / sps / seqs : null; if (perStep != null) lastTps = perStep; $("tps_n").firstChild.nodeValue = lastTps == null ? DASH : sig3(lastTps); - $("acc_n").firstChild.nodeValue = pctn(s.draft_accept, 0); + /* ACCEPTED IS THE LIVE FIGURE, matching the tile above it. `aw` is the same pooled drafting + * window the tile's headline reads, computed earlier in this function -- one derivation, two + * readers, so the panel and the tile cannot disagree. + * DESIGN DECISION, 10-19, at the Operator's direction: this section shows the REAL-TIME + * accepted percentage and the lifetime average sits in the bullets below it. The reasoning is + * on the tile; the short form is that a cumulative ratio on a process that has been up for + * hours is a number that cannot move, and a headline that cannot move reads as a dead page. + * PINNED, NOT PRICED: the Operator may prefer the average back in the big seat, and the swap + * is these two lines. What must not happen is the average returning as the headline with no + * bullet left behind, because then the live figure is the thing nobody can see. + * Undefined when nothing was drafted -- freeze rather than print 0 or repaint the last value. */ + if (aw != null) $("acc_n").firstChild.nodeValue = pctn(aw, 0); $("specaside").textContent = "depth " + dp.length; spec["Drafter"].textContent = drafterName; spec["Depth"].textContent = dp.length; + spec["Average"].textContent = pctn(s.draft_accept, 0) + "%"; } /* ---- devices, in the same panel as the cache meter: they are one question. */ diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index 9fdcd15f..76c55085 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -140,6 +140,10 @@ void Metrics::sample(const SchedMetrics& m) { g_prefill_tps_.set(m.prefill_tps); g_decode_tps_.set(m.decode_tps); g_draft_accept_.set(m.draft_acceptance); + /* Nanoseconds in the scheduler, seconds on the wire: the base unit Prometheus expects, and + * what radiance:engine_step_seconds_* already use. */ + g_step_best_.set((double)m.step_ns_decode_best / 1e9); + g_step_recent_.set((double)m.step_ns_decode_recent / 1e9); const int seen = std::max(0, std::min(m.draft_depth_seen, (int)MAX_DRAFT_POS)); for (int j = 0; j < seen; ++j) { const int64_t r = m.draft_pos_reached[j]; @@ -324,6 +328,23 @@ std::string Metrics::render() const { "Prefill throughput over the scheduler's recent window.", L, g_prefill_tps_.get()); w.gauge("radiance:decode_tokens_per_second", "Decode throughput over the scheduler's recent window.", L, g_decode_tps_.get()); + /* THE DECODE FLOOR, the two figures the dashboard's Decode Step tile shows. They were on + * /stats only, and /stats is documented as not a stable API -- so the one figure worth + * comparing across restarts was reachable only from the surface automation is told not to + * use. Omitted until measured: a floor of 0 seconds is not an unmeasured floor, it is an + * infinitely fast one, and a scrape would plot it as a record. Both reset on restart, so a + * freshly started server simply has no floor to report yet. */ + if (g_step_best_.get() > 0) + w.gauge("radiance:decode_step_seconds_best", + "Fastest single-sequence decode step window this process has run, in seconds " + "per token. A mean over 32 consecutive single-stream steps, not a stopwatch " + "reading. Resets on restart.", L, g_step_best_.get()); + if (g_step_recent_.get() > 0) + w.gauge("radiance:decode_step_seconds_recent", + "Most recent single-sequence decode step window, in seconds per token. The gap " + "to _best tracks what else the machine is doing, not wear; see docs/GUIDE.md. " + "Freezes while the lane is idle, because no window is completing.", + L, g_step_recent_.get()); w.counter("radiance:engine_steps_total", "Scheduler steps executed. One forward pass of the model, plus whatever draft " "rounds followed it; with speculation a step emits more than one token.", diff --git a/core/server/metrics.h b/core/server/metrics.h index 9387e59b..11ba72c4 100644 --- a/core/server/metrics.h +++ b/core/server/metrics.h @@ -113,6 +113,10 @@ private: Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_; Gauge g_kv_max_tokens_, g_kv_max_bytes_; Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_; + /* The decode floor, in seconds: the fastest single-sequence window this process has run, + * and the most recent one. Both stay 0 until a window of 32 single-stream steps completes, + * and both reset on restart -- the render omits them rather than expose an unmeasured 0. */ + Gauge g_step_best_, g_step_recent_; Gauge queue_depth_; /* Per-position conditional draft acceptance (see render() and core/sched/draft.h). */ enum { MAX_DRAFT_POS = 64 }; diff --git a/scripts/README.md b/scripts/README.md index 591a6198..ab3429a8 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -38,6 +38,7 @@ and `agentreplay.py` need `python3`. Scripts find each other through `$(dirname | `mctrace.sh` | A MiniCPM5-2B decode trace under `rocprofv3`, on its own server, formatted for `libr4d/isa/tsum.sh`, mainly for its `blocks` column. | | `ident.sh` | Run-to-run reproducibility at a fixed configuration: one hash per (temperature, question), to compare against another run of the same configuration. A speculative run need not match a non-speculative one byte for byte (the split-K count is chosen from M, so reduction orders differ and a near-tie can flip late in a long answer), but a divergence within the first sentence or two is a defect. | | `cardclock.py` | What holds each card's clock under sustained load, and which card a tensor-parallel step waits for (the slowest rank ends the step). Reads every AMD card's `gpu_metrics` table ten times a second and counts a throttler bit only when the clock is lower while it is set (some firmware keeps a bit on at idle). Shows the engine's step counters per window, so a slow window is attributed to slower steps, fewer tokens per step or host time between steps. Drives its own greedy load, or with `--watch` only samples a server under real traffic; `--compare` shows two saved runs side by side. Read-only on the cards. | +| `statsdump.py` | Record `/stats` to JSONL so the dashboard's figures can be measured over time instead of only watched: one object per poll, appended, `python3` only. Records the engine's snapshot verbatim plus the poll's own time and the gap since the last good poll -- it derives nothing, because the page's best/recent/now lines are computed from this same stream and a second copy of that arithmetic is a second thing that can drift. A failed poll leaves no row (a gap in the file is the honest record of a gap in the data) and an empty run exits non-zero, so a dead server cannot be mistaken for a quiet hour. The decode floor resets with the process: `step_ns_decode_best` improving across a restart is a new process finding its own best moment, not a faster machine. | | `oracle.sh` | Every op compared against libref on the operands the model issued, which rad-kbench cannot do: its operands are its own (dense, rank 2), while the engine's are arena slices and weights loaded from a file. Starts its own server on :8302. Read it for `MISMATCH` lines, and for `NOT CHECKED` lines naming rows whose weight layout has no published inverse and so cannot be compared. | ## Regression checks against a live server diff --git a/scripts/statsdump.py b/scripts/statsdump.py new file mode 100755 index 00000000..bb5db89c --- /dev/null +++ b/scripts/statsdump.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# statsdump.py -- record /stats to a JSONL file, so the dashboard's figures can be measured over +# time instead of only watched. +# +# The dashboard answers "what is this process doing right now". Answering "what was it doing at +# 3 a.m., and is its best step time worse than last week's" needs the same numbers kept. /stats +# already carries them -- the decode floor, throughput per window, cache behaviour, the draft +# counters -- and /metrics carries most of them for a Prometheus scrape. This is the third option, +# for anyone who does not run a scraper: one JSON object per poll, appended, no dependencies beyond +# python3. +# +# scripts/statsdump.py [--port 8800] [--every 1] [--seconds 3600] [--out stats.jsonl] +# scripts/statsdump.py --url http://host:8800 --every 2 --out week.jsonl +# RADIANCE_API_KEY=... scripts/statsdump.py --port 8800 +# +# WHAT IS RECORDED: the engine's own snapshot, verbatim, plus `t` (the poll's own unix time) and +# `dt_s` (seconds since the previous successful poll). Nothing is derived. The page's best/recent/ +# now lines are computed in the browser from this same stream, and recomputing them here would put +# a second copy of that arithmetic where it could drift from the first -- so the analysis step +# derives them, from data that cannot disagree with the engine. +# +# Restarts are visible in the rows themselves: `uptime_s` falls and `startup_s` is the cost of the +# restart that just happened. The decode floor resets with the process, so `step_ns_decode_best` +# improving across a restart is a new process finding its own best moment, not a faster machine -- +# compare `best` across restarts only against a known-good value for the same hardware. +# +# A poll that fails leaves NO row: a gap in the file is the honest record of a gap in the data, and +# a fabricated row would be a measurement. Consecutive failures are reported on stderr as they +# happen, and the exit summary states how many polls were lost, so an empty file cannot be mistaken +# for a quiet hour. +import argparse, json, os, sys, time, urllib.error, urllib.request + +def main(): + ap = argparse.ArgumentParser(add_help=True) + ap.add_argument("--port", type=int, default=8800) + ap.add_argument("--url", default=None, help="full base URL; overrides --port") + ap.add_argument("--every", type=float, default=1.0, help="seconds between polls") + ap.add_argument("--seconds", type=float, default=0.0, help="stop after this long; 0 = run until interrupted") + ap.add_argument("--out", default="stats.jsonl") + ap.add_argument("--api-key", default=os.environ.get("RADIANCE_API_KEY"), + help="or set RADIANCE_API_KEY; the key is never echoed") + a = ap.parse_args() + + base = (a.url or "http://127.0.0.1:%d" % a.port).rstrip("/") + hdr = {"Authorization": "Bearer " + a.api_key} if a.api_key else {} + deadline = time.time() + a.seconds if a.seconds > 0 else None + + # Append, never truncate: a file that already holds last week's data is worth more than a clean + # start, and the rows carry their own timestamps. + out = open(a.out, "a") + prev, ok, lost, streak = None, 0, 0, 0 + sys.stderr.write("statsdump: %s/stats every %.1fs -> %s\n" % (base, a.every, a.out)) + try: + while True: + t0 = time.time() + try: + req = urllib.request.Request(base + "/stats", headers=hdr) + with urllib.request.urlopen(req, timeout=max(5.0, 4 * a.every)) as r: + row = json.loads(r.read().decode()) + except (urllib.error.URLError, OSError, ValueError) as e: + lost += 1; streak += 1 + # Report the first failure and then every tenth: one bad hour should be visible + # without the file's own signal being buried in identical lines. + if streak == 1 or streak % 10 == 0: + sys.stderr.write("statsdump: poll failed (%s), streak %d, %d lost\n" + % (type(e).__name__, streak, lost)) + else: + streak = 0 + row["t"] = t0 + row["dt_s"] = round(t0 - prev, 3) if prev is not None else 0.0 + prev = t0 + out.write(json.dumps(row, separators=(",", ":")) + "\n") + out.flush() # a killed poller must not lose the polls it did get + ok += 1 + if deadline is not None and time.time() >= deadline: + break + # Sleep from the poll's START, so a slow engine does not walk the schedule later. + left = a.every - (time.time() - t0) + if left > 0: + time.sleep(left) + except KeyboardInterrupt: + sys.stderr.write("statsdump: interrupted\n") + finally: + out.close() + sys.stderr.write("statsdump: %d rows written, %d polls lost, %s\n" % (ok, lost, a.out)) + # An empty file is a failure, not a quiet run: say so with the exit status, not only in prose. + return 1 if ok == 0 else 0 + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 9d9ac5bb..0c6cf36a 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -2284,6 +2284,12 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) { CHECK_NEAR(find_one("radiance:draft_acceptance_ratio{"), 0.61, 1e-9); CHECK_NEAR(find_one("vllm:generation_tokens_total{"), 5.0, 1e-9); + /* An unmeasured decode floor is ABSENT, not 0: a floor of 0 seconds per token is an + * infinitely fast one, and a scrape would plot it as a record. This fixture never completes a + * window of 32 single-stream steps, so neither series may appear. */ + CHECK(r.body.find("radiance:decode_step_seconds_best") == std::string::npos); + CHECK(r.body.find("radiance:decode_step_seconds_recent") == std::string::npos); + /* Every sample carries the model_name label vLLM's dashboards group by. */ for (auto& kv : d.samples) CHECK(kv.first.find("model_name=\"test-model\"") != std::string::npos); @@ -2306,6 +2312,48 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) { CHECK(r.body.find("le=\"2560\"") != std::string::npos); } +/* The decode floor reaches /metrics, in seconds. The scheduler keeps nanoseconds and the page + * divides for display; the wire uses the base unit Prometheus expects, the same choice + * radiance:engine_step_seconds_* already makes. */ +TEST(metrics_carries_the_decode_floor_in_seconds) { + Fixture f; + f.sched.m.step_ns_decode_best = 14708911; /* 14.71 ms/token: a measured floor */ + f.sched.m.step_ns_decode_recent = 16428860; /* 16.43 ms/token: the recent window */ + + HttpResponse r = f.get("/metrics"); + CHECK_EQ(r.status, 200); + PromDoc d = parse_prom(r.body); + CHECK_EQ((int)d.errors.size(), 0); + CHECK_EQ(d.type["radiance:decode_step_seconds_best"], std::string("gauge")); + CHECK_EQ(d.type["radiance:decode_step_seconds_recent"], std::string("gauge")); + + auto find_one = [&](const std::string& prefix) -> double { + for (auto& kv : d.samples) + if (kv.first.rfind(prefix, 0) == 0) return kv.second; + return -12345.0; + }; + CHECK_NEAR(find_one("radiance:decode_step_seconds_best{"), 0.014708911, 1e-12); + CHECK_NEAR(find_one("radiance:decode_step_seconds_recent{"), 0.016428860, 1e-12); + + /* A floor is a duration, so it must survive the number formatter: 0.0147 s rendered as an + * integer would read as infinitely fast. Checked on a prefix rather than the whole literal + * because num() prints 17 significant digits and the last ones are the double's own noise. */ + CHECK(r.body.find("radiance:decode_step_seconds_best{model_name=\"test-model\",engine=\"0\"} 0.01470891") + != std::string::npos); +} + +/* Half a window: a floor exists but the recent window has not completed since. Each series is + * gated on its own value, so one may appear while the other is absent. */ +TEST(metrics_omits_only_the_floor_half_that_is_unmeasured) { + Fixture f; + f.sched.m.step_ns_decode_best = 15000000; + f.sched.m.step_ns_decode_recent = 0; + + HttpResponse r = f.get("/metrics"); + CHECK(r.body.find("radiance:decode_step_seconds_best{") != std::string::npos); + CHECK(r.body.find("radiance:decode_step_seconds_recent") == std::string::npos); +} + /* The scheduler's totals are cumulative, and a scrape turns them into counter increments by adding * the difference from the counter's current value. Concurrent scrapes must still count each total * once: however many run, the counter ends at the total. */ From ddb8aa91275c20995bf09bcc3ca8dee5f703f4d1 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 01:05:15 +0000 Subject: [PATCH 099/152] dashboard: acceptance tile recent/now are pooled ratios of sums Math audit before the production roll (op request): triple()'s recent averaged per-poll ratios, but polls carry unequal draft counts, so quiet polls weighed as much as 500-draft polls. Live c8 replica measured the skew: avg-of-ratios 65.7% vs pooled 54.7% -- 11 points, growing with burstiness. The tile now keeps a per-concurrency ring of delta pairs and reports sum(accepted)/sum(reached) for recent and now; highest stays the full-session extreme. Speculation panel headline unchanged (it is the newest window ratio, which is a per-poll quantity by definition). Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 42 ++++++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index f98393e6..a2bce9bb 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1555,6 +1555,23 @@ function triple(key, c, label, fmt, showNow) { if (showNow !== false && e[c] > 0) out += " · now " + Math.round(100 * now / e[c]) + "% of " + label + tag; return out; } +/* The acceptance tile's detail line: highest stays the full-session extreme of window ratios + * (an extreme is an extreme), but recent and now are POOLED ratios of sums (see above). */ +function acceptTriple(c, showNow) { + const e = extAt["accept"]; + const p = accPool[c]; + if (!e || !(c in e) || !p || !p.length) return ""; + let R = 0, A = 0; + for (const d of p) { R += d.r; A += d.a; } + if (R <= 0) return ""; + const last = p[p.length - 1]; + const tag = typeof c === "number" && c > 1 ? "@c" + c : ""; + let out = "highest " + pct(e[c], 0) + " \u00b7 recent " + pct(A / R, 0); + if (showNow !== false && e[c] > 0 && last.r > 0) + out += " \u00b7 now " + Math.round(100 * (last.a / last.r) / e[c]) + "% of highest" + tag; + return out; +} + /* WINDOWED ACCEPTANCE. The engine's figure is cumulative and exact -- tot_accepted_/tot_drafted_ * over the life of the process -- so a best/recent/now line built on it would print the same * number three times and call it a trend. The per-position counters the acceptance chart already @@ -1565,6 +1582,7 @@ function triple(key, c, label, fmt, showNow) { * The counters go backwards when the engine restarts; that poll resets the window rather than * reporting a negative draft. */ const ACC_WIN = 20; /* 10 s of drafting at the 500 ms poll */ +const accPool = {}; /* per concurrency: ring of {dr, da} for the pooled tile window */ let accPrev = null; const accDelta = []; function accWindow(s) { @@ -1577,9 +1595,7 @@ function accWindow(s) { accPrev = { r: reach, a: hit }; if (dr <= 0) return null; accDelta.push({ r: dr, a: da }); if (accDelta.length > ACC_WIN) accDelta.shift(); - let R = 0, A = 0; - for (const d of accDelta) { R += d.r; A += d.a; } - return R > 0 ? A / R : null; + return { ratio: dr > 0 ? da / dr : null, dr: dr, da: da }; } @@ -1963,7 +1979,19 @@ function update(s, dt) { + (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "") : ""; const aw = accWindow(s); - if (aw != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, aw); + const awR = aw ? aw.ratio : null; + if (awR != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, awR); + /* POOLED ACCEPTANCE WINDOW (2026-10-20, math audit before the production roll). + * triple()'s `recent` averages the per-poll RATIOS; polls carry unequal draft counts, so a + * quiet poll and a 500-draft poll would weigh the same -- a mean of ratios, not a ratio of + * sums. Measured on a live c8 burst: avg-of-ratios 65.7% vs pooled 54.7%, a 11-point skew + * that grows with burstiness. The honest window figure is sum(accepted)/sum(reached) over + * the same span, so the tile keeps its own ring of delta pairs per concurrency. */ + if (aw != null && aw.dr > 0) { + const c = s.running > 0 ? s.running : lastActiveC; + const p = accPool[c] || (accPool[c] = []); + p.push(aw); if (p.length > RECENT) p.shift(); + } /* THE HEADLINE IS THE LIVE WINDOW, not the cumulative ratio. The engine's figure is exact but * cumulative, so on a process that has been up for hours it cannot move: 559 fresh drafts moved * it one point against a 33,000-draft denominator, and it froze outright the moment the lane @@ -1977,8 +2005,8 @@ function update(s, dt) { * THE SPARKLINE'S SCALE DIFFERS from the other tiles: its samples are 10 s drafting windows, not * 500 ms polls, so this box spans up to 120 windows of actual drafting rather than 60 s. */ if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH); - else if (aw != null) setMetric("accept", 100 * aw, pctn(aw, 0)); - $("m-acceptdet").textContent = triple("accept", cNow, "highest", (v) => pct(v, 0), busy); + else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0)); + $("m-acceptdet").textContent = acceptTriple(cNow, busy); M.flight.u.textContent = "/ " + s.queue_cap; const list = s.requests || []; @@ -2075,7 +2103,7 @@ function update(s, dt) { * is these two lines. What must not happen is the average returning as the headline with no * bullet left behind, because then the live figure is the thing nobody can see. * Undefined when nothing was drafted -- freeze rather than print 0 or repaint the last value. */ - if (aw != null) $("acc_n").firstChild.nodeValue = pctn(aw, 0); + if (awR != null) $("acc_n").firstChild.nodeValue = pctn(awR, 0); $("specaside").textContent = "depth " + dp.length; spec["Drafter"].textContent = drafterName; spec["Depth"].textContent = dp.length; From 2dde3131215738d0edb11eebdd0bd0ea37e2883e Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 01:18:27 +0000 Subject: [PATCH 100/152] dashboard: rename the acceptance ring off 'p' -- dashboard_test's contract scanner Full-suite build of the production branch FAILED 1 of 96: dashboard_test every_field_the_page_reads_is_one_the_routes_emit reported the page reads draft_positions[].length/.push/.shift. Cause: that test extracts every 'p.' inside update() and asserts each is a field /stats emits -- p is the page's conventional name for a draft_positions element. My pooled ring buffer reused p for an array, so its own methods were read as engine fields. No logic error; a naming collision with the test's contract. Renamed to 'ring' in update() and acceptTriple(). The gate worked exactly as designed: rc=8, flip aborted, lane stayed on stock. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index a2bce9bb..e928eb76 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1559,12 +1559,12 @@ function triple(key, c, label, fmt, showNow) { * (an extreme is an extreme), but recent and now are POOLED ratios of sums (see above). */ function acceptTriple(c, showNow) { const e = extAt["accept"]; - const p = accPool[c]; - if (!e || !(c in e) || !p || !p.length) return ""; + const ring = accPool[c]; + if (!e || !(c in e) || !ring || !ring.length) return ""; let R = 0, A = 0; - for (const d of p) { R += d.r; A += d.a; } + for (const d of ring) { R += d.r; A += d.a; } if (R <= 0) return ""; - const last = p[p.length - 1]; + const last = ring[ring.length - 1]; const tag = typeof c === "number" && c > 1 ? "@c" + c : ""; let out = "highest " + pct(e[c], 0) + " \u00b7 recent " + pct(A / R, 0); if (showNow !== false && e[c] > 0 && last.r > 0) @@ -1989,8 +1989,8 @@ function update(s, dt) { * the same span, so the tile keeps its own ring of delta pairs per concurrency. */ if (aw != null && aw.dr > 0) { const c = s.running > 0 ? s.running : lastActiveC; - const p = accPool[c] || (accPool[c] = []); - p.push(aw); if (p.length > RECENT) p.shift(); + const ring = accPool[c] || (accPool[c] = []); + ring.push(aw); if (ring.length > RECENT) ring.shift(); } /* THE HEADLINE IS THE LIVE WINDOW, not the cumulative ratio. The engine's figure is exact but * cumulative, so on a process that has been up for hours it cannot move: 559 fresh drafts moved From 7c18d8d1bb05e4c5d66166ba5e48b4b014aa6cdf Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 01:31:17 +0000 Subject: [PATCH 101/152] dashboard: close the restart gap in the acceptance tile (Turnstone audit) Auditor Qwen (27B, :8788) returned SHIP-WITH-FIXES; this is gating fix 1. accPool was push-only, so after an engine restart up to RECENT=30 delta pairs from the dead process pooled with the new one's and biased 'recent' -- largest exactly when a restart is likeliest to change acceptance. Restart detection now also watches uptime_s going backwards, which catches the case backward counters cannot: a backgrounded tab whose accPrev froze while the new process drafted past the old one's lifetime total, giving a positive bogus delta. On either signal every pooled ring is cleared and the accept headline + Speculation figure dash for that poll instead of freezing a dead process's ratio. Also drops the dead accDelta/ACC_WIN left by the pre-pool design and corrects the stale '10 s' comment. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index e928eb76..cd0f2a0f 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1576,26 +1576,35 @@ function acceptTriple(c, showNow) { * over the life of the process -- so a best/recent/now line built on it would print the same * number three times and call it a trend. The per-position counters the acceptance chart already * reads are cumulative too, and the DIFFERENCE between two polls is exact acceptance over that - * interval, which is the only figure a detail line can move on. Each sample covers 10 s of - * drafting; `recent` averages the last RECENT samples AT THAT CONCURRENCY and `now` is - * the newest one -- different windows, free to disagree. + * interval, which is the only figure a detail line can move on. Each sample is one poll's delta + * (~500 ms, and only when it drafted); `recent` POOLS the last RECENT such deltas AT THAT + * CONCURRENCY and `now` is the newest one -- different windows, free to disagree. * The counters go backwards when the engine restarts; that poll resets the window rather than * reporting a negative draft. */ -const ACC_WIN = 20; /* 10 s of drafting at the 500 ms poll */ const accPool = {}; /* per concurrency: ring of {dr, da} for the pooled tile window */ -let accPrev = null; -const accDelta = []; +let accPrev = null, accUp = -1, accRestart = false; function accWindow(s) { let reach = 0, hit = 0; for (const p of (s.draft_positions || [])) { reach += p.reached || 0; hit += p.accepted || 0; } - if (accPrev === null || reach < accPrev.r || hit < accPrev.a) { - accPrev = { r: reach, a: hit }; accDelta.length = 0; return null; + /* RESTART DETECTION (2026-10-20, Turnstone audit). Counters going BACKWARDS catches a restart + * the page was watching. uptime_s going backwards catches the one it missed: a backgrounded + * tab whose accPrev froze while a new process drafted past the old process's lifetime total, + * where the delta is positive and the first guard never fires. Either clears every pooled + * ring -- a pre-restart pair must not pool with a post-restart one -- and asks update() to + * dash the headline, so a dead process's ratio never masquerades as the new one's. */ + const up = s.uptime_s; + const restart = accPrev !== null && (reach < accPrev.r || hit < accPrev.a || + (typeof up === "number" && up < accUp)); + if (typeof up === "number") accUp = up; + if (accPrev === null || restart) { + accPrev = { r: reach, a: hit }; + if (restart) { for (const k in accPool) delete accPool[k]; accRestart = true; } + return null; } const dr = reach - accPrev.r, da = hit - accPrev.a; accPrev = { r: reach, a: hit }; if (dr <= 0) return null; - accDelta.push({ r: dr, a: da }); if (accDelta.length > ACC_WIN) accDelta.shift(); - return { ratio: dr > 0 ? da / dr : null, dr: dr, da: da }; + return { ratio: da / dr, dr: dr, da: da }; } @@ -1980,6 +1989,7 @@ function update(s, dt) { : ""; const aw = accWindow(s); const awR = aw ? aw.ratio : null; + const restarted = accRestart; accRestart = false; if (awR != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, awR); /* POOLED ACCEPTANCE WINDOW (2026-10-20, math audit before the production roll). * triple()'s `recent` averages the per-poll RATIOS; polls carry unequal draft counts, so a @@ -2005,6 +2015,7 @@ function update(s, dt) { * THE SPARKLINE'S SCALE DIFFERS from the other tiles: its samples are 10 s drafting windows, not * 500 ms polls, so this box spans up to 120 windows of actual drafting rather than 60 s. */ if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH); + else if (restarted) setMetric("accept", null, DASH); else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0)); $("m-acceptdet").textContent = acceptTriple(cNow, busy); M.flight.u.textContent = "/ " + s.queue_cap; @@ -2103,7 +2114,8 @@ function update(s, dt) { * is these two lines. What must not happen is the average returning as the headline with no * bullet left behind, because then the live figure is the thing nobody can see. * Undefined when nothing was drafted -- freeze rather than print 0 or repaint the last value. */ - if (awR != null) $("acc_n").firstChild.nodeValue = pctn(awR, 0); + if (restarted) $("acc_n").firstChild.nodeValue = "\u2013"; + else if (awR != null) $("acc_n").firstChild.nodeValue = pctn(awR, 0); $("specaside").textContent = "depth " + dp.length; spec["Drafter"].textContent = drafterName; spec["Depth"].textContent = dp.length; From 77f91a0240587abc794b205395fdc08e87cf8ff9 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 02:11:37 +0000 Subject: [PATCH 102/152] dashboard: fix the pooled ring's property names -- recent/now were NaN, never rendered Two judge slices (Tasmania 27B, :8101) independently found what the auditor's pass at 1505ef2 missed: accWindow pushes {ratio, dr, da} but acceptTriple read d.r/d.a/last.r/last.a -- accPrev's names, a different object. Every pooled sum was undefined, so the acceptance detail line was frozen at 'highest X% - recent -' in the PRODUCTION page since 1505ef2. The headline was unaffected, which is why it looked alive. Fixed to d.dr/d.da/last.dr/last.da. Also from the judges: the Speculation 'Average' bullet printed 0% for an undefined lifetime marginal (no drafts yet), breaking the panel's own rule that 0 reads as failure -- now a dash. The comment above it cited a 'GUIDE' that does not exist; it now cites the README section, which is re-landed here (dropped in the rebase onto v1.9.0) with the worked example corrected: 56/75/77 implies 43.4% marginal, not the 44% previously claimed. New test the_pooled_acceptance_ring_reads_the_names_accWindow_writes holds both sides of the ring contract to the same names -- it fails on the exact bug above, which no C++ test could see because the page JS is never executed here. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- README.md | 21 +++++++++++++++++++++ core/server/dashboard.cpp | 12 +++++++----- tests/dashboard_test.cpp | 31 +++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5e99c450..9ca9d2e1 100644 --- a/README.md +++ b/README.md @@ -291,6 +291,27 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o `CMakePresets.json` names the same runs (`ctest --preset fast`, `host`, `gpu`, `full`, `asan`), and [`docs/GUIDE.md`](docs/GUIDE.md) §1.3 describes the tiers and the test binaries' options. +## Draft acceptance + +Speculative decoding drafts up to `--num-speculative-tokens` tokens a step; the target model +verifies them in one pass, and a draft survives only if it matches what the target would have +produced. A position is verified only when every earlier position survived, so the same events +admit two ratios, and they differ only in the denominator: + +- **Conditional** -- accepted / *reached*: of the drafts actually verified at a position, how + many passed. The dashboard's live "accepted now" figure and the per-position bars are + conditional. Always the higher number, and it moves with the workload. +- **Marginal** -- accepted / *drafted*: of everything the drafter proposed, how much survived. + The engine's `draft_accept` (/stats, and `radiance:draft_acceptance_ratio` on /metrics) is + marginal, cumulative over the life of the process. Lower by construction, and slow to move. + +They cannot agree, and neither is the other one broken. At depth 3 a step drafts three tokens +but reaches position 3 only when 1 and 2 both passed, so marginal is roughly the product of the +conditionals: bars reading 56/75/77% give (0.56 + 0.56x0.75 + 0.56x0.75x0.77) / 3 = 43%. A live +63% beside a lifetime 43% is one lane, two questions. Quote the conditional when asking "how +good is the drafter right now"; quote the marginal when asking "what fraction of draft work +became text." Never compare the two across that boundary. + ## Documentation | | | diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index cd0f2a0f..5b71bae9 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1562,13 +1562,13 @@ function acceptTriple(c, showNow) { const ring = accPool[c]; if (!e || !(c in e) || !ring || !ring.length) return ""; let R = 0, A = 0; - for (const d of ring) { R += d.r; A += d.a; } + for (const d of ring) { R += d.dr; A += d.da; } if (R <= 0) return ""; const last = ring[ring.length - 1]; const tag = typeof c === "number" && c > 1 ? "@c" + c : ""; let out = "highest " + pct(e[c], 0) + " \u00b7 recent " + pct(A / R, 0); - if (showNow !== false && e[c] > 0 && last.r > 0) - out += " \u00b7 now " + Math.round(100 * (last.a / last.r) / e[c]) + "% of highest" + tag; + if (showNow !== false && e[c] > 0 && last.dr > 0) + out += " \u00b7 now " + Math.round(100 * (last.da / last.dr) / e[c]) + "% of highest" + tag; return out; } @@ -1656,7 +1656,7 @@ const totals = kvPanel($("totals"), ["Requests", "Steps"]); * panel used to carry as its headline. A bullet now rather than the big number: see the note at * the accept tile. It divides by every token DRAFTED, so it is not comparable with the live * figure above it, which divides by the positions actually REACHED -- the two bases are worked - * through in the GUIDE, and both are derivable from the log. Deliberately not spelled out on the + * through in README.md, section "Draft acceptance", and both are derivable from the log. Deliberately not spelled out on the * face of the panel: the distinction is an analysis-time concern, and a tooltip is invisible on * the phone anyway. */ const spec = kvPanel($("spec"), ["Drafter", "Depth", "Average"]); @@ -2119,7 +2119,9 @@ function update(s, dt) { $("specaside").textContent = "depth " + dp.length; spec["Drafter"].textContent = drafterName; spec["Depth"].textContent = dp.length; - spec["Average"].textContent = pctn(s.draft_accept, 0) + "%"; + /* Undefined when nothing has been drafted yet -- dash, not 0%. The panel's own rule is + * that 0 reads as failure, and this bullet was the one writer breaking it. */ + spec["Average"].textContent = s.draft_accept > 0 ? pct(s.draft_accept, 0) : DASH; } /* ---- devices, in the same panel as the cache meter: they are one question. */ diff --git a/tests/dashboard_test.cpp b/tests/dashboard_test.cpp index 8c4a1564..86c41002 100644 --- a/tests/dashboard_test.cpp +++ b/tests/dashboard_test.cpp @@ -271,6 +271,37 @@ TEST(stats_reports_how_long_bringup_took_once_the_server_listens) { CHECK_EQ(d.get("/stats").value("startup_s", (int64_t)-1), (int64_t)47); } +/* The pooled ring's element shape is a contract between two functions in the page, and no + * browser runs here to notice when they disagree. accWindow pushes {ratio, dr, da}; acceptTriple + * iterates the ring as `d` and reads `last`. When a rename left acceptTriple reading accPrev's + * {r, a} instead, the pooled figures became NaN and the detail line froze at "recent -" while + * every C++ test stayed green (Turnstone judge slices 08 and 11, 2026-10-20). So: scan the page + * text and hold the two sides to the same names. */ +TEST(the_pooled_acceptance_ring_reads_the_names_accWindow_writes) { + Dash d(false); + const std::string p = d.srv->router().call("GET", "/").body; + const std::string aw = function_body(p, "function accWindow("); + const std::string at = function_body(p, "function acceptTriple("); + REQUIRE(!aw.empty() && !at.empty()); + /* what goes INTO the ring */ + CHECK(aw.find("dr: dr") != std::string::npos); + CHECK(aw.find("da: da") != std::string::npos); + /* what comes OUT of it: every `d.` and `last.` must be a ring name */ + const std::set ring = {"dr", "da"}; + for (const std::string& n : fields(at, "d")) { + CHECK(ring.count(n) == 1); + if (!ring.count(n)) + fprintf(stderr, " acceptTriple reads d.%s, which the ring does not carry\n", n.c_str()); + } + for (const std::string& n : fields(at, "last")) { + CHECK(ring.count(n) == 1); + if (!ring.count(n)) + fprintf(stderr, " acceptTriple reads last.%s, which the ring does not carry\n", n.c_str()); + } + /* and the ring must not be empty by construction: the push is gated on dr > 0 */ + CHECK(aw.find("dr <= 0") != std::string::npos); +} + TEST(every_field_the_page_reads_is_one_the_routes_emit) { Dash d(false); HttpResponse page = d.srv->router().call("GET", "/"); From df42bd5c26b55185ff05a712f7ed1e0ad41c0fe7 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 02:23:18 +0000 Subject: [PATCH 103/152] scripts/statsdump: size-cap rotation, monotonic dt_s, survive a failed write MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auditor gating fix 2 (Qwen 27B, AUDIT-qwen-20261020.md §6), confirmed by judge slice 05. An append-only recorder with no cap is a disk-full timer: at 1 poll/s the /stats payload runs to hundreds of MB a day, and the terminal state was an uncaught OSError traceback with no exit summary. --max-mib (default 256) rotates keeping 5 generations; rows carry their own timestamps so the chain stays readable in order. A failed write is now counted and the poller survives to report it. dt_s moves to the monotonic clock -- a wall-clock step could make it negative and every consumer dividing counters by it would inherit the step; t stays wall-clock because it is a timestamp, not a delta. Can-fail check run against the live engine: --max-mib 0.00002 produced 17 rotations with generations capped at .1-.5 and no rows lost. Does not touch the engine or the page, so the running image is unaffected; this lands for the PR and for whenever statsdump is wired in. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- scripts/statsdump.py | 47 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 7 deletions(-) diff --git a/scripts/statsdump.py b/scripts/statsdump.py index bb5db89c..c75ba3e9 100755 --- a/scripts/statsdump.py +++ b/scripts/statsdump.py @@ -37,6 +37,9 @@ def main(): ap.add_argument("--every", type=float, default=1.0, help="seconds between polls") ap.add_argument("--seconds", type=float, default=0.0, help="stop after this long; 0 = run until interrupted") ap.add_argument("--out", default="stats.jsonl") + ap.add_argument("--max-mib", type=float, default=256.0, + help="rotate the file when it passes this size (0 = never); " + "keeps 5 generations as .1 (newest) .. .5") ap.add_argument("--api-key", default=os.environ.get("RADIANCE_API_KEY"), help="or set RADIANCE_API_KEY; the key is never echoed") a = ap.parse_args() @@ -48,7 +51,22 @@ def main(): # Append, never truncate: a file that already holds last week's data is worth more than a clean # start, and the rows carry their own timestamps. out = open(a.out, "a") - prev, ok, lost, streak = None, 0, 0, 0 + prev, ok, lost, streak, rotated = None, 0, 0, 0, 0 + + def rotate(): + """Size cap (audit 2026-10-20 §6): an append-only recorder with no cap is a + disk-full timer. Shift .1->.2 ... keep 5, start fresh; rows carry their own + timestamps so the chain stays readable in order.""" + nonlocal out, rotated + out.close() + for i in range(4, 0, -1): + src = "%s.%d" % (a.out, i) + if os.path.exists(src): + os.replace(src, "%s.%d" % (a.out, i + 1)) + os.replace(a.out, a.out + ".1") + out = open(a.out, "a") + rotated += 1 + sys.stderr.write("statsdump: rotated %s (generation %d)\n" % (a.out, rotated)) sys.stderr.write("statsdump: %s/stats every %.1fs -> %s\n" % (base, a.every, a.out)) try: while True: @@ -67,11 +85,25 @@ def main(): else: streak = 0 row["t"] = t0 - row["dt_s"] = round(t0 - prev, 3) if prev is not None else 0.0 - prev = t0 - out.write(json.dumps(row, separators=(",", ":")) + "\n") - out.flush() # a killed poller must not lose the polls it did get - ok += 1 + # dt_s from the MONOTONIC clock: a wall-clock step (NTP) could make it + # negative, and a consumer dividing counters by dt_s would inherit the + # step. t stays wall-clock: it is the row's timestamp, not a delta. + row["dt_s"] = round(time.monotonic() - prev, 3) if prev is not None else 0.0 + prev = time.monotonic() + line = json.dumps(row, separators=(",", ":")) + "\n" + try: + out.write(line) + out.flush() # a killed poller must not lose the polls it did get + ok += 1 + except OSError as e: + # Disk full mid-write: loud, counted, and the poller SURVIVES to + # report it (audit §6: this path used to die with a traceback and + # no exit summary). The partial line, if any, is detectable JSONL. + lost += 1; streak += 1 + sys.stderr.write("statsdump: write failed (%s), %d lost\n" + % (type(e).__name__, lost)) + if a.max_mib > 0 and out.tell() >= a.max_mib * 1024 * 1024: + rotate() if deadline is not None and time.time() >= deadline: break # Sleep from the poll's START, so a slow engine does not walk the schedule later. @@ -82,7 +114,8 @@ def main(): sys.stderr.write("statsdump: interrupted\n") finally: out.close() - sys.stderr.write("statsdump: %d rows written, %d polls lost, %s\n" % (ok, lost, a.out)) + sys.stderr.write("statsdump: %d rows written, %d polls lost, %d rotations, %s\n" + % (ok, lost, rotated, a.out)) # An empty file is a failure, not a quiet run: say so with the exit status, not only in prose. return 1 if ok == 0 else 0 From 1cf31320a9de3fb960dea94722fb95c3cede5709 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 02:25:55 +0000 Subject: [PATCH 104/152] metrics+dashboard: judge-slice cleanups -- HELP text, dead window, window comment Non-gating findings from the Tasmania judge fan-out (reviews/judge/): - HELP text on radiance:decode_step_seconds_best/_recent said 'seconds per token'. It is a window mean of STEP times, and with speculation a step emits several tokens, so the two differ by the accepted-per-step factor -- the wording invited a comparison that is wrong by exactly that factor. Now says PER STEP and names the conversion. No test asserts on HELP text (server_test parses it into d.help and never reads it), so this is a documentation-only change to the exposition, not to the value. - noteSample gains a argument; acceptance passes win=false. Its winAt["accept"] ring was written every poll and read by nobody -- acceptTriple takes highest from extAt and recent/now from accPool -- so it was a second copy of the same samples that a reviewer reasonably mistook for a second figure. - RECENT's '15 s at the 500 ms poll' is true only while the quantity keeps updating; acceptance samples only when it drafts, so its 30-sample span is 30 UPDATES, minutes under sparse drafting (slice 01). Comment corrected. Diff is 16 insertions / 7 deletions across two files, read line by line (scripted sweep -- no test would have caught a wrong anchor). Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 14 ++++++++++---- core/server/metrics.cpp | 9 ++++++--- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 5b71bae9..3118b095 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1523,15 +1523,21 @@ function setMetric(key, value, text) { * diluting it. The engine's own figure is already a windowed rate (its help text: "over the * scheduler's recent window"), so this window sits on top of the engine's smoothing -- it * decides how long the page remembers, not how sharply the engine measures. */ -const RECENT = 30; /* 15 s at the 500 ms poll */ +const RECENT = 30; /* 15 s at the 500 ms poll WHILE the quantity keeps updating; a quantity + that skips polls (acceptance, which only samples when it drafts) spans + 30 UPDATES, which under sparse drafting is minutes, not 15 s. */ const RECENT_PREFILL = 10; /* 5 s: shorter than the shortest prefill event (see above) */ const extAt = {}, winAt = {}; let lastActiveC = 0; -function noteSample(key, c, value, cap) { +/* `win` false records the extreme only. Acceptance keeps its own pooled ring (accPool) and + * reads `highest` from extAt, so a window here would be a second, never-read copy of the + * same samples -- dead weight that a reviewer reasonably reads as a second figure. */ +function noteSample(key, c, value, cap, win) { if (value == null || !finite(value)) return; const e = extAt[key] || (extAt[key] = {}); - const w = winAt[key] || (winAt[key] = {}); if (!(c in e) || value > e[c]) e[c] = value; + if (win === false) return; + const w = winAt[key] || (winAt[key] = {}); const s = w[c] || (w[c] = []); s.push(value); if (s.length > (cap || RECENT)) s.shift(); } @@ -1990,7 +1996,7 @@ function update(s, dt) { const aw = accWindow(s); const awR = aw ? aw.ratio : null; const restarted = accRestart; accRestart = false; - if (awR != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, awR); + if (awR != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, awR, null, false); /* POOLED ACCEPTANCE WINDOW (2026-10-20, math audit before the production roll). * triple()'s `recent` averages the per-poll RATIOS; polls carry unequal draft counts, so a * quiet poll and a 500-draft poll would weigh the same -- a mean of ratios, not a ratio of diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index 76c55085..8498b8c4 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -337,11 +337,14 @@ std::string Metrics::render() const { if (g_step_best_.get() > 0) w.gauge("radiance:decode_step_seconds_best", "Fastest single-sequence decode step window this process has run, in seconds " - "per token. A mean over 32 consecutive single-stream steps, not a stopwatch " - "reading. Resets on restart.", L, g_step_best_.get()); + "PER STEP. A mean over 32 consecutive single-stream steps, not a stopwatch " + "reading. Not seconds per token: with speculation a step can emit several " + "tokens, so divide by the accepted-per-step figure to compare against a " + "token rate. Resets on restart.", L, g_step_best_.get()); if (g_step_recent_.get() > 0) w.gauge("radiance:decode_step_seconds_recent", - "Most recent single-sequence decode step window, in seconds per token. The gap " + "Most recent single-sequence decode step window, in seconds PER STEP (see " + "_best: not a token rate). The gap " "to _best tracks what else the machine is doing, not wear; see docs/GUIDE.md. " "Freezes while the lane is idle, because no window is completing.", L, g_step_recent_.get()); From 61e3131262bc3bf2a9a108e0a97764551aa7b55c Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 10:31:20 +0000 Subject: [PATCH 105/152] dashboard: live figures read 0 when the lane is idle Operator ruling 2026-10-20, on the three real-time figures: the decode-step headline, the acceptance tile, and the Speculation live figure. The defect was the FREEZE. Each of these held its last value while the lane did nothing, so a stale number kept wearing a current name -- a reader checking the dashboard at rest read a measurement of work that was not happening. Judge slice 10 named the failure mode in review. The fix follows the page's own convention rather than inventing one: every other live figure on this page shows 0 when the lane is idle (tps() renders 0 as "0", and the engine publishes 0 rates when nothing runs), so 0 IS the idle signal here. The dash stays reserved for a quantity that has no value at all -- no draft head, no engine attached. - Decode step: the tile reads this window's step time; a window with no decode steps reads 0. The engine's own best/recent floor figures below it are the engine's windows and stay put. - Acceptance tile: drafted nothing this poll -> 0. Dash only when there is no draft head at all. - Speculation live figure: same condition, same 0. Sparklines are unaffected: setMetric() pushes nothing for a null sample, so history stays honest across idle gaps. The restart path needs no special case -- a restart poll has no delta, so it reads the idle 0 -- and the pooled-ring clear inside accWindow stays, so a pre-restart pair never pools with a post-restart one. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 52 +++++++++++++++++++++++---------------- core/server/metrics.cpp | 4 +-- 2 files changed, 33 insertions(+), 23 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 3118b095..195f7fcc 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1588,7 +1588,7 @@ function acceptTriple(c, showNow) { * The counters go backwards when the engine restarts; that poll resets the window rather than * reporting a negative draft. */ const accPool = {}; /* per concurrency: ring of {dr, da} for the pooled tile window */ -let accPrev = null, accUp = -1, accRestart = false; +let accPrev = null, accUp = -1; function accWindow(s) { let reach = 0, hit = 0; for (const p of (s.draft_positions || [])) { reach += p.reached || 0; hit += p.accepted || 0; } @@ -1596,15 +1596,15 @@ function accWindow(s) { * the page was watching. uptime_s going backwards catches the one it missed: a backgrounded * tab whose accPrev froze while a new process drafted past the old process's lifetime total, * where the delta is positive and the first guard never fires. Either clears every pooled - * ring -- a pre-restart pair must not pool with a post-restart one -- and asks update() to - * dash the headline, so a dead process's ratio never masquerades as the new one's. */ + * ring -- a pre-restart pair must not pool with a post-restart one -- and yields no delta, + * so the headline reads the idle 0 rather than a dead process's ratio. */ const up = s.uptime_s; const restart = accPrev !== null && (reach < accPrev.r || hit < accPrev.a || (typeof up === "number" && up < accUp)); if (typeof up === "number") accUp = up; if (accPrev === null || restart) { accPrev = { r: reach, a: hit }; - if (restart) { for (const k in accPool) delete accPool[k]; accRestart = true; } + if (restart) for (const k in accPool) delete accPool[k]; return null; } const dr = reach - accPrev.r, da = hit - accPrev.a; @@ -1921,14 +1921,20 @@ function update(s, dt) { * mixed load the answer is the mean of two populations. `step_ns_decode / steps_decode` is * neither -- it is what a decode step cost. * - * A window with no decode steps in it holds the last reading rather than blanking, because a - * gauge that flickers to a dash every time the engine pauses is a gauge nobody reads. */ + * A window with no decode steps in it reads 0, not the last reading (operator ruling + * 2026-10-20, second pass): every other live figure on this page shows 0 when the lane is idle + * -- tps() renders 0 as "0" and the engine publishes 0 rates -- so 0 IS the idle signal here, + * and the dash stays reserved for a quantity that has no value at all. A held value was the + * original sin (a stale number wearing a current name); a dash was an over-correction that + * broke the convention. The floor and the engine's recent window below are the engine's own + * figures and stay put. */ const dSteps = prev ? s.steps_decode - prev.steps_decode : 0; const stepMs = dSteps > 0 ? (s.step_ns_decode - prev.step_ns_decode) / 1e6 / dSteps : null; if (stepMs != null) lastStepMs = stepMs; - const st = stepTime(lastStepMs); + const liveStepMs = stepMs === null ? 0 : stepMs; /* no steps in the window -> 0, the idle figure */ + const st = stepTime(liveStepMs); M.step.u.textContent = st.u; - setMetric("step", lastStepMs, st.n); + setMetric("step", liveStepMs, st.n); /* Single-stream steps only: the floor is a single-sequence window, and a batched step read * against it would report a batch arriving as a slowdown. */ @@ -1995,7 +2001,6 @@ function update(s, dt) { : ""; const aw = accWindow(s); const awR = aw ? aw.ratio : null; - const restarted = accRestart; accRestart = false; if (awR != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, awR, null, false); /* POOLED ACCEPTANCE WINDOW (2026-10-20, math audit before the production roll). * triple()'s `recent` averages the per-poll RATIOS; polls carry unequal draft counts, so a @@ -2013,16 +2018,17 @@ function update(s, dt) { * it one point against a 33,000-draft denominator, and it froze outright the moment the lane * went quiet. Every other tile's big number is the current value, and feeding the cumulative one * here also fed the sparkline a quantity that is flat by construction. - * Polls with no new drafts push NOTHING and the headline freezes with them: acceptance is - * UNDEFINED when nothing was drafted, so neither 0 (reads as failure) nor the last value (reads - * as stable) is the truth. A server with no draft head shows the dash -- there is no such figure - * to show. The lifetime ratio stays on /stats and /metrics; what the tile answers is "what is it - * accepting now". + * Polls with no new drafts read 0 (operator ruling 2026-10-20, second pass): the page's + * convention is that a live figure shows 0 when the lane is doing nothing, and the dash is for + * quantities with no value at all. The original freeze was the real defect -- a held value + * reads as a live measurement of a lane that drafted nothing. The lifetime ratio stays on + * /stats and /metrics; what the tile answers is "what is it accepting now", and now, idle, + * it is accepting nothing. * THE SPARKLINE'S SCALE DIFFERS from the other tiles: its samples are 10 s drafting windows, not * 500 ms polls, so this box spans up to 120 windows of actual drafting rather than 60 s. */ if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH); - else if (restarted) setMetric("accept", null, DASH); else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0)); + else setMetric("accept", 0, pctn(0, 0)); /* drafted nothing this poll -> 0, the idle figure */ $("m-acceptdet").textContent = acceptTriple(cNow, busy); M.flight.u.textContent = "/ " + s.queue_cap; @@ -2119,15 +2125,19 @@ function update(s, dt) { * PINNED, NOT PRICED: the Operator may prefer the average back in the big seat, and the swap * is these two lines. What must not happen is the average returning as the headline with no * bullet left behind, because then the live figure is the thing nobody can see. - * Undefined when nothing was drafted -- freeze rather than print 0 or repaint the last value. */ - if (restarted) $("acc_n").firstChild.nodeValue = "\u2013"; - else if (awR != null) $("acc_n").firstChild.nodeValue = pctn(awR, 0); + * Nothing drafted this poll reads 0 -- the page's idle figure, same law as the accept tile + * (op ruling 2026-10-20, second pass). The defect being fixed is the FREEZE: a held value + * reads as a live measurement of a lane that drafted nothing. */ + if (awR != null) $("acc_n").firstChild.nodeValue = pctn(awR, 0); + else $("acc_n").firstChild.nodeValue = pctn(0, 0); /* idle: 0, the page's idle figure */ $("specaside").textContent = "depth " + dp.length; spec["Drafter"].textContent = drafterName; spec["Depth"].textContent = dp.length; - /* Undefined when nothing has been drafted yet -- dash, not 0%. The panel's own rule is - * that 0 reads as failure, and this bullet was the one writer breaking it. */ - spec["Average"].textContent = s.draft_accept > 0 ? pct(s.draft_accept, 0) : DASH; + /* The lifetime marginal, always shown. Judge 22: guarding on >0 conflated "no drafts yet" + * with "drafts made, all rejected" -- a drafter that accepts nothing is exactly the case a + * reader needs to see, and a dash hid it. 0 is the honest figure for both, and the README's + * "Draft acceptance" section says which question this bullet answers. */ + spec["Average"].textContent = pct(s.draft_accept, 0); } /* ---- devices, in the same panel as the cache meter: they are one question. */ diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index 8498b8c4..f258d219 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -339,8 +339,8 @@ std::string Metrics::render() const { "Fastest single-sequence decode step window this process has run, in seconds " "PER STEP. A mean over 32 consecutive single-stream steps, not a stopwatch " "reading. Not seconds per token: with speculation a step can emit several " - "tokens, so divide by the accepted-per-step figure to compare against a " - "token rate. Resets on restart.", L, g_step_best_.get()); + "tokens, so per-token time is this divided by (1 + accepted per step), " + "not by the accepted figure alone. Resets on restart.", L, g_step_best_.get()); if (g_step_recent_.get() > 0) w.gauge("radiance:decode_step_seconds_recent", "Most recent single-sequence decode step window, in seconds PER STEP (see " From 52b3069f76d40b77db0893c3e2669d6fae99fa87 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 03:13:04 +0000 Subject: [PATCH 106/152] scripts/statsdump: survive disk-full AT the cap (judge slice 23) Slice 23 refuted my 'survive a failed write' claim in the primary geometry: a write fails at the cap, the cap check's out.tell() FLUSHES the dirty buffer and raises OUTSIDE the handler -- the poller dies with a traceback and no exit summary, exactly the terminal state the cap was supposed to prevent. Fix: on a failed write, drop the dirty buffer and reopen; the cap check is wrapped so a size check can never be the thing that kills the poller. Can-fail verified with a real EFBIG geometry (RLIMIT_FSIZE 5 KB, cap 104 B, live engine): the pre-fix code dies 'OSError: File too large'; the fixed code completes the run, 16 rotations, exit summary printed, rows counted. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- scripts/statsdump.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/scripts/statsdump.py b/scripts/statsdump.py index c75ba3e9..69ea09f6 100755 --- a/scripts/statsdump.py +++ b/scripts/statsdump.py @@ -58,7 +58,10 @@ def main(): disk-full timer. Shift .1->.2 ... keep 5, start fresh; rows carry their own timestamps so the chain stays readable in order.""" nonlocal out, rotated - out.close() + try: + out.close() # close() flushes; on a full disk the dirty buffer fails to land + except OSError: + pass # those rows are already counted lost -- the fresh handle is the point for i in range(4, 0, -1): src = "%s.%d" % (a.out, i) if os.path.exists(src): @@ -102,8 +105,23 @@ def main(): lost += 1; streak += 1 sys.stderr.write("statsdump: write failed (%s), %d lost\n" % (type(e).__name__, lost)) - if a.max_mib > 0 and out.tell() >= a.max_mib * 1024 * 1024: - rotate() + # Drop the dirty buffer and reopen: a flush on the same full disk fails + # again, and a later tell() would flush it and die OUTSIDE this handler + # (judge slice 23: the cap check's tell() was the actual killer). + try: + out.close() + except OSError: + pass + try: + out = open(a.out, "a") + except OSError: + pass + if a.max_mib > 0: + try: + if out.tell() >= a.max_mib * 1024 * 1024: + rotate() + except OSError: + pass # a size check must never be the thing that kills the poller if deadline is not None and time.time() >= deadline: break # Sleep from the poll's START, so a slow engine does not walk the schedule later. From 57184a0724ad86c66428557d3be1fb46bbc86f52 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 04:43:32 +0000 Subject: [PATCH 107/152] dashboard: un-trap mobile scrolling; rename 'accepted now' to 'conditionally accepted' Two operator findings from live phone use: - Scroll trap: nested scrollers (the request/batch card bodies and .hold) carry overscroll-behavior:contain, set deliberately for the desktop wheel so a scroll over the request table does not move the page behind it. On a phone that containment traps the thumb-drag: the card scrolls, bottoms out, and the page refuses to chain -- the operator's 'scroll halfway, then use the sides for traction' symptom is exactly that, the margins being the only place with no scroller under the finger. Narrow screens now restore overscroll-behavior:auto so the scroll chains to the document; desktop containment is unchanged. - Caption: the Speculation panel's live figure reads 'conditionally accepted' (displayed uppercase by .cap), naming the ratio's basis on the face of the panel. README's reference to the same figure follows. No test asserts on either string (checked before editing). Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- README.md | 2 +- core/server/dashboard.cpp | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9ca9d2e1..5447de41 100644 --- a/README.md +++ b/README.md @@ -299,7 +299,7 @@ produced. A position is verified only when every earlier position survived, so t admit two ratios, and they differ only in the denominator: - **Conditional** -- accepted / *reached*: of the drafts actually verified at a position, how - many passed. The dashboard's live "accepted now" figure and the per-position bars are + many passed. The dashboard's live "conditionally accepted" figure and the per-position bars are conditional. Always the higher number, and it moves with the workload. - **Marginal** -- accepted / *drafted*: of everything the drafter proposed, how much survived. The engine's `draft_accept` (/stats, and `radiance:draft_acceptance_ratio` on /metrics) is diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 195f7fcc..47e2c48b 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -563,7 +563,16 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; } #view-dash.boot > .strip { opacity:.45; } .strip { transition:opacity .18s linear; } .stack { display:grid; gap:14px; } -@media (max-width:1000px) { .body { grid-template-columns:minmax(0,1fr); } } +@media (max-width:1000px) { + .body { grid-template-columns:minmax(0,1fr); } + /* On a phone the page is one column you drag with your thumb. A nested scroller that + * refuses to chain (overscroll-behavior:contain, set for the desktop wheel so a scroll + * over the request table does not move the page behind it) traps the drag here: you + * scroll the card, it bottoms out, and the page will not follow, so you reach for the + * margins where no scroller lives to get the page moving again. On narrow screens let + * the scroll chain to the document; the desktop containment stays. */ + .body .panel > .pbody, .hold { overscroll-behavior:auto; } +} /* the request table */ table { width:100%; border-collapse:collapse; font-family:var(--mono); font-size:11.5px; @@ -1102,7 +1111,7 @@ nav button.on { color:var(--fg); background:var(--track); }
–tok
per step
–%
- accepted now
+ conditionally accepted
From 8cfcd3c6e59c43486874682e9926d020612c2ad6 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 05:12:08 +0000 Subject: [PATCH 108/152] dashboard: the .hold mobile scroll override was dead code -- specificity fix Judge slice 31 FAILed a91bf44 and the operator's thumb confirmed it: the request table still locks under a phone drag. The media-query override listed bare .hold, but the base '.hold { overscroll-behavior:contain }' is defined LATER in this file -- equal specificity, later rule wins the cascade, so the override matched and lost. The .pbody half won (its base rule is earlier), which is why the page scrolled some of the way but the request block did not. Fixed by specificity, not by moving the block: '.body .hold' outranks the base '.hold' regardless of order, and the media query stays co-located with the other breakpoint rules per this file's convention. The graph modal (.ginfo .pbody) deliberately stays contained: it is an overlay the user scrolls on purpose, and chaining out of it into the page behind is the wrong feel. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 47e2c48b..0508b0b2 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -570,8 +570,12 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; } * over the request table does not move the page behind it) traps the drag here: you * scroll the card, it bottoms out, and the page will not follow, so you reach for the * margins where no scroller lives to get the page moving again. On narrow screens let - * the scroll chain to the document; the desktop containment stays. */ - .body .panel > .pbody, .hold { overscroll-behavior:auto; } + * the scroll chain to the document; the desktop containment stays. + * .body .hold, not .hold: the base .hold rule is defined LATER in this file, so a bare + * .hold override here would match and still LOSE the cascade (equal specificity, later + * wins) -- judge slice 31 caught exactly that dead-code trap, and the operator's thumb + * confirmed it on the request table. .body .hold wins on specificity regardless of order. */ + .body .panel > .pbody, .body .hold { overscroll-behavior:auto; } } /* the request table */ From 87becd581214e6d9765b0c00db1403422ebeebc7 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 10:32:30 +0000 Subject: [PATCH 109/152] scripts/statsdump: rotation failure must not leave a closed handle (auditor ringer Q2) The disk-full fix in c9aa677 guarded the WRITE path but not the ROTATION path: rotate() closes the handle first, so if the generation shift or the reopen itself raises (ENOSPC bites when the directory must grow), out stays closed -- and the next poll's write raises ValueError, which the OSError handler does not catch. The poller dies with a traceback and no exit summary: the exact terminal state the size cap exists to prevent. Fix: rotate() reopens best-effort before re-raising (append-open needs no disk space, so it succeeds even on a full disk), and the exit close is guarded so a failing flush cannot eat the summary line. Can-fail verified by injecting ENOSPC into os.replace at the second shift -- the auditor's geometry, rotation failing with the handle already closed: pre-fix dies 'ValueError: I/O operation on closed file' with 0 summary lines; post-fix completes the run, rc=0, summary printed. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- scripts/statsdump.py | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/scripts/statsdump.py b/scripts/statsdump.py index 69ea09f6..0dd244df 100755 --- a/scripts/statsdump.py +++ b/scripts/statsdump.py @@ -62,14 +62,26 @@ def main(): out.close() # close() flushes; on a full disk the dirty buffer fails to land except OSError: pass # those rows are already counted lost -- the fresh handle is the point - for i in range(4, 0, -1): - src = "%s.%d" % (a.out, i) - if os.path.exists(src): - os.replace(src, "%s.%d" % (a.out, i + 1)) - os.replace(a.out, a.out + ".1") - out = open(a.out, "a") - rotated += 1 - sys.stderr.write("statsdump: rotated %s (generation %d)\n" % (a.out, rotated)) + try: + for i in range(4, 0, -1): + src = "%s.%d" % (a.out, i) + if os.path.exists(src): + os.replace(src, "%s.%d" % (a.out, i + 1)) + os.replace(a.out, a.out + ".1") + out = open(a.out, "a") + rotated += 1 + sys.stderr.write("statsdump: rotated %s (generation %d)\n" % (a.out, rotated)) + except OSError: + # The shift or the reopen failed (ENOSPC can bite when the directory must + # grow). out is CLOSED here -- and a closed handle raises ValueError on the + # next write, which the OSError handler does not catch (auditor ringer Q2). + # Reopen best-effort before re-raising: append-open needs no disk space, so + # this succeeds even on a full disk, and the poller keeps counting losses. + try: + out = open(a.out, "a") + except OSError: + pass + raise sys.stderr.write("statsdump: %s/stats every %.1fs -> %s\n" % (base, a.every, a.out)) try: while True: @@ -131,7 +143,10 @@ def main(): except KeyboardInterrupt: sys.stderr.write("statsdump: interrupted\n") finally: - out.close() + try: + out.close() + except OSError: + pass # a flush failing at exit must not eat the summary line below sys.stderr.write("statsdump: %d rows written, %d polls lost, %d rotations, %s\n" % (ok, lost, rotated, a.out)) # An empty file is a failure, not a quiet run: say so with the exit status, not only in prose. From eed70619ccca61511d51762fd7dcd33cfcff7e00 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 10:36:04 +0000 Subject: [PATCH 110/152] dashboard: 'Average' -> 'Accepted of drafted' -- the label names its denominator Operator call. The bullet is the engine's lifetime marginal ratio, accepted/drafted (core/sched/draft.h:172, 'cumulative and exact' -- a pooled ratio of sums, not an average of anything). 'Average' was wrong twice: it is not an average, and it hid which denominator it used. The panel shows two ratios that count the SAME accepted tokens and differ only in the denominator -- reached for the live figure, drafted for this one. 'Average' distinguished them by time, which is not the axis they differ on, and invited reading the lifetime figure as a longer window on the live one. Naming the denominator makes the panel self-documenting, which is the same reason the live figure became 'conditionally accepted'. The label is ours, not upstream's: 685ec5b's panel had no such key, so this asks nothing of upstream vocabulary. No test keys on the string (checked). Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 0508b0b2..744bcb0d 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1671,14 +1671,14 @@ function kvPanel(host, keys) { return out; } const totals = kvPanel($("totals"), ["Requests", "Steps"]); -/* "Average" is the LIFETIME MARGINAL ratio -- upstream's figure, unchanged, and the one this - * panel used to carry as its headline. A bullet now rather than the big number: see the note at - * the accept tile. It divides by every token DRAFTED, so it is not comparable with the live - * figure above it, which divides by the positions actually REACHED -- the two bases are worked - * through in README.md, section "Draft acceptance", and both are derivable from the log. Deliberately not spelled out on the - * face of the panel: the distinction is an analysis-time concern, and a tooltip is invisible on - * the phone anyway. */ -const spec = kvPanel($("spec"), ["Drafter", "Depth", "Average"]); +/* "Accepted of drafted" is the LIFETIME MARGINAL ratio -- the engine's figure, unchanged, and + * the one this panel used to carry as its headline. A bullet now rather than the big number: + * see the note at the accept tile. It divides by every token DRAFTED, so it is not comparable + * with the live figure above it, which divides by the positions actually REACHED; the two bases + * are worked through in README.md, section "Draft acceptance", and both are derivable from the + * log. Each label names its own denominator, which is the whole distinction -- so neither needs + * a tooltip, and a tooltip would be invisible on the phone anyway. */ +const spec = kvPanel($("spec"), ["Drafter", "Depth", "Accepted of drafted"]); /* ---------------------------------------------------------------- meters */ /* `split` gives the track a second segment for a fill that is two things -- see setSplit. */ @@ -2150,7 +2150,7 @@ function update(s, dt) { * with "drafts made, all rejected" -- a drafter that accepts nothing is exactly the case a * reader needs to see, and a dash hid it. 0 is the honest figure for both, and the README's * "Draft acceptance" section says which question this bullet answers. */ - spec["Average"].textContent = pct(s.draft_accept, 0); + spec["Accepted of drafted"].textContent = pct(s.draft_accept, 0); } /* ---- devices, in the same panel as the cache meter: they are one question. */ From 3178807ba772993ec16cb73178e69c88cbb830af Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 10:44:42 +0000 Subject: [PATCH 111/152] dashboard: detail-line 'now' clauses stop reporting stale values as current Operator ruling 2026-10-20, applied one line down: the idle-0 law exists because a stale value wearing a current name is a false measurement. Judge slice 26 found the same defect surviving in the detail lines under the three figures already fixed -- the headline obeyed the law and its own detail line did not, so a busy lane that drafted nothing showed 0 and 'now 87% of highest' directly beneath it. - Accept tile: 'now' is shown only when THIS poll drafted. The guard inside acceptTriple (last.dr > 0) can never be false -- the ring only stores deltas with dr > 0 -- so the freshness test moved to the caller, where the poll's own delta is known. highest/recent are session statistics by design and stay. - Step tile: 'now X% of best' is gated on this window HAVING decode steps, not on the lane being busy. During a prefill-only stretch the lane is busy and lastStepMs holds the last decode poll; the headline reads 0, so the clause must not print. - Speculation 'per step': reads 0 when the window took no decode steps instead of holding the last value. EXTENSION of the ruling by one figure, named here because it was not one of the three the operator listed -- same defect class, flagged by slice 26, and it is derived from the step tile that already reads 0, so leaving it frozen made the panel disagree with itself. Fully-idle was already correct on all three; every one of these was the busy-but-no-measurement window. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 744bcb0d..ca0a0264 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -1912,7 +1912,7 @@ function renderRequests(list, poolTokens) { /* ---------------------------------------------------------------- update */ let prev = null, prevAt = 0, bars = [], devs = [], layerBars = []; -let lastStepMs = null, lastTps = null; +let lastStepMs = null; /* lastTps retired with the per-step freeze (slice 26) */ /* The single-stream floor and the engine's most recent window, shown as two numbers with no * verdict. The engine records the fastest single-sequence decode window it has measured @@ -1964,7 +1964,11 @@ function update(s, dt) { * ~500 ms poll mean and `best` a 32-step window mean, so a short fast stretch can beat the * floor; the figure is capped at 99 and shown as ~99, "at the best", rather than claiming a * record the window cannot confirm. */ - if (s.running > 0 && lastStepMs != null) { + /* Gated on this window HAVING decode steps, not on the lane being busy: during a + * prefill-only stretch the lane is busy, lastStepMs holds the last DECODE poll, and the + * headline correctly reads 0 -- printing "now X% of best" under it would put a stale + * value under the word "now", the exact defect the idle-0 ruling exists to kill. */ + if (stepMs != null && s.running > 0) { const k = s.running; if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs; const ref = k === 1 && floorMs > 0 ? floorMs : bestAt[k]; @@ -2042,7 +2046,12 @@ function update(s, dt) { if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH); else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0)); else setMetric("accept", 0, pctn(0, 0)); /* drafted nothing this poll -> 0, the idle figure */ - $("m-acceptdet").textContent = acceptTriple(cNow, busy); + /* `now` is shown only when THIS poll drafted. The guard inside acceptTriple (last.dr > 0) + * cannot ever be false -- the ring only stores deltas with dr > 0 -- so the freshness test + * belongs here, where the poll's own delta is known. Otherwise a busy lane that drafted + * nothing this poll shows 0 in the headline and "now Z% of highest" one line below it, + * computed from the last drafted delta. highest/recent are session statistics and stay. */ + $("m-acceptdet").textContent = acceptTriple(cNow, busy && awR != null); M.flight.u.textContent = "/ " + s.queue_cap; const list = s.requests || []; @@ -2126,8 +2135,12 @@ function update(s, dt) { * gives tokens a step for the whole batch -- which grows with concurrency and says nothing * about the drafter. What speculation buys is tokens a step for ONE sequence. */ const perStep = sps > 0 && s.decode_tps > 0 ? s.decode_tps / sps / seqs : null; - if (perStep != null) lastTps = perStep; - $("tps_n").firstChild.nodeValue = lastTps == null ? DASH : sig3(lastTps); + /* Reads 0 when this window took no decode steps -- the page's idle figure, same law as + * the step tile above it, which this figure is derived from. It used to hold the last + * value, so a lane that stopped decoding kept reporting what its steps used to cost. + * (Extension of the operator's idle-0 ruling by one figure: same defect, one line down, + * flagged by judge slice 26 as "pre-existing, now more visible".) */ + $("tps_n").firstChild.nodeValue = perStep == null ? "0" : sig3(perStep); /* ACCEPTED IS THE LIVE FIGURE, matching the tile above it. `aw` is the same pooled drafting * window the tile's headline reads, computed earlier in this function -- one derivation, two * readers, so the panel and the tile cannot disagree. From b2e0ef7911b32f7506a4ff013d690bc4698cce69 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 12:48:39 +0000 Subject: [PATCH 112/152] dashboard: the accept sparkline comment described a sampling scheme that never existed Auditor flagged this twice; it is a lie in shipped source (the comment is served inside the page), so it goes before merge rather than after. The comment claimed the sparkline's samples are 10 s drafting windows. No 10 s clock exists anywhere in the page: HIST is 120 at the 500 ms poll (dashboard.cpp:1249), and the accept series pushes via noteSample only when the poll drafted (aw.dr > 0). The true distinction from the other tiles is the drafting-only sampling, not a different window length: 120 drafting samples are 60 s of continuous drafting, stretched over more wall-clock when drafting is intermittent. Comment-only change; no behavior touched. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index ca0a0264..6ca6195e 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -2041,8 +2041,9 @@ function update(s, dt) { * reads as a live measurement of a lane that drafted nothing. The lifetime ratio stays on * /stats and /metrics; what the tile answers is "what is it accepting now", and now, idle, * it is accepting nothing. - * THE SPARKLINE'S SCALE DIFFERS from the other tiles: its samples are 10 s drafting windows, not - * 500 ms polls, so this box spans up to 120 windows of actual drafting rather than 60 s. */ + * THE SPARKLINE'S SCALE DIFFERS from the other tiles: it samples only polls that DRAFTED (the + * others sample every poll), so its 120 samples span 60 s of continuous drafting at the 500 ms + * poll -- and more wall-clock than that when drafting is intermittent. */ if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH); else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0)); else setMetric("accept", 0, pctn(0, 0)); /* drafted nothing this poll -> 0, the idle figure */ From 459529638e05834b8f9d5c1f41ce142d18155e76 Mon Sep 17 00:00:00 2001 From: "Memoria (Noblistic)" Date: Tue, 20 Oct 2026 14:59:15 +0000 Subject: [PATCH 113/152] dashboard: statsdump exits cleanly when its handle is dead; sparkline comment told a third wrong story Judge ringer 4 on the final tree (3 slices, Tasmania, independent questions). Slice A PASS-WITH-CAVEATS, slice B PASS-WITH-CAVEATS, slice C FAIL. Both findings were real and both are fixed here. statsdump (slice B, R1 + R2): the rotation fix deferred the death instead of removing it. If the best-effort reopen inside rotate() itself fails, out stays CLOSED, the re-raised OSError is swallowed by the cap check's handler, and the next poll's write raises ValueError -- which no handler in the file catches (they all catch OSError). Slice B found the unpatched twin in the write-failure handler: close succeeds, reopen fails (EMFILE/ENOENT/EACCES/EIO -- not ENOSPC, which append-open survives), and the cap check's out.tell() dies on the closed handle two statements later. Both paths now raise a dedicated RecorderDead, caught at the loop: the recorder exits loudly with its exit summary, because a handle that cannot be reopened means recording cannot continue. Deferring a traceback by one iteration was the wrong ambition; exiting with the count is the honest terminal state. Canaries reproduce both geometries (reopen fails after rotation shift fails; reopen fails after write fails): pre-fix dies 'ValueError: I/O operation on closed file' with no summary in both; post-fix exits rc=0/rc=1 with the summary printed in both. dashboard.cpp (slice C, FAIL): my previous commit replaced one wrong sparkline comment with another. The truth, verified against the call sites: setMetric samples EVERY poll for every tile (idle polls push 0), so the accept sparkline spans the same 60 s as the others; the only difference is the dash case -- no draft head, no value, a gap that stretches the line over more wall-clock. The original comment claimed 10 s drafting windows; my rewrite claimed drafting-only sampling, conflating the sparkline (setMetric/hist) with the triple's recent window (noteSample, win=false). Two lies in one comment block, both caught by review rather than by me. Authored at: Memoria Qwen 3.8 Flash-Next 125B MoE (level not visible) via Open WebUI --- core/server/dashboard.cpp | 8 +++++--- scripts/statsdump.py | 21 ++++++++++++++++----- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 6ca6195e..9a383322 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -2041,9 +2041,11 @@ function update(s, dt) { * reads as a live measurement of a lane that drafted nothing. The lifetime ratio stays on * /stats and /metrics; what the tile answers is "what is it accepting now", and now, idle, * it is accepting nothing. - * THE SPARKLINE'S SCALE DIFFERS from the other tiles: it samples only polls that DRAFTED (the - * others sample every poll), so its 120 samples span 60 s of continuous drafting at the 500 ms - * poll -- and more wall-clock than that when drafting is intermittent. */ + * THE SPARKLINE'S SCALE IS THE SAME as the other tiles -- 120 samples at the 500 ms poll, 60 s + * -- because setMetric samples every poll, idle polls included (0 is a value; see above). The + * one difference is the dash case: with no draft head there is no value to push, so those polls + * leave a gap and the line stretches over more wall-clock than 60 s. (Judge slice 4C: this + * comment claimed a 10 s window, then a drafting-only window; neither sampling scheme exists.) */ if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH); else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0)); else setMetric("accept", 0, pctn(0, 0)); /* drafted nothing this poll -> 0, the idle figure */ diff --git a/scripts/statsdump.py b/scripts/statsdump.py index 0dd244df..0b58c029 100755 --- a/scripts/statsdump.py +++ b/scripts/statsdump.py @@ -30,6 +30,15 @@ # for a quiet hour. import argparse, json, os, sys, time, urllib.error, urllib.request +class RecorderDead(Exception): + """The output handle could not be reopened; recording cannot continue. + + A closed handle raises ValueError on the next write/tell, which the OSError + handlers do not catch -- the poller would die with a traceback and no exit + summary (judge-4 slices B R1/R2). Dying HERE, loudly, with the summary, is + the honest terminal state: the recorder cannot record.""" + + def main(): ap = argparse.ArgumentParser(add_help=True) ap.add_argument("--port", type=int, default=8800) @@ -79,9 +88,9 @@ def main(): # this succeeds even on a full disk, and the poller keeps counting losses. try: out = open(a.out, "a") - except OSError: - pass - raise + except OSError as reopen_err: + raise RecorderDead("reopen after failed rotation: %s" % reopen_err) from None + raise # reopen succeeded: the ORIGINAL error is now safe to swallow upstream sys.stderr.write("statsdump: %s/stats every %.1fs -> %s\n" % (base, a.every, a.out)) try: while True: @@ -126,8 +135,8 @@ def main(): pass try: out = open(a.out, "a") - except OSError: - pass + except OSError as reopen_err: + raise RecorderDead("reopen after failed write: %s" % reopen_err) from None if a.max_mib > 0: try: if out.tell() >= a.max_mib * 1024 * 1024: @@ -142,6 +151,8 @@ def main(): time.sleep(left) except KeyboardInterrupt: sys.stderr.write("statsdump: interrupted\n") + except RecorderDead as e: + sys.stderr.write("statsdump: DEAD (%s) -- exiting with summary\n" % e) finally: try: out.close() From d2a165d56d7eb06ac8a9311e39bd3ce4e5f4d0b4 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:10 +0200 Subject: [PATCH 114/152] jinja: the caps probe hands the template an empty tools array, not [null] -- GLM-5.3's template iterated it and lost string content json{nullptr} is the one-element array [null], not an empty one. The string-content probe passed it as `tools`; GLM-5.3's template iterates `tools` under `{% if tools %}`, so the probe's render threw on the null element, the throw was taken for "cannot render string content", and with typed content unsupported as well every request logged `render_message_to_json: Neither string content nor typed content is supported`. llama.cpp master passes json::array() (PR #27130); so does this probe now. The GLM-shaped template in chat_test asserts string content. Co-Authored-By: Claude Fable 5.1 --- tests/chat_test.cpp | 3 +++ vendor/llama/common/jinja/caps.cpp | 6 ++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/chat_test.cpp b/tests/chat_test.cpp index df154adb..5a2bd8db 100644 --- a/tests/chat_test.cpp +++ b/tests/chat_test.cpp @@ -1032,6 +1032,9 @@ TEST(a_dotted_integer_is_an_index_as_in_jinja2) { "{%- if add_generation_prompt %}{% endif %}", "", "")); CHECK(glm.caps().tools); CHECK(glm.caps().tool_calls); + /* The string-content probe hands the template an empty tools array, not [null]: this + * template iterates `tools`, threw on the null, and lost string content. */ + CHECK(glm.caps().string_content); ChatTemplate first; CHECK_OK(first.load("{{ messages.0.content }}|{{ messages.1.role }}", "", "")); diff --git a/vendor/llama/common/jinja/caps.cpp b/vendor/llama/common/jinja/caps.cpp index ead86476..ae9e0c95 100644 --- a/vendor/llama/common/jinja/caps.cpp +++ b/vendor/llama/common/jinja/caps.cpp @@ -110,8 +110,10 @@ caps caps_get(jinja::program & prog) { }); }, [&]() { - // tools - return json{nullptr}; + // tools: an empty array, as llama.cpp master hands it. json{nullptr} is the one-element + // array [null]; a template that iterates `tools` (GLM-5.3's does) threw on the null + // and the probe took the throw for "cannot render string content". + return json::array(); }, [&](bool success, value & messages, value &) { auto & content = messages->at(0)->at("content"); From fa4a7a75a44905c52acab6b008b675f3306a291c Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:10 +0200 Subject: [PATCH 115/152] glm5next: the plugin over its blocks, one a file, and rad_glm_tp.h for the shards and the split threshold -- the same graph, read in order The plugin carried the draft head's buffers, weights and ops in its declare and its draft pass in its step, with the three ops that join the head to its layer declared inside the layer function; each GLM block carried its core in a header of its own (rad_block_mla_latent.h, rad_block_kda_state.h, rad_block_dsa_cache.h), the split threshold sat in rad_tp_split.h beside the router's column split, and 64 / world, 8192 / world, 2048 / world were spelled across the plugin and the blocks. tests/arch_test.cpp held the recording builder, the run-phase fakes, the step lint, the batch kits and the fingerprints beside every architecture's cases, 9.5k lines in one translation unit, GLM-5.3's among them. Now one block a file in arch/common: rad_block_glm_{mhc,kda,mla,indexer,router,mtp}.h, the cores joined to their blocks, and GlmMtp the draft head in three parts (inputs, join, head), declared and stepped around the plugin's layer 45. rad_glm_tp.h (GlmTp) holds the widths a rank's shard divides, the one threshold kSplitRows and the replicated all_reduce declared once; SplitF32Proj moves over unchanged. The plugin reads as the stream's buffers, then each block's, the KV groups, the layers, the head and the draft head. tests/arch_fakes.h holds the fakes and the helpers every architecture test needs, included by one translation unit a binary (neither binary links rad_core, as before); GLM-5.3's cases are tests/glm5next_test.cpp, which includes only its plugin, with two cases new: every op the plugin issues carries the operand count its schema declares (the kernel libraries' schemas under $RADIANCE_HOME/kernels, counted as core/runtime/issue.cpp counts), and every declared weight reads an entry the served container holds, at the dtype its stored encoding calls for (the container's names and encodings as rad-info -v lists them). Every declared name, declaration order and issue order is as it was: the pinned graph and step hashes at one and eight ranks are the values arch_test pinned before the move (world 1 0xed3fc26c486ea1b5 / 0x98ba2952bb37b075, world 8 0x8204e073efdeee0c / 0x1279aecfe4e32d9a), and arch_test's pins of the other architectures are unchanged. Co-Authored-By: Claude Fable 5.1 --- arch/common/rad_block_dsa_cache.h | 150 -- arch/common/rad_block_glm_indexer.h | 154 +- arch/common/rad_block_glm_kda.h | 148 +- .../{rad_block_mhc.h => rad_block_glm_mhc.h} | 16 +- arch/common/rad_block_glm_mla.h | 110 +- arch/common/rad_block_glm_mtp.h | 187 ++ arch/common/rad_block_glm_router.h | 2 +- arch/common/rad_block_kda_state.h | 128 - arch/common/rad_block_mla_latent.h | 84 - arch/common/rad_glm_tp.h | 103 + arch/common/rad_tp_split.h | 65 - arch/glm5next/glm5next.cpp | 527 ++-- docs/ARCHITECTURES.md | 25 +- tests/CMakeLists.txt | 22 +- tests/arch_fakes.h | 1177 +++++++++ tests/arch_test.cpp | 2347 +---------------- tests/glm5next_test.cpp | 1628 ++++++++++++ 17 files changed, 3768 insertions(+), 3105 deletions(-) delete mode 100644 arch/common/rad_block_dsa_cache.h rename arch/common/{rad_block_mhc.h => rad_block_glm_mhc.h} (93%) create mode 100644 arch/common/rad_block_glm_mtp.h delete mode 100644 arch/common/rad_block_kda_state.h delete mode 100644 arch/common/rad_block_mla_latent.h create mode 100644 arch/common/rad_glm_tp.h delete mode 100644 arch/common/rad_tp_split.h create mode 100644 tests/arch_fakes.h create mode 100644 tests/glm5next_test.cpp diff --git a/arch/common/rad_block_dsa_cache.h b/arch/common/rad_block_dsa_cache.h deleted file mode 100644 index 52cc782a..00000000 --- a/arch/common/rad_block_dsa_cache.h +++ /dev/null @@ -1,150 +0,0 @@ -/* GLM's stateful compressed-index core. The caller supplies projected queries, - * signed F32 head gates, and [LayerNorm(key), pool_gate] BF16 rows. No RoPE. - * Query projections are replicated across TP ranks; selected pages belong to MLA. */ -#ifndef RAD_BLOCK_DSA_CACHE_H -#define RAD_BLOCK_DSA_CACHE_H -#include "rad_arch.h" - -namespace rad { -namespace arch { -struct DsaCache { - struct Config { - int64_t blocks = 0, work = 0, ring = 0, topk = 512; - }; - struct Wire { - rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0; - rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0; - rad_buf score = 0, selected = 0, nsel = 0, length = 0; - }; - Geom g{}; - Config c{}; - Wire w{}; - int layer = 0; - rad_kvgroup index = 0, tail = 0, attention = 0; - rad_weight ape = 0; - rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0; - - int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg, - const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group, - rad_kvgroup* index_group, const char* ape_source) { - g = geom; - c = cfg; - w = wire; - layer = l; - attention = attn; - tail = tail_group; - if (!b || !index_group || !ape_source || !attention || !tail || c.blocks < 1 || - c.work < (g.max_tok + 3) / 4 + g.max_seqs || c.ring < 4 + g.max_spec || c.topk != 512 || - !w.query || !w.codes || !w.scales || !w.gate || !w.kg || !w.stage || !w.page || - !w.bpos || !w.nc || !w.pooled || !w.pool_scale || !w.score || !w.selected || !w.nsel || - !w.length) - return RAD_E_INVAL; - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, tail)); - const char* name = nm.f("blk.%d.index_ape", l); - RAD_ARCH_TRY(map_copy(b, name, ape_source)); - ape = decl_w(b, name, RAD_F32, { 4, 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, - grp_layer(l)); - if (!ape) return RAD_E_INVAL; - // Query buffers are [tokens*32,128]; scoring uses their rank-three view. - op_query = rw(b, - RAD_OP(b, "dsa_query", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { w.query }, { w.codes, w.scales }); - op_work = rw( - b, - RAD_OP(b, "qsa_work", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), RAD_INT("ratio", 4), - RAD_INT("ring", c.ring), RAD_INT("seqs", g.max_seqs), - RAD_INT("work", c.work), RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { w.kg }, { w.stage, w.page, w.bpos, w.nc }); - // Declare immediately before the cache consumer: page size comes from that op. - if (!*index_group) { - RadKVGroupDecl d{}; - d.kind = RAD_KV_FULL; - d.dtype = RAD_U8; - d.n_head_kv = 1; - d.head_dim = 17; - *index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d); - } - index = *index_group; - if (!index) return RAD_E_INVAL; - op_pool = - rw(b, - RAD_OP(b, "dsa_pool", - RAD_PARAMS(RAD_RANGE("M", 1, c.work), RAD_INT("n", 128), RAD_INT("ratio", 4), - RAD_INT("block_size", 4), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(ape)), - { w.stage, w.page }, { w.pooled, w.pool_scale }); - if (!op_pool || rad_kv_block_size(b, index) != 4) return RAD_E_INVAL; - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, index)); - op_tail = rw(b, - RAD_OP(b, "qsa_tail_store", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), - RAD_INT("ratio", 4), RAD_INT("ring", c.ring), - RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { w.kg }, {}); - op_score = rw(b, - RAD_OP(b, "dsa_score", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128), - RAD_INT("heads", 32), RAD_INT("blocks", c.blocks), - RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")), - RAD_NOWEIGHTS), - { w.codes, w.scales, w.gate, w.nc }, { w.score }); - op_select = rw(b, - RAD_OP(b, "qsa_select", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", c.blocks), - RAD_INT("topk", 512), RAD_INT("ratio", 4), - RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)), - RAD_NOWEIGHTS), - { w.score, w.nc }, { w.selected, w.nsel, w.length }); - return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL; - } - void step(RadCtx* ctx, const RadBatch* batch) const { - const auto* ib = kv_batch(batch, index); - const auto* tb = kv_batch(batch, tail); - const auto* ab = kv_batch(batch, attention); - if (!ib || !tb || !ab || !ib->block_table || !ab->block_table || !tb->state_index) { - rad_step_fail(ctx, "DSA requires index/attention block tables and tail state indices"); - return; - } - const int64_t T = batch->n_tok, S = batch->n_seq; - const int64_t work = (T + 3) / 4 + S, - pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1; - RAD_ISSUE_N(ctx, op_query, T * 32, brows(w.query, T * 32), brows(w.codes, T * 32), - brows(w.scales, T * 32)); - RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), - praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), - praw2(tb->state_index, RAD_I32, S, pitch), - praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), RAD_NONE, - brows(w.stage, work * 4), brows(w.page, work), brows(w.bpos, work), - brows(w.nc, S)); - RAD_ISSUE_N(ctx, op_pool, work, brows(w.stage, work * 4), RAD_W(ape), brows(w.pooled, work), - brows(w.pool_scale, work), brows(w.page, work), kv_cache(index, layer)); - // Gather before overwriting the tail; the wider ring preserves rejected-token rollback. - RAD_ISSUE_N(ctx, op_tail, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), - praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), - praw2(tb->state_index, RAD_I32, S, pitch)); - int64_t live = ((int64_t)batch->max_ctx_len + T + batch->n_spec + 4) / 4 + 1; - if (live > c.blocks) live = c.blocks; - // T is the total across sequences, so the conservative bound can exceed the - // per-sequence page table. Columns without a table entry cannot be scored. - if (live > ib->block_table_pitch) live = ib->block_table_pitch; - if (live < 1) live = 1; - RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32), - brows(w.gate, T), kv_cache(index, layer), RAD_NONE, - praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), - praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S), - bcol_at(w.score, 0, c.blocks, 0, live, T)); - RAD_ISSUE_N(ctx, op_select, T, bcol_at(w.score, 0, c.blocks, 0, live, T), - praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S), - praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1), - brows(w.selected, T), brows(w.nsel, T), brows(w.length, T)); - } -}; -} -} // namespace rad::arch -#endif diff --git a/arch/common/rad_block_glm_indexer.h b/arch/common/rad_block_glm_indexer.h index 59d81696..18ed8c56 100644 --- a/arch/common/rad_block_glm_indexer.h +++ b/arch/common/rad_block_glm_indexer.h @@ -1,13 +1,159 @@ -/* Replicated GLM indexer front end. Casts bridge ordinary linear rows to the - * flattened per-head quantizer and join normalized keys with learned pool gates. */ +/* GLM-5.3's DSA indexer: the stateful compressed-index core over its paged key cache (DsaCache), + * which scores every complete block of a sequence's history against each query and selects the + * 512 the MLA attends to, and the front end around it (GlmIndexer), whose casts bridge ordinary + * linear rows to the flattened per-head quantiser and join normalized keys with learned pool + * gates. No RoPE; the only rotation is the Hadamard inside dsa_query. Selected pages belong to + * the MLA. + * + * Under tensor parallelism the indexer is replicated whole: every rank pools into the whole index + * cache, scores every query row against it and selects for every row. Only the head gates' f32 + * projection splits its columns from GlmTp::kSplitRows (SplitF32Proj). */ #ifndef RAD_BLOCK_GLM_INDEXER_H #define RAD_BLOCK_GLM_INDEXER_H #include "rad_fp8.h" -#include "rad_block_dsa_cache.h" -#include "rad_tp_split.h" +#include "rad_glm_tp.h" namespace rad { namespace arch { +struct DsaCache { + struct Config { + int64_t blocks = 0, work = 0, ring = 0, topk = 512; + }; + struct Wire { + rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0; + rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0; + rad_buf score = 0, selected = 0, nsel = 0, length = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + rad_kvgroup index = 0, tail = 0, attention = 0; + rad_weight ape = 0; + rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg, + const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group, + rad_kvgroup* index_group, const char* ape_source) { + g = geom; + c = cfg; + w = wire; + layer = l; + attention = attn; + tail = tail_group; + if (!b || !index_group || !ape_source || !attention || !tail || c.blocks < 1 || + c.work < (g.max_tok + 3) / 4 + g.max_seqs || c.ring < 4 + g.max_spec || c.topk != 512 || + !w.query || !w.codes || !w.scales || !w.gate || !w.kg || !w.stage || !w.page || + !w.bpos || !w.nc || !w.pooled || !w.pool_scale || !w.score || !w.selected || !w.nsel || + !w.length) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, tail)); + const char* name = nm.f("blk.%d.index_ape", l); + RAD_ARCH_TRY(map_copy(b, name, ape_source)); + ape = decl_w(b, name, RAD_F32, { 4, 128 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(l)); + if (!ape) return RAD_E_INVAL; + // Query buffers are [tokens*32,128]; scoring uses their rank-three view. + op_query = rw(b, + RAD_OP(b, "dsa_query", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * 32), RAD_INT("n", 128), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.query }, { w.codes, w.scales }); + op_work = rw( + b, + RAD_OP(b, "qsa_work", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), RAD_INT("ratio", 4), + RAD_INT("ring", c.ring), RAD_INT("seqs", g.max_seqs), + RAD_INT("work", c.work), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.kg }, { w.stage, w.page, w.bpos, w.nc }); + // Declare immediately before the cache consumer: page size comes from that op. + if (!*index_group) { + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = RAD_U8; + d.n_head_kv = 1; + d.head_dim = 17; + *index_group = rad_decl_kv_group(b, nm.f("kv_dsa_index"), &d); + } + index = *index_group; + if (!index) return RAD_E_INVAL; + op_pool = + rw(b, + RAD_OP(b, "dsa_pool", + RAD_PARAMS(RAD_RANGE("M", 1, c.work), RAD_INT("n", 128), RAD_INT("ratio", 4), + RAD_INT("block_size", 4), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(ape)), + { w.stage, w.page }, { w.pooled, w.pool_scale }); + if (!op_pool || rad_kv_block_size(b, index) != 4) return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, index)); + op_tail = rw(b, + RAD_OP(b, "qsa_tail_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 256), + RAD_INT("ratio", 4), RAD_INT("ring", c.ring), + RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.kg }, {}); + op_score = rw(b, + RAD_OP(b, "dsa_score", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 128), + RAD_INT("heads", 32), RAD_INT("blocks", c.blocks), + RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")), + RAD_NOWEIGHTS), + { w.codes, w.scales, w.gate, w.nc }, { w.score }); + op_select = rw(b, + RAD_OP(b, "qsa_select", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", c.blocks), + RAD_INT("topk", 512), RAD_INT("ratio", 4), + RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)), + RAD_NOWEIGHTS), + { w.score, w.nc }, { w.selected, w.nsel, w.length }); + return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, const RadBatch* batch) const { + const auto* ib = kv_batch(batch, index); + const auto* tb = kv_batch(batch, tail); + const auto* ab = kv_batch(batch, attention); + if (!ib || !tb || !ab || !ib->block_table || !ab->block_table || !tb->state_index) { + rad_step_fail(ctx, "DSA requires index/attention block tables and tail state indices"); + return; + } + const int64_t T = batch->n_tok, S = batch->n_seq; + const int64_t work = (T + 3) / 4 + S, + pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1; + RAD_ISSUE_N(ctx, op_query, T * 32, brows(w.query, T * 32), brows(w.codes, T * 32), + brows(w.scales, T * 32)); + RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), + praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), + praw2(tb->state_index, RAD_I32, S, pitch), + praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), RAD_NONE, + brows(w.stage, work * 4), brows(w.page, work), brows(w.bpos, work), + brows(w.nc, S)); + RAD_ISSUE_N(ctx, op_pool, work, brows(w.stage, work * 4), RAD_W(ape), brows(w.pooled, work), + brows(w.pool_scale, work), brows(w.page, work), kv_cache(index, layer)); + // Gather before overwriting the tail; the wider ring preserves rejected-token rollback. + RAD_ISSUE_N(ctx, op_tail, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), + praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), + praw2(tb->state_index, RAD_I32, S, pitch)); + int64_t live = ((int64_t)batch->max_ctx_len + T + batch->n_spec + 4) / 4 + 1; + if (live > c.blocks) live = c.blocks; + // T is the total across sequences, so the conservative bound can exceed the + // per-sequence page table. Columns without a table entry cannot be scored. + if (live > ib->block_table_pitch) live = ib->block_table_pitch; + if (live < 1) live = 1; + RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32), + brows(w.gate, T), kv_cache(index, layer), RAD_NONE, + praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), + praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S), + bcol_at(w.score, 0, c.blocks, 0, live, T)); + RAD_ISSUE_N(ctx, op_select, T, bcol_at(w.score, 0, c.blocks, 0, live, T), + praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S), + praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1), + brows(w.selected, T), brows(w.nsel, T), brows(w.length, T)); + } +}; + struct GlmIndexer { struct Wire { rad_buf input = 0, q_low = 0, q_wide = 0, kg_raw = 0; diff --git a/arch/common/rad_block_glm_kda.h b/arch/common/rad_block_glm_kda.h index 6617ae0f..ab8b4e61 100644 --- a/arch/common/rad_block_glm_kda.h +++ b/arch/common/rad_block_glm_kda.h @@ -1,13 +1,137 @@ -/* GLM KDA projections around the recurrent/cache core. These checkpoint weights - * are BF16. The two low-rank gate paths have no intervening activation. The - * caller supplies normalized input and owns the mHC residual connection. */ +/* GLM-5.3's KDA layer: the seven bf16 projections around the recurrent core (GlmKda), and the + * core itself over already projected inputs (KdaState), whose ple_conv supplies exactly causal + * depthwise convolution + SiLU, cold start and accepted-history rollback included. The two + * low-rank gate paths have no intervening activation. The caller supplies the normalized input + * and owns the mHC residual connection. + * + * Under tensor parallelism the heads split (GlmTp::heads), and with them the q/k/v rows, the + * convolution taps, the state and the output projection's columns; the two rank-128 projections + * into the gates are replicated. The block's all_reduce sums the output. */ #ifndef RAD_BLOCK_GLM_KDA_H #define RAD_BLOCK_GLM_KDA_H #include "rad_fp8.h" -#include "rad_block_kda_state.h" +#include "rad_glm_tp.h" +#include namespace rad { namespace arch { +struct KdaState { + struct Config { + int64_t heads = 16, dim = 128, width = 4; + double lower = -5; + }; + struct Src { + const char *q_conv = nullptr, *k_conv = nullptr, *v_conv = nullptr, *alog = nullptr, + *bias = nullptr, *norm = nullptr; + }; + struct Wire { + rad_buf qkv = 0, conv = 0, a = 0, beta = 0, gate = 0, out = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + rad_kvgroup state = 0, history = 0; + rad_weight taps = 0, alog = 0, bias = 0, norm = 0; + rad_op op_conv = 0, op_verify = 0, op_prefill = 0, op_norm = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup st, rad_kvgroup cv, + const Config& cfg, const Wire& wire, const Src& src) { + g = geom; + c = cfg; + w = wire; + layer = l; + state = st; + history = cv; + if (!b || !st || !cv || c.heads < 1 || c.dim != 128 || c.width != 4 || g.max_spec > 31 || + !std::isfinite(c.lower) || c.lower >= 0 || !w.qkv || !w.conv || !w.a || !w.beta || + !w.gate || !w.out || w.qkv == w.conv || !src.q_conv || !src.k_conv || !src.v_conv || + !src.alog || !src.bias || !src.norm) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st)); + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv)); + const int64_t width = c.heads * c.dim; + const char *tn = nm.f("blk.%d.ssm_conv.weight", l), *an = nm.f("blk.%d.ssm_a", l), + *bn = nm.f("blk.%d.ssm_dt_bias", l), *nn = nm.f("blk.%d.ssm_norm.weight", l); + RAD_ARCH_TRY(map_concat(b, tn, { src.q_conv, src.k_conv, src.v_conv })); + RAD_ARCH_TRY(map_copy(b, an, src.alog)); + RAD_ARCH_TRY(map_copy(b, bn, src.bias)); + RAD_ARCH_TRY(map_copy(b, nn, src.norm)); + taps = decl_w(b, tn, RAD_BF16, { 3 * width, c.width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, + grp_layer(l), 0, { width, width, width }); + alog = + decl_w(b, an, RAD_F32, { c.heads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + bias = decl_w(b, bn, RAD_F32, { width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + norm = + decl_w(b, nn, RAD_F32, { c.dim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + if (!taps || !alog || !bias || !norm) return RAD_E_INVAL; + op_conv = rw(b, + RAD_OP(b, "ple_conv", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 3 * width), + RAD_INT("width", c.width), RAD_INT("dilation", 1), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(taps)), + { w.qkv }, { w.conv }); + for (int verify = 0; verify < 2; ++verify) { + const rad_op op = rw( + b, + RAD_OP(b, "kda_update", + RAD_PARAMS( + RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_k", c.dim), RAD_INT("head_v", c.dim), + RAD_F64("lower_bound", c.lower), + RAD_F64("scale", 1.0 / std::sqrt((double)c.dim)), + RAD_F64("l2_eps", 1e-6), RAD_STR("mode", verify ? "verify" : "prefill"), + RAD_STR("dtype", "bf16"), + RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate")), + RAD_WEIGHTS(alog, bias)), + { w.conv, w.a, w.beta }, { w.out }); + if (verify) + op_verify = op; + else + op_prefill = op; + } + op_norm = rw(b, + RAD_OP(b, "gdn_gated_rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", c.dim), + RAD_F64("eps", g.eps), RAD_STR("act", "sigmoid")), + RAD_WEIGHTS(norm)), + { w.out, w.gate }, { w.out }); + return op_conv && op_verify && op_prefill && op_norm ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, const RadBatch* batch) const { + const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history); + if (!st || !cv || !st->state_index || !cv->state_index) { + rad_step_fail(ctx, "KDA requires recurrent and convolution state indices"); + return; + } + const int64_t T = batch->n_tok, S = batch->n_seq, width = c.heads * c.dim; + const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1; + int64_t D = 0, DT = 0; + batch_split(batch, &D, &DT); + for (int verify = 1; verify >= 0; --verify) { + const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T; + if (!seqs) continue; + const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1); + const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs); + const RadOperand accepted = + verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE; + RAD_ISSUE_N(ctx, op_conv, rows, brows(w.qkv, rows), RAD_W(taps), + kv_cache(history, layer), cu, RAD_NONE, + praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted, + brows(w.conv, rows)); + RAD_ISSUE_N(ctx, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, width, rows), + bcol(w.conv, width, width, rows), bcol(w.conv, 2 * width, width, rows), + brows(w.a, rows), brows(w.beta, rows), RAD_W(alog), RAD_W(bias), + kv_cache(state, layer), + praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted, + init, brows(w.out, rows)); + } + RAD_ISSUE_N(ctx, op_norm, T, brows(w.out, T), brows(w.gate, T), RAD_W(norm), + brows(w.out, T)); + } +}; + struct GlmKda { struct Wire { rad_buf input = 0, forget_low = 0, gate_low = 0, out = 0; @@ -23,14 +147,14 @@ struct GlmKda { rad_kvgroup history, bool reduce = true) { g = geom; w = wire; - if (!b || !prefix || g.n_embd != 4096 || g.world < 1 || 64 % g.world || !w.input || - !w.forget_low || !w.gate_low || !w.out || w.input == w.out || + if (!b || !prefix || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world || + !w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out || w.forget_low == w.gate_low) return RAD_E_INVAL; // All seven projections are plain BF16 in the pinned checkpoint. Geom bg = g; bg.w_bf16 = true; - const int64_t width = 8192 / g.world, heads = 64 / g.world; + const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world); const auto group = grp_layer(layer); auto act = [](rad_buf x) { ActFP8 a{}; @@ -67,15 +191,7 @@ struct GlmKda { if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 || !gate_b.bf16 || !output.bf16) return RAD_E_UNSUPPORTED; - if (reduce && g.world > 1) - op_ar = rw(b, - RAD_OP(b, "all_reduce", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_RANGE("numel", 4096, g.max_tok * 4096), - RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), - RAD_INT("min_bytes", g.wire_min_bytes)), - RAD_NOWEIGHTS), - { w.out }, { w.out }); + if (reduce) op_ar = GlmTp::reduce(b, g, w.out); return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK; } void step(RadCtx* ctx, const RadBatch* batch) const { diff --git a/arch/common/rad_block_mhc.h b/arch/common/rad_block_glm_mhc.h similarity index 93% rename from arch/common/rad_block_mhc.h rename to arch/common/rad_block_glm_mhc.h index 67b21d15..f65e3bb7 100644 --- a/arch/common/rad_block_mhc.h +++ b/arch/common/rad_block_glm_mhc.h @@ -1,8 +1,10 @@ -/* GLM manifold-constrained residual connections. The mixed residual must have a - * separate destination: each output stream reads every original input stream. */ -#ifndef RAD_BLOCK_MHC_H -#define RAD_BLOCK_MHC_H -#include "rad_tp_split.h" +/* GLM-5.3's manifold-constrained residual connections (mHC): four residual streams in one + * 16384-wide row. read() mixes them down to the block's 4096-wide input and saves the mixing + * coefficients; write() adds the block's output back into every stream. The mixed residual must + * have a separate destination: each output stream reads every original input stream. */ +#ifndef RAD_BLOCK_GLM_MHC_H +#define RAD_BLOCK_GLM_MHC_H +#include "rad_glm_tp.h" #include namespace rad { @@ -27,7 +29,7 @@ struct ManifoldConn { rad_op op_pre = 0, op_post = 0; /* Above the split threshold under TP, GLM's projection is split by residual chunks: each rank * computes the partials of its chunks with mhc_pre's own kernels, an all_gather joins them, - * and mhc_pre_finish completes the read on every rank (rad_tp_split.h). */ + * and mhc_pre_finish completes the read on every rank (rad_glm_tp.h). */ static constexpr int64_t kChunk = 2048, kPartStride = 28; rad_buf part = 0, parts = 0; rad_op op_partial = 0, op_gather = 0, op_finish = 0; @@ -72,7 +74,7 @@ struct ManifoldConn { } int declare_split(RadBuilder* b, Names& nm, const char* name) { const int64_t total = c.hc * g.n_embd / kChunk; - split_rows = kGlmTpSplitRows; + split_rows = GlmTp::kSplitRows; if (g.world < 2 || g.n_embd != 4096 || c.hc != 4 || total % g.world) { split_rows = 0; return RAD_OK; diff --git a/arch/common/rad_block_glm_mla.h b/arch/common/rad_block_glm_mla.h index 1fe2089b..7c54e67d 100644 --- a/arch/common/rad_block_glm_mla.h +++ b/arch/common/rad_block_glm_mla.h @@ -1,12 +1,92 @@ -/* No-RoPE GLM MLA. prepare() exposes normalized Q-lora for the replicated - * indexer; finish() consumes its selection. The caller owns the mHC residual. */ +/* GLM-5.3's sparse latent attention (MLA, no RoPE): the projections and the latent cache store + * around the absorbed core (GlmMla), and the core itself over the latent cache (MlaLatent), whose + * complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent + * for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual. + * + * Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and + * kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are + * replicated. */ #ifndef RAD_BLOCK_GLM_MLA_H #define RAD_BLOCK_GLM_MLA_H #include "rad_fp8.h" -#include "rad_block_mla_latent.h" +#include "rad_glm_tp.h" +#include namespace rad { namespace arch { +struct MlaLatent { + struct Config { + int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513; + }; + struct Wire { + rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0; + }; + Geom g{}; + Config c{}; + Wire w{}; + int layer = 0; + rad_kvgroup kv = 0; + rad_weight projection = 0; + rad_op op_absorb = 0, op_attn = 0, op_expand = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group, + const Config& cfg, const Wire& wire, const char* source) { + g = geom; + c = cfg; + w = wire; + layer = l; + kv = group; + if (!b || !source || !group || c.heads < 1 || c.blocks < 1 || !w.q || !w.q_latent || + !w.attn_latent || !w.out || !w.selected || !w.length || w.q == w.q_latent || + w.q_latent == w.attn_latent || w.attn_latent == w.out || c.latent_dim != 512 || + c.head_dim != 256) + return RAD_E_INVAL; + RAD_ARCH_TRY(rad_bind_layer_kv(b, l, group)); + const char* name = nm.f("blk.%d.attn_kv_b.weight", l); + RAD_ARCH_TRY(map_copy(b, name, source)); + // The conversion recipe decodes this small projection only. + projection = decl_w(b, name, RAD_BF16, { c.heads * 2 * c.head_dim, c.latent_dim }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + if (!projection) return RAD_E_INVAL; + op_absorb = rw( + b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), + RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(projection)), + { w.q }, { w.q_latent }); + op_attn = + rw(b, + RAD_OP(b, "mla_attn", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim), + RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks), + RAD_INT("block_size", 4), + RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.q_latent, w.selected, w.length }, { w.attn_latent }); + if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL; + op_expand = rw( + b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), + RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), + RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(projection)), + { w.attn_latent }, { w.out }); + return op_absorb && op_attn && op_expand ? RAD_OK : RAD_E_INVAL; + } + void step(RadCtx* ctx, int64_t rows) const { + RAD_ISSUE_N(ctx, op_absorb, rows, brows(w.q, rows), RAD_W(projection), + brows(w.q_latent, rows)); + RAD_ISSUE_N(ctx, op_attn, rows, brows(w.q_latent, rows), kv_cache(kv, layer), + brows(w.selected, rows), brows(w.length, rows), brows(w.attn_latent, rows)); + RAD_ISSUE_N(ctx, op_expand, rows, brows(w.attn_latent, rows), RAD_W(projection), + brows(w.out, rows)); + } +}; + struct GlmMla { struct Wire { ActFP8 input{}, q_low{}, attn{}; @@ -30,8 +110,8 @@ struct GlmMla { w = wire; layer = l; kv = group; - if (!b || !prefix || !kv || g.n_embd != 4096 || g.world < 1 || 64 % g.world || !w.input.x || - !w.q_raw || !w.kv_raw || !w.latent || !w.out || !w.q_low.x || !w.attn.x || + if (!b || !prefix || !kv || g.n_embd != 4096 || g.world < 1 || GlmTp::kHeads % g.world || + !w.input.x || !w.q_raw || !w.kv_raw || !w.latent || !w.out || !w.q_low.x || !w.attn.x || w.attn.x != w.core.out) return RAD_E_INVAL; const auto wg = grp_layer(l); @@ -56,8 +136,8 @@ struct GlmMla { RAD_WEIGHTS(kv_gain)), { w.kv_raw }, { w.latent }); if (!op_kv_norm) return RAD_E_INVAL; - RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), 16384 / g.world, 1536, - RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, + RAD_ARCH_TRY(q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b", l), GlmTp::mla_width(g.world), + 1536, RAD_SHARD_ROW, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, w.q_low, w.core.q)); // Cache stores contiguous halves of the normalized latent, with no duplicated K/V. op_store = rw(b, @@ -72,22 +152,14 @@ struct GlmMla { } int declare_finish(RadBuilder* b, Names& nm, const char* prefix, bool reduce = true) { MlaLatent::Config cfg; - cfg.heads = 64 / g.world; + cfg.heads = GlmTp::heads(g.world); RAD_ARCH_TRY( core.declare(b, nm, g, layer, kv, cfg, w.core, nm.ckpt("%s.kv_b_proj.weight", prefix))); - RAD_ARCH_TRY(attn_quant.declare(b, g, w.attn, 16384 / g.world)); + RAD_ARCH_TRY(attn_quant.declare(b, g, w.attn, GlmTp::mla_width(g.world))); RAD_ARCH_TRY(output.declare(b, nm, g, nm.f("blk.%d.attn_output", layer), 4096, - 16384 / g.world, RAD_SHARD_COL, grp_layer(layer), + GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer), { nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out)); - if (reduce && g.world > 1) - op_ar = rw(b, - RAD_OP(b, "all_reduce", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_RANGE("numel", 4096, g.max_tok * 4096), - RAD_STR("dtype", "bf16"), RAD_INT("exact", g.wire_exact), - RAD_INT("min_bytes", g.wire_min_bytes)), - RAD_NOWEIGHTS), - { w.out }, { w.out }); + if (reduce) op_ar = GlmTp::reduce(b, g, w.out); return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL; } void prepare(RadCtx* ctx, const RadBatch* batch) const { diff --git a/arch/common/rad_block_glm_mtp.h b/arch/common/rad_block_glm_mtp.h new file mode 100644 index 00000000..964700f9 --- /dev/null +++ b/arch/common/rad_block_glm_mtp.h @@ -0,0 +1,187 @@ +/* GLM-5.3's draft head: checkpoint layer 45 as a serial drafter (RAD_DRAFT_SERIAL), around the + * one MLA + indexer + MoE layer the plugin declares and steps itself. + * + * h = gather(the trunk's final hidden states, at the rows this pass continues from) + * e = embed(the token one position on) + * x = eh_proj( concat( enorm(e), hnorm(h) ) ) the normalized embedding first + * x += attention(norm(x)); the proposal rows: x += moe(norm(x)) <- the plugin's layer + * h' = shared_head.norm(x); logits = the trunk's lm_head over h' + * + * h' is both the logits input and the next round's `h`. No mHC: the layer's residual is a plain + * add. By the sign of RadBatch::draft_pass a history pass (< 0) covers every row the trunk step + * had, fills the draft layer's latent, index and tail for all of them and runs the MoE and the + * head on the proposal rows only (draft_out_ids); a draft round (> 1) is one row a sequence. + * + * The block is declared and stepped in three parts around the layer, in this order: `inputs` + * before the layer's attention, `join` (the residual add and the proposal rows' selection) between + * its attention and its feed-forward, `head` after it. The embedding and lm_head are the trunk's. + * Its names live under the `mtp.` scope (Names), its weights in layer 45's group. eh_proj + * (4096 x 8192 bf16, 64 MiB) is replicated and read whole in every draft pass. */ +#ifndef RAD_BLOCK_GLM_MTP_H +#define RAD_BLOCK_GLM_MTP_H +#include "rad_glm_tp.h" + +namespace rad { +namespace arch { +struct GlmMtp { + /* The trunk's: its final hidden states, its logits, its embedding and head. */ + struct Wire { + rad_buf final_hidden = 0, logits = 0; + rad_weight token = 0, head = 0; + }; + static constexpr int kDepth = 3; /* --num-speculative-tokens auto */ + Names nm{ "mtp" }; + Geom g{}; + Wire w{}; + rad_buf x = 0, hidden = 0, embedding = 0, concat = 0, out = 0; + rad_weight en = 0, hn = 0, eh = 0, norm = 0; + rad_op op_prev = 0, op_embed = 0, op_embed_ar = 0, op_en = 0, op_hn = 0, op_eh = 0; + rad_op op_residual = 0, op_select = 0, op_back = 0; + rad_op op_norm = 0, op_copy = 0, op_head = 0; + + /* The buffers, the weights, and the ops up to the layer's input. */ + int declare_inputs(RadBuilder* b, const Geom& geom, const Wire& wire) { + g = geom; + w = wire; + if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1) + return RAD_E_INVAL; + x = decl_b(b, nm.f("x"), RAD_BF16, { g.max_tok, 4096 }); + hidden = decl_b(b, nm.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST); + embedding = decl_b(b, nm.f("embedding"), RAD_BF16, { g.max_tok, 4096 }); + concat = decl_b(b, nm.f("concat"), RAD_BF16, { g.max_tok, 8192 }); + out = decl_b(b, nm.f("final"), RAD_BF16, { g.max_tok, 4096 }); + const char* pre = "model.language_model.layers.45"; + auto gain = [&](const char* n, const char* src) { + const char* name = nm.f("%s", n); + if (map_copy(b, name, nm.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0; + return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(45)); + }; + en = gain("enorm.weight", "enorm.weight"); + hn = gain("hnorm.weight", "hnorm.weight"); + norm = gain("output_norm.weight", "shared_head.norm.weight"); + RAD_ARCH_TRY(map_copy(b, nm.f("eh_proj.weight"), nm.ckpt("%s.eh_proj.weight", pre))); + eh = decl_w(b, nm.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(45)); + if (!x || !hidden || !embedding || !concat || !out || !en || !hn || !norm || !eh) + return RAD_E_INVAL; + op_prev = rw(b, + RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { w.final_hidden }, { hidden }); + op_embed = rw(b, + RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(w.token)), + {}, { embedding }); + op_embed_ar = GlmTp::reduce(b, g, embedding, true); + op_en = rmsnorm(b, en, embedding, concat); + op_hn = rmsnorm(b, hn, hidden, concat); + op_eh = rw(b, + RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096), + RAD_INT("K", 8192), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(eh)), + { concat }, { x }); + return op_prev && op_embed && op_en && op_hn && op_eh && (g.world == 1 || op_embed_ar) + ? RAD_OK + : RAD_E_INVAL; + } + /* Between the layer's attention and its feed-forward: the residual add of the attention's + * output `y`, and on a history pass the proposal rows gathered to the head of `x`. */ + int declare_join(RadBuilder* b, rad_buf y) { + op_residual = rw(b, + RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x, y }, { x }); + // All history rows fill the draft cache; only proposal rows need its FFN. + op_select = rw(b, + RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { x }, { hidden }); + op_back = cast(b, hidden, x); + return op_residual && op_select && op_back ? RAD_OK : RAD_E_INVAL; + } + /* After the layer: the head's norm, its output kept as the next round's hidden, the logits, + * and the drafter's declaration. */ + int declare_head(RadBuilder* b) { + op_norm = rmsnorm(b, norm, x, out); + op_copy = cast(b, out, hidden); + op_head = rw(b, + RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", 4096), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w.head)), + { hidden }, { w.logits }); + if (!op_norm || !op_copy || !op_head) return RAD_E_INVAL; + RadDrafterDecl dd{}; + dd.name = "mtp"; + dd.kind = RAD_DRAFT_SERIAL; + dd.depth = g.max_spec; + dd.mask_token = -1; + return rad_declare_drafter(b, &dd); + } + + /* The rows a pass runs its feed-forward and head on: the proposal rows of a history pass, + * every row of a draft round. */ + static int64_t head_rows(const RadBatch* batch) { + return batch->draft_pass < 0 ? batch->n_draft_out : batch->n_tok; + } + void step_inputs(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (batch->draft_pass < 0 && batch->n_out > 0) + RAD_ISSUE_N(c, op_prev, batch->n_out, RAD_B(w.final_hidden), + praw(batch->out_ids, RAD_I32, batch->n_out), brows(hidden, batch->n_out)); + RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token), + brows(embedding, T)); + if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE); + RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T)); + RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T)); + RAD_ISSUE_N(c, op_eh, T, brows(concat, T), RAD_W(eh), brows(x, T)); + } + void step_join(RadCtx* c, const RadBatch* batch, rad_buf y) const { + const int64_t T = batch->n_tok, L = head_rows(batch); + RAD_ISSUE_N(c, op_residual, T, brows(x, T), brows(y, T), brows(x, T)); + if (batch->draft_pass < 0) { + RAD_ISSUE_N(c, op_select, L, RAD_B(x), praw(batch->draft_out_ids, RAD_I32, L), + brows(hidden, L)); + RAD_ISSUE_N(c, op_back, L, brows(hidden, L), brows(x, L)); + } + } + void step_head(RadCtx* c, const RadBatch* batch) const { + const int64_t L = head_rows(batch); + RAD_ISSUE_N(c, op_norm, L, brows(x, L), RAD_W(norm), brows(out, L)); + RAD_ISSUE_N(c, op_copy, L, brows(out, L), brows(hidden, L)); + RAD_ISSUE_N(c, op_head, L, brows(hidden, L), RAD_W(w.head), brows(w.logits, L)); + } + +private: + rad_op rmsnorm(RadBuilder* b, rad_weight gain, rad_buf in, rad_buf out) const { + return rw(b, + RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(gain)), + { in }, { out }); + } + rad_op cast(RadBuilder* b, rad_buf in, rad_buf out) const { + return rw(b, + RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + { in }, { out }); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_block_glm_router.h b/arch/common/rad_block_glm_router.h index ce48cf2f..a23f901b 100644 --- a/arch/common/rad_block_glm_router.h +++ b/arch/common/rad_block_glm_router.h @@ -2,7 +2,7 @@ * come from the uncorrected sigmoid probabilities. All routing arithmetic is F32. */ #ifndef RAD_BLOCK_GLM_ROUTER_H #define RAD_BLOCK_GLM_ROUTER_H -#include "rad_tp_split.h" +#include "rad_glm_tp.h" #include namespace rad { diff --git a/arch/common/rad_block_kda_state.h b/arch/common/rad_block_kda_state.h deleted file mode 100644 index 559245d3..00000000 --- a/arch/common/rad_block_kda_state.h +++ /dev/null @@ -1,128 +0,0 @@ -/* GLM's recurrent core over already projected inputs. ple_conv supplies exactly - * causal depthwise convolution + SiLU, including cold start and accepted-history rollback. */ -#ifndef RAD_BLOCK_KDA_STATE_H -#define RAD_BLOCK_KDA_STATE_H -#include "rad_arch.h" -#include - -namespace rad { -namespace arch { -struct KdaState { - struct Config { - int64_t heads = 16, dim = 128, width = 4; - double lower = -5; - }; - struct Src { - const char *q_conv = nullptr, *k_conv = nullptr, *v_conv = nullptr, *alog = nullptr, - *bias = nullptr, *norm = nullptr; - }; - struct Wire { - rad_buf qkv = 0, conv = 0, a = 0, beta = 0, gate = 0, out = 0; - }; - Geom g{}; - Config c{}; - Wire w{}; - int layer = 0; - rad_kvgroup state = 0, history = 0; - rad_weight taps = 0, alog = 0, bias = 0, norm = 0; - rad_op op_conv = 0, op_verify = 0, op_prefill = 0, op_norm = 0; - - int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup st, rad_kvgroup cv, - const Config& cfg, const Wire& wire, const Src& src) { - g = geom; - c = cfg; - w = wire; - layer = l; - state = st; - history = cv; - if (!b || !st || !cv || c.heads < 1 || c.dim != 128 || c.width != 4 || g.max_spec > 31 || - !std::isfinite(c.lower) || c.lower >= 0 || !w.qkv || !w.conv || !w.a || !w.beta || - !w.gate || !w.out || w.qkv == w.conv || !src.q_conv || !src.k_conv || !src.v_conv || - !src.alog || !src.bias || !src.norm) - return RAD_E_INVAL; - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, st)); - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, cv)); - const int64_t width = c.heads * c.dim; - const char *tn = nm.f("blk.%d.ssm_conv.weight", l), *an = nm.f("blk.%d.ssm_a", l), - *bn = nm.f("blk.%d.ssm_dt_bias", l), *nn = nm.f("blk.%d.ssm_norm.weight", l); - RAD_ARCH_TRY(map_concat(b, tn, { src.q_conv, src.k_conv, src.v_conv })); - RAD_ARCH_TRY(map_copy(b, an, src.alog)); - RAD_ARCH_TRY(map_copy(b, bn, src.bias)); - RAD_ARCH_TRY(map_copy(b, nn, src.norm)); - taps = decl_w(b, tn, RAD_BF16, { 3 * width, c.width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, - grp_layer(l), 0, { width, width, width }); - alog = - decl_w(b, an, RAD_F32, { c.heads }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); - bias = decl_w(b, bn, RAD_F32, { width }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); - norm = - decl_w(b, nn, RAD_F32, { c.dim }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); - if (!taps || !alog || !bias || !norm) return RAD_E_INVAL; - op_conv = rw(b, - RAD_OP(b, "ple_conv", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 3 * width), - RAD_INT("width", c.width), RAD_INT("dilation", 1), - RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(taps)), - { w.qkv }, { w.conv }); - for (int verify = 0; verify < 2; ++verify) { - const rad_op op = rw( - b, - RAD_OP(b, "kda_update", - RAD_PARAMS( - RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), - RAD_INT("head_k", c.dim), RAD_INT("head_v", c.dim), - RAD_F64("lower_bound", c.lower), - RAD_F64("scale", 1.0 / std::sqrt((double)c.dim)), - RAD_F64("l2_eps", 1e-6), RAD_STR("mode", verify ? "verify" : "prefill"), - RAD_STR("dtype", "bf16"), - RAD_STR("state_form", g.max_spec > 0 ? "anchor" : "per_candidate")), - RAD_WEIGHTS(alog, bias)), - { w.conv, w.a, w.beta }, { w.out }); - if (verify) - op_verify = op; - else - op_prefill = op; - } - op_norm = rw(b, - RAD_OP(b, "gdn_gated_rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("channels", c.dim), - RAD_F64("eps", g.eps), RAD_STR("act", "sigmoid")), - RAD_WEIGHTS(norm)), - { w.out, w.gate }, { w.out }); - return op_conv && op_verify && op_prefill && op_norm ? RAD_OK : RAD_E_INVAL; - } - void step(RadCtx* ctx, const RadBatch* batch) const { - const auto *st = kv_batch(batch, state), *cv = kv_batch(batch, history); - if (!st || !cv || !st->state_index || !cv->state_index) { - rad_step_fail(ctx, "KDA requires recurrent and convolution state indices"); - return; - } - const int64_t T = batch->n_tok, S = batch->n_seq, width = c.heads * c.dim; - const int64_t pitch = st->state_index_pitch > 0 ? st->state_index_pitch : 1; - int64_t D = 0, DT = 0; - batch_split(batch, &D, &DT); - for (int verify = 1; verify >= 0; --verify) { - const int64_t seq0 = verify ? 0 : D, seqs = verify ? D : S - D, rows = verify ? DT : T; - if (!seqs) continue; - const RadOperand cu = praw(batch->cu_seqlens + seq0, RAD_I32, seqs + 1); - const RadOperand init = praw(batch->ctx_lens + seq0, RAD_I32, seqs); - const RadOperand accepted = - verify ? praw(batch->num_accepted, RAD_I32, seqs) : RAD_NONE; - RAD_ISSUE_N(ctx, op_conv, rows, brows(w.qkv, rows), RAD_W(taps), - kv_cache(history, layer), cu, RAD_NONE, - praw(cv->state_index + seq0, RAD_I32, seqs), init, accepted, - brows(w.conv, rows)); - RAD_ISSUE_N(ctx, verify ? op_verify : op_prefill, rows, bcol(w.conv, 0, width, rows), - bcol(w.conv, width, width, rows), bcol(w.conv, 2 * width, width, rows), - brows(w.a, rows), brows(w.beta, rows), RAD_W(alog), RAD_W(bias), - kv_cache(state, layer), - praw2(st->state_index + seq0 * pitch, RAD_I32, seqs, pitch), cu, accepted, - init, brows(w.out, rows)); - } - RAD_ISSUE_N(ctx, op_norm, T, brows(w.out, T), brows(w.gate, T), RAD_W(norm), - brows(w.out, T)); - } -}; -} -} // namespace rad::arch -#endif diff --git a/arch/common/rad_block_mla_latent.h b/arch/common/rad_block_mla_latent.h deleted file mode 100644 index abeb3e94..00000000 --- a/arch/common/rad_block_mla_latent.h +++ /dev/null @@ -1,84 +0,0 @@ -/* Absorbed GLM MLA core. The caller projects/norms q and stores the current - * latent before step(). Complete heads shard as rows of the shared K/V weight. */ -#ifndef RAD_BLOCK_MLA_LATENT_H -#define RAD_BLOCK_MLA_LATENT_H -#include "rad_arch.h" -#include - -namespace rad { -namespace arch { -struct MlaLatent { - struct Config { - int64_t heads = 16, head_dim = 256, latent_dim = 512, blocks = 513; - }; - struct Wire { - rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0, selected = 0, length = 0; - }; - Geom g{}; - Config c{}; - Wire w{}; - int layer = 0; - rad_kvgroup kv = 0; - rad_weight projection = 0; - rad_op op_absorb = 0, op_attn = 0, op_expand = 0; - - int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group, - const Config& cfg, const Wire& wire, const char* source) { - g = geom; - c = cfg; - w = wire; - layer = l; - kv = group; - if (!b || !source || !group || c.heads < 1 || c.blocks < 1 || !w.q || !w.q_latent || - !w.attn_latent || !w.out || !w.selected || !w.length || w.q == w.q_latent || - w.q_latent == w.attn_latent || w.attn_latent == w.out || c.latent_dim != 512 || - c.head_dim != 256) - return RAD_E_INVAL; - RAD_ARCH_TRY(rad_bind_layer_kv(b, l, group)); - const char* name = nm.f("blk.%d.attn_kv_b.weight", l); - RAD_ARCH_TRY(map_copy(b, name, source)); - // The conversion recipe decodes this small projection only. - projection = decl_w(b, name, RAD_BF16, { c.heads * 2 * c.head_dim, c.latent_dim }, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); - if (!projection) return RAD_E_INVAL; - op_absorb = rw( - b, - RAD_OP(b, "mla_project", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), - RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), - RAD_STR("mode", "absorb"), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(projection)), - { w.q }, { w.q_latent }); - op_attn = - rw(b, - RAD_OP(b, "mla_attn", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("latent_dim", c.latent_dim), - RAD_INT("heads", c.heads), RAD_INT("blocks", c.blocks), - RAD_INT("block_size", 4), - RAD_F64("scale", 1.0 / std::sqrt((double)c.head_dim)), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { w.q_latent, w.selected, w.length }, { w.attn_latent }); - if (!op_attn || rad_kv_block_size(b, group) != 4) return RAD_E_INVAL; - op_expand = rw( - b, - RAD_OP(b, "mla_project", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("heads", c.heads), - RAD_INT("head_dim", c.head_dim), RAD_INT("latent_dim", c.latent_dim), - RAD_STR("mode", "expand"), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(projection)), - { w.attn_latent }, { w.out }); - return op_absorb && op_attn && op_expand ? RAD_OK : RAD_E_INVAL; - } - void step(RadCtx* ctx, int64_t rows) const { - RAD_ISSUE_N(ctx, op_absorb, rows, brows(w.q, rows), RAD_W(projection), - brows(w.q_latent, rows)); - RAD_ISSUE_N(ctx, op_attn, rows, brows(w.q_latent, rows), kv_cache(kv, layer), - brows(w.selected, rows), brows(w.length, rows), brows(w.attn_latent, rows)); - RAD_ISSUE_N(ctx, op_expand, rows, brows(w.attn_latent, rows), RAD_W(projection), - brows(w.out, rows)); - } -}; -} -} // namespace rad::arch -#endif diff --git a/arch/common/rad_glm_tp.h b/arch/common/rad_glm_tp.h new file mode 100644 index 00000000..52ceab6b --- /dev/null +++ b/arch/common/rad_glm_tp.h @@ -0,0 +1,103 @@ +/* GLM-5.3's tensor parallelism in one place: what a rank's shard of the model is, from which step + * size a replicated piece of work splits over the ranks instead, and the column split of a + * replicated F32 projection. + * + * The residual stream is replicated (spec.md §9). Two kinds of split share the ranks' work: + * + * heads the MLA and KDA heads, with them the rows of their projections, the KDA state and + * the convolution history; the experts' and the dense feed-forward's width + * (`heads`, `kda_width`, `expert_width`, `dense_width`); joined by an all_reduce + * columns a replicated F32 projection's output columns (SplitF32Proj), or the mHC read's + * input chunks (ManifoldConn); joined by an all_gather, bit for bit the replicated + * computation */ +#ifndef RAD_GLM_TP_H +#define RAD_GLM_TP_H +#include "rad_arch.h" + +namespace rad { +namespace arch { +struct GlmTp { + /* The model's widths a rank's shard divides: 64 heads of 128 (KDA) and 256 (MLA), experts of + * 2048 and a dense feed-forward of 12288. */ + static constexpr int64_t kHeads = 64, kKdaDim = 128, kMlaDim = 256, kExpertFF = 2048, + kDenseFF = 12288; + static bool world_ok(int world) { return world == 1 || world == 2 || world == 4 || world == 8; } + static int64_t heads(int world) { return kHeads / world; } + static int64_t kda_width(int world) { return heads(world) * kKdaDim; } + static int64_t mla_width(int world) { return heads(world) * kMlaDim; } + static int64_t expert_width(int world) { return kExpertFF / world; } + static int64_t dense_width(int world) { return kDenseFF / world; } + + /* Rows from which a replicated piece of work splits over the ranks. Below it, as in decode, + * the collective's latency outweighs the saved arithmetic and every rank runs the replicated + * form. */ + static constexpr int64_t kSplitRows = 256; + + /* The all_reduce of a replicated 4096-wide bf16 row over the ranks: the embedding's (exact) + * and each head-split block's (the deployment's wire). */ + static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) { + if (g.world == 1) return 0; + return rw(b, + RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4096, g.max_tok * 4096), + RAD_STR("dtype", "bf16"), + RAD_INT("exact", exact ? 1 : g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + { x }, { x }); + } +}; + +/* The split's ops are declared whatever the step size, and each gather's message as a range of + * rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph + * with the same fixed parameters. + * + * A replicated [n, k] F32 projection computed column-split: rank r runs the same gemm_nt_f32 on + * rows [r*n/world, (r+1)*n/world) of the weight and a row-interleaved all_gather lays the slices + * out as the full [M, n]. The kernel computes every output column independently of n and the + * gather moves bytes, so each value is bit-identical to the replicated projection's. */ +struct SplitF32Proj { + rad_buf part = 0; + rad_op op_part = 0, op_gather = 0; + int64_t cols = 0, k = 0, min_rows = 0, first_col = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n, + int64_t width, rad_weight weight, rad_buf input, rad_buf output) { + min_rows = GlmTp::kSplitRows; + if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) { + min_rows = 0; + return RAD_OK; + } + cols = n / g.world; + k = width; + first_col = g.rank * cols; + part = decl_b(b, nm.f("%s.part", name), RAD_F32, { rows, cols }); + op_part = rw(b, + RAD_OP(b, "gemm_nt_f32", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", cols), RAD_INT("K", k), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(weight)), + { input }, { part }); + op_gather = rw( + b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", cols, rows * cols), + RAD_STR("dtype", "f32"), RAD_INT("row", cols)), + RAD_NOWEIGHTS), + { part }, { output }); + return part && op_part && op_gather ? RAD_OK : RAD_E_INVAL; + } + bool takes(int64_t rows) const { return min_rows && rows >= min_rows; } + void step(RadCtx* ctx, int64_t rows, RadOperand input, rad_weight weight, + RadOperand output) const { + RadOperand slice = RAD_W(weight); + slice.offset = first_col * k; + slice.rows = cols; + RAD_ISSUE_N(ctx, op_part, rows, input, slice, brows(part, rows)); + RAD_ISSUE_N(ctx, op_gather, rows * cols, brows(part, rows), output); + } +}; +} +} // namespace rad::arch +#endif diff --git a/arch/common/rad_tp_split.h b/arch/common/rad_tp_split.h deleted file mode 100644 index 68a92125..00000000 --- a/arch/common/rad_tp_split.h +++ /dev/null @@ -1,65 +0,0 @@ -/* GLM's replicated F32 work split over the tensor-parallel ranks: each rank computes a disjoint - * part with the replicated kernel's own arithmetic and an all_gather moves the parts to every rank, - * so every value is bit-identical to the replicated computation's. */ -#ifndef RAD_TP_SPLIT_H -#define RAD_TP_SPLIT_H -#include "rad_arch.h" - -namespace rad { -namespace arch { -/* Rows from which a replicated F32 projection splits its columns over the ranks. Below it the - * collective's latency outweighs the saved arithmetic, so decode keeps the replicated form. */ -constexpr int64_t kGlmTpSplitRows = 256; - -/* The split's ops are declared whatever the step size, and each gather's message as a range of - * rows: the engine's arena levels declare again at a smaller max_tok and must get the same graph - * with the same fixed parameters. - * - * A replicated [n, k] F32 projection computed column-split: rank r runs the same gemm_nt_f32 on - * rows [r*n/world, (r+1)*n/world) of the weight and a row-interleaved all_gather lays the slices - * out as the full [M, n]. The kernel computes every output column independently of n and the - * gather moves bytes, so each value is bit-identical to the replicated projection's. */ -struct SplitF32Proj { - rad_buf part = 0; - rad_op op_part = 0, op_gather = 0; - int64_t cols = 0, k = 0, min_rows = 0, first_col = 0; - - int declare(RadBuilder* b, Names& nm, const Geom& g, const char* name, int64_t rows, int64_t n, - int64_t width, rad_weight weight, rad_buf input, rad_buf output) { - min_rows = kGlmTpSplitRows; - if (g.world < 2 || n % g.world || (n / g.world * 4) % 16) { - min_rows = 0; - return RAD_OK; - } - cols = n / g.world; - k = width; - first_col = g.rank * cols; - part = decl_b(b, nm.f("%s.part", name), RAD_F32, { rows, cols }); - op_part = rw(b, - RAD_OP(b, "gemm_nt_f32", - RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", cols), RAD_INT("K", k), - RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(weight)), - { input }, { part }); - op_gather = rw( - b, - RAD_OP(b, "all_gather", - RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", cols, rows * cols), - RAD_STR("dtype", "f32"), RAD_INT("row", cols)), - RAD_NOWEIGHTS), - { part }, { output }); - return part && op_part && op_gather ? RAD_OK : RAD_E_INVAL; - } - bool takes(int64_t rows) const { return min_rows && rows >= min_rows; } - void step(RadCtx* ctx, int64_t rows, RadOperand input, rad_weight weight, - RadOperand output) const { - RadOperand slice = RAD_W(weight); - slice.offset = first_col * k; - slice.rows = cols; - RAD_ISSUE_N(ctx, op_part, rows, input, slice, brows(part, rows)); - RAD_ISSUE_N(ctx, op_gather, rows * cols, brows(part, rows), output); - } -}; -} -} // namespace rad::arch -#endif diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index 1e8c394f..73dd4db6 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -1,16 +1,35 @@ -/* GLM-5.3-Flash: four mHC streams, KDA/latent MLA, mixed Quark weights, - * width-sharded routed experts and a native serial next-token decoder. - * This plugin uses only the public ABI and the installed common headers. */ -#include +/* glm5next -- GLM-5.3-Flash (`model_type: glm5_next`) from AMD's Quark MXFP4 export: four mHC + * residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers behind a DSA indexer, + * 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 + * scales, each weight served as the container stores it; its MTP layer is a serial drafter. + * docs/ARCHITECTURES.md describes the model and its traps. + * + * The blocks live in arch/common (installed as ), one a file: + * + * rad_block_glm_mhc.h ManifoldConn the four-stream residual read and write + * rad_block_glm_kda.h GlmKda the 34 linear layers, KdaState their recurrence + * rad_block_glm_mla.h GlmMla the 11 sparse MLA layers, MlaLatent their core + * rad_block_glm_indexer.h GlmIndexer the DSA indexer, DsaCache its key cache and selection + * rad_block_glm_router.h GlmRouter the correction-bias router (through MoeFP8) + * rad_block_glm_mtp.h GlmMtp the draft head around the plugin's layer 45 + * rad_glm_tp.h GlmTp the shards and the split threshold + * + * This file declares the buffers the blocks share, places the blocks and issues the step's + * order. Declaration order is liveness (the buffer plan takes lifetimes from it) and the issue + * order is the recorded pass, so both are kept as they read here. This plugin uses only the + * public ABI and the installed common headers. */ +#include #include #include #include +#include #include #include #include namespace glm5next { using namespace rad::arch; + struct Layer { bool full = false, draft = false; ManifoldConn attn_hc{}, ffn_hc{}; @@ -20,17 +39,17 @@ struct Layer { GlmIndexer index{}; MlpFP8 dense{}; MoeFP8 moe{}; - rad_op residual = 0; }; struct Model { - Names nm{}, dnm{ "mtp" }; + Names nm{}; Geom g{}; std::vector layers; - Layer draft{}; rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0; + /* The streams and the step's stream-wide buffers. */ rad_buf h0 = 0, h1 = 0, x = 0, y = 0, post = 0, comb = 0, final_hidden = 0, logit_input = 0, logits = 0; - ActFP8 act{}, ff{}; + ActFP8 act{}; + /* The blocks' wires: one set of activations, shared by every layer of a kind. */ GlmKda::Wire kw{}; GlmMla::Wire aw{}; GlmIndexer::Wire iw{}; @@ -38,11 +57,10 @@ struct Model { MoeFP8::Wire mw{}; rad_weight token = 0, head = 0, final_gain = 0; rad_op embed = 0, embed_ar = 0, expand = 0, contract = 0, norm = 0, gather = 0, head_op = 0; - rad_buf mtp_x = 0, mtp_h = 0, mtp_e = 0, mtp_concat = 0, mtp_final = 0; - rad_weight en = 0, hn = 0, eh = 0, mnorm = 0; - rad_op mprev = 0, membed = 0, membed_ar = 0, men = 0, mhn = 0, meh = 0, mnorm_op = 0, - mselect = 0, mback = 0, mcopy = 0, mhead = 0; + /* The draft head and its layer, declared only when the deployment speculates. */ bool have_mtp = false; + GlmMtp mtp{}; + Layer draft{}; }; static std::unique_ptr models[MAX_RANKS]; static thread_local std::unique_ptr probe_model; @@ -52,21 +70,10 @@ static int64_t cfg(const RadModelMeta* m, const char* key, int64_t fallback) { std::snprintf(nested, sizeof nested, "text_config.%s", key); return rad_meta_geti(m, key, rad_meta_geti(m, nested, fallback)); } -static rad_op reduce(RadBuilder* b, const Geom& g, rad_buf x, bool exact = false) { - if (g.world == 1) return 0; - return rw(b, - RAD_OP(b, "all_reduce", - RAD_PARAMS( - RAD_INT("world_size", g.world), RAD_RANGE("numel", 4096, g.max_tok * 4096), - RAD_STR("dtype", "bf16"), RAD_INT("exact", exact ? 1 : g.wire_exact), - RAD_INT("min_bytes", g.wire_min_bytes)), - RAD_NOWEIGHTS), - { x }, { x }); -} -static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y, int64_t n = 4096) { +static rad_op copy(RadBuilder* b, const Geom& g, rad_buf x, rad_buf y) { return rw(b, RAD_OP(b, "cast", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), RAD_NOWEIGHTS), { x }, { y }); @@ -79,116 +86,184 @@ static rad_op norm(RadBuilder* b, const Geom& g, rad_weight w, rad_buf x, rad_bu RAD_WEIGHTS(w)), { x }, { y }); } -static int buffers(RadBuilder* b, Model& m) { + +/* ------------------------------------------------------------------ the shared activations */ +static int stream_buffers(RadBuilder* b, Model& m) { auto& g = m.g; auto& nm = m.nm; - const int64_t T = g.max_tok, W = 8192 / g.world, F = 2048 / g.world; - auto bf = [&](const char* n, int64_t width) { - return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); - }; - auto a = [&](ActFP8& v, const char* n, int64_t width) { - v.x = bf(n, width); - return v.declare_qs(b, nm, g, n, width); - }; - m.h0 = bf("manifold", 16384); - m.h1 = bf("manifold_mid", 16384); - m.x = bf("collapsed", 4096); - m.y = bf("attn_delta", 4096); + const int64_t T = g.max_tok; + m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 }); + m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 }); + m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 }); + m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 }); m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 }); m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 }); - RAD_ARCH_TRY(a(m.act, "normalized", 4096)); + m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 }); + RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normalized", 4096)); m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, 4096 }, RAD_BUF_PERSIST); m.logit_input = decl_b(b, nm.f("logit_input"), RAD_BF16, { g.max_logit_rows, 4096 }); m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab }); - RAD_ARCH_TRY(rad_declare_logits(b, m.logits)); - m.kw.input = m.act.x; - m.kw.out = m.y; - m.kw.forget_low = bf("forget_low", 128); - m.kw.gate_low = bf("gate_low", 128); - m.kw.core.qkv = bf("qkv", 3 * W); - m.kw.core.conv = bf("convolved", 3 * W); - m.kw.core.a = bf("forget", W); - m.kw.core.beta = bf("beta", 64 / g.world); - m.kw.core.gate = bf("gate", W); - m.kw.core.out = bf("recurrent_out", W); - m.aw.input = m.act; - m.aw.q_raw = bf("q_raw", 1536); - m.aw.kv_raw = bf("kv_raw", 512); - RAD_ARCH_TRY(a(m.aw.q_low, "q_low", 1536)); - m.aw.latent = bf("latent", 512); - m.aw.out = m.y; - m.aw.core.q = bf("query", 16384 / g.world); - m.aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, 64 / g.world, 512 }); - m.aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, 64 / g.world, 512 }); - RAD_ARCH_TRY(a(m.aw.attn, "expanded", 16384 / g.world)); - m.aw.core.out = m.aw.attn.x; - m.aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { T, 513 }); - m.aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { T }); - const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1; - m.iw.input = m.act.x; - m.iw.q_low = m.aw.q_low.x; - m.iw.q_wide = bf("index_query", 4096); - m.iw.kg_raw = bf("index_key_gate", 256); - auto& iw = m.iw.cache; - iw.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 }); - iw.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { T * 32, 128 }); - iw.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { T * 32, 1 }); - iw.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { T, 32 }); - iw.kg = bf("index_normalized_key_gate", 256); - iw.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 }); - iw.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work }); - iw.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work }); - iw.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs }); - iw.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 }); - iw.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 }); - iw.score = decl_b(b, nm.f("index_scores"), RAD_F32, { T, blocks }); - iw.selected = m.aw.core.selected; - iw.length = m.aw.core.length; - iw.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T }); - m.dw.x = m.x; - m.dw.h = m.act; - m.dw.gate_up = bf("dense_gate_up", 2 * g.n_ff); - RAD_ARCH_TRY(a(m.dw.ffn, "dense_ff", g.n_ff)); - const int64_t R = T; - m.mw.x = m.x; - m.mw.h = m.act; - m.mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 }); - m.mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 }); - m.mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 }); - m.mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 }); - m.mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }); - m.mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { R * 8 }); - m.mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { R * 8 }); - m.mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { R * 8, 2 * F }); - m.mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { R * 8, F }); - RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "expert_ff", F, R * 8)); - m.mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { R * 8, 4096 }); - m.mw.sgu = bf("shared_gate_up", 2 * F); - RAD_ARCH_TRY(a(m.mw.sff, "shared_ff", F)); - m.mw.sout = bf("shared_out", 4096); - m.mw.sgate = bf("shared_one", 1); + return rad_declare_logits(b, m.logits); +} +static int kda_buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + const int64_t T = g.max_tok, W = GlmTp::kda_width(g.world); + auto bf = [&](const char* n, int64_t width) { + return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); + }; + auto& kw = m.kw; + kw.input = m.act.x; + kw.out = m.y; + kw.forget_low = bf("forget_low", 128); + kw.gate_low = bf("gate_low", 128); + kw.core.qkv = bf("qkv", 3 * W); + kw.core.conv = bf("convolved", 3 * W); + kw.core.a = bf("forget", W); + kw.core.beta = bf("beta", GlmTp::heads(g.world)); + kw.core.gate = bf("gate", W); + kw.core.out = bf("recurrent_out", W); return RAD_OK; } +/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. */ +static int mla_buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + const int64_t T = g.max_tok, H = GlmTp::heads(g.world), Q = GlmTp::mla_width(g.world); + auto bf = [&](const char* n, int64_t width) { + return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); + }; + auto& aw = m.aw; + aw.input = m.act; + aw.q_raw = bf("q_raw", 1536); + aw.kv_raw = bf("kv_raw", 512); + aw.q_low.x = bf("q_low", 1536); + RAD_ARCH_TRY(aw.q_low.declare_qs(b, nm, g, "q_low", 1536)); + aw.latent = bf("latent", 512); + aw.out = m.y; + aw.core.q = bf("query", Q); + aw.core.q_latent = decl_b(b, nm.f("q_latent"), RAD_BF16, { T, H, 512 }); + aw.core.attn_latent = decl_b(b, nm.f("attn_latent"), RAD_BF16, { T, H, 512 }); + aw.attn.x = bf("expanded", Q); + RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "expanded", Q)); + aw.core.out = aw.attn.x; + aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { T, 513 }); + aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { T }); + return RAD_OK; +} +static int indexer_buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + const int64_t T = g.max_tok; + const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1; + auto bf = [&](const char* n, int64_t width) { + return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); + }; + auto& iw = m.iw; + iw.input = m.act.x; + iw.q_low = m.aw.q_low.x; + iw.q_wide = bf("index_query", 4096); + iw.kg_raw = bf("index_key_gate", 256); + auto& c = iw.cache; + c.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 }); + c.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { T * 32, 128 }); + c.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { T * 32, 1 }); + c.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { T, 32 }); + c.kg = bf("index_normalized_key_gate", 256); + c.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 }); + c.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work }); + c.bpos = decl_b(b, nm.f("pool_pos"), RAD_I32, { work }); + c.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs }); + c.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 }); + c.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 }); + c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { T, blocks }); + c.selected = m.aw.core.selected; + c.length = m.aw.core.length; + c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T }); + return RAD_OK; +} +static int ffn_buffers(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + const int64_t T = g.max_tok, F = GlmTp::expert_width(g.world); + auto bf = [&](const char* n, int64_t width) { + return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); + }; + auto& dw = m.dw; + dw.x = m.x; + dw.h = m.act; + dw.gate_up = bf("dense_gate_up", 2 * g.n_ff); + dw.ffn.x = bf("dense_ff", g.n_ff); + RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff)); + auto& mw = m.mw; + mw.x = m.x; + mw.h = m.act; + mw.logits = decl_b(b, nm.f("router_logits"), RAD_F32, { T, 288 }); + mw.ids = decl_b(b, nm.f("expert_ids"), RAD_I32, { T, 8 }); + mw.ew = decl_b(b, nm.f("expert_weights"), RAD_F32, { T, 8 }); + mw.eoff = decl_b(b, nm.f("expert_offsets"), RAD_I32, { 289 }); + mw.ecnt = decl_b(b, nm.f("expert_counts"), RAD_I32, { 288 }); + mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * 8 }); + mw.inv = decl_b(b, nm.f("expert_inverse"), RAD_I32, { T * 8 }); + mw.egu = decl_b(b, nm.f("expert_gate_up"), RAD_BF16, { T * 8, 2 * F }); + mw.eff.x = decl_b(b, nm.f("expert_ff"), RAD_BF16, { T * 8, F }); + RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * 8)); + mw.edn = decl_b(b, nm.f("expert_down"), RAD_BF16, { T * 8, 4096 }); + mw.sgu = bf("shared_gate_up", 2 * F); + mw.sff.x = bf("shared_ff", F); + RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", F)); + mw.sout = bf("shared_out", 4096); + mw.sgate = bf("shared_one", 1); + return RAD_OK; +} +static int kv_groups(RadBuilder* b, Model& m) { + auto& g = m.g; + auto& nm = m.nm; + RadKVGroupDecl d{}; + d.kind = RAD_KV_FULL; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.head_dim = 256; + m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d); + d = {}; + d.kind = RAD_KV_LINEAR; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.state_dim[0] = 4 + g.max_spec; + d.state_dim[1] = 256; + m.tail = rad_decl_kv_group(b, nm.f("kv_index_tail"), &d); + d = {}; + d.kind = RAD_KV_LINEAR; + d.dtype = RAD_F32; + d.n_head_kv = GlmTp::heads(g.world); + d.state_dim[0] = d.state_dim[1] = 128; + m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d); + d = {}; + d.kind = RAD_KV_CONV; + d.dtype = RAD_BF16; + d.n_head_kv = 1; + d.head_dim = 3 * GlmTp::kda_width(g.world); + d.conv_width = 4; + m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d); + // The index group is declared by the first indexer, right before its cache consumer. + return m.latent && m.tail && m.state && m.conv ? RAD_OK : RAD_E_INVAL; +} + +/* ------------------------------------------------------------------ one layer */ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool draft) { const auto& g = m.g; lay.draft = draft; lay.full = draft || l % 4 == 3; const char* pre = nm.ckpt("model.language_model.layers.%d", l); const char* ap = nm.ckpt("%s.self_attn", pre); - rad_buf input = draft ? m.mtp_x : m.x; + rad_buf input = draft ? m.mtp.x : m.x; + ManifoldConn::Config hc; + hc.eps = g.eps; if (!draft) { - ManifoldConn::Config hc; - hc.eps = g.eps; ManifoldConn::Wire a{ m.h0, m.x, m.y, m.h1, m.post, m.comb }; - ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb }; ManifoldConn::Src as{ nm.ckpt("%s.hc_attn_fn", pre), nm.ckpt("%s.hc_attn_scale", pre), nm.ckpt("%s.hc_attn_base", pre) }; - ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre), - nm.ckpt("%s.hc_ffn_base", pre) }; RAD_ARCH_TRY(lay.attn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_attn", l), hc, a, as, true)); - // Declare ffn mHC after the attention below: declaration order is liveness. - (void)f; - (void)fs; } const char* nn = nm.f("blk.%d.attn_norm.weight", l); RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre))); @@ -210,29 +285,15 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra nm.ckpt("%s.dt_bias", ap), nm.ckpt("%s.o_norm.weight", ap) }; RAD_ARCH_TRY(lay.kda.declare(b, nm, g, l, m.kw, ap, s, m.state, m.conv)); } + // The ffn connection is declared after the attention's post: declaration order is liveness. if (!draft) { RAD_ARCH_TRY(lay.attn_hc.declare_post(b)); - ManifoldConn::Config hc; - hc.eps = g.eps; ManifoldConn::Wire f{ m.h1, m.x, m.act.x, m.h0, m.post, m.comb }; ManifoldConn::Src fs{ nm.ckpt("%s.hc_ffn_fn", pre), nm.ckpt("%s.hc_ffn_scale", pre), nm.ckpt("%s.hc_ffn_base", pre) }; RAD_ARCH_TRY(lay.ffn_hc.declare(b, nm, g, l, nm.f("blk.%d.hc_ffn", l), hc, f, fs, true)); } else { - lay.residual = rw(b, - RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { m.mtp_x, m.y }, { m.mtp_x }); - // All history rows fill the draft cache; only proposal rows need its FFN. - m.mselect = rw(b, - RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", 4096), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { m.mtp_x }, { m.mtp_h }); - m.mback = copy(b, g, m.mtp_h, m.mtp_x); + RAD_ARCH_TRY(m.mtp.declare_join(b, m.y)); } if (l < 3) { auto w = m.dw; @@ -254,7 +315,7 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra s.shared = nm.ckpt("%s.mlp.shared_experts", pre); s.cfg.n_expert = s.cfg.n_expert_all = 288; s.cfg.top_k = 8; - s.cfg.n_ff_exp = s.cfg.n_ff_shared = 2048 / g.world; + s.cfg.n_ff_exp = s.cfg.n_ff_shared = GlmTp::expert_width(g.world); s.cfg.rows = g.max_tok; s.cfg.sigmoid_router = 1; s.cfg.route_scale = 2.5; @@ -263,8 +324,8 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra s.cfg.router_fuse = 1; s.cfg.swiglu_quant = 1; for (int q = 0; q < 2; ++q) { - s.cfg.ff_lo[q] = g.rank * (2048 / g.world); - s.cfg.ff_hi[q] = (g.rank + 1) * (2048 / g.world); + s.cfg.ff_lo[q] = g.rank * GlmTp::expert_width(g.world); + s.cfg.ff_hi[q] = (g.rank + 1) * GlmTp::expert_width(g.world); } RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, s, &s.cfg)); RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, w, s, false, draft)); @@ -272,29 +333,16 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra if (!draft) RAD_ARCH_TRY(lay.ffn_hc.declare_post(b)); return RAD_OK; } -static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { - if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS) - return RAD_E_INVAL; - const int world = ctx->world_size ? ctx->world_size : 1; - if ((world != 1 && world != 2 && world != 4 && world != 8) || meta->n_embd != 4096 || - meta->n_layers != 45 || meta->n_vocab != 154880 || - cfg(meta, "num_nextn_predict_layers", 0) != 1 || cfg(meta, "hc_mult", 0) != 4 || - cfg(meta, "n_routed_experts", 0) != 288 || cfg(meta, "index_topk", 0) != 2048 || - ctx->max_spec > 31 || (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16)) - return RAD_E_UNSUPPORTED; - auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank]; - slot = std::make_unique(); - auto& m = *slot; - auto& g = m.g; - m.nm = Names(ctx->scope); - auto& nm = m.nm; + +/* ------------------------------------------------------------------ declare */ +static int geometry(Geom& g, const RadModelMeta* meta, const RadBuildCtx* ctx, int world) { g.n_layer = 45; g.n_embd = 4096; - g.head_dim = 256; - g.n_head_all = g.n_head_kv_all = 64; - g.n_head = g.n_head_kv = 64 / world; - g.n_ff_all = 12288; - g.n_ff = 12288 / world; + g.head_dim = GlmTp::kMlaDim; + g.n_head_all = g.n_head_kv_all = GlmTp::kHeads; + g.n_head = g.n_head_kv = GlmTp::heads(world); + g.n_ff_all = GlmTp::kDenseFF; + g.n_ff = GlmTp::dense_width(world); g.n_vocab_all = 154880; g.n_vocab = shard_extent(154880, world, ctx->rank); g.vocab_off = shard_begin(154880, world, ctx->rank); @@ -311,34 +359,31 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.eps = meta->rms_eps; g.wire_exact = !ctx->tp_wire_lossy; g.wire_min_bytes = ctx->tp_wire_min_bytes; - if (g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0) return RAD_E_INVAL; - RAD_ARCH_TRY(buffers(b, m)); - RadKVGroupDecl d{}; - d.kind = RAD_KV_FULL; - d.dtype = RAD_BF16; - d.n_head_kv = 1; - d.head_dim = 256; - m.latent = rad_decl_kv_group(b, nm.f("kv_latent"), &d); - d = {}; - d.kind = RAD_KV_LINEAR; - d.dtype = RAD_BF16; - d.n_head_kv = 1; - d.state_dim[0] = 4 + g.max_spec; - d.state_dim[1] = 256; - m.tail = rad_decl_kv_group(b, nm.f("kv_index_tail"), &d); - d = {}; - d.kind = RAD_KV_LINEAR; - d.dtype = RAD_F32; - d.n_head_kv = 64 / world; - d.state_dim[0] = d.state_dim[1] = 128; - m.state = rad_decl_kv_group(b, nm.f("kv_kda"), &d); - d = {}; - d.kind = RAD_KV_CONV; - d.dtype = RAD_BF16; - d.n_head_kv = 1; - d.head_dim = 3 * 8192 / world; - d.conv_width = 4; - m.conv = rad_decl_kv_group(b, nm.f("kv_kda_conv"), &d); + return g.max_tok < 1 || g.max_ctx < 1 || g.max_seqs < 1 || g.eps <= 0 ? RAD_E_INVAL : RAD_OK; +} +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS) + return RAD_E_INVAL; + const int world = ctx->world_size ? ctx->world_size : 1; + if (!GlmTp::world_ok(world) || meta->n_embd != 4096 || meta->n_layers != 45 || + meta->n_vocab != 154880 || cfg(meta, "num_nextn_predict_layers", 0) != 1 || + cfg(meta, "hc_mult", 0) != 4 || cfg(meta, "n_routed_experts", 0) != 288 || + cfg(meta, "index_topk", 0) != 2048 || ctx->max_spec > 31 || + (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16)) + return RAD_E_UNSUPPORTED; + auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank]; + slot = std::make_unique(); + auto& m = *slot; + auto& g = m.g; + m.nm = Names(ctx->scope); + auto& nm = m.nm; + RAD_ARCH_TRY(geometry(g, meta, ctx, world)); + RAD_ARCH_TRY(stream_buffers(b, m)); + RAD_ARCH_TRY(kda_buffers(b, m)); + RAD_ARCH_TRY(mla_buffers(b, m)); + RAD_ARCH_TRY(indexer_buffers(b, m)); + RAD_ARCH_TRY(ffn_buffers(b, m)); + RAD_ARCH_TRY(kv_groups(b, m)); RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.language_model.embed_tokens.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"))); @@ -357,7 +402,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(m.token)), {}, { m.x }); - m.embed_ar = reduce(b, g, m.x, true); + m.embed_ar = GlmTp::reduce(b, g, m.x, true); m.expand = copy(b, g, m.x, m.h0); m.layers.resize(45); for (int l = 0; l < 45; ++l) RAD_ARCH_TRY(layer(b, m, m.layers[l], nm, l, false)); @@ -382,63 +427,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_WEIGHTS(m.head)), { m.logit_input }, { m.logits }); if (g.max_spec > 0) { - auto& dn = m.dnm; - m.mtp_x = decl_b(b, dn.f("x"), RAD_BF16, { g.max_tok, 4096 }); - m.mtp_h = decl_b(b, dn.f("hidden"), RAD_BF16, { g.max_tok, 4096 }, RAD_BUF_PERSIST); - m.mtp_e = decl_b(b, dn.f("embedding"), RAD_BF16, { g.max_tok, 4096 }); - m.mtp_concat = decl_b(b, dn.f("concat"), RAD_BF16, { g.max_tok, 8192 }); - m.mtp_final = decl_b(b, dn.f("final"), RAD_BF16, { g.max_tok, 4096 }); - const char* pre = "model.language_model.layers.45"; - auto weight = [&](const char* n, const char* src) { - const char* name = dn.f("%s", n); - if (map_copy(b, name, dn.ckpt("%s.%s", pre, src)) < 0) return (rad_weight)0; - return decl_w(b, name, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, - grp_layer(45)); - }; - m.en = weight("enorm.weight", "enorm.weight"); - m.hn = weight("hnorm.weight", "hnorm.weight"); - m.mnorm = weight("output_norm.weight", "shared_head.norm.weight"); - RAD_ARCH_TRY(map_copy(b, dn.f("eh_proj.weight"), dn.ckpt("%s.eh_proj.weight", pre))); - m.eh = decl_w(b, dn.f("eh_proj.weight"), RAD_BF16, { 4096, 8192 }, RAD_ACCESS_PER_TOKEN, - RAD_SHARD_NONE, grp_layer(45)); - m.mprev = rw(b, - RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), - RAD_STR("dtype", "bf16")), - RAD_NOWEIGHTS), - { m.final_hidden }, { m.mtp_h }); - m.membed = rw(b, - RAD_OP(b, "embed_lookup", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", 4096), - RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), - RAD_INT("vocab_offset", g.vocab_off)), - RAD_WEIGHTS(m.token)), - {}, { m.mtp_e }); - m.membed_ar = reduce(b, g, m.mtp_e, true); - m.men = norm(b, g, m.en, m.mtp_e, m.mtp_concat); - m.mhn = norm(b, g, m.hn, m.mtp_h, m.mtp_concat); - m.meh = rw(b, - RAD_OP(b, "gemm_nt", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 4096), - RAD_INT("K", 8192), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(m.eh)), - { m.mtp_concat }, { m.mtp_x }); - RAD_ARCH_TRY(layer(b, m, m.draft, dn, 45, true)); - m.mnorm_op = norm(b, g, m.mnorm, m.mtp_x, m.mtp_final); - m.mcopy = copy(b, g, m.mtp_final, m.mtp_h); - m.mhead = - rw(b, - RAD_OP(b, "logits_gemm", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab), - RAD_INT("n_embd", 4096), RAD_STR("dtype", "bf16")), - RAD_WEIGHTS(m.head)), - { m.mtp_h }, { m.logits }); - RadDrafterDecl dd{}; - dd.name = "mtp"; - dd.kind = RAD_DRAFT_SERIAL; - dd.depth = g.max_spec; - dd.mask_token = -1; - RAD_ARCH_TRY(rad_declare_drafter(b, &dd)); + GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head }; + RAD_ARCH_TRY(m.mtp.declare_inputs(b, g, tw)); + RAD_ARCH_TRY(layer(b, m, m.draft, m.mtp.nm, 45, true)); + RAD_ARCH_TRY(m.mtp.declare_head(b)); m.have_mtp = true; } rad_note(b, @@ -446,6 +438,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c world, m.have_mtp ? "enabled" : "disabled"); return RAD_OK; } + +/* ------------------------------------------------------------------ step */ static void attention(RadCtx* c, Layer& l, const RadBatch* batch) { l.norm.step(c, batch->n_tok); if (l.full) { @@ -455,6 +449,24 @@ static void attention(RadCtx* c, Layer& l, const RadBatch* batch) { } else l.kda.step(c, batch); } +static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) { + if (!m.have_mtp || batch->draft_pass == 1) { + rad_step_fail(c, "GLM MTP pass is not declared or has invalid round 1"); + return; + } + const int64_t T = batch->n_tok; + m.mtp.step_inputs(c, batch); + auto& l = m.draft; + l.norm.step(c, T); + l.mla.prepare(c, batch); + l.index.step(c, batch); + // A history pass with no proposal row fills the draft caches and ends there. + if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return; + l.mla.finish(c, batch); + m.mtp.step_join(c, batch, m.y); + l.moe.step_rows(c, GlmMtp::head_rows(batch)); + m.mtp.step_head(c, batch); +} static void step(RadCtx* c, const RadBatch* batch) { auto& m = *models[rad_rank(c)]; const int64_t T = batch->n_tok; @@ -463,36 +475,7 @@ static void step(RadCtx* c, const RadBatch* batch) { return; } if (batch->draft_pass) { - if (!m.have_mtp || batch->draft_pass == 1) { - rad_step_fail(c, "GLM MTP pass is not declared or has invalid round 1"); - return; - } - if (batch->draft_pass < 0 && batch->n_out > 0) - RAD_ISSUE_N(c, m.mprev, batch->n_out, RAD_B(m.final_hidden), - praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.mtp_h, batch->n_out)); - RAD_ISSUE_N(c, m.membed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), - brows(m.mtp_e, T)); - if (m.membed_ar) RAD_ISSUE_N(c, m.membed_ar, T * 4096, brows(m.mtp_e, T), RAD_NONE); - RAD_ISSUE_N(c, m.men, T, brows(m.mtp_e, T), RAD_W(m.en), bcol(m.mtp_concat, 0, 4096, T)); - RAD_ISSUE_N(c, m.mhn, T, brows(m.mtp_h, T), RAD_W(m.hn), bcol(m.mtp_concat, 4096, 4096, T)); - RAD_ISSUE_N(c, m.meh, T, brows(m.mtp_concat, T), RAD_W(m.eh), brows(m.mtp_x, T)); - auto& l = m.draft; - l.norm.step(c, T); - l.mla.prepare(c, batch); - l.index.step(c, batch); - if (batch->draft_pass < 0 && batch->n_draft_out <= 0) return; - l.mla.finish(c, batch); - RAD_ISSUE_N(c, l.residual, T, brows(m.mtp_x, T), brows(m.y, T), brows(m.mtp_x, T)); - const int64_t L = batch->draft_pass < 0 ? batch->n_draft_out : T; - if (batch->draft_pass < 0) { - RAD_ISSUE_N(c, m.mselect, L, RAD_B(m.mtp_x), praw(batch->draft_out_ids, RAD_I32, L), - brows(m.mtp_h, L)); - RAD_ISSUE_N(c, m.mback, L, brows(m.mtp_h, L), brows(m.mtp_x, L)); - } - l.moe.step_rows(c, L); - RAD_ISSUE_N(c, m.mnorm_op, L, brows(m.mtp_x, L), RAD_W(m.mnorm), brows(m.mtp_final, L)); - RAD_ISSUE_N(c, m.mcopy, L, brows(m.mtp_final, L), brows(m.mtp_h, L)); - RAD_ISSUE_N(c, m.mhead, L, brows(m.mtp_h, L), RAD_W(m.head), brows(m.logits, L)); + draft_pass(c, m, batch); return; } RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T)); @@ -523,7 +506,7 @@ static void step(RadCtx* c, const RadBatch* batch) { } static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; - if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = 3; + if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth; out->shape_probe_ok = 1; return RAD_OK; } diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 5fd529f9..7cddba35 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -415,6 +415,19 @@ the plugin claims the empty descriptor and reads each weight's encoding from the mapped, so never converted, and an image request fails its step. The reference is SGLang's `glm5_next.py` and `glm5_next_nextn.py` at AMD's pinned commit 654df43. +The plugin is one file over blocks in `arch/common`, one block a file; it declares the buffers +the blocks share, places them and issues the step's order. + +| file | block | what | +|---|---|---| +| `rad_block_glm_mhc.h` | `ManifoldConn` | the four-stream residual's read and write | +| `rad_block_glm_kda.h` | `GlmKda`, `KdaState` | the 34 linear layers and their recurrence | +| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers and their absorbed core | +| `rad_block_glm_indexer.h` | `GlmIndexer`, `DsaCache` | the DSA indexer, its key cache and selection | +| `rad_block_glm_router.h` | `GlmRouter` | the correction-bias router, through `MoeFP8` | +| `rad_block_glm_mtp.h` | `GlmMtp` | the draft head around the plugin's layer 45 | +| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the split threshold, the column split of a replicated f32 projection | + ``` 45 layers, hidden 4096, vocab 154880 (embedding and lm_head separate, bf16) mHC: 4 residual streams, a 16384-wide row; 20 Sinkhorn passes, hc_eps 1e-6; the embedding is @@ -446,7 +459,7 @@ Traps: - **`comb` is indexed `[source, destination]`.** Each connection's write is `out[dst] = post[dst] * y + sum_src comb[src, dst] * h[src]`; the transpose has every shape valid and is another model. `out` must be a separate buffer: each output stream reads every - input stream (`rad_block_mhc.h`). + input stream (`rad_block_glm_mhc.h`). - **The router and the index head gates stay f32.** Both projections are f32 weights against a bf16 activation with f32 results (`gemm_nt_f32`), and the routing weights reach the gather as f32. Rounding any of them to bf16 changes which experts and which blocks are picked, and a @@ -504,9 +517,11 @@ The container holds 25845 weights, 171.32 GiB; at eight ranks each card holds 22 3 unless `--num-speculative-tokens` says otherwise (at most 31). Its history pass writes the draft layer's latent, index and tail for every row and runs its MoE on the proposal rows only. -**Tensor parallelism.** At 1, 2, 4 or 8 ranks; declare refuses any other. `arch_test` declares and -steps the whole plugin at 1, 4 and 8, and the connection, router and indexer splits at 1, 2, 4 -and 8. +**Tensor parallelism.** At 1, 2, 4 or 8 ranks; declare refuses any other. `tests/glm5next_test.cpp` +declares and steps the whole plugin at 1, 4 and 8, against pinned graph and step hashes at 1 and +8, the connection, router and index-gate splits at 1, 2, 4 and 8, each issue's operand count +against the loaded kernel libraries' schemas, and every declared weight against the served +container's names and encodings. - The routed and the shared experts split their 2048 width into equal contiguous slices, 256 a rank at eight; each rank computes its slice of every expert, and the block's all-reduce sums @@ -519,7 +534,7 @@ and 8. - The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact. - The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each connection's mHC projection of 24 x 16384) are replicated. From a pass of 256 rows - (`kGlmTpSplitRows`, `arch/common/rad_tp_split.h`), each rank computes a disjoint part + (`GlmTp::kSplitRows`; `SplitF32Proj` in `arch/common/rad_glm_tp.h`), each rank computes a disjoint part with the replicated kernel and an `all_gather` joins the parts, so every value is bit-identical: the router and the head gates split their output columns, the mHC projection its 16384-wide input into eight 2048-column chunks, whose partials `mhc_pre_finish` completes diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5482fc84..74a07b0b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,11 +10,12 @@ # fast every test with none of slow, gpu, oot and perf, set at the end of this file: the # inner loop (`ctest --preset fast`, or `ctest -L fast`) # -# arch_test does not link rad_core: it supplies its own recording fake of the declare-phase C ABI, -# so plugins are tested without depending on core/build/'s builder. With the archive linked, a new -# ABI call missing from the fake would pull in rad_builder.cpp.o and collide on every rad_decl_* -# symbol; without it the error is a single undefined reference. -set(RAD_TESTS_NO_CORE arch_test) +# arch_test and glm5next_test do not link rad_core: they supply their own recording fake of the +# declare-phase C ABI (arch_fakes.h), so plugins are tested without depending on core/build/'s +# builder. With the archive linked, a new ABI call missing from the fake would pull in +# rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a single +# undefined reference. +set(RAD_TESTS_NO_CORE arch_test glm5next_test) # fixture_test tests tools/kfixture.cpp and tools/opshapes.cpp (the seeded draw, the reduction and # the on-disk recording) directly, kbench_test tools/kbench_core.cpp (rad-kbench's rules), and @@ -273,10 +274,13 @@ if(TARGET abi_layout_test) endif() # arch_test reads libref's vocabulary from $RADIANCE_HOME/kernels to check that each architecture -# declares on it, so libref is built before it. -if(TARGET libref AND TARGET arch_test) - add_dependencies(arch_test libref) -endif() +# declares on it, and glm5next_test the loaded libraries' op schemas, so libref is built before +# them. +foreach(t arch_test glm5next_test) + if(TARGET libref AND TARGET ${t}) + add_dependencies(${t} libref) + endif() +endforeach() # kbench_mutant_test runs rad-kbench against the deliberately defective kernel libraries # (core/plugin/testplugin/kbmutant.cc) on the host backend, so it needs the tool, libref and the diff --git a/tests/arch_fakes.h b/tests/arch_fakes.h new file mode 100644 index 00000000..824e2eb3 --- /dev/null +++ b/tests/arch_fakes.h @@ -0,0 +1,1177 @@ +/* arch_fakes.h -- the recording builder, the run-phase fakes, the step lint and the fixtures the + * architecture tests share (arch_test.cpp, glm5next_test.cpp). + * + * No GPU, no model file, no core. With two-phase construction (spec §3) the whole model is known + * between declare and plan, so a unit test can check what a plugin declares. The fake builder + * records every decl_weight, decl_buffer, decl_op, buffer use and name-map call, and the fake RadCtx + * records every issue, so the run phase's order and operands are checked too. + * + * The fake is deliberately not core/build/'s RadBuilder: a defect there must not fail these tests, + * and a plugin that only works against one builder has an undeclared dependency. + * + * It defines the declare- and run-phase C ABI, so exactly one translation unit of a test binary + * includes it, and that binary does not link rad_core (tests/CMakeLists.txt, RAD_TESTS_NO_CORE). */ +#ifndef RAD_ARCH_FAKES_H +#define RAD_ARCH_FAKES_H + +#include "rad_test.h" + +#include "rad_builder.h" +#include "rad_device.h" +#include "rad_runtime.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* ==================================================================== the recording builder */ +namespace { + +struct RecParam { + std::string key; + int kind = 0; + long long ival = 0, ihi = 0; + double dval = 0.0; + std::string sval; +}; + +struct RecWeight { + std::string name; + RadWeightDecl d{}; + /* The uneven slice this weight was handed (rad_weight_shard_span), in the container's + * unsharded units, so tests can check which checkpoint rows each rank reads. Even shards have + * `span_set` false. */ + bool span_set = false; + int64_t span_lo = 0, span_hi = 0; + /* rad_weight_shard_span_parts, recorded likewise. */ + int n_part_spans = 0; + int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0}; + int64_t part_total[RAD_MAX_ROW_PARTS] = {0}; +}; +struct RecBuf { std::string name; RadBufDecl d{}; }; +struct RecOp { + std::string op; + std::vector p; + std::vector w; + std::vector reads, writes; + bool resolved = true; + bool uses_declared = false; /* rad_op_reads/writes were called */ +}; +struct RecMap { + std::string declared; + int mode = 0; + std::vector src; + int concat_dim = 0; +}; +struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; }; +struct RecIssue { + rad_op op = 0; + std::vector opd; + int64_t n = 0; + int lane = 0; /* the lane it was issued on (rad_lane) */ +}; +/* A rad_lane_join: `to` behind everything `from` issued before issue number `at`. */ +struct RecJoin { size_t at = 0; int from = 0, to = 0; }; + +} /* namespace */ + +struct RadBuilder { + std::vector weights; + std::vector bufs; + std::vector ops; + std::vector maps; + std::vector kv_groups; + std::vector> binds; + std::vector notes; + + /* Ops the fake kernel hierarchy refuses, to drive the fused-op fallback; and ops no loaded + * library declares (rad_op_declared), as without an optional library. */ + std::set refuse; + std::set undeclared; + /* When set, the only ops any loaded library declares (a CPU-only engine's: libref's + * vocabulary); every other op is undeclared. */ + const std::set* vocab = nullptr; + std::vector asked_undeclared; /* what a real engine would refuse */ + bool declared(const std::string& op) const { + return vocab ? vocab->count(op) != 0 : undeclared.count(op) == 0; + } + int64_t kv_block = 16; + + /* The buffer the plugin named as this step's logits (rad_declare_logits), or as its pooled + * output (rad_declare_pooled). */ + rad_buf logits = 0; + rad_buf pooled = 0; + + /* The draft head's declaration (rad_declare_drafter), and whether it keeps no cache of its + * own (rad_drafter_shared_kv) and at which rotary offset. */ + RadDrafterDecl drafter{}; + std::string drafter_name; + bool drafter_shared = false; + int drafter_pos = -1; + + /* The buffers named to rad_buf_concurrent: the ones a second lane touches. */ + std::vector concurrent; + + /* The vision and audio encoder declarations (rad_declare_encoder), if any. */ + RadEncoderDecl encoder{}; + std::string encoder_name; + RadEncoderDecl audio_encoder{}; + std::string audio_encoder_name; + + /* The image generator's declaration (rad_declare_generator), if any. */ + RadGeneratorDecl generator{}; + std::string generator_name; + + /* Adapter key names (rad_lora_root, rad_lora_alias): (native, spellings), and each alias as + * (native, from, to, from_lo, from_hi, to_lo). */ + std::vector> lora_roots; + struct LoraAliasRec { std::string native, from, to; int64_t from_lo, from_hi, to_lo; }; + std::vector lora_aliases; + + /* What rad_weight_encoding answers: the first entry whose key the source name contains. Empty + * means no model, so every weight is plain in its declared dtype. */ + std::vector> encs; + + const RecOp* op_of(rad_op h) const { return h ? &ops[h - 1] : nullptr; } +}; + +struct RadCtx { + RadBuilder* b = nullptr; + const RadBatch* batch = nullptr; + int rank = 0; + int world = 1; + std::vector issues; + std::vector routed_layers; + std::string step_fail; + int lane = 0; /* where the next issue goes */ + std::vector joins; + /* Device copies into a buffer (rad_memcpy_async to a rad_buf_ptr address): the buffer and the + * issue number the copy came before. The step lint counts each as a write there. */ + std::vector> copies; +}; + +/* -------------------------------------------------------------------- the declare-side ABI */ +extern "C" rad_weight rad_decl_weight(RadBuilder* b, const char* name, const RadWeightDecl* d) { + b->weights.push_back({name, *d}); + return (rad_weight)b->weights.size(); +} + +extern "C" int rad_weight_encoding(RadBuilder* b, const char* source, RadEncoding* out, int64_t*, + uint32_t*) { + for (const auto& [key, e] : b->encs) + if (source && std::strstr(source, key.c_str())) { *out = e; return RAD_OK; } + return RAD_E_NOTFOUND; +} +extern "C" rad_buf rad_decl_buffer(RadBuilder* b, const char* name, const RadBufDecl* d) { + b->bufs.push_back({name, *d}); + return (rad_buf)b->bufs.size(); +} + +extern "C" rad_op rad_decl_op(RadBuilder* b, const char* op, const RadParam* params, int n_params, + const rad_weight* weights, int n_weights) { + if (!b->declared(op)) { + b->asked_undeclared.push_back(op); + return RAD_NULL_HANDLE; + } + RecOp r; + r.op = op; + for (int i = 0; i < n_params; ++i) { + RecParam p; + p.key = params[i].key ? params[i].key : ""; + p.kind = params[i].kind; + p.ival = params[i].ival; + p.ihi = params[i].ihi; + p.dval = params[i].dval; + p.sval = params[i].sval ? params[i].sval : ""; + r.p.push_back(p); + } + for (int i = 0; i < n_weights; ++i) r.w.push_back(weights[i]); + r.resolved = b->refuse.count(r.op) == 0; + b->ops.push_back(r); + /* Declare always completes. An unresolved op is RAD_NULL_HANDLE, an error only if the plugin + * issues it (rad_builder.h). */ + return r.resolved ? (rad_op)b->ops.size() : RAD_NULL_HANDLE; +} + +extern "C" int rad_op_reads(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { + if (!h) return RAD_E_INVAL; + RecOp& r = b->ops[h - 1]; + r.uses_declared = true; + for (int i = 0; i < n; ++i) r.reads.push_back(bufs[i]); + return RAD_OK; +} + +extern "C" int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { + if (!h) return RAD_E_INVAL; + RecOp& r = b->ops[h - 1]; + r.uses_declared = true; + for (int i = 0; i < n; ++i) r.writes.push_back(bufs[i]); + return RAD_OK; +} + +extern "C" int rad_op_resolved(RadBuilder* b, rad_op h) { + return h != RAD_NULL_HANDLE && b->ops[h - 1].resolved; +} + +extern "C" int rad_op_declared(RadBuilder* b, const char* op) { + return op && b->declared(op); +} + +extern "C" rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, + const RadKVGroupDecl* d) { + b->kv_groups.push_back({name, *d, false}); + return (rad_kvgroup)b->kv_groups.size(); +} + +extern "C" int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) { (void)g; return b->kv_block; } + +extern "C" int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) { + b->binds.push_back({layer, g}); + return RAD_OK; +} + +extern "C" int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) { + RecMap r; + r.declared = m->declared; + r.mode = m->mode; + r.concat_dim = m->concat_dim; + for (int i = 0; i < m->n_src; ++i) r.src.push_back(m->src[i]); + b->maps.push_back(r); + return RAD_OK; +} + +extern "C" void rad_note(RadBuilder* b, const char* fmt, ...) { + char buf[512]; + va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); + b->notes.push_back(buf); +} + +/* The buffer the core samples from, recorded so tests can assert the plugin named the narrow + * one: [max_tok, n_vocab] is legal but 8 GiB at this vocabulary. */ +extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) { + if (!b || !logits) return RAD_E_INVAL; + b->logits = logits; + return RAD_OK; +} + +/* An embedding program names its pooled output instead of logits; a program declares one. */ +extern "C" int rad_declare_pooled(RadBuilder* b, rad_buf pooled) { + if (!b || !pooled || b->logits) return RAD_E_INVAL; + b->pooled = pooled; + return RAD_OK; +} + +/* An image generator's declaration, recorded whole; it too excludes logits. */ +extern "C" int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) { + if (!b || !d || !d->image_out || b->logits || b->pooled) return RAD_E_INVAL; + b->generator = *d; + b->generator_name = d->name ? d->name : ""; + return RAD_OK; +} + +/* Recorded: a generator's adapter key names. */ +extern "C" int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) { + if (!b || !native || !*native) return RAD_E_INVAL; + b->lora_roots.push_back({ native, spellings ? spellings : "" }); + return RAD_OK; +} +extern "C" int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to, + int64_t from_lo, int64_t from_hi, int64_t to_lo) { + if (!b || !native || !from || !to) return RAD_E_INVAL; + b->lora_aliases.push_back({ native, from, to, from_lo, from_hi, to_lo }); + return RAD_OK; +} + +/* Recorded: gemma4's prefill overlap names the buffers its second lane reduces in place. */ +extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { + if (!b || !buf) return RAD_E_INVAL; + b->concurrent.push_back(buf); + return RAD_OK; +} +extern "C" int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) { + if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL; + if (lo < 0 || hi <= lo) return RAD_E_INVAL; + /* The real Builder also checks the declared extent against hi-lo (core/build/rad_builder.cpp); + * the fake only records the span for tests. */ + RecWeight& rw = b->weights[w - 1]; + rw.span_set = true; + rw.span_lo = lo; + rw.span_hi = hi; + return RAD_OK; +} +extern "C" int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, + const int64_t* hi, const int64_t* total, int n) { + if (!b || w == 0 || w > b->weights.size() || !lo || !hi || !total) return RAD_E_INVAL; + if (n < 2 || n > RAD_MAX_ROW_PARTS) return RAD_E_INVAL; + RecWeight& rw = b->weights[w - 1]; + if (rw.d.n_row_parts != n) return RAD_E_INVAL; + for (int g = 0; g < n; ++g) { + if (lo[g] < 0 || hi[g] <= lo[g] || hi[g] > total[g]) return RAD_E_INVAL; + if (rw.d.row_parts[g] != hi[g] - lo[g]) return RAD_E_SHAPE; + rw.part_lo[g] = lo[g]; + rw.part_hi[g] = hi[g]; + rw.part_total[g] = total[g]; + } + rw.n_part_spans = n; + return RAD_OK; +} +extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { + if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL; + b->kv_groups[g - 1].zero = true; + return RAD_OK; +} +extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { + if (!b || !d) return RAD_E_INVAL; + b->drafter = *d; + b->drafter_name = d->name ? d->name : ""; + return RAD_OK; +} +extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { + if (!b || b->drafter.kind != RAD_DRAFT_SERIAL || (pos_offset != 0 && pos_offset != 1)) + return RAD_E_STATE; + b->drafter_shared = true; + b->drafter_pos = pos_offset; + return RAD_OK; +} +extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { + if (!b || !d || !d->name || !d->modalities) return RAD_E_INVAL; + if (d->modalities == RAD_MM_AUDIO) { + b->audio_encoder = *d; + b->audio_encoder_name = d->name; + return RAD_OK; + } + b->encoder = *d; + b->encoder_name = d->name; + return RAD_OK; +} + +/* -------------------------------------------------------------------- model metadata */ +extern "C" long long rad_meta_geti(const RadModelMeta* m, const char* key, long long dflt) { + for (int i = 0; i < m->n_kv; ++i) + if (std::strcmp(m->kv_key[i], key) == 0) return atoll(m->kv_val[i]); + return dflt; +} +extern "C" double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt) { + for (int i = 0; i < m->n_kv; ++i) + if (std::strcmp(m->kv_key[i], key) == 0) return atof(m->kv_val[i]); + return dflt; +} +extern "C" const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt) { + for (int i = 0; i < m->n_kv; ++i) + if (std::strcmp(m->kv_key[i], key) == 0) return m->kv_val[i]; + return dflt; +} + +/* -------------------------------------------------------------------- the run-phase ABI */ +extern "C" int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n) { + RecIssue r; + r.op = op; + r.n = n; + for (int i = 0; i < n_opd; ++i) r.opd.push_back(opd[i]); + r.lane = c->lane; + c->issues.push_back(r); + return RAD_OK; +} +/* The second lane, recorded: each issue's lane, and each join's position among the issues. */ +extern "C" int rad_lane(RadCtx* c, int lane) { + if (lane != 0 && lane != 1) return RAD_E_INVAL; + c->lane = lane; + return RAD_OK; +} +extern "C" int rad_lane_join(RadCtx* c, int from, int to) { + if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL; + c->joins.push_back({ c->issues.size(), from, to }); + return RAD_OK; +} +/* A block that refuses the batch records the reason for the tests. */ +extern "C" int rad_step_fail(RadCtx* c, const char* what) { + c->step_fail = what ? what : ""; + return RAD_E_SHAPE; +} +extern "C" const RadBatch* rad_batch(RadCtx* c) { return c->batch; } +extern "C" int rad_rank(RadCtx* c) { return c->rank; } +extern "C" int rad_world_size(RadCtx* c) { return c->world; } +/* The context itself, so a copy issued on the step's stream is recorded in it (rad_memcpy_async). */ +extern "C" RadStream rad_stream(RadCtx* c) { return (RadStream)c; } +extern "C" int rad_stream_sync(RadStream s) { (void)s; return RAD_OK; } +extern "C" int rad_route_report(RadCtx* c, int layer, const RadRouting* r) { + (void)r; + c->routed_layers.push_back(layer); + return RAD_OK; +} +/* No card-side histogram here, so a router writes and reports its own buffer. */ +extern "C" int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) { + (void)c; (void)layer; (void)n_expert; + return nullptr; +} +/* No prefetch here: the three calls are no-ops, as in a core without one. */ +extern "C" int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, + int64_t rows, int64_t n_embd) { + (void)c; (void)next; (void)h; (void)r0; (void)rows; (void)n_embd; + return RAD_OK; +} +extern "C" int rad_expert_prefetch_mark(RadCtx* c) { (void)c; return RAD_OK; } +extern "C" int rad_expert_prefetch_step(RadCtx* c, int layer) { (void)c; (void)layer; return RAD_OK; } +/* Never dereferenced: a plugin passes these through to rad_route_report or offsets one into a raw + * operand. Each handle gets its own 2^36-byte window above any user-space address, tagged by + * kind in the top bits, so the step lint can map a raw operand inside a buffer back to that buffer + * (fake_buf_of). */ +constexpr int kFakePtrShift = 36; +constexpr uintptr_t kFakeBufTag = (uintptr_t)1 << 61; +constexpr uintptr_t kFakeWeightTag = (uintptr_t)1 << 62; +extern "C" void* rad_weight_ptr(RadCtx* c, rad_weight w) { + (void)c; + return (void*)(kFakeWeightTag | (uintptr_t)w << kFakePtrShift); +} +extern "C" void* rad_buf_ptr(RadCtx* c, rad_buf b) { + (void)c; + return (void*)(kFakeBufTag | (uintptr_t)b << kFakePtrShift); +} +/* The buffer a raw operand points into, if it came from rad_buf_ptr; 0 otherwise. */ +static rad_buf fake_buf_of(const void* p, size_t n_bufs) { + const uintptr_t u = (uintptr_t)p; + if ((u & ~(kFakeBufTag - 1)) != kFakeBufTag) return 0; + const uintptr_t h = (u & (kFakeBufTag - 1)) >> kFakePtrShift; + return h >= 1 && h <= n_bufs ? (rad_buf)h : 0; +} +/* Pinned host memory a plugin fills itself (qwen4exp_fp8's piece bounds, the calibration tap's + * staging), as host memory; nothing else is handed out. */ +extern "C" void* rad_dev_alloc(int64_t bytes, int kind) { + return kind == RAD_MEM_HOST_PINNED && bytes > 0 ? std::calloc(1, (size_t)bytes) : nullptr; +} +extern "C" void rad_dev_free(void* p, int kind) { if (kind == RAD_MEM_HOST_PINNED) std::free(p); } +/* The device copies: nothing is copied. One into a buffer on a step's stream is recorded as a + * write of that buffer before the next issue (RadCtx::copies). */ +extern "C" int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s) { + (void)src; (void)bytes; + RadCtx* c = (RadCtx*)s; + if (c && c->b) + if (const rad_buf h = fake_buf_of(dst, c->b->bufs.size())) + c->copies.push_back({ c->issues.size(), h }); + return RAD_OK; +} +extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s) { + (void)dst; (void)value; (void)bytes; (void)s; + return RAD_OK; +} + +/* ==================================================================== fixtures and helpers */ +namespace { + +/* A deployment: one rank, 256 rows a step, eight sequences, 32k of context. */ +RadBuildCtx build_ctx(int rank = 0, int world = 1) { + RadBuildCtx c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 256; + c.max_seqs = 8; + c.max_ctx = 32768; + c.scope = ""; + return c; +} + +/* The sampled rows (RadBatch::out_ids). The plugin skips the lm_head when n_out is zero (a chunk + * finishing no sequence), so a fake batch must set them or it silently tests the no-logits + * path. */ +static const int32_t kDecodeOut[] = { 0, 1, 2, 3 }; +static const int32_t kPrefillOut[] = { 31, 63 }; /* last token of each 32-token sequence */ + +RadBatch decode_batch() { + RadBatch b{}; + b.phase = RAD_PHASE_DECODE; + b.n_tok = 4; + b.n_seq = 4; + b.max_q_len = 1; + b.max_ctx_len = 100; + b.n_out = 4; + b.out_ids = kDecodeOut; + return b; +} + +RadBatch prefill_batch() { + RadBatch b{}; + b.phase = RAD_PHASE_PREFILL; + b.n_tok = 64; + b.n_seq = 2; + b.max_q_len = 32; + b.max_ctx_len = 32; + b.n_out = 2; + b.out_ids = kPrefillOut; + return b; +} + +/* --- small queries over the recorded graph --- */ +std::vector op_names(const RadBuilder& b) { + std::vector v; + for (const auto& o : b.ops) v.push_back(o.op); + return v; +} + +const RecOp* find_op(const RadBuilder& b, const std::string& name, int nth = 0) { + for (const auto& o : b.ops) + if (o.op == name && nth-- == 0) return &o; + return nullptr; +} + +int count_op(const RadBuilder& b, const std::string& name) { + int n = 0; + for (const auto& o : b.ops) if (o.op == name) ++n; + return n; +} + +const RecParam* param(const RecOp* o, const char* key) { + if (!o) return nullptr; + for (const auto& p : o->p) if (p.key == key) return &p; + return nullptr; +} + +long long pint(const RecOp* o, const char* key) { + const RecParam* p = param(o, key); + return p ? p->ival : -12345; +} + +double pflt(const RecOp* o, const char* key) { + const RecParam* p = param(o, key); + return p ? p->dval : -12345.0; +} + +std::string pstr(const RecOp* o, const char* key) { + const RecParam* p = param(o, key); + return p ? p->sval : std::string(""); +} + +const RecWeight* find_w(const RadBuilder& b, const std::string& name) { + for (const auto& w : b.weights) if (w.name == name) return &w; + return nullptr; +} + +const RecBuf* find_b(const RadBuilder& b, const std::string& name) { + for (const auto& x : b.bufs) if (x.name == name) return &x; + return nullptr; +} + +const RecMap* find_map(const RadBuilder& b, const std::string& declared) { + for (const auto& m : b.maps) if (m.declared == declared) return &m; + return nullptr; +} + +std::string join(const std::vector& v) { + std::string s; + for (size_t i = 0; i < v.size(); ++i) { if (i) s += " "; s += v[i]; } + return s; +} + +std::vector issued_ops(const RadBuilder& b, const RadCtx& c) { + std::vector got; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + got.push_back(o ? o->op : ""); + } + return got; +} + +/* `fn`'s status, with what it prints kept out of the test output. */ +int stderr_of_rc(const std::function& fn) { + int rc = 0; + stderr_of([&] { rc = fn(); }); + return rc; +} + +/* Model metadata built key by key; `meta()` is valid while this object lives. */ +struct MetaKV { + RadModelMeta m{}; + std::vector keys, vals; + std::vector kp, vp; + explicit MetaKV(const RadModelMeta& base) : m(base) { + for (int i = 0; i < base.n_kv; ++i) set(base.kv_key[i], base.kv_val[i]); + } + MetaKV& set(const char* k, const char* v) { + for (size_t i = 0; i < keys.size(); ++i) + if (keys[i] == k) { vals[i] = v; return *this; } + keys.push_back(k); + vals.push_back(v); + return *this; + } + MetaKV& drop(const char* k) { + for (size_t i = 0; i < keys.size(); ++i) + if (keys[i] == k) { + keys.erase(keys.begin() + (long)i); + vals.erase(vals.begin() + (long)i); + break; + } + return *this; + } + const RadModelMeta* meta() { + kp.clear(); vp.clear(); + for (size_t i = 0; i < keys.size(); ++i) { + kp.push_back(keys[i].c_str()); + vp.push_back(vals[i].c_str()); + } + m.n_kv = (int)kp.size(); + m.kv_key = kp.data(); + m.kv_val = vp.data(); + return &m; + } +}; + +RadBuildCtx spec_ctx(int rank, int world, int max_spec) { + RadBuildCtx c = build_ctx(rank, world); + c.max_spec = max_spec; + return c; +} + +const RecIssue* issue_of(const RadBuilder& b, const RadCtx& c, const std::string& name, + int nth = 0) { + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (o && o->op == name && nth-- == 0) return &i; + } + return nullptr; +} + +int count_issued(const std::vector& v, const std::string& name) { + return (int)std::count(v.begin(), v.end(), name); +} + +} /* namespace */ + +/* ==================================================================== the step lint + * + * The buffer plan takes liveness from declaration order: a transient lives over the [first, last] + * op indices of its declared reads and writes, and two transients of one arena whose ranges are + * disjoint may share bytes (core/build/rad_bufplan.cpp). A step that issues ops in another order, + * or across passes of one engine step (trunk, drafter history, draft rounds), can write one buffer + * while another that shares its bytes still holds rows a later issue reads. The runtime refuses + * only an op outside a buffer's range, and only on the branch a real model runs, so the class is + * checked here for every recorded step. + * + * lint_step walks the issues of one engine step's passes in order and reports: + * alias a transient read whose last writer is followed, before the read, by a write of a + * transient of the same arena whose range is disjoint from its own; + * undeclared an op issued outside the declared range of a buffer operand + * (core/runtime/issue.cpp refuses this); + * span an operand that reaches past its buffer or weight, rows and columns applied as + * issue.cpp applies them; + * null op an issue of RAD_NULL_HANDLE (a fused op that did not resolve, with no chain); + * unwritten a transient read before any issue, or device copy into it, of the step wrote it; + * kv a cache operand naming a group or layer no rad_bind_layer_kv bound, or a group + * this rank declared zero; + * strided a GEMM whose input is a column slice narrower than its buffer (libr4d's GEMMs + * read whole rows and refuse it). */ +namespace { + +/* One buffer's planned lifetime. `planned` is false for a buffer live over the whole program + * (PERSIST, DERIVED, rad_buf_concurrent, or no declared use), which shares bytes with nothing. */ +struct Live { + int32_t lo = 0, hi = 0; + bool planned = false; + bool transient = false; + int domain = RAD_DOMAIN_DEVICE; +}; + +/* Liveness by the rule of Builder::finish_buffer_liveness (core/build/rad_builder.cpp). Op handle + * h is op index h: the real builder keeps a sentinel at index 0, and the fake hands out ops in + * declaration order from 1. */ +std::vector liveness(const RadBuilder& b) { + const size_t nb = b.bufs.size(); + const int32_t last_op = (int32_t)b.ops.size(); + std::vector first(nb + 1, -1), last(nb + 1, -1); + for (size_t i = 0; i < b.ops.size(); ++i) + for (const std::vector* v : { &b.ops[i].reads, &b.ops[i].writes }) + for (rad_buf h : *v) { + if (h == 0 || h > nb) continue; + if (first[h] < 0) first[h] = (int32_t)(i + 1); + last[h] = (int32_t)(i + 1); + } + std::set conc(b.concurrent.begin(), b.concurrent.end()); + std::vector L(nb + 1); + for (size_t h = 1; h <= nb; ++h) { + const RadBufDecl& d = b.bufs[h - 1].d; + Live& l = L[h]; + l.transient = d.kind == RAD_BUF_TRANSIENT; + l.domain = d.domain; + if (!l.transient || conc.count((rad_buf)h) || first[h] < 0) { + l.lo = 0; + l.hi = last_op; + continue; + } + l.planned = true; + l.lo = first[h]; + l.hi = last[h]; + if ((rad_buf)h == b.logits || (rad_buf)h == b.pooled) l.hi = last_op; + } + return L; +} + +/* Whether operand `o` stays inside a buffer or weight of `shape` (packed strides, rows and cols + * applied as issue.cpp applies them), as issue.cpp's operand_fits decides. */ +bool operand_fits(const int64_t* shape, uint32_t rank, const RadOperand& o) { + if (o.offset < 0) return false; + int64_t sh[RAD_MAX_RANK] = {}, st[RAD_MAX_RANK] = {}; + int64_t numel = 1; + for (uint32_t d = 0; d < rank; ++d) { sh[d] = shape[d]; numel *= shape[d]; } + int64_t s = 1; + for (int d = (int)rank - 1; d >= 0; --d) { st[d] = s; s *= sh[d]; } + if (o.rows > 0 && rank >= 1) sh[0] = o.rows; + if (o.cols > 0 && rank >= 1) sh[rank - 1] = o.cols; + int64_t span = o.offset; + for (uint32_t d = 0; d < rank; ++d) { + if (sh[d] <= 0) return true; + span += (sh[d] - 1) * st[d]; + } + return span < numel; +} + +bool in(const std::vector& v, rad_buf h) { + return std::find(v.begin(), v.end(), h) != v.end(); +} + +std::vector lint_step(const RadBuilder& b, const std::vector& passes) { + std::vector bad; + const std::vector L = liveness(b); + const size_t nb = b.bufs.size(); + auto name = [&](rad_buf h) { return h && h <= nb ? b.bufs[h - 1].name : std::string("?"); }; + auto shares = [&](rad_buf x, rad_buf y) { + const Live& p = L[x]; + const Live& q = L[y]; + return p.planned && q.planned && p.domain == q.domain && (p.hi < q.lo || q.hi < p.lo); + }; + std::set> bound(b.binds.begin(), b.binds.end()); + std::vector last_write(nb + 1, -1); + int64_t pos = 0; + char where[96]; + for (size_t pi = 0; pi < passes.size(); ++pi) { + const RadCtx& c = *passes[pi]; + size_t next_copy = 0; + for (size_t ii = 0; ii < c.issues.size(); ++ii, ++pos) { + for (; next_copy < c.copies.size() && c.copies[next_copy].first <= ii; ++next_copy) + last_write[c.copies[next_copy].second] = pos; + const RecIssue& is = c.issues[ii]; + const RecOp* o = b.op_of(is.op); + std::snprintf(where, sizeof where, "pass %zu issue %zu (%s, op %u)", pi, ii, + o ? o->op.c_str() : "", (unsigned)is.op); + if (!o) { bad.push_back(std::string(where) + ": null op issued"); continue; } + std::vector rd, wr; + for (size_t k = 0; k < is.opd.size(); ++k) { + const RadOperand& od = is.opd[k]; + const std::string at = std::string(where) + " operand " + std::to_string(k); + if (od.kind == RAD_OPK_BUF) { + const rad_buf h = od.handle; + if (h == 0 || h > nb) { + bad.push_back(at + ": buffer handle out of range"); + continue; + } + const RadBufDecl& d = b.bufs[h - 1].d; + if (!operand_fits(d.shape, d.rank, od)) + bad.push_back(at + ": span past '" + name(h) + "' (offset " + + std::to_string(od.offset) + ", rows " + + std::to_string(od.rows) + ", cols " + + std::to_string(od.cols) + ")"); + const Live& l = L[h]; + if (l.planned && ((int32_t)is.op < l.lo || (int32_t)is.op > l.hi)) + bad.push_back(at + ": undeclared use of '" + name(h) + "' (planned ops " + + std::to_string(l.lo) + ".." + std::to_string(l.hi) + ")"); + const bool r = in(o->reads, h), w = in(o->writes, h); + if (r || !w) rd.push_back(h); + if (w || !r) wr.push_back(h); + /* A GEMM's input is read as contiguous rows: libr4d refuses a column slice + * narrower than its buffer. */ + const int64_t width = d.rank ? d.shape[d.rank - 1] : 0; + if (k == 0 && o->op.rfind("gemm_nt", 0) == 0 && od.cols > 0 && + (od.cols != width || od.offset % width)) + bad.push_back(at + ": " + o->op + " reads " + std::to_string(od.cols) + + " of " + std::to_string(width) + " columns of '" + name(h) + + "' as its input, which is not contiguous"); + } else if (od.kind == RAD_OPK_WEIGHT) { + const uint32_t h = od.handle; + if (h == 0 || h > b.weights.size()) { + bad.push_back(at + ": weight handle out of range"); + continue; + } + const RadWeightDecl& d = b.weights[h - 1].d; + if ((od.offset || od.rows > 0 || od.cols > 0) && + !operand_fits(d.shape, d.rank, od)) + bad.push_back(at + ": span past weight '" + b.weights[h - 1].name + "'"); + } else if (od.kind == RAD_OPK_WTAB) { + if (od.handle == 0 || od.rows <= 0 || od.offset || od.cols || + (size_t)(od.handle + od.rows - 1) > b.weights.size()) + bad.push_back(at + ": weight table out of range"); + } else if (od.kind == RAD_OPK_KV) { + const rad_kvgroup g = od.handle; + if (g == 0 || g > b.kv_groups.size()) + bad.push_back(at + ": KV group handle out of range"); + else if (b.kv_groups[g - 1].zero) + bad.push_back(at + ": KV group '" + b.kv_groups[g - 1].name + + "' is declared zero on this rank"); + else if (!bound.count({ (int)od.offset, g })) + bad.push_back(at + ": layer " + std::to_string(od.offset) + + " is not bound to KV group '" + b.kv_groups[g - 1].name + + "'"); + } else if (od.kind == RAD_OPK_RAW) { + if (od.offset && od.dtype == RAD_DT_INVALID) + bad.push_back(at + ": raw operand with an offset and no dtype"); + /* A pointer into a buffer (rad_buf_ptr) is that buffer to the plan, so it is + * classified by the op's declared sets like a buffer operand. */ + if (const rad_buf h = fake_buf_of(od.raw, nb)) { + const Live& l = L[h]; + if (l.planned && ((int32_t)is.op < l.lo || (int32_t)is.op > l.hi)) + bad.push_back(at + ": undeclared use of '" + name(h) + + "' through a raw pointer"); + const bool r = in(o->reads, h), w = in(o->writes, h); + if (r || !w) rd.push_back(h); + if (w || !r) wr.push_back(h); + } + } + } + for (rad_buf h : rd) { + if (!L[h].transient) continue; + const int64_t w = last_write[h]; + if (w < 0) { + bad.push_back(std::string(where) + ": reads '" + name(h) + + "' before any issue of this step wrote it"); + continue; + } + for (size_t x = 1; x <= nb; ++x) + if (x != h && last_write[x] > w && shares(h, (rad_buf)x)) + bad.push_back(std::string(where) + ": reads '" + name(h) + "' (ops " + + std::to_string(L[h].lo) + ".." + std::to_string(L[h].hi) + + ") after a write of '" + name((rad_buf)x) + "' (ops " + + std::to_string(L[x].lo) + ".." + std::to_string(L[x].hi) + + "), which may share its bytes"); + } + for (rad_buf h : wr) last_write[h] = pos; + } + } + return bad; +} + +/* ---------------------------------------------------------------- whole step batches + * + * A batch as the core builds it: every per-token and per-sequence array filled and a group batch + * for every KV group the builder declared, so a plugin's step can take any path. Decode sequences + * come first (RadBatch::n_seq_decode); each `dq` entry is a decode sequence's query length (1, or + * 1 + n_spec for a verify), each `pq` entry a prefill chunk. Every decode row is sampled (a verify + * needs logits at each row) and a chunk's last row; a chunk continues `prefill_ctx` tokens of + * history. */ +struct Kit { + std::vector tok, pos, cu, ctxl, qlen, out, nacc, dout; + std::vector slot, table, used, sidx; + std::vector kv; + RadBatch b{}; +}; + +std::unique_ptr kit(const RadBuilder& bld, const std::vector& dq, + const std::vector& pq, int32_t prefill_ctx = 0) { + auto k = std::make_unique(); + const int64_t nd = (int64_t)dq.size(), ns = nd + (int64_t)pq.size(); + std::vector ql(dq); + ql.insert(ql.end(), pq.begin(), pq.end()); + int64_t T = 0, max_q = 0, max_ctx = 0, td = 0, mqd = 0, mqp = 0; + k->cu.push_back(0); + for (int64_t s = 0; s < ns; ++s) { + const bool dec = s < nd; + const int32_t ctx = dec ? (int32_t)(40 + 7 * s) : prefill_ctx; + for (int i = 0; i < ql[(size_t)s]; ++i) { + k->tok.push_back((int32_t)(3 + (T + i) % 97)); + k->pos.push_back(ctx + i); + if (dec || i + 1 == ql[(size_t)s]) k->out.push_back((int32_t)(T + i)); + } + T += ql[(size_t)s]; + k->cu.push_back((int32_t)T); + k->ctxl.push_back(ctx); + k->qlen.push_back(ql[(size_t)s]); + k->nacc.push_back(1); + k->dout.push_back((int32_t)T - 1); + max_q = std::max(max_q, ql[(size_t)s]); + max_ctx = std::max(max_ctx, ctx + ql[(size_t)s]); + if (dec) { td += ql[(size_t)s]; mqd = std::max(mqd, ql[(size_t)s]); } + else mqp = std::max(mqp, ql[(size_t)s]); + } + k->tok.resize((size_t)T + 64, 5); /* room for a following prompt (RadBatch::n_ahead) */ + const int64_t pitch = 16; + for (int64_t i = 0; i < T; ++i) k->slot.push_back((int32_t)i); + for (int64_t i = 0; i < ns * pitch; ++i) k->table.push_back((int32_t)i); + for (int64_t s = 0; s < ns; ++s) { + k->used.push_back(k->ctxl[(size_t)s] + k->qlen[(size_t)s]); + k->sidx.push_back((int32_t)s); + } + for (size_t g = 0; g < bld.kv_groups.size(); ++g) { + RadKVGroupBatch gb{}; + gb.group = (rad_kvgroup)(g + 1); + gb.slot_mapping = k->slot.data(); + gb.block_table = k->table.data(); + gb.block_table_pitch = pitch; + gb.seqused = k->used.data(); + gb.state_index = k->sidx.data(); + gb.state_index_pitch = 1; + gb.block_size = bld.kv_block; + gb.max_blocks = pitch; + k->kv.push_back(gb); + } + RadBatch& b = k->b; + b.phase = pq.empty() ? RAD_PHASE_DECODE : dq.empty() ? RAD_PHASE_PREFILL : RAD_PHASE_MIXED; + b.n_tok = T; + b.n_seq = ns; + b.token_ids = k->tok.data(); + b.positions = k->pos.data(); + b.cu_seqlens = k->cu.data(); + b.n_out = (int64_t)k->out.size(); + b.out_ids = k->out.data(); + b.q_lens = k->qlen.data(); + b.ctx_lens = k->ctxl.data(); + b.max_q_len = (int32_t)max_q; + b.max_ctx_len = (int32_t)max_ctx; + b.n_kv_groups = (int)k->kv.size(); + b.kv = k->kv.data(); + b.n_spec = mqd > 1 ? (int)(mqd - 1) : 0; + b.num_accepted = k->nacc.data(); + b.n_seq_decode = nd; + b.n_tok_decode = td; + b.max_q_len_decode = (int32_t)mqd; + b.max_q_len_prefill = (int32_t)mqp; + return k; +} + +/* The draft passes the core stages for a step of `n_seq` sequences. + * + * A serial head's history pass (draft_pass -1) covers every row the trunk step had and carries + * round 1 on each sequence's last row; round r (2..depth) is one row a sequence. A block + * drafter's context pass (-1) covers the trunk's rows; its query pass (1) is `block` rows a + * sequence, the anchor first, and samples the `steps` rows after it (RadDrafterDecl::block). */ +std::unique_ptr history_pass(const RadBuilder& bld, const Kit& trunk) { + std::vector rows; + for (int64_t s = 0; s < trunk.b.n_seq; ++s) rows.push_back(trunk.qlen[(size_t)s]); + auto k = kit(bld, rows, {}); + k->b.draft_pass = -1; + k->out.clear(); + for (int64_t i = 0; i < k->b.n_tok; ++i) k->out.push_back((int32_t)i); + k->b.out_ids = k->out.data(); + k->b.n_out = k->b.n_tok; + k->b.n_draft_out = k->b.n_seq; + k->b.draft_out_ids = k->dout.data(); + return k; +} +std::unique_ptr round_pass(const RadBuilder& bld, int64_t n_seq, int r) { + auto k = kit(bld, std::vector((size_t)n_seq, 1), {}); + k->b.draft_pass = r; + return k; +} +std::unique_ptr context_pass(const RadBuilder& bld, const Kit& trunk) { + auto k = history_pass(bld, trunk); + k->b.n_draft_out = 0; + k->b.draft_out_ids = nullptr; + return k; +} +std::unique_ptr query_pass(const RadBuilder& bld, int64_t n_seq, int64_t block, + int64_t steps) { + auto k = kit(bld, std::vector((size_t)n_seq, (int)block), {}); + k->b.draft_pass = 1; + k->out.clear(); + for (int64_t s = 0; s < n_seq; ++s) + for (int64_t i = 0; i < steps; ++i) + k->out.push_back((int32_t)(s * block + block - steps + i)); + k->b.out_ids = k->out.data(); + k->b.n_out = (int64_t)k->out.size(); + return k; +} + +using StepFn = void (*)(RadCtx*, const RadBatch*); + +/* Runs one engine step's passes in order, each on a context of its own. */ +std::vector> run_passes(RadBuilder& b, StepFn step, + const std::vector& passes, + int rank = 0, int world = 1) { + std::vector> out; + for (const Kit* k : passes) { + out.push_back(std::make_unique()); + RadCtx& c = *out.back(); + c.b = &b; + c.batch = &k->b; + c.rank = rank; + c.world = world; + step(&c, &k->b); + } + return out; +} + +std::vector view(const std::vector>& v) { + std::vector p; + for (const auto& c : v) p.push_back(c.get()); + return p; +} + +/* The lint as a check: every finding is printed, and the step passes only with none. */ +size_t report_lint(const std::vector& f) { + for (size_t i = 0; i < f.size() && i < 12; ++i) fprintf(stderr, " lint: %s\n", f[i].c_str()); + if (f.size() > 12) fprintf(stderr, " lint: ... %zu more\n", f.size() - 12); + return f.size(); +} + +/* Every pass of one engine step ran without a step failure. */ +bool steps_ok(const std::vector>& v) { + bool ok = true; + for (size_t i = 0; i < v.size(); ++i) + if (!v[i]->step_fail.empty()) { + fprintf(stderr, " pass %zu failed: %s\n", i, v[i]->step_fail.c_str()); + ok = false; + } + return ok; +} + +} /* namespace */ + +#define CHECK_LINT(b, ...) CHECK_EQ(report_lint(lint_step((b), { __VA_ARGS__ })), (size_t)0) +/* The passes of one engine step (run_passes): none failed and the lint is clean over them. */ +#define CHECK_PASSES(b, v) \ + do { \ + CHECK(steps_ok(v)); \ + CHECK_EQ(report_lint(lint_step((b), view(v))), (size_t)0); \ + } while (0) + +/* ==================================================================== fingerprints */ +namespace { + +/* A 64-bit FNV-1a fingerprint of everything a declare recorded: ops with their parameters, + * weights, read and write sets and resolution; buffers, weights, KV groups, bindings, name maps, + * the logits / pooled / drafter / generator declarations and the concurrent list. Two declares + * give one value only if the core would build the same program from them. */ +struct Fnv { + uint64_t h = 1469598103934665603ull; + Fnv& raw(const void* p, size_t n) { + const auto* c = (const unsigned char*)p; + for (size_t i = 0; i < n; ++i) { h ^= c[i]; h *= 1099511628211ull; } + return *this; + } + Fnv& s(const std::string& x) { return raw(x.data(), x.size()).i((int64_t)x.size()); } + Fnv& s(const char* x) { return s(std::string(x ? x : "")); } + Fnv& i(int64_t v) { return raw(&v, sizeof v); } + Fnv& f(double v) { return raw(&v, sizeof v); } +}; +uint64_t graph_hash(const RadBuilder& b) { + Fnv f; + for (const RecOp& o : b.ops) { + f.s(o.op).i(o.resolved).i((int64_t)o.p.size()); + for (const RecParam& p : o.p) f.s(p.key).i(p.kind).i(p.ival).i(p.ihi).f(p.dval).s(p.sval); + for (const auto* v : { &o.w, &o.reads, &o.writes }) { + f.i((int64_t)v->size()); + for (uint32_t x : *v) f.i(x); + } + } + for (const RecBuf& x : b.bufs) { + f.s(x.name).i(x.d.dtype).i(x.d.rank).i(x.d.kind).i(x.d.domain).i(x.d.kv).s(x.d.derive); + for (uint32_t d = 0; d < x.d.rank; ++d) f.i(x.d.shape[d]); + } + for (const RecWeight& w : b.weights) { + f.s(w.name).i(w.d.dtype).i(w.d.rank).i(w.d.shard).i(w.d.access).i(w.d.group.layer) + .i(w.d.group.expert).s(w.d.source).s(w.d.planes).i(w.d.n_row_parts).i(w.span_lo) + .i(w.span_hi).i(w.n_part_spans); + for (uint32_t d = 0; d < w.d.rank; ++d) f.i(w.d.shape[d]); + } + for (const RecKV& g : b.kv_groups) + f.s(g.name).i(g.d.kind).i(g.d.dtype).i(g.d.window).i(g.d.n_head_kv).i(g.d.head_dim) + .i(g.d.state_dim[0]).i(g.d.state_dim[1]).i(g.d.conv_width).i(g.zero); + for (const auto& [l, g] : b.binds) f.i(l).i(g); + for (const RecMap& m : b.maps) { + f.s(m.declared).i(m.mode).i(m.concat_dim); + for (const auto& x : m.src) f.s(x); + } + f.i(b.logits).i(b.pooled).s(b.drafter_name).i(b.drafter.kind).i(b.drafter.depth) + .i(b.drafter.block).i(b.drafter.proposal).i(b.drafter.mask_token).i(b.drafter_shared) + .s(b.encoder_name).s(b.audio_encoder_name).s(b.generator_name); + for (rad_buf x : b.concurrent) f.i(x); + return f.h; +} + +/* What a step issued, as a fingerprint: each launch's op (by name and declared parameters), row + * count and lane, every operand by kind, buffer or weight name, offset and extent, a raw operand + * by the batch array and element it points at, and every lane join. */ +uint64_t issue_hash(const RadBuilder& b, const std::vector>& v, + const std::vector& kits) { + Fnv f; + auto raw_at = [&](const void* p) { + if (!p) { f.i(-1); return; } + if (const rad_buf h = fake_buf_of(p, b.bufs.size())) { + f.i(1).s(b.bufs[h - 1].name) + .i((int64_t)((uintptr_t)p - (uintptr_t)rad_buf_ptr(nullptr, h))); + return; + } + for (size_t k = 0; k < kits.size(); ++k) { + const Kit& t = *kits[k]; + const std::vector* arrays[] = { &t.tok, &t.pos, &t.cu, &t.ctxl, &t.qlen, + &t.out, &t.nacc, &t.dout, &t.slot, &t.table, + &t.used, &t.sidx }; + for (size_t a = 0; a < sizeof arrays / sizeof arrays[0]; ++a) { + const std::vector& x = *arrays[a]; + const int32_t* q = (const int32_t*)p; + if (!x.empty() && q >= x.data() && q < x.data() + x.size()) { + f.i(2).i((int64_t)a).i((int64_t)(q - x.data())); + return; + } + } + } + f.i(3); + }; + for (const auto& c : v) { + f.i((int64_t)c->issues.size()); + for (const RecIssue& r : c->issues) { + const RecOp* o = b.op_of(r.op); + f.s(o ? o->op : ""); + if (o) + for (const RecParam& p : o->p) f.s(p.key).i(p.ival).i(p.ihi).f(p.dval).s(p.sval); + f.i(r.n).i(r.lane).i((int64_t)r.opd.size()); + for (const RadOperand& d : r.opd) { + f.i(d.kind).i(d.dtype).i(d.offset).i(d.rows).i(d.cols); + if (d.kind == RAD_OPK_BUF) + f.s(d.handle && d.handle <= b.bufs.size() ? b.bufs[d.handle - 1].name : "?"); + else if (d.kind == RAD_OPK_WEIGHT || d.kind == RAD_OPK_WTAB) + f.s(d.handle && d.handle <= b.weights.size() ? b.weights[d.handle - 1].name + : "?"); + else if (d.kind == RAD_OPK_RAW) + raw_at(d.raw); + else + f.i(d.handle); + } + } + for (const RecJoin& j : c->joins) f.i((int64_t)j.at).i(j.from).i(j.to); + } + return f.h; +} + +/* The steps of the fingerprint: a 4096-row prefill after 4096 tokens of history (wider than a + * MoE pass), a mixed step, a decode step, and with a drafter a verify and its first passes. */ +uint64_t pinned_steps(RadBuilder& b, StepFn step, int rank, int world) { + const auto pf = kit(b, {}, { 4096 }, 4096); + const auto mx = kit(b, { 1, 1 }, { 2000 }, 3000); + const auto dc = kit(b, { 1, 1, 1 }, {}); + std::vector> all; + std::vector kits; + for (const Kit* k : { pf.get(), mx.get(), dc.get() }) { + auto v = run_passes(b, step, { k }, rank, world); + CHECK_PASSES(b, v); + for (auto& c : v) all.push_back(std::move(c)); + kits.push_back(k); + } + std::unique_ptr ver, his, r2; + if (b.drafter.kind == RAD_DRAFT_SERIAL) { + ver = kit(b, std::vector(3, 4), {}); + his = history_pass(b, *ver); + r2 = round_pass(b, 3, 2); + auto v = run_passes(b, step, { ver.get(), his.get(), r2.get() }, rank, world); + CHECK_PASSES(b, v); + for (auto& c : v) all.push_back(std::move(c)); + kits.push_back(ver.get()); kits.push_back(his.get()); kits.push_back(r2.get()); + } + return issue_hash(b, all, kits); +} + +} /* namespace */ + +#endif /* RAD_ARCH_FAKES_H */ diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index a3bd4457..ba7b07a6 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -10,457 +10,12 @@ */ #define RAD_ARCH_NO_EXPORTS 1 -#include "rad_test.h" +#include "arch_fakes.h" -#include "rad_builder.h" -#include "rad_device.h" -#include "rad_runtime.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include +#include #include -/* ==================================================================== the recording builder */ -namespace { - -struct RecParam { - std::string key; - int kind = 0; - long long ival = 0, ihi = 0; - double dval = 0.0; - std::string sval; -}; - -struct RecWeight { - std::string name; - RadWeightDecl d{}; - /* The uneven slice this weight was handed (rad_weight_shard_span), in the container's - * unsharded units, so tests can check which checkpoint rows each rank reads. Even shards have - * `span_set` false. */ - bool span_set = false; - int64_t span_lo = 0, span_hi = 0; - /* rad_weight_shard_span_parts, recorded likewise. */ - int n_part_spans = 0; - int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0}; - int64_t part_total[RAD_MAX_ROW_PARTS] = {0}; -}; -struct RecBuf { std::string name; RadBufDecl d{}; }; -struct RecOp { - std::string op; - std::vector p; - std::vector w; - std::vector reads, writes; - bool resolved = true; - bool uses_declared = false; /* rad_op_reads/writes were called */ -}; -struct RecMap { - std::string declared; - int mode = 0; - std::vector src; - int concat_dim = 0; -}; -struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; }; -struct RecIssue { - rad_op op = 0; - std::vector opd; - int64_t n = 0; - int lane = 0; /* the lane it was issued on (rad_lane) */ -}; -/* A rad_lane_join: `to` behind everything `from` issued before issue number `at`. */ -struct RecJoin { size_t at = 0; int from = 0, to = 0; }; - -} /* namespace */ - -struct RadBuilder { - std::vector weights; - std::vector bufs; - std::vector ops; - std::vector maps; - std::vector kv_groups; - std::vector> binds; - std::vector notes; - - /* Ops the fake kernel hierarchy refuses, to drive the fused-op fallback; and ops no loaded - * library declares (rad_op_declared), as without an optional library. */ - std::set refuse; - std::set undeclared; - /* When set, the only ops any loaded library declares (a CPU-only engine's: libref's - * vocabulary); every other op is undeclared. */ - const std::set* vocab = nullptr; - std::vector asked_undeclared; /* what a real engine would refuse */ - bool declared(const std::string& op) const { - return vocab ? vocab->count(op) != 0 : undeclared.count(op) == 0; - } - int64_t kv_block = 16; - - /* The buffer the plugin named as this step's logits (rad_declare_logits), or as its pooled - * output (rad_declare_pooled). */ - rad_buf logits = 0; - rad_buf pooled = 0; - - /* The draft head's declaration (rad_declare_drafter), and whether it keeps no cache of its - * own (rad_drafter_shared_kv) and at which rotary offset. */ - RadDrafterDecl drafter{}; - std::string drafter_name; - bool drafter_shared = false; - int drafter_pos = -1; - - /* The buffers named to rad_buf_concurrent: the ones a second lane touches. */ - std::vector concurrent; - - /* The vision and audio encoder declarations (rad_declare_encoder), if any. */ - RadEncoderDecl encoder{}; - std::string encoder_name; - RadEncoderDecl audio_encoder{}; - std::string audio_encoder_name; - - /* The image generator's declaration (rad_declare_generator), if any. */ - RadGeneratorDecl generator{}; - std::string generator_name; - - /* Adapter key names (rad_lora_root, rad_lora_alias): (native, spellings), and each alias as - * (native, from, to, from_lo, from_hi, to_lo). */ - std::vector> lora_roots; - struct LoraAliasRec { std::string native, from, to; int64_t from_lo, from_hi, to_lo; }; - std::vector lora_aliases; - - /* What rad_weight_encoding answers: the first entry whose key the source name contains. Empty - * means no model, so every weight is plain in its declared dtype. */ - std::vector> encs; - - const RecOp* op_of(rad_op h) const { return h ? &ops[h - 1] : nullptr; } -}; - -struct RadCtx { - RadBuilder* b = nullptr; - const RadBatch* batch = nullptr; - int rank = 0; - int world = 1; - std::vector issues; - std::vector routed_layers; - std::string step_fail; - int lane = 0; /* where the next issue goes */ - std::vector joins; - /* Device copies into a buffer (rad_memcpy_async to a rad_buf_ptr address): the buffer and the - * issue number the copy came before. The step lint counts each as a write there. */ - std::vector> copies; -}; - -/* -------------------------------------------------------------------- the declare-side ABI */ -extern "C" rad_weight rad_decl_weight(RadBuilder* b, const char* name, const RadWeightDecl* d) { - b->weights.push_back({name, *d}); - return (rad_weight)b->weights.size(); -} - -extern "C" int rad_weight_encoding(RadBuilder* b, const char* source, RadEncoding* out, int64_t*, - uint32_t*) { - for (const auto& [key, e] : b->encs) - if (source && std::strstr(source, key.c_str())) { *out = e; return RAD_OK; } - return RAD_E_NOTFOUND; -} -extern "C" rad_buf rad_decl_buffer(RadBuilder* b, const char* name, const RadBufDecl* d) { - b->bufs.push_back({name, *d}); - return (rad_buf)b->bufs.size(); -} - -extern "C" rad_op rad_decl_op(RadBuilder* b, const char* op, const RadParam* params, int n_params, - const rad_weight* weights, int n_weights) { - if (!b->declared(op)) { - b->asked_undeclared.push_back(op); - return RAD_NULL_HANDLE; - } - RecOp r; - r.op = op; - for (int i = 0; i < n_params; ++i) { - RecParam p; - p.key = params[i].key ? params[i].key : ""; - p.kind = params[i].kind; - p.ival = params[i].ival; - p.ihi = params[i].ihi; - p.dval = params[i].dval; - p.sval = params[i].sval ? params[i].sval : ""; - r.p.push_back(p); - } - for (int i = 0; i < n_weights; ++i) r.w.push_back(weights[i]); - r.resolved = b->refuse.count(r.op) == 0; - b->ops.push_back(r); - /* Declare always completes. An unresolved op is RAD_NULL_HANDLE, an error only if the plugin - * issues it (rad_builder.h). */ - return r.resolved ? (rad_op)b->ops.size() : RAD_NULL_HANDLE; -} - -extern "C" int rad_op_reads(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { - if (!h) return RAD_E_INVAL; - RecOp& r = b->ops[h - 1]; - r.uses_declared = true; - for (int i = 0; i < n; ++i) r.reads.push_back(bufs[i]); - return RAD_OK; -} - -extern "C" int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n) { - if (!h) return RAD_E_INVAL; - RecOp& r = b->ops[h - 1]; - r.uses_declared = true; - for (int i = 0; i < n; ++i) r.writes.push_back(bufs[i]); - return RAD_OK; -} - -extern "C" int rad_op_resolved(RadBuilder* b, rad_op h) { - return h != RAD_NULL_HANDLE && b->ops[h - 1].resolved; -} - -extern "C" int rad_op_declared(RadBuilder* b, const char* op) { - return op && b->declared(op); -} - -extern "C" rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, - const RadKVGroupDecl* d) { - b->kv_groups.push_back({name, *d, false}); - return (rad_kvgroup)b->kv_groups.size(); -} - -extern "C" int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) { (void)g; return b->kv_block; } - -extern "C" int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) { - b->binds.push_back({layer, g}); - return RAD_OK; -} - -extern "C" int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) { - RecMap r; - r.declared = m->declared; - r.mode = m->mode; - r.concat_dim = m->concat_dim; - for (int i = 0; i < m->n_src; ++i) r.src.push_back(m->src[i]); - b->maps.push_back(r); - return RAD_OK; -} - -extern "C" void rad_note(RadBuilder* b, const char* fmt, ...) { - char buf[512]; - va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); - b->notes.push_back(buf); -} - -/* The buffer the core samples from, recorded so tests can assert the plugin named the narrow - * one: [max_tok, n_vocab] is legal but 8 GiB at this vocabulary. */ -extern "C" int rad_declare_logits(RadBuilder* b, rad_buf logits) { - if (!b || !logits) return RAD_E_INVAL; - b->logits = logits; - return RAD_OK; -} - -/* An embedding program names its pooled output instead of logits; a program declares one. */ -extern "C" int rad_declare_pooled(RadBuilder* b, rad_buf pooled) { - if (!b || !pooled || b->logits) return RAD_E_INVAL; - b->pooled = pooled; - return RAD_OK; -} - -/* An image generator's declaration, recorded whole; it too excludes logits. */ -extern "C" int rad_declare_generator(RadBuilder* b, const RadGeneratorDecl* d) { - if (!b || !d || !d->image_out || b->logits || b->pooled) return RAD_E_INVAL; - b->generator = *d; - b->generator_name = d->name ? d->name : ""; - return RAD_OK; -} - -/* Recorded: a generator's adapter key names. */ -extern "C" int rad_lora_root(RadBuilder* b, const char* native, const char* spellings) { - if (!b || !native || !*native) return RAD_E_INVAL; - b->lora_roots.push_back({ native, spellings ? spellings : "" }); - return RAD_OK; -} -extern "C" int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const char* to, - int64_t from_lo, int64_t from_hi, int64_t to_lo) { - if (!b || !native || !from || !to) return RAD_E_INVAL; - b->lora_aliases.push_back({ native, from, to, from_lo, from_hi, to_lo }); - return RAD_OK; -} - -/* Recorded: gemma4's prefill overlap names the buffers its second lane reduces in place. */ -extern "C" int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { - if (!b || !buf) return RAD_E_INVAL; - b->concurrent.push_back(buf); - return RAD_OK; -} -extern "C" int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) { - if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL; - if (lo < 0 || hi <= lo) return RAD_E_INVAL; - /* The real Builder also checks the declared extent against hi-lo (core/build/rad_builder.cpp); - * the fake only records the span for tests. */ - RecWeight& rw = b->weights[w - 1]; - rw.span_set = true; - rw.span_lo = lo; - rw.span_hi = hi; - return RAD_OK; -} -extern "C" int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, - const int64_t* hi, const int64_t* total, int n) { - if (!b || w == 0 || w > b->weights.size() || !lo || !hi || !total) return RAD_E_INVAL; - if (n < 2 || n > RAD_MAX_ROW_PARTS) return RAD_E_INVAL; - RecWeight& rw = b->weights[w - 1]; - if (rw.d.n_row_parts != n) return RAD_E_INVAL; - for (int g = 0; g < n; ++g) { - if (lo[g] < 0 || hi[g] <= lo[g] || hi[g] > total[g]) return RAD_E_INVAL; - if (rw.d.row_parts[g] != hi[g] - lo[g]) return RAD_E_SHAPE; - rw.part_lo[g] = lo[g]; - rw.part_hi[g] = hi[g]; - rw.part_total[g] = total[g]; - } - rw.n_part_spans = n; - return RAD_OK; -} -extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { - if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL; - b->kv_groups[g - 1].zero = true; - return RAD_OK; -} -extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { - if (!b || !d) return RAD_E_INVAL; - b->drafter = *d; - b->drafter_name = d->name ? d->name : ""; - return RAD_OK; -} -extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { - if (!b || b->drafter.kind != RAD_DRAFT_SERIAL || (pos_offset != 0 && pos_offset != 1)) - return RAD_E_STATE; - b->drafter_shared = true; - b->drafter_pos = pos_offset; - return RAD_OK; -} -extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { - if (!b || !d || !d->name || !d->modalities) return RAD_E_INVAL; - if (d->modalities == RAD_MM_AUDIO) { - b->audio_encoder = *d; - b->audio_encoder_name = d->name; - return RAD_OK; - } - b->encoder = *d; - b->encoder_name = d->name; - return RAD_OK; -} - -/* -------------------------------------------------------------------- model metadata */ -extern "C" long long rad_meta_geti(const RadModelMeta* m, const char* key, long long dflt) { - for (int i = 0; i < m->n_kv; ++i) - if (std::strcmp(m->kv_key[i], key) == 0) return atoll(m->kv_val[i]); - return dflt; -} -extern "C" double rad_meta_getf(const RadModelMeta* m, const char* key, double dflt) { - for (int i = 0; i < m->n_kv; ++i) - if (std::strcmp(m->kv_key[i], key) == 0) return atof(m->kv_val[i]); - return dflt; -} -extern "C" const char* rad_meta_gets(const RadModelMeta* m, const char* key, const char* dflt) { - for (int i = 0; i < m->n_kv; ++i) - if (std::strcmp(m->kv_key[i], key) == 0) return m->kv_val[i]; - return dflt; -} - -/* -------------------------------------------------------------------- the run-phase ABI */ -extern "C" int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n) { - RecIssue r; - r.op = op; - r.n = n; - for (int i = 0; i < n_opd; ++i) r.opd.push_back(opd[i]); - r.lane = c->lane; - c->issues.push_back(r); - return RAD_OK; -} -/* The second lane, recorded: each issue's lane, and each join's position among the issues. */ -extern "C" int rad_lane(RadCtx* c, int lane) { - if (lane != 0 && lane != 1) return RAD_E_INVAL; - c->lane = lane; - return RAD_OK; -} -extern "C" int rad_lane_join(RadCtx* c, int from, int to) { - if (from < 0 || from > 1 || to < 0 || to > 1) return RAD_E_INVAL; - c->joins.push_back({ c->issues.size(), from, to }); - return RAD_OK; -} -/* A block that refuses the batch records the reason for the tests. */ -extern "C" int rad_step_fail(RadCtx* c, const char* what) { - c->step_fail = what ? what : ""; - return RAD_E_SHAPE; -} -extern "C" const RadBatch* rad_batch(RadCtx* c) { return c->batch; } -extern "C" int rad_rank(RadCtx* c) { return c->rank; } -extern "C" int rad_world_size(RadCtx* c) { return c->world; } -/* The context itself, so a copy issued on the step's stream is recorded in it (rad_memcpy_async). */ -extern "C" RadStream rad_stream(RadCtx* c) { return (RadStream)c; } -extern "C" int rad_stream_sync(RadStream s) { (void)s; return RAD_OK; } -extern "C" int rad_route_report(RadCtx* c, int layer, const RadRouting* r) { - (void)r; - c->routed_layers.push_back(layer); - return RAD_OK; -} -/* No card-side histogram here, so a router writes and reports its own buffer. */ -extern "C" int32_t* rad_route_counts(RadCtx* c, int layer, int64_t n_expert) { - (void)c; (void)layer; (void)n_expert; - return nullptr; -} -/* No prefetch here: the three calls are no-ops, as in a core without one. */ -extern "C" int rad_expert_prefetch(RadCtx* c, const RadPrefetchNext* next, rad_buf h, int64_t r0, - int64_t rows, int64_t n_embd) { - (void)c; (void)next; (void)h; (void)r0; (void)rows; (void)n_embd; - return RAD_OK; -} -extern "C" int rad_expert_prefetch_mark(RadCtx* c) { (void)c; return RAD_OK; } -extern "C" int rad_expert_prefetch_step(RadCtx* c, int layer) { (void)c; (void)layer; return RAD_OK; } -/* Never dereferenced: a plugin passes these through to rad_route_report or offsets one into a raw - * operand. Each handle gets its own 2^36-byte window above any user-space address, tagged by - * kind in the top bits, so the step lint can map a raw operand inside a buffer back to that buffer - * (fake_buf_of). */ -constexpr int kFakePtrShift = 36; -constexpr uintptr_t kFakeBufTag = (uintptr_t)1 << 61; -constexpr uintptr_t kFakeWeightTag = (uintptr_t)1 << 62; -extern "C" void* rad_weight_ptr(RadCtx* c, rad_weight w) { - (void)c; - return (void*)(kFakeWeightTag | (uintptr_t)w << kFakePtrShift); -} -extern "C" void* rad_buf_ptr(RadCtx* c, rad_buf b) { - (void)c; - return (void*)(kFakeBufTag | (uintptr_t)b << kFakePtrShift); -} -/* The buffer a raw operand points into, if it came from rad_buf_ptr; 0 otherwise. */ -static rad_buf fake_buf_of(const void* p, size_t n_bufs) { - const uintptr_t u = (uintptr_t)p; - if ((u & ~(kFakeBufTag - 1)) != kFakeBufTag) return 0; - const uintptr_t h = (u & (kFakeBufTag - 1)) >> kFakePtrShift; - return h >= 1 && h <= n_bufs ? (rad_buf)h : 0; -} -/* Pinned host memory a plugin fills itself (qwen4exp_fp8's piece bounds, the calibration tap's - * staging), as host memory; nothing else is handed out. */ -extern "C" void* rad_dev_alloc(int64_t bytes, int kind) { - return kind == RAD_MEM_HOST_PINNED && bytes > 0 ? std::calloc(1, (size_t)bytes) : nullptr; -} -extern "C" void rad_dev_free(void* p, int kind) { if (kind == RAD_MEM_HOST_PINNED) std::free(p); } -/* The device copies: nothing is copied. One into a buffer on a step's stream is recorded as a - * write of that buffer before the next issue (RadCtx::copies). */ -extern "C" int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadStream s) { - (void)src; (void)bytes; - RadCtx* c = (RadCtx*)s; - if (c && c->b) - if (const rad_buf h = fake_buf_of(dst, c->b->bufs.size())) - c->copies.push_back({ c->issues.size(), h }); - return RAD_OK; -} -extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s) { - (void)dst; (void)value; (void)bytes; (void)s; - return RAD_OK; -} - /* ==================================================================== the plugin under test */ #include "../arch/qwen35_bf16/qwen35_bf16.cpp" /* The production architecture, for its sizing declare (RadBuildCtx::shape_probe). */ @@ -503,16 +58,6 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s #include "../arch/qwenimage21/qwenimage21.cpp" /* Anima: a cross-attention generator conditioned through two tokenizers. */ #include "../arch/anima/anima.cpp" -/* GLM-5.3-Flash: its connection, router, attention and cache blocks, and the plugin. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include "../arch/glm5next/glm5next.cpp" /* ==================================================================== fixtures and helpers */ namespace { @@ -635,101 +180,6 @@ RadModelMeta gemma4_draft_meta() { return m; } -RadBuildCtx build_ctx(int rank = 0, int world = 1) { - RadBuildCtx c{}; - c.rank = rank; - c.world_size = world; - c.max_tok = 256; - c.max_seqs = 8; - c.max_ctx = 32768; - c.scope = ""; - return c; -} - -/* The sampled rows (RadBatch::out_ids). The plugin skips the lm_head when n_out is zero (a chunk - * finishing no sequence), so a fake batch must set them or it silently tests the no-logits - * path. */ -static const int32_t kDecodeOut[] = { 0, 1, 2, 3 }; -static const int32_t kPrefillOut[] = { 31, 63 }; /* last token of each 32-token sequence */ - -RadBatch decode_batch() { - RadBatch b{}; - b.phase = RAD_PHASE_DECODE; - b.n_tok = 4; - b.n_seq = 4; - b.max_q_len = 1; - b.max_ctx_len = 100; - b.n_out = 4; - b.out_ids = kDecodeOut; - return b; -} - -RadBatch prefill_batch() { - RadBatch b{}; - b.phase = RAD_PHASE_PREFILL; - b.n_tok = 64; - b.n_seq = 2; - b.max_q_len = 32; - b.max_ctx_len = 32; - b.n_out = 2; - b.out_ids = kPrefillOut; - return b; -} - -/* --- small queries over the recorded graph --- */ -std::vector op_names(const RadBuilder& b) { - std::vector v; - for (const auto& o : b.ops) v.push_back(o.op); - return v; -} - -const RecOp* find_op(const RadBuilder& b, const std::string& name, int nth = 0) { - for (const auto& o : b.ops) - if (o.op == name && nth-- == 0) return &o; - return nullptr; -} - -int count_op(const RadBuilder& b, const std::string& name) { - int n = 0; - for (const auto& o : b.ops) if (o.op == name) ++n; - return n; -} - -const RecParam* param(const RecOp* o, const char* key) { - if (!o) return nullptr; - for (const auto& p : o->p) if (p.key == key) return &p; - return nullptr; -} - -long long pint(const RecOp* o, const char* key) { - const RecParam* p = param(o, key); - return p ? p->ival : -12345; -} - -double pflt(const RecOp* o, const char* key) { - const RecParam* p = param(o, key); - return p ? p->dval : -12345.0; -} - -std::string pstr(const RecOp* o, const char* key) { - const RecParam* p = param(o, key); - return p ? p->sval : std::string(""); -} - -const RecWeight* find_w(const RadBuilder& b, const std::string& name) { - for (const auto& w : b.weights) if (w.name == name) return &w; - return nullptr; -} - -const RecBuf* find_b(const RadBuilder& b, const std::string& name) { - for (const auto& x : b.bufs) if (x.name == name) return &x; - return nullptr; -} - -const RecMap* find_map(const RadBuilder& b, const std::string& declared) { - for (const auto& m : b.maps) if (m.declared == declared) return &m; - return nullptr; -} /* The gated attention layer's ops, listed once for every test. * * The fused qk_norm_rope_gate is not declared: its schema requires a precomputed cos/sin table @@ -793,416 +243,8 @@ std::vector program_ops(bool tp) { return v; } -std::string join(const std::vector& v) { - std::string s; - for (size_t i = 0; i < v.size(); ++i) { if (i) s += " "; s += v[i]; } - return s; -} - -std::vector issued_ops(const RadBuilder& b, const RadCtx& c) { - std::vector got; - for (const auto& i : c.issues) { - const RecOp* o = b.op_of(i.op); - got.push_back(o ? o->op : ""); - } - return got; -} - } /* namespace */ -/* ==================================================================== the step lint - * - * The buffer plan takes liveness from declaration order: a transient lives over the [first, last] - * op indices of its declared reads and writes, and two transients of one arena whose ranges are - * disjoint may share bytes (core/build/rad_bufplan.cpp). A step that issues ops in another order, - * or across passes of one engine step (trunk, drafter history, draft rounds), can write one buffer - * while another that shares its bytes still holds rows a later issue reads. The runtime refuses - * only an op outside a buffer's range, and only on the branch a real model runs, so the class is - * checked here for every recorded step. - * - * lint_step walks the issues of one engine step's passes in order and reports: - * alias a transient read whose last writer is followed, before the read, by a write of a - * transient of the same arena whose range is disjoint from its own; - * undeclared an op issued outside the declared range of a buffer operand - * (core/runtime/issue.cpp refuses this); - * span an operand that reaches past its buffer or weight, rows and columns applied as - * issue.cpp applies them; - * null op an issue of RAD_NULL_HANDLE (a fused op that did not resolve, with no chain); - * unwritten a transient read before any issue, or device copy into it, of the step wrote it; - * kv a cache operand naming a group or layer no rad_bind_layer_kv bound, or a group - * this rank declared zero; - * strided a GEMM whose input is a column slice narrower than its buffer (libr4d's GEMMs - * read whole rows and refuse it). */ -namespace { - -/* One buffer's planned lifetime. `planned` is false for a buffer live over the whole program - * (PERSIST, DERIVED, rad_buf_concurrent, or no declared use), which shares bytes with nothing. */ -struct Live { - int32_t lo = 0, hi = 0; - bool planned = false; - bool transient = false; - int domain = RAD_DOMAIN_DEVICE; -}; - -/* Liveness by the rule of Builder::finish_buffer_liveness (core/build/rad_builder.cpp). Op handle - * h is op index h: the real builder keeps a sentinel at index 0, and the fake hands out ops in - * declaration order from 1. */ -std::vector liveness(const RadBuilder& b) { - const size_t nb = b.bufs.size(); - const int32_t last_op = (int32_t)b.ops.size(); - std::vector first(nb + 1, -1), last(nb + 1, -1); - for (size_t i = 0; i < b.ops.size(); ++i) - for (const std::vector* v : { &b.ops[i].reads, &b.ops[i].writes }) - for (rad_buf h : *v) { - if (h == 0 || h > nb) continue; - if (first[h] < 0) first[h] = (int32_t)(i + 1); - last[h] = (int32_t)(i + 1); - } - std::set conc(b.concurrent.begin(), b.concurrent.end()); - std::vector L(nb + 1); - for (size_t h = 1; h <= nb; ++h) { - const RadBufDecl& d = b.bufs[h - 1].d; - Live& l = L[h]; - l.transient = d.kind == RAD_BUF_TRANSIENT; - l.domain = d.domain; - if (!l.transient || conc.count((rad_buf)h) || first[h] < 0) { - l.lo = 0; - l.hi = last_op; - continue; - } - l.planned = true; - l.lo = first[h]; - l.hi = last[h]; - if ((rad_buf)h == b.logits || (rad_buf)h == b.pooled) l.hi = last_op; - } - return L; -} - -/* Whether operand `o` stays inside a buffer or weight of `shape` (packed strides, rows and cols - * applied as issue.cpp applies them), as issue.cpp's operand_fits decides. */ -bool operand_fits(const int64_t* shape, uint32_t rank, const RadOperand& o) { - if (o.offset < 0) return false; - int64_t sh[RAD_MAX_RANK] = {}, st[RAD_MAX_RANK] = {}; - int64_t numel = 1; - for (uint32_t d = 0; d < rank; ++d) { sh[d] = shape[d]; numel *= shape[d]; } - int64_t s = 1; - for (int d = (int)rank - 1; d >= 0; --d) { st[d] = s; s *= sh[d]; } - if (o.rows > 0 && rank >= 1) sh[0] = o.rows; - if (o.cols > 0 && rank >= 1) sh[rank - 1] = o.cols; - int64_t span = o.offset; - for (uint32_t d = 0; d < rank; ++d) { - if (sh[d] <= 0) return true; - span += (sh[d] - 1) * st[d]; - } - return span < numel; -} - -bool in(const std::vector& v, rad_buf h) { - return std::find(v.begin(), v.end(), h) != v.end(); -} - -std::vector lint_step(const RadBuilder& b, const std::vector& passes) { - std::vector bad; - const std::vector L = liveness(b); - const size_t nb = b.bufs.size(); - auto name = [&](rad_buf h) { return h && h <= nb ? b.bufs[h - 1].name : std::string("?"); }; - auto shares = [&](rad_buf x, rad_buf y) { - const Live& p = L[x]; - const Live& q = L[y]; - return p.planned && q.planned && p.domain == q.domain && (p.hi < q.lo || q.hi < p.lo); - }; - std::set> bound(b.binds.begin(), b.binds.end()); - std::vector last_write(nb + 1, -1); - int64_t pos = 0; - char where[96]; - for (size_t pi = 0; pi < passes.size(); ++pi) { - const RadCtx& c = *passes[pi]; - size_t next_copy = 0; - for (size_t ii = 0; ii < c.issues.size(); ++ii, ++pos) { - for (; next_copy < c.copies.size() && c.copies[next_copy].first <= ii; ++next_copy) - last_write[c.copies[next_copy].second] = pos; - const RecIssue& is = c.issues[ii]; - const RecOp* o = b.op_of(is.op); - std::snprintf(where, sizeof where, "pass %zu issue %zu (%s, op %u)", pi, ii, - o ? o->op.c_str() : "", (unsigned)is.op); - if (!o) { bad.push_back(std::string(where) + ": null op issued"); continue; } - std::vector rd, wr; - for (size_t k = 0; k < is.opd.size(); ++k) { - const RadOperand& od = is.opd[k]; - const std::string at = std::string(where) + " operand " + std::to_string(k); - if (od.kind == RAD_OPK_BUF) { - const rad_buf h = od.handle; - if (h == 0 || h > nb) { - bad.push_back(at + ": buffer handle out of range"); - continue; - } - const RadBufDecl& d = b.bufs[h - 1].d; - if (!operand_fits(d.shape, d.rank, od)) - bad.push_back(at + ": span past '" + name(h) + "' (offset " + - std::to_string(od.offset) + ", rows " + - std::to_string(od.rows) + ", cols " + - std::to_string(od.cols) + ")"); - const Live& l = L[h]; - if (l.planned && ((int32_t)is.op < l.lo || (int32_t)is.op > l.hi)) - bad.push_back(at + ": undeclared use of '" + name(h) + "' (planned ops " + - std::to_string(l.lo) + ".." + std::to_string(l.hi) + ")"); - const bool r = in(o->reads, h), w = in(o->writes, h); - if (r || !w) rd.push_back(h); - if (w || !r) wr.push_back(h); - /* A GEMM's input is read as contiguous rows: libr4d refuses a column slice - * narrower than its buffer. */ - const int64_t width = d.rank ? d.shape[d.rank - 1] : 0; - if (k == 0 && o->op.rfind("gemm_nt", 0) == 0 && od.cols > 0 && - (od.cols != width || od.offset % width)) - bad.push_back(at + ": " + o->op + " reads " + std::to_string(od.cols) + - " of " + std::to_string(width) + " columns of '" + name(h) + - "' as its input, which is not contiguous"); - } else if (od.kind == RAD_OPK_WEIGHT) { - const uint32_t h = od.handle; - if (h == 0 || h > b.weights.size()) { - bad.push_back(at + ": weight handle out of range"); - continue; - } - const RadWeightDecl& d = b.weights[h - 1].d; - if ((od.offset || od.rows > 0 || od.cols > 0) && - !operand_fits(d.shape, d.rank, od)) - bad.push_back(at + ": span past weight '" + b.weights[h - 1].name + "'"); - } else if (od.kind == RAD_OPK_WTAB) { - if (od.handle == 0 || od.rows <= 0 || od.offset || od.cols || - (size_t)(od.handle + od.rows - 1) > b.weights.size()) - bad.push_back(at + ": weight table out of range"); - } else if (od.kind == RAD_OPK_KV) { - const rad_kvgroup g = od.handle; - if (g == 0 || g > b.kv_groups.size()) - bad.push_back(at + ": KV group handle out of range"); - else if (b.kv_groups[g - 1].zero) - bad.push_back(at + ": KV group '" + b.kv_groups[g - 1].name + - "' is declared zero on this rank"); - else if (!bound.count({ (int)od.offset, g })) - bad.push_back(at + ": layer " + std::to_string(od.offset) + - " is not bound to KV group '" + b.kv_groups[g - 1].name + - "'"); - } else if (od.kind == RAD_OPK_RAW) { - if (od.offset && od.dtype == RAD_DT_INVALID) - bad.push_back(at + ": raw operand with an offset and no dtype"); - /* A pointer into a buffer (rad_buf_ptr) is that buffer to the plan, so it is - * classified by the op's declared sets like a buffer operand. */ - if (const rad_buf h = fake_buf_of(od.raw, nb)) { - const Live& l = L[h]; - if (l.planned && ((int32_t)is.op < l.lo || (int32_t)is.op > l.hi)) - bad.push_back(at + ": undeclared use of '" + name(h) + - "' through a raw pointer"); - const bool r = in(o->reads, h), w = in(o->writes, h); - if (r || !w) rd.push_back(h); - if (w || !r) wr.push_back(h); - } - } - } - for (rad_buf h : rd) { - if (!L[h].transient) continue; - const int64_t w = last_write[h]; - if (w < 0) { - bad.push_back(std::string(where) + ": reads '" + name(h) + - "' before any issue of this step wrote it"); - continue; - } - for (size_t x = 1; x <= nb; ++x) - if (x != h && last_write[x] > w && shares(h, (rad_buf)x)) - bad.push_back(std::string(where) + ": reads '" + name(h) + "' (ops " + - std::to_string(L[h].lo) + ".." + std::to_string(L[h].hi) + - ") after a write of '" + name((rad_buf)x) + "' (ops " + - std::to_string(L[x].lo) + ".." + std::to_string(L[x].hi) + - "), which may share its bytes"); - } - for (rad_buf h : wr) last_write[h] = pos; - } - } - return bad; -} - -/* ---------------------------------------------------------------- whole step batches - * - * A batch as the core builds it: every per-token and per-sequence array filled and a group batch - * for every KV group the builder declared, so a plugin's step can take any path. Decode sequences - * come first (RadBatch::n_seq_decode); each `dq` entry is a decode sequence's query length (1, or - * 1 + n_spec for a verify), each `pq` entry a prefill chunk. Every decode row is sampled (a verify - * needs logits at each row) and a chunk's last row; a chunk continues `prefill_ctx` tokens of - * history. */ -struct Kit { - std::vector tok, pos, cu, ctxl, qlen, out, nacc, dout; - std::vector slot, table, used, sidx; - std::vector kv; - RadBatch b{}; -}; - -std::unique_ptr kit(const RadBuilder& bld, const std::vector& dq, - const std::vector& pq, int32_t prefill_ctx = 0) { - auto k = std::make_unique(); - const int64_t nd = (int64_t)dq.size(), ns = nd + (int64_t)pq.size(); - std::vector ql(dq); - ql.insert(ql.end(), pq.begin(), pq.end()); - int64_t T = 0, max_q = 0, max_ctx = 0, td = 0, mqd = 0, mqp = 0; - k->cu.push_back(0); - for (int64_t s = 0; s < ns; ++s) { - const bool dec = s < nd; - const int32_t ctx = dec ? (int32_t)(40 + 7 * s) : prefill_ctx; - for (int i = 0; i < ql[(size_t)s]; ++i) { - k->tok.push_back((int32_t)(3 + (T + i) % 97)); - k->pos.push_back(ctx + i); - if (dec || i + 1 == ql[(size_t)s]) k->out.push_back((int32_t)(T + i)); - } - T += ql[(size_t)s]; - k->cu.push_back((int32_t)T); - k->ctxl.push_back(ctx); - k->qlen.push_back(ql[(size_t)s]); - k->nacc.push_back(1); - k->dout.push_back((int32_t)T - 1); - max_q = std::max(max_q, ql[(size_t)s]); - max_ctx = std::max(max_ctx, ctx + ql[(size_t)s]); - if (dec) { td += ql[(size_t)s]; mqd = std::max(mqd, ql[(size_t)s]); } - else mqp = std::max(mqp, ql[(size_t)s]); - } - k->tok.resize((size_t)T + 64, 5); /* room for a following prompt (RadBatch::n_ahead) */ - const int64_t pitch = 16; - for (int64_t i = 0; i < T; ++i) k->slot.push_back((int32_t)i); - for (int64_t i = 0; i < ns * pitch; ++i) k->table.push_back((int32_t)i); - for (int64_t s = 0; s < ns; ++s) { - k->used.push_back(k->ctxl[(size_t)s] + k->qlen[(size_t)s]); - k->sidx.push_back((int32_t)s); - } - for (size_t g = 0; g < bld.kv_groups.size(); ++g) { - RadKVGroupBatch gb{}; - gb.group = (rad_kvgroup)(g + 1); - gb.slot_mapping = k->slot.data(); - gb.block_table = k->table.data(); - gb.block_table_pitch = pitch; - gb.seqused = k->used.data(); - gb.state_index = k->sidx.data(); - gb.state_index_pitch = 1; - gb.block_size = bld.kv_block; - gb.max_blocks = pitch; - k->kv.push_back(gb); - } - RadBatch& b = k->b; - b.phase = pq.empty() ? RAD_PHASE_DECODE : dq.empty() ? RAD_PHASE_PREFILL : RAD_PHASE_MIXED; - b.n_tok = T; - b.n_seq = ns; - b.token_ids = k->tok.data(); - b.positions = k->pos.data(); - b.cu_seqlens = k->cu.data(); - b.n_out = (int64_t)k->out.size(); - b.out_ids = k->out.data(); - b.q_lens = k->qlen.data(); - b.ctx_lens = k->ctxl.data(); - b.max_q_len = (int32_t)max_q; - b.max_ctx_len = (int32_t)max_ctx; - b.n_kv_groups = (int)k->kv.size(); - b.kv = k->kv.data(); - b.n_spec = mqd > 1 ? (int)(mqd - 1) : 0; - b.num_accepted = k->nacc.data(); - b.n_seq_decode = nd; - b.n_tok_decode = td; - b.max_q_len_decode = (int32_t)mqd; - b.max_q_len_prefill = (int32_t)mqp; - return k; -} - -/* The draft passes the core stages for a step of `n_seq` sequences. - * - * A serial head's history pass (draft_pass -1) covers every row the trunk step had and carries - * round 1 on each sequence's last row; round r (2..depth) is one row a sequence. A block - * drafter's context pass (-1) covers the trunk's rows; its query pass (1) is `block` rows a - * sequence, the anchor first, and samples the `steps` rows after it (RadDrafterDecl::block). */ -std::unique_ptr history_pass(const RadBuilder& bld, const Kit& trunk) { - std::vector rows; - for (int64_t s = 0; s < trunk.b.n_seq; ++s) rows.push_back(trunk.qlen[(size_t)s]); - auto k = kit(bld, rows, {}); - k->b.draft_pass = -1; - k->out.clear(); - for (int64_t i = 0; i < k->b.n_tok; ++i) k->out.push_back((int32_t)i); - k->b.out_ids = k->out.data(); - k->b.n_out = k->b.n_tok; - k->b.n_draft_out = k->b.n_seq; - k->b.draft_out_ids = k->dout.data(); - return k; -} -std::unique_ptr round_pass(const RadBuilder& bld, int64_t n_seq, int r) { - auto k = kit(bld, std::vector((size_t)n_seq, 1), {}); - k->b.draft_pass = r; - return k; -} -std::unique_ptr context_pass(const RadBuilder& bld, const Kit& trunk) { - auto k = history_pass(bld, trunk); - k->b.n_draft_out = 0; - k->b.draft_out_ids = nullptr; - return k; -} -std::unique_ptr query_pass(const RadBuilder& bld, int64_t n_seq, int64_t block, - int64_t steps) { - auto k = kit(bld, std::vector((size_t)n_seq, (int)block), {}); - k->b.draft_pass = 1; - k->out.clear(); - for (int64_t s = 0; s < n_seq; ++s) - for (int64_t i = 0; i < steps; ++i) - k->out.push_back((int32_t)(s * block + block - steps + i)); - k->b.out_ids = k->out.data(); - k->b.n_out = (int64_t)k->out.size(); - return k; -} - -using StepFn = void (*)(RadCtx*, const RadBatch*); - -/* Runs one engine step's passes in order, each on a context of its own. */ -std::vector> run_passes(RadBuilder& b, StepFn step, - const std::vector& passes, - int rank = 0, int world = 1) { - std::vector> out; - for (const Kit* k : passes) { - out.push_back(std::make_unique()); - RadCtx& c = *out.back(); - c.b = &b; - c.batch = &k->b; - c.rank = rank; - c.world = world; - step(&c, &k->b); - } - return out; -} - -std::vector view(const std::vector>& v) { - std::vector p; - for (const auto& c : v) p.push_back(c.get()); - return p; -} - -/* The lint as a check: every finding is printed, and the step passes only with none. */ -size_t report_lint(const std::vector& f) { - for (size_t i = 0; i < f.size() && i < 12; ++i) fprintf(stderr, " lint: %s\n", f[i].c_str()); - if (f.size() > 12) fprintf(stderr, " lint: ... %zu more\n", f.size() - 12); - return f.size(); -} - -/* Every pass of one engine step ran without a step failure. */ -bool steps_ok(const std::vector>& v) { - bool ok = true; - for (size_t i = 0; i < v.size(); ++i) - if (!v[i]->step_fail.empty()) { - fprintf(stderr, " pass %zu failed: %s\n", i, v[i]->step_fail.c_str()); - ok = false; - } - return ok; -} - -} /* namespace */ - -#define CHECK_LINT(b, ...) CHECK_EQ(report_lint(lint_step((b), { __VA_ARGS__ })), (size_t)0) -/* The passes of one engine step (run_passes): none failed and the lint is clean over them. */ -#define CHECK_PASSES(b, v) \ - do { \ - CHECK(steps_ok(v)); \ - CHECK_EQ(report_lint(lint_step((b), view(v))), (size_t)0); \ - } while (0) - /* ==================================================================== tests */ TEST(declare_is_a_qwen35_trunk) { @@ -2331,1144 +1373,6 @@ TEST(the_encodings_the_model_holds_choose_the_flash_next_kernels) { CHECK(!p.layers[0].hc_mix.mix_e4m3); } -TEST(manifold_connections_preserve_saved_coefficients_and_use_a_separate_residual_destination) { - using namespace rad::arch; - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - ManifoldConn::Config cfg; - ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", - "model.layers.3.hc_attn_base" }; - ManifoldConn::Wire w; - w.h = decl_b(&b, "h", RAD_BF16, { 32, 16384 }); - w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); - w.y = decl_b(&b, "y", RAD_BF16, { 32, 4096 }); - w.out = decl_b(&b, "out", RAD_BF16, { 32, 16384 }); - w.post = decl_b(&b, "post", RAD_F32, { 32, 4 }); - w.comb = decl_b(&b, "comb", RAD_F32, { 32, 16 }); - ManifoldConn conn; - REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); - REQUIRE_EQ(b.weights.size(), (size_t)3); - CHECK_EQ(b.weights[0].d.shape[0], 24); - CHECK_EQ(b.weights[0].d.shape[1], 16384); - CHECK_EQ(b.weights[1].d.shape[0], 3); - CHECK_EQ(b.weights[2].d.shape[0], 24); - for (const auto& weight : b.weights) { - CHECK_EQ(weight.d.dtype, RAD_F32); - CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); - } - CHECK(b.ops[conn.op_pre - 1].reads == std::vector({ w.h })); - CHECK(b.ops[conn.op_pre - 1].writes == std::vector({ w.x, w.post, w.comb })); - CHECK(b.ops[conn.op_post - 1].reads == std::vector({ w.y, w.h, w.post, w.comb })); - CHECK(b.ops[conn.op_post - 1].writes == std::vector({ w.out })); - RadCtx ctx; - conn.read(&ctx, 4); - conn.write(&ctx, 4); - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].op, conn.op_pre); - CHECK_EQ(ctx.issues[1].op, conn.op_post); - CHECK_EQ(ctx.issues[0].n, 4); - CHECK_EQ(ctx.issues[1].n, 4); - REQUIRE_EQ(ctx.issues[0].opd.size(), (size_t)7); - CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); - const rad_weight coefficients[] = { conn.w_fn, conn.w_scale, conn.w_base }; - for (int i = 0; i < 3; ++i) { - CHECK_EQ(ctx.issues[0].opd[i + 1].kind, RAD_OPK_WEIGHT); - CHECK_EQ(ctx.issues[0].opd[i + 1].handle, coefficients[i]); - } - CHECK_EQ(ctx.issues[0].opd[4].handle, w.x); - CHECK_EQ(ctx.issues[0].opd[5].handle, w.post); - CHECK_EQ(ctx.issues[0].opd[6].handle, w.comb); - REQUIRE_EQ(ctx.issues[1].opd.size(), (size_t)5); - const rad_buf expected[] = { w.y, w.h, w.post, w.comb, w.out }; - for (int i = 0; i < 5; ++i) { - CHECK_EQ(ctx.issues[1].opd[i].handle, expected[i]); - CHECK_EQ(ctx.issues[1].opd[i].rows, 4); - } - auto invalid = w; - invalid.out = w.h; - ManifoldConn refused; - CHECK_EQ(refused.declare(&b, nm, g, 3, "bad", cfg, invalid, src), RAD_E_INVAL); -} - -TEST(manifold_read_splits_its_projection_by_chunks_over_ranks_from_the_row_threshold) { - using namespace rad::arch; - for (int world : { 1, 2, 4, 8 }) - for (int rank = 0; rank < world; ++rank) { - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 512; - g.world = world; - g.rank = rank; - ManifoldConn::Config cfg; - ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", - "model.layers.3.hc_attn_base" }; - ManifoldConn::Wire w; - w.h = decl_b(&b, "h", RAD_BF16, { 512, 16384 }); - w.x = decl_b(&b, "x", RAD_BF16, { 512, 4096 }); - w.y = decl_b(&b, "y", RAD_BF16, { 512, 4096 }); - w.out = decl_b(&b, "out", RAD_BF16, { 512, 16384 }); - w.post = decl_b(&b, "post", RAD_F32, { 512, 4 }); - w.comb = decl_b(&b, "comb", RAD_F32, { 512, 16 }); - ManifoldConn conn; - REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); - const bool split = world > 1; - const int64_t mine = 8 / world; - CHECK_EQ(count_op(b, "mhc_pre"), 1); - CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 1 : 0); - CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); - CHECK_EQ(count_op(b, "mhc_pre_finish"), split ? 1 : 0); - CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); - if (split) { - const RecOp* part = find_op(b, "mhc_pre_partial"); - const RecOp* gather = find_op(b, "all_gather"); - const RecOp* finish = find_op(b, "mhc_pre_finish"); - REQUIRE(part && gather && finish); - CHECK_EQ(pint(part, "chunk"), 2048); - CHECK_EQ(pint(part, "first"), rank * mine); - CHECK_EQ(pint(part, "chunks"), mine); - CHECK(part->w == std::vector({ conn.w_fn })); - CHECK(part->reads == std::vector({ w.h })); - CHECK(part->writes == std::vector({ conn.part })); - CHECK_EQ(pint(gather, "world_size"), world); - CHECK_EQ(pint(gather, "row"), mine * 28); - CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); - CHECK_EQ(param(gather, "numel")->ival, mine * 28); - CHECK_EQ(param(gather, "numel")->ihi, 512 * mine * 28); - CHECK_EQ(pstr(gather, "dtype"), "f32"); - CHECK(gather->reads == std::vector({ conn.part })); - CHECK(gather->writes == std::vector({ conn.parts })); - CHECK_EQ(pint(finish, "chunk"), 2048); - CHECK_EQ(pint(finish, "iterations"), 20); - CHECK(finish->w == std::vector({ conn.w_scale, conn.w_base })); - CHECK(finish->reads == std::vector({ conn.parts, w.h })); - CHECK(finish->writes == std::vector({ w.x, w.post, w.comb })); - CHECK_EQ(find_b(b, "blk.3.mhc_attn.parts")->d.shape[1], 8 * 28); - } - RadCtx ctx; - conn.read(&ctx, 300); - conn.read(&ctx, 255); - if (split) { - REQUIRE_EQ(ctx.issues.size(), (size_t)4); - CHECK_EQ(ctx.issues[0].op, conn.op_partial); - CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); - CHECK_EQ(ctx.issues[0].opd[0].rows, 300); - CHECK_EQ(ctx.issues[0].opd[1].handle, conn.w_fn); - CHECK_EQ(ctx.issues[0].opd[2].handle, conn.part); - CHECK_EQ(ctx.issues[1].op, conn.op_gather); - CHECK_EQ(ctx.issues[1].n, 300 * mine * 28); - CHECK_EQ(ctx.issues[1].opd[1].handle, conn.parts); - CHECK_EQ(ctx.issues[1].opd[1].rows, 300); - CHECK_EQ(ctx.issues[2].op, conn.op_finish); - REQUIRE_EQ(ctx.issues[2].opd.size(), (size_t)7); - const uint32_t expected[] = { conn.parts, w.h, conn.w_scale, conn.w_base, - w.x, w.post, w.comb }; - for (int i = 0; i < 7; ++i) CHECK_EQ(ctx.issues[2].opd[i].handle, expected[i]); - CHECK_EQ(ctx.issues[3].op, conn.op_pre); - } else { - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].op, conn.op_pre); - CHECK_EQ(ctx.issues[1].op, conn.op_pre); - } - } -} - -TEST(glm_routing_keeps_f32_logits_and_correction_replicated_under_tp4) { - using namespace rad::arch; - for (int rank = 0; rank < 4; ++rank) { - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 128; - g.world = 4; - g.rank = rank; - GlmRouter::Config cfg; - GlmRouter::Wire w; - w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); - w.logits = decl_b(&b, "logits", RAD_F32, { 32, 288 }); - w.ids = decl_b(&b, "ids", RAD_I32, { 32, 8 }); - w.weights = decl_b(&b, "weights", RAD_F32, { 32, 8 }); - GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", - "model.layers.3.mlp.gate.e_score_correction_bias" }; - GlmRouter router; - REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); - REQUIRE_EQ(b.weights.size(), (size_t)2); - for (const auto& weight : b.weights) { - CHECK_EQ(weight.d.dtype, RAD_F32); - CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); - } - CHECK_EQ(b.weights[0].d.shape[0], 288); - CHECK_EQ(b.weights[0].d.shape[1], 4096); - CHECK_EQ(b.ops[router.op_project - 1].op, std::string("gemm_nt_f32")); - CHECK_EQ(b.ops[router.op_select - 1].op, std::string("router_sigmoid_topk")); - RadCtx ctx; - router.step(&ctx, 7, 4); - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); - CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); - CHECK_EQ(ctx.issues[0].opd[0].rows, 4); - CHECK_EQ(ctx.issues[1].opd[1].handle, router.correction); - CHECK_EQ(ctx.issues[1].opd[2].handle, w.ids); - CHECK_EQ(ctx.issues[1].opd[3].handle, w.weights); - } -} - -TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold) { - using namespace rad::arch; - for (int world : { 1, 2, 4, 8 }) - for (int rank = 0; rank < world; ++rank) { - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 512; - g.world = world; - g.rank = rank; - GlmRouter::Config cfg; - cfg.rows = 512; - GlmRouter::Wire w; - w.input = decl_b(&b, "hidden", RAD_BF16, { 512, 4096 }); - w.logits = decl_b(&b, "logits", RAD_F32, { 512, 288 }); - w.ids = decl_b(&b, "ids", RAD_I32, { 512, 8 }); - w.weights = decl_b(&b, "weights", RAD_F32, { 512, 8 }); - GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", - "model.layers.3.mlp.gate.e_score_correction_bias" }; - GlmRouter router; - REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); - const bool split = world > 1; - const int64_t cols = 288 / world; - CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); - CHECK_EQ(count_op(b, "gemm_nt_f32"), split ? 2 : 1); - // The weight stays whole and replicated: decode keeps the unsplit projection. - CHECK_EQ(b.weights[0].d.shape[0], 288); - CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); - if (split) { - const RecOp* part = find_op(b, "gemm_nt_f32", 1); - const RecOp* gather = find_op(b, "all_gather"); - REQUIRE(part && gather); - CHECK_EQ(pint(part, "N"), cols); - CHECK_EQ(pint(part, "K"), 4096); - CHECK(part->w == std::vector({ router.projection })); - CHECK(part->reads == std::vector({ w.input })); - CHECK(part->writes == std::vector({ router.split.part })); - CHECK_EQ(pint(gather, "world_size"), world); - CHECK_EQ(pint(gather, "row"), cols); - CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); - CHECK_EQ(param(gather, "numel")->ival, cols); - CHECK_EQ(param(gather, "numel")->ihi, 512 * cols); - CHECK_EQ(pstr(gather, "dtype"), "f32"); - CHECK(gather->reads == std::vector({ router.split.part })); - CHECK(gather->writes == std::vector({ w.logits })); - } - RadCtx ctx; - router.step(&ctx, 7, 300, 7); - if (split) { - REQUIRE_EQ(ctx.issues.size(), (size_t)3); - CHECK_EQ(ctx.issues[0].op, router.split.op_part); - CHECK_EQ(ctx.issues[0].n, 300); - CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); - CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); - CHECK_EQ(ctx.issues[0].opd[0].rows, 300); - CHECK_EQ(ctx.issues[0].opd[1].kind, RAD_OPK_WEIGHT); - CHECK_EQ(ctx.issues[0].opd[1].handle, router.projection); - CHECK_EQ(ctx.issues[0].opd[1].offset, rank * cols * 4096); - CHECK_EQ(ctx.issues[0].opd[1].rows, cols); - CHECK_EQ(ctx.issues[0].opd[2].handle, router.split.part); - CHECK_EQ(ctx.issues[0].opd[2].rows, 300); - CHECK_EQ(ctx.issues[1].op, router.split.op_gather); - CHECK_EQ(ctx.issues[1].n, 300 * cols); - CHECK_EQ(ctx.issues[1].opd[0].handle, router.split.part); - CHECK_EQ(ctx.issues[1].opd[1].handle, w.logits); - CHECK_EQ(ctx.issues[1].opd[1].offset, 7 * 288); - CHECK_EQ(ctx.issues[1].opd[1].rows, 300); - CHECK_EQ(ctx.issues[2].op, router.op_select); - } else { - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].op, router.op_project); - } - ctx.issues.clear(); - router.step(&ctx, 0, 255); - REQUIRE_EQ(ctx.issues.size(), (size_t)2); - CHECK_EQ(ctx.issues[0].op, router.op_project); - } -} - -TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { - using namespace rad::arch; - for (int rank = 0; rank < 4; ++rank) { - RadBuilder b; - b.kv_block = 4; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - g.rank = rank; - RadKVGroupDecl kd{}; - kd.kind = RAD_KV_FULL; - kd.dtype = RAD_BF16; - kd.n_head_kv = 1; - kd.head_dim = 256; - const rad_kvgroup kv = rad_decl_kv_group(&b, "latent", &kd); - MlaLatent::Config cfg; - MlaLatent::Wire w; - w.q = decl_b(&b, "q", RAD_BF16, { 32, 16, 256 }); - w.q_latent = decl_b(&b, "ql", RAD_BF16, { 32, 16, 512 }); - w.attn_latent = decl_b(&b, "al", RAD_BF16, { 32, 16, 512 }); - w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 256 }); - w.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); - w.length = decl_b(&b, "length", RAD_I32, { 32 }); - MlaLatent block; - REQUIRE_EQ( - block.declare(&b, nm, g, 3, kv, cfg, w, "model.layers.3.self_attn.kv_b_proj.weight"), - RAD_OK); - REQUIRE_EQ(b.weights.size(), (size_t)1); - CHECK_EQ(b.weights[0].d.dtype, RAD_BF16); - CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_ROW); - CHECK_EQ(b.weights[0].d.shape[0], 8192); - CHECK_EQ(b.weights[0].d.shape[1], 512); - RadCtx ctx; - block.step(&ctx, 4); - REQUIRE_EQ(ctx.issues.size(), (size_t)3); - CHECK_EQ(b.ops[ctx.issues[0].op - 1].op, std::string("mla_project")); - CHECK_EQ(b.ops[ctx.issues[1].op - 1].op, std::string("mla_attn")); - CHECK_EQ(b.ops[ctx.issues[2].op - 1].op, std::string("mla_project")); - CHECK_EQ(ctx.issues[1].opd[1].kind, RAD_OPK_KV); - CHECK_EQ(ctx.issues[1].opd[2].handle, w.selected); - CHECK_EQ(ctx.issues[1].opd[3].handle, w.length); - CHECK_EQ(ctx.issues[2].opd[1].handle, block.projection); - } -} - -TEST( - glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) { - using namespace rad::arch; - const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", - "index_topk" }; - const char* vals[] = { "1", "4", "288", "2048" }; - RadModelMeta meta{}; - meta.n_layers = 45; - meta.n_embd = 4096; - meta.n_vocab = 154880; - meta.rms_eps = 1e-5f; - meta.n_kv = 4; - meta.kv_key = keys; - meta.kv_val = vals; - const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); - const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - for (int world : { 1, 4, 8 }) - for (int rank = 0; rank < world; ++rank) { - RadBuilder b; - b.kv_block = 4; - b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, - { "mtp.blk.45.ffn_down_exps", fp8 }, - { "ffn_gate_up_exps", mx }, - { "ffn_down_exps", mx }, - { "ffn_gate_up_shexp", mx }, - { "ffn_down_shexp", mx }, - { "ffn_gate_up.weight", fp8 }, - { "ffn_down.weight", fp8 } }; - RadBuildCtx build{}; - build.rank = rank; - build.world_size = world; - build.max_tok = rank == 0 ? 512 : 16; - build.max_seqs = 4; - build.max_ctx = 4096; - build.max_spec = 3; - REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); - const auto& m = *glm5next::models[rank]; - CHECK(m.have_mtp); - CHECK_EQ(b.drafter.kind, RAD_DRAFT_SERIAL); - CHECK_EQ(b.drafter.depth, 3); - CHECK_EQ(m.layers.size(), (size_t)45); - int full = 0; - for (int l = 0; l < 45; ++l) { - const auto& layer = m.layers[l]; - full += layer.full; - CHECK(layer.attn_hc.op_pre < layer.norm.op); - CHECK(layer.attn_hc.op_post < layer.ffn_hc.op_pre); - if (layer.full) { - CHECK(layer.index.cache.op_select < layer.mla.core.op_attn); - CHECK(layer.mla.output.op < layer.attn_hc.op_post); - } else - CHECK(layer.kda.output.op < layer.attn_hc.op_post); - if (l >= 3) { - CHECK_EQ(layer.moe.c.expert_mx, 1); - CHECK(layer.moe.op_gather < layer.ffn_hc.op_post); - } - } - CHECK_EQ(full, 11); - CHECK_EQ(m.draft.moe.c.expert_f32_scale, 1); - for (const auto& map : b.maps) - if (map.declared.starts_with("mtp.")) - for (const auto& source : map.src) CHECK(!source.starts_with("mtp.model.")); - int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, - slots[] = { 0, 1 }, out[] = { 1 }; - int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; - std::vector kv(b.kv_groups.size()); - for (size_t i = 0; i < kv.size(); ++i) { - kv[i].group = (rad_kvgroup)i + 1; - kv[i].slot_mapping = slots; - kv[i].block_table = tables; - kv[i].block_table_pitch = 32; - kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; - kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; - } - RadBatch batch{}; - batch.phase = RAD_PHASE_PREFILL; - batch.n_tok = 2; - batch.n_seq = 1; - batch.token_ids = ids; - batch.positions = positions; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.kv = kv.data(); - batch.n_kv_groups = (int)kv.size(); - batch.n_out = 1; - batch.out_ids = out; - RadCtx ctx; - ctx.b = &b; - ctx.rank = rank; - ctx.world = world; - ctx.batch = &batch; - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - const auto ops = issued_ops(b, ctx); - CHECK_EQ(std::count(ops.begin(), ops.end(), "mhc_pre"), 90); - CHECK_EQ(std::count(ops.begin(), ops.end(), "kda_update"), 34); - CHECK_EQ(std::count(ops.begin(), ops.end(), "mla_attn"), 11); - // Two rows stay under the split threshold: 42 routers and 11 index heads, replicated. - CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt_f32"), 53); - CHECK_EQ(std::count(ops.begin(), ops.end(), "all_gather"), 0); - // The split is declared on every rank whatever its step size; only rank 0 issues it here. - const bool split = world > 1; - // 43 routers and 12 index heads (MTP included), and the 90 mHC reads. - CHECK_EQ(count_op(b, "all_gather"), split ? 55 + 90 : 0); - CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0); - ctx.issues.clear(); - batch.draft_pass = -1; - batch.n_draft_out = 1; - batch.draft_out_ids = out; - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - const auto draft_ops = issued_ops(b, ctx); - CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mhc_pre"), 0); - CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mla_attn"), 1); - CHECK_EQ(ctx.issues.back().op, m.mhead); - CHECK(m.mselect < m.draft.moe.op_router); - for (const auto& issue : ctx.issues) { - if (issue.op == m.draft.moe.op_router || issue.op == m.mnorm_op) - CHECK_EQ(issue.opd[0].rows, 1); // Only the row producing a proposal. - if (issue.op == m.draft.residual) - CHECK_EQ(issue.opd[0].rows, 2); // Full history still fills attention caches. - } - ctx.issues.clear(); - batch.n_draft_out = 0; - glm5next::step(&ctx, &batch); - const auto history = issued_ops(b, ctx); - CHECK(std::find(history.begin(), history.end(), "kv_store") != history.end()); - CHECK(std::find(history.begin(), history.end(), "moe_gemm_q") == history.end()); - if (rank == 0) { - std::vector long_ids(512, 7), long_positions(512), long_slots(512), - long_tables(1024); - for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; - int32_t long_cu[] = { 0, 512 }, last = 511; - for (auto& group : kv) { - group.slot_mapping = long_slots.data(); - group.block_table = long_tables.data(); - group.block_table_pitch = 1024; - } - batch.n_tok = 512; - batch.token_ids = long_ids.data(); - batch.positions = long_positions.data(); - batch.cu_seqlens = long_cu; - batch.out_ids = &last; - batch.draft_pass = 0; - batch.max_q_len = 512; - ctx.issues.clear(); - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - { - // 512 rows reach the split: each projection runs on its column slice and each - // mHC read on its chunks, both gathered; at TP1 nothing changes. - const auto long_ops = issued_ops(b, ctx); - CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "gemm_nt_f32"), 53); - CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_gather"), - world > 1 ? 53 + 90 : 0); - CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre"), - world > 1 ? 0 : 90); - CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre_finish"), - world > 1 ? 90 : 0); - for (const auto& issue : ctx.issues) { - if (b.ops[issue.op - 1].op != "gemm_nt_f32") continue; - const int64_t n = pint(&b.ops[issue.op - 1], "N"); - if (world == 1) - CHECK(n == 288 || n == 32); - else { - CHECK(n == 288 / world || n == 32 / world); - CHECK_EQ(issue.opd[1].rows, n); - } - } - } - for (int l = 3; l < 45; ++l) { - // A prefill routes its full batch once, reusing each expert's - // weights across its rows instead of re-reading them in chunks. - CHECK_EQ(std::count_if(ctx.issues.begin(), ctx.issues.end(), - [&](const auto& issue) { - const auto& moe = m.layers[l].moe; - return issue.op == moe.op_router || - issue.op == moe.glm_router.split.op_part; - }), - 1); - } - // Arena-lending probes must not replace the model the serving - // graph's handles refer to, even when they declare fewer rows. - const auto* live = glm5next::models[rank].get(); - RadBuilder pb; - pb.kv_block = 4; - pb.encs = b.encs; - auto small = build; - small.shape_probe = 1; - small.max_tok = 1; - REQUIRE_EQ(glm5next::declare(&pb, &meta, &small), RAD_OK); - CHECK_EQ(glm5next::models[rank].get(), live); - CHECK_EQ(glm5next::models[rank]->g.max_tok, 512); - RadArchProbe capabilities{}; - REQUIRE_EQ(glm5next::probe(&meta, &capabilities), RAD_OK); - CHECK_EQ(capabilities.shape_probe_ok, 1); - std::array results{}; - std::vector probes; - for (int i = 0; i < 8; ++i) - probes.emplace_back([&, i] { - RadBuilder parallel; - parallel.kv_block = 4; - parallel.encs = b.encs; - auto level = build; - level.rank = i % 4; - level.max_tok = i < 4 ? 256 : 1024; - level.shape_probe = 1; - results[i] = glm5next::declare(¶llel, &meta, &level); - }); - for (auto& thread : probes) thread.join(); - for (int status : results) CHECK_EQ(status, RAD_OK); - CHECK_EQ(glm5next::models[rank].get(), live); - } - } -} - -/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and - * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row - * counts and buffer rows smaller. The TP split declares its ops whatever the step size and its - * gathers' message as a range. */ -TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) { - const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", - "index_topk" }; - const char* vals[] = { "1", "4", "288", "2048" }; - RadModelMeta meta{}; - meta.n_layers = 45; - meta.n_embd = 4096; - meta.n_vocab = 154880; - meta.rms_eps = 1e-5f; - meta.n_kv = 4; - meta.kv_key = keys; - meta.kv_val = vals; - const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); - const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - const int world = 8, rank = 3; - for (int64_t R : { 256, 3072 }) { - auto encs = [&](RadBuilder& b) { - b.kv_block = 4; - b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, - { "mtp.blk.45.ffn_down_exps", fp8 }, - { "ffn_gate_up_exps", mx }, - { "ffn_down_exps", mx }, - { "ffn_gate_up_shexp", mx }, - { "ffn_down_shexp", mx }, - { "ffn_gate_up.weight", fp8 }, - { "ffn_down.weight", fp8 } }; - }; - RadBuildCtx c{}; - c.rank = rank; - c.world_size = world; - c.max_tok = 4096; - c.max_seqs = 8; - c.max_ctx = 32768; - c.max_spec = 3; - RadBuilder full; - encs(full); - REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); - RadBuildCtx p = c; - p.max_tok = R; - p.shape_probe = 1; - RadBuilder small; - encs(small); - REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); - REQUIRE_EQ(small.ops.size(), full.ops.size()); - int differ = 0; - for (size_t i = 0; i < full.ops.size(); ++i) { - if (small.ops[i].op != full.ops[i].op) { - ++differ; - continue; - } - REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); - for (size_t k = 0; k < full.ops[i].p.size(); ++k) { - const RecParam& a = full.ops[i].p[k]; - const RecParam& q = small.ops[i].p[k]; - if (a.kind == RAD_P_RANGE) continue; - // A capacity may shrink: its kernel writes by its operands' extents. - if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) - continue; - if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { - fprintf(stderr, - " R %lld: op %zu '%s' param '%s': " - "%lld real, %lld small\n", - (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), - a.ival, q.ival); - ++differ; - } - } - } - CHECK_EQ(differ, 0); - REQUIRE_EQ(small.bufs.size(), full.bufs.size()); - for (size_t i = 0; i < full.bufs.size(); ++i) - for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) - CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); - } -} - -/* The MoE block's decode fusions: over a two-row trunk step, its draft pass and a 512-row prefill - * (past the router fusion's one-workgroup sort), each fused launch stands where it fits and the - * launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's - * row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) in every MoE pass. */ -TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { - const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", - "index_topk" }; - const char* vals[] = { "1", "4", "288", "2048" }; - RadModelMeta meta{}; - meta.n_layers = 45; - meta.n_embd = 4096; - meta.n_vocab = 154880; - meta.rms_eps = 1e-5f; - meta.n_kv = 4; - meta.kv_key = keys; - meta.kv_val = vals; - const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); - const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - using Counts = std::map; - /* Launches per step: trunk, draft pass, prefill. The trunk has 42 MoE layers, each a routed - * and a shared clamped SwiGLU, and three dense ones. */ - struct Want { - const char* op; - int trunk, draft, prefill; - }; - const Want wants[] = { - { "router_sigmoid_topk_scatter", 42, 1, 0 }, { "router_sigmoid_topk", 0, 0, 42 }, - { "swiglu_clamped_quant_fp8", 87, 2, 87 }, { "swiglu_clamped", 0, 0, 0 }, - { "moe_scatter", 0, 0, 0 }, { "moe_gather", 0, 0, 0 }, - }; - for (int world : { 1, 8 }) { - RadBuilder b; - b.kv_block = 4; - b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, - { "mtp.blk.45.ffn_down_exps", fp8 }, - { "ffn_gate_up_exps", mx }, - { "ffn_down_exps", mx }, - { "ffn_gate_up_shexp", mx }, - { "ffn_down_shexp", mx }, - { "ffn_gate_up.weight", fp8 }, - { "ffn_down.weight", fp8 } }; - RadBuildCtx build{}; - build.rank = 0; - build.world_size = world; - build.max_tok = 512; - build.max_seqs = 4; - build.max_ctx = 4096; - build.max_spec = 3; - REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); - int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, - slots[] = { 0, 1 }, out[] = { 1 }; - int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; - std::vector kv(b.kv_groups.size()); - for (size_t i = 0; i < kv.size(); ++i) { - kv[i].group = (rad_kvgroup)i + 1; - kv[i].slot_mapping = slots; - kv[i].block_table = tables; - kv[i].block_table_pitch = 32; - kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; - kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; - } - RadBatch batch{}; - batch.phase = RAD_PHASE_PREFILL; - batch.n_tok = 2; - batch.n_seq = 1; - batch.token_ids = ids; - batch.positions = positions; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.kv = kv.data(); - batch.n_kv_groups = (int)kv.size(); - batch.n_out = 1; - batch.out_ids = out; - RadCtx ctx; - ctx.b = &b; - ctx.rank = 0; - ctx.world = world; - ctx.batch = &batch; - Counts got[3]; - /* With the inverse, the fused selection writes it as its ninth operand and the gather - * reads it as its third. */ - const rad_buf inv = find_b(b, "expert_inverse") - ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) - : 0; - REQUIRE(inv != 0); - auto run = [&](int k) { - ctx.issues.clear(); - glm5next::step(&ctx, &batch); - CHECK(ctx.step_fail.empty()); - CHECK_LINT(b, &ctx); - for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; - for (const auto& is : ctx.issues) { - const RecOp* o = b.op_of(is.op); - if (!o) continue; - if (o->op == "router_sigmoid_topk_scatter") - CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && - is.opd[8].handle == inv); - if (o->op == "moe_gather_inv") - CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && - is.opd[2].handle == inv); - } - }; - run(0); - batch.draft_pass = -1; - batch.n_draft_out = 1; - batch.draft_out_ids = out; - run(1); - std::vector long_ids(512, 7), long_positions(512), long_slots(512), - long_tables(1024); - for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; - int32_t long_cu[] = { 0, 512 }, last = 511; - for (auto& group : kv) { - group.slot_mapping = long_slots.data(); - group.block_table = long_tables.data(); - group.block_table_pitch = 1024; - } - batch.n_tok = 512; - batch.token_ids = long_ids.data(); - batch.positions = long_positions.data(); - batch.cu_seqlens = long_cu; - batch.out_ids = &last; - batch.draft_pass = 0; - batch.n_draft_out = 0; - batch.max_q_len = 512; - run(2); - for (int k = 0; k < 3; ++k) - for (const Want& w : wants) { - const int want = k == 0 ? w.trunk : k == 1 ? w.draft : w.prefill; - if (got[k][w.op] != want) - fprintf(stderr, " world %d step %d: %s %d (want %d)\n", world, k, w.op, - got[k][w.op], want); - CHECK_EQ(got[k][w.op], want); - } - } -} - -TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ring) { - using namespace rad::arch; - for (bool front : { false, true }) { - RadBuilder b; - b.kv_block = 4; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.max_seqs = 4; - g.max_spec = 3; - RadKVGroupDecl ad{}; - ad.kind = RAD_KV_FULL; - ad.dtype = RAD_BF16; - ad.n_head_kv = 1; - ad.head_dim = 256; - const auto attn = rad_decl_kv_group(&b, "attn", &ad); - // Claim the attention group's consumer before declaring the index group. - RAD_OP(&b, "mla_attn", RAD_PARAMS(RAD_INT("block_size", 4)), RAD_NOWEIGHTS); - RadKVGroupDecl td{}; - td.kind = RAD_KV_LINEAR; - td.dtype = RAD_BF16; - td.n_head_kv = 1; - td.state_dim[0] = 7; - td.state_dim[1] = 256; - const auto tail = rad_decl_kv_group(&b, "tail", &td); - DsaCache::Wire w; - w.query = decl_b(&b, "query", RAD_BF16, { 1024, 128 }); - w.codes = decl_b(&b, "codes", RAD_F8E4M3, { 1024, 128 }); - w.scales = decl_b(&b, "scales", RAD_F32, { 1024, 1 }); - w.gate = decl_b(&b, "gates", RAD_F32, { 32, 32 }); - w.kg = decl_b(&b, "kg", RAD_BF16, { 32, 256 }); - w.stage = decl_b(&b, "stage", RAD_BF16, { 48, 256 }); - w.page = decl_b(&b, "page", RAD_I32, { 12 }); - w.bpos = decl_b(&b, "bpos", RAD_I32, { 12 }); - w.nc = decl_b(&b, "nc", RAD_I32, { 4 }); - w.pooled = decl_b(&b, "pooled", RAD_F8E4M3, { 12, 128 }); - w.pool_scale = decl_b(&b, "pool_scale", RAD_F32, { 12, 1 }); - w.score = decl_b(&b, "score", RAD_F32, { 32, 1024 }); - w.selected = decl_b(&b, "sel", RAD_I32, { 32, 513 }); - w.nsel = decl_b(&b, "nsel", RAD_I32, { 32 }); - w.length = decl_b(&b, "len", RAD_I32, { 32 }); - DsaCache block; - DsaCache::Config cfg; - cfg.blocks = 1024; - cfg.work = 12; - cfg.ring = 7; - rad_kvgroup index = 0; - GlmIndexer indexer; - if (front) { - GlmIndexer::Wire iw; - iw.cache = w; - iw.input = decl_b(&b, "input", RAD_BF16, { 32, 4096 }); - iw.q_low = decl_b(&b, "q_low", RAD_BF16, { 32, 1536 }); - iw.q_wide = decl_b(&b, "q_wide", RAD_BF16, { 32, 4096 }); - iw.kg_raw = decl_b(&b, "kg_raw", RAD_BF16, { 32, 256 }); - REQUIRE_EQ(indexer.declare(&b, nm, g, 3, iw, "indexer", cfg, attn, tail, &index), - RAD_OK); - block = indexer.cache; - CHECK_EQ(b.weights[indexer.head_weight - 1].d.dtype, RAD_F32); - CHECK_EQ(b.weights[indexer.query.w - 1].d.shard, RAD_SHARD_NONE); - CHECK_EQ(b.weights[indexer.key_gate.w - 1].d.shard, RAD_SHARD_NONE); - } else - REQUIRE_EQ(block.declare(&b, nm, g, 3, cfg, w, attn, tail, &index, "indexer.pool.ape"), - RAD_OK); - CHECK_EQ(b.kv_groups[index - 1].d.dtype, RAD_U8); - CHECK_EQ(b.kv_groups[index - 1].d.head_dim, 17); - int32_t ibt[16]{}, abt[16]{}, sidx[12]{}, cu[] = { 0, 3, 8 }, pos[8]{}; - RadKVGroupBatch kv[3]{}; - kv[0].group = index; - kv[0].block_table = ibt; - kv[0].block_table_pitch = 8; - kv[1].group = tail; - kv[1].state_index = sidx; - kv[1].state_index_pitch = 6; - kv[2].group = attn; - kv[2].block_table = abt; - kv[2].block_table_pitch = 8; - RadBatch batch{}; - batch.n_tok = 8; - batch.n_seq = 2; - batch.n_spec = 2; - batch.kv = kv; - batch.n_kv_groups = 3; - batch.positions = pos; - batch.cu_seqlens = cu; - batch.max_ctx_len = 64; // Mixed-row bound exceeds the eight physical table columns. - RadCtx ctx; - ctx.b = &b; - ctx.batch = &batch; - if (front) { - indexer.step(&ctx, &batch); - REQUIRE_EQ(ctx.issues.size(), (size_t)12); - CHECK_EQ(ctx.issues[1].op, indexer.op_query_copy); - CHECK_EQ(ctx.issues[1].opd[1].rows, 256); - CHECK_EQ(ctx.issues[3].op, indexer.op_norm); - CHECK_EQ(ctx.issues[4].opd[0].offset, 128); - CHECK_EQ(ctx.issues[5].op, indexer.op_head); - ctx.issues.erase(ctx.issues.begin(), ctx.issues.begin() + 6); - } else - block.step(&ctx, &batch); - REQUIRE_EQ(ctx.issues.size(), (size_t)6); - CHECK_EQ(ctx.issues[0].n, 256); - CHECK(ctx.issues[1].opd[5].raw == ibt); - CHECK_EQ(ctx.issues[1].opd[4].cols, 6); - CHECK_EQ(ctx.issues[2].op, block.op_pool); - CHECK_EQ(ctx.issues[2].opd[5].handle, index); - CHECK_EQ(ctx.issues[3].op, block.op_tail); - CHECK_EQ(ctx.issues[4].opd[0].rows, 256); - CHECK_EQ(ctx.issues[4].opd[3].handle, index); - CHECK_EQ(ctx.issues[4].opd[4].kind, RAD_OPK_NONE); - CHECK(ctx.issues[4].opd[5].raw == ibt); - CHECK_EQ(ctx.issues[4].opd[8].cols, 8); - CHECK_EQ(ctx.issues[5].opd[0].cols, 8); - CHECK(ctx.issues[5].opd[1].raw == abt); - } -} - -TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) { - using namespace rad::arch; - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.n_ff = 3072; - g.max_tok = 32; - g.world = 4; - const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - b.encs = { { "ffn_gate_up", fp8 }, { "ffn_down", fp8 } }; - MlpFP8::Wire w; - w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); - w.h.x = decl_b(&b, "h", RAD_BF16, { 32, 4096 }); - REQUIRE_EQ(w.h.declare_qs(&b, nm, g, "h", 4096), RAD_OK); - w.gate_up = decl_b(&b, "gate_up", RAD_BF16, { 32, 6144 }); - w.ffn.x = decl_b(&b, "ffn", RAD_BF16, { 32, 3072 }); - REQUIRE_EQ(w.ffn.declare_qs(&b, nm, g, "ffn", 3072), RAD_OK); - MlpFP8 block; - MlpFP8::Src src{ "post_attention_layernorm.weight", "mlp.gate_proj.weight", - "mlp.up_proj.weight", "mlp.down_proj.weight" }; - REQUIRE_EQ(block.declare(&b, nm, g, 0, w, src, false, false, kArNone, false, 10), RAD_OK); - CHECK_EQ(block.op_gated, 0u); - CHECK_EQ(b.ops[block.gq_ffn.op - 1].op, std::string("swiglu_clamped")); - RadCtx ctx; - ctx.b = &b; - block.slice(&ctx, 8, 4, 4); - const auto ops = issued_ops(b, ctx); - CHECK_EQ(std::count(ops.begin(), ops.end(), "swiglu_clamped"), 1); - CHECK(std::find(ops.begin(), ops.end(), "gemm_nt_q_gated") == ops.end()); - CHECK(std::find(ops.begin(), ops.end(), "quant_act_fp8") != ops.end()); -} - -TEST(glm_mla_stores_one_normalized_latent_and_exposes_q_lora_before_sparse_attention) { - using namespace rad::arch; - for (int rank = 0; rank < 4; ++rank) { - RadBuilder b; - b.kv_block = 4; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - g.rank = rank; - RadKVGroupDecl kd{}; - kd.kind = RAD_KV_FULL; - kd.dtype = RAD_BF16; - kd.n_head_kv = 1; - kd.head_dim = 256; - const auto kv = rad_decl_kv_group(&b, "latent", &kd); - auto buf = [&](const char* name, int64_t n) { - return decl_b(&b, name, RAD_BF16, { 32, n }); - }; - GlmMla::Wire w; - w.input.x = buf("input", 4096); - w.q_raw = buf("q_raw", 1536); - w.kv_raw = buf("kv_raw", 512); - w.q_low.x = buf("q_low", 1536); - w.latent = buf("latent_out", 512); - w.out = buf("out", 4096); - REQUIRE_EQ(w.input.declare_qs(&b, nm, g, "input", 4096), RAD_OK); - REQUIRE_EQ(w.q_low.declare_qs(&b, nm, g, "q_low", 1536), RAD_OK); - w.core.q = buf("q", 4096); - w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { 32, 16, 512 }); - w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { 32, 16, 512 }); - w.core.out = buf("expanded", 4096); - w.attn.x = w.core.out; - REQUIRE_EQ(w.attn.declare_qs(&b, nm, g, "expanded", 4096), RAD_OK); - w.core.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); - w.core.length = decl_b(&b, "length", RAD_I32, { 32 }); - GlmMla block; - REQUIRE_EQ(block.declare(&b, nm, g, 3, w, "attn", kv), RAD_OK); - CHECK_EQ(b.weights[block.q_a.w - 1].d.shard, RAD_SHARD_NONE); - CHECK_EQ(b.weights[block.q_b.w - 1].d.shard, RAD_SHARD_ROW); - CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); - int32_t slots[4]{}; - RadKVGroupBatch kb{}; - kb.group = kv; - kb.slot_mapping = slots; - RadBatch batch{}; - batch.n_tok = 4; - batch.kv = &kb; - batch.n_kv_groups = 1; - RadCtx ctx; - ctx.b = &b; - ctx.batch = &batch; - block.prepare(&ctx, &batch); - auto find_issue = [&](rad_op op) -> const RecIssue* { - for (const auto& issue : ctx.issues) - if (issue.op == op) return &issue; - return nullptr; - }; - const auto* store = find_issue(block.op_store); - REQUIRE(store); - CHECK_EQ(store->opd[0].handle, w.latent); - CHECK_EQ(store->opd[0].cols, 256); - CHECK_EQ(store->opd[1].offset, 256); - CHECK_EQ(store->opd[1].cols, 256); - CHECK(store->opd[2].raw == slots); - const auto before = issued_ops(b, ctx); - CHECK(std::find(before.begin(), before.end(), "mla_attn") == before.end()); - block.finish(&ctx, &batch); - const auto* attn = find_issue(block.core.op_attn); - REQUIRE(attn); - CHECK_EQ(attn->opd[2].handle, w.core.selected); - CHECK_EQ(ctx.issues.back().op, block.op_ar); - } -} - -TEST(glm_kda_projects_local_heads_and_reduces_only_after_the_output_projection) { - using namespace rad::arch; - for (int rank = 0; rank < 4; ++rank) { - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - g.rank = rank; - g.max_spec = 3; - RadKVGroupDecl sd{}; - sd.kind = RAD_KV_LINEAR; - sd.dtype = RAD_F32; - sd.n_head_kv = 16; - sd.state_dim[0] = sd.state_dim[1] = 128; - RadKVGroupDecl cd{}; - cd.kind = RAD_KV_CONV; - cd.dtype = RAD_BF16; - cd.n_head_kv = 1; - cd.head_dim = 6144; - cd.conv_width = 4; - const auto state = rad_decl_kv_group(&b, "state", &sd), - history = rad_decl_kv_group(&b, "conv", &cd); - auto buf = [&](const char* name, int64_t width) { - return decl_b(&b, name, RAD_BF16, { 32, width }); - }; - GlmKda::Wire w; - w.input = buf("input", 4096); - w.forget_low = buf("forget_low", 128); - w.gate_low = buf("gate_low", 128); - w.out = buf("out", 4096); - w.core.qkv = buf("qkv", 6144); - w.core.conv = buf("conv_out", 6144); - w.core.a = buf("a", 2048); - w.core.beta = buf("beta", 16); - w.core.gate = buf("gate", 2048); - w.core.out = buf("core_out", 2048); - KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", - "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; - GlmKda block; - REQUIRE_EQ(block.declare(&b, nm, g, 0, w, "attn", src, state, history), RAD_OK); - CHECK_EQ(b.weights[block.qkv.w - 1].d.n_row_parts, 3); - CHECK_EQ(b.weights[block.forget_a.w - 1].d.shard, RAD_SHARD_NONE); - CHECK_EQ(b.weights[block.forget_b.w - 1].d.shard, RAD_SHARD_ROW); - CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); - int32_t cu[] = { 0, 4 }, ctxlens[] = { 0 }, indices[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }; - RadKVGroupBatch kv[2]{}; - kv[0].group = state; - kv[0].state_index = indices; - kv[0].state_index_pitch = 6; - kv[1].group = history; - kv[1].state_index = ci; - RadBatch batch{}; - batch.phase = RAD_PHASE_PREFILL; - batch.n_tok = 4; - batch.n_seq = 1; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.kv = kv; - batch.n_kv_groups = 2; - RadCtx ctx; - ctx.b = &b; - ctx.batch = &batch; - block.step(&ctx, &batch); - const auto ops = issued_ops(b, ctx); - CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt"), 7); - CHECK_EQ(std::count(ops.begin(), ops.end(), "silu"), 0); - REQUIRE_EQ(ctx.issues.size(), (size_t)11); - CHECK_EQ(ctx.issues[9].op, block.output.op); - CHECK_EQ(ctx.issues[10].op, block.op_ar); - CHECK_EQ(ctx.issues[10].opd[0].handle, w.out); - } -} - -TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets) { - using namespace rad::arch; - RadBuilder b; - Names nm(""); - Geom g{}; - g.n_embd = 4096; - g.max_tok = 32; - g.world = 4; - g.max_spec = 3; - RadKVGroupDecl sd{}; - sd.kind = RAD_KV_LINEAR; - sd.dtype = RAD_F32; - sd.n_head_kv = 16; - sd.state_dim[0] = sd.state_dim[1] = 128; - RadKVGroupDecl cd{}; - cd.kind = RAD_KV_CONV; - cd.dtype = RAD_BF16; - cd.n_head_kv = 1; - cd.head_dim = 6144; - cd.conv_width = 4; - const rad_kvgroup st = rad_decl_kv_group(&b, "state", &sd), - cv = rad_decl_kv_group(&b, "conv", &cd); - KdaState::Wire w; - w.qkv = decl_b(&b, "qkv", RAD_BF16, { 32, 6144 }); - w.conv = decl_b(&b, "filtered", RAD_BF16, { 32, 6144 }); - w.a = decl_b(&b, "a", RAD_BF16, { 32, 2048 }); - w.beta = decl_b(&b, "beta", RAD_BF16, { 32, 16 }); - w.gate = decl_b(&b, "gate", RAD_BF16, { 32, 2048 }); - w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 128 }); - KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", - "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; - KdaState block; - KdaState::Config cfg; - REQUIRE_EQ(block.declare(&b, nm, g, 0, st, cv, cfg, w, src), RAD_OK); - CHECK_EQ(b.weights[block.taps - 1].d.n_row_parts, 3); - for (int p = 0; p < 3; ++p) CHECK_EQ(b.weights[block.taps - 1].d.row_parts[p], 2048); - CHECK_EQ(b.weights[block.bias - 1].d.shape[0], 2048); - for (rad_op op : { block.op_prefill, block.op_verify }) { - bool found = false; - for (const auto& p : b.ops[op - 1].p) - if (p.key == "state_form") { - CHECK_EQ(p.sval, std::string("anchor")); - found = true; - } - CHECK(found); - } - int32_t cu[] = { 0, 3, 8 }, ctxlens[] = { 11, 0 }, accepted[] = { 2, 1 }; - int32_t indices[] = { 0, 0, 0, 2, 2, 2, 1, 1, 1, 3, 3, 3 }, conv_indices[] = { 0, 1 }; - RadKVGroupBatch kv[2]{}; - kv[0].group = st; - kv[0].state_index = indices; - kv[0].state_index_pitch = 6; - kv[1].group = cv; - kv[1].state_index = conv_indices; - kv[1].state_index_pitch = 1; - RadBatch batch{}; - batch.phase = RAD_PHASE_MIXED; - batch.n_tok = 8; - batch.n_seq = 2; - batch.n_seq_decode = 1; - batch.n_tok_decode = 3; - batch.cu_seqlens = cu; - batch.ctx_lens = ctxlens; - batch.num_accepted = accepted; - batch.kv = kv; - batch.n_kv_groups = 2; - RadCtx ctx; - ctx.b = &b; - ctx.batch = &batch; - block.step(&ctx, &batch); - REQUIRE_EQ(ctx.issues.size(), (size_t)5); - CHECK_EQ(ctx.issues[0].op, block.op_conv); - CHECK_EQ(ctx.issues[0].n, 3); - CHECK_EQ(ctx.issues[1].op, block.op_verify); - CHECK_EQ(ctx.issues[1].opd[0].cols, 2048); - CHECK_EQ(ctx.issues[1].opd[1].offset, 2048); - CHECK_EQ(ctx.issues[1].opd[2].offset, 4096); - CHECK_EQ(ctx.issues[2].op, block.op_conv); - CHECK_EQ(ctx.issues[2].n, 8); - CHECK(ctx.issues[2].opd[3].raw == cu + 1); - CHECK_EQ(ctx.issues[2].opd[7].kind, RAD_OPK_NONE); - CHECK_EQ(ctx.issues[3].op, block.op_prefill); - CHECK(ctx.issues[3].opd[8].raw == indices + 6); - CHECK(ctx.issues[3].opd[9].raw == cu + 1); - CHECK_EQ(ctx.issues[3].opd[0].offset, 0); - CHECK_EQ(ctx.issues[3].opd[0].rows, 8); - CHECK_EQ(ctx.issues[4].op, block.op_norm); -} - TEST(mxfp4_expert_declarations_preserve_tp4_and_tp8_scale_geometry_and_movement_groups) { using namespace rad::arch; const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); @@ -4488,14 +2392,6 @@ const RecOp* issued_op(const RadBuilder& b, const RadCtx& c, const std::string& } return nullptr; } -const RecIssue* issue_of(const RadBuilder& b, const RadCtx& c, const std::string& name, - int nth = 0) { - for (const auto& i : c.issues) { - const RecOp* o = b.op_of(i.op); - if (o && o->op == name && nth-- == 0) return &i; - } - return nullptr; -} } /* namespace */ @@ -5972,10 +3868,6 @@ int count_resolved(const RadBuilder& b, const std::string& name) { return n; } -int count_issued(const std::vector& v, const std::string& name) { - return (int)std::count(v.begin(), v.end(), name); -} - } /* namespace */ TEST(a_gemma4_moe_trunk_declares_both_arms_and_the_joins) { @@ -6905,50 +4797,6 @@ TEST(the_step_lint_reports_each_rule_it_checks) { namespace { -/* `fn`'s status, with what it prints kept out of the test output. */ -int stderr_of_rc(const std::function& fn) { - int rc = 0; - stderr_of([&] { rc = fn(); }); - return rc; -} - -/* Model metadata built key by key; `meta()` is valid while this object lives. */ -struct MetaKV { - RadModelMeta m{}; - std::vector keys, vals; - std::vector kp, vp; - explicit MetaKV(const RadModelMeta& base) : m(base) { - for (int i = 0; i < base.n_kv; ++i) set(base.kv_key[i], base.kv_val[i]); - } - MetaKV& set(const char* k, const char* v) { - for (size_t i = 0; i < keys.size(); ++i) - if (keys[i] == k) { vals[i] = v; return *this; } - keys.push_back(k); - vals.push_back(v); - return *this; - } - MetaKV& drop(const char* k) { - for (size_t i = 0; i < keys.size(); ++i) - if (keys[i] == k) { - keys.erase(keys.begin() + (long)i); - vals.erase(vals.begin() + (long)i); - break; - } - return *this; - } - const RadModelMeta* meta() { - kp.clear(); vp.clear(); - for (size_t i = 0; i < keys.size(); ++i) { - kp.push_back(keys[i].c_str()); - vp.push_back(vals[i].c_str()); - } - m.n_kv = (int)kp.size(); - m.kv_key = kp.data(); - m.kv_val = vp.data(); - return &m; - } -}; - /* Qwen3.8-27B-FP8's shape cut to the eight-layer fixture, its MTP head declared. */ MetaKV q35fp8_meta() { MetaKV k(qwen35_meta()); @@ -6992,12 +4840,6 @@ MetaKV with_dflash2(MetaKV k) { return k; } -RadBuildCtx spec_ctx(int rank, int world, int max_spec) { - RadBuildCtx c = build_ctx(rank, world); - c.max_spec = max_spec; - return c; -} - /* Every gemm_nt handle a pass issues is issued once: the bf16 GEMMs take a whole pass in one * launch (libr4d's bf16 row serves M to 65536), so a slice loop would be a stale band. */ bool each_gemm_nt_once(const RadBuilder& b, const RadCtx& c) { @@ -9110,57 +6952,6 @@ std::string joined(const std::set& s) { return r.empty() ? std::string("(none)") : r; } -/* A 64-bit FNV-1a fingerprint of everything a declare recorded: ops with their parameters, - * weights, read and write sets and resolution; buffers, weights, KV groups, bindings, name maps, - * the logits / pooled / drafter / generator declarations and the concurrent list. Two declares - * give one value only if the core would build the same program from them. */ -struct Fnv { - uint64_t h = 1469598103934665603ull; - Fnv& raw(const void* p, size_t n) { - const auto* c = (const unsigned char*)p; - for (size_t i = 0; i < n; ++i) { h ^= c[i]; h *= 1099511628211ull; } - return *this; - } - Fnv& s(const std::string& x) { return raw(x.data(), x.size()).i((int64_t)x.size()); } - Fnv& s(const char* x) { return s(std::string(x ? x : "")); } - Fnv& i(int64_t v) { return raw(&v, sizeof v); } - Fnv& f(double v) { return raw(&v, sizeof v); } -}; -uint64_t graph_hash(const RadBuilder& b) { - Fnv f; - for (const RecOp& o : b.ops) { - f.s(o.op).i(o.resolved).i((int64_t)o.p.size()); - for (const RecParam& p : o.p) f.s(p.key).i(p.kind).i(p.ival).i(p.ihi).f(p.dval).s(p.sval); - for (const auto* v : { &o.w, &o.reads, &o.writes }) { - f.i((int64_t)v->size()); - for (uint32_t x : *v) f.i(x); - } - } - for (const RecBuf& x : b.bufs) { - f.s(x.name).i(x.d.dtype).i(x.d.rank).i(x.d.kind).i(x.d.domain).i(x.d.kv).s(x.d.derive); - for (uint32_t d = 0; d < x.d.rank; ++d) f.i(x.d.shape[d]); - } - for (const RecWeight& w : b.weights) { - f.s(w.name).i(w.d.dtype).i(w.d.rank).i(w.d.shard).i(w.d.access).i(w.d.group.layer) - .i(w.d.group.expert).s(w.d.source).s(w.d.planes).i(w.d.n_row_parts).i(w.span_lo) - .i(w.span_hi).i(w.n_part_spans); - for (uint32_t d = 0; d < w.d.rank; ++d) f.i(w.d.shape[d]); - } - for (const RecKV& g : b.kv_groups) - f.s(g.name).i(g.d.kind).i(g.d.dtype).i(g.d.window).i(g.d.n_head_kv).i(g.d.head_dim) - .i(g.d.state_dim[0]).i(g.d.state_dim[1]).i(g.d.conv_width).i(g.zero); - for (const auto& [l, g] : b.binds) f.i(l).i(g); - for (const RecMap& m : b.maps) { - f.s(m.declared).i(m.mode).i(m.concat_dim); - for (const auto& x : m.src) f.s(x); - } - f.i(b.logits).i(b.pooled).s(b.drafter_name).i(b.drafter.kind).i(b.drafter.depth) - .i(b.drafter.block).i(b.drafter.proposal).i(b.drafter.mask_token).i(b.drafter_shared) - .s(b.encoder_name).s(b.audio_encoder_name).s(b.generator_name); - for (rad_buf x : b.concurrent) f.i(x); - return f.h; -} - } /* namespace */ /* For every architecture, declaring with only libref's vocabulary either asks for nothing else and @@ -9706,93 +7497,6 @@ TEST(qwen3asr_refuses_a_tower_it_does_not_serve) { RAD_TEST_MAIN() -/* ==================================================================== a 4096 budget without a span */ -namespace { - -/* What a step issued, as a fingerprint: each launch's op (by name and declared parameters), row - * count and lane, every operand by kind, buffer or weight name, offset and extent, a raw operand - * by the batch array and element it points at, and every lane join. */ -uint64_t issue_hash(const RadBuilder& b, const std::vector>& v, - const std::vector& kits) { - Fnv f; - auto raw_at = [&](const void* p) { - if (!p) { f.i(-1); return; } - if (const rad_buf h = fake_buf_of(p, b.bufs.size())) { - f.i(1).s(b.bufs[h - 1].name) - .i((int64_t)((uintptr_t)p - (uintptr_t)rad_buf_ptr(nullptr, h))); - return; - } - for (size_t k = 0; k < kits.size(); ++k) { - const Kit& t = *kits[k]; - const std::vector* arrays[] = { &t.tok, &t.pos, &t.cu, &t.ctxl, &t.qlen, - &t.out, &t.nacc, &t.dout, &t.slot, &t.table, - &t.used, &t.sidx }; - for (size_t a = 0; a < sizeof arrays / sizeof arrays[0]; ++a) { - const std::vector& x = *arrays[a]; - const int32_t* q = (const int32_t*)p; - if (!x.empty() && q >= x.data() && q < x.data() + x.size()) { - f.i(2).i((int64_t)a).i((int64_t)(q - x.data())); - return; - } - } - } - f.i(3); - }; - for (const auto& c : v) { - f.i((int64_t)c->issues.size()); - for (const RecIssue& r : c->issues) { - const RecOp* o = b.op_of(r.op); - f.s(o ? o->op : ""); - if (o) - for (const RecParam& p : o->p) f.s(p.key).i(p.ival).i(p.ihi).f(p.dval).s(p.sval); - f.i(r.n).i(r.lane).i((int64_t)r.opd.size()); - for (const RadOperand& d : r.opd) { - f.i(d.kind).i(d.dtype).i(d.offset).i(d.rows).i(d.cols); - if (d.kind == RAD_OPK_BUF) - f.s(d.handle && d.handle <= b.bufs.size() ? b.bufs[d.handle - 1].name : "?"); - else if (d.kind == RAD_OPK_WEIGHT || d.kind == RAD_OPK_WTAB) - f.s(d.handle && d.handle <= b.weights.size() ? b.weights[d.handle - 1].name - : "?"); - else if (d.kind == RAD_OPK_RAW) - raw_at(d.raw); - else - f.i(d.handle); - } - } - for (const RecJoin& j : c->joins) f.i((int64_t)j.at).i(j.from).i(j.to); - } - return f.h; -} - -/* The steps of the fingerprint: a 4096-row prefill after 4096 tokens of history (wider than a - * MoE pass), a mixed step, a decode step, and with a drafter a verify and its first passes. */ -uint64_t pinned_steps(RadBuilder& b, StepFn step, int rank, int world) { - const auto pf = kit(b, {}, { 4096 }, 4096); - const auto mx = kit(b, { 1, 1 }, { 2000 }, 3000); - const auto dc = kit(b, { 1, 1, 1 }, {}); - std::vector> all; - std::vector kits; - for (const Kit* k : { pf.get(), mx.get(), dc.get() }) { - auto v = run_passes(b, step, { k }, rank, world); - CHECK_PASSES(b, v); - for (auto& c : v) all.push_back(std::move(c)); - kits.push_back(k); - } - std::unique_ptr ver, his, r2; - if (b.drafter.kind == RAD_DRAFT_SERIAL) { - ver = kit(b, std::vector(3, 4), {}); - his = history_pass(b, *ver); - r2 = round_pass(b, 3, 2); - auto v = run_passes(b, step, { ver.get(), his.get(), r2.get() }, rank, world); - CHECK_PASSES(b, v); - for (auto& c : v) all.push_back(std::move(c)); - kits.push_back(ver.get()); kits.push_back(his.get()); kits.push_back(r2.get()); - } - return issue_hash(b, all, kits); -} - -} /* namespace */ - /* Without --prefill-span a 4096 budget declares and steps the pinned graph and launches: for * Flash-Next and the other plugins built on the same fp8 blocks, at one, two and four ranks, taken * from the plugins as they were before the span. */ @@ -9843,53 +7547,6 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { } } -/* GLM declares and steps the pinned graph and launches at one and eight ranks: a 4096-row prefill - * after history, a mixed step, a decode step, a verify and its draft passes. */ -TEST(glm53_is_the_pinned_graph_and_steps) { - const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", - "index_topk" }; - const char* vals[] = { "1", "4", "288", "2048" }; - RadModelMeta meta{}; - meta.n_layers = 45; - meta.n_embd = 4096; - meta.n_vocab = 154880; - meta.rms_eps = 1e-5f; - meta.n_kv = 4; - meta.kv_key = keys; - meta.kv_val = vals; - const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); - const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); - struct Case { - int world; - uint64_t graph, steps; - }; - const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull }, - { 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } }; - for (const Case& cs : cases) { - RadBuilder b; - b.kv_block = 4; - b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, - { "mtp.blk.45.ffn_down_exps", fp8 }, - { "ffn_gate_up_exps", mx }, - { "ffn_down_exps", mx }, - { "ffn_gate_up_shexp", mx }, - { "ffn_down_shexp", mx }, - { "ffn_gate_up.weight", fp8 }, - { "ffn_down.weight", fp8 } }; - RadBuildCtx ctx = spec_ctx(0, cs.world, 3); - ctx.max_tok = 4096; - ctx.max_seqs = 8; - ctx.max_ctx = 200000; - REQUIRE_EQ(glm5next::declare(&b, &meta, &ctx), RAD_OK); - const uint64_t g = graph_hash(b); - const uint64_t s = pinned_steps(b, glm5next::step, 0, cs.world); - fprintf(stderr, " pin: glm5next world %d: graph 0x%016llxull, steps 0x%016llxull\n", - cs.world, (unsigned long long)g, (unsigned long long)s); - CHECK_EQ(g, cs.graph); - CHECK_EQ(s, cs.steps); - } -} - /* Under a span a Flash-Next prefill of two intervals runs a pass at a time. At every world its * connection reads take a pass each and the indexer scores its pass-tall plane in windows, the MTP * head's pass included. At four ranks the step is pipelined (step_pipelined): every layer's diff --git a/tests/glm5next_test.cpp b/tests/glm5next_test.cpp new file mode 100644 index 00000000..f6c7adfb --- /dev/null +++ b/tests/glm5next_test.cpp @@ -0,0 +1,1628 @@ +/* glm5next_test.cpp -- the declared graph and the steps of GLM-5.3-Flash's plugin and its blocks, + * asserted statically against the recording builder of arch_fakes.h. */ +#define RAD_ARCH_NO_EXPORTS 1 + +#include "arch_fakes.h" + +#include +#include +#include +#include + +/* ==================================================================== the plugin under test */ + +/* GLM-5.3-Flash: its blocks (through the plugin's includes) and the plugin. */ +#include "../arch/glm5next/glm5next.cpp" + +/* ==================================================================== the blocks */ + +TEST(manifold_connections_preserve_saved_coefficients_and_use_a_separate_residual_destination) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + ManifoldConn::Config cfg; + ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", + "model.layers.3.hc_attn_base" }; + ManifoldConn::Wire w; + w.h = decl_b(&b, "h", RAD_BF16, { 32, 16384 }); + w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); + w.y = decl_b(&b, "y", RAD_BF16, { 32, 4096 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16384 }); + w.post = decl_b(&b, "post", RAD_F32, { 32, 4 }); + w.comb = decl_b(&b, "comb", RAD_F32, { 32, 16 }); + ManifoldConn conn; + REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)3); + CHECK_EQ(b.weights[0].d.shape[0], 24); + CHECK_EQ(b.weights[0].d.shape[1], 16384); + CHECK_EQ(b.weights[1].d.shape[0], 3); + CHECK_EQ(b.weights[2].d.shape[0], 24); + for (const auto& weight : b.weights) { + CHECK_EQ(weight.d.dtype, RAD_F32); + CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); + } + CHECK(b.ops[conn.op_pre - 1].reads == std::vector({ w.h })); + CHECK(b.ops[conn.op_pre - 1].writes == std::vector({ w.x, w.post, w.comb })); + CHECK(b.ops[conn.op_post - 1].reads == std::vector({ w.y, w.h, w.post, w.comb })); + CHECK(b.ops[conn.op_post - 1].writes == std::vector({ w.out })); + RadCtx ctx; + conn.read(&ctx, 4); + conn.write(&ctx, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, conn.op_pre); + CHECK_EQ(ctx.issues[1].op, conn.op_post); + CHECK_EQ(ctx.issues[0].n, 4); + CHECK_EQ(ctx.issues[1].n, 4); + REQUIRE_EQ(ctx.issues[0].opd.size(), (size_t)7); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); + const rad_weight coefficients[] = { conn.w_fn, conn.w_scale, conn.w_base }; + for (int i = 0; i < 3; ++i) { + CHECK_EQ(ctx.issues[0].opd[i + 1].kind, RAD_OPK_WEIGHT); + CHECK_EQ(ctx.issues[0].opd[i + 1].handle, coefficients[i]); + } + CHECK_EQ(ctx.issues[0].opd[4].handle, w.x); + CHECK_EQ(ctx.issues[0].opd[5].handle, w.post); + CHECK_EQ(ctx.issues[0].opd[6].handle, w.comb); + REQUIRE_EQ(ctx.issues[1].opd.size(), (size_t)5); + const rad_buf expected[] = { w.y, w.h, w.post, w.comb, w.out }; + for (int i = 0; i < 5; ++i) { + CHECK_EQ(ctx.issues[1].opd[i].handle, expected[i]); + CHECK_EQ(ctx.issues[1].opd[i].rows, 4); + } + auto invalid = w; + invalid.out = w.h; + ManifoldConn refused; + CHECK_EQ(refused.declare(&b, nm, g, 3, "bad", cfg, invalid, src), RAD_E_INVAL); +} + +TEST(manifold_read_splits_its_projection_by_chunks_over_ranks_from_the_row_threshold) { + using namespace rad::arch; + for (int world : { 1, 2, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.world = world; + g.rank = rank; + ManifoldConn::Config cfg; + ManifoldConn::Src src{ "model.layers.3.hc_attn_fn", "model.layers.3.hc_attn_scale", + "model.layers.3.hc_attn_base" }; + ManifoldConn::Wire w; + w.h = decl_b(&b, "h", RAD_BF16, { 512, 16384 }); + w.x = decl_b(&b, "x", RAD_BF16, { 512, 4096 }); + w.y = decl_b(&b, "y", RAD_BF16, { 512, 4096 }); + w.out = decl_b(&b, "out", RAD_BF16, { 512, 16384 }); + w.post = decl_b(&b, "post", RAD_F32, { 512, 4 }); + w.comb = decl_b(&b, "comb", RAD_F32, { 512, 16 }); + ManifoldConn conn; + REQUIRE_EQ(conn.declare(&b, nm, g, 3, "blk.3.mhc_attn", cfg, w, src), RAD_OK); + const bool split = world > 1; + const int64_t mine = 8 / world; + CHECK_EQ(count_op(b, "mhc_pre"), 1); + CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 1 : 0); + CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); + CHECK_EQ(count_op(b, "mhc_pre_finish"), split ? 1 : 0); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); + if (split) { + const RecOp* part = find_op(b, "mhc_pre_partial"); + const RecOp* gather = find_op(b, "all_gather"); + const RecOp* finish = find_op(b, "mhc_pre_finish"); + REQUIRE(part && gather && finish); + CHECK_EQ(pint(part, "chunk"), 2048); + CHECK_EQ(pint(part, "first"), rank * mine); + CHECK_EQ(pint(part, "chunks"), mine); + CHECK(part->w == std::vector({ conn.w_fn })); + CHECK(part->reads == std::vector({ w.h })); + CHECK(part->writes == std::vector({ conn.part })); + CHECK_EQ(pint(gather, "world_size"), world); + CHECK_EQ(pint(gather, "row"), mine * 28); + CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); + CHECK_EQ(param(gather, "numel")->ival, mine * 28); + CHECK_EQ(param(gather, "numel")->ihi, 512 * mine * 28); + CHECK_EQ(pstr(gather, "dtype"), "f32"); + CHECK(gather->reads == std::vector({ conn.part })); + CHECK(gather->writes == std::vector({ conn.parts })); + CHECK_EQ(pint(finish, "chunk"), 2048); + CHECK_EQ(pint(finish, "iterations"), 20); + CHECK(finish->w == std::vector({ conn.w_scale, conn.w_base })); + CHECK(finish->reads == std::vector({ conn.parts, w.h })); + CHECK(finish->writes == std::vector({ w.x, w.post, w.comb })); + CHECK_EQ(find_b(b, "blk.3.mhc_attn.parts")->d.shape[1], 8 * 28); + } + RadCtx ctx; + conn.read(&ctx, 300); + conn.read(&ctx, 255); + if (split) { + REQUIRE_EQ(ctx.issues.size(), (size_t)4); + CHECK_EQ(ctx.issues[0].op, conn.op_partial); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.h); + CHECK_EQ(ctx.issues[0].opd[0].rows, 300); + CHECK_EQ(ctx.issues[0].opd[1].handle, conn.w_fn); + CHECK_EQ(ctx.issues[0].opd[2].handle, conn.part); + CHECK_EQ(ctx.issues[1].op, conn.op_gather); + CHECK_EQ(ctx.issues[1].n, 300 * mine * 28); + CHECK_EQ(ctx.issues[1].opd[1].handle, conn.parts); + CHECK_EQ(ctx.issues[1].opd[1].rows, 300); + CHECK_EQ(ctx.issues[2].op, conn.op_finish); + REQUIRE_EQ(ctx.issues[2].opd.size(), (size_t)7); + const uint32_t expected[] = { conn.parts, w.h, conn.w_scale, conn.w_base, + w.x, w.post, w.comb }; + for (int i = 0; i < 7; ++i) CHECK_EQ(ctx.issues[2].opd[i].handle, expected[i]); + CHECK_EQ(ctx.issues[3].op, conn.op_pre); + } else { + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, conn.op_pre); + CHECK_EQ(ctx.issues[1].op, conn.op_pre); + } + } +} + +TEST(glm_routing_keeps_f32_logits_and_correction_replicated_under_tp4) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 128; + g.world = 4; + g.rank = rank; + GlmRouter::Config cfg; + GlmRouter::Wire w; + w.input = decl_b(&b, "hidden", RAD_BF16, { 128, 4096 }); + w.logits = decl_b(&b, "logits", RAD_F32, { 32, 288 }); + w.ids = decl_b(&b, "ids", RAD_I32, { 32, 8 }); + w.weights = decl_b(&b, "weights", RAD_F32, { 32, 8 }); + GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", + "model.layers.3.mlp.gate.e_score_correction_bias" }; + GlmRouter router; + REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)2); + for (const auto& weight : b.weights) { + CHECK_EQ(weight.d.dtype, RAD_F32); + CHECK_EQ(weight.d.shard, RAD_SHARD_NONE); + } + CHECK_EQ(b.weights[0].d.shape[0], 288); + CHECK_EQ(b.weights[0].d.shape[1], 4096); + CHECK_EQ(b.ops[router.op_project - 1].op, std::string("gemm_nt_f32")); + CHECK_EQ(b.ops[router.op_select - 1].op, std::string("router_sigmoid_topk")); + RadCtx ctx; + router.step(&ctx, 7, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); + CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); + CHECK_EQ(ctx.issues[0].opd[0].rows, 4); + CHECK_EQ(ctx.issues[1].opd[1].handle, router.correction); + CHECK_EQ(ctx.issues[1].opd[2].handle, w.ids); + CHECK_EQ(ctx.issues[1].opd[3].handle, w.weights); + } +} + +TEST(glm_router_and_index_head_split_columns_over_ranks_from_the_row_threshold) { + using namespace rad::arch; + for (int world : { 1, 2, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 512; + g.world = world; + g.rank = rank; + GlmRouter::Config cfg; + cfg.rows = 512; + GlmRouter::Wire w; + w.input = decl_b(&b, "hidden", RAD_BF16, { 512, 4096 }); + w.logits = decl_b(&b, "logits", RAD_F32, { 512, 288 }); + w.ids = decl_b(&b, "ids", RAD_I32, { 512, 8 }); + w.weights = decl_b(&b, "weights", RAD_F32, { 512, 8 }); + GlmRouter::Src src{ "model.layers.3.mlp.gate.weight", + "model.layers.3.mlp.gate.e_score_correction_bias" }; + GlmRouter router; + REQUIRE_EQ(router.declare(&b, nm, g, 3, "blk.3.router", cfg, w, src), RAD_OK); + const bool split = world > 1; + const int64_t cols = 288 / world; + CHECK_EQ(count_op(b, "all_gather"), split ? 1 : 0); + CHECK_EQ(count_op(b, "gemm_nt_f32"), split ? 2 : 1); + // The weight stays whole and replicated: decode keeps the unsplit projection. + CHECK_EQ(b.weights[0].d.shape[0], 288); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_NONE); + if (split) { + const RecOp* part = find_op(b, "gemm_nt_f32", 1); + const RecOp* gather = find_op(b, "all_gather"); + REQUIRE(part && gather); + CHECK_EQ(pint(part, "N"), cols); + CHECK_EQ(pint(part, "K"), 4096); + CHECK(part->w == std::vector({ router.projection })); + CHECK(part->reads == std::vector({ w.input })); + CHECK(part->writes == std::vector({ router.split.part })); + CHECK_EQ(pint(gather, "world_size"), world); + CHECK_EQ(pint(gather, "row"), cols); + CHECK_EQ(param(gather, "numel")->kind, RAD_P_RANGE); + CHECK_EQ(param(gather, "numel")->ival, cols); + CHECK_EQ(param(gather, "numel")->ihi, 512 * cols); + CHECK_EQ(pstr(gather, "dtype"), "f32"); + CHECK(gather->reads == std::vector({ router.split.part })); + CHECK(gather->writes == std::vector({ w.logits })); + } + RadCtx ctx; + router.step(&ctx, 7, 300, 7); + if (split) { + REQUIRE_EQ(ctx.issues.size(), (size_t)3); + CHECK_EQ(ctx.issues[0].op, router.split.op_part); + CHECK_EQ(ctx.issues[0].n, 300); + CHECK_EQ(ctx.issues[0].opd[0].handle, w.input); + CHECK_EQ(ctx.issues[0].opd[0].offset, 7 * 4096); + CHECK_EQ(ctx.issues[0].opd[0].rows, 300); + CHECK_EQ(ctx.issues[0].opd[1].kind, RAD_OPK_WEIGHT); + CHECK_EQ(ctx.issues[0].opd[1].handle, router.projection); + CHECK_EQ(ctx.issues[0].opd[1].offset, rank * cols * 4096); + CHECK_EQ(ctx.issues[0].opd[1].rows, cols); + CHECK_EQ(ctx.issues[0].opd[2].handle, router.split.part); + CHECK_EQ(ctx.issues[0].opd[2].rows, 300); + CHECK_EQ(ctx.issues[1].op, router.split.op_gather); + CHECK_EQ(ctx.issues[1].n, 300 * cols); + CHECK_EQ(ctx.issues[1].opd[0].handle, router.split.part); + CHECK_EQ(ctx.issues[1].opd[1].handle, w.logits); + CHECK_EQ(ctx.issues[1].opd[1].offset, 7 * 288); + CHECK_EQ(ctx.issues[1].opd[1].rows, 300); + CHECK_EQ(ctx.issues[2].op, router.op_select); + } else { + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, router.op_project); + } + ctx.issues.clear(); + router.step(&ctx, 0, 255); + REQUIRE_EQ(ctx.issues.size(), (size_t)2); + CHECK_EQ(ctx.issues[0].op, router.op_project); + } +} + +TEST(absorbed_mla_shards_complete_heads_and_reads_one_latent_cache) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const rad_kvgroup kv = rad_decl_kv_group(&b, "latent", &kd); + MlaLatent::Config cfg; + MlaLatent::Wire w; + w.q = decl_b(&b, "q", RAD_BF16, { 32, 16, 256 }); + w.q_latent = decl_b(&b, "ql", RAD_BF16, { 32, 16, 512 }); + w.attn_latent = decl_b(&b, "al", RAD_BF16, { 32, 16, 512 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 256 }); + w.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); + w.length = decl_b(&b, "length", RAD_I32, { 32 }); + MlaLatent block; + REQUIRE_EQ( + block.declare(&b, nm, g, 3, kv, cfg, w, "model.layers.3.self_attn.kv_b_proj.weight"), + RAD_OK); + REQUIRE_EQ(b.weights.size(), (size_t)1); + CHECK_EQ(b.weights[0].d.dtype, RAD_BF16); + CHECK_EQ(b.weights[0].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[0].d.shape[0], 8192); + CHECK_EQ(b.weights[0].d.shape[1], 512); + RadCtx ctx; + block.step(&ctx, 4); + REQUIRE_EQ(ctx.issues.size(), (size_t)3); + CHECK_EQ(b.ops[ctx.issues[0].op - 1].op, std::string("mla_project")); + CHECK_EQ(b.ops[ctx.issues[1].op - 1].op, std::string("mla_attn")); + CHECK_EQ(b.ops[ctx.issues[2].op - 1].op, std::string("mla_project")); + CHECK_EQ(ctx.issues[1].opd[1].kind, RAD_OPK_KV); + CHECK_EQ(ctx.issues[1].opd[2].handle, w.selected); + CHECK_EQ(ctx.issues[1].opd[3].handle, w.length); + CHECK_EQ(ctx.issues[2].opd[1].handle, block.projection); + } +} + +TEST( + glm53_native_graph_declares_all_layers_preserves_mixed_formats_and_runs_mtp_only_in_draft_passes) { + using namespace rad::arch; + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + for (int world : { 1, 4, 8 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + RadBuildCtx build{}; + build.rank = rank; + build.world_size = world; + build.max_tok = rank == 0 ? 512 : 16; + build.max_seqs = 4; + build.max_ctx = 4096; + build.max_spec = 3; + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + const auto& m = *glm5next::models[rank]; + CHECK(m.have_mtp); + CHECK_EQ(b.drafter.kind, RAD_DRAFT_SERIAL); + CHECK_EQ(b.drafter.depth, 3); + CHECK_EQ(m.layers.size(), (size_t)45); + int full = 0; + for (int l = 0; l < 45; ++l) { + const auto& layer = m.layers[l]; + full += layer.full; + CHECK(layer.attn_hc.op_pre < layer.norm.op); + CHECK(layer.attn_hc.op_post < layer.ffn_hc.op_pre); + if (layer.full) { + CHECK(layer.index.cache.op_select < layer.mla.core.op_attn); + CHECK(layer.mla.output.op < layer.attn_hc.op_post); + } else + CHECK(layer.kda.output.op < layer.attn_hc.op_post); + if (l >= 3) { + CHECK_EQ(layer.moe.c.expert_mx, 1); + CHECK(layer.moe.op_gather < layer.ffn_hc.op_post); + } + } + CHECK_EQ(full, 11); + CHECK_EQ(m.draft.moe.c.expert_f32_scale, 1); + for (const auto& map : b.maps) + if (map.declared.starts_with("mtp.")) + for (const auto& source : map.src) CHECK(!source.starts_with("mtp.model.")); + int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, + slots[] = { 0, 1 }, out[] = { 1 }; + int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; + std::vector kv(b.kv_groups.size()); + for (size_t i = 0; i < kv.size(); ++i) { + kv[i].group = (rad_kvgroup)i + 1; + kv[i].slot_mapping = slots; + kv[i].block_table = tables; + kv[i].block_table_pitch = 32; + kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; + kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; + } + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 2; + batch.n_seq = 1; + batch.token_ids = ids; + batch.positions = positions; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv.data(); + batch.n_kv_groups = (int)kv.size(); + batch.n_out = 1; + batch.out_ids = out; + RadCtx ctx; + ctx.b = &b; + ctx.rank = rank; + ctx.world = world; + ctx.batch = &batch; + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "mhc_pre"), 90); + CHECK_EQ(std::count(ops.begin(), ops.end(), "kda_update"), 34); + CHECK_EQ(std::count(ops.begin(), ops.end(), "mla_attn"), 11); + // Two rows stay under the split threshold: 42 routers and 11 index heads, replicated. + CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt_f32"), 53); + CHECK_EQ(std::count(ops.begin(), ops.end(), "all_gather"), 0); + // The split is declared on every rank whatever its step size; only rank 0 issues it here. + const bool split = world > 1; + // 43 routers and 12 index heads (MTP included), and the 90 mHC reads. + CHECK_EQ(count_op(b, "all_gather"), split ? 55 + 90 : 0); + CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0); + ctx.issues.clear(); + batch.draft_pass = -1; + batch.n_draft_out = 1; + batch.draft_out_ids = out; + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + const auto draft_ops = issued_ops(b, ctx); + CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mhc_pre"), 0); + CHECK_EQ(std::count(draft_ops.begin(), draft_ops.end(), "mla_attn"), 1); + CHECK_EQ(ctx.issues.back().op, m.mtp.op_head); + CHECK(m.mtp.op_select < m.draft.moe.op_router); + for (const auto& issue : ctx.issues) { + if (issue.op == m.draft.moe.op_router || issue.op == m.mtp.op_norm) + CHECK_EQ(issue.opd[0].rows, 1); // Only the row producing a proposal. + if (issue.op == m.mtp.op_residual) + CHECK_EQ(issue.opd[0].rows, 2); // Full history still fills attention caches. + } + ctx.issues.clear(); + batch.n_draft_out = 0; + glm5next::step(&ctx, &batch); + const auto history = issued_ops(b, ctx); + CHECK(std::find(history.begin(), history.end(), "kv_store") != history.end()); + CHECK(std::find(history.begin(), history.end(), "moe_gemm_q") == history.end()); + if (rank == 0) { + std::vector long_ids(512, 7), long_positions(512), long_slots(512), + long_tables(1024); + for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; + int32_t long_cu[] = { 0, 512 }, last = 511; + for (auto& group : kv) { + group.slot_mapping = long_slots.data(); + group.block_table = long_tables.data(); + group.block_table_pitch = 1024; + } + batch.n_tok = 512; + batch.token_ids = long_ids.data(); + batch.positions = long_positions.data(); + batch.cu_seqlens = long_cu; + batch.out_ids = &last; + batch.draft_pass = 0; + batch.max_q_len = 512; + ctx.issues.clear(); + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + { + // 512 rows reach the split: each projection runs on its column slice and each + // mHC read on its chunks, both gathered; at TP1 nothing changes. + const auto long_ops = issued_ops(b, ctx); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "gemm_nt_f32"), 53); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_gather"), + world > 1 ? 53 + 90 : 0); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre"), + world > 1 ? 0 : 90); + CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre_finish"), + world > 1 ? 90 : 0); + for (const auto& issue : ctx.issues) { + if (b.ops[issue.op - 1].op != "gemm_nt_f32") continue; + const int64_t n = pint(&b.ops[issue.op - 1], "N"); + if (world == 1) + CHECK(n == 288 || n == 32); + else { + CHECK(n == 288 / world || n == 32 / world); + CHECK_EQ(issue.opd[1].rows, n); + } + } + } + for (int l = 3; l < 45; ++l) { + // A prefill routes its full batch once, reusing each expert's + // weights across its rows instead of re-reading them in chunks. + CHECK_EQ(std::count_if(ctx.issues.begin(), ctx.issues.end(), + [&](const auto& issue) { + const auto& moe = m.layers[l].moe; + return issue.op == moe.op_router || + issue.op == moe.glm_router.split.op_part; + }), + 1); + } + // Arena-lending probes must not replace the model the serving + // graph's handles refer to, even when they declare fewer rows. + const auto* live = glm5next::models[rank].get(); + RadBuilder pb; + pb.kv_block = 4; + pb.encs = b.encs; + auto small = build; + small.shape_probe = 1; + small.max_tok = 1; + REQUIRE_EQ(glm5next::declare(&pb, &meta, &small), RAD_OK); + CHECK_EQ(glm5next::models[rank].get(), live); + CHECK_EQ(glm5next::models[rank]->g.max_tok, 512); + RadArchProbe capabilities{}; + REQUIRE_EQ(glm5next::probe(&meta, &capabilities), RAD_OK); + CHECK_EQ(capabilities.shape_probe_ok, 1); + std::array results{}; + std::vector probes; + for (int i = 0; i < 8; ++i) + probes.emplace_back([&, i] { + RadBuilder parallel; + parallel.kv_block = 4; + parallel.encs = b.encs; + auto level = build; + level.rank = i % 4; + level.max_tok = i < 4 ? 256 : 1024; + level.shape_probe = 1; + results[i] = glm5next::declare(¶llel, &meta, &level); + }); + for (auto& thread : probes) thread.join(); + for (int status : results) CHECK_EQ(status, RAD_OK); + CHECK_EQ(glm5next::models[rank].get(), live); + } + } +} + +/* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and + * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row + * counts and buffer rows smaller. The TP split declares its ops whatever the step size and its + * gathers' message as a range. */ +TEST(glm53_sizing_declares_match_the_real_graph_at_every_arena_level) { + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + const int world = 8, rank = 3; + for (int64_t R : { 256, 3072 }) { + auto encs = [&](RadBuilder& b) { + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + }; + RadBuildCtx c{}; + c.rank = rank; + c.world_size = world; + c.max_tok = 4096; + c.max_seqs = 8; + c.max_ctx = 32768; + c.max_spec = 3; + RadBuilder full; + encs(full); + REQUIRE_EQ(glm5next::declare(&full, &meta, &c), RAD_OK); + RadBuildCtx p = c; + p.max_tok = R; + p.shape_probe = 1; + RadBuilder small; + encs(small); + REQUIRE_EQ(glm5next::declare(&small, &meta, &p), RAD_OK); + REQUIRE_EQ(small.ops.size(), full.ops.size()); + int differ = 0; + for (size_t i = 0; i < full.ops.size(); ++i) { + if (small.ops[i].op != full.ops[i].op) { + ++differ; + continue; + } + REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); + for (size_t k = 0; k < full.ops[i].p.size(); ++k) { + const RecParam& a = full.ops[i].p[k]; + const RecParam& q = small.ops[i].p[k]; + if (a.kind == RAD_P_RANGE) continue; + // A capacity may shrink: its kernel writes by its operands' extents. + if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) + continue; + if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { + fprintf(stderr, + " R %lld: op %zu '%s' param '%s': " + "%lld real, %lld small\n", + (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), + a.ival, q.ival); + ++differ; + } + } + } + CHECK_EQ(differ, 0); + REQUIRE_EQ(small.bufs.size(), full.bufs.size()); + for (size_t i = 0; i < full.bufs.size(); ++i) + for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) + CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); + } +} + +/* The MoE block's decode fusions: over a two-row trunk step, its draft pass and a 512-row prefill + * (past the router fusion's one-workgroup sort), each fused launch stands where it fits and the + * launches it replaces are gone, with the step lint clean throughout. The sort writes each slot's + * row (`moe_scatter_inv`) and the gather reads it (`moe_gather_inv`) in every MoE pass. */ +TEST(glm53_moe_decode_fusions_replace_their_launches_where_they_fit) { + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + using Counts = std::map; + /* Launches per step: trunk, draft pass, prefill. The trunk has 42 MoE layers, each a routed + * and a shared clamped SwiGLU, and three dense ones. */ + struct Want { + const char* op; + int trunk, draft, prefill; + }; + const Want wants[] = { + { "router_sigmoid_topk_scatter", 42, 1, 0 }, { "router_sigmoid_topk", 0, 0, 42 }, + { "swiglu_clamped_quant_fp8", 87, 2, 87 }, { "swiglu_clamped", 0, 0, 0 }, + { "moe_scatter", 0, 0, 0 }, { "moe_gather", 0, 0, 0 }, + }; + for (int world : { 1, 8 }) { + RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + RadBuildCtx build{}; + build.rank = 0; + build.world_size = world; + build.max_tok = 512; + build.max_seqs = 4; + build.max_ctx = 4096; + build.max_spec = 3; + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + int32_t cu[] = { 0, 2 }, positions[] = { 0, 1 }, ctxlens[] = { 0 }, ids[] = { 7, 9 }, + slots[] = { 0, 1 }, out[] = { 1 }; + int32_t sidx[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }, tables[32]{}; + std::vector kv(b.kv_groups.size()); + for (size_t i = 0; i < kv.size(); ++i) { + kv[i].group = (rad_kvgroup)i + 1; + kv[i].slot_mapping = slots; + kv[i].block_table = tables; + kv[i].block_table_pitch = 32; + kv[i].state_index = b.kv_groups[i].d.kind == RAD_KV_CONV ? ci : sidx; + kv[i].state_index_pitch = b.kv_groups[i].d.kind == RAD_KV_CONV ? 1 : 6; + } + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 2; + batch.n_seq = 1; + batch.token_ids = ids; + batch.positions = positions; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv.data(); + batch.n_kv_groups = (int)kv.size(); + batch.n_out = 1; + batch.out_ids = out; + RadCtx ctx; + ctx.b = &b; + ctx.rank = 0; + ctx.world = world; + ctx.batch = &batch; + Counts got[3]; + /* With the inverse, the fused selection writes it as its ninth operand and the gather + * reads it as its third. */ + const rad_buf inv = find_b(b, "expert_inverse") + ? (rad_buf)(find_b(b, "expert_inverse") - &b.bufs[0] + 1) + : 0; + REQUIRE(inv != 0); + auto run = [&](int k) { + ctx.issues.clear(); + glm5next::step(&ctx, &batch); + CHECK(ctx.step_fail.empty()); + CHECK_LINT(b, &ctx); + for (const auto& op : issued_ops(b, ctx)) ++got[k][op]; + for (const auto& is : ctx.issues) { + const RecOp* o = b.op_of(is.op); + if (!o) continue; + if (o->op == "router_sigmoid_topk_scatter") + CHECK(is.opd.size() > 8 && is.opd[8].kind == RAD_OPK_BUF && + is.opd[8].handle == inv); + if (o->op == "moe_gather_inv") + CHECK(is.opd.size() > 2 && is.opd[2].kind == RAD_OPK_BUF && + is.opd[2].handle == inv); + } + }; + run(0); + batch.draft_pass = -1; + batch.n_draft_out = 1; + batch.draft_out_ids = out; + run(1); + std::vector long_ids(512, 7), long_positions(512), long_slots(512), + long_tables(1024); + for (int i = 0; i < 512; ++i) long_positions[i] = long_slots[i] = i; + int32_t long_cu[] = { 0, 512 }, last = 511; + for (auto& group : kv) { + group.slot_mapping = long_slots.data(); + group.block_table = long_tables.data(); + group.block_table_pitch = 1024; + } + batch.n_tok = 512; + batch.token_ids = long_ids.data(); + batch.positions = long_positions.data(); + batch.cu_seqlens = long_cu; + batch.out_ids = &last; + batch.draft_pass = 0; + batch.n_draft_out = 0; + batch.max_q_len = 512; + run(2); + for (int k = 0; k < 3; ++k) + for (const Want& w : wants) { + const int want = k == 0 ? w.trunk : k == 1 ? w.draft : w.prefill; + if (got[k][w.op] != want) + fprintf(stderr, " world %d step %d: %s %d (want %d)\n", world, k, w.op, + got[k][w.op], want); + CHECK_EQ(got[k][w.op], want); + } + } +} + +TEST(dsa_cache_uses_distinct_index_and_attention_pages_and_a_speculative_tail_ring) { + using namespace rad::arch; + for (bool front : { false, true }) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.max_seqs = 4; + g.max_spec = 3; + RadKVGroupDecl ad{}; + ad.kind = RAD_KV_FULL; + ad.dtype = RAD_BF16; + ad.n_head_kv = 1; + ad.head_dim = 256; + const auto attn = rad_decl_kv_group(&b, "attn", &ad); + // Claim the attention group's consumer before declaring the index group. + RAD_OP(&b, "mla_attn", RAD_PARAMS(RAD_INT("block_size", 4)), RAD_NOWEIGHTS); + RadKVGroupDecl td{}; + td.kind = RAD_KV_LINEAR; + td.dtype = RAD_BF16; + td.n_head_kv = 1; + td.state_dim[0] = 7; + td.state_dim[1] = 256; + const auto tail = rad_decl_kv_group(&b, "tail", &td); + DsaCache::Wire w; + w.query = decl_b(&b, "query", RAD_BF16, { 1024, 128 }); + w.codes = decl_b(&b, "codes", RAD_F8E4M3, { 1024, 128 }); + w.scales = decl_b(&b, "scales", RAD_F32, { 1024, 1 }); + w.gate = decl_b(&b, "gates", RAD_F32, { 32, 32 }); + w.kg = decl_b(&b, "kg", RAD_BF16, { 32, 256 }); + w.stage = decl_b(&b, "stage", RAD_BF16, { 48, 256 }); + w.page = decl_b(&b, "page", RAD_I32, { 12 }); + w.bpos = decl_b(&b, "bpos", RAD_I32, { 12 }); + w.nc = decl_b(&b, "nc", RAD_I32, { 4 }); + w.pooled = decl_b(&b, "pooled", RAD_F8E4M3, { 12, 128 }); + w.pool_scale = decl_b(&b, "pool_scale", RAD_F32, { 12, 1 }); + w.score = decl_b(&b, "score", RAD_F32, { 32, 1024 }); + w.selected = decl_b(&b, "sel", RAD_I32, { 32, 513 }); + w.nsel = decl_b(&b, "nsel", RAD_I32, { 32 }); + w.length = decl_b(&b, "len", RAD_I32, { 32 }); + DsaCache block; + DsaCache::Config cfg; + cfg.blocks = 1024; + cfg.work = 12; + cfg.ring = 7; + rad_kvgroup index = 0; + GlmIndexer indexer; + if (front) { + GlmIndexer::Wire iw; + iw.cache = w; + iw.input = decl_b(&b, "input", RAD_BF16, { 32, 4096 }); + iw.q_low = decl_b(&b, "q_low", RAD_BF16, { 32, 1536 }); + iw.q_wide = decl_b(&b, "q_wide", RAD_BF16, { 32, 4096 }); + iw.kg_raw = decl_b(&b, "kg_raw", RAD_BF16, { 32, 256 }); + REQUIRE_EQ(indexer.declare(&b, nm, g, 3, iw, "indexer", cfg, attn, tail, &index), + RAD_OK); + block = indexer.cache; + CHECK_EQ(b.weights[indexer.head_weight - 1].d.dtype, RAD_F32); + CHECK_EQ(b.weights[indexer.query.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[indexer.key_gate.w - 1].d.shard, RAD_SHARD_NONE); + } else + REQUIRE_EQ(block.declare(&b, nm, g, 3, cfg, w, attn, tail, &index, "indexer.pool.ape"), + RAD_OK); + CHECK_EQ(b.kv_groups[index - 1].d.dtype, RAD_U8); + CHECK_EQ(b.kv_groups[index - 1].d.head_dim, 17); + int32_t ibt[16]{}, abt[16]{}, sidx[12]{}, cu[] = { 0, 3, 8 }, pos[8]{}; + RadKVGroupBatch kv[3]{}; + kv[0].group = index; + kv[0].block_table = ibt; + kv[0].block_table_pitch = 8; + kv[1].group = tail; + kv[1].state_index = sidx; + kv[1].state_index_pitch = 6; + kv[2].group = attn; + kv[2].block_table = abt; + kv[2].block_table_pitch = 8; + RadBatch batch{}; + batch.n_tok = 8; + batch.n_seq = 2; + batch.n_spec = 2; + batch.kv = kv; + batch.n_kv_groups = 3; + batch.positions = pos; + batch.cu_seqlens = cu; + batch.max_ctx_len = 64; // Mixed-row bound exceeds the eight physical table columns. + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + if (front) { + indexer.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)12); + CHECK_EQ(ctx.issues[1].op, indexer.op_query_copy); + CHECK_EQ(ctx.issues[1].opd[1].rows, 256); + CHECK_EQ(ctx.issues[3].op, indexer.op_norm); + CHECK_EQ(ctx.issues[4].opd[0].offset, 128); + CHECK_EQ(ctx.issues[5].op, indexer.op_head); + ctx.issues.erase(ctx.issues.begin(), ctx.issues.begin() + 6); + } else + block.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)6); + CHECK_EQ(ctx.issues[0].n, 256); + CHECK(ctx.issues[1].opd[5].raw == ibt); + CHECK_EQ(ctx.issues[1].opd[4].cols, 6); + CHECK_EQ(ctx.issues[2].op, block.op_pool); + CHECK_EQ(ctx.issues[2].opd[5].handle, index); + CHECK_EQ(ctx.issues[3].op, block.op_tail); + CHECK_EQ(ctx.issues[4].opd[0].rows, 256); + CHECK_EQ(ctx.issues[4].opd[3].handle, index); + CHECK_EQ(ctx.issues[4].opd[4].kind, RAD_OPK_NONE); + CHECK(ctx.issues[4].opd[5].raw == ibt); + CHECK_EQ(ctx.issues[4].opd[8].cols, 8); + CHECK_EQ(ctx.issues[5].opd[0].cols, 8); + CHECK(ctx.issues[5].opd[1].raw == abt); + } +} + +TEST(glm_dense_ffn_keeps_clipping_and_disables_the_unclipped_fp8_epilogue) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.n_ff = 3072; + g.max_tok = 32; + g.world = 4; + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + b.encs = { { "ffn_gate_up", fp8 }, { "ffn_down", fp8 } }; + MlpFP8::Wire w; + w.x = decl_b(&b, "x", RAD_BF16, { 32, 4096 }); + w.h.x = decl_b(&b, "h", RAD_BF16, { 32, 4096 }); + REQUIRE_EQ(w.h.declare_qs(&b, nm, g, "h", 4096), RAD_OK); + w.gate_up = decl_b(&b, "gate_up", RAD_BF16, { 32, 6144 }); + w.ffn.x = decl_b(&b, "ffn", RAD_BF16, { 32, 3072 }); + REQUIRE_EQ(w.ffn.declare_qs(&b, nm, g, "ffn", 3072), RAD_OK); + MlpFP8 block; + MlpFP8::Src src{ "post_attention_layernorm.weight", "mlp.gate_proj.weight", + "mlp.up_proj.weight", "mlp.down_proj.weight" }; + REQUIRE_EQ(block.declare(&b, nm, g, 0, w, src, false, false, kArNone, false, 10), RAD_OK); + CHECK_EQ(block.op_gated, 0u); + CHECK_EQ(b.ops[block.gq_ffn.op - 1].op, std::string("swiglu_clamped")); + RadCtx ctx; + ctx.b = &b; + block.slice(&ctx, 8, 4, 4); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "swiglu_clamped"), 1); + CHECK(std::find(ops.begin(), ops.end(), "gemm_nt_q_gated") == ops.end()); + CHECK(std::find(ops.begin(), ops.end(), "quant_act_fp8") != ops.end()); +} + +TEST(glm_mla_stores_one_normalized_latent_and_exposes_q_lora_before_sparse_attention) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + b.kv_block = 4; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.rank = rank; + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = RAD_BF16; + kd.n_head_kv = 1; + kd.head_dim = 256; + const auto kv = rad_decl_kv_group(&b, "latent", &kd); + auto buf = [&](const char* name, int64_t n) { + return decl_b(&b, name, RAD_BF16, { 32, n }); + }; + GlmMla::Wire w; + w.input.x = buf("input", 4096); + w.q_raw = buf("q_raw", 1536); + w.kv_raw = buf("kv_raw", 512); + w.q_low.x = buf("q_low", 1536); + w.latent = buf("latent_out", 512); + w.out = buf("out", 4096); + REQUIRE_EQ(w.input.declare_qs(&b, nm, g, "input", 4096), RAD_OK); + REQUIRE_EQ(w.q_low.declare_qs(&b, nm, g, "q_low", 1536), RAD_OK); + w.core.q = buf("q", 4096); + w.core.q_latent = decl_b(&b, "q_latent", RAD_BF16, { 32, 16, 512 }); + w.core.attn_latent = decl_b(&b, "attn_latent", RAD_BF16, { 32, 16, 512 }); + w.core.out = buf("expanded", 4096); + w.attn.x = w.core.out; + REQUIRE_EQ(w.attn.declare_qs(&b, nm, g, "expanded", 4096), RAD_OK); + w.core.selected = decl_b(&b, "selected", RAD_I32, { 32, 513 }); + w.core.length = decl_b(&b, "length", RAD_I32, { 32 }); + GlmMla block; + REQUIRE_EQ(block.declare(&b, nm, g, 3, w, "attn", kv), RAD_OK); + CHECK_EQ(b.weights[block.q_a.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[block.q_b.w - 1].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); + int32_t slots[4]{}; + RadKVGroupBatch kb{}; + kb.group = kv; + kb.slot_mapping = slots; + RadBatch batch{}; + batch.n_tok = 4; + batch.kv = &kb; + batch.n_kv_groups = 1; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.prepare(&ctx, &batch); + auto find_issue = [&](rad_op op) -> const RecIssue* { + for (const auto& issue : ctx.issues) + if (issue.op == op) return &issue; + return nullptr; + }; + const auto* store = find_issue(block.op_store); + REQUIRE(store); + CHECK_EQ(store->opd[0].handle, w.latent); + CHECK_EQ(store->opd[0].cols, 256); + CHECK_EQ(store->opd[1].offset, 256); + CHECK_EQ(store->opd[1].cols, 256); + CHECK(store->opd[2].raw == slots); + const auto before = issued_ops(b, ctx); + CHECK(std::find(before.begin(), before.end(), "mla_attn") == before.end()); + block.finish(&ctx, &batch); + const auto* attn = find_issue(block.core.op_attn); + REQUIRE(attn); + CHECK_EQ(attn->opd[2].handle, w.core.selected); + CHECK_EQ(ctx.issues.back().op, block.op_ar); + } +} + +TEST(glm_kda_projects_local_heads_and_reduces_only_after_the_output_projection) { + using namespace rad::arch; + for (int rank = 0; rank < 4; ++rank) { + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.rank = rank; + g.max_spec = 3; + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; + sd.n_head_kv = 16; + sd.state_dim[0] = sd.state_dim[1] = 128; + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 1; + cd.head_dim = 6144; + cd.conv_width = 4; + const auto state = rad_decl_kv_group(&b, "state", &sd), + history = rad_decl_kv_group(&b, "conv", &cd); + auto buf = [&](const char* name, int64_t width) { + return decl_b(&b, name, RAD_BF16, { 32, width }); + }; + GlmKda::Wire w; + w.input = buf("input", 4096); + w.forget_low = buf("forget_low", 128); + w.gate_low = buf("gate_low", 128); + w.out = buf("out", 4096); + w.core.qkv = buf("qkv", 6144); + w.core.conv = buf("conv_out", 6144); + w.core.a = buf("a", 2048); + w.core.beta = buf("beta", 16); + w.core.gate = buf("gate", 2048); + w.core.out = buf("core_out", 2048); + KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", + "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; + GlmKda block; + REQUIRE_EQ(block.declare(&b, nm, g, 0, w, "attn", src, state, history), RAD_OK); + CHECK_EQ(b.weights[block.qkv.w - 1].d.n_row_parts, 3); + CHECK_EQ(b.weights[block.forget_a.w - 1].d.shard, RAD_SHARD_NONE); + CHECK_EQ(b.weights[block.forget_b.w - 1].d.shard, RAD_SHARD_ROW); + CHECK_EQ(b.weights[block.output.w - 1].d.shard, RAD_SHARD_COL); + int32_t cu[] = { 0, 4 }, ctxlens[] = { 0 }, indices[] = { 0, 0, 0, 1, 1, 1 }, ci[] = { 0 }; + RadKVGroupBatch kv[2]{}; + kv[0].group = state; + kv[0].state_index = indices; + kv[0].state_index_pitch = 6; + kv[1].group = history; + kv[1].state_index = ci; + RadBatch batch{}; + batch.phase = RAD_PHASE_PREFILL; + batch.n_tok = 4; + batch.n_seq = 1; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.kv = kv; + batch.n_kv_groups = 2; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.step(&ctx, &batch); + const auto ops = issued_ops(b, ctx); + CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt"), 7); + CHECK_EQ(std::count(ops.begin(), ops.end(), "silu"), 0); + REQUIRE_EQ(ctx.issues.size(), (size_t)11); + CHECK_EQ(ctx.issues[9].op, block.output.op); + CHECK_EQ(ctx.issues[10].op, block.op_ar); + CHECK_EQ(ctx.issues[10].opd[0].handle, w.out); + } +} + +TEST(kda_state_core_splits_mixed_batches_and_preserves_absolute_prefill_offsets) { + using namespace rad::arch; + RadBuilder b; + Names nm(""); + Geom g{}; + g.n_embd = 4096; + g.max_tok = 32; + g.world = 4; + g.max_spec = 3; + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; + sd.n_head_kv = 16; + sd.state_dim[0] = sd.state_dim[1] = 128; + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 1; + cd.head_dim = 6144; + cd.conv_width = 4; + const rad_kvgroup st = rad_decl_kv_group(&b, "state", &sd), + cv = rad_decl_kv_group(&b, "conv", &cd); + KdaState::Wire w; + w.qkv = decl_b(&b, "qkv", RAD_BF16, { 32, 6144 }); + w.conv = decl_b(&b, "filtered", RAD_BF16, { 32, 6144 }); + w.a = decl_b(&b, "a", RAD_BF16, { 32, 2048 }); + w.beta = decl_b(&b, "beta", RAD_BF16, { 32, 16 }); + w.gate = decl_b(&b, "gate", RAD_BF16, { 32, 2048 }); + w.out = decl_b(&b, "out", RAD_BF16, { 32, 16, 128 }); + KdaState::Src src{ "attn.q_conv1d.weight", "attn.k_conv1d.weight", "attn.v_conv1d.weight", + "attn.A_log", "attn.dt_bias", "attn.o_norm.weight" }; + KdaState block; + KdaState::Config cfg; + REQUIRE_EQ(block.declare(&b, nm, g, 0, st, cv, cfg, w, src), RAD_OK); + CHECK_EQ(b.weights[block.taps - 1].d.n_row_parts, 3); + for (int p = 0; p < 3; ++p) CHECK_EQ(b.weights[block.taps - 1].d.row_parts[p], 2048); + CHECK_EQ(b.weights[block.bias - 1].d.shape[0], 2048); + for (rad_op op : { block.op_prefill, block.op_verify }) { + bool found = false; + for (const auto& p : b.ops[op - 1].p) + if (p.key == "state_form") { + CHECK_EQ(p.sval, std::string("anchor")); + found = true; + } + CHECK(found); + } + int32_t cu[] = { 0, 3, 8 }, ctxlens[] = { 11, 0 }, accepted[] = { 2, 1 }; + int32_t indices[] = { 0, 0, 0, 2, 2, 2, 1, 1, 1, 3, 3, 3 }, conv_indices[] = { 0, 1 }; + RadKVGroupBatch kv[2]{}; + kv[0].group = st; + kv[0].state_index = indices; + kv[0].state_index_pitch = 6; + kv[1].group = cv; + kv[1].state_index = conv_indices; + kv[1].state_index_pitch = 1; + RadBatch batch{}; + batch.phase = RAD_PHASE_MIXED; + batch.n_tok = 8; + batch.n_seq = 2; + batch.n_seq_decode = 1; + batch.n_tok_decode = 3; + batch.cu_seqlens = cu; + batch.ctx_lens = ctxlens; + batch.num_accepted = accepted; + batch.kv = kv; + batch.n_kv_groups = 2; + RadCtx ctx; + ctx.b = &b; + ctx.batch = &batch; + block.step(&ctx, &batch); + REQUIRE_EQ(ctx.issues.size(), (size_t)5); + CHECK_EQ(ctx.issues[0].op, block.op_conv); + CHECK_EQ(ctx.issues[0].n, 3); + CHECK_EQ(ctx.issues[1].op, block.op_verify); + CHECK_EQ(ctx.issues[1].opd[0].cols, 2048); + CHECK_EQ(ctx.issues[1].opd[1].offset, 2048); + CHECK_EQ(ctx.issues[1].opd[2].offset, 4096); + CHECK_EQ(ctx.issues[2].op, block.op_conv); + CHECK_EQ(ctx.issues[2].n, 8); + CHECK(ctx.issues[2].opd[3].raw == cu + 1); + CHECK_EQ(ctx.issues[2].opd[7].kind, RAD_OPK_NONE); + CHECK_EQ(ctx.issues[3].op, block.op_prefill); + CHECK(ctx.issues[3].opd[8].raw == indices + 6); + CHECK(ctx.issues[3].opd[9].raw == cu + 1); + CHECK_EQ(ctx.issues[3].opd[0].offset, 0); + CHECK_EQ(ctx.issues[3].opd[0].rows, 8); + CHECK_EQ(ctx.issues[4].op, block.op_norm); +} + +/* ==================================================================== the pinned graph and steps */ + +/* GLM declares and steps the pinned graph and launches at one and eight ranks: a 4096-row prefill + * after history, a mixed step, a decode step, a verify and its draft passes. */ +TEST(glm53_is_the_pinned_graph_and_steps) { + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + struct Case { + int world; + uint64_t graph, steps; + }; + const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull }, + { 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } }; + for (const Case& cs : cases) { + RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + RadBuildCtx ctx = spec_ctx(0, cs.world, 3); + ctx.max_tok = 4096; + ctx.max_seqs = 8; + ctx.max_ctx = 200000; + REQUIRE_EQ(glm5next::declare(&b, &meta, &ctx), RAD_OK); + const uint64_t g = graph_hash(b); + const uint64_t s = pinned_steps(b, glm5next::step, 0, cs.world); + fprintf(stderr, " pin: glm5next world %d: graph 0x%016llxull, steps 0x%016llxull\n", + cs.world, (unsigned long long)g, (unsigned long long)s); + CHECK_EQ(g, cs.graph); + CHECK_EQ(s, cs.steps); + } +} + +/* ==================================================================== fixtures */ +namespace { + +/* GLM-5.3-Flash's container keys, the four the plugin reads. */ +MetaKV glm53_meta() { + RadModelMeta m{}; + m.n_layers = 45; + m.n_embd = 4096; + m.n_vocab = 154880; + m.rms_eps = 1e-5f; + MetaKV k(m); + k.set("num_nextn_predict_layers", "1").set("hc_mult", "4").set("n_routed_experts", "288") + .set("index_topk", "2048"); + return k; +} + +/* The served container's encodings: block fp8 at f32 scales for the attention and dense linears + * and the MTP layer's experts, MXFP4 for the trunk's experts. */ +void glm53_encs(RadBuilder& b) { + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; +} + +/* A deployment of 512 rows a step, four sequences, 4k of context. */ +RadBuildCtx glm53_ctx(int rank, int world, int max_spec = 3) { + RadBuildCtx c = spec_ctx(rank, world, max_spec); + c.max_tok = 512; + c.max_seqs = 4; + c.max_ctx = 4096; + return c; +} + +} /* namespace */ + +RAD_TEST_MAIN() + +/* ==================================================================== the op schemas */ +namespace { + +/* The op schemas the kernel libraries under $RADIANCE_HOME/kernels declare: libr4d's first, the + * served vocabulary, then libref's for what it lacks. Empty without a home or a library, as + * arch_test's libref vocabulary is. */ +struct OpSpec { + int n_operands = 0, w_req = 0, w_max = 0, n_tab = 0; +}; +struct LoadedSchemas { + std::map ops; + bool r4d = false; +}; +const LoadedSchemas& loaded_schemas() { + static LoadedSchemas s; + static bool tried = false; + if (tried) return s; + tried = true; + const char* home = std::getenv("RADIANCE_HOME"); + if (!home) return s; + for (const char* lib : { "libr4d.so", "libref.so" }) { + const std::string path = std::string(home) + "/kernels/" + lib; + void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) { + fprintf(stderr, " cannot load %s: %s\n", path.c_str(), dlerror()); + continue; + } + auto count = (int (*)(void))dlsym(h, "rad_kernel_schema_count"); + auto at = (const RadOpSchema* (*)(int))dlsym(h, "rad_kernel_schema_at"); + if (!count || !at) continue; + for (int i = 0; i < count(); ++i) { + const RadOpSchema* sc = at(i); + if (!sc || !sc->op || s.ops.count(sc->op)) continue; + OpSpec spec; + spec.n_operands = sc->n_operands; + for (int k = 0; sc->operands && k < sc->n_operands; ++k) { + if (sc->operands[k].role == RAD_OPD_WTAB) { + ++spec.n_tab; + } else if (sc->operands[k].role == RAD_OPD_WEIGHT) { + ++spec.w_max; + if (!sc->operands[k].optional) ++spec.w_req; + } + } + s.ops[sc->op] = spec; + } + if (!std::strcmp(lib, "libr4d.so")) s.r4d = true; + } + return s; +} + +} /* namespace */ + +/* Every op the plugin issues carries as many operands as its schema declares, counted as + * core/runtime/issue.cpp counts them (an absent optional operand is one of them), and every op it + * declares names as many weights as rad_builder.cpp admits. The steps: at eight ranks and at + * one, a mixed step over the split threshold (two decode rows beside a 498-row chunk), a step + * under it, a six-row verify and six single-row decodes, each with its history pass and a draft + * round, and a verify of eight sequences at 32k of context. The engine refuses a step at the + * first mismatch, and the fakes alone cannot see one: an issue short of an optional operand + * passes every host test and stops a served engine at its first step through that op. */ +TEST(glm53_issues_every_op_with_the_operand_count_its_schema_declares) { + const LoadedSchemas& lib = loaded_schemas(); + if (lib.ops.empty()) { + fprintf(stderr, " no kernel library under $RADIANCE_HOME/kernels; nothing to count\n"); + return; + } + MetaKV mk = glm53_meta(); + std::set uncovered, wrong; + for (int world : { 8, 1 }) { + const int rank = world == 8 ? 3 : 0; + RadBuilder b; + glm53_encs(b); + RadBuildCtx ctx = glm53_ctx(rank, world, 5); + ctx.max_tok = 4096; + ctx.max_seqs = 8; + ctx.max_ctx = 65536; + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + for (const RecOp& r : b.ops) { + auto it = lib.ops.find(r.op); + if (it == lib.ops.end()) { + uncovered.insert(r.op); + continue; + } + const OpSpec& s = it->second; + const int n_w = (int)r.w.size(); + const bool ok = s.n_tab > 0 ? n_w - s.w_max >= s.n_tab + : n_w >= s.w_req && n_w <= s.w_max; + if (!ok && wrong.insert(r.op + " (declare)").second) + fprintf(stderr, + " world %d: '%s' declares %d weights; the schema has %d (%d required) " + "and %d tables\n", + world, r.op.c_str(), n_w, s.w_max, s.w_req, s.n_tab); + } + std::vector> kits; + auto with_drafts = [&](std::unique_ptr k) { + auto his = history_pass(b, *k); + auto round = round_pass(b, k->b.n_seq, 2); + kits.push_back(std::move(k)); + kits.push_back(std::move(his)); + kits.push_back(std::move(round)); + }; + with_drafts(kit(b, { 1, 1 }, { 498 }, 100)); + with_drafts(kit(b, {}, { 255 })); + with_drafts(kit(b, { 6 }, {})); + with_drafts(kit(b, std::vector(6, 1), {})); + { + auto dec = kit(b, std::vector(8, 6), {}); + const int64_t pitch = 8192; + dec->table.resize((size_t)(8 * pitch)); + for (int64_t i = 0; i < 8 * pitch; ++i) dec->table[(size_t)i] = (int32_t)i; + for (auto& g : dec->kv) { + g.block_table = dec->table.data(); + g.block_table_pitch = g.max_blocks = pitch; + } + dec->b.max_ctx_len = 32000; + kits.push_back(std::move(dec)); + } + std::vector passes; + for (const auto& k : kits) passes.push_back(k.get()); + auto v = run_passes(b, glm5next::step, passes, rank, world); + CHECK_PASSES(b, v); + for (size_t p = 0; p < v.size(); ++p) + for (const RecIssue& issue : v[p]->issues) { + const RecOp* op = b.op_of(issue.op); + REQUIRE(op); + auto it = lib.ops.find(op->op); + if (it == lib.ops.end()) { + uncovered.insert(op->op); + continue; + } + if ((int)issue.opd.size() != it->second.n_operands && wrong.insert(op->op).second) + fprintf(stderr, + " world %d pass %zu: '%s' issued with %zu operands; the schema " + "declares %d\n", + world, p, op->op.c_str(), issue.opd.size(), it->second.n_operands); + } + } + CHECK(wrong.empty()); + for (const auto& o : uncovered) fprintf(stderr, " no schema loaded for '%s'\n", o.c_str()); + if (lib.r4d) CHECK(uncovered.empty()); +} + +/* ==================================================================== the container's names */ +namespace { + +/* The served container, GLM-5.3-Flash-Quark-MXFP4.rad, as `rad-info -v` lists it: each weight's + * name and stored encoding, for the model, one KDA layer (0, with the dense feed-forward of + * layers 0 to 2), one MLA layer (3, with its experts 0 and 287) and the MTP layer under its + * `mtp.` scope (the fp8 linears of its layer under `mtp.mtp.`, as the converter wrote them). The + * other layers of a kind carry the same names at their own index. */ +struct ContainerWeight { + const char* name; + const char* enc; +}; +const ContainerWeight kGlm53Container[] = { + { "output.weight", "bf16" }, + { "output_norm.weight", "bf16" }, + { "token_embd.weight", "bf16" }, + { "blk.0.attn_beta.weight", "bf16" }, + { "blk.0.attn_forget_a.weight", "bf16" }, + { "blk.0.attn_forget_b.weight", "bf16" }, + { "blk.0.attn_gate_a.weight", "bf16" }, + { "blk.0.attn_gate_b.weight", "bf16" }, + { "blk.0.attn_norm.weight", "bf16" }, + { "blk.0.attn_output.weight", "bf16" }, + { "blk.0.attn_qkv.weight", "bf16" }, + { "blk.0.ffn_down.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.0.ffn_gate_up.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.0.ffn_norm.weight", "bf16" }, + { "blk.0.hc_attn.base", "f32" }, + { "blk.0.hc_attn.fn", "bf16" }, + { "blk.0.hc_attn.scale", "f32" }, + { "blk.0.hc_ffn.base", "f32" }, + { "blk.0.hc_ffn.fn", "bf16" }, + { "blk.0.hc_ffn.scale", "f32" }, + { "blk.0.ssm_a", "f32" }, + { "blk.0.ssm_conv.weight", "bf16" }, + { "blk.0.ssm_dt_bias", "f32" }, + { "blk.0.ssm_norm.weight", "bf16" }, + { "blk.3.attn_kv_a.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.3.attn_kv_a_norm.weight", "bf16" }, + { "blk.3.attn_kv_b.weight", "bf16" }, + { "blk.3.attn_norm.weight", "bf16" }, + { "blk.3.attn_output.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.3.attn_q_a.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.3.attn_q_a_norm.weight", "bf16" }, + { "blk.3.attn_q_b.weight", "fp8_e4m3*f32[128x128]" }, + { "blk.3.ffn_down_shexp.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_gate_up_shexp.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_norm.weight", "bf16" }, + { "blk.3.glm_router.correction", "f32" }, + { "blk.3.glm_router.weight", "bf16" }, + { "blk.3.hc_attn.base", "f32" }, + { "blk.3.hc_attn.fn", "bf16" }, + { "blk.3.hc_attn.scale", "f32" }, + { "blk.3.hc_ffn.base", "f32" }, + { "blk.3.hc_ffn.fn", "bf16" }, + { "blk.3.hc_ffn.scale", "f32" }, + { "blk.3.index_ape", "bf16" }, + { "blk.3.index_head.weight", "bf16" }, + { "blk.3.index_key_gate.weight", "bf16" }, + { "blk.3.index_norm.bias", "bf16" }, + { "blk.3.index_norm.weight", "bf16" }, + { "blk.3.index_query.weight", "bf16" }, + { "blk.3.ffn_gate_up_exps.0.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_down_exps.0.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_gate_up_exps.287.weight", "fp4_e2m1*e8m0[1x32]" }, + { "blk.3.ffn_down_exps.287.weight", "fp4_e2m1*e8m0[1x32]" }, + { "mtp.blk.45.attn_kv_a_norm.weight", "bf16" }, + { "mtp.blk.45.attn_kv_b.weight", "bf16" }, + { "mtp.blk.45.attn_norm.weight", "bf16" }, + { "mtp.blk.45.attn_q_a_norm.weight", "bf16" }, + { "mtp.blk.45.ffn_norm.weight", "bf16" }, + { "mtp.blk.45.index_ape", "bf16" }, + { "mtp.blk.45.index_head.weight", "bf16" }, + { "mtp.blk.45.index_norm.bias", "bf16" }, + { "mtp.blk.45.index_norm.weight", "bf16" }, + { "mtp.eh_proj.weight", "bf16" }, + { "mtp.enorm.weight", "bf16" }, + { "mtp.hnorm.weight", "bf16" }, + { "mtp.mtp.blk.45.attn_kv_a.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.attn_output.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.attn_q_a.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.attn_q_b.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.ffn_down_shexp.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.ffn_gate_up_shexp.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.mtp.blk.45.glm_router.correction", "f32" }, + { "mtp.mtp.blk.45.glm_router.weight", "bf16" }, + { "mtp.mtp.blk.45.index_key_gate.weight", "bf16" }, + { "mtp.mtp.blk.45.index_query.weight", "bf16" }, + { "mtp.output_norm.weight", "bf16" }, + { "mtp.blk.45.ffn_gate_up_exps.0.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.blk.45.ffn_down_exps.0.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.blk.45.ffn_gate_up_exps.287.weight", "fp8_e4m3*f32[128x128]" }, + { "mtp.blk.45.ffn_down_exps.287.weight", "fp8_e4m3*f32[128x128]" }, +}; + +RadEncoding container_enc(const std::string& e) { + if (e == "fp8_e4m3*f32[128x128]") return rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + if (e == "fp4_e2m1*e8m0[1x32]") return rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + if (e == "f32") return rad_enc_plain(RAD_F32); + if (e != "bf16") fprintf(stderr, " unknown container encoding '%s'\n", e.c_str()); + return rad_enc_plain(RAD_BF16); +} + +/* The table above expanded to every layer: a KDA layer's names from layer 0 (its dense + * feed-forward in layers 0 to 2 only), an MLA layer's from layer 3, the MoE's from layer 3 into + * every layer from 3. `encs` answers rad_weight_encoding as + * the container would; an expert's key stands without its index, so every expert matches it, + * and the keys run longest first, because the fake matches a key anywhere in the name asked + * (`output.weight` is inside `blk.3.attn_output.weight`). */ +struct Glm53Container { + std::set names; + std::map enc; + std::vector> encs; +}; +const Glm53Container& glm53_container() { + static Glm53Container c; + static bool built = false; + if (built) return c; + built = true; + std::set keys; + auto put = [&](const std::string& name, const char* e) { + if (!c.names.insert(name).second) return; + c.enc[name] = e; + std::string key = name; + const size_t ex = key.find("_exps."); + if (ex != std::string::npos) key = key.substr(0, ex + 5); + if (keys.insert(key).second) c.encs.push_back({ key, container_enc(e) }); + }; + auto at_layer = [](const std::string& n, size_t prefix, int l) { + return "blk." + std::to_string(l) + "." + n.substr(prefix); + }; + for (const ContainerWeight& w : kGlm53Container) { + const std::string n = w.name; + if (n.rfind("blk.0.", 0) == 0) { + const bool dense = n.find(".ffn_") != std::string::npos; + for (int l = 0; l < 45; ++l) + if (l % 4 != 3 && (!dense || l < 3)) put(at_layer(n, 6, l), w.enc); + } else if (n.rfind("blk.3.", 0) == 0) { + const bool moe = n.find(".ffn_") != std::string::npos || + n.find(".glm_router.") != std::string::npos; + for (int l = 3; l < 45; ++l) + if (moe || l % 4 == 3) put(at_layer(n, 6, l), w.enc); + } else { + put(n, w.enc); + } + } + std::stable_sort(c.encs.begin(), c.encs.end(), [](const auto& a, const auto& b) { + return a.first.size() > b.first.size(); + }); + return c; +} + +/* An expert's entry stands for its siblings: any index reads as expert 0's. */ +std::string as_expert_zero(std::string n) { + const size_t ex = n.find("_exps."); + if (ex == std::string::npos) return n; + const size_t dot = n.find('.', ex + 6); + return dot == std::string::npos ? n : n.substr(0, ex + 6) + "0" + n.substr(dot); +} + +} /* namespace */ + +/* Every weight the plugin declares reads an entry the served container holds: under its own name, + * or through `source` for a view (a scale plane), and every GEMM names the dtype its weight's + * stored encoding calls for: `fp8a8f32` on the f32-scaled block FP8, `mxfp4a8` on the MXFP4 + * experts, `bf16` on the plain linears. The encodings come from the table, as the container would + * answer. A weight declared under a name the container does not hold, or a GEMM at a dtype its + * weight's encoding does not call for, passes every host test and leaves bands with no kernel at + * the eight-card start. */ +TEST(glm53_declares_the_served_containers_names_and_their_encodings) { + const Glm53Container& c = glm53_container(); + MetaKV mk = glm53_meta(); + for (int world : { 8, 1 }) { + RadBuilder b; + b.kv_block = 4; + b.encs = c.encs; + RadBuildCtx ctx = glm53_ctx(world == 8 ? 5 : 0, world); + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + std::map declared; + for (const RecWeight& w : b.weights) declared[w.name] = &w; + // The stored entry a declared weight reads: itself, or its source, followed through views. + auto stored = [&](const RecWeight& w) { + std::string n = w.name; + for (int hops = 0; hops < 4; ++hops) { + auto it = declared.find(n); + if (it == declared.end() || !it->second->d.source || n == it->second->d.source) + break; + n = it->second->d.source; + } + return n; + }; + int missing = 0, optional_absent = 0; + for (const RecWeight& w : b.weights) { + const std::string n = as_expert_zero(stored(w)); + if (c.names.count(n)) continue; + if (w.d.optional) { + ++optional_absent; + continue; + } + if (++missing <= 24) + fprintf(stderr, " world %d: '%s' reads '%s', which the container does not hold\n", + world, w.name.c_str(), n.c_str()); + } + CHECK_EQ(missing, 0); + if (optional_absent) + fprintf(stderr, " world %d: %d optional weights the container does not hold\n", world, + optional_absent); + int wrong = 0; + for (const RecOp& r : b.ops) { + if (r.w.empty() || !r.w[0]) continue; + const bool quant = r.op == "gemm_nt_q" || r.op == "gemm_nt_q_gated" || + r.op == "gemm_nt_q_bias" || r.op == "moe_gemm_q" || + r.op == "moe_gemm_q_mod4"; + const bool plain = r.op == "gemm_nt" || r.op == "gemm_nt_bias" || + r.op == "logits_gemm" || r.op == "embed_lookup"; + if (!quant && !plain) continue; + const std::string n = as_expert_zero(stored(b.weights[r.w[0] - 1])); + auto e = c.enc.find(n); + if (e == c.enc.end()) continue; + const char* want = e->second == "fp8_e4m3*f32[128x128]" ? "fp8a8f32" + : e->second == "fp4_e2m1*e8m0[1x32]" ? "mxfp4a8" + : e->second == "bf16" ? "bf16" + : nullptr; + if (!want) continue; + if (quant == (e->second == "bf16") && ++wrong <= 24) { + fprintf(stderr, " world %d: '%s' over '%s' (%s)\n", world, r.op.c_str(), n.c_str(), + e->second.c_str()); + continue; + } + if (pstr(&r, "dtype") != want && ++wrong <= 24) + fprintf(stderr, " world %d: '%s' over '%s' (%s) at dtype %s, not %s\n", world, + r.op.c_str(), n.c_str(), e->second.c_str(), pstr(&r, "dtype").c_str(), want); + } + CHECK_EQ(wrong, 0); + } +} From cdc0ae26df0e87b69bfbae3ae7bdff31be93c001 Mon Sep 17 00:00:00 2001 From: Marc Siebenhaar Date: Wed, 21 Oct 2026 08:43:39 +0200 Subject: [PATCH 116/152] libr4d: opt-in fp8 QK and PV legs for the h256/gqa6 prefill attention (R4D_ATTN_FP8) Ports the 8-bit prefill legs of radiance-vllm-mxfp4's r4d_radiance_extras.patch (commit afa21b5 there) to the h256/gqa6 prefill kernel as two separable bits, off by default: - O_QK8 (32): Q is quantised to e4m3 once at load (after the folded scale), K stays raw bytes in LDS, and Q.K^T runs as fp8 WMMA. - O_PV8 (64): P is packed to e4m3, V stays raw bytes in LDS, and P.V runs as fp8 WMMA. PGROW tightens to 8 octaves (e4m3 max 448) and DOT2 is off. Both need CONTIG and are compiled out for bf16 KV. Byte tiles halve the K/V LDS footprint. prefill_launch reads R4D_ATTN_FP8 once: 0 = f16 (unchanged), 1 = QK8, 2 = PV8, 3 = both. Measured with radiance 1.9.0 on 2x R9700 (230 W), Qwen3.8-27B MXFP4, TP 2, fp8 KV, --tp-wire wht6: - kernel, ctx 200K, chunk 6592: 161.8 ms -> 113.9 ms with 3 (x1.42); per-row relative error against fp32 1.7e-3 -> 3.1e-2 - prompt throughput at 200K: 2,621 -> 3,082-3,127 t/s; at 25K: 4,746 -> 4,861-5,011 t/s - --kld-ref against the unpatched build: R4D_ATTN_FP8=0 is bit-identical (KL 0 on 10,198 positions); 3 gives mean KL 0.0076, p99.9 0.94, max 14.3, top-1 98.4 %, PPL x1.0024 - decode and DFlash2 acceptance unchanged (the decode kernel keeps its f16 legs) --- libr4d/r4d_attn_paged_h256_gqa6.hip | 23 +++++++- libr4d/r4d_attn_prefill_h256_gqa6.hip | 85 +++++++++++++++++++++++---- 2 files changed, 95 insertions(+), 13 deletions(-) diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 8ea978a6..5198fb70 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -19,6 +19,7 @@ #include "r4d_attn_args.h" #include "r4d_common.h" #include +#include #include using std::max; #include "r4d_attn_prefill_h256_gqa6.hip" @@ -56,9 +57,25 @@ static int prefill_launch(const R4DArgs* a, hipStream_t s) { if (a->q_heads / a->kv_heads != A_GQA) return -2; constexpr int BQ = (P_NWARPS * 16) / A_GQA; dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs); - hipLaunchKernelGGL((r4d_attn_prefill_kernel), - grid, dim3(P_NWARPS * 32), 0, s, *a); + // R4D_ATTN_FP8: 0 = f16 (default), 1 = O_QK8, 2 = O_PV8, 3 = both; fp8 KV without V4/K6 only. + int fp8mode = 0; + if constexpr (KVP == 0 && XOPT == 0) { + static const int m = [] { const char* e = getenv("R4D_ATTN_FP8"); return e ? atoi(e) : 0; }(); + fp8mode = m; + } +#define P_LAUNCH(OPTX) \ + hipLaunchKernelGGL((r4d_attn_prefill_kernel), \ + grid, dim3(P_NWARPS * 32), 0, s, *a) + if constexpr (KVP == 0 && XOPT == 0) { + if (fp8mode == 3) P_LAUNCH(P_OPT | O_QK8 | O_PV8); + else if (fp8mode == 2) P_LAUNCH(P_OPT | O_PV8); + else if (fp8mode == 1) P_LAUNCH(P_OPT | O_QK8); + else P_LAUNCH(P_OPT | XOPT); + } else { + P_LAUNCH(P_OPT | XOPT); + } +#undef P_LAUNCH CHK(); return 0; } diff --git a/libr4d/r4d_attn_prefill_h256_gqa6.hip b/libr4d/r4d_attn_prefill_h256_gqa6.hip index 73c071d0..7012095c 100644 --- a/libr4d/r4d_attn_prefill_h256_gqa6.hip +++ b/libr4d/r4d_attn_prefill_h256_gqa6.hip @@ -29,6 +29,10 @@ #define O_F16 1 #define O_MSKIP 2 +// QK8/PV8 (ported from radiance-vllm-mxfp4 r4d_radiance_extras.patch): Q and P as e4m3, +// K and V stay raw bytes in LDS, both matmuls as fp8 WMMA. fp8 KV only, not with V4/K6. +#define O_QK8 32 +#define O_PV8 64 #define O_FOLDQ 8 #define O_CONTIG 512 #define O_PF2 1024 @@ -57,6 +61,13 @@ #define O_V4 33554432 #define O_K6 67108864 +typedef int v2i32_r4d __attribute__((ext_vector_type(2))); // one fp8 WMMA operand (8 e4m3) +// pack 4 floats -> 4 e4m3 bytes in element order (RNE, saturating), 2 instructions +__device__ __forceinline__ uint32_t pk_fp8x4(float a, float b, float c, float d) { + const uint32_t w = __builtin_amdgcn_cvt_pk_fp8_f32(a, b, 0u, false); + return __builtin_amdgcn_cvt_pk_fp8_f32(c, d, w, true); +} + // bf16 dword -> 16-bit dword in the target format, optionally scaled. Used once per kernel on Q. template __device__ __forceinline__ uint32_t r4d_qcvt(uint32_t w, float s) { @@ -78,7 +89,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a) constexpr int CTG = (OPT & O_CONTIG) ? 1 : 0; constexpr int PF = 1 << ((OPT >> 10) & 3); constexpr int SGB = (OPT & O_SGB) ? 1 : 0; - constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16)) ? 1 : 0; + constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16) && !(OPT & O_PV8)) ? 1 : 0; constexpr int BTS = (OPT & O_BTS) ? 1 : 0; constexpr int V4 = ((OPT & O_V4) && !KVP) ? 1 : 0; constexpr int K6 = ((OPT & O_K6) && V4) ? 1 : 0; @@ -90,6 +101,9 @@ void r4d_attn_prefill_kernel(const R4DArgs a) constexpr int GPREV = ((OPT & O_GPREV) && !V4) ? 1 : 0; constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0; constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0; + constexpr int QK8 = ((OPT & O_QK8) && !KVP && !V4) ? 1 : 0; + constexpr int PV8 = ((OPT & O_PV8) && !KVP && !V4) ? 1 : 0; + static_assert(!QK8 || KWIDE, "QK8 raw-byte staging is written for the wide K fetch"); typedef DT16 D; typedef typename D::frag frag16; @@ -108,12 +122,16 @@ void r4d_attn_prefill_kernel(const R4DArgs a) constexpr int NTR = (TILE / 8) * (HEAD_DIM / (KVP ? 32 : 64)); constexpr int VREGS = (NTR + NWARPS - 1) / NWARPS; // uint4 of raw V per thread constexpr float PSHIFT = D::SHIFT; - constexpr float PGROW = D::GROW; + constexpr float PGROW = PV8 ? 8.0f : D::GROW; // e4m3 max is 448 = 2^8.8 static_assert(!KWIDE || KPASS == 1, "the wide K fetch is one straight-line pass"); static_assert(!K6 || KWIDE, "k6_v4 K is staged sixteen dims a thread"); + static_assert((!QK8 && !PV8) || CTG, "the 8-bit fragment maps are written for CONTIG"); - __shared__ uint16_t sK[TILE * KSTR]; - __shared__ uint16_t sV16[HEAD_DIM * VSTR]; + constexpr int KSTR8 = HEAD_DIM + 8, VSTR8 = TILE + 8; + __shared__ uint16_t sK[QK8 ? (TILE * KSTR8 + 1) / 2 : TILE * KSTR]; + __shared__ uint16_t sV16[PV8 ? (HEAD_DIM * VSTR8 + 1) / 2 : HEAD_DIM * VSTR]; + uint8_t* const sK8 = (uint8_t*)sK; + uint8_t* const sV8 = (uint8_t*)sV16; const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; const int c = lane & 15, h = lane >> 4; @@ -142,6 +160,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const float mul = a.scale * kdesc * 1.44269504089f; frag16 qf[NKS]; + v2i32_r4d qf8[QK8 ? NKS : 1]; { const uint16_t* qp = (const uint16_t*)a.q + ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM; @@ -150,10 +169,19 @@ void r4d_attn_prefill_kernel(const R4DArgs a) // CONTIG reads the 8 dims as one run; the split map takes them 4+4. const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h)); const uint2 h0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h + 4 : 8 + 4 * h)); - qf[t] = D::mk(make_uint2(r4d_qcvt(l0.x, mul), - r4d_qcvt(l0.y, mul)), - make_uint2(r4d_qcvt(h0.x, mul), - r4d_qcvt(h0.y, mul))); + if constexpr (QK8) { + const float m_ = FOLDQ ? mul : 1.0f; + #define R4D_QB(w) __builtin_bit_cast(float, (w) << 16) * m_, \ + __builtin_bit_cast(float, (w) & 0xffff0000u) * m_ + qf8[t] = (v2i32_r4d){(int)pk_fp8x4(R4D_QB(l0.x), R4D_QB(l0.y)), + (int)pk_fp8x4(R4D_QB(h0.x), R4D_QB(h0.y))}; + #undef R4D_QB + } else { + qf[t] = D::mk(make_uint2(r4d_qcvt(l0.x, mul), + r4d_qcvt(l0.y, mul)), + make_uint2(r4d_qcvt(h0.x, mul), + r4d_qcvt(h0.y, mul))); + } } } @@ -308,6 +336,10 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const int key = KWIDE ? (2 * (i >> 5) + (i & 1)) : (i / (HEAD_DIM / KEL)); const int ch = KWIDE ? ((i & 31) >> 1) : (i - key * (HEAD_DIM / KEL)); if (KWIDE && key >= TILE) continue; + if constexpr (QK8) { + *(uint4*)(&sK8[key * KSTR8 + ch * KEL]) = kreg[p]; + continue; + } uint16_t* kd = &sK[key * KSTR + ch * KEL]; #pragma unroll for (int q = 0; q < KEL / 8; ++q) { @@ -346,6 +378,11 @@ void r4d_attn_prefill_kernel(const R4DArgs a) // dims; v_perm_b32 splits them into two dim rows. const uint32_t lo0 = byte_gather(v.x, v.y, 0), lo1 = byte_gather(v.z, v.w, 0); const uint32_t hi0 = byte_gather(v.x, v.y, 1), hi1 = byte_gather(v.z, v.w, 1); + if constexpr (PV8) { + *(uint2*)(&sV8[(d0 + 2 * vj) * VSTR8 + kg * 8]) = make_uint2(lo0, lo1); + *(uint2*)(&sV8[(d0 + 2 * vj + 1) * VSTR8 + kg * 8]) = make_uint2(hi0, hi1); + continue; + } uint32_t wl[4], wh[4]; fp8x8_to_16x4w(make_uint2(lo0, lo1), wl); fp8x8_to_16x4w(make_uint2(hi0, hi1), wh); @@ -399,7 +436,20 @@ void r4d_attn_prefill_kernel(const R4DArgs a) #pragma unroll 1 for (int mt = 0; mt < MT; ++mt) { v8f s = (v8f){0,0,0,0,0,0,0,0}; - { + if constexpr (QK8) { + const uint8_t* krow8 = &sK8[(mt * 16 + c) * KSTR8] + 8 * h; + #pragma unroll + for (int g = 0; g < NKS; g += PF) { + v2i32_r4d kb8[PF]; + #pragma unroll + for (int j = 0; j < PF; ++j) + kb8[j] = *(const v2i32_r4d*)(krow8 + 16 * (g + j)); + if (SGB) sched_barrier(); + #pragma unroll + for (int j = 0; j < PF; ++j) + s = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(kb8[j], qf8[g + j], s); + } + } else { const uint16_t* krow = &sK[(mt * 16 + c) * KSTR] + (CTG ? 8 * h : 0); // Load PF fragments before issuing their WMMAs, so each WMMA waits on // s_wait_dscnt PF-1 instead of a full drain. @@ -459,7 +509,22 @@ void r4d_attn_prefill_kernel(const R4DArgs a) } if (!DOT2) l_i += lsum; - { + if constexpr (PV8) { + const v2i32_r4d p8 = (v2i32_r4d){(int)pk_fp8x4(pf[0], pf[1], pf[2], pf[3]), + (int)pk_fp8x4(pf[4], pf[5], pf[6], pf[7])}; + const uint8_t* vbase8 = &sV8[c * VSTR8 + mt * 16 + 8 * h]; + #pragma unroll + for (int g = 0; g < NKS; g += PF) { + v2i32_r4d vb8[PF]; + #pragma unroll + for (int j = 0; j < PF; ++j) + vb8[j] = *(const v2i32_r4d*)(vbase8 + (size_t)(g + j) * 16 * VSTR8); + if (SGB) sched_barrier(); + #pragma unroll + for (int j = 0; j < PF; ++j) + acc[g + j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(vb8[j], p8, acc[g + j]); + } + } else { uint32_t pw[4]; #pragma unroll for (int e = 0; e < 8; e += 2) pw[e >> 1] = D::pk(pf[e], pf[e + 1]); From 51db508f91f08d6f7bf6959a76126e0304b34e71 Mon Sep 17 00:00:00 2001 From: Marc Siebenhaar Date: Wed, 21 Oct 2026 08:43:39 +0200 Subject: [PATCH 117/152] libr4d: R4D_ATTN_FP8 also for the fp8_v4 and k6_v4 caches fp8_v4's K is E4M3 already and goes to LDS as raw bytes, as on the fp8 cache. k6_v4's K and the int4 V of both layouts are widened to the value times its group scale (as for the f16 legs) and rounded once to e4m3 at staging. The launcher reads R4D_ATTN_FP8 for all three fp8-family caches. The eight new prefill instantiations spill no registers. Measured with radiance 1.10.0, fp8_v4 KV, otherwise as above (KL against the fp8-KV reference with R4D_ATTN_FP8=0): - R4D_ATTN_FP8=0 with fp8_v4 matches the shipped libr4d (mean KL 0.006713 in both) - 3: mean KL 0.0073, p99.9 0.89, max 5.2, top-1 98.3 % - prompt 200K: 2,609-2,611 -> 3,073-3,091 t/s; 5 x 200K joint prefill 2,403 -> 2,834 t/s; decode unchanged --- libr4d/r4d_attn_paged_h256_gqa6.hip | 12 ++++---- libr4d/r4d_attn_prefill_h256_gqa6.hip | 40 ++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 5198fb70..441a657d 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -57,9 +57,9 @@ static int prefill_launch(const R4DArgs* a, hipStream_t s) { if (a->q_heads / a->kv_heads != A_GQA) return -2; constexpr int BQ = (P_NWARPS * 16) / A_GQA; dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs); - // R4D_ATTN_FP8: 0 = f16 (default), 1 = O_QK8, 2 = O_PV8, 3 = both; fp8 KV without V4/K6 only. + // R4D_ATTN_FP8: 0 = f16 (default), 1 = O_QK8, 2 = O_PV8, 3 = both; fp8, fp8_v4 and k6_v4 KV. int fp8mode = 0; - if constexpr (KVP == 0 && XOPT == 0) { + if constexpr (KVP == 0) { static const int m = [] { const char* e = getenv("R4D_ATTN_FP8"); return e ? atoi(e) : 0; }(); fp8mode = m; } @@ -67,10 +67,10 @@ static int prefill_launch(const R4DArgs* a, hipStream_t s) { hipLaunchKernelGGL((r4d_attn_prefill_kernel), \ grid, dim3(P_NWARPS * 32), 0, s, *a) - if constexpr (KVP == 0 && XOPT == 0) { - if (fp8mode == 3) P_LAUNCH(P_OPT | O_QK8 | O_PV8); - else if (fp8mode == 2) P_LAUNCH(P_OPT | O_PV8); - else if (fp8mode == 1) P_LAUNCH(P_OPT | O_QK8); + if constexpr (KVP == 0) { + if (fp8mode == 3) P_LAUNCH(P_OPT | XOPT | O_QK8 | O_PV8); + else if (fp8mode == 2) P_LAUNCH(P_OPT | XOPT | O_PV8); + else if (fp8mode == 1) P_LAUNCH(P_OPT | XOPT | O_QK8); else P_LAUNCH(P_OPT | XOPT); } else { P_LAUNCH(P_OPT | XOPT); diff --git a/libr4d/r4d_attn_prefill_h256_gqa6.hip b/libr4d/r4d_attn_prefill_h256_gqa6.hip index 7012095c..10da564b 100644 --- a/libr4d/r4d_attn_prefill_h256_gqa6.hip +++ b/libr4d/r4d_attn_prefill_h256_gqa6.hip @@ -30,7 +30,9 @@ #define O_F16 1 #define O_MSKIP 2 // QK8/PV8 (ported from radiance-vllm-mxfp4 r4d_radiance_extras.patch): Q and P as e4m3, -// K and V stay raw bytes in LDS, both matmuls as fp8 WMMA. fp8 KV only, not with V4/K6. +// K and V as e4m3 bytes in LDS, both matmuls as fp8 WMMA. Not with bf16 KV. On the fp8 cache (and +// fp8_v4's K) the bytes are the cache's own; k6_v4's K and the int4 V of fp8_v4/k6_v4 are widened +// to the value times its group scale and rounded once to e4m3 at staging. #define O_QK8 32 #define O_PV8 64 #define O_FOLDQ 8 @@ -67,6 +69,18 @@ __device__ __forceinline__ uint32_t pk_fp8x4(float a, float b, float c, float d) const uint32_t w = __builtin_amdgcn_cvt_pk_fp8_f32(a, b, 0u, false); return __builtin_amdgcn_cvt_pk_fp8_f32(c, d, w, true); } +// two f16 dwords (four values in element order) -> four e4m3 bytes +__device__ __forceinline__ uint32_t pk_fp8x4_h(uint32_t lo, uint32_t hi) { + typedef _Float16 h2 __attribute__((ext_vector_type(2))); + const h2 a = __builtin_bit_cast(h2, lo), b = __builtin_bit_cast(h2, hi); + return pk_fp8x4((float)a[0], (float)a[1], (float)b[0], (float)b[1]); +} +// one f16 dword -> two e4m3 bytes in the low half +__device__ __forceinline__ uint32_t pk_fp8x2_h(uint32_t w) { + typedef _Float16 h2 __attribute__((ext_vector_type(2))); + const h2 a = __builtin_bit_cast(h2, w); + return (uint32_t)__builtin_amdgcn_cvt_pk_fp8_f32((float)a[0], (float)a[1], 0u, false) & 0xffffu; +} // bf16 dword -> 16-bit dword in the target format, optionally scaled. Used once per kernel on Q. template @@ -101,8 +115,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a) constexpr int GPREV = ((OPT & O_GPREV) && !V4) ? 1 : 0; constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0; constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0; - constexpr int QK8 = ((OPT & O_QK8) && !KVP && !V4) ? 1 : 0; - constexpr int PV8 = ((OPT & O_PV8) && !KVP && !V4) ? 1 : 0; + constexpr int QK8 = ((OPT & O_QK8) && !KVP) ? 1 : 0; + constexpr int PV8 = ((OPT & O_PV8) && !KVP) ? 1 : 0; static_assert(!QK8 || KWIDE, "QK8 raw-byte staging is written for the wide K fetch"); typedef DT16 D; typedef typename D::frag frag16; @@ -258,6 +272,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const h2 s2 = __builtin_bit_cast(h2, v4s[r]); const h2 bias = { (_Float16)1032.0f, (_Float16)1032.0f }; uint16_t* dst = &sV16[(o * 8) * VSTR + 2 * kp]; + uint8_t* dst8 = &sV8[(o * 8) * VSTR8 + 2 * kp]; #pragma unroll for (int b = 0; b < 4; ++b) { // Byte b of the first key's word low, of the second key's word in the high half: @@ -268,6 +283,12 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const uint32_t hi = __builtin_amdgcn_perm(m1, m0, sel) | 0x64006400u; // dim 2b+1 const h2 vl = (__builtin_bit_cast(h2, lo) - bias) * s2; const h2 vh = (__builtin_bit_cast(h2, hi) - bias) * s2; + if constexpr (PV8) { + // [dim][key] bytes: the pair's two keys as one 16-bit store a dim + *(uint16_t*)(dst8 + (2 * b) * VSTR8) = (uint16_t)pk_fp8x2_h(__builtin_bit_cast(uint32_t, vl)); + *(uint16_t*)(dst8 + (2 * b + 1) * VSTR8) = (uint16_t)pk_fp8x2_h(__builtin_bit_cast(uint32_t, vh)); + continue; + } *(uint32_t*)(dst + (2 * b) * VSTR) = __builtin_bit_cast(uint32_t, vl); *(uint32_t*)(dst + (2 * b + 1) * VSTR) = __builtin_bit_cast(uint32_t, vh); } @@ -336,7 +357,18 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const int key = KWIDE ? (2 * (i >> 5) + (i & 1)) : (i / (HEAD_DIM / KEL)); const int ch = KWIDE ? ((i & 31) >> 1) : (i - key * (HEAD_DIM / KEL)); if (KWIDE && key >= TILE) continue; - if constexpr (QK8) { + if constexpr (QK8 && K6) { + // k6_v4: widen to f16 as below, then round each value once to e4m3 + const uint4 r = kreg[p]; + #pragma unroll + for (int q = 0; q < 2; ++q) { + uint32_t w4[4]; + k6x8_to_f16x4w(q ? r.y : r.x, r.z, q, r.w | (r.w << 16), w4); + *(uint2*)(&sK8[key * KSTR8 + ch * KEL + 8 * q]) = + make_uint2(pk_fp8x4_h(w4[0], w4[1]), pk_fp8x4_h(w4[2], w4[3])); + } + continue; + } else if constexpr (QK8) { *(uint4*)(&sK8[key * KSTR8 + ch * KEL]) = kreg[p]; continue; } From 239da14d173a03757f27b32bfc8a5dd8d282e5bb Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 14:54:47 -0500 Subject: [PATCH 118/152] libr4d, arch/gemma4_bf16: the four-rank all-reduce by message size, and the 31B's junction fold to 16 rows The four-rank exact all-reduce picks its transport and block count by message size, for every tp-4 model; the four-rank fused junction gains its tail form (the two-shot with the junction after it), which the 31B takes up to 16 rows. Carries rmsnorm_quant_i8's register form until that PR merges. Squashed from: - libr4d: the four-rank all-reduce's fold a word at a time, 16-row standalone all-reduces on the two-shot, counters in L2 - libr4d: the standalone four-rank all-reduce takes the exact two-shot from 32768 elements - libr4d: the four-rank exact all-reduce's two-shot takes 2 blocks at a DFlash2 verify, not 4 - libr4d: the all-reduce rows' nblocks axis offers 2 and 4 - libr4d: rmsnorm_quant_i8 at decode heights loads the row's operands before its reductions - libr4d: the four-rank fused junction's tail form -- the two-shot with the junction after it - arch/gemma4_bf16: the four-rank fold up to 16 rows, on libr4d's tail form Co-Authored-By: Claude Opus 5.5 --- arch/gemma4_bf16/gemma4_bf16.cpp | 11 +- docs/OPS.md | 6 + libr4d/r4d.h | 8 +- libr4d/r4d_ar_entry.hip | 62 ++++++- libr4d/r4d_args.h | 5 + libr4d/r4d_rmsnorm_quant_i8.hip | 269 ++++++++++++++++++++++++++++--- libr4d/r4d_rows.cpp | 25 ++- libr4d/r4d_selftest.cpp | 23 ++- tests/arch_test.cpp | 16 +- 9 files changed, 375 insertions(+), 50 deletions(-) diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 7b2cabbe..34c2ba87 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -563,10 +563,15 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai * decode step (1 row) ran 5.6% slower without it (89 against 94 tok/s), and a DFlash verify * (16 rows) 9% faster (300 against 276): at 16 rows the standalone all-reduce is the exact * two-shot, while the fold's one block a row each takes a fenced handshake. The per-row costs - * cross near 4-5 rows, so the fold serves up to kAr4FoldRows rows and a taller step issues the - * pair. */ + * cross near 4-5 rows. From 5 rows libr4d's four-rank row takes its tail form instead (axis + * `tail`): the standalone two-shot with the junction run after it in the same launch, behind a + * card-local count, so the junction costs neither a handshake nor a launch. With it a DFlash2 + * verify (8 rows) folds and gains ~1% (348 / 258 / 187 / 516 against 345 / 255 / 185 / 511 tok/s, + * code / prose / story / long, 4x R9700; replies identical), where the one-shot fold there lost + * 6%. So the fold serves up to kAr4FoldRows rows, a z-lab DFlash verify's 16 included, and a + * taller step issues the pair. */ static constexpr int64_t kArOneShotElems = 524288; -static constexpr int64_t kAr4FoldRows = 4; +static constexpr int64_t kAr4FoldRows = 16; struct G4Junction { rad_op op = 0; diff --git a/docs/OPS.md b/docs/OPS.md index b8be4ef2..39bc6a0b 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2152,6 +2152,12 @@ one rounding to bf16), so it is byte-identical to `all_reduce` + `rmsnorm_quant_ sends (ranks - 1) times the message a rank, so it is for decode heights; above them a caller issues the pair, whose `all_reduce` goes two-shot. +From 5 to 32 rows (the `tail` axis, on by default) the four-rank row takes a third form: the +standalone exact two-shot over words, on the blocks the standalone `all_reduce` takes for that +message, with the junction as its tail -- one more block a row, which waits on a card-local count +of the transport blocks (no cross-card handshake), acquires, and runs `rmsnorm_quant_i8`'s row at +its own width. The bytes are the pair's; the launch the junction would take is saved. + ## Vocabulary edges | op | params | operands | diff --git a/libr4d/r4d.h b/libr4d/r4d.h index e62ee672..d414dea5 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -766,8 +766,10 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks, int drain, int acq); // ...and at four ranks, on the wide family's transport: r4d_ar_oneshot_4rank_exact's IPC -// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, and -// the engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h). +// arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, the +// engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h), and, with +// `tail_nbt` blocks (positive), the standalone two-shot on that many with the junction as its tail, +// counting on the two words at `tail_ctr` (ar_rmsnorm_quant_i8_tail_kernel). int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, long my_flags, long seq_ctrs, @@ -775,7 +777,7 @@ int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long int sc_f32, long y, long q, long s, int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int rank, long stream, int nblocks, int drain, int acq, int pub, - long gate, long gate_ctr); + long gate, long gate_ctr, long tail_ctr, int tail_nbt); // ---- sampling ---------------------------------------------------------------------------------- // diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index f735b5b9..aeb48aa0 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -399,7 +399,9 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, * changes: kernels touch other ranks only through those two, so no card addresses another's * VRAM. A message then crosses two links instead of one; only rows requiring device.p2p == 0 * take this path (r4d_rows.cpp). Sequence counters stay in VRAM, since only their own rank - * reads them. */ + * reads them, and coarse-grained: only this rank's kernels touch them, with device- and + * agent-scope atomics, which then complete in L2 rather than past it -- the first returning + * atomic of every launch (r4d_ar_seq_take) is on the push's path. */ R4D_TRY("ar_ipc_alloc", if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; if (host) { @@ -409,7 +411,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen); fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen); } - sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 1, handle, &hlen)); + sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen)); /* This rank's own packed copy, for the rotated 6-bit wire only: the reduce must fold exactly * the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the scales 1/64, so half @@ -665,6 +667,22 @@ static int nb_for(long words16, int max_nb) { return (int)nb; } +/* The four-rank exact one-shot's two-shot band (r4d_rad_ar_oneshot_4rank_exact from ts_min), over + * the words of one shard: one block per 672 words, floor 2, + * ceiling max_nb. A two-shot takes two handshakes, each a PCIe round trip a block, so small shards + * want fewer blocks than nb_for's floor of 4: at a DFlash2 verify's 8 rows of 5376 at tp 4 (1344 + * words a shard) two blocks run the exact two-shot in 20.2 us against 22.8 at four, and from 16 + * rows (2688 words, four blocks either way) the two rules agree (4x R9700, a four-card + * microbenchmark of this kernel, 2026-10-17). The block count moves no byte: every word is folded + * by one thread in ascending rank order whatever the grid. */ +static int nb_for_shard(long shard16, int max_nb) { + long nb = shard16 / 672; + if (nb < 2) nb = 2; + if (nb > max_nb) nb = max_nb; + if (nb > shard16) nb = shard16 > 0 ? shard16 : 1; + return (int)nb; +} + /* Shared front half of every all-reduce launch: find the instance, check the message against * init's sizing, resolve the tuned point. Every kernel of the family is safe in place (`y` absent * or equal to `x`); each entry point says why. */ @@ -959,6 +977,31 @@ extern "C" int r4d_rad_ar_oneshot_4rank_exact(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; if (c.in->world != 4) return RAD_E_SHAPE; const ArInst* in = c.in; + /* From `ts_min` elements, the exact two-shot on this instance: the same fold per element, so + * the same bytes, for half the bytes a rank (a 16-row verify's message, 516 KiB a card at + * 3x, is what the link waits on). It shares the wide family's flags, counters and slots, and + * a shard pair fits any slot that holds the whole message. */ + const long ts_min = r4d_cfg_ar_ts_min(a); + const long words16 = c.numel * in->esize / 16; + if (ts_min > 0 && c.numel >= ts_min && words16 % in->world == 0 && + 2 * (c.numel * in->esize) / in->world <= in->slot_bytes && + c.numel <= R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) { + R4dArCfg cfgv; + r4d_cfg_ar(a, &cfgv); + int nb = cfgv.nblocks > 0 ? cfgv.nblocks + : nb_for_shard(words16 / in->world, + in->nb_cap > 24 ? 24 : in->nb_cap); + if (nb > in->max_blocks) nb = in->max_blocks; + const long gate = link_gate(a), early = in->host ? 0L : gate; + R4D_TRY("ar_oneshot_4rank_exact (two-shot)", + r4d_ar_twoshot_4rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], + in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], + in->my_scratch, in->my_flags, in->my_seq, in->slot16, + c.inp, c.out, c.numel, in->dtype, in->rank, + (long)(uintptr_t)s, nb, c.nthreads, c.drain, c.acq, + c.pub, early, early ? in->gate_ctr : 0L)); + return early ? RAD_LINK_ENDED : RAD_OK; + } /* The wide release, the two-rank family's rule: over P2P the kernel ends the engine's hold * itself once the peers' pushes have landed (the kernel after the handshake is local VRAM * traffic); through the host mailbox the reduce reads the bytes across the link, so early @@ -1458,7 +1501,18 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) } int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : (int)v.M; if (nblocks > in->max_blocks) nblocks = in->max_blocks; - /* One handshake, the junction after it local: the release is the one-shot's. */ + /* Above one-shot heights (the plugin's fold band at 5 rows and up), the `tail` axis's form: + * the standalone two-shot over words on the blocks the standalone all_reduce would take for + * this message (nb_for_shard), with the junction as its tail; its two counters are words of the + * instance's zeroed sequence allocation past the landed counter (r4d_ar_seq.h). P2P only. */ + int tail_nbt = 0; + if (r4d_cfg_ar_tail(a) && v.M >= 5 && !in->host) { + const long words16 = (long)v.M * v.K / 8; + tail_nbt = nb_for_shard(words16 / in->world, in->nb_cap > 24 ? 24 : in->nb_cap); + if (tail_nbt > in->max_blocks) tail_nbt = in->max_blocks; + } + const long tail_ctr = in->my_seq + (2L * in->max_blocks + 8) * 4; + /* The junction after the last handshake is local, so either form releases there. */ const long gate = link_gate(a), early = in->host ? 0L : gate; const int e = r4d_ar_rmsnorm_quant_i8_4rank( in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], @@ -1468,7 +1522,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)v.M, (int)v.K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (int)in->rank, (long)(uintptr_t)s, nblocks, - cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L); + cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L, tail_ctr, tail_nbt); if (e != 0) return RAD_E_SHAPE; return early ? RAD_LINK_ENDED : RAD_OK; } diff --git a/libr4d/r4d_args.h b/libr4d/r4d_args.h index 7be88687..1d024781 100644 --- a/libr4d/r4d_args.h +++ b/libr4d/r4d_args.h @@ -357,6 +357,11 @@ void r4d_cfg_mxfp4_tiled(const RadArgs*, struct R4dMxTileCfg*); void r4d_cfg_mxfp4_decode(const RadArgs*, struct R4dMxDecCfg*); void r4d_cfg_split (const RadArgs*, struct R4dSplitCfg*); void r4d_cfg_ar (const RadArgs*, struct R4dArCfg*); +/* Whether the four-rank fused junction takes its tail form from 5 rows (the row's `tail` axis). */ +int r4d_cfg_ar_tail(const RadArgs*); +/* The four-rank exact one-shot's size, in elements, from which it takes the exact two-shot instead + * (0: never); the all-reduce rows' `ts_min` axis. */ +long r4d_cfg_ar_ts_min(const RadArgs*); void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*); void r4d_cfg_mv (const RadArgs*, struct R4dMvCfg*); /* rmsnorm_quant_i8's decode form: 1 the row's operands in registers before the reductions, 0 the diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index 1fade643..707a644d 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -124,6 +124,30 @@ __device__ __forceinline__ float scalar_of(const void* sc, uint32_t f32) { return f32 ? ((const float*)sc)[0] : bf2f(((const uint16_t*)sc)[0]); } +// The exact all-reduce's fold of one 16-byte word (eight bf16): every source's word loaded first, +// then per element fp32 from 0.0f, the sources in ascending rank, one rounding through +// bf16_hi_rne_nan -- ar_vsum's arithmetic, so the word is the standalone exact all-reduce's. +template +__device__ __forceinline__ int4 fold_word8(const int4* const* src4, size_t k) { + int4 v[WS]; +#pragma unroll + for (int r = 0; r < WS; ++r) v[r] = src4[r][k]; + float acc[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] = 0.0f; +#pragma unroll + for (int r = 0; r < WS; ++r) { + const uint16_t* pv = reinterpret_cast(&v[r]); +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] += bf2f(pv[j]); + } + int4 a; + uint16_t* pa = reinterpret_cast(&a); +#pragma unroll + for (int j = 0; j < 8; ++j) pa[j] = (uint16_t)(bf16_hi_rne_nan(acc[j]) >> 16); + return a; +} + template __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel( const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, @@ -157,19 +181,14 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel( // t takes columns t, t+THR, ...), so each thread keeps its own columns in registers and none needs // another's; only the fragment-order store crosses threads, through `ybuf` as before. The sums, // the order they are taken in and every element's arithmetic are junction_row's, so the bytes are. +// One row of it, for this kernel and for the all-reduce's tail (ar_rmsnorm_quant_i8_tail_kernel). template -__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( - const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, +__device__ __forceinline__ void junction_reg_row( + const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w, const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, - signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, - uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) { - extern __shared__ uint16_t ybuf[]; - __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; - const uint32_t row = blockIdx.x, tid = threadIdx.x; - const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; - uint16_t* __restrict__ rr = RES ? res + (size_t)row * r_ld : nullptr; - uint16_t* __restrict__ yr = yo ? yo + (size_t)row * y_ld : nullptr; - + signed char* __restrict__ qr, float* __restrict__ Sr, uint16_t* __restrict__ yr, uint32_t n, + float eps, float wadd, uint16_t* ybuf, float* l1, float* l2, float* lm) { + const uint32_t tid = threadIdx.x; uint16_t xv[EPT], rv[EPT]; float gp[EPT], gw[EPT]; #pragma unroll @@ -235,10 +254,9 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]); const float scale = fmaxf(m, 1e-8f) / 127.f; const float inv = 1.f / scale; - if (tid == 0) S[row] = scale; + if (tid == 0) *Sr = scale; // ---- the codes, in junction_row's fragment order - signed char* __restrict__ qr = q + (size_t)row * n; for (uint32_t i = tid; i < n; i += THR) { const uint32_t s = i >> 4, j = i & 15; const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); @@ -247,6 +265,21 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( } } +template +__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, + signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, + uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) { + extern __shared__ uint16_t ybuf[]; + __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; + const uint32_t row = blockIdx.x; + junction_reg_row( + x + (size_t)row * x_ld, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sc, sc_f32, + q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, ybuf, + l1, l2, lm); +} + // --------------------------------------------------------------------------------------------- // The same junction with the two-rank all-reduce that precedes it: the branch output is a rank's // partial sum of a column-sharded linear (o_proj, down_proj), and the post-norm is of the whole @@ -256,6 +289,9 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_reg_kernel( // commutes, so both ranks agree) during the post-norm's sum-of-squares pass. A block owns whole // rows, one per block at decode. #define R4D_ARQ8_SPIN_MAX 4000000000ULL +/* The all-reduce's tail form serves up to this many rows: a block a row beside the transport's, + * far under one block a CU on the cards it runs on. */ +#define R4D_ARQ8_TAIL_MAX_ROWS 32 __device__ __forceinline__ void arq8_store_rel(unsigned int* p, unsigned int v) { __hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM); @@ -385,27 +421,30 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel( /* the sources in ascending global rank, this rank's own from `x` (its own slot is never * written), the peers' from their slots in my scratch */ - const uint16_t* src[WS]; + const int4* src4[WS]; #pragma unroll for (int r = 0; r < WS; ++r) - src[r] = r == rank ? (const uint16_t*)x - : (const uint16_t*)(my_base + ((size_t)parity * WS + r) * - (size_t)slot_stride16); + src4[r] = r == rank ? (const int4*)x + : my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16; const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f; for (int row = r0; row < r1; ++row) { const size_t o = (size_t)row * n; uint16_t* __restrict__ xr = x + o; + /* The fold a 16-byte word a thread, every source's word in flight at once (the peers' are + * in fine-grained memory, a round trip each), stored back into `x`; then the post-norm's + * sum of squares over the stored row in the norm's partition. Per element it is the fold + * fold_word8 documents, and the sum reads the same rounded values in the same order, so + * the bytes are those of the fold and the sum taken in one pass. */ + for (int k = (int)tid; k < wpr; k += (int)THR) + ((int4*)xr)[k] = fold_word8(src4, (size_t)row * wpr + k); float ss = 0.0f; - for (uint32_t i = tid; i < n; i += THR) { - float acc = 0.0f; -#pragma unroll - for (int r = 0; r < WS; ++r) acc += bf2f(src[r][o + i]); - const uint16_t a = (uint16_t)(bf16_hi_rne_nan(acc) >> 16); - xr[i] = a; - if (POST) { const float v = bf2f(a); ss += v * v; } + if (POST) { + __syncthreads(); /* the folded row, read across the block's threads */ + for (uint32_t i = tid; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; } } float s1 = 0.0f; if (POST) s1 = rsqrtf(block_sum(ss, l1) / (float)n + eps); + else __syncthreads(); /* junction_row reads the folded row across threads too */ junction_row( xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sv, q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, ybuf, l2, lm); @@ -413,6 +452,139 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel( } } +// --------------------------------------------------------------------------------------------- +// --------------------------------------------------------------------------------------------- +// The junction as the tail of the standalone exact two-shot, in one launch. Blocks [0, nbt) run +// r4d_ar_twoshot_wide_exact_kernel's body over x in place (r4d_ar_twoshot_Nrank_exact.hip): the same +// shards, words, fold (fp32 from 0.0f in ascending rank, one rounding) and handshakes, so x ends as +// the standalone all-reduce leaves it; each then counts itself in on a word of the instance's +// counter allocation, at agent scope behind a release. Blocks [nbt, nbt + M) are the junction, one +// row each as rmsnorm_quant_i8_reg_kernel runs it (junction_reg_row, the same width and partition): +// each waits for every transport block's count, acquires, and runs its row; the last of them zeroes +// both counts for the next launch. So the junction takes neither a cross-card handshake nor a +// launch of its own: the pair's bytes, one dependent launch fewer. Blocks are dispatched in index +// order, so the transport blocks are resident before any junction block spins; the grid is kept far +// under one block a CU. +// +// tail[0] counts the transport blocks done, tail[1] the junction blocks done; both start at zero +// (the counter allocation is zeroed at init) and the last junction block returns them there. +template +__global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_kernel( + uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, + signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, + R4DArWidePeers peers, const int4* __restrict__ my_base, + unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, + unsigned int* __restrict__ tail, int M, uint32_t n, float eps, float wadd, uint32_t r_ld, + uint32_t y_ld, int slot_stride16, int rank, int nbt, int drain, int acq, int pub, + long long* gate, unsigned int* gate_ctr) { + constexpr uint32_t THR = 1024; + constexpr int NPEERS = WS - 1; + extern __shared__ uint16_t ybuf[]; + __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; + __shared__ unsigned int s_seq, s_slot; + const int b = (int)blockIdx.x, tid = (int)threadIdx.x, nt = (int)THR; + + if (b < nbt) { + // ---- the standalone exact two-shot, x in place, block b of nbt + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); + r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); + const unsigned int s = s_seq; + const int parity = (int)s_slot; + int4* const x4 = (int4*)x; + const int n16 = (int)(((long)M * n) >> 3); + const int base = n16 / WS, rem = n16 % WS; + const int sh_max = base + (rem ? 1 : 0); +#define R4D_TT_OFF(o) ((o) * base + ((o) < rem ? (o) : rem)) +#define R4D_TT_LEN(o) (base + ((o) < rem ? 1 : 0)) + const int wd = (sh_max + nbt - 1) / nbt; + const int w0 = b * wd; + int w1 = w0 + wd; if (w1 > sh_max) w1 = sh_max; + int4* pa[NPEERS]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) + pa[p] = peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16; + for (int p = 0; p < NPEERS; ++p) { + const int owner = peers.rank[p]; + const int4* src = x4 + (size_t)R4D_TT_OFF(owner); + int4* dst = pa[p]; + const int lim = w1 < R4D_TT_LEN(owner) ? w1 : R4D_TT_LEN(owner); + for (int k = w0 + tid; k < lim; k += nt) dst[k] = src[k]; + } + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub); + const int4* src[WS]; +#pragma unroll + for (int r = 0; r < WS; ++r) + src[r] = (r == rank) ? (x4 + (size_t)R4D_TT_OFF(rank)) + : (my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16); + int4* my_out = x4 + (size_t)R4D_TT_OFF(rank); + const int my_lim = w1 < R4D_TT_LEN(rank) ? w1 : R4D_TT_LEN(rank); + for (int k = w0 + tid; k < my_lim; k += nt) { + float acc[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] = 0.0f; +#pragma unroll + for (int r = 0; r < WS; ++r) { + const int4 v = src[r][k]; + const __hip_bfloat16* pv = reinterpret_cast(&v); +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] += r4d_ar_to_f(pv[j]); + } + int4 o; + __hip_bfloat16* po = reinterpret_cast<__hip_bfloat16*>(&o); +#pragma unroll + for (int j = 0; j < 8; ++j) r4d_ar_from_f(acc[j], po[j]); + my_out[k] = o; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) pa[p][sh_max + k] = o; + } + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nbt, (unsigned int)tid); + for (int p = 0; p < NPEERS; ++p) { + const int owner = peers.rank[p]; + const int4* srcB = my_base + ((size_t)parity * WS + owner) * (size_t)slot_stride16 + sh_max; + int4* dst = x4 + (size_t)R4D_TT_OFF(owner); + const int lim = w1 < R4D_TT_LEN(owner) ? w1 : R4D_TT_LEN(owner); + for (int k = w0 + tid; k < lim; k += nt) dst[k] = srcB[k]; + } +#undef R4D_TT_OFF +#undef R4D_TT_LEN + // ---- every word this block stored in x, published, then counted in + __syncthreads(); + if (tid == 0) { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent"); + __hip_atomic_fetch_add(&tail[0], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + } + return; + } + + // ---- the junction, row b - nbt, once x is whole on this card + const int row = b - nbt; + if (tid == 0) { + unsigned long long z = 0; + while (__hip_atomic_load(&tail[0], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < + (unsigned int)nbt) { + __builtin_amdgcn_s_sleep(1); + if (++z > R4D_AR_SPIN_MAX) __builtin_trap(); + } + } + __syncthreads(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + junction_reg_row( + x + (size_t)row * n, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sc, sc_f32, + q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, ybuf, + l1, l2, lm); + __syncthreads(); + if (tid == 0) { + const unsigned int prev = + __hip_atomic_fetch_add(&tail[1], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + if (prev + 1u == (unsigned int)M) { + __hip_atomic_store(&tail[0], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + __hip_atomic_store(&tail[1], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + } + } +} + } // namespace // ============================================================== the plugin ABI entry point @@ -559,6 +731,8 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long // and the per-source slot stride -- and the rest is the junction's. The checks are the wide // launchers' (rank range, the message inside one slot, the grid inside the flag array, every // allocation's extent), returned as codes rather than thrown, for the reason this file gives. +// The all-reduce is the one-shot. With `tail_nbt` blocks (positive) it is instead the standalone two-shot over words on that many blocks with the junction as its tail, +// a block a row (ar_rmsnorm_quant_i8_tail_kernel), counting on the two words at `tail_ctr`. extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, @@ -567,7 +741,8 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat int sc_f32, long y, long q, long s, int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int rank, long stream, int nblocks, int drain, int acq, - int pub, long gate, long gate_ctr) { + int pub, long gate, long gate_ctr, + long tail_ctr, int tail_nbt) { constexpr int WS = 4, NPEERS = WS - 1; const long ps[NPEERS] = { peer_scratch0, peer_scratch1, peer_scratch2 }; const long pf[NPEERS] = { peer_flags0, peer_flags1, peer_flags2 }; @@ -610,6 +785,50 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat const int thr = r4d_act_threads(M, n); const size_t lds = (size_t)n * sizeof(uint16_t); + + /* The junction as the standalone two-shot's tail (ar_rmsnorm_quant_i8_tail_kernel): at the + * junction's register width (1024 threads), up to R4D_ARQ8_TAIL_MAX_ROWS rows. */ + const int ept = n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0; + if (tail_nbt > 0 && tail_ctr && thr == 1024 && ept > 0 && M <= R4D_ARQ8_TAIL_MAX_ROWS && + tail_nbt <= R4D_AR_WIDE_MAX_BLOCKS) { + try { + r4d_ar_check_extent(my_flags, (long)tail_nbt * WS * (long)sizeof(unsigned int), + "ar_rmsnorm_quant_i8", "my_flags"); + r4d_ar_check_extent(tail_ctr, 2L * (long)sizeof(unsigned int), "ar_rmsnorm_quant_i8", + "tail counters"); + for (int i = 0; i < NPEERS; ++i) + r4d_ar_check_extent(pf[i], (long)tail_nbt * WS * (long)sizeof(unsigned int), + "ar_rmsnorm_quant_i8", "peer flags"); + } catch (...) { + return -8; + } +#define R4D_ARQ8T_K(WF, RS, PO, SC, E) \ + hipLaunchKernelGGL((ar_rmsnorm_quant_i8_tail_kernel), \ + dim3((uint32_t)(tail_nbt + M)), dim3(1024), lds, (hipStream_t)stream, \ + (uint16_t*)x, (uint16_t*)res, (const void*)w, (const void*)wp, \ + (const void*)sc, (uint32_t)sc_f32, (signed char*)q, (float*)s, \ + (uint16_t*)y, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ + (unsigned int*)seq_ctrs, (unsigned int*)tail_ctr, M, (uint32_t)n, eps, \ + wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, rank, \ + tail_nbt, drain, acq, pub, (long long*)gate, (unsigned int*)gate_ctr) +#define R4D_ARQ8T_E(WF, RS, PO, SC) \ + do { if (ept == 4) R4D_ARQ8T_K(WF, RS, PO, SC, 4); \ + else if (ept == 6) R4D_ARQ8T_K(WF, RS, PO, SC, 6); \ + else R4D_ARQ8T_K(WF, RS, PO, SC, 8); } while (0) +#define R4D_ARQ8T_W(WF) \ + do { if (!res) R4D_ARQ8T_E(WF, false, false, false); \ + else if (!wp && !sc) R4D_ARQ8T_E(WF, true, false, false); \ + else if (wp && !sc) R4D_ARQ8T_E(WF, true, true, false); \ + else if (wp && sc) R4D_ARQ8T_E(WF, true, true, true); \ + else R4D_ARQ8T_E(WF, true, false, true); } while (0) + if (w_f32) R4D_ARQ8T_W(true); + else R4D_ARQ8T_W(false); +#undef R4D_ARQ8T_W +#undef R4D_ARQ8T_E +#undef R4D_ARQ8T_K + return hipGetLastError() == hipSuccess ? 0 : -4; + } + #define R4D_ARQ8W_T(WF, RS, PO, SC, T) \ hipLaunchKernelGGL((ar_rmsnorm_quant_i8_wide_kernel), dim3((uint32_t)nb), \ dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \ diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 67d2d63b..d64d8665 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4717,15 +4717,25 @@ static const RadTunable tAttnSplit[] = { * On the fp8 fused row only drain and acq apply: it forces `nthreads` to the norm's width for * bit-exactness, and pinning `nblocks` would undo r4d_ar_entry.hip's cap. No axis changes the * result. */ -static const int64_t kArNblocks[] = { 0, 8, 16, 24 }; +static const int64_t kArNblocks[] = { 0, 2, 4, 8, 16, 24 }; static const int64_t kArNthreads[] = { 256, 512, 1024 }; static const int64_t kArDrain[] = { 1, 3 }; static const int64_t kArAcq[] = { 0, 1 }; +/* `ts_min`: from this many elements the four-rank exact one-shot hands the message to the exact + * two-shot on the same instance (the same per-element fold, so the same bytes): a rank then sends + * 1.5x the message instead of 3x, for a second handshake. 32768 is about six rows of 5376, so an + * 8-row DFlash2 verify's all-reduces take the two-shot too (on 4x R9700, 2026-10-17: 297 -> 303 + * tok/s code, long decode 447 -> 460, against 65536 that kept them one-shot); a 16-row verify's + * already did. 0 keeps the one-shot to its band's top. Read only by that + * adapter; declared by every all-reduce table so one RADIANCE_TUNE=all_reduce:ts_min=N pin is legal + * for every row the op resolves to. */ +static const int64_t kArTsMin[] = { 0, 16384, 32768, 65536, 131072, 262144 }; static const RadTunable tAr[] = { { "nblocks", kArNblocks, NELEM(kArNblocks), 0, "blocks in the grid. 0 = scale with the message and clamp" }, { "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "threads per block; the fused fp8 row overrides this for bit-exactness" }, { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, + { "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "elements from which the four-rank one-shot takes the exact two-shot; 0 = never" }, }; /* The four-rank fused junction (ar_rmsnorm_quant_i8_4rank): tAr's axes, its own value sets. * On 4x R9700 over PCIe P2P a junction costs about 22 us at one row of 5376 and 57 us at sixteen @@ -4739,6 +4749,7 @@ static const RadTunable tAr[] = { * call takes: fewer blocks (2 or 4, each owning several rows) take fewer. The defaults are the * forms that have run on cards; the others are for RADIANCE_TUNE until they have. None of them * changes the result. */ +static const int64_t kArQ84Tail[] = { 1, 0 }; static const int64_t kArQ84Nblocks[] = { 0, 2, 4, 8, 16, 24 }; static const int64_t kArQ84Acq[] = { 0, 1 }; static const int64_t kArQ84Pub[] = { 1 }; @@ -4748,6 +4759,7 @@ static const RadTunable tArQ84[] = { { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, { "acq", kArQ84Acq, NELEM(kArQ84Acq), 0, "acquire after the flag read: 0 system invalidate a wave, 1 full fence" }, { "pub", kArQ84Pub, NELEM(kArQ84Pub), 1, "release before the flag store: 1 one system writeback" }, + { "tail", kArQ84Tail, NELEM(kArQ84Tail), 1, "from 5 to 32 rows: the standalone two-shot with the junction as its tail, a block a row (no handshake or launch of its own); 0 = the one-shot" }, }; /* The four-rank two-shots beside compute: four blocks of 1024. A pipelined Flash-Next prefill at * TP4 (qwen4exp_fp8) runs each all-reduce of a 2048-row piece beside the other piece's MoE passes, @@ -4759,6 +4771,7 @@ static const RadTunable tArTs4Lane[] = { { "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "threads per block" }, { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, + { "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "unused here (tAr says why it is declared)" }, }; /* The same axes with narrow defaults, for a collective issued beside compute (`overlap` 1). The * wide launch (up to 24 blocks of 1024 threads spinning on peer flags) suits an all-reduce that has @@ -4770,6 +4783,7 @@ static const RadTunable tArLane[] = { { "nthreads", kArNthreads, NELEM(kArNthreads), 256, "threads per block" }, { "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" }, { "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" }, + { "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "unused here (tAr says why it is declared)" }, }; /* --------------------------------------------------------------------------------- row top-k @@ -7686,7 +7700,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "the four-rank exact one-shot all-reduce and the junction after it -- post-norm of the reduced " "sum, residual add, scalar, RMS norm and quant_act_i8's quantiser -- in one kernel", "exactly 4 ranks; n a multiple of 16, x unpitched (it is the message); a block owns whole rows; " - "exact wire; one-shot, so (ranks - 1) x the message a rank -- for decode heights", + "exact wire; one-shot ((ranks - 1) x the message a rank) -- for decode heights; from 5 to 32 " + "rows (axis `tail`) the standalone two-shot with the junction as its tail", "bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale; the reduced sum " "rounded to bf16 as the standalone exact all-reduce stores it", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, @@ -9013,6 +9028,12 @@ extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) { /* An axis of the four-rank junction only (tArQ84); 1 for every other row, as before. */ out->pub = TUNE(a, tArQ84, "pub"); } +extern "C" int r4d_cfg_ar_tail(const RadArgs* a) { + return TUNE(a, tArQ84, "tail"); +} +extern "C" long r4d_cfg_ar_ts_min(const RadArgs* a) { + return (long)tune_i(a, tAr, NELEM(tAr), "ts_min"); +} extern "C" void r4d_cfg_topk(const RadArgs* a, R4dTopkCfg* out) { out->rc = 0; /* derived from pt1 at issue; see the note at tTopk */ out->nch = TUNE(a, tTopk, "nch"); diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 227b8914..7b3ac961 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -21553,8 +21553,11 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons runs = { /* bf16: 524288 the one-shot band's top, 524352 the first message the two-shot's rows * take (numel % 64 == 0 either way, so both divide); the shipped chunk sizes; and - * 4194304 again to close the run on a size already folded. */ - { "bf16", { 4194304, 128, 524288, 524352, 4196352, 20971520, 46137344, 4194304 }, 2 }, + * 4194304 again to close the run on a size already folded. 86016, a 16-row verify at + * 5376, and 524288 are past the one-shot row's default ts_min, so that row hands them + * to the two-shot; 128 and 43008 (eight rows) stay on the one-shot. */ + { "bf16", { 4194304, 128, 43008, 86016, 524288, 524352, 4196352, 20971520, 46137344, + 4194304 }, 2 }, /* fp32: words = numel / 4, whole groups of four either side of the same edge. */ { "fp32", { 1048580 - 4, 524352 }, 0 }, }; @@ -22638,6 +22641,7 @@ struct ArQ8 { bool res = false, scal = false; bool gated = false; /* hand the launch an odd `link_gate` word */ long long gate_after = -1; /* ...and what the launch left in it */ + int tail = -1; /* the `tail` axis pinned, or -1: the default */ void* inst = nullptr; int rc_init = RAD_E_STATE, rc_launch = RAD_OK; const std::vector* r_in = nullptr; /* the replicated residual, w and w_post */ @@ -22657,6 +22661,8 @@ static void ar_q8_worker(ArQ8* t) { PS("dtype", "bf16"), PF("wadd", 0.0) }; t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, 4, &t->inst); if (t->rc_init != RAD_OK) return; + /* The tuned point arrives as a parameter of the launch, as the core appends it. */ + if (t->tail >= 0) ps.push_back(PI("tail", t->tail)); /* Allocated here and not through dalloc, whose list four rank threads would race on. */ void* x = nullptr; void* r = nullptr; void* w = nullptr; void* wp = nullptr; void* sc = nullptr; @@ -22724,8 +22730,13 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector 0, scal = form == 2; const std::string at = " M=" + std::to_string(M) + " n=" + std::to_string(K) + (form == 0 ? ", plain" : form == 1 ? ", junction" - : ", junction with scalar"); + : ", junction with scalar") + + (sh.tail ? ", two-shot with the junction as its tail" : ", one-shot"); /* The chain on the first card: rmsnorm_quant_i8 over the reduced sum. */ st_set_device(devs[0]); @@ -22805,6 +22817,7 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector folded = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" }; @@ -4641,7 +4641,7 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ }; RadBuilder b; CHECK_OK(declare4(b)); - CHECK(noted(b, "folded in at steps of 4 rows or fewer")); + CHECK(noted(b, "folded in at steps of 16 rows or fewer")); auto fold_hi = [](const RadBuilder& bb, int* n) { int64_t hi = -1; *n = 0; @@ -4655,17 +4655,17 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ return hi; }; int n_ar = 0; - CHECK_EQ(fold_hi(b, &n_ar), 4); + CHECK_EQ(fold_hi(b, &n_ar), 16); CHECK_EQ(n_ar, 2 * L - 1); - /* a verify's height and a step past the one-shot's band both issue the pair */ + /* a verify's height folds (libr4d's tail form) and a step past 16 rows issues the pair */ const int32_t out[1] = { 127 }; for (int rows : { 16, 128 }) { RadBatch tall = one_prompt(rows, out); RadCtx c; c.b = &b; c.rank = 0; c.world = 4; c.batch = &tall; gemma4_bf16::step(&c, &tall); CHECK(c.step_fail.empty()); - CHECK_EQ(join(issued_ops(b, c)), join(apart)); + CHECK_EQ(join(issued_ops(b, c)), join(rows <= 16 ? folded : apart)); } From bdb37d5d1692b34f7da305f276ab0903edb4e4fc Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 14:54:47 -0500 Subject: [PATCH 119/152] arch: Gemma 4 31B with z-lab's DFlash drafter Gemma 4's DFlash drafter moves into arch/common so both Gemma 4 plugins declare it, on the int8 grid too; the 31B declares it beside its w4a8 / w8a8 trunk when the container carries one; the w4a8 and Q8 -df recipes and compose files; the tests. Squashed from: - arch: Gemma 4's DFlash drafter into arch/common, for both Gemma 4 plugins, and on the int8 grid - arch: z-lab's DFlash drafter beside the 31B's w4a8 / w8a8 trunk, its gqa-8 attention at gqa 4 - data/recipes: gemma4-31b with DFlash, the w4a8 trunk with a block-fp8 drafter, and Q8 - tests: the 31B with its DFlash drafter declares the chains where libr4d's fused ops are not declared - tests: the 31B's steps with its DFlash drafter lint clean, on both grids, at one, two and four ranks Co-Authored-By: Claude Opus 5.5 --- README.md | 10 + arch/common/rad_fp8.h | 6 +- arch/common/rad_gemma4_dflash.h | 1162 +++++++++++++++++ arch/gemma4/gemma4.cpp | 203 +-- arch/gemma4/gemma4_dflash.h | 682 ---------- arch/gemma4_bf16/gemma4_bf16.cpp | 128 +- .../gemma4-31b-dense-bf16-q8-df.recipe | 56 + .../gemma4-31b-dense-bf16-w4a8-df.recipe | 56 + deploy/compose/gemma4-31b-q8-df.yaml | 16 + deploy/compose/gemma4-31b-w4a8-df.yaml | 17 + docs/ARCHITECTURES.md | 50 +- tests/arch_test.cpp | 475 +++++++ 12 files changed, 1960 insertions(+), 901 deletions(-) create mode 100644 arch/common/rad_gemma4_dflash.h delete mode 100644 arch/gemma4/gemma4_dflash.h create mode 100644 data/recipes/gemma4-31b-dense-bf16-q8-df.recipe create mode 100644 data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe create mode 100644 deploy/compose/gemma4-31b-q8-df.yaml create mode 100644 deploy/compose/gemma4-31b-w4a8-df.yaml diff --git a/README.md b/README.md index 5447de41..9689564e 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | | Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` | +| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (20 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-w4a8-df.yaml` | +| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` | @@ -256,6 +258,14 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-w4a8.ra --recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \ --set quantization_config.quant_method=compressed-tensors \ --draft-model /srv/models/hf/google/gemma-4-31B-it-assistant +build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-w4a8-df.rad \ + --recipe data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe \ + --set quantization_config.quant_method=compressed-tensors \ + --draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash +build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q8-df.rad \ + --recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \ + --set quantization_config.quant_method=compressed-tensors \ + --draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash build/bin/rad-convert /srv/models/hf/z-lab/Qwen3.8-27B-PARO -o qwen3.8-27b-paro-int4.rad \ --recipe data/recipes/q38-27b-paro-mxfp4-df2.recipe \ --draft-model /srv/models/hf/z-lab/Qwen3.8-27B-DFlash2 diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 8a262e4d..c756bdf3 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -1515,10 +1515,12 @@ struct DenseFP8 { /* The caller made the name map (a row range of a checkpoint tensor); declare() does not. */ bool mapped = false; + /* `mapped`: the caller made the name map already, to ask the encoding before choosing this + * struct over another grid's -- a COPY map declared twice is refused (rad_builder.cpp). */ int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, int access, int shard, RadWeightGroup grp, std::initializer_list src, - std::initializer_list row_parts = {}); + std::initializer_list row_parts = {}, bool mapped = false); /* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */ rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K, std::initializer_list reads, std::initializer_list writes) const { @@ -1541,7 +1543,7 @@ struct DenseFP8 { inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, int access, int shard, RadWeightGroup grp, std::initializer_list src, - std::initializer_list row_parts) { + std::initializer_list row_parts, bool mapped) { if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; /* ---- OCP-MXFP4, from the weight's encoding. The exponent grid is one row tall, so parts need diff --git a/arch/common/rad_gemma4_dflash.h b/arch/common/rad_gemma4_dflash.h new file mode 100644 index 00000000..0340e1a2 --- /dev/null +++ b/arch/common/rad_gemma4_dflash.h @@ -0,0 +1,1162 @@ +/* rad_gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4, + * and what both Gemma 4 plugins need to carry it: arch/gemma4 (the 26B-A4B and the dense sizes, + * from bf16) and arch/gemma4_bf16 (the dense 31B at w4a8 or w8a8). + * + * ============================== WHAT IT IS ============================== + * + * rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around + * attention and the feed-forward, and the candidate selector). The original DFlash is a small + * Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one + * forward and takes every position's argmax from the target's lm_head. + * + * context pass, one row a committed token: + * c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids))) + * for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v) + * + * query pass, `block` rows a sequence: + * x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below + * for each layer: + * h = input_layernorm(x) + * q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store + * x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window, + * the full layer non-causal over everything + * x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x) + * x = norm(x) + * over the mask rows: logits = lm_head(x) [the target's]; draft = argmax + * + * z-lab publishes one for gemma-4-26B-A4B-it (2816 wide, 32 heads, taps 1 6 11 17 22 27 of 30) and + * one for gemma-4-31B-it (5376 wide, 64 heads / 8 kv x 128, ffn 10752, taps 1 12 23 35 46 57 of + * 60), both five layers, four sliding and one full, at block 16. Nothing below is per size. + * + * ============================== THE THREE GEMMA-SPECIFIC FACTS ============================== + * + * From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is + * verified against the trunk. + * + * The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as + * bf16 (53.0 at 2816, 73.5 at 5376), and the drafter was trained through the target's embedding + * module, which applies it. `embed_lookup`'s `mult` carries it; embed_scale() below is the value. + * + * The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names + * four sliding layers and one full one, and the PR's test pins `causal True` on the sliding + * layers and `False` on the full one, so this block declares two attention ops and issues the one + * each layer's type names. + * + * The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and + * cap * tanh(x / cap) is strictly increasing. + * + * ============================== THE HEAD ============================== + * + * The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma + * ties it to the embedding, so it is the weight the trunk's `embed_lookup` reads and costs no extra + * bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's slice and the ranks' + * candidates merge exactly (`row_topk` at R = 2 -> `all_gather` -> `pair_argmax`; R = 2 because the + * gather moves 16-byte rows, see kTopR). + * + * The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a + * 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds an 8-bit copy of the table + * under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical weights, as in + * rad_block_dflash2.h), made by one of the recipe lines + * + * dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 (block fp8) + * dflash.draft_head.weight rtn codes=i8 group=128 scale=f16 clamp=sym (int8, w8a8) + * + * the head is `gemm_nt_q` over that copy, half the bytes, with the argmax over its coarser logits. + * Drafts are still verified, so the copy can change proposals but never accepted text. Without the + * copy, or in another encoding, the bf16 table is read. The copy costs half the table's bytes again + * (176 MiB per rank at tp 4 on the 26B, 352 MiB on the 31B). There is no rerank against the bf16 + * table: DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not. + * + * ============================== THE LINEARS ARE 8-BIT ============================== + * + * As in DFlash2, since the drafter is read whole on every decode step: the container must be + * converted with a recipe that makes the seven linears (fc, and six a layer) 8-bit, on one of two + * activation grids, which the container's choice for `fc` decides: + * + * E4M3 block fp8 (`codes=fp8_e4m3 block=128x128 scale=bf16`) or OCP-MXFP4, read at fp8a8 / + * mxfp4a8 against an E4M3 activation with an f32 scale per (row, 128): quant_act_fp8, or + * rmsnorm_quant_fp8 where the input is a norm. + * int8 int8 codes with an f16 scale per (row, 128 columns) (`codes=i8 group=128 scale=f16 + * clamp=sym`), the Q8 grid gemma4_bf16's trunk takes at w8a8, read by gemm_nt_q at w8a8 + * against quant_act_i8's activation: int8 in the GEMM's fragment order and one f32 scale + * per row, or rmsnorm_quant_i8 where the input is a norm. + * + * The two cannot mix within the drafter: one quantised activation feeds several linears (q, k and v + * read one pair), so every linear must read the grid its producer writes. declare() refuses a bf16 + * linear, and a linear on the other grid, by name rather than letting the loader fail on a view. + */ +#ifndef RAD_GEMMA4_DFLASH_H +#define RAD_GEMMA4_DFLASH_H + +#include "rad_arch.h" +#include "rad_fp8.h" + +#include +#include +#include +#include +#include +#include + +namespace gemma4 { + +using namespace rad::arch; + +/* ============================================================== what both plugins share */ + +/* The embedding scale as the reference applies it: Gemma4TextScaledWordEmbedding multiplies the + * looked-up rows by `embed_scale.to(weight.dtype)`, sqrt(hidden) rounded to bf16 (53.0 at 2816, not + * 53.066; 73.5 at 5376, not 73.32). The trunk, the assistant head and the drafter all read the + * embedding through that module, so all three take this value. */ +inline double embed_scale(int64_t hidden) { + return rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)hidden))); +} + +/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no + * transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */ +inline bool block_fp8_128(const RadEncoding& e) { + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] && + e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 && + sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK; +} + +/* Int8 on the w8a8 grid: i8 codes and an f16 scale per [1 x 128], no transform (a recipe's `rtn + * codes=i8 group=128 scale=f16 clamp=sym`), what gemm_nt_q reads at w8a8. Not rad_fp8.h's + * linear_is_w8, which is the i8a8 grid's bf16 scale over a per-(row, 128) activation. */ +inline bool linear_w8a8(const RadEncoding& e) { + if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false; + const RadEncPlane* sc = rad_enc_plane(&e, "scale"); + return e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && sc && sc->dtype == RAD_F16 && + sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK; +} + +/* Which drafter the container carries under `draft.`: 1 for DFlash (v1), 2 for DFlash2 (which is + * rad_block_dflash2.h's, not this block), 0 for none or a draft that is not a DFlash. */ +inline int dflash_kind(const RadModelMeta* meta) { + const char* da = rad_meta_gets(meta, "draft.architectures", ""); + if (!da || !std::strstr(da, "DFlash")) return 0; + return std::strstr(da, "DFlash2") ? 2 : 1; +} + +/* The block a DFlash checkpoint was trained at, 0 where it states none. v1 states it at the top + * level; a SpecForge config nests it under dflash_config. */ +inline long long dflash_block(const RadModelMeta* meta) { + long long bs = rad_meta_geti(meta, "draft.block_size", 0); + if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); + return bs > 0 ? bs : 0; +} + +/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less + * the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the + * container carries one and `out` now names its depth. */ +inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) { + if (dflash_kind(meta) != 1) return false; + const long long bs = dflash_block(meta); + if (bs <= 1) return false; + out->draft_depth = (int)(bs - 1); + out->draft_depth_fixed = 1; + return true; +} + +/* ============================================================== the block */ + +struct Dflash1 { + enum { MAX_LAYERS = 8, MAX_TAPS = 8 }; + + struct Config { + int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */ + int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */ + int64_t window = 0; /* the sliding layers' window; 0 for none */ + int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */ + double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */ + int64_t kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */ + int64_t steps() const { return block - 1; } + }; + + /* The attention's queries per kv head. libr4d serves the drafter's head-128 attention, causal + * over a window and non-causal alike, on one kernel that takes 4 queries per kv head and + * q_len * gqa <= 64, so a block of 16 at 4. The 26B's drafter is gqa 4. The 31B's is 64 heads + * over 8 kv heads, gqa 8 at every rank count, which no kernel serves at a block of 16: its + * cache holds each kv head twice, and attention sees 4 queries per copy. That is exact (query + * head q still reads kv head q / 8), and costs a copy of k and v per layer and a cache twice the + * size, a few MiB at the drafter's width. */ + static constexpr int64_t kAttnGqa = 4; + static int64_t kv_rep_for(const Geom& g) { + const int64_t gqa = g.gqa(); + return gqa > kAttnGqa && gqa % kAttnGqa == 0 ? gqa / kAttnGqa : 1; + } + + /* What the trunk hands the drafter (declare_drafter). */ + struct Trunk { + int64_t n_taps = 0; + double escale = 1.0; /* embed_scale(hidden) */ + rad_buf src = 0; /* [max_tok, n_taps * n_embd] bf16: the taps, in tap order */ + rad_weight w_tok = 0; /* the trunk's tied table, row-sharded with the vocabulary */ + const char* tok_src = nullptr; /* its checkpoint name, which the head's 8-bit copy maps */ + int base_layer = 0; /* the drafter's first absolute layer, past the trunk's */ + }; + + struct Wire { + /* the context pass */ + rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | codes | f32 */ + rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */ + rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */ + rad_buf ck4 = 0, cv4 = 0; /* [max_tok, kv_dim * kv_rep]: the cache's copies */ + /* the query pass */ + rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */ + rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */ + rad_buf k4 = 0, v4 = 0; /* [qrows, kv_dim * kv_rep] */ + rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */ + rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */ + rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */ + /* the head, one row per draft position */ + rad_buf sel_h = 0; /* [srows, n_embd] */ + rad_buf selq = 0, sels = 0; /* [srows, n_embd] codes | f32, the 8-bit head's */ + rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */ + rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */ + rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */ + rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */ + }; + + /* One of the drafter's linears, in the grid the container holds it (see the file header): block + * fp8 or MXFP4 through DenseFP8, or int8 at w8a8 -- codes and an f16 scale per [1 x 128] as two + * views of one stored weight, the w4a8 grid's layout at twice the radix. `w` and `s` are the + * GEMM's two weight operands either way, and `bref()` its trailing one. */ + struct Lin { + rad_weight w = 0, s = 0; + bool i8 = false; + DenseFP8 f{}; + + int declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, int access, + int shard, RadWeightGroup grp, std::initializer_list src, + std::initializer_list row_parts = {}); + rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K, + std::initializer_list reads, + std::initializer_list writes) const { + if (!i8) return f.gemm(b, hi, N, K, reads, writes); + return rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w8a8")), + RAD_WEIGHTS(w, s)), + reads, writes); + } + RadOperand bref() const { return i8 ? RAD_NONE : f.bref(); } + }; + + Geom g{}; /* the drafter's geometry */ + Config cfg{}; + Wire w{}; + int first_layer = 0; + int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0; + rad_kvgroup kv = 0; + bool sharded = false; + /* The activation grid: false is E4M3 with a scale per (row, 128), true int8 with a scale per + * row. Read off `fc`'s encoding; every other linear has to agree (see the file header). */ + bool i8 = false; + + Lin w_fc{}; + rad_weight w_hnorm = 0, w_norm = 0; + rad_weight w_tok = 0; /* the target's table: embedding and head */ + Lin w_dh{}; /* its 8-bit copy, the head where it is stored */ + bool q_head = false; /* the head reads w_dh */ + rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; + Lin w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{}; + rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}; + Lin w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{}; + + rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0; + /* the kv heads' copies into the cache's layout (kv_rep > 1): k and v, context and query pass */ + rad_op op_rep_ck = 0, op_rep_cv = 0, op_rep_k = 0, op_rep_v = 0; + rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; + + rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0; + rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}; + /* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` (on the int8 + * grid `rmsnorm_quant_i8`) is served: op_anq[i] for the attention input (layer 0's without the + * add) and op_fnq[i] for the feed-forward input. Zero where not served; the `add` / `rmsnorm` / + * quantiser chain is issued instead. */ + rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {}; + rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; + rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; + rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; + rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0; + rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; + rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0; + + /* Candidates each rank contributes under a sharded head. The draft needs one, but the gather + * moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is + * refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax` + * reduces the world * 2 of them to the global top-1. */ + static constexpr int64_t kTopR = 2; + + static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); } + + /* The taps the container's drafter reads, when it carries a DFlash (v1) drafter and the serve + * speculates: the trunk layers into `out` and their count (0 when there is nothing to tap), or a + * refusal -- a DFlash2 drafter, which this block is not, or one naming no layer of an + * `n_layer`-layer trunk, which belongs to another target. */ + static int taps(const RadModelMeta* meta, const RadBuildCtx* ctx, int64_t n_layer, int* out, + int max); + + /* The whole drafter, declared after the trunk (declaration order is the buffer planner's + * liveness): its config read off `draft.`, its KV group bound from `t.base_layer`, the block, + * and the RadDrafterDecl the engine drives it by. `trunk` is the trunk's geometry, which the + * drafter's copies for what they share: the ranks, the vocabulary shard, the step bounds. */ + static int declare_drafter(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Names& nm, const Geom& trunk, const Trunk& t, Dflash1* df, + rad_kvgroup* kv_out); + + int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, + rad_kvgroup group, rad_weight tok_embd, const char* ck, rad_buf src, + const char* tok_src); + void context(RadCtx* c, const RadBatch* batch) const; + void step(RadCtx* c, const RadBatch* batch) const; + +private: + int64_t q_dim() const { return g.n_head * g.head_dim; } + int64_t kv_dim() const { return g.n_head_kv * g.head_dim; } + + /* The pair a quantiser writes for an n-wide activation of `rows`: the codes, and the f32 scale + * plane -- one per (row, 128) on the E4M3 grid, one per row on the int8 one. */ + void decl_pair(RadBuilder* b, Names& nm, const char* q, const char* s, int64_t rows, int64_t n, + rad_buf* qb, rad_buf* sb) const { + *qb = decl_b(b, nm.f("%s", q), i8 ? RAD_I8 : RAD_F8E4M3, {rows, n}); + *sb = decl_b(b, nm.f("%s", s), RAD_F32, {rows, i8 ? 1 : fp8_blocks(n)}); + } + /* The standalone quantiser of an n-wide activation, in the grid: `quant_act_fp8` with a scale + * per 128 columns, or `quant_act_i8` with one per row, whose `group` only sizes the optional + * code sums this symmetric grid does not take (gemma4_bf16.cpp's G4Linear). */ + rad_op decl_quant(RadBuilder* b, int64_t rows, int64_t n, rad_buf x, rad_buf q, + rad_buf s) const { + return rw(b, RAD_OP(b, i8 ? "quant_act_i8" : "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {x}, {q, s}); + } + /* ...and its issue. quant_act_i8 has a third output, the row sums an asymmetric grid reads, + * absent on this symmetric one and passed as a null operand, since operands are positional. */ + void quant(RadCtx* c, rad_op op, int64_t T, rad_buf x, rad_buf q, rad_buf s) const { + if (i8) RAD_ISSUE_N(c, op, T, brows(x, T), brows(q, T), brows(s, T), RAD_NONE); + else RAD_ISSUE_N(c, op, T, brows(x, T), brows(q, T), brows(s, T)); + } + /* A fused norm and quantiser's issue: x (the delta where it adds), the residual or none, the + * gain, the pair, no bf16 copy, and on the int8 grid rmsnorm_quant_i8's two junction gains + * (post-norm and scalar), which a drafter layer has neither of. */ + void norm_quant(RadCtx* c, rad_op op, int64_t T, RadOperand x, RadOperand res, + rad_weight gain) const { + if (i8) + RAD_ISSUE_N(c, op, T, x, res, RAD_W(gain), brows(w.hq, T), brows(w.hs, T), RAD_NONE, + RAD_NONE, RAD_NONE); + else + RAD_ISSUE_N(c, op, T, x, res, RAD_W(gain), brows(w.hq, T), brows(w.hs, T), RAD_NONE); + } + /* The kv heads into the cache's layout: head h to copies h * kv_rep .. h * kv_rep + kv_rep - 1, + * so the copies of one head sit side by side and query head q of a gqa-4 attention, which reads + * cache head q / 4, reads head q / (4 * kv_rep), the projection's own. One head-wide strided row + * copy (`cast`, bf16 to bf16) a copy. */ + void rep_kv(RadCtx* c, rad_op op, int64_t T, rad_buf src, rad_buf dst) const { + const int64_t hd = g.head_dim, r = cfg.kv_rep; + for (int64_t h = 0; h < g.n_head_kv; ++h) + for (int64_t i = 0; i < r; ++i) + RAD_ISSUE(c, op, bcol(src, h * hd, hd, T), bcol(dst, (h * r + i) * hd, hd, T)); + } + /* A linear's GEMM over its input's pair. */ + void gemm(RadCtx* c, rad_op op, int64_t T, rad_buf q, rad_buf s, const Lin& l, + rad_buf y) const { + RAD_ISSUE_N(c, op, T, brows(q, T), brows(s, T), RAD_W(l.w), RAD_W(l.s), brows(y, T), + RAD_NONE, l.bref()); + } + /* The linears must be quantised by the recipe, in the grid `fc` set. A bf16 one would be read + * through a view of a dtype it is not stored in, and the loader's error would name the view, + * not the missing recipe; one on the other grid would read a pair its producer does not write. */ + int need_quantised(RadBuilder* b, const char* wn, const Lin& l) const { + RadEncoding e{}; + if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */ + const uint32_t dt = e.plane[0].dtype; + if (dt != RAD_F8E4M3 && dt != RAD_FP4E2M1 && dt != RAD_I8) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its linears " + "are served 8-bit: convert with a recipe that names them, e.g. " + "`dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 " + "scale=bf16` (or `codes=i8 group=128 scale=f16 clamp=sym`) and the " + "same for fc, attn_k/v/output, ffn_gate_up and ffn_down.\n", + wn, rad_dtype_name(dt)); + return RAD_E_DTYPE; + } + if (l.i8 != i8) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is %s and its fc is %s; " + "one quantised activation feeds several linears, so the drafter's " + "linears take one grid and the recipe's rules for them must agree\n", + wn, l.i8 ? "int8 (w8a8)" : "on the E4M3 grid (fp8 or MXFP4)", + i8 ? "int8 (w8a8)" : "on the E4M3 grid (fp8 or MXFP4)"); + return RAD_E_DTYPE; + } + return RAD_OK; + } +}; + +/* ------------------------------------------------------------------------------ one linear */ + +inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int64_t N, int64_t K, + int access, int shard, RadWeightGroup grp, + std::initializer_list src, + std::initializer_list row_parts) { + /* The name map once, before the question it answers: a COPY map declared twice is refused and + * a CONCAT one extended (rad_builder.cpp), so DenseFP8 is told the map is made. */ + const char* wn = nm.f("%s.weight", base); + RAD_ARCH_TRY(map_linear(b, wn, src)); + RadEncoding enc{}; + i8 = weight_enc(b, wn, &enc) && linear_w8a8(enc); + if (!i8) { + RAD_ARCH_TRY(f.declare(b, nm, base, N, K, access, shard, grp, src, row_parts, true)); + w = f.w; + s = f.s; + return RAD_OK; + } + /* w8a8: rows in 16s (the fragment's tile) and K in whole 128-column scale groups. The scale + * plane has the weight's rows, so it takes the weight's row parts as they are. */ + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an int8 weight takes rows in 16s " + "and K in whole %d-column scale groups.\n", + base, (long long)N, (long long)K, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + int64_t p[RAD_MAX_ROW_PARTS] = {0}; + int np = 0; + for (int64_t q : row_parts) { + if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL; + p[np++] = q; + } + w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, p, np); + s = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_F16, { N, K / RAD_FP8_BLOCK }, + access, shard, grp, p, np); + return w && s ? RAD_OK : RAD_E_INVAL; +} + +/* ------------------------------------------------------------------------------ the taps */ + +inline int Dflash1::taps(const RadModelMeta* meta, const RadBuildCtx* ctx, int64_t n_layer, + int* out, int max) { + if (ctx->max_spec <= 0) return 0; + const int kind = dflash_kind(meta); + if (kind == 0) return 0; + if (kind == 2) { + fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin " + "serves the DFlash (v1) block z-lab publishes for Gemma 4\n"); + return RAD_E_UNSUPPORTED; + } + const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr); + if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr); + const int n = parse_layer_ids(ids, n_layer, out, max); + if (n <= 0) { + fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model has; it is " + "paired with a different target\n"); + return RAD_E_UNSUPPORTED; + } + return n; +} + +/* ------------------------------------------------------------------------------ the drafter */ + +inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, + const RadBuildCtx* ctx, Names& nm, const Geom& trunk, + const Trunk& t, Dflash1* df, rad_kvgroup* kv_out) { + Geom dg{}; + RAD_ARCH_TRY(drafter_geom(dg, trunk, meta, "gemma4 DFlash")); + if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) { + fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads " + "the target's embedding and head, so it is not this target's drafter\n", + (long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd); + return RAD_E_UNSUPPORTED; + } + + Config dc{}; + dc.n_taps = t.n_taps; + dc.escale = t.escale; + const long long trained = dflash_block(meta); + if (trained < 2) { + fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n"); + return RAD_E_FORMAT; + } + if ((long long)ctx->max_spec + 1 != trained) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter was trained at block_size %lld, " + "which is %lld draft tokens, and this serve asks for %d. A block-diffusion " + "drafter denoises a fixed number of mask positions; run it at " + "--num-speculative-tokens %lld (or `auto`).\n", + trained, trained - 1, ctx->max_spec, trained - 1); + return RAD_E_UNSUPPORTED; + } + dc.block = trained; + if (dg.n_layer > MAX_LAYERS) return RAD_E_UNSUPPORTED; + { + std::vector full; + const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr); + if (lt) { + RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention", + &full)); + if ((int64_t)full.size() != dg.n_layer) { + fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and " + "it has %lld\n", full.size(), (long long)dg.n_layer); + return RAD_E_INVAL; + } + } else { + full.assign((size_t)dg.n_layer, 1); + } + bool any_swa = false; + for (int64_t l = 0; l < dg.n_layer; ++l) { + dc.full[l] = full[(size_t)l]; + any_swa = any_swa || !full[(size_t)l]; + } + if (any_swa) { + dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size", + rad_meta_geti(meta, "draft.sliding_window", 0)); + if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) { + fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no " + "window\n"); + return RAD_E_INVAL; + } + } + } + if (!head_sharded(dg) && dg.world > 1) { + fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole " + "16-row blocks over %d ranks, which the drafter's sharded head needs\n", + (long long)dg.n_vocab_all, dg.world); + return RAD_E_UNSUPPORTED; + } + + /* One unbounded cache for all the drafter's layers, because its full layer reads every + * position. The sliding layers bound themselves with their attention op's `window`, so the + * declared drafter window is 0 and the core stages the whole context. A separate window group + * for the sliding layers would save memory. */ + /* The cache holds kv_rep copies of each of this rank's kv heads (kv_rep_for). */ + dc.kv_rep = kv_rep_for(dg); + { + Geom cg = dg; + cg.n_head_kv *= dc.kv_rep; + cg.n_head_kv_all *= dc.kv_rep; + RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, cg, 0, t.base_layer, kv_out)); + dg.kv_dtype = cg.kv_dtype; + } + + RAD_ARCH_TRY(df->declare(b, nm, dg, dc, t.base_layer, *kv_out, t.w_tok, "draft", t.src, + t.tok_src)); + + RadDrafterDecl drf{}; + drf.name = "dflash"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */ + drf.proposal = df->w.tokens; + drf.proposal_pitch = dc.steps(); + drf.window = 0; /* the full layer reads everything; see the group */ + drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", + rad_meta_geti(meta, "draft.mask_token_id", -1)); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + + int nfull = 0; + for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l]; + rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld " + "sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the " + "trunk at %lld tap(s); linears %s. One forward over %lld rows proposes %lld " + "tokens; the head is %s, argmax %s", + (long long)dg.n_layer, t.base_layer, t.base_layer + (int)dg.n_layer - 1, nfull, + (long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head, + (long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, + (long long)t.n_taps, + df->i8 ? "int8 (w8a8, an int8 activation per row)" : "on the E4M3 grid (fp8a8 / mxfp4a8)", + (long long)dc.block, (long long)dc.steps(), + !df->q_head ? "the target's tied bf16 table" + : df->w_dh.i8 ? "the container's int8 copy of the target's table (dflash.draft_head)" + : "the container's block-fp8 copy of the target's table (dflash.draft_head)", + head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary"); + if (dc.kv_rep > 1) + rad_note(b, "the DFlash drafter's cache holds each of its %lld kv head(s) a rank %lld times, " + "so its attention runs at %lld queries per kv head, the width libr4d's head-%lld " + "kernel serves at a block of %lld (gqa %lld otherwise)", + (long long)dg.n_head_kv, (long long)dc.kv_rep, (long long)kAttnGqa, + (long long)dg.head_dim, (long long)dc.block, (long long)dg.gqa()); + return RAD_OK; +} + +/* ------------------------------------------------------------------------------ declare */ + +inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, + int base_layer, rad_kvgroup group, rad_weight tok_embd, + const char* ck, rad_buf src, const char* tok_src) { + g = geom; cfg = c; first_layer = base_layer; kv = group; w_tok = tok_embd; + w = Wire{}; + w.src = src; + if (!ck || !w_tok || !tok_src || !src) return RAD_E_INVAL; + if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) { + fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most " + "%d\n", (long long)g.n_layer, MAX_LAYERS); + return RAD_E_UNSUPPORTED; + } + if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL; + if (cfg.kv_rep < 1 || g.gqa() % cfg.kv_rep) return RAD_E_INVAL; + + const int64_t qd = q_dim(), kvd = kv_dim(), rep = cfg.kv_rep; + crows = g.max_tok; + qrows = g.max_seqs * cfg.block; + if (qrows > g.max_tok) qrows = g.max_tok; + srows = g.max_seqs * cfg.steps(); + if (qrows <= 0 || srows <= 0) return RAD_E_INVAL; + sharded = head_sharded(g); + const int64_t tw = cfg.n_taps * g.n_embd; + + /* ---------------------------------------------------------------- model-scope weights + * `fc` first: its encoding is the drafter's activation grid, which the buffers below take. */ + RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, tw, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model(), { nm.ckpt("%s.fc.weight", ck) })); + i8 = w_fc.i8; + RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight"), w_fc)); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck))); + w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + + /* ---------------------------------------------------------------- the buffers */ + decl_pair(b, nm, "df_srcq", "df_srcs", g.max_tok, tw, &w.srcq, &w.srcs); + w.c = decl_b(b, nm.f("df_c"), g.act_dtype, {g.max_tok, g.n_embd}); + decl_pair(b, nm, "df_cq", "df_cs", g.max_tok, g.n_embd, &w.cq, &w.cs); + w.ck = decl_b(b, nm.f("df_ck"), g.act_dtype, {g.max_tok, kvd}); + w.cv = decl_b(b, nm.f("df_cv"), g.act_dtype, {g.max_tok, kvd}); + if (rep > 1) { + w.ck4 = decl_b(b, nm.f("df_ck4"), g.act_dtype, {g.max_tok, kvd * rep}); + w.cv4 = decl_b(b, nm.f("df_cv4"), g.act_dtype, {g.max_tok, kvd * rep}); + } + w.x = decl_b(b, nm.f("df_x"), g.act_dtype, {qrows, g.n_embd}); + w.h = decl_b(b, nm.f("df_h"), g.act_dtype, {qrows, g.n_embd}); + decl_pair(b, nm, "df_hq", "df_hs", qrows, g.n_embd, &w.hq, &w.hs); + w.q = decl_b(b, nm.f("df_q"), g.act_dtype, {qrows, qd}); + w.k = decl_b(b, nm.f("df_k"), g.act_dtype, {qrows, kvd}); + w.v = decl_b(b, nm.f("df_v"), g.act_dtype, {qrows, kvd}); + if (rep > 1) { + w.k4 = decl_b(b, nm.f("df_k4"), g.act_dtype, {qrows, kvd * rep}); + w.v4 = decl_b(b, nm.f("df_v4"), g.act_dtype, {qrows, kvd * rep}); + } + w.attn = decl_b(b, nm.f("df_attn"), g.act_dtype, {qrows, qd}); + decl_pair(b, nm, "df_atq", "df_ats", qrows, qd, &w.atq, &w.ats); + w.gate_up = decl_b(b, nm.f("df_gate_up"), g.act_dtype, {qrows, 2 * g.n_ff}); + w.ffn = decl_b(b, nm.f("df_ffn"), g.act_dtype, {qrows, g.n_ff}); + decl_pair(b, nm, "df_ffq", "df_ffs", qrows, g.n_ff, &w.ffq, &w.ffs); + w.sel_h = decl_b(b, nm.f("df_selh"), g.act_dtype, {srows, g.n_embd}); + w.dlog = decl_b(b, nm.f("df_dlog"), g.act_dtype, {srows, g.n_vocab}); + if (sharded) { + w.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {srows, kTopR}); + w.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {srows, kTopR}); + w.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {srows, kTopR, 2}); + w.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {srows, (int64_t)g.world * kTopR, 2}); + } else { + w.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {srows, 1}); + } + /* The draft, one row per draft position: [n_seq * steps, 1], which is [n_seq, steps] with a + * pitch of `steps`, read by the engine through the drafter's declaration. */ + w.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {srows, 1}); + + /* ---------------------------------------------------------------- per-layer weights */ + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const RadWeightGroup gl = grp_layer(first_layer + i); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i), + nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), + nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), + nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i))); + RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), + nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i))); + w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); + /* The declared names match rad_block_dflash2.h's, so one recipe quantises both + * drafters. */ + RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, + { nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) })); + RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff, + g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, + { nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i), + nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) }, + { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, + { nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) })); + const Lin* lins[6] = { &w_q[i], &w_k[i], &w_v[i], &w_o[i], &w_gu[i], &w_dn[i] }; + const char* names[6] = { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", + "ffn_down" }; + for (int k = 0; k < 6; ++k) + RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, names[k]), *lins[k])); + } + /* The int8 grid's prefill band: above 64 rows libr4d's w8a8 GEMM is the tiled one, which takes + * N in 256s. The context pass runs at prefill heights (fc, k and v over every committed row) and + * the query pass at qrows, so a linear whose rows on this rank are not whole 256s has no kernel + * past 64, and is refused here by name rather than as an op that does not resolve. */ + if (i8) { + const int64_t ns[4] = { g.n_embd, kvd, qd, 2 * g.n_ff }; + const int64_t hi[4] = { crows, crows, qrows, qrows }; + for (int k = 0; k < 4; ++k) + if (hi[k] > 64 && ns[k] % 256) { + fprintf(stderr, "radiance: gemma4: one of the DFlash drafter's int8 linears is " + "%lld rows per rank, and above 64 rows the w8a8 GEMM takes them in " + "256s; serve this drafter at fewer ranks or on the E4M3 grid\n", + (long long)ns[k]); + return RAD_E_UNSUPPORTED; + } + } + + /* ---------------------------------------------------------------- attention: two kinds + * Declared before either kv_store, which reads `block_size` back from the resolved kernel. + * Both read the one KV group, so whichever resolves first answers for it. */ + auto attn = [&](int causal, int64_t window) { + return rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa() / rep), RAD_INT("causal", causal), + RAD_INT("window", window), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn}); + }; + bool any_full = false, any_swa = false; + for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true; + if (any_swa) op_attn_swa = attn(1, cfg.window); + if (any_full) op_attn_full = attn(0, 0); + + /* The copies into the cache's layout (rep_kv), a head-wide strided row copy each. Each pass's + * pair is declared in its first layer, where it is first issued: declaration order is the + * buffer planner's liveness, and declared after the layers the copies' buffers would look born + * after the last layer's input and free to share its bytes. */ + auto rep_op = [&](int64_t rows, rad_buf src, rad_buf dst) { + return rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.head_dim), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {src}, {dst}); + }; + + /* ---------------------------------------------------------------- the context pass */ + op_qsrc = decl_quant(b, crows, tw, w.src, w.srcq, w.srcs); + op_cfc = w_fc.gemm(b, crows, g.n_embd, tw, {w.srcq, w.srcs}, {w.c}); + op_cnorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_hnorm)), + {w.c}, {w.c}); + op_qc = decl_quant(b, crows, g.n_embd, w.c, w.cq, w.cs); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck}); + op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv}); + if (rep > 1 && i == 0) { + op_rep_ck = rep_op(crows, w.ck, w.ck4); + op_rep_cv = rep_op(crows, w.cv, w.cv4); + } + op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn[i])), + {w.ck}, {w.ck}); + } + op_crope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.ck}, {w.ck}); + op_cstore = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv * rep), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {rep > 1 ? w.ck4 : w.ck, rep > 1 ? w.cv4 : w.cv}, {}); + + /* ---------------------------------------------------------------- the query pass */ + op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)), + RAD_WEIGHTS(w_tok)), + {}, {w.x}); + if (g.world > 1) + op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {w.x}, {w.x}); + op_qh = decl_quant(b, qrows, g.n_embd, w.h, w.hq, w.hs); + op_qat = decl_quant(b, qrows, qd, w.attn, w.atq, w.ats); + op_qff = decl_quant(b, qrows, g.n_ff, w.ffn, w.ffq, w.ffs); + + /* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the + * fused_add_rms_norm form (x += h first). On the E4M3 grid it computes exactly the chain's + * result, the norm of the bf16-rounded sum and the codes of the bf16-rounded norm + * (libr4d/r4d_rows.cpp); the int8 one keeps the sum in f32 (docs/OPS.md). It is asked about + * first, since declaring an op no loaded library declares is an error. */ + const bool has_nq = rad_op_declared(b, i8 ? "rmsnorm_quant_i8" : "rmsnorm_quant_fp8") != 0; + auto norm_quant_op = [&](rad_weight gain, bool add) -> rad_op { + if (!has_nq) return (rad_op)0; + const rad_op h = i8 + ? RAD_OP(b, "rmsnorm_quant_i8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype), + RAD_F64("wadd", 0.0)), + RAD_WEIGHTS(gain)) + : RAD_OP(b, "rmsnorm_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)), + RAD_WEIGHTS(gain)); + return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs}); + }; + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_anorm[i])), + {w.x}, {w.h}); + op_anq[i] = norm_quant_op(w_anorm[i], l > 0); + op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q}); + op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k}); + op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v}); + if (rep > 1 && i == 0) { + op_rep_k = rep_op(qrows, w.k, w.k4); + op_rep_v = rep_op(qrows, w.v, w.v4); + } + op_qn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn[i])), + {w.q}, {w.q}); + op_kn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn[i])), + {w.k}, {w.k}); + op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h}); + op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_fnorm[i])), + {w.x}, {w.h}); + op_fnq[i] = norm_quant_op(w_fnorm[i], true); + op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up}); + /* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's + * rule, band included). E4M3 grid only: libr4d's fold is fp8a8. */ + { + const int64_t hi = qrows < 64 ? qrows : 64; + if (hi > 0 && !i8 && !w_gu[i].f.mx) { + op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff), + RAD_INT("K", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")), + RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)), + {w.hq, w.hs}, {w.ffq, w.ffs}); + if (op_gug[i]) gated_rows = hi; + } + } + op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h}); + } + op_qrope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.q}, {w.q}); + op_krope = rw(b, decl_rotary(b, g, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("mode", "neox")), + RAD_NOWEIGHTS), + {w.k}, {w.k}); + op_store = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv * rep), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {rep > 1 ? w.k4 : w.k, rep > 1 ? w.v4 : w.v}, {}); + op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.gate_up}, {w.ffn}); + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + op_final = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + + /* ---------------------------------------------------------------- the head + * The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous, + * projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded, + * each rank reports its best kTopR as global ids with logits; these are all-gathered and + * reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the + * global winner is its own shard's first. */ + op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.h}, {w.sel_h}); + /* The 8-bit copy, where the container holds one (see the file header). The name map comes + * first since it is how the encoding is looked up; rad-convert writes only declared weights. + * The copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and + * `vocab_off` holds. Its grid is its own, not the linears': it reads its own quantised copy of + * the gathered rows. */ + const char* dhn = nm.f("dflash.draft_head.weight"); + RAD_ARCH_TRY(map_copy(b, dhn, tok_src)); + RadEncoding he{}; + const bool known = weight_enc(b, dhn, &he); + const bool head_fp8 = known && block_fp8_128(he); + const bool head_i8 = known && linear_w8a8(he); + q_head = head_fp8 || head_i8; + if (q_head) { + if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: gemma4: the 8-bit draft head is %lldx%lld a rank, which " + "is not whole %d-row scale blocks\n", + (long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE; + w_dh.i8 = head_i8; + w_dh.w = decl_view(b, dhn, nullptr, "codes", head_i8 ? RAD_I8 : RAD_F8E4M3, + { g.n_vocab, g.n_embd }, RAD_ACCESS_PER_TOKEN, shard, grp_model()); + w_dh.s = head_i8 + ? decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16, + { g.n_vocab, g.n_embd / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, shard, + grp_model()) + : decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16, + { fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN, + shard, grp_model()); + w_dh.f.w = w_dh.w; + w_dh.f.s = w_dh.s; + if (!w_dh.w || !w_dh.s) return RAD_E_INVAL; + w.selq = decl_b(b, nm.f("df_selq"), head_i8 ? RAD_I8 : RAD_F8E4M3, {srows, g.n_embd}); + w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, + {srows, head_i8 ? 1 : fp8_blocks(g.n_embd)}); + op_qsel = rw(b, RAD_OP(b, head_i8 ? "quant_act_i8" : "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.sel_h}, {w.selq, w.sels}); + op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog}); + } else { + op_head = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_tok)), + {w.sel_h}, {w.dlog}); + } + if (sharded) { + op_topk = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.cand, w.unary, w.dpair}); + /* Row-interleaved, so one draft position's pairs from every rank land side by side. */ + op_dgather = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"), + RAD_INT("row", kTopR * 2)), + RAD_NOWEIGHTS), + {w.dpair}, {w.dgath}); + op_pick = rw(b, RAD_OP(b, "pair_argmax", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {w.dgath}, {w.tokens}); + if (!op_pick) { + fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the " + "device, and no loaded kernel library serves it there\n"); + return RAD_E_UNSUPPORTED; + } + } else { + op_topk = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", 1), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.dlog}, {w.tokens, w.unary}); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------------------ the context pass */ + +inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + + quant(c, op_qsrc, T, w.src, w.srcq, w.srcs); + gemm(c, op_cfc, T, w.srcq, w.srcs, w_fc, w.c); + RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T)); + quant(c, op_qc, T, w.c, w.cq, w.cs); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + gemm(c, op_ck[i], T, w.cq, w.cs, w_k[i], w.ck); + gemm(c, op_cv[i], T, w.cq, w.cs, w_v[i], w.cv); + RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]), + brows(w.ck, T)); + RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T)); + const bool rep = cfg.kv_rep > 1; + if (rep) { + rep_kv(c, op_rep_ck, T, w.ck, w.ck4); + rep_kv(c, op_rep_cv, T, w.cv, w.cv4); + } + RAD_ISSUE_N(c, op_cstore, T, brows(rep ? w.ck4 : w.ck, T), brows(rep ? w.cv4 : w.cv, T), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + } +} + +/* ------------------------------------------------------------------------------ the query pass */ + +inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + + RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T)); + if (op_embed_ar) + RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa; + + /* The attention input, with the last layer's residual add where one launch takes both. */ + if (op_anq[i]) { + norm_quant(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T), + l > 0 ? brows(w.x, T) : RAD_NONE, w_anorm[i]); + } else { + RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); + quant(c, op_qh, T, w.h, w.hq, w.hs); + } + gemm(c, op_qp[i], T, w.hq, w.hs, w_q[i], w.q); + gemm(c, op_kp[i], T, w.hq, w.hs, w_k[i], w.k); + gemm(c, op_vp[i], T, w.hq, w.hs, w_v[i], w.v); + RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T)); + RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T)); + RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T)); + const bool rep = cfg.kv_rep > 1; + if (rep) { + rep_kv(c, op_rep_k, T, w.k, w.k4); + rep_kv(c, op_rep_v, T, w.v, w.v4); + } + RAD_ISSUE_N(c, op_store, T, brows(rep ? w.k4 : w.k, T), brows(rep ? w.v4 : w.v, T), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + brows(w.q, T), kv_cache(kv, first_layer + i), + praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), + praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T)); + quant(c, op_qat, T, w.attn, w.atq, w.ats); + gemm(c, op_op[i], T, w.atq, w.ats, w_o[i], w.h); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + if (op_fnq[i]) { + norm_quant(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), w_fnorm[i]); + } else { + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); + quant(c, op_qh, T, w.h, w.hq, w.hs); + } + if (op_gug[i] && T <= gated_rows) { + RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), + RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T), + RAD_NONE); + } else { + gemm(c, op_gu[i], T, w.hq, w.hs, w_gu[i], w.gate_up); + RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T)); + quant(c, op_qff, T, w.ffn, w.ffq, w.ffs); + } + gemm(c, op_dn[i], T, w.ffq, w.ffs, w_dn[i], w.h); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + /* the residual add, unless the next layer's input norm takes it */ + if (l + 1 == g.n_layer || !op_anq[i + 1]) + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); + } + RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + + const int64_t S = batch->n_out; + if (S <= 0) return; + RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S)); + if (q_head) { + if (w_dh.i8) + RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S), + RAD_NONE); + else + RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S)); + RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w), + RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref()); + } else { + RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S)); + } + if (sharded) { + RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S), + brows(w.dpair, S)); + RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S)); + RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE); + } else { + RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S), + RAD_NONE); + } +} + +} /* namespace gemma4 */ + +#endif /* RAD_GEMMA4_DFLASH_H */ diff --git a/arch/gemma4/gemma4.cpp b/arch/gemma4/gemma4.cpp index f6d56cef..1bff90fe 100644 --- a/arch/gemma4/gemma4.cpp +++ b/arch/gemma4/gemma4.cpp @@ -90,8 +90,7 @@ #include #include #include - -#include "gemma4_dflash.h" +#include #include #include @@ -223,16 +222,15 @@ struct Model { rad_weight w_tok = 0, w_onorm = 0; rad_op op_embed = 0, op_embed_ar = 0, op_onorm = 0, op_gather = 0, op_logits = 0, op_cap = 0; - enum { MAX_TAPS = 8 }; + enum { MAX_TAPS = Dflash1::MAX_TAPS }; int n_taps = 0; int tap_layer[MAX_TAPS] = {}; rad_buf b_dfsrc = 0; Dflash1 df{}; - Dflash1::Wire dfw{}; rad_kvgroup kv_draft = 0; bool have_df = false; - const char* tok_src = nullptr; /* the checkpoint's table, which the fp8 draft head copies */ + const char* tok_src = nullptr; /* the checkpoint's table, which the 8-bit draft head copies */ std::vector layers; }; @@ -301,159 +299,19 @@ static rad_op decl_full_rope(RadBuilder* b, const Kind& k, int64_t rows, int64_t /* ============================================================== the drafter */ +/* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), past the trunk's layers, reading the + * taps the trunk copies into `dflash_src` and the trunk's tied table. */ static int declare_dflash(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, Model& m, int base_layer) { - Names& nm = m.nm; - Geom dg{}; - RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma4 DFlash")); - if (rad_meta_geti(meta, "draft.hidden_size", dg.n_embd) != dg.n_embd) { - fprintf(stderr, "radiance: gemma4: the drafter is %lld wide and the target %lld; it reads " - "the target's embedding and head, so it is not this target's drafter\n", - (long long)rad_meta_geti(meta, "draft.hidden_size", 0), (long long)dg.n_embd); - return RAD_E_UNSUPPORTED; - } - - Dflash1::Config dc{}; - dc.n_taps = m.n_taps; - dc.escale = m.escale; - /* v1 states its block at the top level; a SpecForge config nests it under dflash_config. */ - long long trained = rad_meta_geti(meta, "draft.block_size", 0); - if (trained <= 0) trained = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); - if (trained < 2) { - fprintf(stderr, "radiance: gemma4: the DFlash checkpoint states no block_size\n"); - return RAD_E_FORMAT; - } - if ((long long)ctx->max_spec + 1 != trained) { - fprintf(stderr, "radiance: gemma4: the DFlash drafter was trained at block_size %lld, " - "which is %lld draft tokens, and this serve asks for %d. A block-diffusion " - "drafter denoises a fixed number of mask positions; run it at " - "--num-speculative-tokens %lld (or `auto`).\n", - trained, trained - 1, ctx->max_spec, trained - 1); - return RAD_E_UNSUPPORTED; - } - dc.block = trained; - if (dg.n_layer > Dflash1::MAX_LAYERS) return RAD_E_UNSUPPORTED; - { - std::vector full; - const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr); - if (lt) { - RAD_ARCH_TRY(parse_layer_kinds("gemma4", lt, {"full_attention"}, "sliding_attention", - &full)); - if ((int64_t)full.size() != dg.n_layer) { - fprintf(stderr, "radiance: gemma4: the drafter's layer_types names %zu layers and " - "it has %lld\n", full.size(), (long long)dg.n_layer); - return RAD_E_INVAL; - } - } else { - full.assign((size_t)dg.n_layer, 1); - } - bool any_swa = false; - for (int64_t l = 0; l < dg.n_layer; ++l) { - dc.full[l] = full[(size_t)l]; - any_swa = any_swa || !full[(size_t)l]; - } - if (any_swa) { - dc.window = rad_meta_geti(meta, "draft.dflash_config.swa_window_size", - rad_meta_geti(meta, "draft.sliding_window", 0)); - if (!rad_meta_geti(meta, "draft.use_sliding_window", 1) || dc.window <= 0) { - fprintf(stderr, "radiance: gemma4: the drafter names sliding layers and no " - "window\n"); - return RAD_E_INVAL; - } - } - } - - /* One unbounded cache for all the drafter's layers, because its full layer reads every - * position. The sliding layers bound themselves with their attention op's `window`, so the - * declared drafter window is 0 and the core stages the whole context. A separate window group - * for the sliding layers would save memory. */ - RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, 0, base_layer, &m.kv_draft)); - - const int64_t qd = dg.n_head * dg.head_dim; - const int64_t kvd = dg.n_head_kv * dg.head_dim; - int64_t qr = dg.max_seqs * dc.block; - if (qr > dg.max_tok) qr = dg.max_tok; - const int64_t sr = dg.max_seqs * dc.steps(); - const int64_t tw = dc.n_taps * dg.n_embd; - - Dflash1::Wire& dw = m.dfw; - dw.src = m.b_dfsrc; - dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, tw}); - dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(tw)}); - dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd}); - dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd}); - dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)}); - dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd}); - dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd}); - dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd}); - dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd}); - dw.hq = decl_b(b, nm.f("df_hq"), RAD_F8E4M3, {qr, dg.n_embd}); - dw.hs = decl_b(b, nm.f("df_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)}); - dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd}); - dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd}); - dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd}); - dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd}); - dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd}); - dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)}); - dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff}); - dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff}); - dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); - dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); - dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd}); - dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, dg.n_vocab}); - if (Dflash1::head_sharded(dg)) { - const int64_t R = Dflash1::kTopR; - dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, R}); - dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, R}); - dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, R, 2}); - dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * R, 2}); - } else { - dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, 1}); - } - if (!Dflash1::head_sharded(dg) && dg.world > 1) { - fprintf(stderr, "radiance: gemma4: the vocabulary (%lld) does not split evenly into whole " - "16-row blocks over %d ranks, which the drafter's sharded head needs\n", - (long long)dg.n_vocab_all, dg.world); - return RAD_E_UNSUPPORTED; - } - /* The draft, one row per draft position: [n_seq * steps, 1], i.e. [n_seq, steps] with pitch - * `steps`, read by the engine through the drafter declaration below. */ - dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {sr, 1}); - - RAD_ARCH_TRY(m.df.declare(b, nm, dg, dc, base_layer, m.kv_draft, m.w_tok, "draft", dw, - m.tok_src)); + Dflash1::Trunk t{}; + t.n_taps = m.n_taps; + t.escale = m.escale; + t.src = m.b_dfsrc; + t.w_tok = m.w_tok; + t.tok_src = m.tok_src; + t.base_layer = base_layer; + RAD_ARCH_TRY(Dflash1::declare_drafter(b, meta, ctx, m.nm, m.g, t, &m.df, &m.kv_draft)); m.have_df = true; - - RadDrafterDecl drf{}; - drf.name = "dflash"; - drf.kind = RAD_DRAFT_BLOCK; - drf.depth = ctx->max_spec; - drf.block = dc.block; /* the anchor predicts nothing: block = depth + 1 */ - drf.proposal = dw.tokens; - drf.proposal_pitch = dc.steps(); - drf.window = 0; /* the full layer reads everything; see the group */ - drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", - rad_meta_geti(meta, "draft.mask_token_id", -1)); - if (drf.mask_token < 0) { - fprintf(stderr, "radiance: gemma4: the DFlash checkpoint declares no mask_token_id\n"); - return RAD_E_FORMAT; - } - RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); - - int nfull = 0; - for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l]; - rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld " - "sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the " - "trunk at %d tap(s). ONE forward over %lld rows proposes %lld tokens; the head is " - "%s, argmax %s", - (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, nfull, - (long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head, - (long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, m.n_taps, - (long long)dc.block, (long long)dc.steps(), - m.df.fp8_head - ? "the container's block-fp8 copy of the target's table (dflash.draft_head)" - : "the target's tied bf16 table", - Dflash1::head_sharded(dg) ? "per vocab shard, merged" : "over the whole vocabulary"); return RAD_OK; } @@ -662,7 +520,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ---- the embedding scale and the rotary scaling the converter may have written. The scale * is rounded to bf16 because the reference holds it in a bf16 buffer: sqrt(2816) = 53.066 * multiplies as 53.0. */ - m.escale = rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)E))); + m.escale = embed_scale(E); RAD_ARCH_TRY(yarn_from(g, meta, "", m.ks.hd)); if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f) { fprintf(stderr, "radiance: gemma4: --rope-scaling is not implemented for this family's " @@ -794,24 +652,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* ---- the drafter's taps, declared when the container carries a DFlash drafter and this * serve speculates. DFlash2 is refused by name: its convolutions and selector are another * block. */ - if (ctx->max_spec > 0) { - const char* da = rad_meta_gets(meta, "draft.architectures", ""); - if (da && std::strstr(da, "DFlash2")) { - fprintf(stderr, "radiance: gemma4: the container carries a DFlash2 drafter; this plugin " - "serves the DFlash (v1) block z-lab publishes for Gemma 4\n"); - return RAD_E_UNSUPPORTED; - } - if (da && std::strstr(da, "DFlash")) { - const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr); - if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr); - m.n_taps = parse_layer_ids(ids, m.n_layer, m.tap_layer, Model::MAX_TAPS); - if (m.n_taps <= 0) { - fprintf(stderr, "radiance: gemma4: the drafter names no trunk layer this model " - "has; it is paired with a different target\n"); - return RAD_E_UNSUPPORTED; - } - m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)m.n_taps * E}); - } + { + const int n = Dflash1::taps(meta, ctx, m.n_layer, m.tap_layer, Model::MAX_TAPS); + if (n < 0) return n; + m.n_taps = n; + if (n > 0) m.b_dfsrc = decl_b(b, nm.f("dflash_src"), RAD_BF16, {T, (int64_t)n * E}); } m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); @@ -1869,15 +1714,7 @@ static void step(RadCtx* c, const RadBatch* batch) { static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; out->draft_depth = 0; - const char* da = rad_meta_gets(meta, "draft.architectures", ""); - if (da && std::strstr(da, "DFlash") && !std::strstr(da, "DFlash2")) { - long long bs = rad_meta_geti(meta, "draft.block_size", 0); - if (bs <= 0) bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 0); - if (bs > 1) { - out->draft_depth = (int)(bs - 1); - out->draft_depth_fixed = 1; - } - } + (void)dflash_probe(meta, out); return RAD_OK; } diff --git a/arch/gemma4/gemma4_dflash.h b/arch/gemma4/gemma4_dflash.h deleted file mode 100644 index 1e6e2e2f..00000000 --- a/arch/gemma4/gemma4_dflash.h +++ /dev/null @@ -1,682 +0,0 @@ -/* gemma4_dflash.h -- the DFlash (v1) block-diffusion drafter, as z-lab trains it for Gemma 4. - * - * ============================== WHAT IT IS ============================== - * - * rad_block_dflash2.h without DFlash2's additions (the per-layer dynamic convolutions around - * attention and the feed-forward, and the candidate selector). The original DFlash is a small - * Qwen3-shaped transformer that denoises one anchor token plus `block - 1` mask tokens in one - * forward and takes every position's argmax from the target's lm_head. - * - * context pass, one row a committed token: - * c = hidden_norm(fc(concat of the trunk's residual stream at target_layer_ids))) - * for each layer: k = k_norm(k_proj(c)) then rope; v = v_proj(c); kv_store(k, v) - * - * query pass, `block` rows a sequence: - * x = embed(anchor, mask, ...) * sqrt(hidden) <- Gemma's embedding scale, see below - * for each layer: - * h = input_layernorm(x) - * q, k, v = q_proj(h), k_proj(h), v_proj(h); q_norm, k_norm; rope; kv_store - * x += o_proj(attention(q, cache)) sliding layers causal over a 2048 window, - * the full layer non-causal over everything - * x += down(silu(gate(h')) * up(h')), h' = post_attention_layernorm(x) - * x = norm(x) - * over the mask rows: logits = lm_head(x) [the target's]; draft = argmax - * - * ============================== THE THREE GEMMA-SPECIFIC FACTS ============================== - * - * From vLLM PR #41703. Getting any of them wrong costs only acceptance, since every draft is - * verified against the trunk. - * - * The embedding is scaled. Gemma multiplies its token embedding by sqrt(hidden_size), stored as - * bf16 (53.0 at 2816), and the drafter was trained through the target's embedding module, which - * applies it. `embed_lookup`'s `mult` carries it. - * - * The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names - * four sliding layers and one full one, and the PR's test pins `causal True` on the sliding - * layers and `False` on the full one, so this block declares two attention ops and issues the one - * each layer's type names. - * - * The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and - * cap * tanh(x / cap) is strictly increasing. - * - * ============================== THE HEAD ============================== - * - * The target's own head, read in bf16 by an ordinary `gemm_nt` over the gathered mask rows. Gemma - * ties it to the embedding, so it is the weight the trunk's `embed_lookup` and `logits_gemm` read - * and costs no extra bytes. It is vocab-sharded with the trunk: the top-1 runs over this rank's - * slice and the ranks' candidates merge exactly (`row_topk` at R = 2 -> `all_gather` -> - * `pair_argmax`; R = 2 because the gather moves 16-byte rows, see kTopR). - * - * The bf16 head (262144 x 2816 x 2 bytes) is the widest read on the draft path, about 566 us of a - * 26B-A4B decode step at tp 4 on 4x R9700. So where the container holds a block-fp8 copy of the - * table under its own name, `dflash.draft_head.weight` (one checkpoint tensor, two logical - * weights, as in rad_block_dflash2.h), made by the recipe line - * - * dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 - * - * the head is `gemm_nt_q` over that copy at fp8a8, half the bytes, with the argmax over its - * coarser logits. Drafts are still verified, so the copy can change proposals but never accepted - * text. Without the copy, or in another encoding, the bf16 table is read. The copy costs half the - * table's bytes again (176 MiB per rank at tp 4). There is no rerank against the bf16 table: - * DFlash2's rerank needs the target's head in fp8 or int8, which a tied Gemma head is not. - * - * ============================== THE LINEARS ARE FP8 ============================== - * - * As in DFlash2, since the drafter is read whole on every decode step: the container must be - * converted with a recipe that makes the six linears block fp8 (or MXFP4). declare() refuses a bf16 - * one by name rather than letting the loader fail on a view. - */ -#ifndef GEMMA4_DFLASH_H -#define GEMMA4_DFLASH_H - -#include -#include - -#include -#include - -namespace gemma4 { - -using namespace rad::arch; - -/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no - * transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */ -inline bool block_fp8_128(const RadEncoding& e) { - const RadEncPlane* sc = rad_enc_plane(&e, "scale"); - return rad_enc_is(&e, "affine") && e.n_planes == 2 && !e.transform[0] && - e.plane[0].dtype == RAD_F8E4M3 && sc && sc->dtype == RAD_BF16 && - sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK; -} - -struct Dflash1 { - enum { MAX_LAYERS = 8 }; - - struct Config { - int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */ - int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */ - int64_t window = 0; /* the sliding layers' window; 0 for none */ - int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */ - double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */ - int64_t steps() const { return block - 1; } - }; - - struct Wire { - /* the context pass */ - rad_buf src = 0, srcq = 0, srcs = 0; /* [max_tok, n_taps*n_embd] bf16 | e4m3 | f32 */ - rad_buf c = 0, cq = 0, cs = 0; /* [max_tok, n_embd] */ - rad_buf ck = 0, cv = 0; /* [max_tok, kv_dim] -- see rad_block_dflash2.h */ - /* the query pass */ - rad_buf x = 0, h = 0, hq = 0, hs = 0; /* [qrows, n_embd] */ - rad_buf q = 0, k = 0, v = 0; /* [qrows, q_dim | kv_dim | kv_dim] */ - rad_buf attn = 0, atq = 0, ats = 0; /* [qrows, q_dim] */ - rad_buf gate_up = 0; /* [qrows, 2 * n_ff] */ - rad_buf ffn = 0, ffq = 0, ffs = 0; /* [qrows, n_ff] */ - /* the head, one row per draft position */ - rad_buf sel_h = 0; /* [srows, n_embd] */ - rad_buf selq = 0, sels = 0; /* [srows, n_embd] e4m3 | f32, the fp8 head's */ - rad_buf dlog = 0; /* [srows, n_vocab on this rank] bf16 */ - rad_buf cand = 0, unary = 0; /* [srows, kTopR] i32 | f32 -- this rank's best */ - rad_buf dpair = 0, dgath = 0; /* [srows, kTopR, 2] | [srows, world * kTopR, 2] f32 */ - rad_buf tokens = 0; /* [srows, 1] i32: the draft, pitch `steps` */ - }; - - Geom g{}; /* the drafter's geometry */ - Config cfg{}; - Wire w{}; - int first_layer = 0; - int64_t qrows = 0, crows = 0, srows = 0, gated_rows = 0; - rad_kvgroup kv = 0; - bool sharded = false; - - DenseFP8 w_fc{}; - rad_weight w_hnorm = 0, w_norm = 0; - rad_weight w_tok = 0; /* the target's table: embedding and head */ - DenseFP8 w_dh{}; /* its block-fp8 copy, the head where it is stored */ - bool fp8_head = false; - rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; - DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{}; - rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}; - DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{}; - - rad_op op_qsrc = 0, op_cfc = 0, op_cnorm = 0, op_qc = 0, op_crope = 0, op_cstore = 0; - rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; - - rad_op op_embed = 0, op_embed_ar = 0, op_qh = 0, op_qat = 0, op_qff = 0; - rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}; - /* The residual add, norm and quantiser in one launch where `rmsnorm_quant_fp8` is served - * (libr4d): op_anq[i] for the attention input (layer 0's without the add) and op_fnq[i] for - * the feed-forward input. Zero where not served; the `add` / `rmsnorm` / `quant_act_fp8` chain - * is issued instead. */ - rad_op op_anq[MAX_LAYERS] = {}, op_fnq[MAX_LAYERS] = {}; - rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; - rad_op op_op[MAX_LAYERS] = {}, op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; - rad_op op_gu[MAX_LAYERS] = {}, op_gug[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; - rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn_swa = 0, op_attn_full = 0; - rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; - rad_op op_gather = 0, op_qsel = 0, op_head = 0, op_topk = 0, op_dgather = 0, op_pick = 0; - - /* Candidates each rank contributes under a sharded head. The draft needs one, but the gather - * moves whole 16-byte words per row and an (int32 id, f32 value) pair is 8 bytes, so R = 1 is - * refused at launch (as rad_block_mtp_hc.h states). Two pairs make one word; `pair_argmax` - * reduces the world * 2 of them to the global top-1. */ - static constexpr int64_t kTopR = 2; - - static bool head_sharded(const Geom& g) { return vocab_head_sharded(g); } - - int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, - rad_kvgroup group, rad_weight tok_embd, const char* ck, const Wire& wire, - const char* tok_src); - void context(RadCtx* c, const RadBatch* batch) const; - void step(RadCtx* c, const RadBatch* batch) const; - -private: - int64_t q_dim() const { return g.n_head * g.head_dim; } - int64_t kv_dim() const { return g.n_head_kv * g.head_dim; } - /* The six linears must be quantised by the recipe. DenseFP8 declares E4M3 (or MXFP4) views - * whatever the container holds, and the loader's error for a bf16 weight read through an fp8 - * view would name the view, not the missing recipe. */ - static int need_quantised(RadBuilder* b, const char* wn) { - RadEncoding e{}; - if (!weight_enc(b, wn, &e) || e.n_planes <= 0) return RAD_OK; /* nothing to ask yet */ - const uint32_t dt = e.plane[0].dtype; - if (dt == RAD_F8E4M3 || dt == RAD_FP4E2M1) return RAD_OK; - fprintf(stderr, "radiance: gemma4: the DFlash drafter's '%s' is stored %s. Its six linears " - "are served block fp8 (or MXFP4): convert with a recipe that names them, " - "e.g. `dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 " - "scale=bf16` and the same for fc, attn_k/v/output, ffn_gate_up and " - "ffn_down.\n", wn, rad_dtype_name(dt)); - return RAD_E_DTYPE; - } -}; - -/* ------------------------------------------------------------------------------ declare */ - -inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, - int base_layer, rad_kvgroup group, rad_weight tok_embd, - const char* ck, const Wire& wire, const char* tok_src) { - g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd; - if (!ck || !w_tok || !tok_src) return RAD_E_INVAL; - if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) { - fprintf(stderr, "radiance: gemma4: the drafter has %lld layers; this block carries at most " - "%d\n", (long long)g.n_layer, MAX_LAYERS); - return RAD_E_UNSUPPORTED; - } - if (cfg.block < 2 || cfg.n_taps <= 0) return RAD_E_INVAL; - - const int64_t qd = q_dim(), kvd = kv_dim(); - crows = g.max_tok; - qrows = g.max_seqs * cfg.block; - if (qrows > g.max_tok) qrows = g.max_tok; - srows = g.max_seqs * cfg.steps(); - if (qrows <= 0 || srows <= 0) return RAD_E_INVAL; - sharded = head_sharded(g); - - /* ---------------------------------------------------------------- model-scope weights */ - RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(), - { nm.ckpt("%s.fc.weight", ck) })); - RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.fc.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck))); - w_hnorm = decl_w(b, nm.f("dflash.hidden_norm.weight"), RAD_F32, {g.n_embd}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); - w_norm = decl_w(b, nm.f("dflash.norm.weight"), RAD_F32, {g.n_embd}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); - - /* ---------------------------------------------------------------- per-layer weights */ - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - const RadWeightGroup gl = grp_layer(first_layer + i); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_norm.weight", i), - nm.ckpt("%s.layers.%d.input_layernorm.weight", ck, i))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), - nm.ckpt("%s.layers.%d.post_attention_layernorm.weight", ck, i))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), - nm.ckpt("%s.layers.%d.self_attn.q_norm.weight", ck, i))); - RAD_ARCH_TRY(map_copy(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), - nm.ckpt("%s.layers.%d.self_attn.k_norm.weight", ck, i))); - w_anorm[i] = decl_w(b, nm.f("dflash.blk.%d.attn_norm.weight", i), RAD_F32, {g.n_embd}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); - w_fnorm[i] = decl_w(b, nm.f("dflash.blk.%d.ffn_norm.weight", i), RAD_F32, {g.n_embd}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); - w_qn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_q_norm.weight", i), RAD_F32, {g.head_dim}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); - w_kn[i] = decl_w(b, nm.f("dflash.blk.%d.attn_k_norm.weight", i), RAD_F32, {g.head_dim}, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, gl); - /* The declared names match rad_block_dflash2.h's, so one recipe quantises both - * drafters. */ - RAD_ARCH_TRY(w_q[i].declare(b, nm, nm.f("dflash.blk.%d.attn_q", i), qd, g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, - { nm.ckpt("%s.layers.%d.self_attn.q_proj.weight", ck, i) })); - RAD_ARCH_TRY(w_k[i].declare(b, nm, nm.f("dflash.blk.%d.attn_k", i), kvd, g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, - { nm.ckpt("%s.layers.%d.self_attn.k_proj.weight", ck, i) })); - RAD_ARCH_TRY(w_v[i].declare(b, nm, nm.f("dflash.blk.%d.attn_v", i), kvd, g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, - { nm.ckpt("%s.layers.%d.self_attn.v_proj.weight", ck, i) })); - RAD_ARCH_TRY(w_o[i].declare(b, nm, nm.f("dflash.blk.%d.attn_output", i), g.n_embd, qd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, - { nm.ckpt("%s.layers.%d.self_attn.o_proj.weight", ck, i) })); - RAD_ARCH_TRY(w_gu[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_gate_up", i), 2 * g.n_ff, - g.n_embd, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, gl, - { nm.ckpt("%s.layers.%d.mlp.gate_proj.weight", ck, i), - nm.ckpt("%s.layers.%d.mlp.up_proj.weight", ck, i) }, - { g.n_ff, g.n_ff })); - RAD_ARCH_TRY(w_dn[i].declare(b, nm, nm.f("dflash.blk.%d.ffn_down", i), g.n_embd, g.n_ff, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, gl, - { nm.ckpt("%s.layers.%d.mlp.down_proj.weight", ck, i) })); - for (const char* s : { "attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", - "ffn_down" }) - RAD_ARCH_TRY(need_quantised(b, nm.f("dflash.blk.%d.%s.weight", i, s))); - } - - /* ---------------------------------------------------------------- attention: two kinds - * Declared before either kv_store, which reads `block_size` back from the resolved kernel. - * Both read the one KV group, so whichever resolves first answers for it. */ - auto attn = [&](int causal, int64_t window) { - return rw(b, RAD_OP(b, "attn_paged", - RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), - RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal), - RAD_INT("window", window), RAD_INT("n_head", g.n_head), - RAD_INT("block_size", RAD_KV_BLOCK), - RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), - RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS), - {w.q}, {w.attn}); - }; - bool any_full = false, any_swa = false; - for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true; - if (any_swa) op_attn_swa = attn(1, cfg.window); - if (any_full) op_attn_full = attn(0, 0); - - /* ---------------------------------------------------------------- the context pass */ - op_qsrc = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", cfg.n_taps * g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.src}, {w.srcq, w.srcs}); - op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c}); - op_cnorm = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_hnorm)), - {w.c}, {w.c}); - op_qc = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.c}, {w.cq, w.cs}); - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - op_ck[i] = w_k[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.ck}); - op_cv[i] = w_v[i].gemm(b, crows, kvd, g.n_embd, {w.cq, w.cs}, {w.cv}); - op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv), - RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), - RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_kn[i])), - {w.ck}, {w.ck}); - } - op_crope = rw(b, decl_rotary(b, g, "rope", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), - RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), - RAD_STR("mode", "neox")), - RAD_NOWEIGHTS), - {w.ck}, {w.ck}); - op_cstore = rw(b, RAD_OP(b, "kv_store", - RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head_kv", g.n_head_kv), - RAD_INT("block_size", rad_kv_block_size(b, kv)), - RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS), - {w.ck, w.cv}, {}); - - /* ---------------------------------------------------------------- the query pass */ - op_embed = rw(b, RAD_OP(b, "embed_lookup", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", g.n_embd), - RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), - RAD_INT("vocab_offset", g.vocab_off), RAD_F64("mult", cfg.escale)), - RAD_WEIGHTS(w_tok)), - {}, {w.x}); - if (g.world > 1) - op_embed_ar = rw(b, RAD_OP(b, "all_reduce", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), - RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), - RAD_NOWEIGHTS), - {w.x}, {w.x}); - op_qh = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.h}, {w.hq, w.hs}); - op_qat = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", qd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.attn}, {w.atq, w.ats}); - op_qff = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.ffn}, {w.ffq, w.ffs}); - - /* x's norm under `gain`, quantised into hq|hs, in one launch; with `add`, the - * fused_add_rms_norm form (x += h first). It computes exactly the chain's result: the norm of - * the bf16-rounded sum and the codes of the bf16-rounded norm (libr4d/r4d_rows.cpp). */ - auto norm_quant = [&](rad_weight gain, bool add) -> rad_op { - const rad_op h = RAD_OP(b, "rmsnorm_quant_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), - RAD_STR("dtype", g.dtype), RAD_F64("wadd", 0.0)), - RAD_WEIGHTS(gain)); - return add ? rw(b, h, {w.h, w.x}, {w.x, w.hq, w.hs}) : rw(b, h, {w.x}, {w.hq, w.hs}); - }; - - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_anorm[i])), - {w.x}, {w.h}); - op_anq[i] = norm_quant(w_anorm[i], l > 0); - op_qp[i] = w_q[i].gemm(b, qrows, qd, g.n_embd, {w.hq, w.hs}, {w.q}); - op_kp[i] = w_k[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.k}); - op_vp[i] = w_v[i].gemm(b, qrows, kvd, g.n_embd, {w.hq, w.hs}, {w.v}); - op_qn[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), RAD_INT("n", g.head_dim), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_qn[i])), - {w.q}, {w.q}); - op_kn[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv), - RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), - RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_kn[i])), - {w.k}, {w.k}); - op_op[i] = w_o[i].gemm(b, qrows, g.n_embd, qd, {w.atq, w.ats}, {w.h}); - op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_fnorm[i])), - {w.x}, {w.h}); - op_fnq[i] = norm_quant(w_fnorm[i], true); - op_gu[i] = w_gu[i].gemm(b, qrows, 2 * g.n_ff, g.n_embd, {w.hq, w.hs}, {w.gate_up}); - /* The gate_up|silu|quant fold where it resolves, else the pair (rad_block_dflash2.h's - * rule, band included). */ - { - const int64_t hi = qrows < 64 ? qrows : 64; - if (hi > 0 && !w_gu[i].mx) { - op_gug[i] = rw(b, RAD_OP(b, "gemm_nt_q_gated", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", 2 * g.n_ff), - RAD_INT("K", g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), - RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")), - RAD_WEIGHTS(w_gu[i].w, w_gu[i].s)), - {w.hq, w.hs}, {w.ffq, w.ffs}); - if (op_gug[i]) gated_rows = hi; - } - } - op_dn[i] = w_dn[i].gemm(b, qrows, g.n_embd, g.n_ff, {w.ffq, w.ffs}, {w.h}); - } - op_qrope = rw(b, decl_rotary(b, g, "rope", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0), - RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), - RAD_STR("mode", "neox")), - RAD_NOWEIGHTS), - {w.q}, {w.q}); - op_krope = rw(b, decl_rotary(b, g, "rope", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0), - RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), - RAD_STR("mode", "neox")), - RAD_NOWEIGHTS), - {w.k}, {w.k}); - op_store = rw(b, RAD_OP(b, "kv_store", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), - RAD_INT("n_head_kv", g.n_head_kv), - RAD_INT("block_size", rad_kv_block_size(b, kv)), - RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS), - {w.k, w.v}, {}); - op_act = rw(b, RAD_OP(b, "silu_mul", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.gate_up}, {w.ffn}); - if (g.world > 1) - op_ar = rw(b, RAD_OP(b, "all_reduce", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_RANGE("numel", g.n_embd, qrows * g.n_embd), - RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), - RAD_INT("min_bytes", g.wire_min_bytes)), - RAD_NOWEIGHTS), - {w.h}, {w.h}); - op_add = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.x, w.h}, {w.x}); - op_final = rw(b, RAD_OP(b, "rmsnorm", - RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), - RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_norm)), - {w.x}, {w.h}); - - /* ---------------------------------------------------------------- the head - * The mask rows (offsets 1..block-1 of each block, named by out_ids) are gathered contiguous, - * projected onto this rank's slice of the target's vocabulary, and the argmax taken. Sharded, - * each rank reports its best kTopR as global ids with logits; these are all-gathered and - * reduced to the global top-1 by `pair_argmax` (ties to the lower id), which is exact since the - * global winner is its own shard's first. */ - op_gather = rw(b, RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.h}, {w.sel_h}); - /* The fp8 copy, where the container holds one (see the file header). The name map comes first - * since it is how the encoding is looked up; rad-convert writes only declared weights. The - * copy is row-sharded like the table, so this rank's rows are the same vocabulary slice and - * `vocab_off` holds. */ - const char* dhn = nm.f("dflash.draft_head.weight"); - RAD_ARCH_TRY(map_copy(b, dhn, tok_src)); - RadEncoding he{}; - fp8_head = weight_enc(b, dhn, &he) && block_fp8_128(he); - if (fp8_head) { - if (g.n_vocab % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK) { - fprintf(stderr, "radiance: gemma4: the fp8 draft head is %lldx%lld a rank, which " - "is not whole %d-row scale blocks\n", - (long long)g.n_vocab, (long long)g.n_embd, RAD_FP8_BLOCK); - return RAD_E_INVAL; - } - const int shard = g.world > 1 ? RAD_SHARD_ROW : RAD_SHARD_NONE; - w_dh.w = decl_view(b, dhn, nullptr, "codes", RAD_F8E4M3, { g.n_vocab, g.n_embd }, - RAD_ACCESS_PER_TOKEN, shard, grp_model()); - w_dh.s = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_BF16, - { fp8_blocks(g.n_vocab), fp8_blocks(g.n_embd) }, RAD_ACCESS_PER_TOKEN, - shard, grp_model()); - if (!w_dh.w || !w_dh.s) return RAD_E_INVAL; - w.selq = decl_b(b, nm.f("df_selq"), RAD_F8E4M3, {srows, g.n_embd}); - w.sels = decl_b(b, nm.f("df_sels"), RAD_F32, {srows, fp8_blocks(g.n_embd)}); - op_qsel = rw(b, RAD_OP(b, "quant_act_fp8", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_embd), - RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.sel_h}, {w.selq, w.sels}); - op_head = w_dh.gemm(b, srows, g.n_vocab, g.n_embd, {w.selq, w.sels}, {w.dlog}); - } else { - op_head = rw(b, RAD_OP(b, "gemm_nt", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), - RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w_tok)), - {w.sel_h}, {w.dlog}); - } - if (sharded) { - op_topk = rw(b, RAD_OP(b, "row_topk", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), - RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.dlog}, {w.cand, w.unary, w.dpair}); - /* Row-interleaved, so one draft position's pairs from every rank land side by side. */ - op_dgather = rw(b, RAD_OP(b, "all_gather", - RAD_PARAMS(RAD_INT("world_size", g.world), - RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"), - RAD_INT("row", kTopR * 2)), - RAD_NOWEIGHTS), - {w.dpair}, {w.dgath}); - op_pick = rw(b, RAD_OP(b, "pair_argmax", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR), - RAD_STR("dtype", "f32")), - RAD_NOWEIGHTS), - {w.dgath}, {w.tokens}); - if (!op_pick) { - fprintf(stderr, "radiance: gemma4: the sharded draft head needs `pair_argmax` on the " - "device, and no loaded kernel library serves it there\n"); - return RAD_E_UNSUPPORTED; - } - } else { - op_topk = rw(b, RAD_OP(b, "row_topk", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), - RAD_INT("R", 1), RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {w.dlog}, {w.tokens, w.unary}); - } - return RAD_OK; -} - -/* ------------------------------------------------------------------------------ the context pass */ - -inline void Dflash1::context(RadCtx* c, const RadBatch* batch) const { - const int64_t T = batch->n_tok; - if (T <= 0) return; - const RadKVGroupBatch* kvb = kv_batch(batch, kv); - const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; - - RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T)); - RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), - brows(w.c, T), RAD_NONE, w_fc.bref()); - RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T)); - RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T)); - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - RAD_ISSUE_N(c, op_ck[i], T, brows(w.cq, T), brows(w.cs, T), - RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref()); - RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T), - RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref()); - RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]), - brows(w.ck, T)); - RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T)); - RAD_ISSUE_N(c, op_cstore, T, brows(w.ck, T), brows(w.cv, T), praw(slot, RAD_I32, T), - kv_cache(kv, first_layer + i)); - } -} - -/* ------------------------------------------------------------------------------ the query pass */ - -inline void Dflash1::step(RadCtx* c, const RadBatch* batch) const { - const int64_t T = batch->n_tok; - if (T <= 0) return; - const RadKVGroupBatch* kvb = kv_batch(batch, kv); - const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; - const int32_t* table = kvb ? kvb->block_table : nullptr; - const int32_t* used = kvb ? kvb->seqused : nullptr; - - RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T)); - if (op_embed_ar) - RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); - - for (int64_t l = 0; l < g.n_layer; ++l) { - const int i = (int)l; - const rad_op op_attn = cfg.full[i] ? op_attn_full : op_attn_swa; - - /* The attention input, with the last layer's residual add where one launch takes both. */ - if (op_anq[i]) { - RAD_ISSUE_N(c, op_anq[i], T, l > 0 ? brows(w.h, T) : brows(w.x, T), - l > 0 ? brows(w.x, T) : RAD_NONE, RAD_W(w_anorm[i]), brows(w.hq, T), - brows(w.hs, T), RAD_NONE); - } else { - RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); - RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); - } - RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_q[i].w), RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref()); - RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref()); - RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref()); - RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T)); - RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T)); - RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T)); - RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T)); - RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), - kv_cache(kv, first_layer + i)); - RAD_ISSUE_N(c, op_attn, batch->max_q_len, - brows(w.q, T), kv_cache(kv, first_layer + i), - praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), - praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE, - praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T)); - RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T)); - RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T), - RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref()); - if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - if (op_fnq[i]) { - RAD_ISSUE_N(c, op_fnq[i], T, brows(w.h, T), brows(w.x, T), RAD_W(w_fnorm[i]), - brows(w.hq, T), brows(w.hs, T), RAD_NONE); - } else { - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); - RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); - RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); - } - if (op_gug[i] && T <= gated_rows) { - RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T), - RAD_NONE); - } else { - RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T), - RAD_W(w_gu[i].w), RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, - w_gu[i].bref()); - RAD_ISSUE_N(c, op_act, T, brows(w.gate_up, T), brows(w.ffn, T)); - RAD_ISSUE_N(c, op_qff, T, brows(w.ffn, T), brows(w.ffq, T), brows(w.ffs, T)); - } - RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T), - RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref()); - if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - /* the residual add, unless the next layer's input norm takes it */ - if (l + 1 == g.n_layer || !op_anq[i + 1]) - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h, T), brows(w.x, T)); - } - RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); - - const int64_t S = batch->n_out; - if (S <= 0) return; - RAD_ISSUE_N(c, op_gather, S, RAD_B(w.h), praw(batch->out_ids, RAD_I32, S), brows(w.sel_h, S)); - if (fp8_head) { - RAD_ISSUE_N(c, op_qsel, S, brows(w.sel_h, S), brows(w.selq, S), brows(w.sels, S)); - RAD_ISSUE_N(c, op_head, S, brows(w.selq, S), brows(w.sels, S), RAD_W(w_dh.w), - RAD_W(w_dh.s), brows(w.dlog, S), RAD_NONE, w_dh.bref()); - } else { - RAD_ISSUE_N(c, op_head, S, brows(w.sel_h, S), RAD_W(w_tok), brows(w.dlog, S)); - } - if (sharded) { - RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.cand, S), brows(w.unary, S), - brows(w.dpair, S)); - RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S)); - RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S), RAD_NONE); - } else { - RAD_ISSUE_N(c, op_topk, S, brows(w.dlog, S), brows(w.tokens, S), brows(w.unary, S), - RAD_NONE); - } -} - -} /* namespace gemma4 */ - -#endif /* GEMMA4_DFLASH_H */ diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 34c2ba87..ebdd95a0 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -7,10 +7,17 @@ * declare), with a second norm on each projection's output before its residual, a weightless RMS * norm on the value, and a GELU (not SwiGLU) feed-forward. The final logits are soft-capped to * cap * tanh(x / cap). + * + * Two draft models, whichever the container carries under `draft.`: Google's assistant head (a + * serial head over the trunk's own cache, the Gemma4Head below) or z-lab's DFlash drafter (a + * five-layer block drafter with its own cache, reading the trunk's residual stream at six layers, + * arch/common/rad_gemma4_dflash.h) -- the 31B's z-lab/gemma-4-31B-it-DFlash proposes 15 tokens a + * pass where the assistant proposes one a round. */ #include #include #include +#include #include #include @@ -20,12 +27,6 @@ #include #include -/* sqrt(n_embd) rounded to bf16: the reference's embedding module multiplies the looked-up rows by - * `embed_scale.to(bf16)`, 73.5 at 5376 and not 73.32. */ -static double embed_scale(int64_t n) { - return rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)n))); -} - namespace gemma4_bf16 { using namespace rad::arch; @@ -839,7 +840,7 @@ int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, cons RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_embd", n_trunk), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), RAD_INT("vocab_offset", g.vocab_off), - RAD_F64("mult", embed_scale(n_trunk))), + RAD_F64("mult", gemma4::embed_scale(n_trunk))), RAD_WEIGHTS(w_tok)), {}, {b_e}); if (g.world > 1) @@ -1098,6 +1099,8 @@ struct Layer { * The last layer has no j_ma: its stream goes to the final norm, which feeds the lm_head, not * a quantiser. */ G4Junction j_am{}, j_ma{}; + /* the DFlash drafter's tap: this layer's output into its column slice of `dflash_src` */ + rad_op op_tap = 0; }; struct Model { @@ -1133,6 +1136,17 @@ struct Model { bool fuse = false; bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */ int64_t ar_rows = 0; /* ...in a step of at most this many rows (G4Junction::ar_rows) */ + + /* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), declared only when the container + * carries one and the deployment speculates: the trunk layers it taps, the [max_tok, taps x + * n_embd] plane the taps fill, the block and its own KV group. */ + enum { MAX_TAPS = gemma4::Dflash1::MAX_TAPS }; + int n_taps = 0; + int tap_layer[MAX_TAPS] = {}; + rad_buf b_dfsrc = 0; + gemma4::Dflash1 df{}; + rad_kvgroup kv_draft = 0; + bool have_df = false; }; static Model g_model[MAX_RANKS]; @@ -1255,6 +1269,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + /* ---- the DFlash drafter's taps, declared when the container carries z-lab's drafter and this + * serve speculates. The plane is declared here and written by an op declared inside each layer + * it taps, because the buffer planner's liveness is declaration order (the tap below). */ + { + const int n = gemma4::Dflash1::taps(meta, ctx, g.n_layer, m.tap_layer, Model::MAX_TAPS); + if (n < 0) return n; + m.n_taps = n; + if (n > 0) + m.b_dfsrc = decl_b(b, nm.f("dflash_src"), g.act_dtype, + {g.max_tok, (int64_t)n * g.n_embd}); + } + /* ---- the vocabulary edges. Gemma 4 ties the head to the embedding. */ const char* pre = "model.language_model.layers"; RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.language_model.embed_tokens.weight"))); @@ -1276,14 +1302,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* The embedding is scaled by sqrt(n_embd) at the lookup, not in the table (as in llama.cpp's * build_inp_embd and HF's ScaledWordEmbedding), so the plain table stays tied to the head. * Without it the token signal in the residual stream would be ~73x too small. The scale is - * sqrt(n_embd) rounded to bf16, as the reference multiplies by it (embed_scale: 73.5 + * sqrt(n_embd) rounded to bf16, as the reference multiplies by it (gemma4::embed_scale: 73.5 * at 5376, not 73.32). The first norm hides the difference but the residual stream does not, * and the DFlash drafter was trained on the reference's hidden states. */ m.op_embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), RAD_INT("vocab_offset", g.vocab_off), - RAD_F64("mult", embed_scale(g.n_embd))), + RAD_F64("mult", gemma4::embed_scale(g.n_embd))), RAD_WEIGHTS(m.w_tok)), {}, {m.b_x}); if (g.world > 1) @@ -1329,6 +1355,19 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(lay.w_scalar)), {mw.x}, {mw.x}); + + /* The tap: a row copy of the layer's output (after the scalar, HF's hidden_states[l + 1]) + * into the column slice the tap owns. It is declared here, in the layer it is issued + * after, because the buffer planner's liveness is declaration order. A tap declared once + * after the trunk made `dflash_src` look born at its end and free to share with what every + * layer writes, which on arch/gemma4 cost 98% of the drafts with the reply still fluent. */ + for (int t = 0; t < m.n_taps; ++t) + if (m.tap_layer[t] == (int)l && !lay.op_tap) + lay.op_tap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_dfsrc}); } /* ---- the junctions, declared once every layer exists (j_ma reads the next layer's gain). @@ -1414,10 +1453,31 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(rad_drafter_shared_kv(b, kHeadPosOffset)); } - /* ---- the vision tower, its weight groups past the trunk's and the head's (counted even when - * the head is not declared, so the groups do not move with max_spec). */ + /* ---- or z-lab's DFlash drafter, past the trunk's layers. It is declared last because + * declaration order is the buffer planner's liveness. It reads the taps the trunk copied into + * `dflash_src` and the trunk's tied table, as its embedding and, where the container holds no + * 8-bit copy, as its head. */ + if (m.n_taps > 0) { + gemma4::Dflash1::Trunk t{}; + t.n_taps = m.n_taps; + t.escale = gemma4::embed_scale(g.n_embd); + t.src = m.b_dfsrc; + t.w_tok = m.w_tok; + t.tok_src = nm.ckpt("model.language_model.embed_tokens.weight"); + t.base_layer = (int)m.n_main; + RAD_ARCH_TRY(gemma4::Dflash1::declare_drafter(b, meta, ctx, nm, g, t, &m.df, &m.kv_draft)); + m.have_df = true; + } + + /* ---- the vision tower, its weight groups past the trunk's and the draft model's: the + * assistant's layers and its exit, or the DFlash drafter's layers. They are counted even when + * the draft model is not declared, so the groups do not move with max_spec. */ { - const int64_t head_groups = has_assistant(meta) ? meta_text_geti(meta, "num_hidden_layers", 0, "draft.") + 1 : 0; + int64_t head_groups = 0; + if (has_assistant(meta)) + head_groups = meta_text_geti(meta, "num_hidden_layers", 0, "draft.") + 1; + else if (gemma4::dflash_kind(meta) == 1) + head_groups = rad_meta_geti(meta, "draft.num_hidden_layers", 0); RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups), "model.", "gemma4_bf16")); } @@ -1448,12 +1508,19 @@ static void step(RadCtx* c, const RadBatch* batch) { m.vis.step(c, batch); return; } - /* A draft pass runs only the head. The trunk already left its final-normed hidden state in - * `h`, which the head's history pass gathers from. */ + /* A draft pass runs only the draft model. The trunk already left its final-normed hidden state + * in `h`, which the assistant's history pass gathers from, and its taps in `dflash_src`, which + * the DFlash drafter's context pass reads. */ if (batch->draft_pass != 0) { + if (m.have_df) { + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(c, batch); + return; + } if (!m.have_head) { rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " - "container carries no `draft.` assistant, or declare ran at max_spec 0"); + "container carries no `draft.` assistant or DFlash drafter, or declare " + "ran at max_spec 0"); return; } m.head.step(c, batch); @@ -1483,13 +1550,20 @@ static void step(RadCtx* c, const RadBatch* batch) { if (m.fuse && !last) { /* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */ l.j_ma.step(c, T, far); - continue; + } else { + /* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after + * the mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The + * checkpoint's values (0.03-0.99) are trained weights that rescale the residual toward + * O(1). */ + RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar), + brows(m.b_x, batch->n_tok)); } - /* The per-layer scalar, `cur = cur * scalar` over the residual stream, applied after the - * mlp add, as vLLM's `hidden_states = hidden_states * self.layer_scalar`. The checkpoint's - * values (0.03-0.99) are trained weights that rescale the residual toward O(1). */ - RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar), - brows(m.b_x, batch->n_tok)); + /* The drafter's taps, once the layer's output is whole. Either way that is after the + * scalar, since the junction applies it to the stream it writes. */ + for (int t = 0; t < m.n_taps && l.op_tap; ++t) + if (m.tap_layer[t] == (int)li) + RAD_ISSUE(c, l.op_tap, brows(m.b_x, T), + bcol(m.b_dfsrc, (int64_t)t * m.g.n_embd, m.g.n_embd, T)); } RAD_ISSUE(c, m.op_final, @@ -1513,13 +1587,16 @@ static void step(RadCtx* c, const RadBatch* batch) { const RadChatFormat* chat_format(const RadModelMeta*) { return gemma4_chat_format(); } /* The default draft depth for `--num-speculative-tokens auto`. A serial head's depth is an - * operating point, not a trained depth: every depth runs. */ + * operating point, not a trained depth: every depth runs. A DFlash drafter's is the block it was + * trained at, fixed. */ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; if (has_assistant(meta)) { out->draft_depth = kHeadDepth; out->draft_depth_fixed = 0; } + /* A DFlash drafter names the block it was trained at, and only that (rad_gemma4_dflash.h). */ + (void)gemma4::dflash_probe(meta, out); /* The tower's pooling window, so a pass size the core picks itself is whole windows. */ if (Gemma4Vision::present(meta)) { const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0); @@ -1530,9 +1607,10 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { #ifndef RAD_ARCH_NO_EXPORTS RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0", - "Gemma 4 dense (text and images), w4a8 from its bf16 or its CT-INT4 (QAT) release: " - "sliding-window and proportional-RoPE global attention over a plain RMSNorm stream " - "with GELU feed-forward, per-layer scalar scaling and soft-capped logits") + "Gemma 4 dense (text and images), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) " + "release: sliding-window and proportional-RoPE global attention over a plain " + "RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped " + "logits; Google's assistant head or z-lab's DFlash drafter") RAD_ARCH_CHAT_FORMAT(gemma4_bf16) RAD_ARCH_PROBE(gemma4_bf16) #endif diff --git a/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe b/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe new file mode 100644 index 00000000..2276fb5f --- /dev/null +++ b/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe @@ -0,0 +1,56 @@ +# gemma4-31b-dense-bf16-q8-df.recipe -- Gemma 4 31B dense (text) from Google's bf16 checkpoint at +# eight bits (Q8_0's grid as libr4d serves it), with z-lab's DFlash drafter at eight bits too. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \ +# --set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-q8-df.rad +# +# radiance serve gemma4-31b-dense-q8-df.rad --num-speculative-tokens auto ... +# +# Q8_0 is int8 codes, symmetric, one f16 scale per block, the scale amax / 127: exactly `codes=i8 +# scale=f16 clamp=sym` and the default absmax rule. What differs is the block. GGML's is 32 values +# and libr4d's int8 GEMMs read 128 (their group is compiled in, C_EQ("group", 128)), so a block +# here is four of Q8_0's. Every rule below is that one grid: +# +# the trunk's linears gemm_nt_q at w8a8: the w4a8 grid at twice the radix, read by the same +# fused junctions (rmsnorm_quant_i8, qkv_norm_rope, gelu_mul_quant_i8), so +# the step takes the int4 container's launches with twice its weight bytes +# the drafter's linears gemm_nt_q at w8a8 too, rmsnorm_quant_i8 folding each residual add, norm +# and quantiser (arch/common/rad_gemma4_dflash.h) +# the drafter's head its own int8 copy of the tied table, gemm_nt_q at w8a8 +# +# The activations are int8 with a scale per row, not per 32-block (llama.cpp's q8_1): the w8a8 +# grid's quantiser is per row, the one the int4 container already reads. libr4d's other int8 grid, +# i8a8, takes a scale per (row, 128) and is closer still to Q8_0 x Q8_1, but nothing in libr4d +# fuses a norm into its quantiser yet, so it would cost five launches per junction at decode. +# +# The trunk's lm_head is int8 as well, as Q8_0 makes `output.weight`: logits_gemm_i8 reads it +# against the bf16 hidden state (no activation quantiser), with a bf16 scale per row and 128 +# columns. It is the trunk's verifier, so drop the line to keep it bf16, at 352 MB per rank more +# read each step. The embedding table stays bf16: it is read one row per token, and it is the +# drafter's table too. +# +# ~33 GiB: the int8 trunk's linears (~28 GiB), the bf16 table and its int8 head (2 GiB), the +# vision tower, the drafter (1.4 GiB) and its head's copy (0.7 GiB). At tp 4, ~8 GiB per rank on a +# 32 GiB R9700. +# +# This starts from bf16 for the reason gemma4-31b-dense-bf16-w4a8-df.recipe gives: the drafter +# reads the trunk's hidden states and was trained beside the bf16 trunk. + +blk.*.attn_q.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.attn_k.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.attn_v.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.attn_o.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.ffn_down.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=f16 clamp=sym + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +dflash.fc.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.attn_q.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.attn_k.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.attn_v.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.attn_output.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.blk.*.ffn_down.weight rtn codes=i8 group=128 scale=f16 clamp=sym +dflash.draft_head.weight rtn codes=i8 group=128 scale=f16 clamp=sym diff --git a/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe b/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe new file mode 100644 index 00000000..ba60ebea --- /dev/null +++ b/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe @@ -0,0 +1,56 @@ +# gemma4-31b-dense-bf16-w4a8-df.recipe -- Gemma 4 31B dense (text) from Google's bf16 checkpoint +# at w4a8, as gemma4-31b-dense-bf16-w4a8.recipe makes it, with z-lab's DFlash drafter merged in +# place of the assistant head. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe \ +# --set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-w4a8-df.rad +# +# radiance serve gemma4-31b-dense-w4a8-df.rad --num-speculative-tokens auto ... +# +# The drafter (z-lab/gemma-4-31B-it-DFlash) is five Qwen3-shaped layers of 5376 (64 heads / 8 kv +# x 128, ffn 10752) and an fc over the trunk's residual stream at layers 1 12 23 35 46 57: 1.5 B +# parameters, 3.1 GB at bf16. It denoises a block of 16 in one pass and proposes 15 tokens; z-lab +# measures 4.2-8.6 accepted per step on B300 at bf16, against the assistant head's ~2. The plugin's +# probe names that depth, so rad-convert declares at it and `--num-speculative-tokens auto` serves +# it; any other depth is refused by name. +# +# This starts from bf16, not from the QAT release. The drafter reads the trunk's hidden states at +# six layers and was trained beside the bf16 trunk, so the trunk that serves it should be as close +# to that one as four bits allow: rule=search, as in the plain bf16 recipe, which measured the +# assistant head accepting 0.71/0.62/0.63 of its k=3 drafts from this grid against 0.49/0.50/0.44 +# from the QAT one. +# +# The trunk's lm_head is int8, as keptn42's container has it: logits_gemm_i8 reads it against the +# bf16 hidden state (no activation quantiser), with a bf16 scale per row and 128 columns. At tp 4 a +# rank's slice of the 262144 x 5376 table is 704 MB in bf16, a sixth of everything a verify step +# reads at int4, and 352 MB at int8. It is the trunk's verifier; drop the line to keep it bf16. +# +# ~20 GiB: the int4 trunk's linears (~14 GiB), the bf16 table and its int8 head (2 GiB), the +# vision tower, the drafter at block fp8 (1.4 GiB) and its head's block-fp8 copy (0.7 GiB). + +blk.*.attn_q.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_k.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_v.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_o.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_down.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_gate_up.weight rtn codes=i4 group=128 scale=f16 rule=search + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +# The DFlash drafter's seven linears: block fp8, read at fp8a8 against an E4M3 activation (the +# drafter only proposes; the trunk verifies). All seven take one grid, because one quantised +# activation feeds several of them, and the plugin checks it. +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The drafter's head: the target's tied table again under a name of its own, block fp8, which the +# draft head reads instead of the bf16 table. That halves the widest read on the draft path (704 MB +# per rank at tp 4 in bf16), for half the table's bytes again. Drafts are verified, so this changes +# what is proposed, never what is accepted. +dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 diff --git a/deploy/compose/gemma4-31b-q8-df.yaml b/deploy/compose/gemma4-31b-q8-df.yaml new file mode 100644 index 00000000..3ee8ce9c --- /dev/null +++ b/deploy/compose/gemma4-31b-q8-df.yaml @@ -0,0 +1,16 @@ +# Gemma 4 31B-it at eight bits: the trunk's linears and its lm_head int8 on Q8_0's grid (symmetric, +# an f16 scale a block of 128 columns, absmax / 127), int8 activations, z-lab's DFlash drafter +# merged in at int8 too (15 tokens a pass), and the vision tower. Converted with +# data/recipes/gemma4-31b-dense-bf16-q8-df.recipe. Sampling defaults are the checkpoint's +# generation_config; thinking is switched per request (chat_template_kwargs). +# 33 GiB of weights: ~16.5 GiB per card at --tp 2, ~8 GiB at --tp 4 on four cards. +name: radiance-gemma4-31b-q8-df +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-gemma4-31b-q8-df + command: > + --model /models/gemma4-31b-dense-q8-df.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 65536 --kv-cache-dtype fp8 + --num-speculative-tokens auto --max-num-batched-tokens 2048 --temp 1.0 --top-p 0.95 --top-k 64 diff --git a/deploy/compose/gemma4-31b-w4a8-df.yaml b/deploy/compose/gemma4-31b-w4a8-df.yaml new file mode 100644 index 00000000..f9e322da --- /dev/null +++ b/deploy/compose/gemma4-31b-w4a8-df.yaml @@ -0,0 +1,17 @@ +# Gemma 4 31B-it: int4 trunk (round-to-nearest with a scale search, from the bf16 checkpoint) with +# int8 activations, z-lab's DFlash drafter merged in (block fp8, 15 tokens a pass), and the vision +# tower. Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe. Sampling defaults are the +# checkpoint's generation_config; thinking is switched per request (chat_template_kwargs). +# The drafter serves one depth, the block it was trained at (16, so 15 drafts); `auto` asks the +# container. On four cards use --tp 4. --draft-window adaptive lets each sequence verify only as +# much of the block as its own acceptance pays for, worth it at higher --max-num-seqs. +name: radiance-gemma4-31b-w4a8-df +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-gemma4-31b-w4a8-df + command: > + --model /models/gemma4-31b-dense-w4a8-df.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 65536 --kv-cache-dtype fp8 + --num-speculative-tokens auto --max-num-batched-tokens 2048 --temp 1.0 --top-p 0.95 --top-k 64 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 7cddba35..7df0b1f7 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -17,7 +17,7 @@ plugin claims. | `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Text only, bf16 KV | | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | -| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release, served w4a8. Optional draft head: Google's assistant (`rad-convert --draft-model`), with no cache of its own (`rad_drafter_shared_kv`) | +| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`) | | `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) | | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 | | `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 | @@ -637,8 +637,10 @@ Traps: `arch/gemma4` serves a container converted from Google's bf16 checkpoint (`Gemma4ForConditionalGeneration` or `Gemma4ForCausalLM`), the recipe choosing what is fp8: gemma-4-26B-A4B-it, and the dense sizes without per-layer embeddings. The CT-INT4 31B release is -`arch/gemma4_bf16`'s. A z-lab DFlash drafter is merged at convert time (`--draft-model`); the -recipes are `data/recipes/gemma4-26b-a4b-df*.recipe`. The reference is transformers' +`arch/gemma4_bf16`'s, and so is the 31B quantised from bf16 at w4a8 or w8a8, which takes the same +DFlash drafter (see "The 31B" below). A z-lab DFlash drafter is merged at convert time +(`--draft-model`); the recipes are `data/recipes/gemma4-26b-a4b-df*.recipe` and +`data/recipes/gemma4-31b-dense-bf16-*-df.recipe`. The reference is transformers' `modeling_gemma4`. ``` @@ -705,13 +707,43 @@ and cannot show it, so time a prefill without it. A step that runs whole (every step) puts the dense arm on the second lane instead, beside the routed arm, with its reductions on lane 0. The startup notes say which form each step takes. -**The draft head in fp8.** The drafter's head is the widest read on the draft path: the target's +**The draft head in 8 bits.** The drafter's head is the widest read on the draft path: the target's bf16 table, 352 MiB per rank at tp 4, every draft pass. A container converted with the line -`dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the three `-df` recipes -carry it) stores a block-fp8 copy under that name, and the head reads it at fp8a8 instead: half -the bytes, for 176 MiB per rank more. Drafts are verified, so the coarser logits can change what is -proposed, never what is accepted; `draft_n_accepted` shows whether they propose worse. Without the -copy the head reads the bf16 table, and the startup note names which head is in use. +`dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the 26B `-df` recipes and +the 31B w4a8 one carry it) stores a block-fp8 copy under that name, and the head reads it at fp8a8 +instead: half the bytes, for 176 MiB per rank more. With `codes=i8 group=128 scale=f16 clamp=sym` +(the 31B Q8 recipe) the copy is int8, read at w8a8. Drafts are verified, so the coarser logits can +change what is proposed, never what is accepted; `draft_n_accepted` shows whether they propose +worse. Without the copy the head reads the bf16 table, and the startup note names which head is in +use. + +**The drafter's linears on either 8-bit grid.** The seven linears (fc and six per layer) are on the +E4M3 grid (block fp8 or MXFP4, at fp8a8 / mxfp4a8 over an E4M3 activation with a scale per (row, +128)) or on the int8 one (`codes=i8 group=128 scale=f16`, at w8a8 over `quant_act_i8`'s activation +with a scale per row, and `rmsnorm_quant_i8` folding each residual add, norm and quantiser as +`rmsnorm_quant_fp8` does on the other). `fc`'s encoding picks the grid. One quantised activation +feeds several linears, so a linear on the other grid is refused by name. The gate_up|silu|quant +fold (`gemm_nt_q_gated`) is fp8a8 only, so the int8 grid keeps `silu_mul` and the quantiser, one +launch per layer more. Above 64 rows the w8a8 GEMM is the tiled one, which takes N in 256s; the +31B drafter's k and v are 256 rows per rank at tp 4, the narrowest that still fits. + +**The 31B.** z-lab's `gemma-4-31B-it-DFlash` is the same block at 5376 (64 heads / 8 kv x 128, +ffn 10752, five layers, taps 1 12 23 35 46 57 of 60, block 16), and `arch/gemma4_bf16` serves it +beside its w4a8 or w8a8 trunk. The taps are copies of the stream each tapped layer's junction +leaves (`rmsnorm_quant_i8` adds the feed-forward and applies the layer scalar, so the copy is +`hidden_states[l + 1]`), declared in the layer they copy for the liveness reason below. The drafter +is declared after the trunk, its layers at 60..64 on a KV group of its own. Its 64 heads over 8 kv +heads are gqa 8 at every rank count, and libr4d's head-128 attention (the one the 26B's gqa-4 +drafter runs on, causal over a window or not) takes 4 queries per kv head at a block of 16. So the +cache holds each kv head twice, written by a head-wide copy of k and v after the projection, and +the attention runs at gqa 4. It is exact: query head q reads a copy of kv head q / 8. A container carries the +assistant head or the drafter under `draft.`, not both. The recipes are +`gemma4-31b-dense-bf16-w4a8-df.recipe` (int4 trunk, int8 lm_head, block-fp8 drafter, ~20 GiB) +and `gemma4-31b-dense-bf16-q8-df.recipe` (Q8_0's grid at libr4d's group of 128 for the trunk, its +lm_head and the drafter, ~33 GiB). Both start from bf16, because the drafter reads the trunk's +hidden states and was trained beside the bf16 trunk. Both plugins scale the embedding by +sqrt(hidden) rounded to bf16, as the reference's embedding module does (73.5 at 5376, not 73.32), +and the drafter reads it through the same scale. **The 31B's junctions at four ranks.** At two ranks every junction carries the all-reduce in front of it (`ar_rmsnorm_quant_i8`). At four it does too, at decode heights. libr4d's diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 9522f5f0..13d38a5a 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -4677,6 +4677,481 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ for (const auto& o : off.ops) CHECK(o.op != "ar_rmsnorm_quant_i8"); } +/* ============ gemma4 31B + DFlash: z-lab's block drafter on the w4a8 / w8a8 trunk ============ */ + +namespace { + +/* The twelve-layer 31B above with z-lab/gemma-4-31B-it-DFlash merged under `draft.` as + * `rad-convert --draft-model` writes it: its own geometry (5376 wide, 64 heads / 8 kv x 128, ffn + * 10752, five layers -- four sliding over 2048, one full -- at block 16), reading the trunk at three + * of the fixture's twelve layers where the real one reads six of sixty. */ +std::vector g431df_keys() { + std::vector k(std::begin(k_gem4_keys), std::end(k_gem4_keys)); + for (const char* s : { "draft.architectures", "draft.num_hidden_layers", "draft.head_dim", + "draft.num_attention_heads", "draft.num_key_value_heads", + "draft.intermediate_size", "draft.rms_norm_eps", "draft.rope_theta", + "draft.hidden_size", "draft.vocab_size", "draft.block_size", + "draft.dflash_config.target_layer_ids", + "draft.dflash_config.mask_token_id", "draft.layer_types", + "draft.sliding_window" }) + k.push_back(s); + return k; +} +std::vector g431df_vals() { + std::vector v(std::begin(k_gem4_vals), std::end(k_gem4_vals)); + for (const char* s : { "[\"DFlashDraftModel\"]", "5", "128", "64", "8", "10752", "1e-06", + "1000000", "5376", "262144", "16", "[1, 5, 9]", "4", + "[\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", " + "\"sliding_attention\", \"full_attention\"]", + "2048" }) + v.push_back(s); + return v; +} + +struct G431Df { + std::vector keys = g431df_keys(), vals = g431df_vals(); + RadModelMeta meta() const { + RadModelMeta m = gemma4_meta(); + m.n_kv = (int)keys.size(); + m.kv_key = keys.data(); + m.kv_val = vals.data(); + return m; + } +}; + +/* The trunk at w4a8 as the -df recipe makes it, the drafter's linears on one 8-bit grid -- the + * E4M3 one (block fp8) or the int8 one (w8a8) -- and, with `head`, the table's 8-bit copy in the + * same grid. The drafter's keys come FIRST: the fake answers the first key a name contains, and + * `attn_q.` is in `dflash.blk.0.attn_q.weight` too. */ +void g431df_encs(RadBuilder& b, bool i8, bool head) { + const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); + const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); + const RadEncoding q8 = rad_enc_affine(RAD_I8, RAD_F16, 1, 128); + const RadEncoding& d = i8 ? q8 : fp8; + b.encs = { { "dflash.fc.", d }, { "dflash.blk.", d } }; + if (head) b.encs.push_back({ "dflash.draft_head.", d }); + for (const char* s : { "attn_q.", "attn_k.", "attn_v.", "attn_o.", "ffn_gate_up.", "ffn_down." }) + b.encs.push_back({ s, w4 }); +} + +int count_writes_to(const RadBuilder& b, const RadCtx& c, int buf) { + int n = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (o && std::find(o->writes.begin(), o->writes.end(), (rad_buf)buf) != o->writes.end()) + ++n; + } + return n; +} + +rad_kvgroup kv_named(const RadBuilder& b, const char* name) { + for (size_t i = 0; i < b.kv_groups.size(); ++i) + if (b.kv_groups[i].name == name) return (rad_kvgroup)(i + 1); + return 0; +} + +} /* namespace */ + +/* The 31B declares z-lab's drafter as a block drafter past its trunk: five layers at 12..16 on a KV + * group of their own, the trunk's taps in one plane, its embedding read at the reference's scale, + * and the depth the block was trained at, the only one it serves, which probe names for rad-convert + * and `--num-speculative-tokens auto`. Without speculation none of it is declared. */ +TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { + G431Df f; + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df_encs(b, false, false); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + CHECK_EQ(b.drafter_name, std::string("dflash")); + CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_BLOCK); + CHECK_EQ(b.drafter.depth, 15); + CHECK_EQ((int)b.drafter.block, 16); + CHECK_EQ(b.drafter.mask_token, 4); + CHECK(!b.drafter_shared); + CHECK_EQ(b.drafter.proposal, (rad_buf)buf_named(b, "dflash_tokens")); + + /* its own cache, the five layers past the trunk's twelve bound to it */ + const rad_kvgroup kvd = kv_named(b, "kv_draft"); + REQUIRE(kvd != 0); + CHECK_EQ((int)b.kv_groups[kvd - 1].d.kind, (int)RAD_KV_FULL); + CHECK_EQ(b.kv_groups[kvd - 1].d.head_dim, 128); + /* 64 heads over 8 kv heads is gqa 8, and libr4d's head-128 attention takes 4 queries per kv + * head at a block of 16: the cache holds each kv head twice, the projections stay 8 heads + * wide, and every attention and cache write of the drafter sees 16 kv heads at gqa 4. */ + CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 16); + CHECK_EQ(b.bufs[buf_named(b, "df_k") - 1].d.shape[1], 8 * 128); + CHECK_EQ(b.bufs[buf_named(b, "df_k4") - 1].d.shape[1], 16 * 128); + { + int n_attn = 0, n_store = 0; + for (const auto& o : b.ops) { + if (o.op == "attn_paged" && pint(&o, "head_dim") == 128) { + ++n_attn; + CHECK_EQ(pint(&o, "gqa"), 4); + CHECK_EQ(pint(&o, "n_head"), 64); + } + if (o.op == "kv_store" && pint(&o, "head_dim") == 128) { + ++n_store; + CHECK_EQ(pint(&o, "n_head_kv"), 16); + } + } + CHECK_EQ(n_attn, 2); /* the sliding layers' and the full layer's */ + CHECK_EQ(n_store, 2); /* the context pass's and the query pass's */ + } + std::vector bound; + for (const auto& [layer, g] : b.binds) if (g == kvd) bound.push_back(layer); + CHECK(bound == (std::vector{ 12, 13, 14, 15, 16 })); + + /* three taps of 5376 a row */ + const int src = buf_named(b, "dflash_src"); + REQUIRE(src > 0); + CHECK_EQ(b.bufs[src - 1].d.shape[1], 3 * 5376); + + /* the drafter embeds the anchor and the masks through the TRUNK's table at 73.5 */ + const RecOp* te = find_op(b, "embed_lookup", 0); + const RecOp* de = find_op(b, "embed_lookup", 1); + REQUIRE(te != nullptr && de != nullptr); + CHECK(te->w == de->w); + CHECK_NEAR(pflt(de, "mult"), 73.5, 1e-9); + + /* one name map a declared weight: a COPY map repeated is refused by the real builder */ + std::map maps; + for (const auto& mp : b.maps) if (mp.mode == RAD_MAP_COPY) ++maps[mp.declared]; + for (const auto& [name, n] : maps) CHECK_EQ(name + " x" + std::to_string(n), name + " x1"); + + RadArchProbe p{}; + CHECK_OK(gemma4_bf16::probe(&meta, &p)); + CHECK_EQ(p.draft_depth, 15); + CHECK_EQ(p.draft_depth_fixed, 1); + + /* no speculation: no drafter, no taps */ + RadBuilder b0; + g431df_encs(b0, false, false); + RadBuildCtx c0 = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b0, &meta, &c0)); + CHECK_EQ(buf_named(b0, "dflash_src"), 0); + CHECK(b0.drafter_name.empty()); + + /* and a depth the block was not trained at is refused by name */ + RadBuilder b4; + g431df_encs(b4, false, false); + RadBuildCtx c4 = build_ctx(); + c4.max_spec = 4; + CHECK_EQ(gemma4_bf16::declare(&b4, &meta, &c4), RAD_E_UNSUPPORTED); +} + +/* The taps on the w4a8 trunk are declared in the layer they copy, so `dflash_src` is live from its + * first write on (the arch/gemma4 trap that cost 98% of the drafts). Each is issued once its + * layer's output is whole, after the junction that adds the feed-forward, applies the layer scalar + * and quantises the next layer's input, so the copy is HF's hidden_states[l + 1]. */ +TEST(gemma4_31b_dflash_taps_the_stream_the_junction_leaves) { + G431Df f; + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df_encs(b, false, false); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + const int src = buf_named(b, "dflash_src"), gu = buf_named(b, "gate_up"); + REQUIRE(src > 0 && gu > 0); + int first_src = -1, last_gu = -1; + for (size_t i = 0; i < b.ops.size(); ++i) + for (rad_buf w : b.ops[i].writes) { + if ((int)w == src && first_src < 0) first_src = (int)i; + if ((int)w == gu) last_gu = (int)i; + } + REQUIRE(first_src >= 0 && last_gu >= 0); + CHECK(first_src < last_gu); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + CHECK_EQ(count_writes_to(b, c, src), 3); + int t = 0; + for (size_t i = 0; i < c.issues.size(); ++i) { + const RecOp* o = b.op_of(c.issues[i].op); + if (!o || std::find(o->writes.begin(), o->writes.end(), (rad_buf)src) == o->writes.end()) + continue; + REQUIRE(i > 0); + CHECK_EQ(b.op_of(c.issues[i - 1].op)->op, std::string("rmsnorm_quant_i8")); + REQUIRE(c.issues[i].opd.size() == 2); + CHECK_EQ(c.issues[i].opd[1].handle, (uint32_t)src); + CHECK_EQ(c.issues[i].opd[1].offset, (int64_t)t * 5376); /* the tap's own column slice */ + ++t; + } +} + +/* A draft pass runs only the drafter: the context pass from the taps into the drafter's cache, + * the query pass over the block to the proposal. */ +TEST(gemma4_31b_dflash_passes_run_the_drafter_and_nothing_else) { + G431Df f; + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df_encs(b, false, true); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + const int src = buf_named(b, "dflash_src"), tok = buf_named(b, "dflash_tokens"); + + for (int pass : { -1, 1 }) { + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + batch.draft_pass = pass; + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + REQUIRE(!ops.empty()); + CHECK_EQ(count_issued(ops, "gelu_mul_quant_i8"), 0); /* no trunk layer */ + CHECK_EQ(count_issued(ops, "kv_store"), 5); + if (pass < 0) { + CHECK_EQ(ops.front(), std::string("quant_act_fp8")); + const RecOp* o = b.op_of(c.issues.front().op); + CHECK(std::find(o->reads.begin(), o->reads.end(), (rad_buf)src) != o->reads.end()); + CHECK_EQ(count_issued(ops, "attn_paged"), 0); + } else { + CHECK_EQ(ops.front(), std::string("embed_lookup")); + CHECK_EQ(count_issued(ops, "attn_paged"), 5); + CHECK_EQ(count_writes_to(b, c, tok), 1); + } + } +} + +/* Q8, the drafter on the int8 grid. Every linear is gemm_nt_q at w8a8 over quant_act_i8's per-row + * activation, each residual add, norm and quantiser is one rmsnorm_quant_i8 (ten per draft pass, as + * rmsnorm_quant_fp8 is on the E4M3 grid), and nothing on the E4M3 grid is declared. The + * gate_up|silu|quant fold is fp8a8 only, so the int8 grid keeps silu_mul and the quantiser. Where + * rmsnorm_quant_i8 is refused, the chain runs. */ +TEST(gemma4_31b_dflash_on_the_int8_grid_reads_w8a8_and_folds_its_norms) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int refuse = 0; refuse < 2; ++refuse) { + RadBuilder b; + g431df_encs(b, true, true); + if (refuse) b.refuse.insert("rmsnorm_quant_i8"); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + CHECK(b.bufs[buf_named(b, "df_hq") - 1].d.dtype == RAD_I8); + CHECK_EQ(b.bufs[buf_named(b, "df_hs") - 1].d.shape[1], 1); /* a scale a row */ + const RecWeight* wq = find_w(b, "dflash.blk.0.attn_q.weight"); + const RecWeight* sq = find_w(b, "dflash.blk.0.attn_q.scale"); + REQUIRE(wq != nullptr && sq != nullptr); + CHECK(wq->d.dtype == RAD_I8 && sq->d.dtype == RAD_F16); + CHECK_EQ(sq->d.shape[1], 5376 / 128); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + batch.draft_pass = 1; + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + CHECK_EQ(count_issued(ops, "rmsnorm_quant_i8"), refuse ? 0 : 10); + CHECK_EQ(count_issued(ops, "add"), refuse ? 10 : 1); + /* the attention output's and the gated product's a layer, x's twice a layer in the chain, + * and the head's copy of the gathered rows */ + CHECK_EQ(count_issued(ops, "quant_act_i8"), (refuse ? 20 : 10) + 1); + CHECK_EQ(count_issued(ops, "silu_mul"), 5); + for (const char* fp : { "quant_act_fp8", "rmsnorm_quant_fp8", "gemm_nt_q_gated" }) + CHECK_EQ(count_issued(ops, fp), 0); + int q = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o || o->op != "gemm_nt_q") continue; + CHECK_EQ(pstr(o, "dtype"), std::string("w8a8")); + ++q; + } + CHECK_EQ(q, 5 * 6 + 1); /* six linears a layer, and the head */ + if (refuse) continue; + + /* the fused form's operands: rmsnorm_quant_i8's eight, the delta and the residual past + * layer 0, and no junction gains */ + const uint32_t x = (uint32_t)buf_named(b, "df_x"), h = (uint32_t)buf_named(b, "df_h"); + int k = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o || o->op != "rmsnorm_quant_i8") continue; + REQUIRE(i.opd.size() == 8); + CHECK_EQ(i.opd[0].handle, k++ == 0 ? x : h); + CHECK_EQ((int)i.opd[6].kind, (int)RAD_OPK_NONE); + CHECK_EQ((int)i.opd[7].kind, (int)RAD_OPK_NONE); + } + + /* and the context pass: two quantisers, eleven w8a8 GEMMs (fc, then k and v a layer) */ + RadCtx cc; cc.b = &b; cc.rank = 0; cc.world = 1; + RadBatch cb = decode_batch(); + cb.draft_pass = -1; + cc.batch = &cb; + gemma4_bf16::step(&cc, &cb); + CHECK(cc.step_fail.empty()); + const std::vector cops = issued_ops(b, cc); + CHECK_EQ(count_issued(cops, "quant_act_i8"), 2); + CHECK_EQ(count_issued(cops, "gemm_nt_q"), 11); + } +} + +/* The drafter's linears take one grid: one quantised activation feeds several of them, so an fc on + * the E4M3 grid and layers on the int8 one would read pairs nothing writes. Refused by name. */ +TEST(gemma4_31b_dflash_refuses_linears_on_two_grids) { + G431Df f; + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df_encs(b, true, false); + b.encs[0].second = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); /* fc on E4M3 */ + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_E_DTYPE); +} + +/* The head's int8 copy: where the container holds one, the gathered rows are quantised a row at a + * time and read by gemm_nt_q at w8a8 over it; otherwise the head reads the tied bf16 table. */ +TEST(gemma4_31b_dflash_head_reads_the_int8_copy_where_the_container_holds_one) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int copy = 0; copy < 2; ++copy) { + RadBuilder b; + g431df_encs(b, true, copy == 1); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + const int dlog = buf_named(b, "df_dlog"); + const RecOp* head = nullptr; + for (const auto& o : b.ops) + if (o.resolved && + std::find(o.writes.begin(), o.writes.end(), (rad_buf)dlog) != o.writes.end()) + head = &o; + REQUIRE(head != nullptr); + CHECK_EQ(head->op, std::string(copy ? "gemm_nt_q" : "gemm_nt")); + if (!copy) continue; + CHECK_EQ(pstr(head, "dtype"), std::string("w8a8")); + const int selq = buf_named(b, "df_selq"), sels = buf_named(b, "df_sels"); + REQUIRE(selq > 0 && sels > 0); + CHECK(b.bufs[selq - 1].d.dtype == RAD_I8); + CHECK_EQ(b.bufs[sels - 1].d.shape[1], 1); + const RecWeight* hs = find_w(b, "dflash.draft_head.scale"); + REQUIRE(hs != nullptr); + CHECK(hs->d.dtype == RAD_F16); + CHECK_EQ(hs->d.shape[0], 262144); + CHECK_EQ(hs->d.shape[1], 5376 / 128); + } +} + +/* At four ranks, as the R9700 box serves it: the drafter's heads split 16 / 2 kv per rank, its head + * is vocab-sharded with the trunk's and merged by pair_argmax, and both 8-bit grids declare (the + * int8 one's prefill GEMM takes N in 256s, which a 256-row k and v still are). */ +TEST(gemma4_31b_dflash_at_four_ranks) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int i8 = 0; i8 < 2; ++i8) { + RadBuilder b; + g431df_encs(b, i8 == 1, true); + RadBuildCtx ctx = build_ctx(1, 4); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + const rad_kvgroup kvd = kv_named(b, "kv_draft"); + REQUIRE(kvd != 0); + /* two kv heads a rank, each held twice: gqa 4 over the cache (the declares test says why) */ + CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 4); + CHECK_EQ(b.bufs[buf_named(b, "df_q") - 1].d.shape[1], 16 * 128); + CHECK_EQ(b.bufs[buf_named(b, "df_k") - 1].d.shape[1], 2 * 128); + CHECK(buf_named(b, "df_dgath") > 0); + for (const auto& o : b.ops) + if (o.op == "attn_paged" && pint(&o, "head_dim") == 128) CHECK_EQ(pint(&o, "gqa"), 4); + + RadCtx c; c.b = &b; c.rank = 1; c.world = 4; + RadBatch batch = decode_batch(); + batch.draft_pass = 1; + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + CHECK_EQ(count_issued(ops, "pair_argmax"), 1); + CHECK_EQ(count_issued(ops, "all_gather"), 1); + /* the embedding's reduction and two a layer */ + CHECK_EQ(count_issued(ops, "all_reduce"), 1 + 2 * 5); + /* k and v into the cache's layout: two heads, two copies each, a layer */ + CHECK_EQ(count_issued(ops, "cast"), 5 * 2 * (2 * 2)); + } +} + +/* Where no loaded library declares libr4d's fused ops (a CPU-only build, where rad-convert and the + * host backend run), asking for one is an error, so the 31B with its DFlash drafter asks first and + * declares the chains: the junctions, the attention prologue, the gated quantiser, the folded + * all-reduce, and the drafter's fused norm on the int8 grid. It declares on both grids, at one rank + * and two, and never asks for an undeclared op. */ +TEST(gemma4_31b_without_libr4d_declares_the_chains_and_asks_for_no_undeclared_op) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int i8 = 0; i8 < 2; ++i8) + for (int world : { 1, 2 }) { + RadBuilder b; + g431df_encs(b, i8 == 1, true); + for (const char* op : { "rmsnorm_quant_i8", "gelu_mul_quant_i8", "qkv_norm_rope", + "ar_rmsnorm_quant_i8" }) + b.undeclared.insert(op); + RadBuildCtx ctx = build_ctx(0, world); + ctx.max_spec = 15; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + CHECK(b.asked_undeclared.empty()); + RadCtx c; c.b = &b; c.rank = 0; c.world = world; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + CHECK_EQ(count_issued(ops, "rmsnorm_p"), 12); /* the prologue's value norm, unfused */ + CHECK_EQ(count_issued(ops, "gelu_mul"), 12); + batch.draft_pass = 1; + RadCtx d; d.b = &b; d.rank = 0; d.world = world; d.batch = &batch; + gemma4_bf16::step(&d, &batch); + CHECK(d.step_fail.empty()); + CHECK_EQ(count_issued(issued_ops(b, d), "rmsnorm_quant_i8"), 0); + } +} + +/* The 31B's engine steps lint clean with z-lab's drafter, on both of the drafter's grids, at one, + * two and four ranks (the first and last rank of each): a decode step, a mixed step, a prefill + * chunk tall enough to run as two slices, and a verify step with the drafter's context and query + * passes behind it. The lint holds the buffers each pass reads to what an earlier op of the step + * wrote and the planner kept alive, across the passes, so a tap whose plane the planner let another + * buffer share, or a drafter buffer read after its arena slot was reused, fails here. Eight + * sequences at a block of 16 is 128 query rows, past every fused band the drafter has. */ +TEST(gemma4_31b_steps_lint_clean_with_a_dflash_drafter) { + G431Df f; + const RadModelMeta meta = f.meta(); + for (int i8 = 0; i8 < 2; ++i8) + for (int world : { 1, 2, 4 }) + for (int rank : { 0, world - 1 }) { + if (world == 1 && rank > 0) continue; + RadBuilder b; + g431df_encs(b, i8 == 1, true); + RadBuildCtx ctx = build_ctx(rank, world); + ctx.max_tok = 2048; + ctx.max_spec = 15; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + REQUIRE_EQ((int)b.drafter.kind, (int)RAD_DRAFT_BLOCK); + for (const auto& k : { kit(b, { 1, 1, 1 }, {}), kit(b, { 8, 1 }, { 5 }), + kit(b, {}, { 1500 }) }) { + const auto v = run_passes(b, gemma4_bf16::step, { k.get() }, rank, world); + CHECK_PASSES(b, v); + } + for (int64_t n_seq : { 2, 8 }) { + const auto ver = kit(b, std::vector((size_t)n_seq, 16), {}); + const auto ctxp = context_pass(b, *ver); + const auto qry = query_pass(b, n_seq, 16, 15); + const auto v = run_passes(b, gemma4_bf16::step, + { ver.get(), ctxp.get(), qry.get() }, rank, world); + CHECK_PASSES(b, v); + } + } +} + /* ==================================================================== the step lint, checked */ namespace { From 04e54803873108eeb1fbb17fc81ec10c8223dc01 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 14:54:47 -0500 Subject: [PATCH 120/152] arch, data/recipes, libr4d: the 31B's prefill overlap, q|k|v as one linear, RedHatAI's DFlash2, its fc split The 31B's prefill steps of 1024 rows or more run as two slices with each slice's all-reduces beside the other's compute; q, k and v as one linear where the container holds them so; the 31B serves RedHatAI's DFlash2 speculator; DFlash2's fc projection is split over the ranks, bit for bit. Squashed from: - arch/gemma4_bf16: a prefill step in two slices, each slice's reductions on the second lane - arch/gemma4_bf16: q, k and v as one linear where the container holds them so - data/recipes: the 31B -df recipes make q, k and v one linear (blk.*.attn_qkv) - arch/gemma4: the 31B serves RedHatAI's DFlash2 speculator (gemma-4-31B-it-speculator.dflash2) - libr4d: gemm_nt_q takes split_n, and all_gather lands rows at a wider output pitch - arch/common: DFlash2's fc split over the ranks as windows of block-aligned rows, bit for bit Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_arch.h | 35 +- arch/common/rad_block_dflash2.h | 140 +++- arch/common/rad_fp8.h | 36 +- arch/common/rad_gemma4_dflash.h | 48 ++ arch/gemma4_bf16/gemma4_bf16.cpp | 726 ++++++++++++++++-- .../gemma4-31b-dense-bf16-q8-df.recipe | 7 +- .../gemma4-31b-dense-bf16-w4a8-df.recipe | 10 +- .../gemma4-31b-dense-bf16-w4a8-df2.recipe | 46 ++ docs/ARCHITECTURES.md | 45 +- docs/GUIDE.md | 1 + docs/OPS.md | 17 +- libavx/avx_registry.cpp | 4 +- libr4d/r4d.h | 6 +- libr4d/r4d_ar_entry.hip | 61 +- libr4d/r4d_ar_gather_2rank.hip | 63 +- libr4d/r4d_ar_gather_Nrank.hip | 74 +- libr4d/r4d_gemm_fp8a8.hip | 34 +- libr4d/r4d_rows.cpp | 3 + libr4d/r4d_selftest.cpp | 171 ++++- libref/ref_registry.cpp | 4 +- tests/arch_test.cpp | 473 +++++++++++- 21 files changed, 1805 insertions(+), 199 deletions(-) create mode 100644 data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index 01918a7f..690da3bd 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -1262,17 +1262,30 @@ inline const RadKVGroupBatch* kv_batch(const RadBatch* b, rad_kvgroup group) { * layer, head, feed-forward, norm and rotary geometry of the container's `draft.` config, split * over the ranks, and a plain RMS norm. A drafter is a second model, so nothing is defaulted: a * config that does not describe one is refused, naming `what` (spec §17). So is a vocabulary - * other than the target's, since a drafter reads the target's embedding and lm_head. */ + * other than the target's, since a drafter reads the target's embedding and lm_head. + * + * The layer config sits at the top of `draft.` in z-lab's and SpecForge's checkpoints, and under + * `draft.transformer_layer_config.` in vLLM's speculators format (RedHatAI's DFlash2 drafters), + * whose top level holds the speculator's own keys instead (drafter_layer_prefix). */ +inline const char* drafter_layer_prefix(const RadModelMeta* meta) { + if (rad_meta_geti(meta, "draft.num_hidden_layers", 0) > 0) return "draft."; + if (rad_meta_geti(meta, "draft.transformer_layer_config.num_hidden_layers", 0) > 0) + return "draft.transformer_layer_config."; + return "draft."; +} inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, const char* what) { dg = target; - dg.n_layer = rad_meta_geti(meta, "draft.num_hidden_layers", 0); - dg.head_dim = rad_meta_geti(meta, "draft.head_dim", 0); - dg.n_head_all = rad_meta_geti(meta, "draft.num_attention_heads", 0); - dg.n_head_kv_all = rad_meta_geti(meta, "draft.num_key_value_heads", 0); - dg.n_ff_all = rad_meta_geti(meta, "draft.intermediate_size", 0); - dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0); - dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta", - rad_meta_getf(meta, "draft.rope_theta", 0.0)); + const char* pre = drafter_layer_prefix(meta); + char key[160]; + auto k = [&](const char* name) { std::snprintf(key, sizeof key, "%s%s", pre, name); return key; }; + dg.n_layer = rad_meta_geti(meta, k("num_hidden_layers"), 0); + dg.head_dim = rad_meta_geti(meta, k("head_dim"), 0); + dg.n_head_all = rad_meta_geti(meta, k("num_attention_heads"), 0); + dg.n_head_kv_all = rad_meta_geti(meta, k("num_key_value_heads"), 0); + dg.n_ff_all = rad_meta_geti(meta, k("intermediate_size"), 0); + dg.eps = (float)rad_meta_getf(meta, k("rms_norm_eps"), 0.0); + const double th = rad_meta_getf(meta, k("rope_theta"), 0.0); + dg.theta = (float)rad_meta_getf(meta, k("rope_parameters.rope_theta"), th); dg.wadd = dg.wadd_qk = 0.0f; if (dg.n_layer <= 0 || dg.head_dim <= 0 || dg.n_head_all <= 0 || dg.n_head_kv_all <= 0 || dg.n_ff_all <= 0 || !(dg.eps > 0.0f) || !(dg.theta > 0.0f)) { @@ -1283,11 +1296,11 @@ inline int drafter_geom(Geom& dg, const Geom& target, const RadModelMeta* meta, (long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta); return RAD_E_INVAL; } - RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim)); + RAD_ARCH_TRY(yarn_from(dg, meta, pre, dg.head_dim)); RAD_ARCH_TRY(divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)); RAD_ARCH_TRY(divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)); RAD_ARCH_TRY(divide_or_fail(dg.n_ff_all, dg.world, "draft intermediate_size", &dg.n_ff)); - const long long dvocab = rad_meta_geti(meta, "draft.vocab_size", dg.n_vocab_all); + const long long dvocab = rad_meta_geti(meta, k("vocab_size"), dg.n_vocab_all); if (dvocab != dg.n_vocab_all) { fprintf(stderr, "radiance: the %s drafter claims a %lld-token vocabulary and the target " "has %lld; it reads the target's embedding and lm_head\n", diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h index e41ca366..800f5790 100644 --- a/arch/common/rad_block_dflash2.h +++ b/arch/common/rad_block_dflash2.h @@ -69,10 +69,21 @@ * q/kv and gate_up shard by row, o and down by column with an all-reduce: ten collectives per * draft pass, each 5120 * block * 2 bytes (80 KiB at block 8), below the lossy wire's floor. * + * fc [n_embd, n_taps*n_embd], 262 MiB in fp8 at Qwen3.8's width, read whole by the + * context pass every step. Split by rows over the ranks and all-gathered, and + * kept bit for bit. Each rank hands over an equal share of c's columns + * (n_embd / world) and computes the fewest whole 128-row scale blocks that cover + * it (the 31B at tp 4: 1344 columns a rank inside 11 blocks, 1408 rows, against + * 42 blocks whole), a row span of the one stored weight + * (DenseFP8::declare_slice), so no reconvert. The GEMM takes its K split from + * the whole width (OPS.md's `split_n`), so each output is summed as the unsplit + * fc sums it, and the all-gather reads each rank's window out of its wider rows + * (an input pitch) and writes c whole. A GEMM cannot write a column slice (the + * narrow fp8 kernel's store is tight), which is why the windows are the + * gather's to cut. One rank, or an fc off block fp8, keeps it whole. + * * Replicated: * - * fc [n_embd, n_taps*n_embd], 262 MiB. Column-sharding would halve it but add an - * all-reduce to the prefill path. * conv weights projection and base kernel, 26 MiB a layer. The convolution spans the whole * replicated hidden row, so every rank needs every coefficient. * codebooks [n_vocab, 256], 127 MiB each, gathered by global token id. Only 128 rows are @@ -127,6 +138,10 @@ struct Dflash2 { /* the context pass */ rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */ rad_buf c = 0; /* [max_tok, n_embd] fc's output, then normed in place */ + /* [max_tok, fc_rows] the block-aligned rows of a split fc this rank computes, whose + * fc_share-wide window at fc_off is gathered into c. The block declares it (only when it + * splits fc); leave it 0. */ + rad_buf cpart = 0; /* K and V are separate buffers because of the per-head k norm: `rmsnorm` takes one row * pitch, and K heads inside a fused [K|V] row are head_dim apart within a token but * 2*kv_dim apart between tokens. libr4d refuses such an operand (libr4d/r4d_model.cpp, @@ -191,10 +206,17 @@ struct Dflash2 { * MXFP4 accepts ~1% fewer tokens per step than fp8 and saves ~1.5 ms of a ~34 ms step. * Quantisation can only change acceptance, since every draft is verified. */ DenseFP8 w_fc{}; + /* fc split by rows (see SHARDING): w_fc is this rank's fc_rows block-aligned rows, holding its + * fc_share output columns at row fc_off. fc_rows 0: w_fc is the whole fc, replicated. */ + int64_t fc_share = 0, fc_rows = 0, fc_off = 0; rad_weight w_hnorm = 0, w_norm = 0; rad_weight w_selp = 0, w_pred = 0, w_succ = 0; rad_weight w_tok = 0; /* the target's embedding table */ - rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit copy of the target's lm_head */ + rad_weight w_dh = 0, w_dhs = 0; /* the 2-bit (or 8-bit) copy of the target's lm_head */ + /* The copy is int8 with an f16 scale per (row, 128 of K) where the recipe made it so (the + * 31B's: the head read at w8a8, so the selector sees the candidates an 8-bit head ranks), and + * the 2-bit grid otherwise. Set by declare from the copy's encoding. */ + bool head_i8 = false; /* per-layer weights */ rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; @@ -209,6 +231,7 @@ struct Dflash2 { /* context-pass ops */ rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0; + rad_op op_cgath = 0; /* the split fc's all-gather */ rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; /* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration @@ -284,9 +307,38 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co if (qrows <= 0 || srows <= 0) return RAD_E_INVAL; /* ---------------------------------------------------------------- model-scope weights */ - RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, cfg.n_taps * g.n_embd, - RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(), - { nm.ckpt("%s.fc.weight", ck) })); + { + const int64_t K = cfg.n_taps * g.n_embd; + const char* fwn = nm.f("dflash.fc.weight"); + RAD_ARCH_TRY(map_linear(b, fwn, { nm.ckpt("%s.fc.weight", ck) })); + /* Split only block fp8 (an MXFP4 GEMM's K split is its own), into equal shares of whole + * 16-byte words (the gather's unit). */ + RadEncoding fe{}; + const RadEncPlane* fsc = nullptr; + const bool fp8 = weight_enc(b, fwn, &fe) && rad_enc_is(&fe, "affine") && fe.n_planes == 2 && + !fe.transform[0] && fe.plane[0].dtype == RAD_F8E4M3 && + (fsc = rad_enc_plane(&fe, "scale")) && fsc->block[0] == RAD_FP8_BLOCK && + fsc->block[1] == RAD_FP8_BLOCK; + const int64_t share = (g.world > 1 && g.n_embd % RAD_FP8_BLOCK == 0 && + g.n_embd % g.world == 0 && (g.n_embd / g.world) % 8 == 0) + ? g.n_embd / g.world : 0; + if (fp8 && share > 0) { + const int64_t B = RAD_FP8_BLOCK; + const int64_t lo = share * g.rank / B * B; + const int64_t hi = (share * (g.rank + 1) + B - 1) / B * B; + fc_share = share; + fc_rows = hi - lo; + fc_off = share * g.rank - lo; + RAD_ARCH_TRY(w_fc.declare_slice(b, nm, nm.f("dflash.fc"), fwn, lo, hi, K, + RAD_ACCESS_PER_TOKEN, grp_model())); + if (!w.cpart) + w.cpart = decl_b(b, nm.f("df_cpart"), g.act_dtype, { g.max_tok, fc_rows }); + } else { + RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dflash.fc"), g.n_embd, K, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model(), { nm.ckpt("%s.fc.weight", ck) }, + {}, true)); + } + } RAD_ARCH_TRY(map_copy(b, nm.f("dflash.hidden_norm.weight"), nm.ckpt("%s.hidden_norm.weight", ck))); RAD_ARCH_TRY(map_copy(b, nm.f("dflash.norm.weight"), nm.ckpt("%s.norm.weight", ck))); RAD_ARCH_TRY(map_copy(b, nm.f("dflash.sel_proj.weight"), @@ -321,10 +373,28 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co const int dh_split = dh_shard ? RAD_SHARD_ROW : RAD_SHARD_NONE; const char* dhn = nm.f("dflash.draft_head.weight"); RAD_ARCH_TRY(map_copy(b, dhn, ck_lm)); - w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd}, - RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); - w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16, - {head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); + /* The 8-bit form: int8 codes, one f16 scale per (row, 128 of K), symmetric, which gemm_nt_q + * reads at w8a8 against the same quant_act_i8 activation (without its asum). */ + { + RadEncoding e{}; + const RadEncPlane* sc = nullptr; + head_i8 = weight_enc(b, dhn, &e) && rad_enc_is(&e, "affine") && e.n_planes == 2 && + !e.transform[0] && e.plane[0].dtype == RAD_I8 && e.plane[0].block[1] == 1 && + (sc = rad_enc_plane(&e, "scale")) && sc->dtype == RAD_F16 && + sc->block[0] == 1 && sc->block[1] == DF_W2_GROUP; + } + if (head_i8) { + w_dh = decl_view(b, dhn, nullptr, "codes", RAD_I8, {head_rows(g), g.n_embd}, + RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); + w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale", RAD_F16, + {head_rows(g), g.n_embd / DF_W2_GROUP}, RAD_ACCESS_PER_TOKEN, dh_split, + grp_model()); + } else { + w_dh = decl_view(b, dhn, nullptr, "codes", RAD_U2, {head_rows(g), g.n_embd}, + RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); + w_dhs = decl_view(b, nm.f("dflash.draft_head.scale"), dhn, "scale,zero", RAD_F16, + {head_rows(g), g.n_embd}, RAD_ACCESS_PER_TOKEN, dh_split, grp_model()); + } if (!w_dh || !w_dhs) return RAD_E_INVAL; /* ---------------------------------------------------------------- per-layer weights */ @@ -422,7 +492,21 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.src}, {w.srcq, w.srcs}); - op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c}); + if (fc_rows) { + /* The split (SHARDING above): this rank's block-aligned rows into `cpart`, its window of + * them gathered into `c`. The GEMM takes its K split from the whole width. The gather + * rides the trunk's all-reduce instance (the same numel bound, so the same instance). */ + op_cfc = w_fc.gemm(b, crows, fc_rows, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.cpart}, + g.n_embd); + op_cgath = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_INT("numel", crows * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("row", fc_share)), + RAD_NOWEIGHTS), + {w.cpart}, {w.c}); + } else { + op_cfc = w_fc.gemm(b, crows, g.n_embd, cfg.n_taps * g.n_embd, {w.srcq, w.srcs}, {w.c}); + } /* In place, like the per-head q/k norms below: a row's scale is computed before the row is * written. */ op_cnorm = rw(b, RAD_OP(b, "rmsnorm", @@ -643,12 +727,19 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_INT("group", DF_W2_GROUP), RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), {w.sel_h}, {w.dq, w.ds, w.dsum}); - op_dlogits = rw(b, RAD_OP(b, "gemm_nt_q", - RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)), - RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP), - RAD_STR("dtype", "w2a8")), - RAD_WEIGHTS(w_dh, w_dhs)), - {w.dq, w.ds, w.dsum}, {w.dlog}); + op_dlogits = head_i8 + ? rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)), + RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP), + RAD_STR("dtype", "w8a8")), + RAD_WEIGHTS(w_dh, w_dhs)), + {w.dq, w.ds}, {w.dlog}) + : rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", head_rows(g)), + RAD_INT("K", g.n_embd), RAD_INT("group", DF_W2_GROUP), + RAD_STR("dtype", "w2a8")), + RAD_WEIGHTS(w_dh, w_dhs)), + {w.dq, w.ds, w.dsum}, {w.dlog}); /* Sharded, the top-R runs over this rank's plane, reports global ids and also writes the pair * plane the gather moves. Replicated, `vocab_off` is omitted: an optional parameter present * with value 0 is a different declaration from an absent one. */ @@ -731,8 +822,14 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const { /* As wide as the prefill chunk, one launch per op (the fp8a8 pair covers every M). */ RAD_ISSUE_N(c, op_qsrc, T, brows(w.src, T), brows(w.srcq, T), brows(w.srcs, T)); - RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), - brows(w.c, T), RAD_NONE, w_fc.bref()); + if (fc_rows) { + RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), + brows(w.cpart, T), RAD_NONE, w_fc.bref()); + RAD_ISSUE_N(c, op_cgath, T, bcol(w.cpart, fc_off, fc_share, T), brows(w.c, T)); + } else { + RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), RAD_W(w_fc.s), + brows(w.c, T), RAD_NONE, w_fc.bref()); + } RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.c, T)); RAD_ISSUE_N(c, op_qc, T, brows(w.c, T), brows(w.cq, T), brows(w.cs, T)); @@ -843,9 +940,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { * whole. */ RAD_ISSUE_N(c, op_dquant, S, brows(w.sel_h, S), brows(w.dq, S), brows(w.ds, S), RAD_B(w.dsum)); /* The trailing operand is mxfp4's optional reference, absent here. Operands are positional, - * so an absent optional one is RAD_NONE, not a shorter list. */ + * so an absent optional one is RAD_NONE, not a shorter list. The 8-bit head is symmetric and + * takes no asum. */ RAD_ISSUE_N(c, op_dlogits, S, brows(w.dq, S), brows(w.ds, S), RAD_W(w_dh), RAD_W(w_dhs), - brows(w.dlog, S), RAD_B(w.dsum), RAD_NONE); + brows(w.dlog, S), head_i8 ? RAD_NONE : RAD_B(w.dsum), RAD_NONE); /* RAD_NONE fills the unused `pairs` slot. Sharded, this rank's top-R are only candidates and * the merge overwrites `cand`/`unary`. */ if (op_dmerge) { diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index c756bdf3..b8ba87cd 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -1521,15 +1521,47 @@ struct DenseFP8 { int access, int shard, RadWeightGroup grp, std::initializer_list src, std::initializer_list row_parts = {}, bool mapped = false); - /* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. */ + /* Rows [lo, hi) of the stored block-fp8 weight `src_wn` (codes and scale plane; mapped by + * whoever declared it), read as an [hi - lo, K] weight named ``: a row slice that need + * not be a rank's even share, and may be the same rows on every rank. Whole 128-row blocks, + * so each slice's codes and scales are the stored ones. fp8 only: an MXFP4 linear's GEMM + * splits K by its own rule. A slice issued with `gemm(..., split_n)` set to the stored width + * computes the stored linear's outputs to the bit. */ + int declare_slice(RadBuilder* b, Names& nm, const char* base, const char* src_wn, int64_t lo, + int64_t hi, int64_t K, int access, RadWeightGroup grp) { + if (lo < 0 || hi <= lo || lo % RAD_FP8_BLOCK || hi % RAD_FP8_BLOCK || K % RAD_FP8_BLOCK) + return RAD_E_INVAL; + mx = false; + ref = 0; + const char* wn = nm.f("%s.weight", base); + const char* sn = nm.f("%s.scale", base); + const bool own = !std::strcmp(wn, src_wn); /* the stored weight's own name */ + w = decl_view(b, wn, own ? nullptr : src_wn, "codes", RAD_F8E4M3, { hi - lo, K }, access, + RAD_SHARD_ROW, grp); + s = decl_view(b, sn, src_wn, "scale", RAD_BF16, { fp8_blocks(hi - lo), fp8_blocks(K) }, + access, RAD_SHARD_ROW, grp); + if (!w || !s) return RAD_E_INVAL; + RAD_ARCH_TRY(rad_weight_shard_span(b, w, lo, hi)); + return rad_weight_shard_span(b, s, lo / RAD_FP8_BLOCK, hi / RAD_FP8_BLOCK); + } + /* `gemm_nt_q` over this weight, `fp8a8` or `mxfp4a8` as it was declared, ranged M 1..hi. + * `split_n`, when set, is the stored width a row slice takes its K split from (docs/OPS.md). */ rad_op gemm(RadBuilder* b, int64_t hi, int64_t N, int64_t K, - std::initializer_list reads, std::initializer_list writes) const { + std::initializer_list reads, std::initializer_list writes, + int64_t split_n = 0) const { if (mx) return rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")), RAD_WEIGHTS(w, s, ref)), reads, writes); + if (split_n > 0) + return rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8"), + RAD_INT("split_n", split_n)), + RAD_WEIGHTS(w, s)), + reads, writes); return rw(b, RAD_OP(b, "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8")), diff --git a/arch/common/rad_gemma4_dflash.h b/arch/common/rad_gemma4_dflash.h index 0340e1a2..d962ac9b 100644 --- a/arch/common/rad_gemma4_dflash.h +++ b/arch/common/rad_gemma4_dflash.h @@ -159,6 +159,54 @@ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) { return true; } +/* The same for a DFlash2 drafter, for a plugin that serves rad_block_dflash2.h (the 31B's): its + * anchor predicts nothing either, so the depth is the trained block less one, 7 for RedHatAI's + * gemma-4-31B-it-speculator.dflash2 (block_size 8). */ +inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) { + if (dflash_kind(meta) != 2) return false; + const long long bs = dflash_block(meta); + if (bs <= 1) return false; + out->draft_depth = (int)(bs - 1); + out->draft_depth_fixed = 1; + return true; +} + +/* A DFlash2 drafter's trunk taps, as the layers whose output the trunk copies into `dflash_src`. + * + * vLLM's speculators format names them `aux_hidden_state_layer_ids`, counted as vLLM captures + * them: id i is the residual stream entering layer i, so the output of layer i - 1 (id n_layer, + * which `--include-last-layer` emits, is the last layer's output). z-lab's `target_layer_ids` count + * the layer whose output is taken. RedHatAI's 1 17 29 47 59 are this trunk's layers 0 16 28 46 + * 58. Id 0 would be the embedding, which no layer outputs, and is refused. */ +inline int dflash2_taps(const RadModelMeta* meta, const RadBuildCtx* ctx, int64_t n_layer, int* out, + int max) { + if (ctx->max_spec <= 0 || dflash_kind(meta) != 2) return 0; + const char* aux = rad_meta_gets(meta, "draft.aux_hidden_state_layer_ids", nullptr); + int n = 0; + if (aux) { + int raw[16]; + const int m = parse_layer_ids(aux, n_layer + 1, raw, max < 16 ? max : 16); + for (int i = 0; i < m; ++i) { + if (raw[i] < 1) { + fprintf(stderr, "radiance: gemma4: the DFlash2 drafter taps aux hidden state 0, the " + "embedding, which no trunk layer outputs\n"); + return RAD_E_UNSUPPORTED; + } + out[n++] = raw[i] - 1; + } + } else { + const char* ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr); + if (!ids) ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr); + n = parse_layer_ids(ids, n_layer, out, max); + } + if (n <= 0) { + fprintf(stderr, "radiance: gemma4: the DFlash2 drafter names no trunk layer this model has; " + "it is paired with a different target\n"); + return RAD_E_UNSUPPORTED; + } + return n; +} + /* ============================================================== the block */ struct Dflash1 { diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index ebdd95a0..578afa43 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -18,8 +18,10 @@ #include #include #include +#include #include +#include #include #include #include @@ -117,8 +119,24 @@ struct G4Linear { void step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const; /* the GEMM alone, for a caller that wrote the int8 pair itself (a fused norm + quantiser) */ void gemm(RadCtx* c, rad_buf y, int64_t T) const; + /* The same two over rows [r0, r0 + n) of the step: a slice of the prefill overlap. The + * quantiser and the GEMM are a row at a time above their bands, so a slice's rows are the + * whole step's (see "the prefill overlap" below). */ + void step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const; + void gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const; }; +/* A weight on the w4a8 / w8a8 grid: i4 or i8 codes with an f16 scale per [1 x 128], the encoding + * gemm_nt_q reads against quant_act_i8's pair. */ +static bool g4_grid_w4(const RadEncoding& enc) { + const RadEncPlane* sc = rad_enc_plane(&enc, "scale"); + const uint32_t cdt = enc.n_planes > 0 ? enc.plane[0].dtype : 0; + return rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] && + (cdt == RAD_I4 || cdt == RAD_I8) && enc.plane[0].block[1] == 1 && + sc && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == 128; +} + +/* An empty `src` means the caller made the weight's name map (a probe asked it first). */ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, std::initializer_list src, int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, @@ -126,10 +144,10 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char std::initializer_list row_parts, const G4Linear* in_from) { N = n_out; K = n_in; - if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; + if (N <= 0 || K <= 0) return RAD_E_INVAL; const char* wn = nm.f("%s.weight", base); - if (src.size() == 1) RAD_ARCH_TRY(map_copy(b, wn, *src.begin())); - else RAD_ARCH_TRY(map_concat(b, wn, src, 0)); + if (src.size() == 1) RAD_ARCH_TRY(map_copy(b, wn, *src.begin())); + else if (src.size() > 1) RAD_ARCH_TRY(map_concat(b, wn, src, 0)); RadEncoding enc{}; const bool known = weight_enc(b, wn, &enc); /* A builder with no model behind it (a test, a synthetic tool) answers RAD_E_NOTFOUND, and @@ -153,16 +171,11 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char /* A w4 weight: i4 codes and an f16 scale per [1 x 128]. gemm_nt_q at w4a8 reads an int8 * activation and an f32 per-row scale, so a quantiser over the bf16 plane `a` writes the int8 * pair (q8, s8). The codes + scale layout is the same as w4a16's, so containers serve - * unchanged. */ - const RadEncPlane* sc = rad_enc_plane(&enc, "scale"); - /* An 8-bit weight on the same grid (i8 codes, f16 scale per [1 x 128]): gemm_nt_q at w8a8 - * reads the same int8 activation and per-row scale as w4a8, so the quantiser is shared. A - * recipe uses it for linears int4 hurts (attention, down_proj). */ + * unchanged. An 8-bit weight on the same grid (i8 codes, f16 scale per [1 x 128]): gemm_nt_q + * at w8a8 reads the same int8 activation and per-row scale as w4a8, so the quantiser is + * shared. A recipe uses it for linears int4 hurts (attention, down_proj). */ const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0; - const bool w4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] && - (cdt == RAD_I4 || cdt == RAD_I8) && enc.plane[0].block[1] == 1 && - sc && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == 128; - if (w4) { + if (known && g4_grid_w4(enc)) { if (N % 16 || K % 128) { fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a w4 weight takes rows in " "16s and K in whole 128-column scale groups.\n", base, @@ -225,9 +238,27 @@ inline void G4Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const { brows(y, T), RAD_NONE, RAD_NONE); } +inline void G4Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const { + if (!quant) { + RAD_ISSUE_N(c, op, n, brow_slice(a, r0, n, K), RAD_W(w), brow_slice(y, r0, n, N)); + return; + } + if (!shared_in) + RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K), + brow_slice(s8, r0, n, 1), RAD_NONE); + gemm_rows(c, y, r0, n); +} + +inline void G4Linear::gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const { + RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, 1), RAD_W(w), RAD_W(ws), + brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE); +} + /* ---- one attention block, parameterised by class. */ struct Gemma4Attn { - struct Wire { rad_buf x = 0, h = 0, q = 0, k = 0, v = 0, attn = 0; }; + /* `qkv` is the fused projection's row, [max_tok, q | k | v], declared by the first layer of its + * class that has one (the model's slot passed to declare). */ + struct Wire { rad_buf x = 0, h = 0, q = 0, k = 0, v = 0, attn = 0, qkv = 0; }; Wire w{}; Geom g{}; @@ -237,23 +268,46 @@ struct Gemma4Attn { rad_weight w_norm = 0, w_qn = 0, w_kn = 0, w_post = 0; /* the norms (always bf16) */ G4Linear ln_q{}, ln_k{}, ln_v{}, ln_o{}; /* the GEMM weights (bf16 or w4a8) */ + /* q, k and v as one linear, where the container holds them so (blk.N.attn_qkv): one GEMM a + * layer instead of three. q, k and v are then column slices of `w.qkv`. */ + G4Linear ln_qkv{}; + bool fused = false; rad_op op_norm = 0, op_vn = 0, op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0, op_attn = 0, op_kv = 0, op_post = 0, op_ar = 0, op_add = 0; /* the five prologue ops (v norm, q norm, k norm, two rotaries) as one, where it resolves */ rad_op op_qnr = 0; + /* Fused only: attention reading q where it lies in the row (attn_paged_qrow), where it resolves + * to the kernel attn_paged would take anyway; else the copy of q into its own rows (`cast`) that + * a step of more than one row issues ahead of attn_paged. Without qkv_norm_rope the copies of + * k and v too, ahead of the unfused prologue, which reads them dense. */ + rad_op op_attn_row = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0; + + /* The linear whose int8 pair a junction writes, and whether every projection reads it. */ + const G4Linear& ln_in() const { return fused ? ln_qkv : ln_q; } + bool reads_pair() const { + return fused ? ln_qkv.quant + : ln_q.quant && ln_k.shared_in && (!cls.has_v || ln_v.shared_in); + } int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, - rad_kvgroup group, const Wire& wire, const char* pre); + rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot); /* `entry_done`: a junction op already wrote this block's quantised input (ln_q's pair). * `tail_fused`: the caller issues the post-norm and the add as a junction op. */ void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, bool ar_fused = false) const; + /* step()'s parts, for the prefill overlap: the projections over rows [r0, r0 + n) from the + * pair a junction wrote, everything between the projections and o_proj over the whole step + * (it reads every row's keys), and o_proj over rows [r0, r0 + n). */ + void project(RadCtx* c, int64_t r0, int64_t n) const; + void attend(RadCtx* c, const RadBatch* batch) const; + void out_proj(RadCtx* c, int64_t r0, int64_t n) const; }; int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, - rad_kvgroup group, const Wire& wire, const char* pre) { + rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot) { g = geom; cls = cgeo; layer = l; kv = group; w = wire; const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); + const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0); /* The norms: always bf16 (no rule matches them), name map first. */ RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l))); @@ -271,18 +325,50 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const w_post = decl_w(b, nm.f("blk.%d.attn_post_norm.weight", l), RAD_BF16, {g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); - /* The GEMM weights: bf16 or w4a8, probed by G4Linear. */ - RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), - { nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l) }, - qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q)); - const G4Linear* qin = &ln_q; /* k and v read q's int8 pair */ - RAD_ARCH_TRY(ln_k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), - { nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l) }, - kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.k, {}, qin)); - if (cls.has_v) - RAD_ARCH_TRY(ln_v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), - { nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l) }, - kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.v, {}, qin)); + /* The GEMM weights: bf16 or w4a8, probed by G4Linear. + * + * q, k and v are one linear, `blk.N.attn_qkv` (q | k | v, or q | k on a k_eq_v class), where + * the weight is on the w4a8 / w8a8 grid: a recipe that names it (rad-convert answers the + * probe from the recipe) or a container converted with one. Each rank takes its slice of each + * part, so the row holds this rank's q, k and v heads. The rows are q's, k's and v's rows, and + * the grid's groups never cross a row, so the codes are the three linears' codes (libr4d's + * skinny GEMM picks its K split from N, so on a card k and v may round differently in the last + * bit). One GEMM a layer reads the three weights in one pass where three paid the skinny GEMM's + * fixed cost each: on the R9700 at decode (--profile-ops, tp 4) q, k and v take 17 + 13.5 + + * 13.5 us and a 4096-row GEMM of the same K 25 us. A container that holds the three apart, or + * bf16 weights, keeps three linears reading q's int8 pair. */ + const char* q_src = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l); + const char* k_src = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l); + const char* v_src = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l); + const char* qkv_wn = nm.f("blk.%d.attn_qkv.weight", l); + if (cls.has_v) RAD_ARCH_TRY(map_concat(b, qkv_wn, { q_src, k_src, v_src })); + else RAD_ARCH_TRY(map_concat(b, qkv_wn, { q_src, k_src })); + { + RadEncoding e{}; + fused = weight_enc(b, qkv_wn, &e) && g4_grid_w4(e); + } + if (fused) { + if (!qkv_slot) return RAD_E_INVAL; + if (!*qkv_slot) + *qkv_slot = decl_b(b, nm.f(cls.has_v ? "attn_qkvs" : "attn_qkvg"), g.act_dtype, + {g.max_tok, qkvd}); + w.qkv = *qkv_slot; + if (cls.has_v) + RAD_ARCH_TRY(ln_qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), {}, qkvd, g.n_embd, + RAD_SHARD_ROW, grp_layer(l), w.h, w.qkv, {qd, kvd, kvd})); + else + RAD_ARCH_TRY(ln_qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), {}, qkvd, g.n_embd, + RAD_SHARD_ROW, grp_layer(l), w.h, w.qkv, {qd, kvd})); + } else { + RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), { q_src }, + qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q)); + const G4Linear* qin = &ln_q; /* k and v read q's int8 pair */ + RAD_ARCH_TRY(ln_k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), { k_src }, + kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.k, {}, qin)); + if (cls.has_v) + RAD_ARCH_TRY(ln_v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), { v_src }, + kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.v, {}, qin)); + } RAD_ARCH_TRY(ln_o.declare(b, nm, g, nm.f("blk.%d.attn_o", l), { nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l) }, g.n_embd, qd, RAD_SHARD_COL, grp_layer(l), w.attn, w.h)); @@ -340,22 +426,27 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const /* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM * use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim), * so 1.0 is passed explicitly. */ - op_attn = rw(b, RAD_OP(b, "attn_paged", - RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), - RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), RAD_INT("window", cls.window), - RAD_INT("n_head", cls.n_head), RAD_INT("block_size", RAD_KV_BLOCK), - RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), - RAD_F64("scale", 1.0), - RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS), - {w.q}, {w.attn}); + auto attn = [&](const char* op, std::initializer_list rd) { + return rw(b, RAD_OP(b, op, + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), + RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_F64("scale", 1.0), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + rd, {w.attn}); + }; /* The prologue as one op: libr4d's `qkv_norm_rope` is rmsnorm_p + rmsnorm + rmsnorm + rope + * rope over the three projections, byte-identical, one workgroup per (token, head). Declared * beside the unfused five and used only where it resolves; a multi-component or YaRN rotary * keeps the five, as does an engine whose libraries do not declare it (CPU-only), where asking - * for it would stop the declare. */ - if (!g.rope_mc && g.yarn.factor == 0.0f && rad_op_declared(b, "qkv_norm_rope")) { + * for it would stop the declare. It reads q, k and v at their own row pitches, so on a fused + * layer it works in place on the row's column slices. */ + auto decl_qnr = [&]() { + if (g.rope_mc || g.yarn.factor != 0.0f || !rad_op_declared(b, "qkv_norm_rope")) return; op_qnr = RAD_OP(b, "qkv_norm_rope", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", cls.n_head_kv), @@ -367,17 +458,60 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_qn, w_kn)); /* A k_eq_v class derives v from the raw k: v is written, never read. */ - op_qnr = cls.has_v ? rw(b, op_qnr, {w.q, w.k, w.v}, {w.q, w.k, w.v}) - : rw(b, op_qnr, {w.q, w.k}, {w.q, w.k, w.v}); + if (fused) + op_qnr = cls.has_v ? rw(b, op_qnr, {w.qkv}, {w.qkv}) + : rw(b, op_qnr, {w.qkv}, {w.qkv, w.v}); + else + op_qnr = cls.has_v ? rw(b, op_qnr, {w.q, w.k, w.v}, {w.q, w.k, w.v}) + : rw(b, op_qnr, {w.q, w.k}, {w.q, w.k, w.v}); + }; + + /* A column slice of the fused row copied into its own rows (`cast`, bf16 to bf16, which every + * library takes with pitched operands). */ + auto lift = [&](int64_t n, rad_buf dst) { + return rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {w.qkv}, {dst}); + }; + + if (!fused) { + op_attn = attn("attn_paged", {w.q}); + decl_qnr(); + } else { + /* The prologue first: what attention reads depends on it. Without it the unfused five read + * q, k and v dense, so all three are copied out of the row ahead of them. */ + decl_qnr(); + if (!op_qnr) { + op_lift_k = lift(kvd, w.k); + if (cls.has_v) op_lift_v = lift(kvd, w.v); + } + /* With it attention reads q in the row where that costs nothing. libr4d's dedicated paged + * kernels stop at head_dim 256; at 512 (the global class) attn_paged takes the windowed + * kernel, which is the kernel attn_paged_qrow takes, so the row is read in place. At 256 the + * dedicated h256 kernels serve attn_paged in 0.26-0.71 of the windowed kernel's time + * (libr4d/r4d_plugin.h, R4D_PRIO_ATTN_WINDOW), so the sliding class keeps attn_paged: a step + * of one row reads q in place (one row of a slice is dense), a taller one copies q out. */ + if (op_qnr && cls.head_dim > 256 && rad_op_declared(b, "attn_paged_qrow")) + op_attn_row = attn("attn_paged_qrow", {w.qkv}); + if (!op_attn_row) { + op_lift_q = lift(qd, w.q); + op_attn = attn("attn_paged", {w.q, w.qkv}); + } } - op_kv = rw(b, RAD_OP(b, "kv_store", + /* On a fused layer with the one-op prologue, k and v are stored from the row (kv_store takes + * them at their own pitches); a k_eq_v class's v is its own buffer either way. */ + op_kv = RAD_OP(b, "kv_store", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), RAD_INT("n_head_kv", cls.n_head_kv), RAD_INT("block_size", rad_kv_block_size(b, kv)), RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS), - {w.k, w.v}, {}); + RAD_NOWEIGHTS); + if (!(fused && op_qnr)) op_kv = rw(b, op_kv, {w.k, w.v}, {}); + else if (cls.has_v) op_kv = rw(b, op_kv, {w.qkv}, {}); + else op_kv = rw(b, op_kv, {w.qkv, w.v}, {}); /* o_proj is column-sharded: the rank's partial sum is reduced first, then normed. */ if (g.world > 1) @@ -404,13 +538,13 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, bool ar_fused) const { - const RadKVGroupBatch* kvb = kv_batch(batch, kv); - const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; - const int32_t* table = kvb ? kvb->block_table : nullptr; - const int32_t* used = kvb ? kvb->seqused : nullptr; const int64_t T = batch->n_tok; - if (entry_done) { + if (fused) { + if (!entry_done) RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + if (entry_done) ln_qkv.gemm(c, w.qkv, T); + else ln_qkv.step(c, w.h, w.qkv, T); + } else if (entry_done) { ln_q.gemm(c, w.q, T); ln_k.gemm(c, w.k, T); if (cls.has_v) ln_v.gemm(c, w.v, T); @@ -420,11 +554,53 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta ln_k.step(c, w.h, w.k, T); if (cls.has_v) ln_v.step(c, w.h, w.v, T); } + attend(c, batch); + + ln_o.step(c, w.attn, w.h, T); + /* The all-reduce comes before the post-norm: o_proj is column-sharded, so each rank holds a + * partial sum, and the norm is of the whole output (sum_r rmsnorm(p_r) != rmsnorm(sum_r p_r)). */ + if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + if (tail_fused) return; + RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); + RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T)); +} + +void Gemma4Attn::project(RadCtx* c, int64_t r0, int64_t n) const { + if (fused) { + ln_qkv.gemm_rows(c, w.qkv, r0, n); + return; + } + ln_q.gemm_rows(c, w.q, r0, n); + ln_k.gemm_rows(c, w.k, r0, n); + if (cls.has_v) ln_v.gemm_rows(c, w.v, r0, n); +} + +void Gemma4Attn::out_proj(RadCtx* c, int64_t r0, int64_t n) const { + ln_o.step_rows(c, w.attn, w.h, r0, n); +} + +void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + const int64_t T = batch->n_tok; + const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); + /* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the + * one-op prologue the row's column slices (a k_eq_v class's v is its own buffer either way). */ + const bool row = fused && op_qnr; + const RadOperand Q = row ? bcol(w.qkv, 0, qd, T) : brows(w.q, T); + const RadOperand K = row ? bcol(w.qkv, qd, kvd, T) : brows(w.k, T); + const RadOperand V = row && cls.has_v ? bcol(w.qkv, qd + kvd, kvd, T) : brows(w.v, T); if (op_qnr) { - RAD_ISSUE(c, op_qnr, brows(w.q, T), brows(w.k, T), brows(w.v, T), rope_posmc(g, batch, T), - RAD_W(w_qn), RAD_W(w_kn)); + RAD_ISSUE(c, op_qnr, Q, K, V, rope_posmc(g, batch, T), RAD_W(w_qn), RAD_W(w_kn)); } else { + if (fused) { /* the unfused five read q, k and v dense */ + RAD_ISSUE_N(c, op_lift_q, T, bcol(w.qkv, 0, qd, T), brows(w.q, T)); + RAD_ISSUE_N(c, op_lift_k, T, bcol(w.qkv, qd, kvd, T), brows(w.k, T)); + if (cls.has_v) RAD_ISSUE_N(c, op_lift_v, T, bcol(w.qkv, qd + kvd, kvd, T), brows(w.v, T)); + } /* Normalise v first: on a k_eq_v class v derives from the raw k, before k_norm rewrites it. */ RAD_ISSUE_N(c, op_vn, T * cls.n_head_kv, brows(cls.has_v ? w.v : w.k, T), brows(w.v, T)); RAD_ISSUE_N(c, op_qn, T * cls.n_head, brows(w.q, T), RAD_W(w_qn), brows(w.q, T)); @@ -434,23 +610,25 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta RAD_ISSUE(c, op_rk, brows(w.k, T), rope_posmc(g, batch, T)); } - RAD_ISSUE(c, op_kv, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer)); + RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer)); - RAD_ISSUE_N(c, op_attn, batch->max_q_len, - brows(w.q, T), kv_cache(kv, layer), + /* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */ + rad_op a_op = op_attn; + RadOperand a_q = brows(w.q, T); + if (op_attn_row) { + a_op = op_attn_row; + a_q = Q; + } else if (row) { + if (T == 1) a_q = Q; + else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T)); + } + RAD_ISSUE_N(c, a_op, batch->max_q_len, + a_q, 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, praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(w.attn, T)); - - ln_o.step(c, w.attn, w.h, T); - /* The all-reduce comes before the post-norm: o_proj is column-sharded, so each rank holds a - * partial sum, and the norm is of the whole output (sum_r rmsnorm(p_r) != rmsnorm(sum_r p_r)). */ - if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - if (tail_fused) return; - RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); - RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T)); } /* ---- the feed-forward: GELU (not SwiGLU), with a second norm on the down-projection output. */ @@ -469,8 +647,32 @@ struct Gemma4Mlp { int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre); void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, bool ar_fused = false) const; + /* For the prefill overlap, over rows [r0, r0 + n): the arm from the pair a junction wrote to + * down_proj's partial in `h`, and the post-norm and add the last layer takes unfused. */ + void arm(RadCtx* c, int64_t r0, int64_t n) const; + void tail(RadCtx* c, int64_t r0, int64_t n) const; }; +void Gemma4Mlp::arm(RadCtx* c, int64_t r0, int64_t n) const { + const int64_t F = g.n_ff; + ln_gu.gemm_rows(c, w.gu, r0, n); + if (op_gq) { + RAD_ISSUE_N(c, op_gq, n, brow_slice(w.gu, r0, n, 2 * F), brow_slice(ln_down.q8, r0, n, F), + brow_slice(ln_down.s8, r0, n, 1), RAD_NONE); + ln_down.gemm_rows(c, w.h, r0, n); + } else { + RAD_ISSUE_N(c, op_act, n, brow_slice(w.gu, r0, n, 2 * F), brow_slice(w.ffn, r0, n, F)); + ln_down.step_rows(c, w.ffn, w.h, r0, n); + } +} + +void Gemma4Mlp::tail(RadCtx* c, int64_t r0, int64_t n) const { + const int64_t E = g.n_embd; + RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, E), RAD_W(w_post), brow_slice(w.h, r0, n, E)); + RAD_ISSUE_N(c, op_add, n, brow_slice(w.x, r0, n, E), brow_slice(w.h, r0, n, E), + brow_slice(w.x, r0, n, E)); +} + int Gemma4Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre) { g = geom; layer = l; w = wire; @@ -627,6 +829,13 @@ struct G4Junction { brows(q8, T), brows(s8, T), RAD_NONE, wp ? RAD_W(wp) : RAD_NONE, sc ? RAD_W(sc) : RAD_NONE); } + /* Rows [r0, r0 + n), without the all-reduce: a slice of the prefill overlap, whose reduction + * rode the second lane. */ + void step_rows(RadCtx* c, int64_t E, int64_t r0, int64_t n) const { + RAD_ISSUE_N(c, op, n, brow_slice(x, r0, n, E), res ? brow_slice(res, r0, n, E) : RAD_NONE, + RAD_W(w), brow_slice(q8, r0, n, E), brow_slice(s8, r0, n, 1), RAD_NONE, + wp ? RAD_W(wp) : RAD_NONE, sc ? RAD_W(sc) : RAD_NONE); + } }; /* ==================================================================== the assistant head @@ -1088,6 +1297,13 @@ void Gemma4Head::step(RadCtx* c, const RadBatch* batch) const { ln_post.step(c, b_hd, b_hn, T); } +/* The prefill overlap's smallest slice (trunk_overlap). It is above every row band the sliced + * kernels have, with room to spare: the int8 GEMMs' skinny band (64) and r4d_act_threads' last + * width change at these widths (120 rows), which fixes the norms' and the quantisers' + * sum-of-squares partition. And it is large enough that a slice's reduction is worth a second + * lane. */ +static constexpr int64_t kOverlapRows = 512; + struct Layer { bool global = false; Gemma4Attn attn{}; @@ -1115,6 +1331,7 @@ struct Model { rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0; rad_buf b_qs = 0, b_ks = 0, b_vs = 0, b_attns = 0; /* sliding rows */ rad_buf b_qg = 0, b_kg = 0, b_vg = 0, b_atting = 0; /* global rows */ + rad_buf b_qkvs = 0, b_qkvg = 0; /* the fused projections' rows, where a layer has one */ rad_buf b_gu = 0, b_ffn = 0; rad_weight w_tok = 0, w_out = 0, w_lm = 0; @@ -1136,6 +1353,9 @@ struct Model { bool fuse = false; bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */ int64_t ar_rows = 0; /* ...in a step of at most this many rows (G4Junction::ar_rows) */ + /* A prefill step of 2 * kOverlapRows rows or more runs as two slices, each slice's + * all-reduces on the second lane beside the other's compute (trunk_overlap). Set at declare. */ + bool overlap = false; /* z-lab's DFlash drafter (arch/common/rad_gemma4_dflash.h), declared only when the container * carries one and the deployment speculates: the trunk layers it taps, the [max_tok, taps x @@ -1147,10 +1367,214 @@ struct Model { gemma4::Dflash1 df{}; rad_kvgroup kv_draft = 0; bool have_df = false; + /* Or a DFlash2 drafter (arch/common/rad_block_dflash2.h): RedHatAI's speculators-format one + * for the 31B. Same taps and plane; its own block, buffers and KV group. */ + Dflash2 df2{}; + Dflash2::Wire df2w{}; + bool have_df2 = false; }; static Model g_model[MAX_RANKS]; +/* A DFlash2 drafter's config key, from vLLM's speculators layout (the speculator's keys at the + * top of `draft.`) or z-lab's (under `draft.dflash_config.`), whichever the checkpoint has. */ +static long long df2_geti(const RadModelMeta* meta, const char* key, long long dflt) { + char k[160]; + std::snprintf(k, sizeof k, "draft.%s", key); + const long long v = rad_meta_geti(meta, k, LLONG_MIN); + if (v != LLONG_MIN) return v; + std::snprintf(k, sizeof k, "draft.dflash_config.%s", key); + return rad_meta_geti(meta, k, dflt); +} + +/* The DFlash2 drafter: RedHatAI/gemma-4-31B-it-speculator.dflash2, a speculators-format DFlash2 + * (z-lab's architecture, trained by Red Hat on gemma-4-31B-it's outputs) in place of z-lab's + * DFlash. rad_block_dflash2.h is the block; this reads its config and wires it to the trunk. + * + * From the checkpoint and speculators' code (models/dflash2, models/dflash/core.py): + * + * - five Qwen3-shaped layers at the trunk's width, every one sliding (2048) and non-causal; + * - the target's table as a plain nn.Embedding: no Gemma sqrt(hidden) scale (z-lab's DFlash + * goes through the target's scaled module; this one does not), so the block's unscaled + * lookup is right; + * - the target's head as a plain linear, no soft-cap, which the block's head is; + * - taps counted as vLLM captures them, the residual entering a layer (gemma4::dflash2_taps); + * - block 8: the anchor predicts nothing, seven drafts (sample_from_anchor false). + * + * The head reads the 8-bit copy the -df2 recipe makes (rad_block_dflash2.h, head_i8), so the + * selector ranks what an 8-bit head proposes. Nothing here is defaulted quietly: a config this + * block does not implement is refused by name. */ +static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m) { + Names& nm = m.nm; + Geom dg{}; + RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma4 DFlash2")); + const char* lp = drafter_layer_prefix(meta); + char key[160]; + std::snprintf(key, sizeof key, "%shidden_size", lp); + if (rad_meta_geti(meta, key, dg.n_embd) != dg.n_embd) { + fprintf(stderr, "radiance: gemma4: the DFlash2 drafter is %lld wide and the trunk %lld; its " + "fc and residual stream are the trunk's width\n", + rad_meta_geti(meta, key, 0), (long long)dg.n_embd); + return RAD_E_UNSUPPORTED; + } + std::snprintf(key, sizeof key, "%shidden_act", lp); + const char* act = rad_meta_gets(meta, key, "silu"); + if (std::strcmp(act, "silu")) { + fprintf(stderr, "radiance: gemma4: the DFlash2 drafter's MLP uses %s; the block's is silu\n", + act); + return RAD_E_UNSUPPORTED; + } + if (df2_geti(meta, "sample_from_anchor", 0)) { + fprintf(stderr, "radiance: gemma4: this DFlash2 drafter samples from its anchor row; the " + "block's anchor predicts nothing\n"); + return RAD_E_UNSUPPORTED; + } + + Dflash2::Config dc{}; + dc.n_taps = m.n_taps; + dc.block = ctx->max_spec + 1; + dc.taps = df2_geti(meta, "conv_kernel_size", 2); + dc.group = df2_geti(meta, "conv_group_size", 16); + dc.sel_rank = df2_geti(meta, "selector_rank", 0); + dc.sel_topk = df2_geti(meta, "selector_top_k", 0); + if (dc.sel_rank <= 0 || dc.sel_topk <= 0) { + fprintf(stderr, "radiance: gemma4: the DFlash2 drafter states no selector geometry (rank " + "%lld, top_k %lld)\n", (long long)dc.sel_rank, (long long)dc.sel_topk); + return RAD_E_INVAL; + } + /* Attention: one window for every layer, since the block issues one attention op. A sliding + * window non-causal within the block is speculators' sliding_window_non_causal; z-lab's + * layout says is_causal. */ + { + std::snprintf(key, sizeof key, "%slayer_types", lp); + std::vector sliding; + if (const char* lt = rad_meta_gets(meta, key, nullptr)) + RAD_ARCH_TRY(parse_layer_kinds("gemma4 DFlash2", lt, {"sliding_attention"}, + "full_attention", &sliding)); + const bool any_full = std::find(sliding.begin(), sliding.end(), 0) != sliding.end(); + const bool any_slide = std::find(sliding.begin(), sliding.end(), 1) != sliding.end(); + if (any_full && any_slide) { + fprintf(stderr, "radiance: gemma4: the DFlash2 drafter mixes sliding and full layers; " + "the block takes one attention width for all of them\n"); + return RAD_E_UNSUPPORTED; + } + std::snprintf(key, sizeof key, "%ssliding_window", lp); + const long long win = rad_meta_geti(meta, key, 0); + std::snprintf(key, sizeof key, "%suse_sliding_window", lp); + if (any_slide || rad_meta_geti(meta, key, 0)) + dc.window = df2_geti(meta, "swa_window_size", win); + const long long nc = rad_meta_geti(meta, "draft.sliding_window_non_causal", -1); + dc.causal = nc >= 0 ? (nc ? 0 : 1) : (rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0); + } + + /* The query block must be a power of two (the convolution masks a row's position with + * block_size - 1), and the depth the probe named is the trained one. */ + const long long trained = gemma4::dflash_block(meta); + if (dc.block < 2 || (dc.block & (dc.block - 1))) { + fprintf(stderr, "radiance: gemma4: DFlash2's convolution masks the block position with " + "block_size - 1, so the query block must be a power of two; %d draft " + "tokens make it %lld (trained at %lld)\n", + ctx->max_spec, (long long)dc.block, trained); + return RAD_E_UNSUPPORTED; + } + if (trained > 0 && trained != dc.block) + rad_note(b, "DFlash2 was trained at block_size %lld (%lld draft tokens) and runs at %lld; " + "it accepts less away from its trained block", trained, trained - 1, + (long long)dc.block); + /* The three scalars rad_block_dflash2.h does not apply (z-lab's names; speculators has none). */ + if (rad_meta_getf(meta, "draft.dflash_config.input_embedding_scale", 1.0) != 1.0 || + rad_meta_getf(meta, "draft.dflash_config.output_multiplier", 1.0) != 1.0 || + rad_meta_getf(meta, "draft.dflash_config.final_logit_softcapping", 0.0) != 0.0) { + fprintf(stderr, "radiance: gemma4: this DFlash2 checkpoint scales its embedding or its " + "logits, or soft-caps them; the block applies none of the three\n"); + return RAD_E_UNSUPPORTED; + } + + RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, dc.window, (int)m.n_main, &m.kv_draft)); + + const int64_t qd = dg.n_head * dg.head_dim; + const int64_t kvd = dg.n_head_kv * dg.head_dim; + int64_t qr = dg.max_seqs * dc.block; + if (qr > dg.max_tok) qr = dg.max_tok; + const int64_t sr = dg.max_seqs * dc.steps(); + const int64_t spad = ((sr + 15) / 16) * 16; + + Dflash2::Wire& dw = m.df2w; + dw.src = m.b_dfsrc; + dw.c = decl_b(b, nm.f("df_c"), dg.act_dtype, {dg.max_tok, dg.n_embd}); + dw.ck = decl_b(b, nm.f("df_ck"), dg.act_dtype, {dg.max_tok, kvd}); + dw.cv = decl_b(b, nm.f("df_cv"), dg.act_dtype, {dg.max_tok, kvd}); + dw.x = decl_b(b, nm.f("df_x"), dg.act_dtype, {qr, dg.n_embd}); + dw.h = decl_b(b, nm.f("df_h"), dg.act_dtype, {qr, dg.n_embd}); + dw.h2 = decl_b(b, nm.f("df_h2"), dg.act_dtype, {qr, dg.n_embd}); + dw.coef = decl_b(b, nm.f("df_coef"), dg.act_dtype, {qr, dc.coef_dim(dg.n_embd)}); + dw.q = decl_b(b, nm.f("df_q"), dg.act_dtype, {qr, qd}); + dw.k = decl_b(b, nm.f("df_k"), dg.act_dtype, {qr, kvd}); + dw.v = decl_b(b, nm.f("df_v"), dg.act_dtype, {qr, kvd}); + dw.attn = decl_b(b, nm.f("df_attn"), dg.act_dtype, {qr, qd}); + dw.gate_up = decl_b(b, nm.f("df_gate_up"), dg.act_dtype, {qr, 2 * dg.n_ff}); + dw.ffn = decl_b(b, nm.f("df_ffn"), dg.act_dtype, {qr, dg.n_ff}); + dw.srcq = decl_b(b, nm.f("df_srcq"), RAD_F8E4M3, {dg.max_tok, dc.n_taps * dg.n_embd}); + dw.srcs = decl_b(b, nm.f("df_srcs"), RAD_F32, + {dg.max_tok, fp8_blocks(dc.n_taps * dg.n_embd)}); + dw.cq = decl_b(b, nm.f("df_cq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd}); + dw.cs = decl_b(b, nm.f("df_cs"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)}); + dw.h2q = decl_b(b, nm.f("df_h2q"), RAD_F8E4M3, {qr, dg.n_embd}); + dw.h2s = decl_b(b, nm.f("df_h2s"), RAD_F32, {qr, fp8_blocks(dg.n_embd)}); + dw.atq = decl_b(b, nm.f("df_atq"), RAD_F8E4M3, {qr, qd}); + dw.ats = decl_b(b, nm.f("df_ats"), RAD_F32, {qr, fp8_blocks(qd)}); + dw.ffq = decl_b(b, nm.f("df_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); + dw.ffs = decl_b(b, nm.f("df_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); + dw.sel_h = decl_b(b, nm.f("df_selh"), dg.act_dtype, {sr, dg.n_embd}); + dw.hp = decl_b(b, nm.f("df_hp"), dg.act_dtype, {sr, dc.sel_rank}); + dw.dq = decl_b(b, nm.f("df_dq"), RAD_I8, {sr, dg.n_embd}); + dw.ds = decl_b(b, nm.f("df_ds"), RAD_F32, {sr, 1}); + dw.dsum = decl_b(b, nm.f("df_dsum"), RAD_F32, {dg.n_embd / 128, spad}); + dw.dlog = decl_b(b, nm.f("df_dlog"), dg.act_dtype, {sr, Dflash2::head_rows(dg)}); + /* No rescoring against the trunk's head: the -df2 recipe's head is already 8-bit, so the + * candidates are the ones an 8-bit head ranks (rad_block_dflash2.h, head_i8). */ + const int64_t tw = dc.sel_topk; + dw.cand = decl_b(b, nm.f("df_cand"), RAD_I32, {sr, tw}); + dw.unary = decl_b(b, nm.f("df_unary"), RAD_F32, {sr, tw}); + if (Dflash2::head_sharded(dg)) { + dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2}); + dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2}); + } + dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()}); + + /* The head copy comes from the tied table, under the block's own name; the recipe makes it + * 8-bit. */ + RAD_ARCH_TRY(m.df2.declare(b, nm, dg, dc, (int)m.n_main, m.kv_draft, m.w_tok, "draft", + nm.ckpt("model.language_model.embed_tokens.weight"), dw)); + m.have_df2 = true; + + RadDrafterDecl drf{}; + drf.name = "dflash2"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + drf.block = dc.block; + drf.proposal = dw.tokens; + drf.proposal_pitch = dc.steps(); + drf.window = dc.window; + drf.mask_token = (int32_t)df2_geti(meta, "mask_token_id", -1); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: gemma4: this DFlash2 checkpoint declares no mask_token_id, and " + "every drafted position embeds it\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + + rad_note(b, "DFlash2 drafter: %lld layers at absolute %lld.., %lld heads / %lld kv x %lld, ffn " + "%lld, %s attention with a %lld-token window, %d trunk taps; one forward proposes " + "%lld tokens through the candidate selector, its head %s", + (long long)dg.n_layer, (long long)m.n_main, (long long)dg.n_head_all, + (long long)dg.n_head_kv_all, (long long)dg.head_dim, (long long)dg.n_ff_all, + dc.causal ? "causal" : "non-causal", (long long)dc.window, m.n_taps, + (long long)dc.steps(), m.df2.head_i8 ? "8-bit" : "2-bit"); + return RAD_OK; +} + static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { if (!b || !meta || !ctx) return RAD_E_INVAL; if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; @@ -1273,7 +1697,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * serve speculates. The plane is declared here and written by an op declared inside each layer * it taps, because the buffer planner's liveness is declaration order (the tap below). */ { - const int n = gemma4::Dflash1::taps(meta, ctx, g.n_layer, m.tap_layer, Model::MAX_TAPS); + const int n = gemma4::dflash_kind(meta) == 2 + ? gemma4::dflash2_taps(meta, ctx, g.n_layer, m.tap_layer, Model::MAX_TAPS) + : gemma4::Dflash1::taps(meta, ctx, g.n_layer, m.tap_layer, Model::MAX_TAPS); if (n < 0) return n; m.n_taps = n; if (n > 0) @@ -1342,7 +1768,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s; const Gemma4Attn::Wire& aw = lay.global ? gw : sw; RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); - RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre, + lay.global ? &m.b_qkvg : &m.b_qkvs)); RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, pre)); /* The per-layer scalar: `cur = cur * scalar`, a [1] bf16 over the residual stream. */ @@ -1378,10 +1805,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (m.n_main > 0) { bool ok = true; for (const Layer& lay : m.layers) - ok = ok && lay.attn.ln_q.quant && lay.attn.ln_k.shared_in && - (!lay.attn.cls.has_v || lay.attn.ln_v.shared_in) && lay.mlp.ln_gu.quant; + ok = ok && lay.attn.reads_pair() && lay.mlp.ln_gu.quant; if (ok) { - RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, 0, m.layers[0].attn.ln_q)); + RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, 0, + m.layers[0].attn.ln_in())); ok = m.j0.op != 0; for (int64_t l = 0; ok && l < m.n_main; ++l) { Layer& lay = m.layers[(size_t)l]; @@ -1391,7 +1818,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (ok && l + 1 < m.n_main) { const Layer& nx = m.layers[(size_t)l + 1]; RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm, lay.mlp.w_post, - lay.w_scalar, nx.attn.ln_q)); + lay.w_scalar, nx.attn.ln_in())); ok = lay.j_ma.op != 0; } } @@ -1409,6 +1836,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.ar_rows = ar ? rows : 0; } + /* ---- the prefill overlap (trunk_overlap). It needs a reduction to hide, every junction fused + * (the slices issue only the fused forms), and the exact wire, the one shown to give a slice + * the bits it gives the whole. The buffer the second lane reduces in place is taken out of the + * arena's sharing, which the runtime asks of every buffer a second lane touches; it lives + * across the whole trunk already. */ + const char* ov = std::getenv("RADIANCE_GEMMA4_OVERLAP"); /* 0: every step whole */ + const bool ov_off = ov && !std::strcmp(ov, "0"); + m.overlap = !ov_off && g.world > 1 && g.wire_exact && m.fuse && g.max_tok >= 2 * kOverlapRows; + for (const Layer& lay : m.layers) + m.overlap = m.overlap && lay.attn.op_ar && lay.mlp.op_ar; + if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h)); + /* ---- the tail: final norm, the sampled rows, the lm_head, and the soft-cap. */ m.op_final = rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), @@ -1457,7 +1896,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * declaration order is the buffer planner's liveness. It reads the taps the trunk copied into * `dflash_src` and the trunk's tied table, as its embedding and, where the container holds no * 8-bit copy, as its head. */ - if (m.n_taps > 0) { + if (m.n_taps > 0 && gemma4::dflash_kind(meta) == 2) { + RAD_ARCH_TRY(declare_dflash2(b, meta, ctx, m)); + } else if (m.n_taps > 0) { gemma4::Dflash1::Trunk t{}; t.n_taps = m.n_taps; t.escale = gemma4::embed_scale(g.n_embd); @@ -1478,6 +1919,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c head_groups = meta_text_geti(meta, "num_hidden_layers", 0, "draft.") + 1; else if (gemma4::dflash_kind(meta) == 1) head_groups = rad_meta_geti(meta, "draft.num_hidden_layers", 0); + else if (gemma4::dflash_kind(meta) == 2) { + char k[160]; + std::snprintf(k, sizeof k, "%snum_hidden_layers", drafter_layer_prefix(meta)); + head_groups = rad_meta_geti(meta, k, 0); + } RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups), "model.", "gemma4_bf16")); } @@ -1487,6 +1933,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.rank, g.world, (long long)g.n_layer, (long long)n_global, (long long)(g.n_layer - n_global), (long long)sliding_win, (long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g); + { + int64_t n_fused = 0, n_row = 0; + for (const Layer& lay : m.layers) { + n_fused += lay.attn.fused ? 1 : 0; + n_row += lay.attn.op_attn_row ? 1 : 0; + } + if (n_fused) + rad_note(b, "q, k and v as one linear (blk.*.attn_qkv) on %lld of %lld layers; attention " + "reads q in the row on %lld, copies it out above one row on the rest", + (long long)n_fused, (long long)m.layers.size(), (long long)n_row); + else + rad_note(b, "q, k and v as three linears (a container converted before attn_qkv, or " + "bf16 weights): convert with a recipe naming blk.*.attn_qkv.weight for one"); + } + if (g.world > 1) { + if (m.overlap) + rad_note(b, "prefill overlap: a step of %lld rows or more runs as two slices, each " + "slice's all-reduces on a second stream beside the other's compute", + (long long)(2 * kOverlapRows)); + else + rad_note(b, "prefill overlap: off (%s)", + ov_off ? "RADIANCE_GEMMA4_OVERLAP=0" + : !g.wire_exact ? "the lossy all-reduce wire" + : !m.fuse ? "the residual junctions are not fused" + : "a step holds fewer than two slices"); + } if (m.fuse && (g.world == 2 || g.world == 4)) { if (!m.fuse_ar) rad_note(b, "residual junctions: the all-reduce in front of each issued apart"); @@ -1500,6 +1972,109 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c return RAD_OK; } +/* ==================================================================== the prefill overlap + * + * A prefill step in two slices, each slice's all-reduces on the runtime's second lane (rad_lane) + * beside the other slice's compute: arch/gemma4's trunk_overlap, on this trunk. A layer reduces + * T x n_embd twice, after o_proj and after down_proj, both column-sharded; run whole, the + * reductions and the compute take turns. Cut in two, a slice's reduction runs while the other + * slice computes: + * + * lane 0 o(A) o(B) . jam(A) arm(A) . jam(B) arm(B) . jma(A) qkv(A) . jma(B) qkv(B) attn o(A) .. + * lane 1 ar(A) ar(B) ar(A) ar(B) + * + * Attention runs whole (the prologue, the cache write and attn_paged): it reads every row's keys, + * and its batch bounds describe the whole step. The rest is a row at a time: the projections, the + * junctions, the feed-forward arm and the reductions. + * + * The same kernels give the same bits (core/runtime/ctx.h, the second lane's rule four). Both slices + * are at least kOverlapRows rows: above the int8 GEMMs' skinny band, whose prefill and tiled + * kernels take each row's K in order whatever M is; above r4d_act_threads' last width change, so + * every junction, quantiser and norm folds a row's sum of squares as the whole step's does; and the + * exact all-reduce folds a word in fp32 in ascending rank order whatever message carries it. On + * the exact wire only. + * + * One buffer carries both reductions: o_proj and down_proj both write `h`, and the junctions read + * it. So the order below never lets lane 0 write rows of `h` lane 1 is reducing: slice A's arm + * writes h[A] only after A's attention reduction was waited for, while lane 1 reduces h[B]. Every + * reduction rides lane 1 behind a join from lane 0, which holds its producer; lane 0 waits for lane + * 1 before the reduction's consumer; each wait goes in after the lane-0 work that does not need it. + * The embedding's reduction stays on lane 0, ahead of everything lane 1 is first joined behind, so + * the collectives keep one order on every rank. At two ranks the junctions here carry no + * all-reduce (the reduction rode lane 1); a step that runs whole keeps the fused one. */ +static int64_t split_at(const Model& m, int64_t T) { + if (!m.overlap || T < 2 * kOverlapRows) return 0; + return (T / 2) / 128 * 128; /* slice A whole 128-row tiles; both slices >= kOverlapRows */ +} + +static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int64_t cut) { + const int64_t T = batch->n_tok, E = m.g.n_embd; + const int64_t a0 = 0, an = cut, b0 = cut, bn = T - cut; + bool lanes_ok = true; + /* An all-reduce in place over rows [r0, r0 + n) of `h`, on lane 1 behind everything lane 0 + * has issued -- its producer among it. */ + auto reduce = [&](rad_op op, int64_t r0, int64_t n) { + lanes_ok = lanes_ok && rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK; + RAD_ISSUE_N(c, op, n * E, brow_slice(m.b_h, r0, n, E), RAD_NONE); + lanes_ok = rad_lane(c, 0) == RAD_OK && lanes_ok; + }; + /* Lane 0 behind every reduction issued so far. */ + auto join_back = [&] { lanes_ok = rad_lane_join(c, 1, 0) == RAD_OK && lanes_ok; }; + /* Rows [r0, r0 + n) of layer li's end, once their feed-forward reduction is in: the junction + * into the next layer -- or the last layer's post-norm, add and scalar -- and the drafter's + * taps of those rows. */ + auto join_ff = [&](size_t li, int64_t r0, int64_t n) { + const Layer& y = m.layers[li]; + if (li + 1 < m.layers.size()) { + y.j_ma.step_rows(c, E, r0, n); + } else { + y.mlp.tail(c, r0, n); + RAD_ISSUE_N(c, y.op_scale, n, brow_slice(m.b_x, r0, n, E), RAD_W(y.w_scalar), + brow_slice(m.b_x, r0, n, E)); + } + for (int t = 0; t < m.n_taps && y.op_tap; ++t) + if (m.tap_layer[t] == (int)li) + RAD_ISSUE_N(c, y.op_tap, n, brow_slice(m.b_x, r0, n, E), + bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * E, (int64_t)t * E, E, n)); + }; + + m.j0.step(c, T); + const size_t L = m.layers.size(); + for (size_t li = 0; li < L; ++li) { + const Layer& y = m.layers[li]; + if (li == 0) { + y.attn.project(c, a0, an); + y.attn.project(c, b0, bn); + } else { + join_ff(li - 1, a0, an); /* its reduction was waited for last layer */ + y.attn.project(c, a0, an); + join_back(); /* the last layer's feed-forward, slice B */ + join_ff(li - 1, b0, bn); + y.attn.project(c, b0, bn); + } + y.attn.attend(c, batch); + y.attn.out_proj(c, a0, an); + reduce(y.attn.op_ar, a0, an); + y.attn.out_proj(c, b0, bn); + join_back(); /* attention, slice A */ + reduce(y.attn.op_ar, b0, bn); + y.j_am.step_rows(c, E, a0, an); + y.mlp.arm(c, a0, an); + join_back(); /* attention, slice B */ + reduce(y.mlp.op_ar, a0, an); + y.j_am.step_rows(c, E, b0, bn); + y.mlp.arm(c, b0, bn); + join_back(); /* the feed-forward, slice A */ + reduce(y.mlp.op_ar, b0, bn); + } + join_ff(L - 1, a0, an); + join_back(); /* the last feed-forward, slice B */ + join_ff(L - 1, b0, bn); + if (!lanes_ok) + rad_step_fail(c, "gemma4_bf16: the prefill overlap could not order its second lane against " + "the first"); +} + static void step(RadCtx* c, const RadBatch* batch) { Model& m = g_model[rad_rank(c)]; @@ -1517,6 +2092,11 @@ static void step(RadCtx* c, const RadBatch* batch) { else m.df.context(c, batch); return; } + if (m.have_df2) { + if (batch->draft_pass > 0) m.df2.step(c, batch); + else m.df2.context(c, batch); + return; + } if (!m.have_head) { rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " "container carries no `draft.` assistant or DFlash drafter, or declare " @@ -1538,10 +2118,12 @@ static void step(RadCtx* c, const RadBatch* batch) { praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok)); const int64_t T = batch->n_tok; - if (m.fuse) m.j0.step(c, T); + const int64_t cut = split_at(m, T); + if (cut > 0) trunk_overlap(c, m, batch, cut); + else if (m.fuse) m.j0.step(c, T); /* the junctions carry the reductions in front of them in a step their fold serves */ const bool far = m.fuse_ar && T <= m.ar_rows; - for (size_t li = 0; li < m.layers.size(); ++li) { + for (size_t li = 0; cut == 0 && li < m.layers.size(); ++li) { const Layer& l = m.layers[li]; const bool last = li + 1 == m.layers.size(); l.attn.step(c, batch, m.fuse, m.fuse, far); @@ -1595,8 +2177,10 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { out->draft_depth = kHeadDepth; out->draft_depth_fixed = 0; } - /* A DFlash drafter names the block it was trained at, and only that (rad_gemma4_dflash.h). */ + /* A DFlash drafter names the block it was trained at, and only that (rad_gemma4_dflash.h); a + * DFlash2 one too (rad_block_dflash2.h). */ (void)gemma4::dflash_probe(meta, out); + (void)gemma4::dflash2_probe(meta, out); /* The tower's pooling window, so a pass size the core picks itself is whole windows. */ if (Gemma4Vision::present(meta)) { const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0); diff --git a/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe b/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe index 2276fb5f..c4010a70 100644 --- a/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe +++ b/data/recipes/gemma4-31b-dense-bf16-q8-df.recipe @@ -35,11 +35,10 @@ # 32 GiB R9700. # # This starts from bf16 for the reason gemma4-31b-dense-bf16-w4a8-df.recipe gives: the drafter -# reads the trunk's hidden states and was trained beside the bf16 trunk. +# reads the trunk's hidden states and was trained beside the bf16 trunk. q, k and v are one linear +# (blk.*.attn_qkv), for the reason that recipe gives. -blk.*.attn_q.weight rtn codes=i8 group=128 scale=f16 clamp=sym -blk.*.attn_k.weight rtn codes=i8 group=128 scale=f16 clamp=sym -blk.*.attn_v.weight rtn codes=i8 group=128 scale=f16 clamp=sym +blk.*.attn_qkv.weight rtn codes=i8 group=128 scale=f16 clamp=sym blk.*.attn_o.weight rtn codes=i8 group=128 scale=f16 clamp=sym blk.*.ffn_down.weight rtn codes=i8 group=128 scale=f16 clamp=sym blk.*.ffn_gate_up.weight rtn codes=i8 group=128 scale=f16 clamp=sym diff --git a/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe b/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe index ba60ebea..a3316af2 100644 --- a/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe +++ b/data/recipes/gemma4-31b-dense-bf16-w4a8-df.recipe @@ -28,10 +28,14 @@ # # ~20 GiB: the int4 trunk's linears (~14 GiB), the bf16 table and its int8 head (2 GiB), the # vision tower, the drafter at block fp8 (1.4 GiB) and its head's block-fp8 copy (0.7 GiB). +# +# q, k and v are one linear, blk.*.attn_qkv (q | k | v; q | k on the global layers, where v is +# k): the plugin serves one GEMM a layer where three paid the skinny GEMM's fixed cost each. The +# grid's groups never cross a row, so the codes are those of three separate rules (on the cards k +# and v may round differently in the last bit: the GEMM's K split follows N). A container +# converted before this, with the three apart, still serves. -blk.*.attn_q.weight rtn codes=i4 group=128 scale=f16 rule=search -blk.*.attn_k.weight rtn codes=i4 group=128 scale=f16 rule=search -blk.*.attn_v.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_qkv.weight rtn codes=i4 group=128 scale=f16 rule=search blk.*.attn_o.weight rtn codes=i4 group=128 scale=f16 rule=search blk.*.ffn_down.weight rtn codes=i4 group=128 scale=f16 rule=search blk.*.ffn_gate_up.weight rtn codes=i4 group=128 scale=f16 rule=search diff --git a/data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe b/data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe new file mode 100644 index 00000000..6c7346e5 --- /dev/null +++ b/data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe @@ -0,0 +1,46 @@ +# gemma4-31b-dense-bf16-w4a8-df2.recipe -- Gemma 4 31B dense (text) from Google's bf16 checkpoint +# at w4a8, as gemma4-31b-dense-bf16-w4a8-df.recipe makes it, with RedHatAI's DFlash2 speculator +# merged in place of z-lab's DFlash drafter. +# +# rad-convert --draft-model \ +# --recipe data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe \ +# --set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-w4a8-df2-qkv.rad +# +# radiance serve gemma4-31b-dense-w4a8-df2-qkv.rad --num-speculative-tokens auto ... +# +# The drafter (RedHatAI/gemma-4-31B-it-speculator.dflash2) is a speculators-format DFlash2: five +# Qwen3-shaped layers at 5376 (32 heads / 16 kv x 256, MLP 21504), every one on a 2048-token +# window, non-causal, an fc over the trunk's residual stream entering layers 1 17 29 47 59, a +# grouped dynamic convolution around each sublayer and a candidate selector (rank 256, top-k 16): +# 2.75 B parameters, 5.5 GB at bf16. It proposes 7 tokens a pass (block 8); the plugin's probe names +# that depth, and rad_block_dflash2.h is the block. +# +# It ships no embedding or head: it reads the trunk's table, unscaled, and the trunk's head. The +# trunk is the -df recipe's (int4 trunk, q|k|v as one linear, int8 lm_head), so the same rules. +# +# ~24 GiB: the -df recipe's trunk and table (~16 GiB), the vision tower, the drafter at block fp8 +# (2.6 GiB), its selector codebooks at bf16 (2 x 128 MiB) and its head's int8 copy (1.4 GiB). + +blk.*.attn_qkv.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_o.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_down.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_gate_up.weight rtn codes=i4 group=128 scale=f16 rule=search + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +# The drafter's seven linears: block fp8, read at fp8a8 against an E4M3 activation, as the block +# declares them (rad_fp8.h's DenseFP8). The convolution projections, the selector and the norms +# stay bf16, as the block reads them. +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +# The draft head: the trunk's tied table under the block's own name, int8 with an f16 scale per +# (row, 128 of K), which the block reads at w8a8 (rad_block_dflash2.h, head_i8). Not the 2-bit +# grid the Qwen3.8 recipes use: the selector then ranks the candidates an 8-bit head proposes. +# Drafts are verified, so this changes what is proposed, never what is accepted. +dflash.draft_head.weight rtn codes=i8 group=128 scale=f16 clamp=sym diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 7df0b1f7..b242ead9 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -17,7 +17,7 @@ plugin claims. | `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Text only, bf16 KV | | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | -| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`) | +| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`), or RedHatAI's DFlash2 speculator (`arch/common/rad_block_dflash2.h`) | | `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) | | `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 | | `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 | @@ -745,6 +745,49 @@ hidden states and was trained beside the bf16 trunk. Both plugins scale the embe sqrt(hidden) rounded to bf16, as the reference's embedding module does (73.5 at 5376, not 73.32), and the drafter reads it through the same scale. +**The 31B's prefill overlap.** `arch/gemma4_bf16` cuts a prefill step of 1024 rows or more in two +(slice A whole 128-row tiles, both at least 512) and runs each slice's two all-reduces per layer on +the second lane beside the other slice's compute, as the prefill overlap above does, with one +difference: o_proj and down_proj both write `h`, so the issue order never lets lane 0 write rows of +`h` that lane 1 is reducing, and `h` is the one buffer taken out of the arena's sharing. Attention +runs whole. Both slices are above every row band the sliced kernels have (the int8 GEMMs' skinny +band at 64, since the prefill kernel takes each row's K in order whatever M is, and +r4d_act_threads' last width change at 120 rows for these widths), so on the exact wire the output +equals the whole step's bit for bit. Every junction must be fused, as the w4a8 and w8a8 +containers' are; a bf16 trunk runs whole, and so does every step under `RADIANCE_GEMMA4_OVERLAP=0`. + +**The 31B's q, k and v as one linear.** Converted with a recipe that names `blk.*.attn_qkv.weight` +(both -df recipes do), each layer's q, k and v (q and k on a global layer, where v is k) are one +weight, each rank holding its slice of every part, and one `gemm_nt_q` reads them where three did: +at decode on the R9700 q, k and v take 17 + 13.5 + 13.5 us and a 4096-row GEMM of the same K 25. +The grid's groups never cross a row, so the codes are those of three separate rules, and on libref +the replies are too. On libr4d the skinny GEMM picks its in-block K split from N (k and v alone +split K in two, the fused GEMM does not), so k and v can round differently in the last bit and a +long greedy reply can part from the old container's late. `qkv_norm_rope` and `kv_store` work on +the row's column slices in place. A global layer's +attention reads q in the row (`attn_paged_qrow`, the windowed kernel that serves head_dim 512 under +`attn_paged` too); a sliding layer's reads it there in a one-row step, and a taller step copies q +out with a `cast` for libr4d's h256/gqa2 kernels, which take 0.26-0.71 of the windowed kernel's +time. Without `qkv_norm_rope` (a CPU-only engine) q, k and v are copied out for the unfused +prologue. A container that holds the three apart serves as before: the plugin asks the weight's +encoding, which rad-convert answers from the recipe and a container from its entries. + +**The 31B with a DFlash2 drafter.** RedHatAI's `gemma-4-31B-it-speculator.dflash2` is z-lab's +DFlash2 architecture trained with vLLM's speculators library: five Qwen3-shaped layers at 5376 (32 +heads / 16 kv x 256, ffn 21504), every one on a 2048-token window and non-causal, the grouped +dynamic convolution and the candidate selector (rank 256, top-k 16), block 8 (seven drafts). The +31B serves it with the block qwen35_fp8 uses for Qwen3.8's (`arch/common/rad_block_dflash2.h`) in +place of z-lab's DFlash, when the container's drafter is a `DFlash2DraftModel`. Its config is in +the speculators layout: the speculator's keys at the top of `draft.` and the layers' under +`draft.transformer_layer_config.` (`drafter_layer_prefix`). Its `aux_hidden_state_layer_ids` +count as vLLM captures them, the residual entering a layer, so 1 17 29 47 59 tap the outputs of +layers 0 16 28 46 58 (`gemma4::dflash2_taps`). It was trained against the target's table as a +plain embedding and the target's head as a plain linear, so its lookup takes no Gemma scale and its +head no soft-cap. The -df2 recipe stores its head copy int8 (`head_i8`, read at w8a8) rather than +the 2-bit grid Qwen3.8's recipes use, so the selector ranks what an 8-bit head proposes. Its +attention is the sliding layers' h256 gqa-2 split-KV decode, non-causal. `run-gemma4-31b.sh` +takes it with `DRAFTER=df2`. + **The 31B's junctions at four ranks.** At two ranks every junction carries the all-reduce in front of it (`ar_rmsnorm_quant_i8`). At four it does too, at decode heights. libr4d's `ar_rmsnorm_quant_i8_4rank` is the exact four-rank one-shot with the junction as its epilogue, diff --git a/docs/GUIDE.md b/docs/GUIDE.md index e7be592a..f09baa09 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3086,6 +3086,7 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | +| `RADIANCE_GEMMA4_OVERLAP` | the Gemma 4 31B's prefill overlap (`arch/gemma4_bf16`, two or more ranks, fused junctions, the exact all-reduce wire): a prefill step of 1024 rows or more runs as two slices, each slice's all-reduces on a second stream beside the other's compute. On by default; `0` turns it off and runs every step whole (the startup notes say which) | | `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) | Engine development has its own instruments: `RADIANCE_DEBUG_*` (residual probes, routing and issue diff --git a/docs/OPS.md b/docs/OPS.md index 39bc6a0b..e207e32f 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -691,7 +691,7 @@ may not have arrived. | `gemm_nt` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` | | `gemm_nt_f32` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` | | `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` | -| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | +| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | | `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` | `nt` is A row-major `[M,K]` times B transposed `[N,K]`, giving `[M,N]`: the layout every weight in @@ -726,7 +726,14 @@ weight element (n, k) is `(code - zero) * scale`, one f16 scale and one integer `a_sum` is `quant_act_i8`'s `asum`, group-major `[K/group][Mpad]` with `Mpad = ceil(M/16)*16`. The ParoQuant grids (the four 4- and 5-bit ones) take parts (`pb1`, `pb2`); `w2a8` and `w4a8_asym` do -not, and none has a bias form. libr4d's kernels compute the same products in another order (split-K +not, and none has a bias form. + +`split_n` is the output width whose K split the call takes, when it is a row slice of a wider +linear (a rank's share of a weight whose rows do not divide among the ranks, issued as two slices). +libr4d's narrow fp8a8 and i8a8 kernels pick their K split from N alone, and the split sets the order +K partials are summed in, so a slice given the whole width sums each output as the whole linear +does and its outputs are the linear's to the bit. Absent, N. The host libraries never split K and +ignore it. libr4d's kernels compute the same products in another order (split-K partials, the activation scale applied at the store); libavx folds the scales into its decoded rows, each product rounding once where libref rounds each group's sub-sum. A `b_scale` that is not joined at these grids has no zero to read and is refused (`RAD_E_DTYPE`). libref describes none of them @@ -2094,6 +2101,12 @@ libr4d serves these at 2, 3, 4 and 8 ranks: - `all_gather` at those widths rides the same instance as the wide `all_reduce` (`ar_gather_3rank`, `_4rank`, `_8rank`). +With `row`, `all_gather`'s `y` may be the leading `world_size * row` columns of a wider buffer, and +`x` a `row`-wide window of a wider one (column views whose row pitch is whole 16-byte words): rows +are read and land at those pitches, and the rest of each row is left as it was. A linear split by +rows whose rank shares cut its scale blocks has each rank compute the whole blocks covering its +share and hand over the share's window, gathered into a tight output (arch/common's DFlash2 fc). + `min_bytes` is the byte floor under which a lossy row serves the message exactly. It is a parameter, not a library constant, because it is a property of the link: compression pays only once the transfer is bandwidth-bound, and for a decode step's few residual rows the rotate, pack and unpack diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 61e4ef8b..6eb8f1b3 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -258,8 +258,10 @@ static const RadParamSpec pGemmBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD_O("res"), OUT("y") }; +/* `split_n` is libr4d's (docs/OPS.md); accepted and ignored here. */ static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), - P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2") }; + P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"), + P_INTO("split_n") }; static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype") }; static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"), WGT("b_scale"), diff --git a/libr4d/r4d.h b/libr4d/r4d.h index d414dea5..5489e7dc 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -309,7 +309,8 @@ void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems); // rotated-6-bit void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, - long nthreads, long drain, long acq); + long nthreads, long drain, long acq, long dpitch, + long spitch); // ---- all-reduce: one-shot, push, 4 or 8 ranks over P2P ------------------------------------- // The same algorithm at width (r4d_ar_oneshot_Nrank_exact.hip). Peer arguments are in ascending @@ -343,7 +344,8 @@ void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1, long peer_flags long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, - long drain, long acq, long pub); + long drain, long acq, long pub, long dpitch, + long spitch); void r4d_ar_oneshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index aeb48aa0..f0d6ef8a 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -752,7 +752,7 @@ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - long gate, long gate_ctr); + long gate, long gate_ctr, long dpitch, long spitch); extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -761,11 +761,14 @@ extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, - long pub); + long pub, long dpitch, long spitch); -/* Not ar_setup: an all-gather's output is world_size times its input. */ +/* Not ar_setup: an all-gather's output is world_size times its input. With `row`, `y` may also be + * the leading world_size * row columns of a wider buffer and `x` a row-wide window of one + * (docs/OPS.md); `*dpitch_out` and `*spitch_out` are then their row pitches in elements, else 0. */ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, ArCall* c, - long long* row_out) { + long long* row_out, long long* dpitch_out, + long long* spitch_out) { const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); if (!in) return RAD_E_STATE; /* init did not run: a core sequencing bug */ if (in->world != ws) return RAD_E_SHAPE; /* the peer bundle is compiled for this width */ @@ -773,7 +776,6 @@ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, const RadTensor* x = r4d_opt(a, AR_X); const RadTensor* y = r4d_opt(a, AR_Y); if (!x || !y) return RAD_E_INVAL; /* the gather has no in-place form */ - if (!r4d_contig(x) || !r4d_contig(y)) return RAD_E_STRIDE; if (y->data == x->data) return RAD_E_INVAL; const long n = (long)r4d_numel(x); @@ -783,6 +785,27 @@ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, const long long row = r4d_pgeti_or(a->p, a->n_p, "row", 0); if (row < 0 || (row > 0 && (n % row || (row * in->esize) % 16))) return RAD_E_SHAPE; + /* A row-interleaved gather's [rows][world * row] may sit in the leading columns of a wider + * buffer, the pitch in whole 16-byte words: rows land at that pitch, the rest of each row is + * left alone. */ + long long dpitch = 0; + if (!r4d_contig(y)) { + const long long p = r4d_row_pitch(y); + if (row <= 0 || y->rank != 2 || p <= 0 || y->shape[1] != (int64_t)row * in->world || + (p * in->esize) % 16) + return RAD_E_STRIDE; + dpitch = p; + } + /* Likewise x may be [rows][row] read at a wider pitch: a rank's window of a row it computed + * wider (a split linear's block-aligned superset, arch/common/rad_block_dflash2.h). */ + long long spitch = 0; + if (!r4d_contig(x)) { + const long long p = r4d_row_pitch(x); + if (row <= 0 || x->rank != 2 || p <= 0 || x->shape[1] != (int64_t)row || + (p * in->esize) % 16) + return RAD_E_STRIDE; + spitch = p; + } if (((long long)n * in->esize) % 16) return RAD_E_ALIGN; if (!r4d_aligned(x->data, 16) || !r4d_aligned(y->data, 16)) return RAD_E_ALIGN; @@ -804,43 +827,46 @@ static int ar_gather_wide_setup(const RadArgs* a, int ws, const ArInst** out_in, c->acq = cfgv.acq; c->pub = cfgv.pub; *row_out = row; + *dpitch_out = dpitch; + *spitch_out = spitch; return RAD_OK; } extern "C" int r4d_rad_ar_gather_2rank(const RadArgs* a, RadStream s) { const ArInst* in = nullptr; ArCall c; - long long row = 0; - int rc = ar_gather_wide_setup(a, 2, &in, &c, &row); + long long row = 0, dpitch = 0, spitch = 0; + int rc = ar_gather_wide_setup(a, 2, &in, &c, &row, &dpitch, &spitch); if (rc != RAD_OK) return rc; R4D_TRY("ar_gather_2rank", r4d_ar_gather_2rank(in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, - c.acq)); + c.acq, (long)dpitch, (long)spitch)); return RAD_OK; } extern "C" int r4d_rad_ar_gather_3rank(const RadArgs* a, RadStream s) { const ArInst* in = nullptr; ArCall c; - long long row = 0; - int rc = ar_gather_wide_setup(a, 3, &in, &c, &row); + long long row = 0, dpitch = 0, spitch = 0; + int rc = ar_gather_wide_setup(a, 3, &in, &c, &row, &dpitch, &spitch); if (rc != RAD_OK) return rc; R4D_TRY("ar_gather_3rank", r4d_ar_gather_3rank(in->peer_scratch[0], in->peer_scratch[1], in->peer_flags[0], in->peer_flags[1], in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, - (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub)); + (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub, + (long)dpitch, (long)spitch)); return RAD_OK; } extern "C" int r4d_rad_ar_gather_4rank(const RadArgs* a, RadStream s) { const ArInst* in = nullptr; ArCall c; - long long row = 0; - int rc = ar_gather_wide_setup(a, 4, &in, &c, &row); + long long row = 0, dpitch = 0, spitch = 0; + int rc = ar_gather_wide_setup(a, 4, &in, &c, &row, &dpitch, &spitch); if (rc != RAD_OK) return rc; /* One handshake, placement after it local: the release is the one-shot's. */ const long gate = link_gate(a), early = in->host ? 0L : gate; @@ -850,15 +876,15 @@ extern "C" int r4d_rad_ar_gather_4rank(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub, - early, early ? in->gate_ctr : 0L)); + early, early ? in->gate_ctr : 0L, (long)dpitch, (long)spitch)); return early ? RAD_LINK_ENDED : RAD_OK; } extern "C" int r4d_rad_ar_gather_8rank(const RadArgs* a, RadStream s) { const ArInst* in = nullptr; ArCall c; - long long row = 0; - int rc = ar_gather_wide_setup(a, 8, &in, &c, &row); + long long row = 0, dpitch = 0, spitch = 0; + int rc = ar_gather_wide_setup(a, 8, &in, &c, &row, &dpitch, &spitch); if (rc != RAD_OK) return rc; R4D_TRY("ar_gather_8rank", r4d_ar_gather_8rank(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], @@ -869,7 +895,8 @@ extern "C" int r4d_rad_ar_gather_8rank(const RadArgs* a, RadStream s) { in->peer_flags[6], in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, - (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub)); + (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub, + (long)dpitch, (long)spitch)); return RAD_OK; } diff --git a/libr4d/r4d_ar_gather_2rank.hip b/libr4d/r4d_ar_gather_2rank.hip index 3d1461f2..fdbacfd3 100644 --- a/libr4d/r4d_ar_gather_2rank.hip +++ b/libr4d/r4d_ar_gather_2rank.hip @@ -38,11 +38,20 @@ __device__ __forceinline__ unsigned int r4d_g_load_acq(const unsigned int* p) { // // The vocab-parallel sampler's merge reads one row of gathered candidates per position at a single // row stride, which the concatenated form cannot express. Interleaving costs one division per word -// and saves a transpose launch. -__device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who) { +// and saves a transpose launch. `dp16` is the output's row pitch in words: 2 * row16 for a tight +// [rows][2][row16], more when the gathered rows are the leading columns of a wider buffer. +__device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who, int dp16) { if (row16 <= 0 || row16 >= n16) return who * n16 + k; const int m = k / row16, c = k - m * row16; - return m * (2 * row16) + who * row16 + c; + return m * dp16 + who * row16 + c; +} + +// Where word k of this rank's contribution is read: `sp16` is the input's row pitch in words, +// row16 when its rows are tight, more when they are a window of a wider row. +__device__ __forceinline__ int r4d_g_src(int k, int row16, int n16, int sp16) { + if (row16 <= 0 || row16 >= n16 || sp16 == row16) return k; + const int m = k / row16, c = k - m * row16; + return m * sp16 + c; } // Block b owns words [start,end) of the 16B-word space and drives its own flag handshake; no @@ -50,7 +59,8 @@ __device__ __forceinline__ int r4d_g_dst(int k, int row16, int n16, int who) { __global__ void r4d_ar_gather_2rank_kernel( const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, - int n16, int slot_stride16, int rank, int row16, int drain, int acq, unsigned int nbw) { + int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq, + unsigned int nbw) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe @@ -68,14 +78,20 @@ __global__ void r4d_ar_gather_2rank_kernel( { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { - int4 v0 = in4[k], v1 = in4[k + nt], v2 = in4[k + 2 * nt], v3 = in4[k + 3 * nt]; + int4 v0 = in4[r4d_g_src(k, row16, n16, sp16)], v1 = in4[r4d_g_src(k + nt, row16, n16, sp16)], + v2 = in4[r4d_g_src(k + 2 * nt, row16, n16, sp16)], + v3 = in4[r4d_g_src(k + 3 * nt, row16, n16, sp16)]; ps[k] = v0; ps[k + nt] = v1; ps[k + 2 * nt] = v2; ps[k + 3 * nt] = v3; - out4[r4d_g_dst(k, row16, n16, rank)] = v0; - out4[r4d_g_dst(k + nt, row16, n16, rank)] = v1; - out4[r4d_g_dst(k + 2 * nt, row16, n16, rank)] = v2; - out4[r4d_g_dst(k + 3 * nt, row16, n16, rank)] = v3; + out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v0; + out4[r4d_g_dst(k + nt, row16, n16, rank, dp16)] = v1; + out4[r4d_g_dst(k + 2 * nt, row16, n16, rank, dp16)] = v2; + out4[r4d_g_dst(k + 3 * nt, row16, n16, rank, dp16)] = v3; + } + for (; k < end; k += nt) { + int4 v = in4[r4d_g_src(k, row16, n16, sp16)]; + ps[k] = v; + out4[r4d_g_dst(k, row16, n16, rank, dp16)] = v; } - for (; k < end; k += nt) { int4 v = in4[k]; ps[k] = v; out4[r4d_g_dst(k, row16, n16, rank)] = v; } } // Drain modes, as in the all-reduce: order the pushes before the release flag so the peer cannot // see the flag before the data. @@ -100,19 +116,19 @@ __global__ void r4d_ar_gather_2rank_kernel( const int who = 1 - rank; int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { - out4[r4d_g_dst(k, row16, n16, who)] = ms[k]; - out4[r4d_g_dst(k + nt, row16, n16, who)] = ms[k + nt]; - out4[r4d_g_dst(k + 2 * nt, row16, n16, who)] = ms[k + 2 * nt]; - out4[r4d_g_dst(k + 3 * nt, row16, n16, who)] = ms[k + 3 * nt]; + out4[r4d_g_dst(k, row16, n16, who, dp16)] = ms[k]; + out4[r4d_g_dst(k + nt, row16, n16, who, dp16)] = ms[k + nt]; + out4[r4d_g_dst(k + 2 * nt, row16, n16, who, dp16)] = ms[k + 2 * nt]; + out4[r4d_g_dst(k + 3 * nt, row16, n16, who, dp16)] = ms[k + 3 * nt]; } - for (; k < end; k += nt) out4[r4d_g_dst(k, row16, n16, who)] = ms[k]; + for (; k < end; k += nt) out4[r4d_g_dst(k, row16, n16, who, dp16)] = ms[k]; } } void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream_i, long nblocks, - long nthreads, long drain, long acq) { + long nthreads, long drain, long acq, long dpitch, long spitch) { hipStream_t st = (hipStream_t)stream_i; const int esize = (dtype == 2) ? 4 : 2; const long nbytes = (long)n_elem * esize; @@ -126,6 +142,19 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo if (row_elems > 0 && (rowb % 16 != 0 || nbytes % rowb != 0)) throw std::runtime_error("all_gather: row is not a whole number of 16B words"); const int row16 = row_elems > 0 ? (int)(rowb / 16) : 0; + // The output's row pitch in elements, 0 for a tight [rows][2][row]: whole words, at least the + // two ranks' row. + const long dpb = (long)dpitch * esize; + if (dpitch > 0 && (row16 <= 0 || dpb % 16 != 0 || dpitch < 2 * row_elems)) + throw std::runtime_error("all_gather: the output pitch is not a whole number of 16B words " + "at least two rows wide"); + const int dp16 = dpitch > 0 ? (int)(dpb / 16) : 2 * row16; + // The input's row pitch in elements, 0 for tight rows: whole words, at least a row. + const long spb = (long)spitch * esize; + if (spitch > 0 && (row16 <= 0 || spb % 16 != 0 || spitch < row_elems)) + throw std::runtime_error("all_gather: the input pitch is not a whole number of 16B words " + "at least a row wide"); + const int sp16 = spitch > 0 ? (int)(spb / 16) : row16; int nb = (int)nblocks; if (nb < 1) nb = 1; if (nb > n16) nb = n16; @@ -139,5 +168,5 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo r4d_ar_gather_2rank_kernel<<>>( (const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, - (int)slot_stride16, (int)rank, row16, (int)drain, (int)acq, nbw); + (int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, (int)acq, nbw); } diff --git a/libr4d/r4d_ar_gather_Nrank.hip b/libr4d/r4d_ar_gather_Nrank.hip index f98e0a3f..5d27155e 100644 --- a/libr4d/r4d_ar_gather_Nrank.hip +++ b/libr4d/r4d_ar_gather_Nrank.hip @@ -32,14 +32,15 @@ extern "C" void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, - long nblocks, long nthreads, long drain, long acq, long pub); + long nblocks, long nthreads, long drain, long acq, long pub, + long dpitch, long spitch); extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - long gate, long gate_ctr); + long gate, long gate_ctr, long dpitch, long spitch); extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -48,14 +49,23 @@ extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, - long pub); + long pub, long dpitch, long spitch); // Where a rank's words land: the 2-rank r4d_g_dst generalised to WS. Named differently because two // __device__ definitions of one name in the two units would violate the ODR. -__device__ __forceinline__ int r4d_g_dst_ws(int k, int row16, int n16, int WS, int who) { +// `dp16` is the output's row pitch in words, WS * row16 when the gathered rows are tight. +__device__ __forceinline__ int r4d_g_dst_ws(int k, int row16, int n16, int who, int dp16) { if (row16 <= 0 || row16 >= n16) return who * n16 + k; const int m = k / row16, c = k - m * row16; - return m * (WS * row16) + who * row16 + c; + return m * dp16 + who * row16 + c; +} + +// Where word k of this rank's contribution is read: `sp16` is the input's row pitch in words, +// row16 when its rows are tight, more when they are a window of a wider row. +__device__ __forceinline__ int r4d_g_src_ws(int k, int row16, int n16, int sp16) { + if (row16 <= 0 || row16 >= n16 || sp16 == row16) return k; + const int m = k / row16, c = k - m * row16; + return m * sp16 + c; } // Block b owns words [start,end) of the 16B-word space and drives its own handshake; no cross-block @@ -65,8 +75,8 @@ __global__ void r4d_ar_gather_wide_kernel( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, int4* __restrict__ out4, unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, - int n16, int slot_stride16, int rank, int row16, int drain, int acq, int pub, - long long* gate, unsigned int* gate_ctr) { + int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq, + int pub, long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; // Placement holds WS source words live per output word, so the 2x unroll spills at ws=8 (same // limit as the one-shot all-reduce). @@ -95,14 +105,17 @@ __global__ void r4d_ar_gather_wide_kernel( { int k = start + tid; for (; k + 3 * nt < end; k += 4 * nt) { - const int4 v0 = in4[k], v1 = in4[k + nt], v2 = in4[k + 2 * nt], v3 = in4[k + 3 * nt]; + const int4 v0 = in4[r4d_g_src_ws(k, row16, n16, sp16)]; + const int4 v1 = in4[r4d_g_src_ws(k + nt, row16, n16, sp16)]; + const int4 v2 = in4[r4d_g_src_ws(k + 2 * nt, row16, n16, sp16)]; + const int4 v3 = in4[r4d_g_src_ws(k + 3 * nt, row16, n16, sp16)]; #pragma unroll for (int p = 0; p < NPEERS; ++p) { ps[p][k] = v0; ps[p][k + nt] = v1; ps[p][k + 2 * nt] = v2; ps[p][k + 3 * nt] = v3; } } for (; k < end; k += nt) { - const int4 v = in4[k]; + const int4 v = in4[r4d_g_src_ws(k, row16, n16, sp16)]; #pragma unroll for (int p = 0; p < NPEERS; ++p) ps[p][k] = v; } @@ -117,7 +130,7 @@ __global__ void r4d_ar_gather_wide_kernel( r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); // Place every rank's slice. Slot [parity][our rank] of our own scratch is never written, so, as - // in the all-reduce, our rank's source is the input itself and the loop is branch-free. + // in the all-reduce, our rank's source is the input itself, read at its own pitch. const int4* src[WS]; #pragma unroll for (int r = 0; r < WS; ++r) @@ -127,17 +140,19 @@ __global__ void r4d_ar_gather_wide_kernel( int k = start + tid; if (RU == 2) { for (; k + nt < end; k += 2 * nt) { + const int k0 = r4d_g_src_ws(k, row16, n16, sp16), k1 = r4d_g_src_ws(k + nt, row16, n16, sp16); #pragma unroll for (int r = 0; r < WS; ++r) { - out4[r4d_g_dst_ws(k, row16, n16, WS, r)] = src[r][k]; - out4[r4d_g_dst_ws(k + nt, row16, n16, WS, r)] = src[r][k + nt]; + out4[r4d_g_dst_ws(k, row16, n16, r, dp16)] = src[r][r == rank ? k0 : k]; + out4[r4d_g_dst_ws(k + nt, row16, n16, r, dp16)] = src[r][r == rank ? k1 : k + nt]; } } } for (; k < end; k += nt) { + const int k0 = r4d_g_src_ws(k, row16, n16, sp16); #pragma unroll for (int r = 0; r < WS; ++r) - out4[r4d_g_dst_ws(k, row16, n16, WS, r)] = src[r][k]; + out4[r4d_g_dst_ws(k, row16, n16, r, dp16)] = src[r][r == rank ? k0 : k]; } } } @@ -150,7 +165,7 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream_i, long nblocks, long nthreads, long drain, long acq, - long pub, long gate, long gate_ctr) { + long pub, long gate, long gate_ctr, long dpitch, long spitch) { constexpr int NPEERS = WS - 1; static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound"); @@ -173,6 +188,20 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla if (row_elems > 0 && (rowb % 16 != 0 || nbytes % rowb != 0)) throw std::runtime_error("all_gather: row is not a whole number of 16B words"); const int row16 = row_elems > 0 ? (int)(rowb / 16) : 0; + // The output's row pitch in elements, 0 for a tight [rows][WS][row]: whole words, at least the + // WS ranks' row (the gathered rows as the leading columns of a wider buffer). + const long dpb = (long)dpitch * esize; + if (dpitch > 0 && (row16 <= 0 || dpb % 16 != 0 || dpitch < (long)WS * row_elems)) + throw std::runtime_error("all_gather: the output pitch is not a whole number of 16B words " + "at least " + std::to_string(WS) + " rows wide"); + const int dp16 = dpitch > 0 ? (int)(dpb / 16) : WS * row16; + // The input's row pitch in elements, 0 for tight rows: whole words, at least a row (a rank's + // window of a wider row). + const long spb = (long)spitch * esize; + if (spitch > 0 && (row16 <= 0 || spb % 16 != 0 || spitch < row_elems)) + throw std::runtime_error("all_gather: the input pitch is not a whole number of 16B words " + "at least a row wide"); + const int sp16 = spitch > 0 ? (int)(spb / 16) : row16; int nb = (int)nblocks; if (nb < 1) nb = R4D_AR_NB_DESIGN; @@ -209,8 +238,8 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla hipStream_t st = (hipStream_t)stream_i; r4d_ar_gather_wide_kernel<<>>( (const int4*)inp, peers, (const int4*)my_scratch, (int4*)out, (unsigned int*)my_flags, - (unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, row16, (int)drain, (int)acq, - (int)pub, (long long*)gate, (unsigned int*)gate_ctr); + (unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, + (int)acq, (int)pub, (long long*)gate, (unsigned int*)gate_ctr); } /* Three ranks, e.g. Qwen3.8-Flash-Next padded to 36 heads / 3 KV heads (docs/TP3.md). */ @@ -218,13 +247,14 @@ void r4d_ar_gather_3rank(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, - long nblocks, long nthreads, long drain, long acq, long pub) { + long nblocks, long nthreads, long drain, long acq, long pub, long dpitch, + long spitch) { const long ps[2] = {peer_scratch0, peer_scratch1}; const long pf[2] = {peer_flags0, peer_flags1}; /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_gather_wide_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub, - 0L, 0L); + 0L, 0L, dpitch, spitch); } void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -232,12 +262,12 @@ void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scrat long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, long pub, long gate, - long gate_ctr) { + long gate_ctr, long dpitch, long spitch) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_gather_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub, - gate, gate_ctr); + gate, gate_ctr, dpitch, spitch); } void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -247,7 +277,7 @@ void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scrat long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, - long pub) { + long pub, long dpitch, long spitch) { const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3, peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, @@ -255,5 +285,5 @@ void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scrat /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_gather_wide_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub, - 0L, 0L); + 0L, 0L, dpitch, spitch); } diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index 970ed3b3..e0faee96 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -931,7 +931,7 @@ extern "C" int r4d_gemm_fp8a8_block(void) { return (int)kBlock; } static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, RadStream stream, - bool i8 = false); + bool i8 = false, int split_n = 0); extern "C" int r4d_gemm_fp8a8_nt_m16(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, @@ -961,12 +961,21 @@ extern "C" void r4d_gemm_fp8a8_pin_nt(int nt) { // Bytes of f32 scratch one r4d_gemm_fp8a8_nt_m16 call needs, or 0 when it will not split. The // caller may pass more, or none (the launch then runs unsplit: correct but slow, and unreported). // The bound is max_m() so the query and the band cannot drift apart. -extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) { +// +// `split_n` (0: N) is the width the split is chosen for. The split depends on N alone, and it +// fixes the order K partials are summed in, so a row slice of a wider linear (N rows of a +// split_n-row weight) passes the whole width to sum each output as the whole linear does: the +// slice's outputs are then the linear's to the bit. +static long m16_scratch(int M, int K, int N, int split_n) { if (M <= 0 || K <= 0 || N <= 0 || M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0; uint32_t ck = 0; - const uint32_t k2 = narrow_ksplit((uint32_t)N, (uint32_t)K, (uint32_t)M, &ck); + const uint32_t k2 = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K, + (uint32_t)M, &ck); return k2 > 1 ? (long)k2 * M * N * (long)sizeof(float) : 0; } +extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) { + return m16_scratch(M, K, N, 0); +} // C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T, M <= 64. // @@ -976,10 +985,12 @@ extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) { // ws [ceil(N/128)][ceil(K/128)] bf16, `sw_ld` elements a row (0 = ceil(K/128)) // c [M][N] bf16 // -// Returns 0, or a negative code for a shape it does not serve. `scratch` may be 0. +// Returns 0, or a negative code for a shape it does not serve. `scratch` may be 0. `split_n` is +// r4d_gemm_fp8a8_nt_m16_scratch's. static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, - long scratch, long scratch_bytes, RadStream stream, bool i8) { + long scratch, long scratch_bytes, RadStream stream, bool i8, + int split_n) { int emit_rc = RAD_OK; if (!a || !ascale || !wq || !ws || !c) return -1; if (M <= 0 || K <= 0 || N <= 0) return -2; @@ -1000,7 +1011,8 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, const uint32_t gx = ((uint32_t)N + fm - 1) / fm; uint32_t ck = 0; - uint32_t ksplit = narrow_ksplit((uint32_t)N, (uint32_t)K, (uint32_t)M, &ck); + uint32_t ksplit = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K, + (uint32_t)M, &ck); const long need = ksplit > 1 ? (long)ksplit * M * N * (long)sizeof(float) : 0; if (need && (!scratch || scratch_bytes < need)) { ksplit = 1; ck = 0; } @@ -1260,10 +1272,10 @@ static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, // The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h. extern "C" int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs* a) { const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0), - K = r4d_geti_or(a, "K", 0); + K = r4d_geti_or(a, "K", 0), sn = r4d_geti_or(a, "split_n", 0); if (M < 1 || N < 1 || K < 1) return 0; if (M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0; - return (int64_t)r4d_gemm_fp8a8_nt_m16_scratch((int)M, (int)K, (int)N); + return (int64_t)m16_scratch((int)M, (int)K, (int)N, (int)sn); } extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) { @@ -1276,7 +1288,8 @@ extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) { const int e = gemm_fp8a8_nt_m16_emit( r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld, - (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream); + (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, false, + (int)r4d_geti_or(a, "split_n", 0)); return e == 0 ? RAD_OK : RAD_E_SHAPE; } @@ -1390,7 +1403,8 @@ extern "C" int r4d_rad_gemm_i8a8_m16(const RadArgs* a, RadStream stream) { const int e = gemm_fp8a8_nt_m16_emit( r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld, - (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, true); + (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, true, + (int)r4d_geti_or(a, "split_n", 0)); return e == 0 ? RAD_OK : RAD_E_SHAPE; } diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index d64d8665..9cccf694 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -736,6 +736,9 @@ static const RadParamSpec pGemmNtQ[] = { { "dtype", RAD_P_STR, RAD_REQUIRED }, { "pb1", RAD_P_INT, RAD_OPTIONAL }, { "pb2", RAD_P_INT, RAD_OPTIONAL }, + /* The width whose K split a row slice of a wider linear takes (docs/OPS.md); only the narrow + * fp8a8 / i8a8 rows split K by N, and they read it. */ + { "split_n", RAD_P_INT, RAD_OPTIONAL }, }; /* docs/OPS.md's `gemm_nt_q` is `a`, `a_scale`, `b`w, `b_scale`w -> `y`. Two of libr4d's six * quantised GEMMs need a seventh operand. RadLayout can declare aux streams beside a weight, but diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 7b3ac961..2f204341 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -11647,6 +11647,62 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { why.empty(), why); } + /* A row slice of this linear issued with split_n = N (DenseFP8::declare_slice: a split + * fc's share and its tail) must give each of its rows exactly as the whole GEMM does, + * whatever K split its own width would pick: half the rows, and the last 128 (which + * alone would split K the most). The slice's planes are quantised from its own rows, + * which on whole 128-row blocks are the whole weight's codes and scales. */ + if (N >= 256) { + const int64_t cut = (N / 2) / 128 * 128; + std::string why; + const std::pair slices[] = { { 0, cut }, { N - 128, N } }; + for (const auto& sl : slices) { + const int64_t lo = sl.first, hi = sl.second, Ns = hi - lo; + std::vector wsl(wf.begin() + lo * K, wf.begin() + hi * K); + const Planes psl = fp8_block_planes(wsl, Ns, K); + std::vector lps = { PI("N", Ns), PI("K", K), PI("group", 128) }; + std::vector qsl; + if (stored(nr, lps, 2, psl, { "codes" }, &qsl) != RAD_OK) { + why = "the slice's layout hook refused"; + break; + } + void* d_wsl = dalloc((size_t)Ns * K); + void* d_ysl = dalloc((size_t)M * Ns * 2); + if (!d_wsl || !d_ysl) { why = "hipMalloc failed"; break; } + st_memcpy(d_wsl, qsl.data(), qsl.size(), hipMemcpyHostToDevice); + std::vector tsl = { + T(d_q, RAD_F8E4M3, { M, K }), T(d_qs, RAD_F32, { M, sk }), + T(d_wsl, RAD_F8E4M3, { Ns, K }), + T((char*)d_s + (size_t)(lo / 128) * (size_t)sk * 2, RAD_BF16, + { Ns / 128, sk }), + T(d_ysl, RAD_BF16, { M, Ns }), T(nullptr, RAD_F32, { 1 }), + T(nullptr, RAD_U8, { 1 }), + }; + absent(tsl[5]); absent(tsl[6]); + std::vector pss = { + PI("M", M), PI("N", Ns), PI("K", K), PI("group", 128), + PS("dtype", "fp8a8"), PI("split_n", N), + }; + st_memset(d_ysl, 0, (size_t)M * Ns * 2); + run_case(nr, tsl, pss); + std::vector ys((size_t)M * Ns); + st_memcpy(ys.data(), d_ysl, ys.size() * 2, hipMemcpyDeviceToHost); + for (int64_t m = 0; m < M && why.empty(); ++m) + for (int64_t r = 0; r < Ns; ++r) + if (ys[(size_t)(m * Ns + r)] != got[(size_t)(m * N + lo + r)]) { + why = "rows [" + std::to_string((long long)lo) + ", " + + std::to_string((long long)hi) + ") differ at m " + + std::to_string((long long)m) + " row " + + std::to_string((long long)(lo + r)); + break; + } + if (!why.empty()) break; + } + ok((std::string("gemm_fp8a8_nt_m16's row slices given split_n are the whole GEMM's " + "rows, M ") + std::to_string((long long)M)).c_str(), + why.empty(), why); + } + /* ---- ...and with the gate and the quantiser folded into its epilogue ------------- * * Byte equality: the engine substitutes the fold for the pair (this GEMM's bf16 @@ -21025,6 +21081,12 @@ struct ArThread { /* Ranks in the collective: 2, or 3 for the wide family at a width that is not a power of * two. */ int world = 2; + /* The all-gather's output row pitch in elements, 0 for a tight [rows][world][row]; more lands + * the gathered rows in the leading columns of a wider buffer. */ + int64_t pitch = 0; + /* Its input row pitch, 0 for tight rows; more reads each row's first `row_elems` out of a wider + * row whose other columns hold junk. */ + int64_t spitch = 0; }; static void ar_worker(ArThread* t) { @@ -21207,8 +21269,10 @@ static void gather_worker(ArThread* t) { void* in = nullptr; void* out = nullptr; + const int64_t rows = t->pitch > 0 ? t->numel / t->row_elems : 0; + const int64_t out_n = t->pitch > 0 ? rows * t->pitch : t->numel * t->world; if (hipMalloc(&in, (size_t)t->numel * 4) != hipSuccess) { t->rc_launch = RAD_E_NOMEM; return; } - if (hipMalloc(&out, (size_t)t->numel * 4 * t->world) != hipSuccess) { t->rc_launch = RAD_E_NOMEM; return; } + if (hipMalloc(&out, (size_t)out_n * 4) != hipSuccess) { t->rc_launch = RAD_E_NOMEM; return; } std::vector h((size_t)t->numel); for (int64_t i = 0; i < t->numel; i += 2) { @@ -21216,10 +21280,29 @@ static void gather_worker(ArThread* t) { const float v = (float)(t->rank + 1) * 0.5f + (float)i; /* its logit */ std::memcpy(&h[(size_t)i + 1], &v, 4); } - st_memcpy(in, h.data(), h.size() * 4, hipMemcpyHostToDevice); - st_memset(out, 0xAB, (size_t)t->numel * 4 * t->world); /* marks untouched slices */ + if (t->spitch > 0) { /* each row's contribution at the front of a wider row of junk */ + const int64_t srows = t->numel / t->row_elems; + std::vector hp((size_t)(srows * t->spitch), 0xCDCDCDCDu); + for (int64_t m = 0; m < srows; ++m) + std::memcpy(&hp[(size_t)(m * t->spitch)], &h[(size_t)(m * t->row_elems)], + (size_t)t->row_elems * 4); + st_free(in); + if (hipMalloc(&in, hp.size() * 4) != hipSuccess) { t->rc_launch = RAD_E_NOMEM; return; } + st_memcpy(in, hp.data(), hp.size() * 4, hipMemcpyHostToDevice); + } else { + st_memcpy(in, h.data(), h.size() * 4, hipMemcpyHostToDevice); + } + st_memset(out, 0xAB, (size_t)out_n * 4); /* marks untouched slices */ RadTensor ts[2] = { T(in, RAD_F32, { t->numel }), T(out, RAD_F32, { t->numel * t->world }) }; + if (t->pitch > 0) { /* [rows][world * row], the leading columns of rows `pitch` apart */ + ts[1] = T(out, RAD_F32, { rows, t->world * t->row_elems }); + ts[1].stride[0] = t->pitch; + } + if (t->spitch > 0) { /* [rows][row], read `spitch` apart */ + ts[0] = T(in, RAD_F32, { t->numel / t->row_elems, t->row_elems }); + ts[0].stride[0] = t->spitch; + } RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts; a.n_t = 2; @@ -21230,7 +21313,7 @@ static void gather_worker(ArThread* t) { t->rc_launch = t->row->launch(&a, nullptr); st_stream_sync(nullptr); - t->out.assign((size_t)t->numel * t->world, 0.0f); + t->out.assign((size_t)out_n, 0.0f); st_memcpy(t->out.data(), out, t->out.size() * 4, hipMemcpyDeviceToHost); st_free(in); st_free(out); @@ -22310,6 +22393,86 @@ static void gather_wide_rank(const Plugin& pl, const std::vector& devs, con bad == 0, std::to_string(bad) + " words wrong, " + std::to_string(bad_id) + " of them token ids"); if (row->fini) for (ArThread& a : t) if (a.inst) row->fini(a.inst); + + /* The same rows landed in the leading columns of a wider buffer, as a row-sharded linear whose + * width does not divide among the ranks gathers into the front of its full output row: 64 + * columns (four words) past world * row, which must keep their marker. */ + { + const int64_t pitch = W * rowe + 64; + std::vector tp((size_t)W); + std::vector thp; + for (int r = 0; r < W; ++r) { + tp[(size_t)r] = ArThread{ row, r, devs[(size_t)r], numel }; + tp[(size_t)r].world = W; + tp[(size_t)r].row_elems = rowe; + tp[(size_t)r].pitch = pitch; + thp.emplace_back(gather_worker, &tp[(size_t)r]); + } + for (std::thread& x : thp) x.join(); + bool upp = true; + std::string rcp; + for (const ArThread& a : tp) { + upp = upp && a.rc_init == RAD_OK && a.rc_launch == RAD_OK; + rcp += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; + } + int64_t badp = 0, clobbered = 0; + if (upp) + for (const ArThread& a : tp) + for (int64_t m = 0; m < nrows; ++m) { + for (int r = 0; r < W; ++r) + for (int64_t j = 0; j < rowe; ++j) { + uint32_t got; + std::memcpy(&got, &a.out[(size_t)(m * pitch + r * rowe + j)], 4); + if (got != sent(r, m * rowe + j)) ++badp; + } + for (int64_t j = W * rowe; j < pitch; ++j) { + uint32_t got; + std::memcpy(&got, &a.out[(size_t)(m * pitch + j)], 4); + if (got != 0xABABABABu) ++clobbered; + } + } + ok((w + "-rank all-gather lands its rows at a wider output pitch, the rest untouched").c_str(), + upp && badp == 0 && clobbered == 0, + upp ? std::to_string(badp) + " words wrong, " + std::to_string(clobbered) + + " words past the rows overwritten" + : "init/launch rc " + rcp); + if (row->fini) for (ArThread& a : tp) if (a.inst) row->fini(a.inst); + } + + /* And each rank's rows read out of a wider input row, as a split linear's rank hands over its + * window of the block-aligned rows it computed: the junk around the window must not travel. */ + { + const int64_t spitch = rowe + 64; + std::vector ts2((size_t)W); + std::vector ths; + for (int r = 0; r < W; ++r) { + ts2[(size_t)r] = ArThread{ row, r, devs[(size_t)r], numel }; + ts2[(size_t)r].world = W; + ts2[(size_t)r].row_elems = rowe; + ts2[(size_t)r].spitch = spitch; + ths.emplace_back(gather_worker, &ts2[(size_t)r]); + } + for (std::thread& x : ths) x.join(); + bool ups = true; + std::string rcs2; + for (const ArThread& a : ts2) { + ups = ups && a.rc_init == RAD_OK && a.rc_launch == RAD_OK; + rcs2 += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; + } + int64_t bads = 0; + if (ups) + for (const ArThread& a : ts2) + for (int64_t m = 0; m < nrows; ++m) + for (int r = 0; r < W; ++r) + for (int64_t j = 0; j < rowe; ++j) { + uint32_t got; + std::memcpy(&got, &a.out[(size_t)(m * W * rowe + r * rowe + j)], 4); + if (got != sent(r, m * rowe + j)) ++bads; + } + ok((w + "-rank all-gather reads each rank's rows at a wider input pitch").c_str(), + ups && bads == 0, ups ? std::to_string(bads) + " words wrong" : "init/launch rc " + rcs2); + if (row->fini) for (ArThread& a : ts2) if (a.inst) row->fini(a.inst); + } ok((w + "-rank all-gather fini ran").c_str(), true); } diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 090b02e4..f7da5fa3 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -317,8 +317,10 @@ static const RadParamSpec pGemmBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_ static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD_O("res"), OUT("y") }; +/* `split_n` is libr4d's (docs/OPS.md): ref never splits K, so it accepts and ignores it. */ static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), - P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2") }; + P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"), + P_INTO("split_n") }; /* The bias form has no parts (`pb1`/`pb2`); only the plain product supports them. */ static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype") }; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 13d38a5a..0f93a880 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -4722,15 +4722,19 @@ struct G431Df { /* The trunk at w4a8 as the -df recipe makes it, the drafter's linears on one 8-bit grid -- the * E4M3 one (block fp8) or the int8 one (w8a8) -- and, with `head`, the table's 8-bit copy in the * same grid. The drafter's keys come FIRST: the fake answers the first key a name contains, and - * `attn_q.` is in `dflash.blk.0.attn_q.weight` too. */ -void g431df_encs(RadBuilder& b, bool i8, bool head) { + * `attn_q.` is in `dflash.blk.0.attn_q.weight` too. With `fused`, the trunk's q, k and v are one + * linear, as a recipe naming `blk.*.attn_qkv.weight` converts them. */ +void g431df_encs(RadBuilder& b, bool i8, bool head, bool fused = false) { const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, 128, 128); const RadEncoding q8 = rad_enc_affine(RAD_I8, RAD_F16, 1, 128); const RadEncoding& d = i8 ? q8 : fp8; b.encs = { { "dflash.fc.", d }, { "dflash.blk.", d } }; if (head) b.encs.push_back({ "dflash.draft_head.", d }); - for (const char* s : { "attn_q.", "attn_k.", "attn_v.", "attn_o.", "ffn_gate_up.", "ffn_down." }) + if (fused) b.encs.push_back({ "attn_qkv.", w4 }); + else + for (const char* s : { "attn_q.", "attn_k.", "attn_v." }) b.encs.push_back({ s, w4 }); + for (const char* s : { "attn_o.", "ffn_gate_up.", "ffn_down." }) b.encs.push_back({ s, w4 }); } @@ -5080,6 +5084,140 @@ TEST(gemma4_31b_dflash_at_four_ranks) { } } +/* The 31B's prefill in two slices (gemma4_bf16, trunk_overlap). The order and the work: every + * trunk reduction rides lane 1 behind its producer and ahead of its consumer and nothing else does; + * no two issues on different lanes reach the same rows unordered (`h` carries both reductions); the + * cut leaves both slices at least 512 rows; and the slices issue exactly the rows the whole step + * issues, the drafter's taps a slice each. Only `h` is taken out of the arena's sharing. A step + * under two slices, and a decode step, run whole with their reductions on lane 0. At two ranks the + * slices take the plain junctions, the whole step the ones with the all-reduce folded in. */ +TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_second_lane) { + G431Df f; + const RadModelMeta meta = f.meta(); + const int64_t E = 5376, L = 12; + for (int world : { 4, 2 }) { + auto model = [&](RadBuilder& b, bool lossy) { + g431df_encs(b, false, true); + RadBuildCtx ctx = build_ctx(0, world); + ctx.max_tok = 4096; + ctx.max_spec = 15; + if (lossy) ctx.tp_wire_lossy = 1; /* nothing shows a slice its bits on that wire */ + return gemma4_bf16::declare(&b, &meta, &ctx); + }; + auto run = [&](RadBuilder& b, RadCtx& c, RadBatch& batch) { + c.b = &b; c.rank = 0; c.world = world; c.batch = &batch; + gemma4_bf16::step(&c, &batch); + }; + + struct Case { int64_t T, cut; }; + for (const Case k : { Case{4096, 2048}, Case{1100, 512}, Case{1024, 512}, Case{1023, 0} }) { + const int32_t out[1] = { (int32_t)(k.T - 1) }; + RadBuilder b; + CHECK_OK(model(b, false)); + CHECK(noted(b, "prefill overlap: a step of 1024 rows or more runs as two slices")); + REQUIRE(b.concurrent.size() == 1); + CHECK_EQ(b.concurrent[0], (rad_buf)buf_named(b, "h")); + RadBatch batch = one_prompt(k.T, out); + RadCtx c; + run(b, c, batch); + CHECK(c.step_fail.empty()); + CHECK_EQ(c.lane, 0); + CHECK_EQ(races(b, c), 0); + + std::vector lane1; + int other1 = 0; + for (const auto& i : c.issues) { + if (i.lane != 1) continue; + const RecOp* o = b.op_of(i.op); + REQUIRE(o != nullptr); + if (o->op == "all_reduce") lane1.push_back(i.n); + else ++other1; + } + CHECK_EQ(other1, 0); + if (k.cut == 0) { + CHECK(lane1.empty()); + } else { + REQUIRE(lane1.size() == (size_t)(4 * L)); + for (int64_t l = 0; l < L; ++l) { + CHECK_EQ(lane1[4 * l + 0], k.cut * E); /* attention, slice A */ + CHECK_EQ(lane1[4 * l + 1], (k.T - k.cut) * E); /* attention, slice B */ + CHECK_EQ(lane1[4 * l + 2], k.cut * E); /* feed-forward, slice A */ + CHECK_EQ(lane1[4 * l + 3], (k.T - k.cut) * E); /* feed-forward, slice B */ + } + CHECK_EQ(count_issued(issued_ops(b, c), "ar_rmsnorm_quant_i8"), 0); + } + + /* The whole step, on the lossy wire: the same rows by op -- every junction, GEMM and + * quantiser over the same rows, the reductions over the same elements. */ + RadBuilder w; + CHECK_OK(model(w, true)); + CHECK(noted(w, "prefill overlap: off (the lossy all-reduce wire)")); + CHECK(w.concurrent.empty()); + RadBatch wbatch = one_prompt(k.T, out); + RadCtx wc; + run(w, wc, wbatch); + CHECK(wc.step_fail.empty()); + for (const auto& i : wc.issues) CHECK_EQ(i.lane, 0); + std::map sliced = rows_by_op(b, c, k.T), whole = rows_by_op(w, wc, k.T); + if (world == 2 && k.cut == 0) { + /* At two ranks on the exact wire a step that runs whole folds all but two of its + * reductions -- the embedding's and the last layer's feed-forward -- into its + * 2L - 1 junctions; the lossy wire folds none. */ + CHECK_EQ(sliced["ar_rmsnorm_quant_i8"], (2 * L - 1) * k.T); + sliced.erase("ar_rmsnorm_quant_i8"); + sliced["all_reduce"] += (2 * L - 1) * k.T * E; + sliced["rmsnorm_quant_i8"] += (2 * L - 1) * k.T; + } + CHECK(sliced == whole); + CHECK_EQ((int)ns_of(b, c, "cast").size(), k.cut ? 6 : 3); /* three taps, a slice each */ + } + + /* a decode step runs whole: every reduction on lane 0, nothing on lane 1 */ + RadBuilder b; + CHECK_OK(model(b, false)); + RadBatch d = decode_batch(); + RadCtx c; + run(b, c, d); + CHECK(c.step_fail.empty()); + CHECK(c.joins.empty()); + for (const auto& i : c.issues) CHECK_EQ(i.lane, 0); + /* folded where the plugin declares the fold at this rank count (two ranks; four with the + * four-rank junction), every junction but the last layer's feed-forward one */ + bool fold = false; + for (const auto& o : b.ops) fold = fold || o.op == "ar_rmsnorm_quant_i8"; + CHECK(fold || world == 4); + CHECK_EQ(count_issued(issued_ops(b, c), "ar_rmsnorm_quant_i8"), fold ? 2 * (int)L - 1 : 0); + } + + /* the overlap needs the fused junctions: a bf16 trunk keeps its chain and runs whole */ + RadBuilder b; + RadModelMeta plain = gemma4_meta(); + RadBuildCtx ctx = build_ctx(0, 4); + ctx.max_tok = 4096; + CHECK_OK(gemma4_bf16::declare(&b, &plain, &ctx)); + CHECK(noted(b, "prefill overlap: off (the residual junctions are not fused)")); + CHECK(b.concurrent.empty()); + + /* and the switch: every step whole, nothing on the second lane */ + setenv("RADIANCE_GEMMA4_OVERLAP", "0", 1); + RadBuilder sw; + g431df_encs(sw, false, true); + RadBuildCtx sctx = build_ctx(0, 4); + sctx.max_tok = 4096; + sctx.max_spec = 15; + const int rc = gemma4_bf16::declare(&sw, &meta, &sctx); + unsetenv("RADIANCE_GEMMA4_OVERLAP"); + CHECK_OK(rc); + CHECK(noted(sw, "prefill overlap: off (RADIANCE_GEMMA4_OVERLAP=0)")); + CHECK(sw.concurrent.empty()); + const int32_t out[1] = { 4095 }; + RadBatch big = one_prompt(4096, out); + RadCtx sc; sc.b = &sw; sc.rank = 0; sc.world = 4; sc.batch = &big; + gemma4_bf16::step(&sc, &big); + CHECK(sc.step_fail.empty()); + for (const auto& i : sc.issues) CHECK_EQ(i.lane, 0); +} + /* Where no loaded library declares libr4d's fused ops (a CPU-only build, where rad-convert and the * host backend run), asking for one is an error, so the 31B with its DFlash drafter asks first and * declares the chains: the junctions, the attention prologue, the gated quantiser, the folded @@ -5121,23 +5259,26 @@ TEST(gemma4_31b_without_libr4d_declares_the_chains_and_asks_for_no_undeclared_op * passes behind it. The lint holds the buffers each pass reads to what an earlier op of the step * wrote and the planner kept alive, across the passes, so a tap whose plane the planner let another * buffer share, or a drafter buffer read after its arena slot was reused, fails here. Eight - * sequences at a block of 16 is 128 query rows, past every fused band the drafter has. */ + * sequences at a block of 16 is 128 query rows, past every fused band the drafter has. Both trunk + * layouts: q, k and v apart, and as one linear, where a one-row decode reads q in the row and a + * taller step copies it out. */ TEST(gemma4_31b_steps_lint_clean_with_a_dflash_drafter) { G431Df f; const RadModelMeta meta = f.meta(); + for (int fused = 0; fused < 2; ++fused) for (int i8 = 0; i8 < 2; ++i8) for (int world : { 1, 2, 4 }) for (int rank : { 0, world - 1 }) { if (world == 1 && rank > 0) continue; RadBuilder b; - g431df_encs(b, i8 == 1, true); + g431df_encs(b, i8 == 1, true, fused == 1); RadBuildCtx ctx = build_ctx(rank, world); ctx.max_tok = 2048; ctx.max_spec = 15; REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); REQUIRE_EQ((int)b.drafter.kind, (int)RAD_DRAFT_BLOCK); - for (const auto& k : { kit(b, { 1, 1, 1 }, {}), kit(b, { 8, 1 }, { 5 }), - kit(b, {}, { 1500 }) }) { + for (const auto& k : { kit(b, { 1 }, {}), kit(b, { 1, 1, 1 }, {}), + kit(b, { 8, 1 }, { 5 }), kit(b, {}, { 1500 }) }) { const auto v = run_passes(b, gemma4_bf16::step, { k.get() }, rank, world); CHECK_PASSES(b, v); } @@ -5152,6 +5293,304 @@ TEST(gemma4_31b_steps_lint_clean_with_a_dflash_drafter) { } } +/* ============ gemma4 31B + DFlash2: RedHatAI's speculators-format drafter ============ */ +namespace { +/* The 31B fixture with a DFlash2 drafter in vLLM's speculators layout, as rad-convert merges + * RedHatAI/gemma-4-31B-it-speculator.dflash2's config.json: the speculator's own keys at the top of + * `draft.`, the decoder layers' config under `draft.transformer_layer_config.`, booleans as 1/0. + * Taps at aux ids 1 5 9 (the residual entering those layers) for the fixture's twelve layers. */ +struct G431Df2 { + std::vector keys, vals; + G431Df2() { + keys.assign(std::begin(k_gem4_keys), std::end(k_gem4_keys)); + vals.assign(std::begin(k_gem4_vals), std::end(k_gem4_vals)); + const char* kv[][2] = { + { "draft.architectures", "[\"DFlash2DraftModel\"]" }, + { "draft.speculators_model_type", "dflash2" }, + { "draft.block_size", "8" }, + { "draft.mask_token_id", "4" }, + { "draft.aux_hidden_state_layer_ids", "[1, 5, 9]" }, + { "draft.selector_rank", "256" }, + { "draft.selector_top_k", "16" }, + { "draft.conv_kernel_size", "2" }, + { "draft.conv_group_size", "16" }, + { "draft.sample_from_anchor", "0" }, + { "draft.sliding_window_non_causal", "1" }, + { "draft.draft_vocab_size", "262144" }, + { "draft.transformer_layer_config.num_hidden_layers", "5" }, + { "draft.transformer_layer_config.head_dim", "256" }, + { "draft.transformer_layer_config.num_attention_heads", "32" }, + { "draft.transformer_layer_config.num_key_value_heads", "16" }, + { "draft.transformer_layer_config.intermediate_size", "21504" }, + { "draft.transformer_layer_config.rms_norm_eps", "1e-06" }, + { "draft.transformer_layer_config.rope_parameters.rope_theta", "10000.0" }, + { "draft.transformer_layer_config.hidden_size", "5376" }, + { "draft.transformer_layer_config.vocab_size", "262144" }, + { "draft.transformer_layer_config.hidden_act", "silu" }, + { "draft.transformer_layer_config.sliding_window", "2048" }, + { "draft.transformer_layer_config.use_sliding_window", "1" }, + { "draft.transformer_layer_config.layer_types", + "[\"sliding_attention\", \"sliding_attention\", \"sliding_attention\", " + "\"sliding_attention\", \"sliding_attention\"]" }, + }; + for (const auto& p : kv) { keys.push_back(p[0]); vals.push_back(p[1]); } + } + RadModelMeta meta() const { + RadModelMeta m = gemma4_meta(); + m.n_kv = (int)keys.size(); + m.kv_key = keys.data(); + m.kv_val = vals.data(); + return m; + } +}; + +/* The -df2 recipe's grids: the drafter's linears at block fp8, its head copy int8 (or, without + * `head8`, no 8-bit encoding, which leaves the 2-bit grid), and the trunk at w4a8 with q|k|v fused. */ +void g431df2_encs(RadBuilder& b, bool head8) { + g431df_encs(b, false, false, true); + if (head8) b.encs.insert(b.encs.begin(), { "dflash.draft_head.", rad_enc_affine(RAD_I8, RAD_F16, 1, 128) }); +} +} /* namespace */ + +/* The 31B declares RedHatAI's DFlash2 drafter as a block drafter past its trunk, read from the + * speculators layout: depth 7 (block 8, the anchor predicting nothing), mask 4, every layer on a + * 2048-token window, non-causal, its own windowed KV group of 16 kv heads x 256, the taps on the + * layers BEFORE the aux ids (1 5 9 -> 0 4 8), the trunk's table read unscaled, and its head on the + * 8-bit copy, the candidates merged across ranks where the head is vocab-sharded. */ +TEST(gemma4_31b_declares_redhats_dflash2_from_the_speculators_layout) { + G431Df2 f; + const RadModelMeta meta = f.meta(); + RadBuildCtx pc = build_ctx(); + pc.max_spec = 7; + int taps[8] = {}; + CHECK_EQ(gemma4::dflash2_taps(&meta, &pc, 12, taps, 8), 3); + CHECK_EQ(taps[0], 0); + CHECK_EQ(taps[1], 4); + CHECK_EQ(taps[2], 8); + RadArchProbe p{}; + CHECK_OK(gemma4_bf16::probe(&meta, &p)); + CHECK_EQ(p.draft_depth, 7); + CHECK_EQ(p.draft_depth_fixed, 1); + + for (int world : { 1, 4 }) + for (int head8 = 0; head8 < 2; ++head8) { + RadBuilder b; + g431df2_encs(b, head8 == 1); + RadBuildCtx ctx = build_ctx(0, world); + ctx.max_spec = 7; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + + CHECK_EQ(b.drafter_name, std::string("dflash2")); + CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_BLOCK); + CHECK_EQ(b.drafter.depth, 7); + CHECK_EQ((int)b.drafter.block, 8); + CHECK_EQ(b.drafter.mask_token, 4); + CHECK_EQ(b.drafter.window, 2048); + CHECK_EQ(b.drafter.proposal, (rad_buf)buf_named(b, "dflash_tokens")); + + const rad_kvgroup kvd = kv_named(b, "kv_draft"); + REQUIRE(kvd != 0); + CHECK_EQ((int)b.kv_groups[kvd - 1].d.kind, (int)RAD_KV_WINDOW); + CHECK_EQ(b.kv_groups[kvd - 1].d.head_dim, 256); + CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 16 / world); + + const int src = buf_named(b, "dflash_src"); + REQUIRE(src > 0); + CHECK_EQ(b.bufs[src - 1].d.shape[1], 3 * 5376); + + /* attention: head 256, gqa 2, non-causal, the window */ + int n_attn = 0; + for (const auto& o : b.ops) + if (o.op == "attn_paged" && pint(&o, "head_dim") == 256 && pint(&o, "window") == 2048 && + pint(&o, "causal") == 0) { + ++n_attn; + CHECK_EQ(pint(&o, "gqa"), 2); + } + CHECK_EQ(n_attn, 1); + + /* the drafter's lookup reads the trunk's table without Gemma's scale */ + const RecOp* te = find_op(b, "embed_lookup", 0); + const RecOp* de = find_op(b, "embed_lookup", 1); + REQUIRE(te != nullptr && de != nullptr); + CHECK(te->w == de->w); + CHECK_NEAR(pflt(te, "mult"), 73.5, 1e-9); + CHECK(param(de, "mult") == nullptr); + + /* the head: 8-bit where the copy is int8, else the 2-bit grid; merged across ranks */ + bool head_seen = false; + for (const auto& o : b.ops) + if (o.op == "gemm_nt_q" && pint(&o, "K") == 5376 && pint(&o, "N") == 262144 / world) { + head_seen = true; + CHECK_EQ(pstr(&o, "dtype"), std::string(head8 ? "w8a8" : "w2a8")); + } + CHECK(head_seen); + CHECK_EQ(count_op(b, "row_topk_merge"), world > 1 ? 1 : 0); + CHECK_EQ(count_op(b, "dflash_select"), 1); + } +} + +/* Every engine step with RedHatAI's DFlash2 behind the trunk lints clean at one, two and four ranks: + * decode, a mixed step, a prefill chunk, and a verify step with the drafter's context and query + * passes behind it (block 8). */ +TEST(gemma4_31b_steps_lint_clean_with_a_dflash2_drafter) { + G431Df2 f; + const RadModelMeta meta = f.meta(); + for (int world : { 1, 2, 4 }) + for (int rank : { 0, world - 1 }) { + if (world == 1 && rank > 0) continue; + RadBuilder b; + g431df2_encs(b, true); + RadBuildCtx ctx = build_ctx(rank, world); + ctx.max_tok = 2048; + ctx.max_spec = 7; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + for (const auto& k : { kit(b, { 1 }, {}), kit(b, { 1, 1, 1 }, {}), + kit(b, { 8, 1 }, { 5 }), kit(b, {}, { 1500 }) }) { + const auto v = run_passes(b, gemma4_bf16::step, { k.get() }, rank, world); + CHECK_PASSES(b, v); + } + for (int64_t n_seq : { 2, 8 }) { + const auto ver = kit(b, std::vector((size_t)n_seq, 8), {}); + const auto ctxp = context_pass(b, *ver); + const auto qry = query_pass(b, n_seq, 8, 7); + const auto v = run_passes(b, gemma4_bf16::step, + { ver.get(), ctxp.get(), qry.get() }, rank, world); + CHECK_PASSES(b, v); + } + } +} + +/* DFlash2's fc, split by rows over the ranks and kept bit for bit. At four ranks each rank hands + * over 1344 of c's 5376 columns and computes the 11 whole scale blocks covering them (1408 rows: a + * span of the one stored weight, so a container converted before the split serves it), its window + * starting 0 or 64 rows in; the GEMM takes its K split from the whole 5376 rows (split_n), and the + * all_gather reads each window at the GEMM output's pitch and writes c whole. At two ranks a share + * is 21 whole blocks; at one rank the fc is whole, and so is an MXFP4 fc at four (its GEMM picks + * its own K split, so only block fp8 splits). */ +TEST(gemma4_31b_dflash2_fc_splits_by_rows_without_changing_a_bit) { + G431Df2 f; + const RadModelMeta meta = f.meta(); + const int64_t E = 5376, K = 3 * E; /* the fixture taps three trunk layers */ + struct Case { int world; int rank; int64_t lo, hi, share; }; + for (const Case cs : { Case{ 4, 0, 0, 1408, 1344 }, Case{ 4, 1, 1280, 2688, 1344 }, + Case{ 4, 2, 2688, 4096, 1344 }, Case{ 4, 3, 3968, 5376, 1344 }, + Case{ 2, 0, 0, 2688, 2688 }, Case{ 2, 1, 2688, 5376, 2688 }, + Case{ 1, 0, 0, 0, 0 } }) { + RadBuilder b; + g431df2_encs(b, true); + RadBuildCtx ctx = build_ctx(cs.rank, cs.world); + ctx.max_tok = 2048; + ctx.max_spec = 7; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + const RecWeight* fw = find_w(b, "dflash.fc.weight"); + const RecWeight* fs = find_w(b, "dflash.fc.scale"); + REQUIRE(fw != nullptr); + REQUIRE(fs != nullptr); + CHECK_EQ(fw->d.shape[1], K); + CHECK(find_w(b, "dflash.fc_tail.weight") == nullptr); + int split_gemms = 0, fc_gathers = 0; + for (const RecOp& o : b.ops) { + if (o.op == "gemm_nt_q" && pint(&o, "split_n") == E) { + ++split_gemms; + CHECK_EQ(pint(&o, "N"), (long long)(cs.hi - cs.lo)); + } + if (o.op == "all_gather" && pint(&o, "row") == cs.share) { + ++fc_gathers; + CHECK_EQ(pint(&o, "numel"), (long long)(2048 * E)); /* the trunk's instance */ + CHECK_EQ(pint(&o, "world_size"), (long long)cs.world); + } + } + if (!cs.share) { + CHECK_EQ(fw->d.shape[0], E); + CHECK_EQ(fw->d.shard, RAD_SHARD_NONE); + CHECK(!fw->span_set); + CHECK_EQ(split_gemms, 0); + continue; + } + CHECK_EQ(fw->d.shape[0], cs.hi - cs.lo); + CHECK_EQ(fw->d.shard, RAD_SHARD_ROW); + CHECK(fw->span_set); + CHECK_EQ(fw->span_lo, cs.lo); + CHECK_EQ(fw->span_hi, cs.hi); + CHECK(fs->span_set); /* the scale plane's span is in 128-row blocks */ + CHECK_EQ(fs->span_lo, cs.lo / 128); + CHECK_EQ(fs->span_hi, cs.hi / 128); + /* the window covers exactly this rank's share */ + CHECK(cs.lo <= cs.rank * cs.share && (cs.rank + 1) * cs.share <= cs.hi); + CHECK_EQ(split_gemms, 1); + CHECK_EQ(fc_gathers, 1); + } + + /* An MXFP4 drafter: fc whole on every rank. */ + { + RadBuilder b; + g431df2_encs(b, true); + for (auto& e : b.encs) + if (e.first == "dflash.fc." || e.first == "dflash.blk.") + e.second = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + RadBuildCtx ctx = build_ctx(1, 4); + ctx.max_tok = 2048; + ctx.max_spec = 7; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + const RecWeight* fw = find_w(b, "dflash.fc.weight"); + REQUIRE(fw != nullptr); + CHECK_EQ(fw->d.shape[0], E); + CHECK_EQ(fw->d.shard, RAD_SHARD_NONE); + CHECK(find_w(b, "dflash.fc_tail.weight") == nullptr); + for (const RecOp& o : b.ops) CHECK(pint(&o, "split_n") != E); + } +} + +/* Where the container holds q, k and v as one linear (a recipe naming blk.*.attn_qkv.weight), the + * 31B declares one projection a layer -- q | k | v on a sliding layer, q | k on a global one, each + * rank its slice of every part -- and none of the three apart, and the junction writes that + * linear's int8 pair. The step: four GEMMs a layer instead of six (five on a global layer). A + * global layer's attention reads q in the row (attn_paged_qrow); a sliding layer's reads it there + * at one row and from attn_qs, copied out, at sixteen. */ +TEST(gemma4_31b_takes_q_k_and_v_as_one_linear_where_the_container_holds_them_so) { + G431Df f; + const RadModelMeta meta = f.meta(); + const int64_t E = 5376, L = 12; + for (int world : { 1, 4 }) { + RadBuilder b; + g431df_encs(b, false, true, true); + RadBuildCtx ctx = build_ctx(0, world); + ctx.max_tok = 2048; + ctx.max_spec = 15; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + + for (int64_t l = 0; l < L; ++l) { + const bool global = (l + 1) % 6 == 0; + const std::string pre = "blk." + std::to_string(l) + "."; + const RecWeight* qkv = nullptr; + for (const RecWeight& w : b.weights) { + if (w.name == pre + "attn_qkv.weight") qkv = &w; + for (const char* sep : { "attn_q.weight", "attn_k.weight", "attn_v.weight" }) + CHECK(w.name != pre + sep); + } + REQUIRE(qkv); + CHECK_EQ(qkv->d.shape[0], (global ? 32 * 512 + 4 * 512 : 32 * 256 + 2 * 16 * 256) / world); + CHECK_EQ(qkv->d.shape[1], E); + CHECK_EQ((int)qkv->d.n_row_parts, global ? 2 : 3); + } + + for (const int q : { 1, 16 }) { + const auto k = kit(b, { q }, {}); + const auto v = run_passes(b, gemma4_bf16::step, { k.get() }, 0, world); + CHECK_PASSES(b, v); + const std::vector ops = issued_ops(b, *v[0]); + CHECK_EQ(count_issued(ops, "gemm_nt_q"), (int)(4 * L)); + CHECK_EQ(count_issued(ops, "attn_paged_qrow"), 2); + CHECK_EQ(count_issued(ops, "attn_paged"), 10); + CHECK_EQ(count_issued(ops, "quant_act_i8"), (int)L); /* o_proj's input only */ + CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qs")), q == 1 ? 0 : 10); + /* the GEMM, then qkv_norm_rope in place */ + CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qkvs")), 2 * 10); + CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qkvg")), 2 * 2); + } + } +} + /* ==================================================================== the step lint, checked */ namespace { @@ -7321,6 +7760,11 @@ struct ArchCases { b->encs = { { "attn_q.", w4g }, { "attn_k.", w4g }, { "attn_v.", w4g }, { "attn_o.", w4g }, { "ffn_gate_up.", w4g }, { "ffn_down.", w4g } }; }; + /* The same with q, k and v as one linear, as a recipe naming attn_qkv converts it. */ + auto g4qkv = [this](RadBuilder* b) { + b->encs = { { "attn_qkv.", w4g }, { "attn_o.", w4g }, { "ffn_gate_up.", w4g }, + { "ffn_down.", w4g } }; + }; /* The ops libref lacks that each still asks for, both two-rank fusions with no chain: * qwen35_fp8's all-reduce norm (layer_fold assumes it at two ranks) and Flash-Next's * all-reduce into the wide stream. */ @@ -7365,15 +7809,24 @@ struct ArchCases { add("lfm2_bf16", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return lfm2_bf16::declare(b, &lfm, &c); }, lfm2_bf16::step, 0, {}, 0x1775b188dc4a5120ull); + /* The first three moved only by the attn_qkv name map each layer declares to ask whether + * the container holds q, k and v as one linear: with those maps left out of the hash they + * are the earlier pins, 0xafc23087c634a537, 0x719fa07788f8b98a and 0x93b174ab52cc0d31. */ add("gemma4_bf16", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0xafc23087c634a537ull); + gemma4_bf16::step, 0, {}, 0x174e157911e121a9ull); add("gemma4_bf16, w4a8", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x719fa07788f8b98aull); + gemma4_bf16::step, 0, {}, 0x4bf536b78c6b11eeull); add("gemma4_bf16, w4a8, two ranks", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, - nullptr, 0, {}, 0x93b174ab52cc0d31ull); + nullptr, 0, {}, 0xed7ccbb0c6aecfebull); + add("gemma4_bf16, w4a8, fused qkv", [this, sc, g4qkv](RadBuilder* b) { + g4qkv(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, + gemma4_bf16::step, 0, {}, 0x0ae60e16d6b6424cull); + add("gemma4_bf16, w4a8, fused qkv, two ranks", [this, sc, g4qkv](RadBuilder* b) { + g4qkv(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, + nullptr, 0, {}, 0xcc58bb53457bca11ull); add("gemma4", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4::declare(b, &g4m, &c); }, gemma4::step, 0, {}, 0x0f227f5853b6488cull); From 015cba8837dc2618cdb5782ad295ee568dd8cfd6 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 14:54:47 -0500 Subject: [PATCH 121/152] libr4d, arch: the 31B and DFlash2 with fewer launches a step, same bytes Attention reads q and the gqa-8 drafter's KV in place (attn_paged_qrow); the 31B's attention prologue stores k and v itself (qkv_norm_rope_kv_store); DFlash2's norm/rope/cache-store chains and add-then-norm pairs run as one launch each. Carries the launch-cliff padding until that PR merges. Squashed from: - libr4d: attn_paged_qrow on the split-KV decode kernel -- h256/gqa2, and h128/gqa8 by two groups a kv head - arch: the 31B's sliding layers and its drafter read through attn_paged_qrow where a card serves it - libr4d: step past the full-card launch cliff in qkv_norm_rope and the row norms - libr4d: qkv_norm_rope describes its operands, so rad-kbench and rad-tune can time it - libr4d, arch/gemma4_bf16: qkv_norm_rope_kv_store -- the 31B's prologue stores k and v itself - libr4d, arch/common: qkv_norm_rope takes v_norm; DFlash2's query pass folds its q/k chain - libr4d, arch/common: qkv_norm_rope takes n_head 0; DFlash2's context pass folds its key chain - libr4d, arch/common: add_rmsnorm; DFlash2 issues each residual add with the norm after it Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_block_dflash2.h | 139 ++++++++++++++++-- arch/common/rad_gemma4_dflash.h | 49 ++++++- arch/gemma4_bf16/gemma4_bf16.cpp | 114 ++++++++++----- docs/ARCHITECTURES.md | 23 ++- docs/OPS.md | 32 ++++- libr4d/r4d.h | 20 +++ libr4d/r4d_attn_args.h | 24 +++- libr4d/r4d_attn_decode_h256_gqa6.hip | 37 +++-- libr4d/r4d_attn_paged_gqa8.hip | 2 +- libr4d/r4d_attn_paged_h128_gqa4.hip | 8 ++ libr4d/r4d_attn_paged_h256_gqa2.hip | 8 ++ libr4d/r4d_attn_paged_h256_gqa6.hip | 62 +++++++- libr4d/r4d_fuse.cpp | 65 +++++++++ libr4d/r4d_model_bf16.hip | 79 +++++++++++ libr4d/r4d_plugin.h | 15 ++ libr4d/r4d_qkv_norm_rope.hip | 194 +++++++++++++++++++++---- libr4d/r4d_rows.cpp | 166 +++++++++++++++++++++- libr4d/r4d_selftest.cpp | 202 +++++++++++++++++++++++++-- libr4d/r4d_shapes.cpp | 56 ++++++++ tests/arch_test.cpp | 201 ++++++++++++++++++++------ 20 files changed, 1332 insertions(+), 164 deletions(-) diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h index 800f5790..823940f7 100644 --- a/arch/common/rad_block_dflash2.h +++ b/arch/common/rad_block_dflash2.h @@ -233,6 +233,9 @@ struct Dflash2 { rad_op op_cfc = 0, op_cnorm = 0, op_crope = 0, op_cstore = 0; rad_op op_cgath = 0; /* the split fc's all-gather */ rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; + /* The k norm, the k rotary and the cache store as one launch a layer (qkv_norm_rope_kv_store + * with n_head 0 and v_norm 0), issued in place of those three where it resolves. */ + rad_op op_cqkr[MAX_LAYERS] = {}; /* Activation quantisers, one per activation that feeds a linear. Weightless, so one declaration * serves every layer; ops with weights are per layer because a weight's prefetch interval @@ -248,11 +251,19 @@ struct Dflash2 { rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; rad_op op_op[MAX_LAYERS] = {}; rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}; + /* The q and k norms, both rotaries and the cache store as one launch a layer + * (qkv_norm_rope_kv_store with v_norm 0), issued in place of those five where it resolves. */ + rad_op op_qkr[MAX_LAYERS] = {}; rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */ rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {}; rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0; rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; + /* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and + * that norm where it resolves: op_afn[i] after layer i's attention (its feed-forward norm), + * op_aan[i] after layer i-1's feed-forward (layer i's attention norm, i >= 1), op_afinal after + * the last layer's (the final norm). All or none. */ + rad_op op_afn[MAX_LAYERS] = {}, op_aan[MAX_LAYERS] = {}, op_afinal = 0; /* head and selector */ rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0; @@ -684,6 +695,62 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("kv_dtype", g.kv_dtype)), RAD_NOWEIGHTS), {w.k, w.v}, {}); + /* The query pass's q/k norms, rotaries and store as one launch a layer where a library + * serves it: qkv_norm_rope_kv_store with v_norm 0 (v stored as it is), byte-identical to the + * two rmsnorms, the two ropes and kv_store (docs/OPS.md), which stay declared beside it for + * a library that does not. No YaRN (the fold takes none). */ + { + /* Only for a shape a library serves: an op declared for one that resolves to no device + * kernel is a hole that refuses startup (Program::device_holes), whether or not it is + * issued, so the block asks within libr4d's span for the fold (head_dim 256 to 512 in + * steps of 256, bf16 rows, an fp8 or bf16 cache). Qwen3.8's DFlash2 drafter (head_dim + * 128) keeps the chain. */ + const bool fold_shape = g.head_dim >= 256 && g.head_dim <= 512 && g.head_dim % 256 == 0 && + !std::strcmp(g.dtype, "bf16") && + (!std::strcmp(g.kv_dtype, "fp8_e4m3") || + !std::strcmp(g.kv_dtype, "bf16")); + if (fold_shape && g.yarn.factor == 0.0f && + rad_op_declared(b, "qkv_norm_rope_kv_store")) { + const int64_t bsz = rad_kv_block_size(b, kv); + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_qkr[i] = RAD_OP(b, "qkv_norm_rope_kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"), + RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype), + RAD_INT("v_norm", 0), RAD_INT("block_size", bsz), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_qn[i], w_kn[i])); + if (!op_qkr[i] || !rad_op_resolved(b, op_qkr[i])) { + for (int j = 0; j <= i; ++j) op_qkr[j] = 0; + break; + } + op_qkr[i] = rw(b, op_qkr[i], {w.q, w.k, w.v}, {w.q, w.k, w.v}); + } + /* The context pass's keys the same way: no q (n_head 0, `q` passed as k's buffer and + * `q_w` as k's norm, neither read), the context rows' slots. */ + for (int64_t l = 0; op_qkr[0] && l < g.n_layer; ++l) { + const int i = (int)l; + op_cqkr[i] = RAD_OP(b, "qkv_norm_rope_kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", 0), RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"), + RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype), + RAD_INT("v_norm", 0), RAD_INT("block_size", bsz), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_kn[i], w_kn[i])); + if (!op_cqkr[i] || !rad_op_resolved(b, op_cqkr[i])) { + for (int j = 0; j <= i; ++j) op_cqkr[j] = 0; + break; + } + op_cqkr[i] = rw(b, op_cqkr[i], {w.ck, w.cv}, {w.ck}); + } + } + } op_act = rw(b, RAD_OP(b, "silu_mul", RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), @@ -708,6 +775,30 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_norm)), {w.x}, {w.h}); + /* Each residual add and the norm after it as one launch where a library serves add_rmsnorm + * (byte-identical to the pair: the norm is taken over the bf16 sum it stores), taken only + * where every handle resolves (rad_op_resolved), all or none; the pairs declared beside it run + * otherwise. */ + if (rad_op_declared(b, "add_rmsnorm")) { + auto an = [&](rad_weight wt) -> rad_op { + const rad_op h = RAD_OP(b, "add_rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(wt)); + return h && rad_op_resolved(b, h) ? rw(b, h, {w.x, w.h2}, {w.x, w.h}) : (rad_op)0; + }; + bool all = true; + for (int64_t l = 0; all && l < g.n_layer; ++l) { + const int i = (int)l; + op_afn[i] = an(w_fnorm[i]); + if (l > 0) op_aan[i] = an(w_anorm[i]); + all = op_afn[i] && (l == 0 || op_aan[i]); + } + op_afinal = all ? an(w_norm) : 0; + if (!op_afinal) + for (int i = 0; i < MAX_LAYERS; ++i) op_afn[i] = op_aan[i] = 0; + } /* ---------------------------------------------------------------- the head and the selector * @@ -839,6 +930,12 @@ inline void Dflash2::context(RadCtx* c, const RadBatch* batch) const { RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref()); RAD_ISSUE_N(c, op_cv[i], T, brows(w.cq, T), brows(w.cs, T), RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref()); + if (op_cqkr[i]) { + RAD_ISSUE_N(c, op_cqkr[i], T, brows(w.ck, T), brows(w.ck, T), brows(w.cv, T), + praw(batch->positions, RAD_I32, T), RAD_W(w_kn[i]), RAD_W(w_kn[i]), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + continue; + } RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]), brows(w.ck, T)); RAD_ISSUE_N(c, op_crope, T, brows(w.ck, T), praw(batch->positions, RAD_I32, T)); @@ -864,11 +961,23 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); + /* x += h2 waits for the norm after it, which takes it in (add_rmsnorm) where declared */ + bool add_pending = false; + auto norm = [&](rad_op plain, rad_op folded, rad_weight wt) { + if (add_pending && folded) { + RAD_ISSUE_N(c, folded, T, brows(w.x, T), brows(w.h2, T), RAD_W(wt), brows(w.h, T)); + } else { + if (add_pending) RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T)); + RAD_ISSUE_N(c, plain, T, brows(w.x, T), RAD_W(wt), brows(w.h, T)); + } + add_pending = false; + }; + for (int64_t l = 0; l < g.n_layer; ++l) { const int i = (int)l; /* ---- attention, wrapped in the two halves of one convolution */ - RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); + norm(op_anorm[i], op_aan[i], w_anorm[i]); RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T)); RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T), wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T)); @@ -880,13 +989,19 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref()); RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T), RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref()); - RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T)); - RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, - brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T)); - RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T)); - RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T)); - RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), - praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + if (op_qkr[i]) { + RAD_ISSUE_N(c, op_qkr[i], T, brows(w.q, T), brows(w.k, T), brows(w.v, T), + praw(batch->positions, RAD_I32, T), RAD_W(w_qn[i]), RAD_W(w_kn[i]), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + } else { + RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.q, T)); + RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, + brows(w.k, T), RAD_W(w_kn[i]), brows(w.k, T)); + RAD_ISSUE_N(c, op_qrope, T, brows(w.q, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_krope, T, brows(w.k, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_store, T, brows(w.k, T), brows(w.v, T), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + } RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(w.q, T), kv_cache(kv, first_layer + i), praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), @@ -903,10 +1018,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T)); - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T)); + add_pending = true; /* ---- the feed-forward, wrapped in the other convolution */ - RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); + norm(op_fnorm[i], op_afn[i], w_fnorm[i]); RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T)); RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T), wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T)); @@ -926,10 +1041,10 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T)); - RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.h2, T), brows(w.x, T)); + add_pending = true; } - RAD_ISSUE_N(c, op_final, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + norm(op_final, op_afinal, w_norm); /* The predicting rows, `steps` per sequence, named by the scheduler through out_ids. */ const int64_t S = batch->n_out; diff --git a/arch/common/rad_gemma4_dflash.h b/arch/common/rad_gemma4_dflash.h index d962ac9b..cdf3ecff 100644 --- a/arch/common/rad_gemma4_dflash.h +++ b/arch/common/rad_gemma4_dflash.h @@ -219,21 +219,45 @@ struct Dflash1 { int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */ double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */ int64_t kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */ + bool qrow = false; /* attention at the drafter's own gqa via attn_paged_qrow */ int64_t steps() const { return block - 1; } }; /* The attention's queries per kv head. libr4d serves the drafter's head-128 attention, causal * over a window and non-causal alike, on one kernel that takes 4 queries per kv head and * q_len * gqa <= 64, so a block of 16 at 4. The 26B's drafter is gqa 4. The 31B's is 64 heads - * over 8 kv heads, gqa 8 at every rank count, which no kernel serves at a block of 16: its - * cache holds each kv head twice, and attention sees 4 queries per copy. That is exact (query - * head q still reads kv head q / 8), and costs a copy of k and v per layer and a cache twice the - * size, a few MiB at the drafter's width. */ + * over 8 kv heads, gqa 8 at every rank count, which no attn_paged kernel serves at a block of + * 16: unless attn_paged_qrow does (qrow_serves), its cache holds each kv head twice, and + * attention sees 4 queries per copy. That is exact (query head q still reads kv head q / 8), + * and costs a copy of k and v per head and layer and a cache twice the size, a few MiB at the + * drafter's width. */ static constexpr int64_t kAttnGqa = 4; static int64_t kv_rep_for(const Geom& g) { const int64_t gqa = g.gqa(); return gqa > kAttnGqa && gqa % kAttnGqa == 0 ? gqa / kAttnGqa : 1; } + /* libr4d also serves gqa 8 at head_dim 128 under attn_paged_qrow: that kernel with each kv head + * read by two query groups, so the cache holds each head once and nothing is copied. No host + * library declares attn_paged_qrow, so it resolves only to a card's kernel; asked first, it + * decides the cache's head count (declare_drafter). The asking ops take no buffers and are not + * issued; the attention the drafter issues is declared after its KV group, which takes its + * block size from it. */ + static bool qrow_serves(RadBuilder* b, const Geom& g, const Config& c) { + bool any_full = false, any_swa = false; + for (int64_t l = 0; l < g.n_layer; ++l) (c.full[l] ? any_full : any_swa) = true; + auto ask = [&](int causal, int64_t window) { + const rad_op h = RAD_OP(b, "attn_paged_qrow", + RAD_PARAMS(RAD_RANGE("q_len", 1, c.block), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", causal), + RAD_INT("window", window), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS); + return h != RAD_NULL_HANDLE && rad_op_resolved(b, h); + }; + return (!any_swa || ask(1, c.window)) && (!any_full || ask(0, 0)); + } /* What the trunk hands the drafter (declare_drafter). */ struct Trunk { @@ -577,8 +601,17 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, * position. The sliding layers bound themselves with their attention op's `window`, so the * declared drafter window is 0 and the core stages the whole context. A separate window group * for the sliding layers would save memory. */ - /* The cache holds kv_rep copies of each of this rank's kv heads (kv_rep_for). */ + /* The cache holds kv_rep copies of each of this rank's kv heads (kv_rep_for), or each once where + * a card serves the drafter's own gqa (qrow_serves). */ dc.kv_rep = kv_rep_for(dg); + if (dc.kv_rep > 1 && rad_op_declared(b, "attn_paged_qrow")) { + Geom pg = dg; + pg.kv_dtype = rad_dtype_name(rad_kv_cache_dtype(ctx, RAD_BF16)); /* as the group takes it */ + if (qrow_serves(b, pg, dc)) { + dc.kv_rep = 1; + dc.qrow = true; + } + } { Geom cg = dg; cg.n_head_kv *= dc.kv_rep; @@ -628,6 +661,10 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, "kernel serves at a block of %lld (gqa %lld otherwise)", (long long)dg.n_head_kv, (long long)dc.kv_rep, (long long)kAttnGqa, (long long)dg.head_dim, (long long)dc.block, (long long)dg.gqa()); + else if (dc.qrow) + rad_note(b, "the DFlash drafter attends at %lld queries per kv head through attn_paged_qrow, " + "its cache holding each of its %lld kv head(s) a rank once", + (long long)dg.gqa(), (long long)dg.n_head_kv); return RAD_OK; } @@ -778,7 +815,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co * Declared before either kv_store, which reads `block_size` back from the resolved kernel. * Both read the one KV group, so whichever resolves first answers for it. */ auto attn = [&](int causal, int64_t window) { - return rw(b, RAD_OP(b, "attn_paged", + return rw(b, RAD_OP(b, cfg.qrow ? "attn_paged_qrow" : "attn_paged", RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa() / rep), RAD_INT("causal", causal), RAD_INT("window", window), RAD_INT("n_head", g.n_head), diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 578afa43..a83f3982 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -276,11 +276,16 @@ struct Gemma4Attn { op_rq = 0, op_rk = 0, op_attn = 0, op_kv = 0, op_post = 0, op_ar = 0, op_add = 0; /* the five prologue ops (v norm, q norm, k norm, two rotaries) as one, where it resolves */ rad_op op_qnr = 0; + /* ...and that with kv_store folded in (qkv_norm_rope_kv_store), issued in place of op_qnr and + * op_kv where it resolves; op_kv is then not declared */ + rad_op op_qnr_kv = 0; /* Fused only: attention reading q where it lies in the row (attn_paged_qrow), where it resolves - * to the kernel attn_paged would take anyway; else the copy of q into its own rows (`cast`) that - * a step of more than one row issues ahead of attn_paged. Without qkv_norm_rope the copies of - * k and v too, ahead of the unfused prologue, which reads them dense. */ - rad_op op_attn_row = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0; + * to the kernel attn_paged would take anyway -- at every height (op_attn_row), or at decode + * heights up to dec_hi query rows a sequence (op_attn_dec); else the copy of q into its own rows + * (`cast`) that a step of more than one row issues ahead of attn_paged. Without qkv_norm_rope + * the copies of k and v too, ahead of the unfused prologue, which reads them dense. */ + rad_op op_attn_row = 0, op_attn_dec = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0; + int64_t dec_hi = 0; /* The linear whose int8 pair a junction writes, and whether every projection reads it. */ const G4Linear& ln_in() const { return fused ? ln_qkv : ln_q; } @@ -426,9 +431,10 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const /* Gemma 4 scores Q.K without the 1/sqrt(head_dim) factor (HF Gemma4TextAttention and vLLM * use scaling = 1.0; the q/k norm gains absorb it). attn_paged defaults to 1/sqrt(head_dim), * so 1.0 is passed explicitly. */ - auto attn = [&](const char* op, std::initializer_list rd) { + auto attn = [&](const char* op, std::initializer_list rd, int64_t q_hi = 0) { return rw(b, RAD_OP(b, op, - RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_PARAMS(RAD_RANGE("q_len", 1, q_hi > 0 ? q_hi : g.max_tok), + RAD_INT("head_dim", cls.head_dim), RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head), RAD_INT("block_size", RAD_KV_BLOCK), @@ -445,6 +451,14 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const * keeps the five, as does an engine whose libraries do not declare it (CPU-only), where asking * for it would stop the declare. It reads q, k and v at their own row pitches, so on a fused * layer it works in place on the row's column slices. */ + /* What the prologue reads and writes, either form. A k_eq_v class derives v from the raw k: + * v is written, never read. */ + auto qnr_rw = [&](rad_op op) { + if (fused) + return cls.has_v ? rw(b, op, {w.qkv}, {w.qkv}) : rw(b, op, {w.qkv}, {w.qkv, w.v}); + return cls.has_v ? rw(b, op, {w.q, w.k, w.v}, {w.q, w.k, w.v}) + : rw(b, op, {w.q, w.k}, {w.q, w.k, w.v}); + }; auto decl_qnr = [&]() { if (g.rope_mc || g.yarn.factor != 0.0f || !rad_op_declared(b, "qkv_norm_rope")) return; op_qnr = RAD_OP(b, "qkv_norm_rope", @@ -457,13 +471,7 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RAD_F64("wadd", g.wadd_qk), RAD_INT("v_from_k", cls.has_v ? 0 : 1), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_qn, w_kn)); - /* A k_eq_v class derives v from the raw k: v is written, never read. */ - if (fused) - op_qnr = cls.has_v ? rw(b, op_qnr, {w.qkv}, {w.qkv}) - : rw(b, op_qnr, {w.qkv}, {w.qkv, w.v}); - else - op_qnr = cls.has_v ? rw(b, op_qnr, {w.q, w.k, w.v}, {w.q, w.k, w.v}) - : rw(b, op_qnr, {w.q, w.k}, {w.q, w.k, w.v}); + op_qnr = qnr_rw(op_qnr); }; /* A column slice of the fused row copied into its own rows (`cast`, bf16 to bf16, which every @@ -489,29 +497,60 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const } /* With it attention reads q in the row where that costs nothing. libr4d's dedicated paged * kernels stop at head_dim 256; at 512 (the global class) attn_paged takes the windowed - * kernel, which is the kernel attn_paged_qrow takes, so the row is read in place. At 256 the - * dedicated h256 kernels serve attn_paged in 0.26-0.71 of the windowed kernel's time - * (libr4d/r4d_plugin.h, R4D_PRIO_ATTN_WINDOW), so the sliding class keeps attn_paged: a step - * of one row reads q in place (one row of a slice is dense), a taller one copies q out. */ - if (op_qnr && cls.head_dim > 256 && rad_op_declared(b, "attn_paged_qrow")) + * kernel, which is the kernel attn_paged_qrow takes, so the row is read in place at every + * height. At 256 the dedicated h256 kernels serve attn_paged in 0.26-0.71 of the windowed + * kernel's time (libr4d/r4d_plugin.h, R4D_PRIO_ATTN_WINDOW). Their split-KV decode reads q + * at a pitch under attn_paged_qrow too, over its band (q_len * gqa <= 64: 32 query rows a + * sequence at the sliding class's gqa 2), so the sliding class reads the row there -- a + * verify step included -- and keeps attn_paged above it, a prefill copying q out first. */ + const bool qrow = op_qnr && rad_op_declared(b, "attn_paged_qrow"); + if (qrow && cls.head_dim > 256) { op_attn_row = attn("attn_paged_qrow", {w.qkv}); + } else if (qrow) { + dec_hi = std::min(g.max_tok, 64 / cls.gqa()); + op_attn_dec = attn("attn_paged_qrow", {w.qkv}, dec_hi); + if (!op_attn_dec) dec_hi = 0; + } if (!op_attn_row) { op_lift_q = lift(qd, w.q); op_attn = attn("attn_paged", {w.q, w.qkv}); } } + /* With the cache store folded into the prologue where a library serves it + * (qkv_norm_rope_kv_store: the same prologue, then kv_store of the finished k and v from the + * same launch, byte for byte), one launch a layer fewer. Declared after the attention ops, + * since its block_size comes off the resolved attention kernel (rad_kv_block_size), and + * issued in place of op_qnr and op_kv. */ + if (op_qnr && rad_op_declared(b, "qkv_norm_rope_kv_store")) { + op_qnr_kv = RAD_OP(b, "qkv_norm_rope_kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", cls.n_head_kv), + RAD_F64("theta", cls.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", cls.scale), RAD_STR("mode", "neox"), + RAD_INT("rotary_dim", cls.n_rot), + RAD_STR("ladder", cls.head_ladder ? "head" : "rotary"), + RAD_F64("wadd", g.wadd_qk), RAD_INT("v_from_k", cls.has_v ? 0 : 1), + RAD_STR("dtype", g.dtype), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_qn, w_kn)); + if (op_qnr_kv) op_qnr_kv = qnr_rw(op_qnr_kv); + } /* On a fused layer with the one-op prologue, k and v are stored from the row (kv_store takes - * them at their own pitches); a k_eq_v class's v is its own buffer either way. */ - op_kv = RAD_OP(b, "kv_store", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), - RAD_INT("n_head_kv", cls.n_head_kv), - RAD_INT("block_size", rad_kv_block_size(b, kv)), - RAD_STR("kv_dtype", g.kv_dtype)), - RAD_NOWEIGHTS); - if (!(fused && op_qnr)) op_kv = rw(b, op_kv, {w.k, w.v}, {}); - else if (cls.has_v) op_kv = rw(b, op_kv, {w.qkv}, {}); - else op_kv = rw(b, op_kv, {w.qkv, w.v}, {}); + * them at their own pitches); a k_eq_v class's v is its own buffer either way. Not declared + * where the prologue stores them itself. */ + if (!op_qnr_kv) { + op_kv = RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head_kv", cls.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS); + if (!(fused && op_qnr)) op_kv = rw(b, op_kv, {w.k, w.v}, {}); + else if (cls.has_v) op_kv = rw(b, op_kv, {w.qkv}, {}); + else op_kv = rw(b, op_kv, {w.qkv, w.v}, {}); + } /* o_proj is column-sharded: the rank's partial sum is reduced first, then normed. */ if (g.world > 1) @@ -593,7 +632,10 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { const RadOperand K = row ? bcol(w.qkv, qd, kvd, T) : brows(w.k, T); const RadOperand V = row && cls.has_v ? bcol(w.qkv, qd + kvd, kvd, T) : brows(w.v, T); - if (op_qnr) { + if (op_qnr_kv) { + RAD_ISSUE(c, op_qnr_kv, Q, K, V, rope_posmc(g, batch, T), RAD_W(w_qn), RAD_W(w_kn), + praw(slot, RAD_I32, T), kv_cache(kv, layer)); + } else if (op_qnr) { RAD_ISSUE(c, op_qnr, Q, K, V, rope_posmc(g, batch, T), RAD_W(w_qn), RAD_W(w_kn)); } else { if (fused) { /* the unfused five read q, k and v dense */ @@ -610,7 +652,7 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { RAD_ISSUE(c, op_rk, brows(w.k, T), rope_posmc(g, batch, T)); } - RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer)); + if (op_kv) RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer)); /* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */ rad_op a_op = op_attn; @@ -618,6 +660,9 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { if (op_attn_row) { a_op = op_attn_row; a_q = Q; + } else if (op_attn_dec && batch->max_q_len <= dec_hi) { + a_op = op_attn_dec; + a_q = Q; } else if (row) { if (T == 1) a_q = Q; else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T)); @@ -1934,15 +1979,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c (long long)(g.n_layer - n_global), (long long)sliding_win, (long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g); { - int64_t n_fused = 0, n_row = 0; + int64_t n_fused = 0, n_row = 0, n_dec = 0, dec_hi = 0; for (const Layer& lay : m.layers) { n_fused += lay.attn.fused ? 1 : 0; n_row += lay.attn.op_attn_row ? 1 : 0; + if (lay.attn.op_attn_dec) { ++n_dec; dec_hi = lay.attn.dec_hi; } } if (n_fused) rad_note(b, "q, k and v as one linear (blk.*.attn_qkv) on %lld of %lld layers; attention " - "reads q in the row on %lld, copies it out above one row on the rest", - (long long)n_fused, (long long)m.layers.size(), (long long)n_row); + "reads q in the row at every height on %lld, up to %lld query rows a " + "sequence on %lld, and copies it out above that or one row", + (long long)n_fused, (long long)m.layers.size(), (long long)n_row, + (long long)dec_hi, (long long)n_dec); else rad_note(b, "q, k and v as three linears (a container converted before attn_qkv, or " "bf16 weights): convert with a recipe naming blk.*.attn_qkv.weight for one"); diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index b242ead9..58e8f307 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -764,13 +764,22 @@ The grid's groups never cross a row, so the codes are those of three separate ru the replies are too. On libr4d the skinny GEMM picks its in-block K split from N (k and v alone split K in two, the fused GEMM does not), so k and v can round differently in the last bit and a long greedy reply can part from the old container's late. `qkv_norm_rope` and `kv_store` work on -the row's column slices in place. A global layer's -attention reads q in the row (`attn_paged_qrow`, the windowed kernel that serves head_dim 512 under -`attn_paged` too); a sliding layer's reads it there in a one-row step, and a taller step copies q -out with a `cast` for libr4d's h256/gqa2 kernels, which take 0.26-0.71 of the windowed kernel's -time. Without `qkv_norm_rope` (a CPU-only engine) q, k and v are copied out for the unfused -prologue. A container that holds the three apart serves as before: the plugin asks the weight's -encoding, which rad-convert answers from the recipe and a container from its entries. +the row's column slices in place. Attention reads q in the row through `attn_paged_qrow`: a global +layer at every height (the windowed kernel, which serves head_dim 512 under `attn_paged` too), a +sliding layer up to 32 query rows a sequence (libr4d's h256/gqa2 split-KV decode with q at a pitch, +so a verify step included); a taller sliding step (a prefill) copies q out with a `cast` for the +h256/gqa2 prefill kernel, which takes 0.43-0.67 of the windowed kernel's time. Without +`qkv_norm_rope` (a CPU-only engine) q, k and v are copied out for the unfused prologue. A container +that holds the three apart serves as before: the plugin asks the weight's encoding, which +rad-convert answers from the recipe and a container from its entries. + +**The 31B's drafter at gqa 8.** z-lab's 31B drafter is 64 heads over 8 kv heads. Where a card +serves `attn_paged_qrow` at head_dim 128, gqa 8 and q_len 16 (libr4d's gqa-4 split-KV decode with +each kv head read by two query groups), the drafter's cache holds each kv head once and attention +runs at gqa 8. The op has no host rows, so the plugin asks it before the drafter's KV group, whose +head count follows the answer. Elsewhere the cache holds each kv head twice and attention runs at +gqa 4, the kv heads copied into place with a `cast` a head and copy (80 launches a draft step at +tp 4). **The 31B with a DFlash2 drafter.** RedHatAI's `gemma-4-31B-it-speculator.dflash2` is z-lab's DFlash2 architecture trained with vLLM's speculators library: five Qwen3-shaped layers at 5376 (32 diff --git a/docs/OPS.md b/docs/OPS.md index e207e32f..5621f5cb 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -449,7 +449,11 @@ dense block by a `cast`. It has its own name because other `attn_paged` kernels (libr4d's with `RAD_E_STRIDE`, at the first step), and under `attn_paged` the first library in `--kernels` wins the op, an order the architecture cannot see. Asked for by name, the op resolves to a library that reads the pitch or to nothing, and the architecture copies `q` for `attn_paged` in -the second case. +the second case. In libr4d the windowed kernels serve it at every height; the split-KV decode kernel +serves it at h256/gqa2 over its decode band (q_len up to 32, ahead of the windowed rows there), and +at h128/gqa8 up to q_len 16 by reading each kv head for two query groups of 4 (a drafter's cache +then holds each kv head once). Since no host library declares the op, a plugin that asks for it +learns whether a card serves the geometry. libref has no row for any of them, deliberately. An architecture asks for a fusion and declares the chain where it does not resolve (`rad_op_resolved`); a reference row would make it resolve @@ -821,6 +825,7 @@ bytes). | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | | `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? | | `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | +| `qkv_norm_rope_kv_store` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` `v_norm`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w, `slot_mapping`, `kv_cache`:inout | **`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each band. @@ -937,9 +942,19 @@ the same reason: its angles must stay `rope`'s exactly. **`qkv_norm_rope`** (device-only) is the same prologue over separate `q`, `k` and `v` projections (Gemma 4's text attention, three GEMMs): the q and k norms, the unit-gain value norm and the rotary -in one dispatch. `v_from_k` 1 takes v from the raw k before the k norm (the k == v global class). +in one dispatch. `v_from_k` 1 takes v from the raw k before the k norm (the k == v global class); +`v_norm` 0 leaves v unnormed (a Qwen3-shaped layer: two norms and two rotaries). `n_head` 0 is the +k (and v) heads alone, `q` and `q_w` passed but neither read nor written: a pass that writes only +keys and values (a block drafter's context pass). The rotary parameters are `rope`'s, `ladder` included. Byte-identical to `rmsnorm_p`, two -`rmsnorm`s and two `rope`s. +`rmsnorm`s and two `rope`s (one each at `n_head` 0). + +**`qkv_norm_rope_kv_store`** (device-only) is `qkv_norm_rope` followed by `kv_store` in one launch: +the block of each k head (and of each v head, or under `v_from_k` the k head's block for both) ends +holding its token's finished head, so it also writes it into the paged cache at the token's slot. +Its parameters are the two ops' own, its operands the prologue's followed by `slot_mapping` and +`kv_cache`. Byte-identical to the pair at either cache width: the store converts each element as +`kv_store` does, and q, k and v are still written in place as the prologue leaves them. | op | params | operands | |---|---|---| @@ -2829,6 +2844,17 @@ Blocks are `block_size` rows starting at row 0, so a tap never reaches into the `[T, 2, taps, NG]` coefficient projection. `out` must not alias `x`. libr4d's kernel serves `taps` 2, `group_size` 16 and a power-of-two `block_size`; libref and libavx any. +`add_rmsnorm` (device-only) is the drafter's residual add and the norm after it in one pass: + +| op | params | operands | +|---|---|---| +| `add_rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`:inout, `a`, `w`w → `y` | + +It writes `x + a` into `x`, rounded as `add` rounds it, then `y = rmsnorm(x) * (w + wadd) * mult` +over the `x` it wrote, at `rmsnorm`'s width and column partition: byte-identical to `add` followed +by `rmsnorm`, on both outputs. That is where it differs from `rmsnorm_add`, which normalises the +unrounded sum: a drafter whose trained graph is the pair keeps its bits. + `dflash_select` is the greedy walk over the candidate lattice: `cand`/`unary` are `row_topk`'s two output planes at one row per draft position, `hp` the selector's rank-256 query, and `anchor` the step's own token ids (`anchor_stride` is the block width, because a draft pass carries `block` ids a diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 5489e7dc..c159bfd3 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -65,6 +65,20 @@ struct R4DArgs { // null. const int* cu_q; // (num_seqs+1,) int32 device, or null for a uniform q_len int total_q; // rows of q/out; ignored unless cu_q is set + + // ---- Views the split-KV decode kernel reads (r4d_attn_decode_h256_gqa6.hip); every other + // kernel leaves them at zero and reads q dense with one cache head per query group. + // + // `q_ld` is the element distance between q rows, 0 for dense (q_heads * head_dim): the q part + // of a fused [q|k|v] projection read where it lies (attn_paged_qrow). A multiple of 4. + // + // `kv_rep` maps query groups onto cache heads: group g (q heads g*GQA .. g*GQA+GQA-1) reads + // cache head g / kv_rep, and the descales are per cache head. kv_heads then counts the groups + // (q_heads / GQA) and the cache holds kv_heads / kv_rep heads. 0 or 1 is one head a group. It + // runs a gqa of GQA * kv_rep on the kernel compiled for GQA, whose workgroup holds at most 64 + // rows of q_len * GQA: the 31B's DFlash drafter, gqa 8 at a block of 16, on the gqa-4 kernel. + long q_ld; + int kv_rep; }; // Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook @@ -89,6 +103,9 @@ int r4d_attn_decode_h256_gqa6_bf16kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa4_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa4_bf16kv (const R4DArgs* a, hipStream_t stream); long r4d_attn_decode_h128_gqa4_scratch_bytes(const R4DArgs* a); +// ...with R4DArgs::kv_rep and q_ld read: a gqa of 4 * kv_rep over a cache of kv_heads / kv_rep. +int r4d_attn_decode_h128_gqa4_rep_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h128_gqa4_rep_bf16kv (const R4DArgs* a, hipStream_t stream); // Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache // dtype: the partials are f16 either way. long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a); @@ -106,6 +123,9 @@ int r4d_attn_prefill_h128_gqa2w_bf16kv(const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa2w_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h128_gqa2w_bf16kv (const R4DArgs* a, hipStream_t stream); long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a); +// ...with q at R4DArgs::q_ld (attn_paged_qrow). +int r4d_attn_decode_h256_gqa2_qld_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h256_gqa2_qld_bf16kv (const R4DArgs* a, hipStream_t stream); // The geometry the attention kernels above are compiled for, so a caller can check a model // before the first launch. void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows); diff --git a/libr4d/r4d_attn_args.h b/libr4d/r4d_attn_args.h index b171226c..7814715a 100644 --- a/libr4d/r4d_attn_args.h +++ b/libr4d/r4d_attn_args.h @@ -39,10 +39,14 @@ enum { AP_Q = 0, AP_KV, AP_BT, AP_SEQ, AP_KDS, AP_VDS, AP_CU, AP_OUT }; * would abort the engine. So cu_seqlens is used whenever present, and the uniform arithmetic * (q_len = total_q / num_seqs) only when it is not. In the ragged case q_len is the batch maximum, * taken from the parameter the arch block issued the op with (batch->max_q_len). + * + * `q_pitched`: q may be a column slice of a wider row (attn_paged_qrow), its pitch in r->q_ld. Only + * the split-KV decode kernel reads q_ld; every other caller leaves this off. */ /* `row` is a token's bytes (elements for a 16-bit cache) in a (block, head) page: 2 * head_dim, * or 25 * head_dim / 16 for the fp8_v4 cache (E4M3 K, int4 V, f16 group scales). */ -static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_dim, long long row) { +static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_dim, long long row, + bool q_pitched = false) { const RadTensor* q = r4d_opt(a, AP_Q); const RadTensor* kv = r4d_opt(a, AP_KV); const RadTensor* bt = r4d_opt(a, AP_BT); @@ -74,8 +78,16 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d } /* q and out are indexed as one dense [total_q, q_heads, head_dim] block; the kernel has no - * pitch argument for either. */ - if (!r4d_contig(q) || !r4d_contig(o)) return R4D_NO(RAD_E_STRIDE); + * pitch argument for either -- except q under q_pitched, whose rows may be apart: dense inside + * a row, a pitch in whole 8-byte loads (the kernel reads q four elements at a time). */ + long long q_ld = 0; + if (q_pitched && !r4d_contig(q)) { + q_ld = r4d_row_pitch(q); + if (q_ld < q_heads * head_dim || q_ld % 4) return R4D_NO(RAD_E_STRIDE); + } else if (!r4d_contig(q)) { + return R4D_NO(RAD_E_STRIDE); + } + if (!r4d_contig(o)) return R4D_NO(RAD_E_STRIDE); if (o->shape[0] != total_q || r4d_numel(o) != total_q * q_heads * head_dim) return R4D_NO(RAD_E_SHAPE); if (su->shape[0] != num_seqs) return R4D_NO(RAD_E_SHAPE); @@ -104,6 +116,7 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d r->k_descale = kds ? (const float*)kds->data : nullptr; r->v_descale = vds ? (const float*)vds->data : nullptr; r->q_descale = nullptr; /* the query is bf16 in every variant */ + r->q_ld = (long)q_ld; /* 0: dense */ r->scratch = a->scratch; r->num_seqs = (int)num_seqs; r->cu_q = ragged ? (const int*)cu->data : nullptr; @@ -152,8 +165,9 @@ static inline int split_of(const RadArgs* a) { } -static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim) { - return fill_paged_row(a, r, expect_head_dim, 2LL * expect_head_dim); +static inline int fill_paged(const RadArgs* a, R4DArgs* r, int expect_head_dim, + bool q_pitched = false) { + return fill_paged_row(a, r, expect_head_dim, 2LL * expect_head_dim, q_pitched); } #endif /* R4D_ATTN_ARGS_H */ diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index aaacdc36..228fe7de 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -56,6 +56,13 @@ // k6_v4 cache (int6 K, int4 V); a token's row layout is RadBuildCtx::kv_quant's (abi/rad_builder.h). #define O_V4 33554432 #define O_K6 67108864 +// The two views of R4DArgs (r4d.h), compiled in only where a row asks for them, since the h256 +// instances sit at the 256-VGPR bound and a runtime pitch and head map spill there: +// QLD q rows at R4DArgs::q_ld (attn_paged_qrow), not dense. +// KVREP query group g reads cache head g / R4DArgs::kv_rep, descales per cache head. +// Neither changes the arithmetic. +#define O_QLD 134217728 +#define O_KVREP 268435456 __host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; } __host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) { int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits; @@ -103,6 +110,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) static_assert(!K6 || (!KLDS && (OPT & O_CONTIG) && !KRAW), "k6_v4 K is widened from the paged cache, a lane's eight dims contiguous"); static_assert(!V4 || (OPT & O_F16), "fp8_v4 widens to f16"); + constexpr int QLD = (OPT & O_QLD) ? 1 : 0; + constexpr int KVREP = (OPT & O_KVREP) ? 1 : 0; typedef DT16 D; typedef typename D::frag frag16; @@ -133,6 +142,8 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int c = lane & 15, h = lane >> 4; const int sp = blockIdx.x, kvh = blockIdx.y, seq = blockIdx.z; + // kvh is the query group; under KVREP the cache head it reads is kvh / kv_rep + const int kvc = KVREP ? kvh / a.kv_rep : kvh; const int ctx = a.seqused_k[seq]; if (ctx <= 0) return; @@ -161,13 +172,17 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int qhead = kvh * GQA + hi; const int* __restrict__ bt = a.block_table + (size_t)seq * a.max_blocks; - const float kdesc = a.k_descale ? a.k_descale[seq * a.kv_heads + kvh] : 1.0f; + const float kdesc = a.k_descale + ? a.k_descale[seq * (KVREP ? a.kv_heads / a.kv_rep : a.kv_heads) + kvc] + : 1.0f; const float mul = a.scale * kdesc * 1.44269504089f; frag16 qf[NKS]; { - const uint16_t* qp = (const uint16_t*)a.q - + ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM; + const uint16_t* qp = QLD ? (const uint16_t*)a.q + (size_t)(qoff + qrow) * a.q_ld + + (size_t)qhead * HEAD_DIM + : (const uint16_t*)a.q + + ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM; #pragma unroll for (int t = 0; t < NKS; ++t) { const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h)); @@ -267,7 +282,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) const int d0 = dg * (KVP ? 32 : 64) + vg * (KVP ? 8 : 16); const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS]; const size_t o = (size_t)blk * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + + (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB + HEAD_DIM + d0; const void* p = KVP ? (const void*)((const uint16_t*)a.kv + o) : (const void*)((const uint8_t*)a.kv + o); @@ -345,7 +360,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) if (WIN && kk < wlo0) kk = wlo0; const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS]; const size_t o = (size_t)kb * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB; + + (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB; uint16_t* kd = &sK[key * KSTR]; uint32_t w4[4]; if (KVP) { @@ -372,7 +387,7 @@ void r4d_attn_decode_kernel(const R4DArgs a, int splits) if (WIN && kk < wlo0) kk = wlo0; const int kb = BTS ? blk[(kk - k0) / BS] : bt[kk / BS]; grow = (const uint8_t*)a.kv + ((size_t)kb * a.kv_block_stride - + (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB) + + (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB) * (KVP ? 2 : 1); } // A fragment's raw K: 8 elements of 1 byte (fp8) or 2 (bf16). @@ -730,8 +745,9 @@ void splitkv_combine_vec_body(const R4DArgs& a, int splits, int tile, const R4DG } } - const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); - const float vd = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f; + const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); /* the query group */ + const int krep = a.kv_rep > 1 ? a.kv_rep : 1; /* its cache head: kvh / krep */ + const float vd = a.v_descale ? a.v_descale[seq * (a.kv_heads / krep) + kvh / krep] : 1.0f; uint16_t ob[DPL]; #pragma unroll for (int j = 0; j < DPL; ++j) { @@ -873,8 +889,9 @@ void splitkv_combine_body(const R4DArgs& a, int splits, int tile, const R4DGateQ #pragma unroll for (int i = 0; i < CHAINS; ++i) av += ch[i]; - const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); - const float vd = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f; + const int kvh = (job % a.q_heads) / (a.q_heads / a.kv_heads); /* the query group */ + const int krep = a.kv_rep > 1 ? a.kv_rep : 1; /* its cache head: kvh / krep */ + const float vd = a.v_descale ? a.v_descale[seq * (a.kv_heads / krep) + kvh / krep] : 1.0f; finish(f32_to_bf16(tot > 0.0f ? av * vd / tot : 0.0f)); } diff --git a/libr4d/r4d_attn_paged_gqa8.hip b/libr4d/r4d_attn_paged_gqa8.hip index ab6bbb27..10d1cea9 100644 --- a/libr4d/r4d_attn_paged_gqa8.hip +++ b/libr4d/r4d_attn_paged_gqa8.hip @@ -106,7 +106,7 @@ extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) { } template -/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168 +/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (184 * bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the * combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). `XOPT` adds * option bits to the attention kernel's (O_V4, O_K6: the cache layout). */ diff --git a/libr4d/r4d_attn_paged_h128_gqa4.hip b/libr4d/r4d_attn_paged_h128_gqa4.hip index d48d88e1..84dbb930 100644 --- a/libr4d/r4d_attn_paged_h128_gqa4.hip +++ b/libr4d/r4d_attn_paged_h128_gqa4.hip @@ -37,3 +37,11 @@ extern "C" int r4d_attn_decode_h128_gqa4_fp8kv(const R4DArgs* a, hipStream_t s) extern "C" int r4d_attn_decode_h128_gqa4_bf16kv(const R4DArgs* a, hipStream_t s) { return r4d_decode_launch_win(a, s); } +// The same over a cache holding each kv head once for kv_rep query groups (O_KVREP), q at +// R4DArgs::q_ld (O_QLD): gqa 8 on this gqa-4 kernel, under attn_paged_qrow. +extern "C" int r4d_attn_decode_h128_gqa4_rep_fp8kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} +extern "C" int r4d_attn_decode_h128_gqa4_rep_bf16kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} diff --git a/libr4d/r4d_attn_paged_h256_gqa2.hip b/libr4d/r4d_attn_paged_h256_gqa2.hip index 297dd4ec..77ee867f 100644 --- a/libr4d/r4d_attn_paged_h256_gqa2.hip +++ b/libr4d/r4d_attn_paged_h256_gqa2.hip @@ -36,6 +36,14 @@ extern "C" int r4d_attn_decode_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) { return r4d_decode_launch_win(a, s); } +// The same with q at R4DArgs::q_ld (O_QLD), for attn_paged_qrow; its own instances, so the dense +// ones above keep their registers. +extern "C" int r4d_attn_decode_h256_gqa2_qld_fp8kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} +extern "C" int r4d_attn_decode_h256_gqa2_qld_bf16kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} // ---- prefill --------------------------------------------------------------------------------- // The h256/gqa6 prefill option set but at K prefetch 4 (P_OPT there is 3954187); O_KWIDE is valid diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 441a657d..0d3ead43 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -219,7 +219,11 @@ static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) { return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r); } -static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long long row = 0) { +/* `row`: a token's bytes in a (block, head) page (fill_paged_row), 0 for 2 * head_dim; `rep`: the + * launch maps each kv head onto `rep` query groups (R4DArgs::kv_rep), so the split law counts + * groups, gqa / rep of them a kv head; `q_pitched`: q may be a slice (attn_paged_qrow). */ +static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long long row = 0, + int rep = 1, bool q_pitched = false) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); @@ -231,7 +235,8 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo r.head_dim = head_dim; r.q_heads = (int)n_head; const long long gqa = r4d_geti_or(a, "gqa", 1); - r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head); + r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head) * rep; + r.kv_rep = rep; r.num_seqs = (int)max_seqs; r.q_len = (int)r4d_geti_or(a, "q_len", 1); r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0); @@ -249,8 +254,10 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo return worst; } - int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim); + int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim, q_pitched); if (rc != RAD_OK) return rc; + r.kv_heads *= rep; + r.kv_rep = rep; r.splits = sp; return decode_scratch_bytes_of(&r, which); } @@ -263,11 +270,17 @@ extern "C" int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs* a) { return decode_scratch(a, 128, 1); } -static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which, long long row = 0) { +static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which, long long row = 0, + int rep = 1, bool q_pitched = false) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); - int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim); + int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim, q_pitched); if (rc != RAD_OK) return rc; + /* a QLD instance reads q_ld whatever q is: dense is the pitch q_heads * head_dim */ + if (q_pitched && r->q_ld == 0) r->q_ld = (long)r->q_heads * head_dim; + /* each cache head serves `rep` query groups: the kernel's grid and its gqa check count groups */ + r->kv_heads *= rep; + r->kv_rep = rep; r->splits = sp; const int64_t need = decode_scratch_bytes_of(r, which); if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); @@ -389,3 +402,42 @@ extern "C" int r4d_rad_attn_decode_h128_gqa2w_bf16(const RadArgs* a, RadStream s if (rc != RAD_OK) return rc; return r4d_attn_decode_h128_gqa2w_bf16kv(&r, (hipStream_t)s); } + +/* The same decode under attn_paged_qrow: q read at its own row pitch (R4DArgs::q_ld), the sliding + * layers' q where Gemma 4 31B's fused q|k|v projection left it. Same kernel, same arithmetic. */ +extern "C" int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs* a) { + return decode_scratch(a, 256, 2, 0, 1, true); +} +extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 256, 2, 0, 1, true); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa2_qld_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 256, 2, 0, 1, true); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa2_qld_bf16kv(&r, (hipStream_t)s); +} + +/* Head_dim 128 at 8 queries per kv head, any window, causal or not, q_len up to 16, under + * attn_paged_qrow: the gqa-4 kernel with each kv head mapped onto two query groups + * (R4DArgs::kv_rep = 2), the 31B's DFlash drafter's attention over a cache that holds each kv head + * once. The workgroup holds q_len * 4 rows, so a block of 16 fits where gqa 8 (128 rows) does not; + * the two groups of a kv head read its blocks twice, as the copies they replace did. */ +extern "C" int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs* a) { + return decode_scratch(a, 128, 1, 0, 2, true); +} +extern "C" int r4d_rad_attn_qrow_h128_gqa8_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 128, 1, 0, 2, true); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h128_gqa4_rep_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_qrow_h128_gqa8_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 128, 1, 0, 2, true); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h128_gqa4_rep_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index bc176795..dfa95d2a 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -586,6 +586,71 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u } } +/* ========================================================================================== + * qkv_norm_rope_kv_store -- qkv_norm_rope, then kv_store of its finished k and v. + * (rows: qkv_norm_rope_kv_store_fp8 and _bf16; kernel: libr4d/r4d_qkv_norm_rope.hip, + * qkv_norm_rope_kernel under KV) + * + * Operands: [0] q [1] k [2] v [3] positions [4] q_w [5] k_w [6] slot_mapping [7] kv_cache + * + * No temporaries: the prologue rewrites q, k and v in place and the store reads k and v as the + * prologue left them, which is what the kernel stores. */ +extern "C" int r4d_fuse_qkv_norm_rope_kv_store(const RadParam* p, int n_p, uint64_t present, + int step, RadFuseStep* out) { + (void)present; + if (!out) return RAD_E_INVAL; + switch (step) { + case 0: { + Step s(out, "qkv_norm_rope"); + s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head") + .mirror(p, n_p, "n_head_kv").mirror(p, n_p, "theta").mirror(p, n_p, "eps") + .mirror_opt(p, n_p, "scale").mirror_opt(p, n_p, "mode").mirror_opt(p, n_p, "rotary_dim") + .mirror_opt(p, n_p, "ladder").mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "v_from_k") + .mirror(p, n_p, "dtype").mirror_opt(p, n_p, "v_norm"); + return s.wire({ 0, 1, 2, 3, 4, 5 }); + } + case 1: { + Step s(out, "kv_store"); + s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head_kv") + .mirror(p, n_p, "block_size").mirror(p, n_p, "kv_dtype") + .mirror_opt(p, n_p, "k_scale").mirror_opt(p, n_p, "v_scale"); + /* k, v, slot_mapping, kv_cache */ + return s.wire({ 1, 2, 6, 7 }); + } + default: + return RAD_E_NOTFOUND; + } +} + +/* ========================================================================================== + * add_rmsnorm -- add (x += a), then rmsnorm of the x it wrote. + * (row: add_rmsnorm_bf16; kernel: libr4d/r4d_model_bf16.hip, add_rmsnorm_kernel) + * + * Operands: [0] x [1] a [2] w [3] y + * + * No temporaries: the add writes x in place and the norm reads it. */ +extern "C" int r4d_fuse_add_rmsnorm(const RadParam* p, int n_p, uint64_t present, int step, + RadFuseStep* out) { + (void)present; + if (!out) return RAD_E_INVAL; + switch (step) { + case 0: { + Step s(out, "add"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype"); + /* a = x, b = the addend, y = x */ + return s.wire({ 0, 1, 0 }); + } + case 1: { + Step s(out, "rmsnorm"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "eps").mirror(p, n_p, "dtype") + .mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "mult"); + return s.wire({ 0, 2, 3 }); + } + default: + return RAD_E_NOTFOUND; + } +} + /* ========================================================================================== * attn_paged_gate_quant -- attn_paged, then gate_quant_fp8 over its output. * (row: attn_decode_gq_h256_gqa12_fp8kv; kernels: libr4d/r4d_attn_decode_h256_gqa6.hip, the diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index d1952c80..e41f1f73 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -226,6 +226,38 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel( } } +// ---------------------------------------------------------------------------- add_rmsnorm +// x = x + a, rounded as `add` rounds it, then y = rmsnorm(x) over the x just written, computed as +// rmsnorm_kernel computes it: the same width (r4d_act_threads), the same columns a thread, the same +// block_sum. A thread re-reads only the x it wrote itself, so no barrier separates the passes. +// Byte-identical to `add` followed by `rmsnorm`, on x and on y. +template +__global__ __launch_bounds__(THR) void add_rmsnorm_kernel( + uint16_t* __restrict__ x, const uint16_t* __restrict__ a, const void* __restrict__ w, + uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, + uint32_t a_ld, uint32_t y_ld, uint32_t M) { + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + if (m >= M) return; // a row the launch added past the full-card cliff (r4d_cliff_rows) + uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + const uint16_t* __restrict__ ar = a + (size_t)m * a_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const uint16_t h = f32_to_bf16(bf16_to_f32(xr[i]) + bf16_to_f32(ar[i])); + xr[i] = h; + const float v = bf16_to_f32(h); + ss += v * v; + } + ss = block_sum(ss, lds); + const float s = rsqrtf(ss / (float)n + eps); + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]); + yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * s * (g + wadd) * mult); + } +} + // ---------------------------------------------------------------------------- rmsnorm_p // ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps), rmsnorm with no gain. Gemma's attention applies // it to V (llama.cpp's ggml_rms_norm(V, eps)), which has no checkpoint gain. Accumulates exactly as @@ -1420,6 +1452,53 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { : RAD_E_DEVICE; } +/* ------------------------------------------------------------------ add_rmsnorm */ + +enum { AN_X = 0, AN_A, AN_W, AN_Y }; + +extern "C" int r4d_rad_add_rmsnorm(const RadArgs* a, RadStream s) { + int emit_rc = RAD_OK; + const RadTensor* x = r4d_opt(a, AN_X); + const RadTensor* ad = r4d_opt(a, AN_A); + const RadTensor* w = r4d_opt(a, AN_W); + const RadTensor* y = r4d_opt(a, AN_Y); + if (!x || !ad || !w || !y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(x)); + R4D_NEED(dt_bf16(ad)); + R4D_NEED(dt_bf16(y)); + if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); + if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + const bool w_f32 = w->dtype == RAD_F32; + const long long n = r4d_geti_or(a, "n", r4d_dim(w, (int)w->rank - 1)); + if (n <= 0 || r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE); + long long M = 0, Ma = 0, My = 0; + const long long x_ld = r4d_rows_pitch(x, n, &M); + const long long a_ld = r4d_rows_pitch(ad, n, &Ma); + const long long y_ld = r4d_rows_pitch(y, n, &My); + if (x_ld < 0 || a_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || Ma < M || My < M) return R4D_NO(RAD_E_SHAPE); + const float eps = (float)r4d_getf(a, "eps", 1e-6); + const float wadd = (float)r4d_getf(a, "wadd", 0.0); + const float mult = (float)r4d_getf(a, "mult", 1.0); + /* rmsnorm's width, from the same table (see r4d_rmsnorm_mult_bf16) */ + const int thr = r4d_act_threads((int)M, (int)n); +#define R4D_AN_T(wf, T) \ + emit_rc = R4D_EMIT(s, (add_rmsnorm_kernel), \ + dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \ + (uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \ + (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \ + (uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M) +#define R4D_AN(wf) \ + do { if (thr == 1024) R4D_AN_T(wf, 1024); \ + else if (thr == 512) R4D_AN_T(wf, 512); \ + else R4D_AN_T(wf, 256); } while (0) + if (w_f32) R4D_AN(true); + else R4D_AN(false); +#undef R4D_AN +#undef R4D_AN_T + return emit_rc; +} + /* ------------------------------------------------------------------ rmsnorm_p */ extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) { diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 337717be..8e7fbafe 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -117,6 +117,14 @@ int r4d_rad_attn_prefill_h128_gqa2w_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_gqa2w_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_gqa2w_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs*); +/* attn_paged_qrow on the split-KV decode kernel: the h256/gqa2 decode with q at its own pitch, and + * head_dim 128 at gqa 8 as the gqa-4 kernel with two query groups a kv head (R4DArgs::kv_rep). */ +int r4d_rad_attn_qrow_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_qrow_decode_h256_gqa2_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_qrow_decode_h256_gqa2_scratch(const RadArgs*); +int r4d_rad_attn_qrow_h128_gqa8_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_qrow_h128_gqa8_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs*); /* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not * (r4d_attn_paged_window.hip): one entry point per geometry and cache dtype, every q_len and any q * row pitch, so they serve both attn_paged and attn_paged_qrow. */ @@ -461,6 +469,8 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*); /* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */ int r4d_rad_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream); +int r4d_rad_add_rmsnorm (const RadArgs*, RadStream); +int r4d_rad_qkv_norm_rope_kv_store(const RadArgs*, RadStream); int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs*, RadStream); @@ -781,6 +791,9 @@ int r4d_shape_attn_paged (const RadParam*, int, int operand, RadOpdDesc*) int r4d_shape_attn_paged_gate_quant(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qk_norm_rope_gate (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_qkv_norm_rope (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_qkv_norm_rope_kv_store(const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_add_rmsnorm(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_rope_table (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gdn_gated_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*); @@ -853,6 +866,8 @@ int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseSt int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_add_rmsnorm(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_ar_gather_hc_write (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_attn_paged_gate_quant(const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip index f620efe9..c83a48a3 100644 --- a/libr4d/r4d_qkv_norm_rope.hip +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -18,7 +18,16 @@ // `x0*s + x1*c`), under the library's -ffp-contract=off. // // `v_from_k` is Gemma's global class: k == v, so v is the value norm of the raw k, taken before the -// k norm overwrites it, in the order the unfused block issues them. +// k norm overwrites it, in the order the unfused block issues them. `v_norm` 0 leaves v as it is +// (a Qwen3-shaped layer, the DFlash2 drafter's: q and k normed, v not), so the launch is the two +// norms and two rotaries, and with the store v's heads only store. +// +// `qkv_norm_rope_kv_store` is the same launch followed by `kv_store`: the block of a k head (and of +// a v head) ends holding its token's finished head, so it also writes it into the paged cache at +// the token's slot, converted as kv_store converts it (E4M3: times the inverse descale, clamped to +// +-448, v_cvt_pk_fp8_f32 four columns a lane; bf16: the values as they are). The head is staged in +// LDS for that, since the fp8 store packs four neighbouring columns a lane. Byte-identical to the +// pair at either cache width; the k, v and q rows are still written, as the pair leaves them. // // Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip. #include "r4d.h" @@ -52,10 +61,12 @@ __device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_ return s; } -// The rotary over a normed head staged in `nb`, written to `out`: rope_kernel's body for pair i. +// The rotary over a normed head staged in `nb`, written to `out` (and to `st` when the head is also +// stored): rope_kernel's body for pair i. template __device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t* __restrict__ out, - float p0, uint32_t rot, uint32_t nfreq, int den, float theta) { + float p0, uint32_t rot, uint32_t nfreq, int den, float theta, + uint16_t* __restrict__ st) { const uint32_t half = rot / 2, t = threadIdx.x; if (t < half) { float inv = 1.0f / powf(theta, (float)(2 * t) / (float)den); @@ -64,35 +75,99 @@ __device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t float c, s; sincosf(ang, &s, &c); const float x0 = bf2f(nb[t]), x1 = bf2f(nb[t + half]); - out[t] = f32_to_bf16(x0 * c - x1 * s); - out[t + half] = f32_to_bf16(x0 * s + x1 * c); + const uint16_t y0 = f32_to_bf16(x0 * c - x1 * s), y1 = f32_to_bf16(x0 * s + x1 * c); + out[t] = y0; + out[t + half] = y1; + if (st) { st[t] = y0; st[t + half] = y1; } + } + for (uint32_t i = rot + t; i < HD; i += HD) { // the unrotated tail + out[i] = nb[i]; + if (st) st[i] = nb[i]; + } +} + +// One head into the paged cache at element offset `off` (r4d_model_bf16.hip's kv_store kernels): +// KV 1 an E4M3 cache, four columns a lane as kv_store_fp8_kernel converts them; KV 2 a bf16 cache, +// the values as they are. `src` is the head in LDS, complete before the call. +template +__device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off, + const uint16_t* __restrict__ src, float inv) { + const uint32_t t = threadIdx.x; + if (KV == 1) { + if (t < HD / 4) { + const uint32_t d = t * 4u; + float f[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) f[e] = bf2f(src[d + (uint32_t)e]) * inv; + // clamped because v_cvt_pk_fp8_f32 returns NaN out of range instead of saturating + int pk = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[0], -448.0f), 448.0f), + fminf(fmaxf(f[1], -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(f[2], -448.0f), 448.0f), + fminf(fmaxf(f[3], -448.0f), 448.0f), pk, true); + *(uint32_t*)((uint8_t*)kv + off + d) = (uint32_t)pk; + } + } else if (KV == 2) { + for (uint32_t i = t; i < HD; i += HD) ((uint16_t*)kv)[off + i] = src[i]; } - for (uint32_t i = rot + t; i < HD; i += HD) out[i] = nb[i]; // the unrotated tail } // blockIdx.y: [0, nq) a query head, [nq, nq+nkv) a key head (and with VK its value, from the raw // key), [nq+nkv, nq+2nkv) a value head normalised in place (without VK). -template +// +// KV 1 or 2 also stores each k and v head into the paged cache [n_blocks, nkv, block_size, 2*HD] +// at slot[m] (k at column 0, v at HD), for rows m < n_slot whose slot is in range; KV 0 stores +// nothing and ignores the cache arguments. +template __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos, - uint32_t m_rows) { + uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot, + uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm) { __shared__ float l1[HD / kWave], l2[HD / kWave]; __shared__ uint16_t nb[HD]; + __shared__ uint16_t sb[KV ? HD : 1]; // the head this block stores + __shared__ uint16_t vb[(KV && VK) ? HD : 1]; // and, under VK, the value from the raw k const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x; if (m >= m_rows) return; // a row the launch added past the full-card cliff (r4d_cliff_rows) const float div = rscale != 0.0f ? rscale : 1.0f; // rope rotates only the rows its positions cover; a row past them is normed and not rotated const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f; + // The row's cache slot, as kv_store reads it: a negative or out-of-range slot stores nothing. + // Uniform over the block, so the barriers below are too. + size_t base = 0; + bool put = false; + if (KV && m < n_slot) { + const int32_t sl = slot[m]; + if (sl >= 0 && (uint32_t)sl / block_size < n_blocks) { + put = true; + base = ((size_t)((uint32_t)sl / block_size) * nkv * block_size + + (size_t)((uint32_t)sl % block_size)) * 2 * HD; + } + } + const size_t head_step = (size_t)block_size * 2 * HD; - if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p - uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)(hh - nq - nkv) * HD; - const float s = rsqrtf(head_ss(x, pv, l1) / (float)HD + eps); - __syncthreads(); // every thread has read x before any writes it - for (uint32_t i = t; i < HD; i += HD) x[i] = f32_to_bf16(bf2f(x[i]) * s); + if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p (or, without v_norm, only stored) + const uint32_t h = hh - nq - nkv; + uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)h * HD; + if (vnorm) { + const float s = rsqrtf(head_ss(x, pv, l1) / (float)HD + eps); + __syncthreads(); // every thread has read x before any writes it + for (uint32_t i = t; i < HD; i += HD) { + const uint16_t y = f32_to_bf16(bf2f(x[i]) * s); + x[i] = y; + if (KV) sb[i] = y; + } + } else if (KV) { + for (uint32_t i = t; i < HD; i += HD) sb[i] = x[i]; + } + if (KV && put) { + __syncthreads(); + kv_put(kvc, base + (size_t)h * head_step + HD, sb, v_inv); + } return; } const bool isq = hh < nq; @@ -104,7 +179,11 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( if (VK && !isq) { // v = rmsnorm_p(raw k), before the k norm rewrites k uint16_t* __restrict__ vo = v + (size_t)m * v_ld + (size_t)h * HD; const float sv = rsqrtf(head_ss(x, pv, l2) / (float)HD + eps); - for (uint32_t i = t; i < HD; i += HD) vo[i] = f32_to_bf16(bf2f(x[i]) * sv); + for (uint32_t i = t; i < HD; i += HD) { + const uint16_t y = f32_to_bf16(bf2f(x[i]) * sv); + vo[i] = y; + if (KV && VK) vb[i] = y; + } } const float s = rsqrtf(head_ss(x, isq ? pq : pk, l1) / (float)HD + eps); for (uint32_t i = t; i < HD; i += HD) { @@ -112,16 +191,24 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd)); } __syncthreads(); // the normed head is complete before any pair reads across it - if (m < n_pos) rotate(nb, x, p0, rot, nfreq, den, theta); - else for (uint32_t i = t; i < HD; i += HD) x[i] = nb[i]; + uint16_t* const st = (KV && !isq) ? sb : nullptr; + if (m < n_pos) rotate(nb, x, p0, rot, nfreq, den, theta, st); + else for (uint32_t i = t; i < HD; i += HD) { x[i] = nb[i]; if (st) st[i] = nb[i]; } + if (KV && !isq && put) { + __syncthreads(); // the stored head (and VK's value) complete in LDS + kv_put(kvc, base + (size_t)h * head_step, sb, k_inv); + if (VK) kv_put(kvc, base + (size_t)h * head_step + HD, vb, v_inv); + } } } // namespace -// ============================================================== the plugin ABI entry point -enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW }; +// ============================================================== the plugin ABI entry points +enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW, QN_SLOT, QN_CACHE }; -extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { +// Both ops' launch: `store` reads qkv_norm_rope_kv_store's slot mapping and cache (operands 6, 7) +// and its kv_store parameters. +static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store) { int emit_rc = RAD_OK; const RadTensor* q = r4d_opt(a, QN_Q); const RadTensor* k = r4d_opt(a, QN_K); @@ -138,11 +225,12 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { const long long nkv = r4d_geti_or(a, "n_head_kv", 0); const long long rot = r4d_geti_or(a, "rotary_dim", hd); const long long vk = r4d_geti_or(a, "v_from_k", 0); - // v_norm 0: no value norm at all (Gemma 3); the v heads are left out of the grid. + // v_norm 0: no value norm (Gemma 3; a Qwen3-shaped layer such as the DFlash2 drafter's): the v + // heads are left out of the grid, or with the store only store. const long long vn = r4d_geti_or(a, "v_norm", 1); if (hd != 128 && hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE); - if (vk && !vn) return R4D_NO(RAD_E_INVAL); - if (nq <= 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + if (vk && !vn) return R4D_NO(RAD_E_INVAL); // v from k is v's norm + if (nq < 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(qw) != hd || r4d_numel(kw) != hd) return R4D_NO(RAD_E_SHAPE); const char* mode = r4d_gets(a, "mode"); if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); @@ -158,39 +246,87 @@ extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { const long long rot_l = (den == hd && rot < hd) ? hd : rot; long long M = 0, Mk = 0, Mv = 0; - const long long q_ld = r4d_rows_pitch(q, nq * hd, &M); + /* n_head 0: the k (and v) heads alone, q neither read nor written (a context pass's keys) */ + const long long q_ld = nq ? r4d_rows_pitch(q, nq * hd, &M) : 0; const long long k_ld = r4d_rows_pitch(k, nkv * hd, &Mk); const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv); if (q_ld < 0 || k_ld < 0 || v_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (!nq) M = Mk; const long long Mp = r4d_numel(ps); if (Mp <= 0 || M < Mp || Mk != M || Mv != M) return R4D_NO(RAD_E_SHAPE); // The standalone kernels' widths, from the same function: rmsnorm (one row per head) at // r4d_act_threads(rows, head_dim), rmsnorm_p at 256. - const uint32_t pq = (uint32_t)std::min(r4d_act_threads((int)(M * nq), (int)hd), hd); + const uint32_t pq = nq ? (uint32_t)std::min(r4d_act_threads((int)(M * nq), (int)hd), hd) + : (uint32_t)hd; const uint32_t pk = (uint32_t)std::min(r4d_act_threads((int)(M * nkv), (int)hd), hd); const uint32_t pv = (uint32_t)std::min(256, hd); const float eps = (float)r4d_getf(a, "eps", 1e-6); const float wadd = (float)r4d_getf(a, "wadd", 0.0); const float theta = (float)r4d_getf(a, "theta", 10000.0); const float rsc = (float)r4d_getf(a, "scale", 1.0); - const uint32_t heads = (uint32_t)(nq + nkv + ((vk || !vn) ? 0 : nkv)); + /* v's own heads: normed (and stored), stored only, or with neither nothing to do */ + const uint32_t heads = (uint32_t)(nq + nkv + ((vk || (!vn && !store)) ? 0 : nkv)); // A tp-4 verify of the 31B is 16 rows x 16 heads of 8 wavefronts: exactly a full card, the // cliff r4d_cliff_rows steps past with one idle row. const dim3 grid(r4d_cliff_rows((uint32_t)M, heads, (uint32_t)(hd / kWave)), heads); -#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ + // The store's geometry, checked as kv_store_geom checks it (r4d_model_bf16.hip). + int kvw = 0; // 0 none, 1 E4M3, 2 bf16 + const RadTensor* sm = nullptr; + const RadTensor* kv = nullptr; + long long bs = 0, nblk = 0, nslot = 0; + float kinv = 1.0f, vinv = 1.0f; + if (store) { + sm = r4d_opt(a, QN_SLOT); + kv = r4d_opt(a, QN_CACHE); + if (!sm || !kv) return R4D_NO(RAD_E_INVAL); + if (sm->dtype != RAD_I32 || !r4d_contig(sm) || !r4d_contig(kv)) return R4D_NO(RAD_E_STRIDE); + bs = r4d_geti_or(a, "block_size", 0); + if (bs <= 0 || kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || + kv->shape[3] != 2 * hd) + return R4D_NO(RAD_E_SHAPE); + nblk = kv->shape[0]; + nslot = r4d_numel(sm); + if (nslot <= 0 || nslot > M) return R4D_NO(RAD_E_SHAPE); + if (kv->dtype == RAD_F8E4M3) { + const double ks = r4d_getf(a, "k_scale", 1.0), vs = r4d_getf(a, "v_scale", 1.0); + if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL); + kinv = 1.0f / (float)ks; + vinv = 1.0f / (float)vs; + kvw = 1; + } else if (kv->dtype == RAD_BF16) { + kvw = 2; + } else { + return R4D_NO(RAD_E_DTYPE); + } + } + +#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ (uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \ r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \ (uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp, \ - (uint32_t)M) + (uint32_t)M, (const int32_t*)(sm ? r4d_p(sm) : nullptr), (void*)(kv ? r4d_wp(kv) : nullptr), \ + (uint32_t)nslot, (uint32_t)bs, (uint32_t)nblk, kinv, vinv, (uint32_t)(vn ? 1 : 0)) +#define R4D_QNR_KV(HD, WF, VK) \ + do { if (kvw == 1) R4D_QNR_T(HD, WF, VK, 1); else if (kvw == 2) R4D_QNR_T(HD, WF, VK, 2); \ + else R4D_QNR_T(HD, WF, VK, 0); } while (0) #define R4D_QNR(HD) \ - do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \ - else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0) + do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_KV(HD, true, true); else R4D_QNR_KV(HD, true, false); } \ + else { if (vk) R4D_QNR_KV(HD, false, true); else R4D_QNR_KV(HD, false, false); } } while (0) if (hd == 128) R4D_QNR(128); else if (hd == 256) R4D_QNR(256); else R4D_QNR(512); #undef R4D_QNR +#undef R4D_QNR_KV #undef R4D_QNR_T return emit_rc; } + +extern "C" int r4d_rad_qkv_norm_rope(const RadArgs* a, RadStream stream) { + return qkv_norm_rope_launch(a, stream, false); +} + +extern "C" int r4d_rad_qkv_norm_rope_kv_store(const RadArgs* a, RadStream stream) { + return qkv_norm_rope_launch(a, stream, true); +} diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 9cccf694..4567168a 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -728,6 +728,21 @@ static const RadOperandSpec oGemmNt[] = { * (w5a16, w4a16_asym, w4a8i8_asym, w5a8i8): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each * meet their own copy of the activation, side by side in a row of `a` ([M, parts * K]). 0 leaves a * bound out. Absent on other grids, where a fused projection has one activation. */ +/* `add_rmsnorm` is `add` (x += a) followed by `rmsnorm` of the x it wrote (docs/OPS.md). */ +static const RadParamSpec pAddRmsNorm[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + P_F64("eps"), + { "dtype", RAD_P_STR, RAD_REQUIRED }, + P_F64O("wadd"), + P_F64O("mult"), +}; +static const RadOperandSpec oAddRmsNorm[] = { + { "x", RAD_OPD_INOUT, 0 }, + { "a", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pGemmNtQ[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "N", RAD_P_INT, RAD_REQUIRED }, @@ -1404,6 +1419,7 @@ static const RadParamSpec pQkvNormRope[] = { { "ladder", RAD_P_STR, RAD_OPTIONAL }, P_F64O("wadd"), { "v_from_k", RAD_P_INT, RAD_OPTIONAL }, + /* 0 leaves v unnormed (Gemma 3; a Qwen3-shaped layer); absent, 1 */ { "v_norm", RAD_P_INT, RAD_OPTIONAL }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; @@ -1415,6 +1431,39 @@ static const RadOperandSpec oQkvNormRope[] = { { "q_w", RAD_OPD_WEIGHT, 0 }, { "k_w", RAD_OPD_WEIGHT, 0 }, }; +/* `qkv_norm_rope_kv_store` is qkv_norm_rope followed by kv_store in one launch: the prologue's + * operands, then kv_store's slot mapping and paged cache; every parameter is one of the two ops'. + * Byte-identical to the pair (docs/OPS.md). */ +static const RadParamSpec pQkvNormRopeKv[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "head_dim", RAD_P_INT, RAD_REQUIRED }, + { "n_head", RAD_P_INT, RAD_REQUIRED }, + { "n_head_kv", RAD_P_INT, RAD_REQUIRED }, + P_F64("theta"), + P_F64("eps"), + P_F64O("scale"), + { "mode", RAD_P_STR, RAD_OPTIONAL }, + { "rotary_dim", RAD_P_INT, RAD_OPTIONAL }, + { "ladder", RAD_P_STR, RAD_OPTIONAL }, + P_F64O("wadd"), + { "v_from_k", RAD_P_INT, RAD_OPTIONAL }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "v_norm", RAD_P_INT, RAD_OPTIONAL }, + { "block_size", RAD_P_INT, RAD_REQUIRED }, + { "kv_dtype", RAD_P_STR, RAD_REQUIRED }, + P_F64O("k_scale"), + P_F64O("v_scale"), +}; +static const RadOperandSpec oQkvNormRopeKv[] = { + { "q", RAD_OPD_INOUT, 0 }, + { "k", RAD_OPD_INOUT, 0 }, + { "v", RAD_OPD_INOUT, 0 }, + { "positions", RAD_OPD_IN, 0 }, + { "q_w", RAD_OPD_WEIGHT, 0 }, + { "k_w", RAD_OPD_WEIGHT, 0 }, + { "slot_mapping", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_INOUT, 0 }, +}; /* `gelu_mul_quant_i8` is `gelu_mul` with quant_act_i8's quantiser on its pass: the down projection * input of a GELU-gated feed-forward on the w4a8 grid, byte-identical to the pair. */ @@ -3097,9 +3146,17 @@ static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm_quant_i8", pRmsNormQuantI8, oRmsNormQuantI8, "RMS norm and the per-row int8 quantiser the w4a8 skinny GEMM reads, in one pass; with " "a residual the norm is of residual + x (+ a post-norm of x, x a scalar), stored back."), + SCHEMA("add_rmsnorm", pAddRmsNorm, oAddRmsNorm, + "x = x + a, then y = rmsnorm(x) * (w + wadd) * mult over the x written: a residual add " + "and the next norm in one pass, byte-identical to add then rmsnorm. The norm is taken " + "over the bf16 sum it stores; rmsnorm_add normalises the unrounded one."), SCHEMA("qkv_norm_rope", pQkvNormRope, oQkvNormRope, "per-head q and k RMS norms, the weightless v norm and the rotary of q and k over separate " - "q, k and v projections, in one dispatch; v from the raw k under v_from_k."), + "q, k and v projections, in one dispatch; v from the raw k under v_from_k. n_head 0 " + "leaves q unread (the k and v heads alone)."), + SCHEMA("qkv_norm_rope_kv_store", pQkvNormRopeKv, oQkvNormRopeKv, + "qkv_norm_rope, then kv_store of the finished k and v heads into the paged cache, in one " + "launch."), SCHEMA("gelu_mul_quant_i8", pGeluMulQuantI8, oGeluMulQuantI8, "gelu(gate) * up (tanh form) and the per-row int8 quantiser the w4a8 skinny GEMM reads, in " "one pass."), @@ -3548,6 +3605,19 @@ static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; +/* Head_dim 128 at 8 queries per kv head under attn_paged_qrow: the gqa-4 kernel above with each kv + * head mapped onto two query groups (R4DArgs::kv_rep), so q_len * 4 <= 64 bounds it where gqa 8's + * own decode (q_len <= 8, no window) stops at 8. The 31B's DFlash drafter: 64 heads over 8 kv heads, + * sliding layers over 2048 and a full non-causal one, at a block of 16. Under attn_paged_qrow, which + * no host library declares, so a drafter asking for it learns whether a card serves it. */ +static const RadConstraint cAttnQrowH128G8Fp8[] = { + C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnQrowH128G8Bf16[] = { + C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; /* Gemma 4 dense sliding-window prefill (r4d_attn_paged_h256_gqa2.hip): the decode leg's geometry * without a q_len bound, serving q_len > 32. The kernel's WIN bit masks the window and skips tiles * below it. Without this row the prefill band would have no device kernel, which is fatal (spec @@ -4480,6 +4550,9 @@ static const RadConstraint cRmsNormQuantI8[] = { C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), }; /* head_dim 256 or 512: a workgroup is one head, a thread one channel. */ +static const RadConstraint cAddRmsNorm[] = { + C_GE("n", 1), C_IN("dtype", "bf16"), +}; static const RadConstraint cQkvNormRope[] = { C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), }; @@ -4487,6 +4560,14 @@ static const RadConstraint cQkvNormRope[] = { static const RadConstraint cQkvNormRopeH128[] = { C_EQ("head_dim", 128), C_IN("dtype", "bf16"), }; +static const RadConstraint cQkvNormRopeKv[] = { + C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), + C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cQkvNormRopeKvBf16[] = { + C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), + C_GE("block_size", 1), C_IN("kv_dtype", "bf16"), +}; static const RadConstraint cGeluMulQuantI8[] = { C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), }; @@ -5902,6 +5983,52 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_attn_decode_h128_gqa2w_bf16, r4d_rad_attn_decode_h128_gqa2w_scratch, nullptr, nullptr, r4d_shape_attn_paged }, +/* The same decode under attn_paged_qrow, reading q at its own row pitch: Gemma 4 31B's sliding + * layers read q in the fused q|k|v row. It outranks the windowed qrow rows (R4D_PRIO_ONLY) in its + * band, as attn_paged's does, since it takes 0.26-0.71 of their time there; above q_len 32 the + * windowed kernel serves the op alone. No opd_shape, as for every qrow row: libref has none. */ +{ "attn_qrow_decode_h256_gqa2_fp8kv", "attn_paged_qrow", "attn", + "paged attention reading q at its own row pitch, sliding window, split-KV (decode / verify)", + "head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, " + "window taken from the launch argument (0 = full attention)", + "bf16 query (any row pitch, a multiple of 4), fp8-e4m3 kv cache with per-(seq,head) descales, " + "bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256Gqa2Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_decode_h256_gqa2_fp8, + r4d_rad_attn_qrow_decode_h256_gqa2_scratch, + nullptr, nullptr, nullptr }, + +{ "attn_qrow_decode_h256_gqa2_bf16kv", "attn_paged_qrow", "attn", + "paged attention reading q at its own row pitch, sliding window, split-KV (decode / verify)", + "head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, " + "window taken from the launch argument (0 = full attention)", + "bf16 query (any row pitch, a multiple of 4), bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_decode_h256_gqa2_bf16, + r4d_rad_attn_qrow_decode_h256_gqa2_scratch, + nullptr, nullptr, nullptr }, + +/* Head_dim 128 at gqa 8 under attn_paged_qrow (cAttnQrowH128G8Fp8 says why). */ +{ "attn_qrow_h128_gqa8_fp8kv", "attn_paged_qrow", "attn", + "paged attention, any window, causal or not, split-KV (draft block); q at any row pitch", + "head_dim 128, 8 queries per kv head as two groups of 4 a kv head, paged block 16, q_len <= 16", + "bf16 query (any row pitch, a multiple of 4), fp8-e4m3 kv cache with per-(seq,head) descales, " + "bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnQrowH128G8Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_h128_gqa8_fp8, r4d_rad_attn_qrow_h128_gqa8_scratch, + nullptr, nullptr, nullptr }, + +{ "attn_qrow_h128_gqa8_bf16kv", "attn_paged_qrow", "attn", + "paged attention, any window, causal or not, split-KV (draft block); q at any row pitch", + "head_dim 128, 8 queries per kv head as two groups of 4 a kv head, paged block 16, q_len <= 16", + "bf16 query (any row pitch, a multiple of 4), bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnQrowH128G8Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_h128_gqa8_bf16, r4d_rad_attn_qrow_h128_gqa8_scratch, + nullptr, nullptr, nullptr }, { "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", @@ -7662,7 +7789,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "rope x2, each norm taken by its standalone kernel's partition", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkvNormRope), NOTUNE, - nullptr, nullptr, r4d_rad_qkv_norm_rope }, + nullptr, nullptr, r4d_rad_qkv_norm_rope, nullptr, nullptr, nullptr, r4d_shape_qkv_norm_rope }, { "qkv_norm_rope_h128_bf16", "qkv_norm_rope", "attn", "per-head RMS norms of separate q and k projections, the weightless norm of v unless v_norm is 0, " @@ -7675,6 +7802,41 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cQkvNormRopeH128), NOTUNE, nullptr, nullptr, r4d_rad_qkv_norm_rope }, +/* The prologue and the cache store in one launch: a k (or v) head's block ends holding its token's + * finished head, so it writes it into the cache too, converted as kv_store converts it. Saves the + * store's launch a layer, which at decode is most of its cost. */ +{ "qkv_norm_rope_kv_store_fp8", "qkv_norm_rope_kv_store", "attn", + "qkv_norm_rope, and kv_store into an E4M3 paged cache from the same launch", + "qkv_norm_rope's shapes; cache exactly [n_blocks, n_head_kv, block_size, 2*head_dim], one slot " + "a row; a negative or out-of-range slot stores nothing", + "bf16 q/k/v and gains (or f32 gains), i32 positions and slots, fp8-e4m3 cache, scalar " + "k_scale / v_scale descales; byte-identical to qkv_norm_rope + kv_store_fp8", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkvNormRopeKv), NOTUNE, + nullptr, nullptr, r4d_rad_qkv_norm_rope_kv_store, nullptr, nullptr, nullptr, + r4d_shape_qkv_norm_rope_kv_store, nullptr, r4d_fuse_qkv_norm_rope_kv_store }, + +/* The same into a bf16 cache: the store is the values kv_store_bf16 copies. */ +{ "qkv_norm_rope_kv_store_bf16", "qkv_norm_rope_kv_store", "attn", + "qkv_norm_rope, and kv_store into a bf16 paged cache from the same launch", + "qkv_norm_rope's shapes; cache exactly [n_blocks, n_head_kv, block_size, 2*head_dim], one slot " + "a row; a negative or out-of-range slot stores nothing", + "bf16 q/k/v, gains, cache; i32 positions and slots; byte-identical to qkv_norm_rope + " + "kv_store_bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkvNormRopeKvBf16), NOTUNE, + nullptr, nullptr, r4d_rad_qkv_norm_rope_kv_store, nullptr, nullptr, nullptr, + r4d_shape_qkv_norm_rope_kv_store, nullptr, r4d_fuse_qkv_norm_rope_kv_store }, + +{ "add_rmsnorm_bf16", "add_rmsnorm", "norm", + "x += a, then the root-mean-square norm of the x written, one workgroup a row as rmsnorm_bf16", + "any n; rmsnorm_bf16's width and column partition, so the sum of squares folds as it does", + "bf16 x / a / y, f32 or bf16 gain, fp32 reduction; byte-identical to add_bf16 + rmsnorm_bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAddRmsNorm), NOTUNE, + nullptr, nullptr, r4d_rad_add_rmsnorm, nullptr, nullptr, nullptr, + r4d_shape_add_rmsnorm, nullptr, r4d_fuse_add_rmsnorm }, + { "gelu_mul_quant_i8", "gelu_mul_quant_i8", "quant", "gelu(gate) * up, the tanh form, and quant_act_i8's quantiser in one pass over the row", "n a multiple of 16 and n*2 bytes within LDS; one workgroup per row", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 2f204341..47fe35a0 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -943,9 +943,11 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8 /* Numeric attention check: fill q and the paged k/v with avalanche-random data, run the row, and * compare the bf16 output against the oracle above. A negative control corrupts part of the * reference and requires the comparison to fail. */ +/* `q_extra` > 0: q is a column slice of rows q_extra elements wider than its heads (an + * attn_paged_qrow row reads it at that pitch, as from a fused q|k|v projection). */ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa, int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64, - int64_t bs = 16) { + int64_t bs = 16, int64_t q_extra = 0) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); if (!r) { ok(name, false, "row absent"); return; } @@ -992,8 +994,16 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d } const std::vector bt = iota_i32(max_blocks); - void* d_q = dalloc((size_t)total_q * q_heads * head_dim * 2); - st_memcpy(d_q, qh.data(), qh.size() * 2, hipMemcpyHostToDevice); + const int64_t q_ld = q_heads * head_dim + q_extra; + void* d_q = dalloc((size_t)total_q * q_ld * 2); + { + /* the slice's rows at the pitch, the rest of each row a value no head holds */ + std::vector qp((size_t)total_q * q_ld, h_to_bf16(9.0f)); + for (int64_t t = 0; t < total_q; ++t) + std::memcpy(&qp[(size_t)(t * q_ld)], &qh[(size_t)(t * q_heads * head_dim)], + (size_t)(q_heads * head_dim) * 2); + st_memcpy(d_q, qp.data(), qp.size() * 2, hipMemcpyHostToDevice); + } void* d_kv = dalloc(kv.size()); st_memcpy(d_kv, kv.data(), kv.size(), hipMemcpyHostToDevice); void* d_out = dalloc((size_t)total_q * q_heads * head_dim * 2); @@ -1008,6 +1018,7 @@ static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_d T(nullptr, RAD_I32, { seqs + 1 }), T(d_out, RAD_BF16, { total_q, q_heads, head_dim }), }; + ts[0].stride[0] = q_ld; if (kvdt == RAD_BF16) { absent(ts[4]); absent(ts[5]); } absent(ts[6]); std::vector ps = { @@ -10977,10 +10988,16 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { const RadKernelInfo* rp = find(pl, "rope_bf16"); const RadKernelInfo* fz = find(pl, "qkv_norm_rope_bf16"); if (!np || !nrm || !rp || !fz) { ok("qkv_norm_rope vs its five", false, "rows absent"); return; } + /* vn false: no value norm (Gemma 3's prologue, and a Qwen3-shaped layer such as the DFlash2 + * drafter's), q and k normed and v not, so the chain is four ops and v must come out as it went + * in; nq 0 as well: that layer's keys alone (the drafter's context pass), the chain a k norm and + * a k rope, q passed as k's buffer */ struct Cls { int64_t hd, nq, nkv, rot; const char* ladder; double theta; bool vk, vn; }; for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false, true }, Cls{ 512, 16, 2, 128, "head", 1000000.0, true, true }, - Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false } }) { + Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false }, + Cls{ 256, 8, 4, 256, "rotary", 10000.0, false, false }, + Cls{ 256, 0, 4, 256, "rotary", 10000.0, false, false } }) { /* 8 rows of the head-256 class are 8 x 32 workgroups of 8 wavefronts, a full card: the * launch adds an idle row past the cliff (r4d_cliff_rows), which must not change a byte. */ for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)8, (int64_t)40 }) { @@ -10996,9 +11013,11 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { hkw[(size_t)c] = h_to_bf16(0.5f + 0.005f * (float)((c * 11) % 47)); } for (int64_t m = 0; m < M; ++m) hp[(size_t)m] = (int32_t)(1000 + 7 * m); - void* dq[2] = { dalloc(hq.size() * 2), dalloc(hq.size() * 2) }; + void* dq[2] = { nullptr, nullptr }; void* dk[2] = { dalloc(hk.size() * 2), dalloc(hk.size() * 2) }; void* dv[2] = { dalloc(hv.size() * 2), dalloc(hv.size() * 2) }; + for (int j = 0; j < 2; ++j) dq[j] = cl.nq ? dalloc(hq.size() * 2) : dk[j]; + const int64_t QW = cl.nq ? QD : KD; /* q's width as passed (k's buffer at nq 0) */ void* dqw = dalloc(hqw.size() * 2); void* dkw = dalloc(hkw.size() * 2); void* dp = dalloc(hp.size() * 4); @@ -11016,26 +11035,28 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { int rc = !cl.vn ? RAD_OK : launch_row(np, { T(cl.vk ? dk[0] : dv[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dv[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16") }); - if (rc == RAD_OK) + if (rc == RAD_OK && cl.nq) rc = launch_row(nrm, { T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }), T(dqw, RAD_BF16, { cl.hd }), T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }) }, { PI("M", M * cl.nq), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); if (rc == RAD_OK) rc = launch_row(nrm, { T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dkw, RAD_BF16, { cl.hd }), T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); - for (int j = 0; j < 2 && rc == RAD_OK; ++j) + for (int j = cl.nq ? 0 : 1; j < 2 && rc == RAD_OK; ++j) rc = launch_row(rp, { T(j ? dk[0] : dq[0], RAD_BF16, { M, (j ? cl.nkv : cl.nq) * cl.hd }), T(dp, RAD_I32, { M }) }, { PI("M", M), PI("head_dim", cl.hd), PI("n_head", j ? cl.nkv : cl.nq), PI("n_head_kv", 0), PF("theta", cl.theta), PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), PS("ladder", cl.ladder) }); /* --- the one --- */ if (rc == RAD_OK) - rc = launch_row(fz, { T(dq[1], RAD_BF16, { M, QD }), T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }), + rc = launch_row(fz, { T(dq[1], RAD_BF16, { M, QW }), T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }), T(dp, RAD_I32, { M }), T(dqw, RAD_BF16, { cl.hd }), T(dkw, RAD_BF16, { cl.hd }) }, { PI("M", M), PI("head_dim", cl.hd), PI("n_head", cl.nq), PI("n_head_kv", cl.nkv), PF("theta", cl.theta), PF("eps", eps), PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), PS("ladder", cl.ladder), PF("wadd", wadd), PI("v_from_k", cl.vk ? 1 : 0), PI("v_norm", cl.vn ? 1 : 0), PS("dtype", "bf16") }); - const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + " M=" + std::to_string(M); + const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + + (cl.nq ? "" : " n_head=0") + (cl.vn ? "" : " v_norm=0") + + " M=" + std::to_string(M); if (rc != RAD_OK) { ok((what + " vs its five").c_str(), false, "rc=" + std::to_string(rc)); continue; } int nd = 0, moved = 0; for (int t = 0; t < 3; ++t) { @@ -11047,12 +11068,149 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { const std::vector& h0 = t == 0 ? hq : (t == 1 ? hk : hv); for (size_t i = 0; i < n; ++i) { nd += a[i] != b[i]; moved += b[i] != h0[i]; } } - ok((what + " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2").c_str(), nd == 0 && moved > 0, + ok((what + (cl.nq ? " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2" + : " is byte-identical to rmsnorm + rope over k")).c_str(), + nd == 0 && moved > 0, "differs " + std::to_string(nd) + ", changed from the input " + std::to_string(moved)); + + /* --- and with kv_store folded in (qkv_norm_rope_kv_store): the pair (the prologue's + * output above, then kv_store) against the one launch from the same inputs, at both + * cache widths. Slots are unique with one row's negative (padding, which stores + * nothing), and the caches start marked, so a stray or a missing store shows. --- */ + for (const bool f8 : { true, false }) { + const RadKernelInfo* ks = find(pl, f8 ? "kv_store_fp8" : "kv_store_bf16"); + const RadKernelInfo* fk = find(pl, f8 ? "qkv_norm_rope_kv_store_fp8" + : "qkv_norm_rope_kv_store_bf16"); + const std::string w2 = what + (f8 ? " + kv_store_fp8" : " + kv_store_bf16"); + if (!ks || !fk) { ok(w2.c_str(), false, "rows absent"); continue; } + const int64_t bs = 16, nb = (M + bs - 1) / bs + 2, esz = f8 ? 1 : 2; + const size_t cb = (size_t)(nb * cl.nkv * bs * 2 * cl.hd * esz); + std::vector hs((size_t)M); + for (int64_t m = 0; m < M; ++m) hs[(size_t)m] = (int32_t)((m * 37 + 3) % (nb * bs)); + if (M > 1) hs[1] = -1; + void* dsl = dalloc(hs.size() * 4); + void* dc[2] = { dalloc(cb), dalloc(cb) }; + void* d3[3] = { nullptr, dalloc(hk.size() * 2), dalloc(hv.size() * 2) }; + d3[0] = cl.nq ? dalloc(hq.size() * 2) : d3[1]; + if (!dsl || !dc[0] || !dc[1] || !d3[0] || !d3[1] || !d3[2]) { + ok(w2.c_str(), false, "hipMalloc failed"); + continue; + } + st_memcpy(dsl, hs.data(), hs.size() * 4, hipMemcpyHostToDevice); + st_memset(dc[0], 0x5A, cb); + st_memset(dc[1], 0x5A, cb); + st_memcpy(d3[0], hq.data(), hq.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d3[1], hk.data(), hk.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d3[2], hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + const uint32_t kvdt = f8 ? RAD_F8E4M3 : RAD_BF16; + const char* kvn = f8 ? "fp8_e4m3" : "bf16"; + int r2 = launch_row(ks, { T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }), + T(dsl, RAD_I32, { M }), + T(dc[0], kvdt, { nb, cl.nkv, bs, 2 * cl.hd }) }, + { PI("M", M), PI("head_dim", cl.hd), PI("n_head_kv", cl.nkv), + PI("block_size", bs), PS("kv_dtype", kvn) }); + if (r2 == RAD_OK) + r2 = launch_row(fk, { T(d3[0], RAD_BF16, { M, QW }), T(d3[1], RAD_BF16, { M, KD }), + T(d3[2], RAD_BF16, { M, KD }), T(dp, RAD_I32, { M }), + T(dqw, RAD_BF16, { cl.hd }), T(dkw, RAD_BF16, { cl.hd }), + T(dsl, RAD_I32, { M }), + T(dc[1], kvdt, { nb, cl.nkv, bs, 2 * cl.hd }) }, + { PI("M", M), PI("head_dim", cl.hd), PI("n_head", cl.nq), + PI("n_head_kv", cl.nkv), PF("theta", cl.theta), PF("eps", eps), + PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), + PS("ladder", cl.ladder), PF("wadd", wadd), + PI("v_from_k", cl.vk ? 1 : 0), PS("dtype", "bf16"), + PI("v_norm", cl.vn ? 1 : 0), + PI("block_size", bs), PS("kv_dtype", kvn) }); + if (r2 != RAD_OK) { ok(w2.c_str(), false, "rc=" + std::to_string(r2)); continue; } + std::vector c0(cb), c1(cb); + st_memcpy(c0.data(), dc[0], cb, hipMemcpyDeviceToHost); + st_memcpy(c1.data(), dc[1], cb, hipMemcpyDeviceToHost); + size_t ncd = 0, written = 0; + for (size_t i = 0; i < cb; ++i) { ncd += c0[i] != c1[i]; written += c1[i] != 0x5A; } + size_t nrow = 0; + for (int t = 0; t < 3; ++t) { + void* const pr = t == 0 ? dq[1] : (t == 1 ? dk[1] : dv[1]); + const size_t n = t == 0 ? hq.size() : hk.size(); + std::vector a(n), b(n); + st_memcpy(a.data(), pr, n * 2, hipMemcpyDeviceToHost); + st_memcpy(b.data(), d3[t], n * 2, hipMemcpyDeviceToHost); + for (size_t i = 0; i < n; ++i) nrow += a[i] != b[i]; + } + ok((w2 + " folded into one launch is byte-identical to the pair").c_str(), + ncd == 0 && nrow == 0 && written > 0, + "cache bytes differ " + std::to_string(ncd) + ", q/k/v differ " + + std::to_string(nrow) + ", cache bytes written " + std::to_string(written)); + } } } } +/* ---- add_rmsnorm, against add then rmsnorm -------------------------------------------------- + * + * x = x + a, then rmsnorm of the x written: a DFlash2 drafter's residual add and its next norm. + * Byte-identical on x and on y at every r4d_act_threads width (a query pass's rows, a prefill + * chunk's), with an f32 gain (as plugins declare) and a bf16 one, with and without Gemma's `1 +`. */ +static void add_rmsnorm_numeric(const Plugin& pl) { + const RadKernelInfo* ad = find(pl, "add_bf16"); + const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); + const RadKernelInfo* fz = find(pl, "add_rmsnorm_bf16"); + if (!ad || !nrm || !fz) { ok("add_rmsnorm vs add + rmsnorm", false, "rows absent"); return; } + const int64_t K = 5376; + for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)16, (int64_t)40, (int64_t)300 }) + for (int form = 0; form < 3; ++form) { + const bool f32 = form != 1; + const double wadd = form == 2 ? 1.0 : 0.0; + std::vector hx((size_t)M * K), ha((size_t)M * K), hwb((size_t)K); + std::vector hwf((size_t)K); + for (int64_t r = 0; r < M; ++r) + for (int64_t c = 0; c < K; ++c) { + hx[(size_t)r * K + c] = h_to_bf16(0.029f * (float)((r * 31 + c * 17) % 73) - 1.1f); + ha[(size_t)r * K + c] = h_to_bf16(0.013f * (float)((r * 11 + c * 23) % 61) - 0.4f); + } + for (int64_t c = 0; c < K; ++c) { + hwf[(size_t)c] = 0.7f + 0.0031f * (float)((c * 19) % 53); + hwb[(size_t)c] = h_to_bf16(hwf[(size_t)c]); + } + const size_t nb = (size_t)M * K * 2; + void* dx[2] = { dalloc(nb), dalloc(nb) }; + void* dy[2] = { dalloc(nb), dalloc(nb) }; + void* da = dalloc(nb); + void* dw = dalloc((size_t)K * 4); + if (!dx[1] || !dy[1] || !da || !dw) { ok("add_rmsnorm alloc", false, "hipMalloc failed"); return; } + for (int j = 0; j < 2; ++j) st_memcpy(dx[j], hx.data(), nb, hipMemcpyHostToDevice); + st_memcpy(da, ha.data(), nb, hipMemcpyHostToDevice); + if (f32) st_memcpy(dw, hwf.data(), (size_t)K * 4, hipMemcpyHostToDevice); + else st_memcpy(dw, hwb.data(), (size_t)K * 2, hipMemcpyHostToDevice); + const uint32_t wdt = f32 ? RAD_F32 : RAD_BF16; + const double eps = 1e-6; + int rc = launch_row(ad, { T(dx[0], RAD_BF16, { M, K }), T(da, RAD_BF16, { M, K }), T(dx[0], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(nrm, { T(dx[0], RAD_BF16, { M, K }), T(dw, wdt, { K }), T(dy[0], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); + if (rc == RAD_OK) + rc = launch_row(fz, { T(dx[1], RAD_BF16, { M, K }), T(da, RAD_BF16, { M, K }), T(dw, wdt, { K }), + T(dy[1], RAD_BF16, { M, K }) }, + { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); + const std::string what = std::string("add_rmsnorm M=") + std::to_string(M) + + (f32 ? " f32 gain" : " bf16 gain") + (wadd != 0.0 ? " wadd=1" : ""); + if (rc != RAD_OK) { ok(what.c_str(), false, "rc=" + std::to_string(rc)); continue; } + size_t ndx = 0, ndy = 0, moved = 0; + for (int t = 0; t < 2; ++t) { + std::vector u((size_t)M * K), v((size_t)M * K); + st_memcpy(u.data(), t ? dy[0] : dx[0], nb, hipMemcpyDeviceToHost); + st_memcpy(v.data(), t ? dy[1] : dx[1], nb, hipMemcpyDeviceToHost); + for (size_t i = 0; i < u.size(); ++i) { + (t ? ndy : ndx) += u[i] != v[i]; + if (!t) moved += v[i] != hx[i]; + } + } + ok((what + " is byte-identical to add + rmsnorm").c_str(), ndx == 0 && ndy == 0 && moved > 0, + "x differs " + std::to_string(ndx) + ", y differs " + std::to_string(ndy)); + } +} + /* ---- rmsnorm_quant_i8, against the chain it replaces ------------------------------------------ * * Byte-identical, as the fp8 fusions above, in the three forms a sandwich-norm model issues: the @@ -23810,6 +23968,20 @@ static void device_phase(const Plugin& pl) { attn_case(pl, "attn_decode_h256_gqa6_bf16kv", 256, 6, 1, "bf16", 0); attn_case(pl, "attn_decode_h128_gqa4_fp8kv", 128, 4, 1, "fp8_e4m3", 0); attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0); + /* attn_paged_qrow on the split-KV decode kernel: head_dim 128 at gqa 8 (two query groups a kv + * head, R4DArgs::kv_rep) at the drafter's block of 16, windowed and not, and the h256/gqa2 + * decode with q as a slice of a wider row, at one row and at a verify's sixteen. */ + for (const char* kvd : { "fp8_e4m3", "bf16" }) { + const bool f8 = !std::strcmp(kvd, "bf16") ? false : true; + const char* r128 = f8 ? "attn_qrow_h128_gqa8_fp8kv" : "attn_qrow_h128_gqa8_bf16kv"; + const char* r256 = f8 ? "attn_qrow_decode_h256_gqa2_fp8kv" : "attn_qrow_decode_h256_gqa2_bf16kv"; + attn_numeric_case(pl, r128, 128, 8, 16, kvd, 0, 256); + attn_numeric_case(pl, r128, 128, 8, 16, kvd, 48, 256); + attn_numeric_case(pl, r128, 128, 8, 1, kvd, 0, 256, 16, 2048); + attn_numeric_case(pl, r256, 256, 2, 1, kvd, 0, 256, 16, 2048); + attn_numeric_case(pl, r256, 256, 2, 16, kvd, 0, 256, 16, 2048); + attn_numeric_case(pl, r256, 256, 2, 16, kvd, 64, 256); + } attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 32, "bf16", 1); attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 1, "bf16", 1); /* Gemma 4 dense sliding window, decode, with the model's window of 1024: exercises the @@ -26131,14 +26303,20 @@ static void device_phase(const Plugin& pl) { if (!g_case) std::printf("\ngelu_mul_quant_i8, against the pair it replaces\n"); gelu_mul_quant_i8_numeric(pl); } - if (sel("qkv_norm_rope_bf16")) { - if (!g_case) std::printf("\nqkv_norm_rope, against the five ops it replaces\n"); + if (sel("qkv_norm_rope_bf16") || sel("qkv_norm_rope_kv_store_fp8") || + sel("qkv_norm_rope_kv_store_bf16")) { + if (!g_case) std::printf("\nqkv_norm_rope, and with kv_store folded in, against the ops it " + "replaces\n"); qkv_norm_rope_numeric(pl); } if (sel("rmsnorm_quant_i8")) { if (!g_case) std::printf("\nrmsnorm_quant_i8, against the chain it replaces\n"); rmsnorm_quant_i8_numeric(pl); } + if (sel("add_rmsnorm_bf16")) { + if (!g_case) std::printf("\nadd_rmsnorm, against add then rmsnorm\n"); + add_rmsnorm_numeric(pl); + } /* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape asks * these kernels for. Both rows run: an fc declared over M 1..64 resolves to _m16 for small diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 5f8edd16..075a34e3 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -340,6 +340,20 @@ extern "C" int r4d_shape_rmsnorm(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* add_rmsnorm -- rmsnorm's operands with the addend after x. */ +extern "C" int r4d_shape_add_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t n = pi(p, n_p, "n"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { + opd(D, M, n), + opd(D, M, n), + opd((uint32_t)RAD_F32, n), + opd(D, M, n), + }; + R4D_PICK(l); +} + /* ---- the vision tower's (r4d_vit_bf16.hip). Every optional operand is passed: the norm's bias and * the GEMM's residual are the same code with a branch taken, so this covers both forms. */ extern "C" int r4d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1076,6 +1090,48 @@ extern "C" int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, R4D_PICK(l); } +/* qkv_norm_rope -- separate q [M, n_head * head_dim], k and v [M, n_head_kv * head_dim] (dense + * here; the shim also takes each as a slice of a wider row), the positions, and the q and k gains, + * f32 as every architecture plugin declares them (shim in r4d_qkv_norm_rope.hip). As for `rope`, + * a position is not a lookup: the kernel takes sincos of position x frequency, so it is drawn over + * a context's range, where the angles a decode step sees are, not over the band's rows. */ +extern "C" int r4d_shape_qkv_norm_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t hd = pi(p, n_p, "head_dim"); + const int64_t nq = pi(p, n_p, "n_head"); + const int64_t nkv = pi(p, n_p, "n_head_kv"); + const RadOpdDesc l[] = { + /* at n_head 0 the kernel reads no q; it is passed as k's buffer, so drawn like k */ + opd((uint32_t)RAD_BF16, M, (nq ? nq : nkv) * hd), + opd((uint32_t)RAD_BF16, M, nkv * hd), + opd((uint32_t)RAD_BF16, M, nkv * hd), + opd_idx(M, 0, 32768), + opd((uint32_t)RAD_F32, hd), + opd((uint32_t)RAD_F32, hd), + }; + R4D_PICK(l); +} + +/* qkv_norm_rope_kv_store -- qkv_norm_rope's six, then kv_store's slot mapping (unique slots, as + * the engine hands them) and its paged cache, sized as kv_store's description sizes it. */ +extern "C" int r4d_shape_qkv_norm_rope_kv_store(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + if (operand < 6) return r4d_shape_qkv_norm_rope(p, n_p, operand, out); + const int64_t M = pi(p, n_p, "M"); + const int64_t hd = pi(p, n_p, "head_dim"); + const int64_t kvh = pi(p, n_p, "n_head_kv"); + const int64_t bs = pi(p, n_p, "block_size"); + const uint32_t KV = dt_act(p, n_p, "kv_dtype"); + if (M <= 0 || bs <= 0) return RAD_E_UNSUPPORTED; + const int64_t nb = (M + bs - 1) / bs + 2; + const RadOpdDesc l[] = { + opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), + opd_idx(M, 0, nb * bs, -1, RAD_OPD_F_IDX_UNIQUE), + opd(KV, nb, kvh, bs, 2 * hd), + }; + R4D_PICK(l); +} + /* rope_table -- the cos/sin plane the fused prologue reads (shim in r4d_qk_norm_rope_gate.hip). */ extern "C" int r4d_shape_rope_table(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 0f93a880..56b3d8bb 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3235,7 +3235,9 @@ TEST(declare_is_a_gemma4_trunk) { /* 12 layers: 10 sliding + 2 global (layers 5 and 11). */ CHECK_EQ(count_op(b, "attn_paged"), 12); - CHECK_EQ(count_op(b, "kv_store"), 12); + /* the cache store rides the fused prologue where it resolves (qkv_norm_rope_kv_store) */ + CHECK_EQ(count_op(b, "qkv_norm_rope_kv_store"), 12); + CHECK_EQ(count_op(b, "kv_store"), 0); CHECK_EQ(count_op(b, "rmsnorm_p"), 12); /* weightless value norm, one per layer */ CHECK_EQ(count_op(b, "rope"), 24); /* q + k */ CHECK_EQ(count_op(b, "gelu_mul"), 12); /* Gemma's FFN activation, not SwiGLU */ @@ -3446,6 +3448,7 @@ TEST(gemma4_every_weight_has_a_name_map) { TEST(a_gemma4_decode_step_runs_both_classes_in_order) { RadBuilder b; b.refuse.insert("qkv_norm_rope"); /* force the unfused prologue; fused is checked below */ + b.refuse.insert("qkv_norm_rope_kv_store"); RadModelMeta meta = gemma4_meta(); RadBuildCtx ctx = build_ctx(); CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); @@ -3518,7 +3521,7 @@ TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) { for (int l = 0; l < 12; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q"); - for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) want.push_back(s); if (l < 11) want.push_back("ar_rmsnorm_quant_i8"); @@ -3532,7 +3535,7 @@ TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) { for (int l = 0; l < 12; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) plain.push_back("gemm_nt_q"); - for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q", "all_reduce" }) plain.push_back(s); @@ -3549,7 +3552,7 @@ TEST(a_gemma4_w4a8_step_fuses_its_residual_junctions) { for (int l = 0; l < 12; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q"); - for (const char* s : { "qkv_norm_rope", "kv_store", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) want.push_back(s); @@ -3576,7 +3579,8 @@ TEST(a_gemma4_w4a8_step_without_the_fused_ops_keeps_the_chain_and_one_qkv_quanti } for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) want.push_back(s); - CHECK_EQ(join(gemma4_w4_step({ "rmsnorm_quant_i8", "qkv_norm_rope", "gelu_mul_quant_i8" })), join(want)); + CHECK_EQ(join(gemma4_w4_step({ "rmsnorm_quant_i8", "qkv_norm_rope", "qkv_norm_rope_kv_store", + "gelu_mul_quant_i8" })), join(want)); } /* =============================== gemma4: the assistant (MTP) head =============================== */ @@ -3644,7 +3648,7 @@ TEST(gemma4_assistant_is_a_serial_head_with_no_cache_of_its_own) { /* Four head attention layers beside the trunk's twelve, none storing. */ CHECK_EQ(count_op(b, "attn_paged"), 16); - CHECK_EQ(count_op(b, "kv_store"), 12); + CHECK_EQ(count_op(b, "kv_store") + count_op(b, "qkv_norm_rope_kv_store"), 12); CHECK_EQ(count_op(b, "logit_softcap"), 1); /* trunk only; head logits are not capped */ CHECK_EQ(count_op(b, "logits_gemm"), 2); @@ -4609,10 +4613,10 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ for (int l = 0; l < L; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) { folded.push_back("gemm_nt_q"); apart.push_back("gemm_nt_q"); } - for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) folded.push_back(s); - for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q", "all_reduce" }) apart.push_back(s); @@ -4763,8 +4767,10 @@ rad_kvgroup kv_named(const RadBuilder& b, const char* name) { TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { G431Df f; const RadModelMeta meta = f.meta(); + for (const bool served : { true, false }) { RadBuilder b; g431df_encs(b, false, false); + if (!served) b.refuse.insert("attn_paged_qrow"); RadBuildCtx ctx = build_ctx(); ctx.max_spec = 15; CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); @@ -4782,23 +4788,29 @@ TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { REQUIRE(kvd != 0); CHECK_EQ((int)b.kv_groups[kvd - 1].d.kind, (int)RAD_KV_FULL); CHECK_EQ(b.kv_groups[kvd - 1].d.head_dim, 128); - /* 64 heads over 8 kv heads is gqa 8, and libr4d's head-128 attention takes 4 queries per kv - * head at a block of 16: the cache holds each kv head twice, the projections stay 8 heads - * wide, and every attention and cache write of the drafter sees 16 kv heads at gqa 4. */ - CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 16); + /* 64 heads over 8 kv heads is gqa 8. Where a card serves it under attn_paged_qrow (libr4d's + * head-128 kernel with two query groups a kv head), the cache holds each kv head once and + * attention runs at gqa 8. Where not, libr4d's head-128 attention takes 4 queries per kv head + * at a block of 16: the cache holds each kv head twice, the projections stay 8 heads wide, and + * every attention and cache write of the drafter sees 16 kv heads at gqa 4. */ + const int64_t heads = served ? 8 : 16; + CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, heads); CHECK_EQ(b.bufs[buf_named(b, "df_k") - 1].d.shape[1], 8 * 128); - CHECK_EQ(b.bufs[buf_named(b, "df_k4") - 1].d.shape[1], 16 * 128); + if (served) CHECK_EQ(buf_named(b, "df_k4"), 0); + else CHECK_EQ(b.bufs[buf_named(b, "df_k4") - 1].d.shape[1], 16 * 128); { int n_attn = 0, n_store = 0; for (const auto& o : b.ops) { - if (o.op == "attn_paged" && pint(&o, "head_dim") == 128) { + /* the asking ops (qrow_serves) name no buffer */ + if (o.op == (served ? "attn_paged_qrow" : "attn_paged") && pint(&o, "head_dim") == 128 && + !o.reads.empty()) { ++n_attn; - CHECK_EQ(pint(&o, "gqa"), 4); + CHECK_EQ(pint(&o, "gqa"), served ? 8 : 4); CHECK_EQ(pint(&o, "n_head"), 64); } if (o.op == "kv_store" && pint(&o, "head_dim") == 128) { ++n_store; - CHECK_EQ(pint(&o, "n_head_kv"), 16); + CHECK_EQ(pint(&o, "n_head_kv"), heads); } } CHECK_EQ(n_attn, 2); /* the sliding layers' and the full layer's */ @@ -4844,6 +4856,7 @@ TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { RadBuildCtx c4 = build_ctx(); c4.max_spec = 4; CHECK_EQ(gemma4_bf16::declare(&b4, &meta, &c4), RAD_E_UNSUPPORTED); + } } /* The taps on the w4a8 trunk are declared in the layer they copy, so `dflash_src` is live from its @@ -4917,10 +4930,10 @@ TEST(gemma4_31b_dflash_passes_run_the_drafter_and_nothing_else) { CHECK_EQ(ops.front(), std::string("quant_act_fp8")); const RecOp* o = b.op_of(c.issues.front().op); CHECK(std::find(o->reads.begin(), o->reads.end(), (rad_buf)src) != o->reads.end()); - CHECK_EQ(count_issued(ops, "attn_paged"), 0); + CHECK_EQ(count_issued(ops, "attn_paged") + count_issued(ops, "attn_paged_qrow"), 0); } else { CHECK_EQ(ops.front(), std::string("embed_lookup")); - CHECK_EQ(count_issued(ops, "attn_paged"), 5); + CHECK_EQ(count_issued(ops, "attn_paged") + count_issued(ops, "attn_paged_qrow"), 5); CHECK_EQ(count_writes_to(b, c, tok), 1); } } @@ -5052,21 +5065,26 @@ TEST(gemma4_31b_dflash_head_reads_the_int8_copy_where_the_container_holds_one) { TEST(gemma4_31b_dflash_at_four_ranks) { G431Df f; const RadModelMeta meta = f.meta(); - for (int i8 = 0; i8 < 2; ++i8) { + for (int i8 = 0; i8 < 2; ++i8) + for (const bool served : { true, false }) { RadBuilder b; g431df_encs(b, i8 == 1, true); + if (!served) b.refuse.insert("attn_paged_qrow"); RadBuildCtx ctx = build_ctx(1, 4); ctx.max_spec = 15; CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); const rad_kvgroup kvd = kv_named(b, "kv_draft"); REQUIRE(kvd != 0); - /* two kv heads a rank, each held twice: gqa 4 over the cache (the declares test says why) */ - CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, 4); + /* two kv heads a rank: once at gqa 8 where attn_paged_qrow serves it, else each held twice + * at gqa 4 (the declares test says why) */ + CHECK_EQ(b.kv_groups[kvd - 1].d.n_head_kv, served ? 2 : 4); CHECK_EQ(b.bufs[buf_named(b, "df_q") - 1].d.shape[1], 16 * 128); CHECK_EQ(b.bufs[buf_named(b, "df_k") - 1].d.shape[1], 2 * 128); CHECK(buf_named(b, "df_dgath") > 0); for (const auto& o : b.ops) - if (o.op == "attn_paged" && pint(&o, "head_dim") == 128) CHECK_EQ(pint(&o, "gqa"), 4); + if ((o.op == "attn_paged" || o.op == "attn_paged_qrow") && pint(&o, "head_dim") == 128 && + !o.reads.empty()) + CHECK_EQ(pint(&o, "gqa"), served ? 8 : 4); RadCtx c; c.b = &b; c.rank = 1; c.world = 4; RadBatch batch = decode_batch(); @@ -5079,8 +5097,8 @@ TEST(gemma4_31b_dflash_at_four_ranks) { CHECK_EQ(count_issued(ops, "all_gather"), 1); /* the embedding's reduction and two a layer */ CHECK_EQ(count_issued(ops, "all_reduce"), 1 + 2 * 5); - /* k and v into the cache's layout: two heads, two copies each, a layer */ - CHECK_EQ(count_issued(ops, "cast"), 5 * 2 * (2 * 2)); + /* k and v into the cache's layout: two heads, two copies each, a layer -- or none */ + CHECK_EQ(count_issued(ops, "cast"), served ? 0 : 5 * 2 * (2 * 2)); } } @@ -5231,7 +5249,7 @@ TEST(gemma4_31b_without_libr4d_declares_the_chains_and_asks_for_no_undeclared_op RadBuilder b; g431df_encs(b, i8 == 1, true); for (const char* op : { "rmsnorm_quant_i8", "gelu_mul_quant_i8", "qkv_norm_rope", - "ar_rmsnorm_quant_i8" }) + "qkv_norm_rope_kv_store", "ar_rmsnorm_quant_i8" }) b.undeclared.insert(op); RadBuildCtx ctx = build_ctx(0, world); ctx.max_spec = 15; @@ -5429,6 +5447,75 @@ TEST(gemma4_31b_declares_redhats_dflash2_from_the_speculators_layout) { } } +/* DFlash2's two passes each run their attention prologue as one launch a layer where + * qkv_norm_rope_kv_store resolves: the query pass with its q heads (8 a rank at four ranks; v_norm + * 0), the context pass with none (n_head 0: the keys alone, q passed as k's buffer, which it does + * not read). With the fold refused, both chains return: the norms, the rotaries and kv_store. */ +TEST(gemma4_31b_dflash2_folds_both_passes_prologues) { + G431Df2 f; + const RadModelMeta meta = f.meta(); + const int L = 5; + for (int off = 0; off < 2; ++off) { + RadBuilder b; + g431df2_encs(b, true); + if (off) b.refuse.insert("qkv_norm_rope_kv_store"); + RadBuildCtx ctx = build_ctx(0, 4); + ctx.max_tok = 2048; + ctx.max_spec = 7; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + const auto ver = kit(b, { 8 }, {}); + const auto ctxp = context_pass(b, *ver); + const auto qry = query_pass(b, 1, 8, 7); + const auto v = run_passes(b, gemma4_bf16::step, { ctxp.get(), qry.get() }, 0, 4); + REQUIRE(steps_ok(v)); + for (int p = 0; p < 2; ++p) { + const RadCtx& c = *v[(size_t)p]; + int fused = 0; + for (const RecIssue& is : c.issues) { + const RecOp* o = b.op_of(is.op); + if (!o || o->op != "qkv_norm_rope_kv_store") continue; + ++fused; + CHECK_EQ(pint(o, "n_head"), p == 0 ? 0 : 8); + CHECK_EQ(pint(o, "v_norm"), 0); + if (p == 0) { + REQUIRE(is.opd.size() >= 2); + CHECK_EQ(is.opd[0].handle, is.opd[1].handle); + } + } + const std::vector ops = issued_ops(b, c); + CHECK_EQ(fused, off ? 0 : L); + CHECK_EQ(count_issued(ops, "kv_store"), off ? L : 0); + CHECK_EQ(count_issued(ops, "rope"), off ? (p == 0 ? L : 2 * L) : 0); + } + } +} + +/* DFlash2's query pass issues each residual add with the norm after it, as one add_rmsnorm where it + * resolves: after every attention (the feed-forward norm) and every feed-forward (the next layer's + * attention norm, after the last the final norm), ten on the 31B's five layers, no add left and + * one plain norm (layer 0's, after the embedding). With add_rmsnorm refused, the pairs. */ +TEST(gemma4_31b_dflash2_folds_each_residual_add_into_the_next_norm) { + G431Df2 f; + const RadModelMeta meta = f.meta(); + const int L = 5; + for (int off = 0; off < 2; ++off) { + RadBuilder b; + g431df2_encs(b, true); + if (off) b.refuse.insert("add_rmsnorm"); + RadBuildCtx ctx = build_ctx(0, 4); + ctx.max_tok = 2048; + ctx.max_spec = 7; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + const auto qry = query_pass(b, 1, 8, 7); + const auto v = run_passes(b, gemma4_bf16::step, { qry.get() }, 0, 4); + REQUIRE(steps_ok(v)); + const std::vector ops = issued_ops(b, *v[0]); + CHECK_EQ(count_issued(ops, "add_rmsnorm"), off ? 0 : 2 * L); + CHECK_EQ(count_issued(ops, "add"), off ? 2 * L : 0); + CHECK_EQ(count_issued(ops, "rmsnorm"), off ? 2 * L + 1 : 1); + } +} + /* Every engine step with RedHatAI's DFlash2 behind the trunk lints clean at one, two and four ranks: * decode, a mixed step, a prefill chunk, and a verify step with the drafter's context and query * passes behind it (block 8). */ @@ -5574,20 +5661,39 @@ TEST(gemma4_31b_takes_q_k_and_v_as_one_linear_where_the_container_holds_them_so) CHECK_EQ((int)qkv->d.n_row_parts, global ? 2 : 3); } - for (const int q : { 1, 16 }) { + for (const int q : { 1, 16, 40 }) { const auto k = kit(b, { q }, {}); const auto v = run_passes(b, gemma4_bf16::step, { k.get() }, 0, world); CHECK_PASSES(b, v); const std::vector ops = issued_ops(b, *v[0]); CHECK_EQ(count_issued(ops, "gemm_nt_q"), (int)(4 * L)); - CHECK_EQ(count_issued(ops, "attn_paged_qrow"), 2); - CHECK_EQ(count_issued(ops, "attn_paged"), 10); + /* the sliding layers read the row up to 32 rows a sequence (gqa 2), copy q out above */ + const bool dec = q <= 32; + CHECK_EQ(count_issued(ops, "attn_paged_qrow"), dec ? 12 : 2); + CHECK_EQ(count_issued(ops, "attn_paged"), dec ? 0 : 10); CHECK_EQ(count_issued(ops, "quant_act_i8"), (int)L); /* o_proj's input only */ - CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qs")), q == 1 ? 0 : 10); + CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qs")), dec ? 0 : 10); /* the GEMM, then qkv_norm_rope in place */ CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qkvs")), 2 * 10); CHECK_EQ(count_writes_to(b, *v[0], buf_named(b, "attn_qkvg")), 2 * 2); } + + /* Where attn_paged_qrow is not served: attn_paged everywhere, q in the row at one row and + * copied out above it. */ + RadBuilder r; + g431df_encs(r, false, true, true); + r.refuse.insert("attn_paged_qrow"); + REQUIRE_EQ(gemma4_bf16::declare(&r, &meta, &ctx), RAD_OK); + for (const int q : { 1, 16 }) { + const auto k = kit(r, { q }, {}); + const auto v = run_passes(r, gemma4_bf16::step, { k.get() }, 0, world); + CHECK_PASSES(r, v); + const std::vector ops = issued_ops(r, *v[0]); + CHECK_EQ(count_issued(ops, "attn_paged_qrow"), 0); + CHECK_EQ(count_issued(ops, "attn_paged"), 12); + CHECK_EQ(count_writes_to(r, *v[0], buf_named(r, "attn_qs")), q == 1 ? 0 : 10); + CHECK_EQ(count_writes_to(r, *v[0], buf_named(r, "attn_qg")), q == 1 ? 0 : 2); + } } } @@ -6010,6 +6116,23 @@ TEST(qwen35_fp8_steps_lint_clean_with_a_dflash2_drafter) { lint_qwen35_fp8_family(qwen35_fp8::declare, qwen35_fp8::step, mk.meta(), 7, true, 8); } +/* Qwen3.8's DFlash2 drafter has head_dim 128, outside every qkv_norm_rope_kv_store a library serves + * (libr4d's: 256 to 512), and an op declared for a shape that resolves to no device kernel refuses + * startup whether or not it is issued. So the block declares no prologue fold for it, and each pass + * keeps its norm, rope and kv_store chain; the residual adds, which add_rmsnorm serves at n_embd, + * still fold, two a layer. */ +TEST(qwen35_fp8_dflash2_head_128_drafter_declares_no_prologue_fold) { + MetaKV mk = with_dflash2(q35fp8_meta()); + RadBuilder b; + RadBuildCtx ctx = spec_ctx(0, 1, 7); + REQUIRE_EQ(qwen35_fp8::declare(&b, mk.meta(), &ctx), RAD_OK); + int folds_128 = 0; + for (const auto& o : b.ops) + if (o.op == "qkv_norm_rope_kv_store" && pint(&o, "head_dim") == 128) ++folds_128; + CHECK_EQ(folds_128, 0); + CHECK_EQ(count_op(b, "add_rmsnorm"), 2 * 2); +} + /* =============================== gemma3: TranslateGemma 27B's trunk =========================== */ namespace { @@ -7783,13 +7906,13 @@ struct ArchCases { nullptr, 3, { "ar_rmsnorm_quant_fp8" }, 0x1c28909125c12f52ull); add("qwen35_fp8 + DFlash2", [this, sc](RadBuilder* b) { auto c = sc(1, 7); return qwen35_fp8::declare(b, q35df.meta(), &c); }, - qwen35_fp8::step, 7, {}, 0xb5691456a0ce7e9dull); + qwen35_fp8::step, 7, {}, 0x76bc2f92b452df49ull); add("qwen35_w8a8 + DFlash2", [this, sc](RadBuilder* b) { auto c = sc(1, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, - qwen35_w8a8::step, 7, {}, 0xed8219da9fcc0ceaull); + qwen35_w8a8::step, 7, {}, 0x5570932de623edcaull); add("qwen35_w8a8 + DFlash2, two ranks", [this, sc](RadBuilder* b) { auto c = sc(2, 7); return w8a8_declare(b, q35w8df.meta(), &c); }, - nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0x2c00f131709dedcfull); + nullptr, 7, { "ar_rmsnorm_quant_fp8" }, 0xec1ca3ad670311bbull); add("qwen35moe_fp8 + MTP", [this, sc](RadBuilder* b) { auto c = sc(1, 3); return qwen35moe_fp8::declare(b, q35moe.meta(), &c); }, qwen35moe_fp8::step, 3, {}, 0x1bd3b53543cd06eeull); @@ -7814,19 +7937,19 @@ struct ArchCases { * are the earlier pins, 0xafc23087c634a537, 0x719fa07788f8b98a and 0x93b174ab52cc0d31. */ add("gemma4_bf16", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x174e157911e121a9ull); + gemma4_bf16::step, 0, {}, 0x2ba2f4943031468full); add("gemma4_bf16, w4a8", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x4bf536b78c6b11eeull); + gemma4_bf16::step, 0, {}, 0x2e4c6e3235dd3802ull); add("gemma4_bf16, w4a8, two ranks", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, - nullptr, 0, {}, 0xed7ccbb0c6aecfebull); + nullptr, 0, {}, 0xade9c0ccfad1fd47ull); add("gemma4_bf16, w4a8, fused qkv", [this, sc, g4qkv](RadBuilder* b) { g4qkv(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, - gemma4_bf16::step, 0, {}, 0x0ae60e16d6b6424cull); + gemma4_bf16::step, 0, {}, 0x3913aca59733d0e2ull); add("gemma4_bf16, w4a8, fused qkv, two ranks", [this, sc, g4qkv](RadBuilder* b) { g4qkv(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, - nullptr, 0, {}, 0xcc58bb53457bca11ull); + nullptr, 0, {}, 0x8a9935e773f546efull); add("gemma4", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4::declare(b, &g4m, &c); }, gemma4::step, 0, {}, 0x0f227f5853b6488cull); @@ -8218,8 +8341,8 @@ TEST(gemma4_assistant_head_engine_step_lints_clean) { * fingerprints above). */ TEST(gemma4_bf16_without_the_fused_ops_declares_the_chains_and_asks_for_no_undeclared_op) { const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); - const std::set fused = { "qkv_norm_rope", "rmsnorm_quant_i8", "gelu_mul_quant_i8", - "ar_rmsnorm_quant_i8" }; + const std::set fused = { "qkv_norm_rope", "qkv_norm_rope_kv_store", "rmsnorm_quant_i8", + "gelu_mul_quant_i8", "ar_rmsnorm_quant_i8" }; for (int world : { 1, 2 }) { std::vector seq[2]; for (int undeclared = 0; undeclared < 2; ++undeclared) { From cb5a69ac3f993560ed8dcb32fa524b3b9f987c62 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sat, 17 Oct 2026 10:17:39 -0500 Subject: [PATCH 122/152] engine: a block drafter on the card's acceptance -- its passes queued behind the step, the next step issued ahead A block drafter (DFlash) ran its two passes after the commit, staged from the committed sequence: the verify, a host wait and the commit, the context and query passes, a second host wait for the proposals, then the next step's build and issue, with the cards idle through each host turn and the ranks starting every pass at different times. Pipelining was off for block drafters. It now takes the serial drafters' path (sched/advance.h). After the trunk's ranks join, the acceptance runs on every rank (ADV_ACCEPT). block_begin runs before the commit (on_card): the context pass mirrors the trunk step, whose positions the host knows (a row issued ahead continued from the committed end, as commit() reads it); the query block's rows are device rows staged at the furthest anchor acceptance could leave, with the KV reservation that far, and ADV_BLOCK puts the anchor (the token the verify chose) and the masks at the card's committed end. After the query pass, ADV_BTAKE takes the proposals into each StepSlot behind the anchor, which is the token row the next verify reads (ADV_TRUNK), so issue_ahead verifies them with no host round trip. The slots come back with the step's one readback; finish_block_drafter checks the card's acceptance against the host's, as the serial driver does, publishes the proposals and moves the drafter's filled range. RADIANCE_DRAFT_BLOCK_HOST=1 keeps the host's driver, for the A/B, and has a row in GUIDE.md's environment table. On libref with the tiny 31B-shaped checkpoint (and one doctored so its drafter is right part of the time) the two drivers give the same replies, the same draft acceptance and the same sampled text, and greedy matches plain decoding. sched_test runs 24 pipelined steps against the host's driver: the same trunk steps and the same context and query passes, positions, lengths and slots (the context pass's token ids aside, which that pass does not read); advance_test covers the two modes and the chain. Co-Authored-By: Claude Opus 5.5 --- core/engine.cpp | 33 +++++--- core/engine.h | 17 +++- core/engine_draft.cpp | 134 +++++++++++++++++++++++------ core/sched/advance.h | 12 ++- core/sched/advance_impl.h | 17 ++++ core/sched/scheduler.cpp | 39 +++++++-- core/sched/scheduler.h | 13 ++- docs/GUIDE.md | 1 + spec.md | 4 +- tests/advance_test.cpp | 120 ++++++++++++++++++++++++++ tests/sched_test.cpp | 173 ++++++++++++++++++++++++++++++++++++++ 11 files changed, 508 insertions(+), 55 deletions(-) diff --git a/core/engine.cpp b/core/engine.cpp index fff9bb5f..f5d0d25e 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -353,6 +353,8 @@ int Engine::issue_ahead(const RadBatch** out) { if (!pipelining_) return RAD_OK; for (int i = 0; i < serial_rows_ && serial_done_ > 0; ++i) sched_.expect_draft(serial_row_[(size_t)i].seq, serial_done_); + for (int i = 0; i < block_rows_; ++i) + sched_.expect_draft(block_row_[(size_t)i].seq, drafter_.depth); const RadBatch* nb = sched_.step_next(); if (!nb) return RAD_OK; /* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance @@ -403,9 +405,13 @@ int Engine::step_loop() { int idle = 0; std::vector cancel; /* Not in KL mode: its scored rows are copied out of the logits buffer after collection, and a - * pass issued ahead would overwrite them. */ - pipelining_ = !cfg_.kld() && !embedding_ && drafter_.kind != RAD_DRAFT_BLOCK && - (serial_drafting() || cfg_.n_spec <= 0); + * pass issued ahead would overwrite them. A block drafter pipelines only on the card + * (engine_draft.cpp); the host's driver stages from the committed sequence. */ + block_card_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && !cfg_.kld() && + !embedding_ && [] { const char* v = std::getenv("RADIANCE_DRAFT_BLOCK_HOST"); + return !(v && *v && *v != '0'); }(); + pipelining_ = !cfg_.kld() && !embedding_ && (drafter_.kind != RAD_DRAFT_BLOCK || block_card_) && + (serial_drafting() || block_card_ || cfg_.n_spec <= 0); const bool t_on = (int)log_level() >= (int)Log::Debug; /* The next step's forward pass when already issued behind the previous step, before its * readback (Scheduler::step_next). */ @@ -696,10 +702,10 @@ int Engine::step_loop() { } if (t_on) phase_mark(PH_SAVE); - /* Queue the serial drafter's passes behind the step before waiting: the card computes - * acceptance itself and every pass reads it there (sched/advance.h), so one wait covers - * the whole step. */ - st = issue_serial_drafter(b->step, so); + /* Queue the drafter's passes behind the step before waiting: the card computes acceptance + * itself and every pass reads it there (sched/advance.h), so one wait covers the whole + * step. */ + st = block_card_ ? issue_block_drafter(b->step, so) : issue_serial_drafter(b->step, so); if (st < 0) return fail_loop(st); st = mark_step_end(b, so); if (st < 0) return fail_loop(st); @@ -763,12 +769,13 @@ int Engine::step_loop() { if (t_on) phase_mark(PH_COMMIT); if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); } - /* The drafter for the next step. A block drafter runs here, since its passes are staged - * from the committed sequence. A serial one already ran on the card; what remains is to - * check its acceptance against the host's and publish its proposals. Both drivers return - * immediately for a kind that is not theirs. */ - st = drafter_.kind == RAD_DRAFT_BLOCK ? run_block_drafter(b->step) - : finish_serial_drafter(so); + /* The drafter for the next step. The host's block driver runs here, since it stages from + * the committed sequence. A serial one, or a block one on the card, already ran; what + * remains is to check its acceptance against the host's and publish its proposals. Each + * driver returns immediately for a kind that is not its own. */ + st = drafter_.kind != RAD_DRAFT_BLOCK ? finish_serial_drafter(so) + : block_card_ ? finish_block_drafter(so) + : run_block_drafter(b->step); if (st < 0) return fail_loop(st); /* The step ends here, after its draft rounds, so step timing includes them * (Scheduler::step_finished). */ diff --git a/core/engine.h b/core/engine.h index e8b4e180..ca9c8e36 100644 --- a/core/engine.h +++ b/core/engine.h @@ -382,8 +382,8 @@ private: int issue_ahead(const RadBatch** out); /* The arena level and the followers' pools, before any release that runs a forward pass. */ int prepare_release(const RadBatch* b); - /* Whether a step may be issued ahead: requires that the drafter, if any, runs on the card (a - * block drafter and the prompt-lookup drafter both read the committed sequence). */ + /* Whether a step may be issued ahead: requires that the drafter, if any, runs on the card (the + * prompt-lookup drafter and the host's block driver both read the committed sequence). */ bool pipelining_ = false; int finish_serial_drafter(const StepOut& so); /* Handed from issue_serial_drafter to finish_serial_drafter: the drafting rows, the rounds @@ -407,8 +407,19 @@ private: void phase_mark(int p); /* Block driver (spec §10): a context pass mirroring the step just run, then one pass that - * fills every drafted position at once. DFlash2 has this shape. */ + * fills every drafted position at once. DFlash2 has this shape. run_block_drafter stages both + * after the commit; on the card (`block_card_`, the default), issue_block_drafter queues them + * behind the step before its readback and finish_block_drafter publishes the proposals after + * the commit, so the step can be issued ahead. RADIANCE_DRAFT_BLOCK_HOST=1 keeps the host's. */ int run_block_drafter(int step); + int block_pass(const RadBatch* db, const char* what, int step); + bool block_card_ = false; + int issue_block_drafter(int step, StepOut& so); + int finish_block_drafter(const StepOut& so); + /* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows, + * in the query pass's order, and how many there are (0 when no query pass ran). */ + std::vector block_row_; + int block_rows_ = 0; /* Encoder driver (spec §11, core/engine_mm.cpp): encodes every media item the scheduler waits * on, in passes of whole segments, and reads it back into the item. Runs between steps, never * inside one. */ diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp index 61a12d26..cc43a80f 100644 --- a/core/engine_draft.cpp +++ b/core/engine_draft.cpp @@ -275,7 +275,37 @@ int Engine::finish_serial_drafter(const StepOut& so) { * one. * * Proposals go out through set_draft() like every other. + * + * Two drivers run these passes. run_block_drafter, after the step commits, stages both from the + * committed sequence and reads the proposals back: two host waits a step with the card idle + * between them, and no step issued ahead. The card's driver (issue_block_drafter, the default) + * queues both behind the step before its readback, from the card's acceptance, as the serial + * driver does; RADIANCE_DRAFT_BLOCK_HOST=1 selects the host's. */ + +/* One drafter pass through the barrier. Neither pass samples (no logits in the context pass; the + * query pass has its own selector), so the sampler chain is zero rows. */ +int Engine::block_pass(const RadBatch* db, const char* what, int step) { + for (auto& rk : ranks_) { + int s = rk->sampler.build_greedy(0); + if (s < 0) { + RAD_ERR("drafter '%s': build_greedy: %s", drafter_.name, rad_strerror(s)); + return s; + } + } + issue_what_.store(kIssueAll, std::memory_order_release); + step_batch_.store(db, std::memory_order_release); + barrier_->arrive_and_wait(); + barrier_->arrive_and_wait(); + const int s = step_status_.load(std::memory_order_acquire); + if (s < 0) + RAD_ERR("drafter '%s': %s pass of step %d failed: %s -- the engine cannot continue", + drafter_.name, what, step, rad_strerror(s)); + /* Probe after each pass; by the step loop's dump these buffers hold stale values. */ + if (s >= 0) dump_buffers(ranks_[0]->ctx, step, what); + return s; +} + int Engine::run_block_drafter(int step) { if (drafter_.kind != RAD_DRAFT_BLOCK || drafter_.depth <= 0) return RAD_OK; @@ -294,39 +324,16 @@ int Engine::run_block_drafter(int step) { return RAD_E_STATE; } - /* Neither pass samples (no logits in the context pass; the query pass has its own selector), - * so the sampler chain is zero rows. */ - auto run_pass = [&](const RadBatch* db, const char* what) -> int { - for (auto& rk : ranks_) { - int s = rk->sampler.build_greedy(0); - if (s < 0) { - RAD_ERR("drafter '%s': build_greedy: %s", drafter_.name, rad_strerror(s)); - return s; - } - } - issue_what_.store(kIssueAll, std::memory_order_release); - step_batch_.store(db, std::memory_order_release); - barrier_->arrive_and_wait(); - barrier_->arrive_and_wait(); - const int s = step_status_.load(std::memory_order_acquire); - if (s < 0) - RAD_ERR("drafter '%s': %s pass of step %d failed: %s -- the engine cannot continue", - drafter_.name, what, step, rad_strerror(s)); - /* Probe after each pass; by the step loop's dump these buffers hold stale values. */ - if (s >= 0) dump_buffers(r0.ctx, step, what); - return s; - }; - /* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the * drafter will need, and skipping would leave a permanent hole in its cache. */ - if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(run_pass(cb, "context")); + if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step)); /* Cleared so a query batch that could not be built does not republish the previous step's * proposals. */ draft_out_.clear(); if (n > 0) { if (const RadBatch* qb = sched_.block_query(step)) { - RAD_TRY(run_pass(qb, "query")); + RAD_TRY(block_pass(qb, "query", step)); const int64_t n_raw = (int64_t)n * steps; int32_t* const raw = readback_.reserve(n_raw); if (!raw) return RAD_E_NOMEM; @@ -346,4 +353,81 @@ int Engine::run_block_drafter(int step) { return RAD_OK; } +/* The card's driver: both passes behind the step, without waiting. After the trunk's ranks join, + * the acceptance runs on every rank (ADV_ACCEPT), leaving each sequence's anchor and committed + * end in its StepSlot. The context pass mirrors the trunk step, whose positions the host knows. + * The query pass's rows are device rows that the card positions at the committed end (ADV_BLOCK), + * and its proposals go into the slots behind the anchor (ADV_BTAKE): exactly the token row the + * next verify reads (ADV_TRUNK), so the step issued ahead verifies them with no host round trip. + * collect_step's wait covers both passes and the slots' readback. */ +int Engine::issue_block_drafter(int step, StepOut& so) { + block_rows_ = 0; + if (!block_card_) return RAD_OK; + + RAD_TRY(advance_all(ADV_ACCEPT, 0, false)); + /* The sampled ids before either pass, as the serial driver reads them. */ + RAD_TRY(collect_issue(so)); + + const int steps = drafter_.depth; + const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1; + block_row_.resize((size_t)cfg_.max_seqs); + const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token, + block_row_.data(), (int)block_row_.size(), /*on_card=*/true); + + /* Even when nothing drafts; see run_block_drafter. */ + if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step)); + if (n <= 0) return RAD_OK; + const RadBatch* qb = sched_.block_query(step); + if (!qb) return RAD_OK; + RAD_TRY(advance_all(ADV_BLOCK, 0, false)); + RAD_TRY(block_pass(qb, "query", step)); + RAD_TRY(advance_all(ADV_BTAKE, steps, true, n)); + Rank& r0 = *ranks_[0]; + RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots, + (int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream())); + block_rows_ = n; + return RAD_OK; +} + +/* After commit: check the host's acceptance against the card's, which positioned the query pass + * (a disagreement is a defect and the step is refused, as in finish_serial_drafter), move the + * drafter's filled range, and publish each row's proposal from the slots. */ +int Engine::finish_block_drafter(const StepOut& so) { + if (!block_card_) return RAD_OK; + if (block_rows_ > 0) { + const StepPlan& plan = sched_.plan(); + for (size_t i = 0; i < plan.e.size(); ++i) { + const StepEntry& e = plan.e[i]; + if (so.first_row[i] < 0) continue; + const StepSlot& S = slots_host_[e.card]; /* in range: the builder refuses others */ + if (S.acc != so.accepted[i] || S.tok[0] != so.token[i]) { + RAD_ERR("drafter '%s': the card accepted %d draft(s) ending in token %d for " + "sequence %llu and the host %d ending in %d; the query pass ran from the " + "card's", drafter_.name, S.acc, S.tok[0], (unsigned long long)e.seq, + so.accepted[i], so.token[i]); + sched_.block_end(); + return RAD_E_STATE; + } + } + } + sched_.block_end(); + if (block_rows_ <= 0) return RAD_OK; + + Rank& r0 = *ranks_[0]; + const int steps = drafter_.depth; + draft_out_.assign((size_t)block_rows_ * (size_t)steps, 0); + for (int i = 0; i < block_rows_; ++i) { + const StepSlot& S = slots_host_[block_row_[(size_t)i].card]; + for (int j = 0; j < steps; ++j) + draft_out_[(size_t)i * (size_t)steps + (size_t)j] = S.tok[1 + j]; + } + for (int i = 0; i < block_rows_; ++i) { + /* As in finish_serial_drafter: the step issued ahead only carries a request whose answer + * is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. */ + if (!r0.sampler.allows_speculation(block_row_[(size_t)i].seq)) continue; + sched_.set_draft(block_row_[(size_t)i].seq, &draft_out_[(size_t)i * (size_t)steps], steps); + } + return RAD_OK; +} + } /* namespace rad */ diff --git a/core/sched/advance.h b/core/sched/advance.h index ec6dc705..6776a123 100644 --- a/core/sched/advance.h +++ b/core/sched/advance.h @@ -44,6 +44,9 @@ enum AdvMode : int32_t { ADV_HIST = 3, /* before the draft head's history pass: the verified positions */ ADV_ROUND = 4, /* before draft round `round` >= 2: the next position, the last proposal */ ADV_TAKE = 5, /* after the last round: its proposal into the state */ + /* A block drafter (RAD_DRAFT_BLOCK) on the card: */ + ADV_BLOCK = 6, /* before the query pass: the anchor at the committed end, then the masks */ + ADV_BTAKE = 7, /* after it: its `round` proposals into the state, behind the bonus token */ }; /* One KV group, as the builder stages it for this build. Offsets are bytes into the rank's slab, @@ -63,7 +66,8 @@ struct AdvGroup { * kernel's argument. */ struct AdvanceArgs { int32_t mode = 0; - int32_t round = 0; /* ADV_ROUND: the draft round, from 2; ADV_TAKE: the last, from 1 */ + int32_t round = 0; /* ADV_ROUND: the draft round, from 2; ADV_TAKE: the last, from 1; + * ADV_BTAKE: how many proposals a row */ int32_t n_seq = 0; int32_t n_groups = 0; char* slab = nullptr; /* this rank's device slab */ @@ -72,13 +76,15 @@ struct AdvanceArgs { /* [4][row_pitch] int32: device-row flag; the verify step's token row of the row's first * verified position; its first sampled row, or -1 for a row that sampled nothing; and one * number the mode reads -- ADV_ACCEPT the row's draft count, ADV_HIST how many of the row's - * positions come before the verified ones, whose tokens the host staged. */ + * positions come before the verified ones, whose tokens the host staged, ADV_BLOCK the token + * id its mask rows embed. */ int64_t row_off = 0; int32_t row_pitch = 0; int64_t grp_off = 0; /* [n_groups] AdvGroup */ StepSlot* st = nullptr; /* [max_seqs], by scheduler slot */ /* ADV_ACCEPT and ADV_HIST: the verify step's sampled tokens, one a row. ADV_ROUND and - * ADV_TAKE: the last round's proposals, row i at i * src_pitch. */ + * ADV_TAKE: the last round's proposals, row i at i * src_pitch. ADV_BTAKE: the block's + * proposals, row i's from i * src_pitch. */ const int32_t* src = nullptr; int64_t src_pitch = 1; const int32_t* eog = nullptr; /* end-of-generation ids, sorted */ diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h index df289759..bf331cce 100644 --- a/core/sched/advance_impl.h +++ b/core/sched/advance_impl.h @@ -159,6 +159,23 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) { case ADV_TAKE: S.tok[a.round] = a.src[(int64_t)i * a.src_pitch]; return; + case ADV_BLOCK: { + /* A block drafter's query row: the anchor (the token the verify just chose) at the + * committed end, where the next verify starts, then `aux`, the mask id, at every position + * after it. The host staged the furthest the anchor can be. */ + const int32_t base = S.ctx; + tok[k] = S.tok[0]; + for (int32_t j = 1; j < n; ++j) tok[k + j] = aux; + for (int32_t j = 0; j < n; ++j) adv_pos(a, pos, k + j, base + j); + ctx[i] = base; + adv_groups(a, i, k, base, n); + return; + } + case ADV_BTAKE: + /* Row i is the query pass's i-th block, which is the i-th drafting sequence. */ + for (int32_t j = 0; j < a.round; ++j) + S.tok[1 + j] = a.src[(int64_t)i * a.src_pitch + j]; + return; default: return; } diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index b2fac3e8..f2bac4e9 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -2300,8 +2300,14 @@ void Scheduler::serial_end(int rounds_done) { * it exactly, rejected suffix included: the drafter reads hidden states positionally from its * own buffer, so batch row i must be buffer row i. The rejected positions lie in [n_computed, * n_computed + block), which the query pass overwrites before anything reads them, and the - * ensure() below covers them since n_computed + block reaches the trunk step's own end. */ -int Scheduler::block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max) { + * ensure() below covers them since n_computed + block reaches the trunk step's own end. + * + * On the card the step has not committed yet. The step began at n_computed (a row issued ahead + * was staged at its furthest reach; it really continued from the committed end, as commit() + * reads it), and the anchor lands somewhere in [that + n_tokens - n_spec, that + n_tokens] + * depending on acceptance: the gates take the end that binds them, the query rows the furthest. */ +int Scheduler::block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max, + bool on_card) { std::lock_guard lk(mu_); block_.clear(); block_len_ = 0; @@ -2348,20 +2354,28 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block } SchedReq& s = *sp; Request& r = *s.req; - d.base_pos = r.n_computed; + if (on_card && e.dev) d.ctx_len = (int32_t)r.n_computed; + /* The anchor's position, the sequence's committed end: lowest and highest it can be. */ + const int64_t next_lo = on_card ? (int64_t)d.ctx_len + e.n_tokens - e.n_spec : r.n_computed; + const int64_t next_hi = on_card ? (int64_t)d.ctx_len + e.n_tokens : r.n_computed; + d.base_pos = next_hi; + d.dev = on_card; /* May it propose? It needs an anchor token (the one the sampler just chose, so the entry * produced one) and a draft cache covering what the block's attention reads. The high end * is this step's context pass, about to cover everything up to the trunk's end. The low - * end is draft_lo, non-zero only after a prefix-cache hit that left a hole. */ - const bool have_tok = e.produces_token && !r.output.empty() && r.n_computed >= 1; + * end is draft_lo, non-zero only after a prefix-cache hit that left a hole. On the card + * the anchor is the card's, and a request that may not speculate is left out here rather + * than at set_draft, since the step issued ahead verifies what this pass proposes. */ + const bool have_tok = on_card ? e.produces_token && r.may_speculate + : e.produces_token && !r.output.empty() && r.n_computed >= 1; /* Where this sequence's draft cache starts once the context pass has run: its own floor, * or for a sequence that never had one, this step's first row (0 for an ordinary prefill, * the hit length after a prefix-cache hit). The binding query row is the lowest, at * n_computed, and it reads back to n_computed - window + 1. */ - const int64_t lo = draft_floor(s, (int64_t)e.ctx_len); + const int64_t lo = draft_floor(s, (int64_t)d.ctx_len); const bool reach = lo <= 0 ? true - : (window > 0 && r.n_computed - window + 1 >= lo); + : (window > 0 && next_lo - window + 1 >= lo); /* RADIANCE_DEBUG_DRAFT counts which gate declined. A drafter that silently stops * proposing looks like collapsed acceptance downstream (accept% is conditional on @@ -2369,9 +2383,9 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block const bool ok_room = n_draft_rows < max; /* The query block writes positions n_computed .. n_computed + block - 1, and none of them * may be at or past the end of the context. */ - const bool ok_ctx = ctx_limit_ <= 0 || r.n_computed + block <= ctx_limit_; + const bool ok_ctx = ctx_limit_ <= 0 || next_hi + block <= ctx_limit_; const bool ok_kv = ok_room && ok_ctx && - kv_->ensure_from(r.id, r.n_computed + block, r.n_computed) >= 0; + kv_->ensure_from(r.id, next_hi + block, r.n_computed) >= 0; static const bool dbg = [] { const char* v = std::getenv("RADIANCE_DEBUG_DRAFT"); return v && *v && *v != '0'; }(); if (dbg) { @@ -2483,6 +2497,13 @@ const RadBatch* Scheduler::block_query(int step) { * block = depth it starts on it. */ e.hidden_row = row + block - depth; e.hidden_n = depth; + /* On the card the anchor, its position and every mask come from the card (ADV_BLOCK), + * which reads the mask id here; the host staged them at the furthest position. */ + if (d.dev) { + e.dev = true; + e.dev_out = -1; + e.dev_aux = block_mask_.empty() ? 0 : block_mask_[0]; + } block_plan_.e.push_back(e); block_plan_.n_tok += block; row += block; diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 06aa8711..7919e54e 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -333,6 +333,13 @@ public: * * The drafter writes its proposal to its declared proposal buffer, not through the sampler, * and the engine publishes it through set_draft(). + * + * On the card (`on_card`), block_begin runs before commit() instead, right after the step is + * issued, so both passes queue behind it with no readback in between. The context pass is + * unchanged: it mirrors the trunk step, whose positions the host knows. The query pass's + * anchor depends on acceptance, so its rows are device rows (advance.h, ADV_BLOCK) staged at + * the furthest position acceptance could leave, and the reservation covers that far. + * block_end still runs after commit(). */ struct BlockRow { uint64_t seq = 0; @@ -343,7 +350,8 @@ public: * last `depth` rows), `window` its attention window (0 for none) and `mask` the token id its * masked query slots embed. Returns how many sequences may draft and fills `out` with them, * in the order block_query() emits them. */ - int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max); + int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max, + bool on_card = false); const RadBatch* block_context(int step); const RadBatch* block_query(int step); void block_end(); @@ -570,6 +578,9 @@ private: int32_t n_tokens = 0; int64_t base_pos = 0; /* the anchor's position: the sequence's next one */ bool can_draft = false; + /* On the card: the anchor's position is the card's, and `base_pos` the furthest it can + * be (Scheduler::block_begin). */ + bool dev = false; /* A placeholder: the trunk step finished this sequence, so it has no KV and drafts * nothing, but keeps its row so later rows stay aligned with the trunk's. The pass stores * nothing for it (a negative slot is padding). */ diff --git a/docs/GUIDE.md b/docs/GUIDE.md index f09baa09..e2ee6d0c 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3088,6 +3088,7 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_GEMMA4_OVERLAP` | the Gemma 4 31B's prefill overlap (`arch/gemma4_bf16`, two or more ranks, fused junctions, the exact all-reduce wire): a prefill step of 1024 rows or more runs as two slices, each slice's all-reduces on a second stream beside the other's compute. On by default; `0` turns it off and runs every step whole (the startup notes say which) | | `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) | +| `RADIANCE_DRAFT_BLOCK_HOST` | `1` runs a block drafter's (DFlash) passes from the host after each commit, two waits a step and no step issued ahead, instead of on the card's acceptance. For comparing the two drivers; the replies and the drafts' acceptance are the same | Engine development has its own instruments: `RADIANCE_DEBUG_*` (residual probes, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on the operands the model issued; diff --git a/spec.md b/spec.md index 1ace7bff..8faee7f3 100644 --- a/spec.md +++ b/spec.md @@ -1183,7 +1183,9 @@ core. **Kind is a shape, not a model.** `RAD_DRAFT_SERIAL` runs `depth` dependent passes, each embedding what the last proposed. `RAD_DRAFT_BLOCK` runs a context pass, then one pass that fills every drafted position. MTP and EAGLE-style heads are serial; block-diffusion drafters (DFlash2, DSpark) -are block. +are block. Both run on the card's acceptance (`core/sched/advance.h`): the verify's acceptance, the +positions of every pass after it and the proposals stay on the card, so a step's passes and the +next step are issued before the step is read back, and the host's commit runs beside the card. Separate draft models are not supported; a drafter is part of the model's source. `rad-convert --draft-model` merges a drafter that ships as its own repository into the container diff --git a/tests/advance_test.cpp b/tests/advance_test.cpp index 2e17a85b..60b77bcd 100644 --- a/tests/advance_test.cpp +++ b/tests/advance_test.cpp @@ -419,4 +419,124 @@ TEST(the_card_stages_a_cacheless_head_at_the_committed_position) { } } +/* ================================================================== the block drafter */ + +/* A block drafter's query row on the card: the anchor (the verify's chosen token) at the + * committed end, the row's mask id (`aux`) at every position after it, slots through the row's + * own table and the group's length to the block's end. The host staged the furthest the anchor + * could be; a host row is left as staged. A wrong base drafts from the wrong position and + * acceptance collapses with no error; a wrong slot writes the drafter's K/V into another block. */ +TEST(a_block_query_row_takes_its_anchor_and_position_from_the_step_slot) { + Slab s(ADV_BLOCK, /*n_groups=*/1, /*block=*/4); + /* Row 0: a block of four for card 3, staged at 60; the card has it at 50. */ + s.row(0, true, 0, 4, 60, 3, 0, -1, /*mask=*/4); + for (int b = 0; b < Slab::kPitch; ++b) s.bt(0, 0)[b] = 100 + b; + s.st[3].ctx = 50; s.st[3].tok[0] = 777; + /* Row 1: host-staged, untouched. */ + s.row(1, false, 4, 2, 30, 4, 0, -1, 9); + s.w[Slab::TOK + 4] = 900; s.w[Slab::TOK + 5] = 901; + s.w[Slab::POS + 4] = 30; s.w[Slab::POS + 5] = 31; + /* Row 2: card 1 at 7 with mask 9; its block 1 (positions 4..7) was never assigned. */ + s.row(2, true, 6, 4, 20, 1, 0, -1, 9); + s.bt(0, 2)[1] = -1; + s.st[1].ctx = 7; s.st[1].tok[0] = 555; + s.run(); + + const int32_t tok[10] = { 777, 4, 4, 4, 900, 901, 555, 9, 9, 9 }; + const int32_t pos[10] = { 50, 51, 52, 53, 30, 31, 7, 8, 9, 10 }; + const int32_t slot[10] = { 112 * 4 + 2, 112 * 4 + 3, 113 * 4 + 0, 113 * 4 + 1, 0, 0, + -1, 8, 9, 10 }; + for (int t = 0; t < 10; ++t) { + CHECK_EQ(s.w[Slab::TOK + t], tok[t]); + CHECK_EQ(s.w[Slab::POS + t], pos[t]); + CHECK_EQ(s.slot(0, t), slot[t]); + } + CHECK_EQ(s.w[Slab::CTX + 0], 50); + CHECK_EQ(s.w[Slab::CTX + 1], 30); + CHECK_EQ(s.w[Slab::CTX + 2], 7); + CHECK_EQ(s.used(0, 0), 54); + CHECK_EQ(s.used(0, 2), 11); + CHECK_EQ(s.st[3].tok[0], 777); /* the anchor stays the next verify's first token */ +} + +/* The block's proposals go into the slot behind the anchor, row i's from i * src_pitch: exactly + * the tokens the next verify reads after its first. The anchor and host rows are untouched. */ +TEST(a_block_take_puts_each_rows_proposals_behind_its_anchor) { + Slab s(ADV_BTAKE); + s.a.round = 3; + s.a.src_pitch = 3; + for (int i = 0; i < 3; ++i) { + s.row(i, true, 4 * i, 4, 0, /*card=*/2 - i, 0, -1, 4); + s.st[2 - i].tok[0] = 50 + i; + for (int c = 0; c < 3; ++c) s.src[i * 3 + c] = 1000 * (i + 1) + c; + } + s.row(3, false, 12, 4, 0, 5, 0, -1, 4); + s.src[9] = 4242; + s.run(); + for (int i = 0; i < 3; ++i) { + const StepSlot& S = s.st[2 - i]; + CHECK_EQ(S.tok[0], 50 + i); + for (int c = 0; c < 3; ++c) CHECK_EQ(S.tok[1 + c], 1000 * (i + 1) + c); + } + CHECK(s.st[5].tok[1] != 4242); +} + +/* The chain a pipelined block-drafter step runs, row for row: the verify's acceptance, the query + * block at the committed end, the take, then the step issued ahead. A verify at 101..105 (four + * drafts) accepts two, so the anchor is the target's third pick at 104, and the next verify + * starts there with the anchor and the block's proposals. */ +TEST(a_block_drafter_step_on_the_card_continues_where_the_verify_left_off) { + StepSlot st; + /* The verify: 7000 then drafts 7101..7104; the target picks 7101, 7102, 9999, ... */ + { + Slab v(ADV_ACCEPT); + v.row(0, false, 0, 5, 101, 1, 0, 0, 4); + const int32_t t[5] = { 7000, 7101, 7102, 7103, 7104 }; + const int32_t y[5] = { 7101, 7102, 9999, 1, 2 }; + for (int j = 0; j < 5; ++j) { v.w[Slab::TOK + j] = t[j]; v.src[j] = y[j]; } + v.run(); + st = v.st[1]; + } + CHECK_EQ(st.acc, 2); + CHECK_EQ(st.ctx, 104); + CHECK_EQ(st.tok[0], 9999); + /* The query block of four, staged at the furthest anchor, 106. */ + { + Slab q(ADV_BLOCK); + q.st[1] = st; + q.row(0, true, 0, 4, 106, 1, 0, -1, 4); + q.run(); + const int32_t tok[4] = { 9999, 4, 4, 4 }; + for (int j = 0; j < 4; ++j) { + CHECK_EQ(q.w[Slab::TOK + j], tok[j]); + CHECK_EQ(q.w[Slab::POS + j], 104 + j); + } + st = q.st[1]; + } + /* Its three proposals, then the next verify of 1 + 3. */ + { + Slab t(ADV_BTAKE); + t.st[1] = st; + t.a.round = 3; + t.a.src_pitch = 3; + t.row(0, true, 0, 4, 106, 1, 0, -1, 4); + t.src[0] = 8001; t.src[1] = 8002; t.src[2] = 8003; + t.run(); + st = t.st[1]; + } + { + Slab n(ADV_TRUNK); + n.st[1] = st; + n.row(0, true, 0, 4, 106, 1, 0, 0, 3); + n.run(); + const int32_t tok[4] = { 9999, 8001, 8002, 8003 }; + for (int j = 0; j < 4; ++j) { + CHECK_EQ(n.w[Slab::TOK + j], tok[j]); + CHECK_EQ(n.w[Slab::POS + j], 104 + j); + } + CHECK_EQ(n.w[Slab::CTX], 104); + CHECK_EQ(n.w[Slab::ACC], 3); + } +} + RAD_TEST_MAIN() diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 4fd32561..294e8b7b 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -3937,6 +3937,179 @@ TEST(a_step_issued_ahead_equals_the_step_built_after_the_commit) { } } +/* ================================================================== a block drafter on the card */ +namespace { +/* Every pass of a block drafter's run: each step's trunk batch, then its context and query + * passes, as the card holds them once its advances have run. */ +struct BlockRun { + std::vector trunk, context, query; + std::vector> out; + int ahead = 0; + int card_host_disagree = 0; +}; +constexpr int kBlk = 8, kBlkDepth = 7; +constexpr int32_t kBlkMask = 99; + +/* The host's driver: both passes built after the commit, from the committed sequence. */ +BlockRun block_reference(int steps) { + Fixture f; + std::vector ids; + ahead_setup(f, kBlkDepth, ids); + BlockRun run; + const RadBatch* b = f.sch.step(); + if (!b) return run; + run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv)); + Scheduler::BlockRow rows[4]; + for (int t = 0; t < steps; ++t) { + CHECK_OK(ahead_commit(f, t)); + CHECK_EQ(f.sch.block_begin(kBlk, kBlkDepth, 0, kBlkMask, rows, 4), 3); + const RadBatch* cb = f.sch.block_context(t + 1); + if (!cb) { CHECK(cb != nullptr); return run; } + run.context.push_back(read_rows(cb, f.sch.plan(), f.kv)); + const RadBatch* qb = f.sch.block_query(t + 1); + if (!qb) { CHECK(qb != nullptr); return run; } + /* The query plan is the scheduler's own; its rows are the drafting sequences in order. */ + StepPlan qp; + for (int i = 0; i < 3; ++i) { StepEntry e; e.seq = rows[i].seq; qp.e.push_back(e); } + run.query.push_back(read_rows(qb, qp, f.kv)); + f.sch.block_end(); + ahead_publish(f, ids, kBlkDepth, t + 1); + b = f.sch.step(); + if (!b) break; + run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv)); + } + for (uint64_t id : ids) run.out.push_back(f.sch.find(id)->output); + return run; +} + +/* The card's driver (Engine::issue_block_drafter): the step's acceptance into the StepSlots, both + * passes built before the commit with the query rows placed by ADV_BLOCK, the proposals into the + * slots (ADV_BTAKE), expect_draft and step_next with ADV_TRUNK, then the commit, block_end, the + * drafts published and promote_next. */ +BlockRun block_pipelined(int steps) { + Fixture f; + std::vector ids; + ahead_setup(f, kBlkDepth, ids); + BlockRun run; + std::vector slots((size_t)f.cfg.max_seqs); + const RadBatch* b = f.sch.step(); + if (!b) return run; + run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv)); + Scheduler::BlockRow rows[4]; + for (int t = 0; t < steps; ++t) { + const StepPlan& p = f.sch.plan(); + std::vector y((size_t)b->n_out + 1, -1); + for (const StepEntry& e : p.e) { + if (e.dev_out < 0) continue; + const int32_t a = ahead_acc(e.seq, t, e.n_spec); + for (int j = 0; j <= e.n_spec; ++j) + y[(size_t)(e.dev_out + j)] = j < a ? ahead_draft(e.seq, t, j) : ahead_tok(e.seq, t); + } + AdvanceArgs acc = f.sch.advance_args(0); + acc.mode = ADV_ACCEPT; + acc.st = slots.data(); + acc.src = y.data(); + for (int i = 0; i < acc.n_seq; ++i) adv_row(acc, i); + for (const StepEntry& e : p.e) { + const StepSlot& S = slots[(size_t)e.card]; + if (S.acc != ahead_acc(e.seq, t, e.n_spec) || S.tok[0] != ahead_tok(e.seq, t)) + ++run.card_host_disagree; + } + + CHECK_EQ(f.sch.block_begin(kBlk, kBlkDepth, 0, kBlkMask, rows, 4, /*on_card=*/true), 3); + const RadBatch* cb = f.sch.block_context(t + 1); + if (!cb) { CHECK(cb != nullptr); return run; } + run.context.push_back(read_rows(cb, f.sch.plan(), f.kv)); + const RadBatch* qb = f.sch.block_query(t + 1); + if (!qb) { CHECK(qb != nullptr); return run; } + AdvanceArgs q = f.sch.advance_args(0); + q.mode = ADV_BLOCK; + q.st = slots.data(); + for (int i = 0; i < q.n_seq; ++i) adv_row(q, i); + StepPlan qp; + for (int i = 0; i < 3; ++i) { StepEntry e; e.seq = rows[i].seq; qp.e.push_back(e); } + run.query.push_back(read_rows(qb, qp, f.kv)); + /* The block's proposals for step t + 1, taken behind the anchor. */ + std::vector prop((size_t)3 * kBlkDepth); + for (int i = 0; i < 3; ++i) + for (int j = 0; j < kBlkDepth; ++j) + prop[(size_t)(i * kBlkDepth + j)] = ahead_draft(rows[i].seq, t + 1, j); + AdvanceArgs tk = f.sch.advance_args(0); + tk.mode = ADV_BTAKE; + tk.round = kBlkDepth; + tk.src = prop.data(); + tk.src_pitch = kBlkDepth; + tk.st = slots.data(); + for (int i = 0; i < tk.n_seq; ++i) adv_row(tk, i); + for (int i = 0; i < 3; ++i) f.sch.expect_draft(rows[i].seq, kBlkDepth); + + const RadBatch* nb = f.sch.step_next(); + if (nb) { + AdvanceArgs tr = f.sch.advance_args(0); + tr.mode = ADV_TRUNK; + tr.st = slots.data(); + for (int i = 0; i < tr.n_seq; ++i) adv_row(tr, i); + } + CHECK_OK(ahead_commit(f, t)); + f.sch.block_end(); + ahead_publish(f, ids, kBlkDepth, t + 1); + if (nb) { + f.sch.promote_next(); + b = nb; + ++run.ahead; + } else { + b = f.sch.step(); + if (!b) break; + } + run.trunk.push_back(read_rows(b, f.sch.plan(), f.kv)); + } + for (uint64_t id : ids) run.out.push_back(f.sch.find(id)->output); + return run; +} +} /* namespace */ + +/* A block drafter on the card runs the passes the host's driver runs after the commit: the same + * trunk steps, and context and query passes with the same positions, lengths and slots once the + * card's advances have filled in what the host only bounded, and the same query tokens. Its query + * block is staged before the step's acceptance is known, at the furthest anchor; a wrong position + * drafts from the wrong place (acceptance collapses, no error) and a wrong slot writes the + * drafter's K/V into another block. Every step after the first runs issued ahead. + * + * The context pass's token ids are not compared: that pass reads hidden states and no ids + * (Scheduler::block_context), and staged before the commit, its accepted positions are not in the + * sequence yet. */ +TEST(a_block_drafter_on_the_card_runs_the_passes_the_hosts_driver_runs) { + const int T = 24; + const BlockRun a = block_reference(T); + const BlockRun b = block_pipelined(T); + CHECK_EQ(b.ahead, T); + CHECK_EQ(b.card_host_disagree, 0); + REQUIRE_EQ(a.trunk.size(), (size_t)T + 1); + REQUIRE_EQ(a.trunk.size(), b.trunk.size()); + REQUIRE_EQ(a.context.size(), b.context.size()); + REQUIRE_EQ(a.query.size(), b.query.size()); + for (size_t t = 0; t < a.trunk.size(); ++t) { + CHECK(a.trunk[t] == b.trunk[t]); + CHECK_EQ(b.trunk[t].bad_slots, 0); + } + for (size_t t = 0; t < a.context.size(); ++t) { + BatchRows ca = a.context[t], cb = b.context[t]; + ca.tok.clear(); + cb.tok.clear(); + const bool same_c = ca == cb, same_q = a.query[t] == b.query[t]; + CHECK(same_c); + CHECK(same_q); + if (!same_c || !same_q) + std::fprintf(stderr, " step %zu: context %s, query %s\n", t, + same_c ? "same" : "differs", same_q ? "same" : "differs"); + CHECK_EQ(a.context[t].bad_slots, 0); + CHECK_EQ(b.context[t].bad_slots, 0); + CHECK_EQ(a.query[t].bad_slots, 0); + CHECK_EQ(b.query[t].bad_slots, 0); + } + CHECK(a.out == b.out); +} + /* ================================================================== the token budget per token */ /* A verify step emits up to 1 + n_spec tokens at once. The budget (max_tokens, and the context) * is applied token by token before each reaches the sink: trimming `output` afterwards would leave From 1bb7ad3ef942fc7e2afc96ac1fc77a930065b7fc Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Sun, 18 Oct 2026 09:32:38 -0500 Subject: [PATCH 123/152] The series' PR beneath, composed (a copy; it drops out when it lands) #159's tree (a full fence on four-rank prefill-sized all-reduces), which the maintainer will merge by hand in the next release, as the integration branch composed and tested it. Not for review here: review the last commit. Co-Authored-By: Claude Opus 5.5 --- docs/GUIDE.md | 1 + libr4d/r4d_rows.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index e2ee6d0c..faa248ca 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3085,6 +3085,7 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) | | `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | +| `RADIANCE_AR_FENCE_FROM` | four-rank all-reduces of at least this many elements take a full fence before their flag (default 131072: prefill chunks, never decode or verify); cures a rare fresh-start divergence on the 31B at tp 4; `0` turns it off | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_GEMMA4_OVERLAP` | the Gemma 4 31B's prefill overlap (`arch/gemma4_bf16`, two or more ranks, fused junctions, the exact all-reduce wire): a prefill step of 1024 rows or more runs as two slices, each slice's all-reduces on a second stream beside the other's compute. On by default; `0` turns it off and runs every step whole (the startup notes say which) | | `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) | diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 4567168a..9a8ba1d0 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -9185,6 +9185,25 @@ extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) { extern "C" void r4d_cfg_split(const RadArgs* a, R4dSplitCfg* out) { out->splits = TUNE(a, tAttnSplit, "splits"); } +/* A fresh-start divergence (4x R9700 behind an EPYC root complex, 2026-10-17): on a freshly + * started 31B server, a prefill all-reduce now and then reads a peer's scratch before that peer's + * words have landed -- the first reuse of a double-buffered slot, inputs identical on every rank + * (RADIANCE_DEBUG_OPHASH) -- and the first greedy reply flips a near-tie. Every thread's full + * system fence before the flag (drain 1) cures it, as does one after it (acq 1); the per-wave + * store wait (drain 3) and the publisher's one writeback (pub 1) do not, and Relaxed Ordering off + * on every link does not. The mechanism below the fence is not known. Decode heights never showed + * it, and the fence costs them ~0.7 %, so it is taken only from RADIANCE_AR_FENCE_FROM elements + * (default 131072, 24 rows of the 31B's 5376: above any verify height, and every prefill chunk); + * 0 never. Read once. Only at four ranks, where it was seen and cured: at two (Qwen3.8-27B's + * prefill at tp 2) it cost 4.5% of prefill, and no two-rank start ever flipped. */ +static long long ar_fence_from() { + static const long long v = [] { + const char* e = std::getenv("RADIANCE_AR_FENCE_FROM"); + return e && *e ? std::atoll(e) : 131072LL; + }(); + return v; +} + extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) { out->nblocks = TUNE(a, tAr, "nblocks"); out->nthreads = TUNE(a, tAr, "nthreads"); @@ -9192,6 +9211,12 @@ extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) { out->acq = TUNE(a, tAr, "acq"); /* An axis of the four-rank junction only (tArQ84); 1 for every other row, as before. */ out->pub = TUNE(a, tArQ84, "pub"); + /* Operand 0 is the message on every collective that reads this (all_reduce's x, a junction's + * [M, n] input, all_gather's source). */ + const long long from = ar_fence_from(); + if (from > 0 && a && a->t && a->n_t > 0 && rad_tensor_numel(&a->t[0]) >= from && + r4d_geti_or(a, "world_size", 4) == 4) /* the four-rank rows carry no world_size */ + out->drain = 1; } extern "C" int r4d_cfg_ar_tail(const RadArgs* a) { return TUNE(a, tArQ84, "tail"); From ab2b3be6c0073fa28bd7ad93de16820411f2a432 Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 14:55:09 -0500 Subject: [PATCH 124/152] core, libr4d, arch: chained launches with block drafters, more prefill overlap, weight reads beside the all-reduces Chained launches on the AQL backend (a dependent kernel waits on a queue counter in its own prologue), on by default where the model's plugin measured a gain with its block drafter (the Gemma 4 31B and 26B); the prefill overlap runs attention per slice with narrower lane-1 reductions; the next GEMM's weight is read into the on-die cache beside each all-reduce at decode heights. Squashed from: - core, libr4d: chained launches -- dependent kernels wait in their prologue, not behind the barrier bit - core, libr4d: chain a kernel by its name, not by the row that launched it - libr4d, core: chained forms hold nothing across their body - libr4d: a chained kernel's prologue polls its counter less often after the first few tries - core/sched: the advance kernel's chained form - docs: GUIDE lists RADIANCE_CHAIN; chained launches stay opt-in - core/device: a chained packet behind a chained one keeps its barrier bit while a plain one may run - libr4d: qkv_norm_rope and its kv_store fold as chained forms - libr4d: the split-KV decode attention and its merge as chained forms - libr4d: the four-rank fused junction's tail form as a chained form - libr4d: the attention, prologue and junction chained forms hold nothing across their body - libr4d: the 31B's windowed attention and quant_act_i8 as chained forms; r4d_chain.h stubs for the host emulator - libr4d: DFlash2's kernels as chained forms - libr4d: chained forms for the decode tail - abi, core, arch: chained launches on by default where the plugin measured a gain with its drafter - arch/gemma4_bf16: the prefill overlap's lane-1 all-reduces take the narrow launch (`overlap` 1) - arch/gemma4_bf16, libr4d: the prefill overlap runs attention per slice; kv_len_trim - abi, core, libr4d: RAD_LAYOUT_ANY, and a device-only weight read (prefetch) - arch: read the next GEMM's weight into the cache beside each collective at decode heights Co-Authored-By: Claude Opus 5.5 --- abi/rad_abi.h | 26 ++- abi/rad_builder.h | 15 ++ arch/common/rad_arch.h | 47 +++++ arch/common/rad_block_dflash2.h | 29 +++ arch/common/rad_gemma4_dflash.h | 26 ++- arch/gemma4_bf16/gemma4_bf16.cpp | 232 +++++++++++++++++++++- core/build/rad_builder.cpp | 4 + core/device/aql.cpp | 94 ++++++++- core/device/device.h | 9 + core/device/dispatch.cpp | 23 +++ core/engine_bringup.cpp | 19 ++ core/plugin/loader.cpp | 2 + core/plugin/select.cpp | 5 + core/plugin/testplugin/testplugin.cc | 17 +- core/rad_core.h | 2 + core/runtime/ctx.cpp | 1 + core/sched/advance.hip | 53 ++++- docs/GUIDE.md | 2 + docs/OPS.md | 26 +++ libr4d/CMakeLists.txt | 4 + libr4d/r4d.h | 8 +- libr4d/r4d_ar_entry.hip | 20 +- libr4d/r4d_ar_gather_Nrank.hip | 39 +++- libr4d/r4d_ar_twoshot_Nrank_exact.hip | 36 +++- libr4d/r4d_args.h | 2 + libr4d/r4d_attn_args.h | 1 + libr4d/r4d_attn_decode_h256_gqa6.hip | 58 +++++- libr4d/r4d_attn_paged_window.hip | 48 ++++- libr4d/r4d_chain.h | 85 ++++++++ libr4d/r4d_dflash_conv_t2_g16_bf16.hip | 35 +++- libr4d/r4d_dflash_select_bf16.hip | 54 ++++- libr4d/r4d_gelu_mul_quant_i8.hip | 28 ++- libr4d/r4d_gemm_bf16_nt_m64.hip | 38 +++- libr4d/r4d_gemm_fp8a16_nt_m1.hip | 38 +++- libr4d/r4d_gemm_fp8a8.hip | 79 +++++++- libr4d/r4d_gemm_w4a8_nt_m64.hip | 49 +++-- libr4d/r4d_gemm_w8a8_nt_m64.hip | 43 +++- libr4d/r4d_kv_len_trim.hip | 40 ++++ libr4d/r4d_model_bf16.hip | 188 +++++++++++++++--- libr4d/r4d_plugin.h | 4 + libr4d/r4d_prefetch.hip | 83 ++++++++ libr4d/r4d_qkv_norm_rope.hip | 33 ++- libr4d/r4d_quant_act_fp8.hip | 38 +++- libr4d/r4d_quant_act_i8.hip | 34 +++- libr4d/r4d_rmsnorm_quant_i8.hip | 36 +++- libr4d/r4d_rows.cpp | 106 ++++++++++ libr4d/r4d_rowtopk_bf16.hip | 62 +++++- libr4d/r4d_sample_stages_f32.hip | 102 ++++++++-- libr4d/r4d_selftest.cpp | 122 ++++++++++++ tests/abi_layout_rows.h | 1 + tests/arch_fakes.h | 8 + tests/arch_test.cpp | 265 +++++++++++++++++++++---- tests/build_test.cpp | 40 ++++ 53 files changed, 2239 insertions(+), 220 deletions(-) create mode 100644 libr4d/r4d_chain.h create mode 100644 libr4d/r4d_kv_len_trim.hip create mode 100644 libr4d/r4d_prefetch.hip diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 6e0179cb..ed4eefa7 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -135,7 +135,13 @@ typedef struct RadLayout { * RAD_E_DTYPE the kernel does not read this encoding (an fp8 GEMM handed int4, a rotated * weight to a kernel that does not rotate its activation). A declare-time * error naming the weight, the encoding and the kernel. - * RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads. */ + * RAD_E_SHAPE the selected planes, or their extents, are not what the kernel reads. + * RAD_LAYOUT_ANY the kernel reads the stored bytes without interpreting them (a prefetch + * into the cache), so it takes whatever form another reader chose and claims + * none: the builder does not count it when settling the stored form, and the + * runtime's layout check accepts it. A weight only such kernels read is + * stored as it is. */ +#define RAD_LAYOUT_ANY 1 typedef int (*RadLayoutFn)(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n_planes, RadLayout* out); @@ -498,6 +504,24 @@ typedef void (*RadPluginCloseFn)(void); * it, which is always correct. Symbol name: `rad_kernel_concurrent`. */ typedef int (*RadKernelConcurrentFn)(int i); +/* Optional promise about kernel `i` of rad_kernel_at: nonzero means it can chain. Chaining replaces + * the packet processor's ordering between dependent launches (the AQL barrier bit) with a wait in + * the kernel. Where chaining is on the engine resolves the row with the parameter `chain` = 1, and + * the launch may then emit chained forms of its kernels, recognised by "r4dchain" in the kernel's + * name; only those get a record and lose the bit. A chained form, before its first read of an + * operand, one lane a block waits until the 64-bit word at the record's `ctr` reaches `target`, + * then the block barriers and acquires at agent scope; after its last write the block releases at + * agent scope, barriers, and one lane adds 1 to `ctr`. Every block, including one with nothing to + * do, adds exactly once. The record is RAD_CHAIN_REC_BYTES at byte RAD_CHAIN_KARG_OFF of the + * kernel's argument segment: { magic, target, ctr, check }, with check = magic ^ target ^ ctr ^ + * RAD_CHAIN_CHECK. A record whose magic or check does not match means: run without waiting and do + * not add. Without the symbol, or with 0, the engine never asks. Symbol name: `rad_kernel_chain`. */ +typedef int (*RadKernelChainFn)(int i); +#define RAD_CHAIN_KARG_OFF 992 +#define RAD_CHAIN_REC_BYTES 32 +#define RAD_CHAIN_MAGIC 0x3130434e48434452ull /* "RDCHCN01" */ +#define RAD_CHAIN_CHECK 0x9e3779b97f4a7c15ull + /* Optional promise about kernel `i` of rad_kernel_at: nonzero means it is a collective. Its * launches exchange data with the other ranks' cards, so the interconnect carries their bytes * while they run and the step waits on it. The engine keeps its own bulk traffic on those links diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 948d9f7f..e3a3a477 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -643,6 +643,15 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d); * checkpoint was trained with is the plugin's to know. */ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset); +/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on + * the AQL backend only, which keeps a completion counter per queue -- by default where the model's + * plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter + * decodes speculatively, or as RADIANCE_CHAIN says. A plugin that places work by whether a kernel + * waits in its prologue behind the one before it -- a weight read issued on lane 0 right after its + * GEMM -- asks this instead of reading the environment, so it follows that decision. Additive + * export; RAD_ABI_VERSION does not move. */ +int rad_chain_on(void); + /* ================================================================== the encoder */ /* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and * reads its result, so the plugin declares it. A plugin that declares none serves text only, and @@ -1281,6 +1290,12 @@ typedef struct RadArchProbe { * libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at * startup with the plugin named. */ int32_t kv_quant_ok; + /* Nonzero when this plugin measured its speculative step faster with chained launches + * (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the + * queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core + * then takes them by default; RADIANCE_CHAIN overrides either way. Zero keeps them off: plain + * decode measured slower chained, and a plugin that never measured them asks for nothing. */ + int32_t chain_pays; } RadArchProbe; int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index 690da3bd..330743bf 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -587,6 +587,53 @@ inline rad_op rw(RadBuilder* b, rad_op h, return h; } +/* ---- A weight read into the on-die cache beside a collective (libr4d `prefetch`, docs/OPS.md). + * At decode heights a GEMM streams its weight once from memory, and a collective in front of it + * leaves the card's memory idle for its round trip. prefetch_beside issues `op`, a `prefetch` of + * the next GEMM's weight `w`, behind the GEMM before the collective, so the two do not share the + * memory, and the next GEMM finds its leading bytes in the cache. Nothing it reads or writes is a + * model value, so on the second lane it keeps that lane's rules with no buffer named + * (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte. + * + * Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a + * z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps + * (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first + * greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each + * start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that + * divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the + * all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the + * reads touch. The reads stay off prompt steps all the same. */ +constexpr int64_t kPrefetchRows = 16; +/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d + * r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without + * holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit + * on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On + * 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365, + * prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where + * launches chain (rad_chain_on, the core's decision), since a plain launch would read in series + * there; elsewhere the read goes on lane 1, behind a join from lane 0. */ +inline bool prefetch_lane0() { return rad_chain_on() != 0; } +inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) { + if (!op || T > kPrefetchRows) return; + if (prefetch_lane0()) { + RAD_ISSUE(c, op, RAD_W(w)); + return; + } + if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w)); + rad_lane(c, 0); +} +/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */ +inline bool prefetch_enabled() { + const char* e = std::getenv("RADIANCE_PREFETCH"); + return !(e && !std::strcmp(e, "0")); +} +/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0 + * otherwise. */ +inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) { + if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0; + return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w)); +} + /* ================================================================== geometry */ /* Dimensions come from model metadata, so one plugin covers every size in a family. Sharded * dimensions are already divided by world_size: the plugin declares divided dimensions and emits diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h index 823940f7..d26bf7ad 100644 --- a/arch/common/rad_block_dflash2.h +++ b/arch/common/rad_block_dflash2.h @@ -127,6 +127,9 @@ struct Dflash2 { /* The target's embedding scale, applied to the query block as the drafter was trained * (dflash_config.input_embedding_scale): 1 for Qwen, sqrt(hidden) in bf16 for Gemma. */ double escale = 1.0; + /* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query + * pass (prefetch_beside, rad_arch.h); 0 reads none. */ + int64_t prefetch = 0; int64_t steps() const { return block - 1; } int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; } /* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's); @@ -264,6 +267,13 @@ struct Dflash2 { * op_aan[i] after layer i-1's feed-forward (layer i's attention norm, i >= 1), op_afinal after * the last layer's (the final norm). All or none. */ rad_op op_afn[MAX_LAYERS] = {}, op_aan[MAX_LAYERS] = {}, op_afinal = 0; + /* The reads beside the query pass's all-reduces (cfg.prefetch), each the GEMMs that follow + * in their order: beside the attention's, the feed-forward's coefficient projection, then + * gate_up; beside the feed-forward's, the next layer's attention coefficient projection, then + * its q -- after the last layer, the draft head; and o's beside the attention itself. 0 where + * none is declared. */ + rad_op op_pfa[MAX_LAYERS][2] = {}, op_pff[MAX_LAYERS][2] = {}, op_pfo[MAX_LAYERS] = {}; + rad_weight pfa_w[MAX_LAYERS][2] = {}, pff_w[MAX_LAYERS][2] = {}, pfo_w[MAX_LAYERS] = {}; /* head and selector */ rad_op op_gather = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0; @@ -900,6 +910,22 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_WEIGHTS(w_pred, w_succ)), {w.cand, w.unary, w.hp}, {w.tokens}); + /* The reads beside the all-reduces, after every weight they read is declared. */ + if (op_ar && cfg.prefetch > 0) + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + pfa_w[i][0] = w_fcp[i]; + pfa_w[i][1] = w_gu[i].w; + pff_w[i][0] = l + 1 < g.n_layer ? w_acp[i + 1] : w_dh; + pff_w[i][1] = l + 1 < g.n_layer ? w_q[i + 1].w : 0; + for (int j = 0; j < 2; ++j) { + op_pfa[i][j] = decl_prefetch(b, pfa_w[i][j], cfg.prefetch); + op_pff[i][j] = decl_prefetch(b, pff_w[i][j], cfg.prefetch); + } + pfo_w[i] = w_o[i].w; + op_pfo[i] = decl_prefetch(b, pfo_w[i], cfg.prefetch); + } + return RAD_OK; } @@ -989,6 +1015,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { RAD_W(w_k[i].w), RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref()); RAD_ISSUE_N(c, op_vp[i], T, brows(w.h2q, T), brows(w.h2s, T), RAD_W(w_v[i].w), RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref()); + prefetch_beside(c, op_pfo[i], pfo_w[i], T); if (op_qkr[i]) { RAD_ISSUE_N(c, op_qkr[i], T, brows(w.q, T), brows(w.k, T), brows(w.v, T), praw(batch->positions, RAD_I32, T), RAD_W(w_qn[i]), RAD_W(w_kn[i]), @@ -1012,6 +1039,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { RAD_ISSUE_N(c, op_qat, T, brows(w.attn, T), brows(w.atq, T), brows(w.ats, T)); RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T), RAD_W(w_o[i].w), RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref()); + for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pfa[i][j], pfa_w[i][j], T); /* Reduce before the closing convolution. It is linear with coefficients from the * replicated norm, so either order gives the same result; reducing first keeps x's * update agreed across ranks. */ @@ -1038,6 +1066,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { } RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T), RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref()); + for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T); if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T)); diff --git a/arch/common/rad_gemma4_dflash.h b/arch/common/rad_gemma4_dflash.h index cdf3ecff..b6660921 100644 --- a/arch/common/rad_gemma4_dflash.h +++ b/arch/common/rad_gemma4_dflash.h @@ -112,6 +112,23 @@ inline double embed_scale(int64_t hidden) { return rad_bf16_to_f32(rad_f32_to_bf16((float)std::sqrt((double)hidden))); } +/* prefetch where a library serves it: the 31B trunk reading the next GEMM's leading weight bytes + * into the on-die cache beside the all-reduce in front of that GEMM, at decode heights (on lane 0 + * as a chained read, or on the second lane: rad_arch.h prefetch_lane0), and the DFlash2 drafter's + * reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB. With + * the reads on lane 0 (two rounds on 4x R9700): 20 MB 391 / 391 code tok/s, 289 / 288 prose; + * 16 MB 386 / 384, 285 / 283; 24 MB 388 / 387; 12 MB 368 / 369. */ +constexpr int64_t kPrefetchBytes = (int64_t)20 << 20; + +/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention. It + * took the place of o_proj's read there: the 31B at tp 4 on 4x R9700, two rounds, every reply + * identical, 380 / 281 / 203 tok/s against 367 / 271 / 196 with o_proj's 16 MB; 10, 11, 12, 14 + * and 20 MB of down_proj 379, 377, 373, 373 and 362; down_proj beside o_proj's read, or beside the + * feed-forward reduction, slower than either alone. The reads beside a reduction are one queue, + * and a longer one beside the attention pushes gate_up's read past the reduction it should hide + * in. */ +constexpr int64_t kPrefetchDownBytes = (int64_t)9 << 20; + /* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no * transform (a recipe's `rtn codes=fp8_e4m3 block=128x128 scale=bf16`). */ inline bool block_fp8_128(const RadEncoding& e) { @@ -149,25 +166,30 @@ inline long long dflash_block(const RadModelMeta* meta) { /* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less * the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the - * container carries one and `out` now names its depth. */ + * container carries one and `out` now names its depth. Chained launches measured a gain with it + * (the 26B-A4B's speculative step, +1% on 4x R9700), so the probe asks for them + * (RadArchProbe::chain_pays). */ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) { if (dflash_kind(meta) != 1) return false; const long long bs = dflash_block(meta); if (bs <= 1) return false; out->draft_depth = (int)(bs - 1); out->draft_depth_fixed = 1; + out->chain_pays = 1; return true; } /* The same for a DFlash2 drafter, for a plugin that serves rad_block_dflash2.h (the 31B's): its * anchor predicts nothing either, so the depth is the trained block less one, 7 for RedHatAI's - * gemma-4-31B-it-speculator.dflash2 (block_size 8). */ + * gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches measured a gain with it (the + * 31B's speculative step, +13% on 4x R9700), so the probe asks for them. */ inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) { if (dflash_kind(meta) != 2) return false; const long long bs = dflash_block(meta); if (bs <= 1) return false; out->draft_depth = (int)(bs - 1); out->draft_depth_fixed = 1; + out->chain_pays = 1; return true; } diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index a83f3982..01459f5f 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -286,6 +286,13 @@ struct Gemma4Attn { * the copies of k and v too, ahead of the unfused prologue, which reads them dense. */ rad_op op_attn_row = 0, op_attn_dec = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0; int64_t dec_hi = 0; + /* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see + * "Prefetch beside the reductions") */ + rad_op op_pf = 0; + rad_weight pf_w = 0; + /* the feed-forward's down_proj read into the cache beside the attention itself, or 0 */ + rad_op op_pfd = 0; + rad_weight pfd_w = 0; /* The linear whose int8 pair a junction writes, and whether every projection reads it. */ const G4Linear& ln_in() const { return fused ? ln_qkv : ln_q; } @@ -306,6 +313,13 @@ struct Gemma4Attn { void project(RadCtx* c, int64_t r0, int64_t n) const; void attend(RadCtx* c, const RadBatch* batch) const; void out_proj(RadCtx* c, int64_t r0, int64_t n) const; + /* The prologue and the attention over rows [r0, r0 + n) of a one-sequence step alone (the + * prefill overlap's slices), `used` the context the slice ends at (kv_len_trim for a slice + * that ends before the step does). Only with the one-launch prologue and a prefill-height + * attention that reads q dense or in the row (slicable). */ + bool slicable() const { return op_qnr_kv && (op_attn_row || op_attn); } + void attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n, + RadOperand used) const; }; int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, @@ -575,6 +589,22 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const return RAD_OK; } +/* ---- Prefetch beside the reductions (prefetch_beside, rad_arch.h). The all-reduce in front of + * each GEMM leaves the card's memory idle for its round trip (~20 us at a DFlash2 verify's rows on + * 4x R9700), so the trunk reads the next GEMM's leading bytes in that window -- gate_up's after + * o_proj, the next layer's q|k|v after down_proj -- and the GEMM finds them in the 64 MB on-die + * cache. The attention leaves it mostly idle too at a verify's few rows and a chat's context, so + * down_proj's weight is read beside it, after q|k|v. On four cards (a microbenchmark of the + * two-shot and a GEMM-like stream of a cold 29 MB weight) 16 MB read beside the reduction took a + * layer from 84.0 us to 70.1; read on the same lane it gained nothing. */ + +/* The height prefetch_beside judges a trunk step by: its rows on a decode step (decode and verify + * rows only), and none at all on one that carries a prompt's rows (rad_arch.h, kPrefetchRows): the + * row ceiling keeps long prefills out, and this keeps out the short ones it would let in. */ +static int64_t prefetch_height(const RadBatch* batch) { + return batch->phase == RAD_PHASE_DECODE ? batch->n_tok : INT64_MAX; +} + void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, bool ar_fused) const { const int64_t T = batch->n_tok; @@ -593,9 +623,11 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta ln_k.step(c, w.h, w.k, T); if (cls.has_v) ln_v.step(c, w.h, w.v, T); } + prefetch_beside(c, op_pfd, pfd_w, prefetch_height(batch)); attend(c, batch); ln_o.step(c, w.attn, w.h, T); + prefetch_beside(c, op_pf, pf_w, prefetch_height(batch)); /* The all-reduce comes before the post-norm: o_proj is column-sharded, so each rank holds a * partial sum, and the norm is of the whole output (sum_r rmsnorm(p_r) != rmsnorm(sum_r p_r)). */ if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); @@ -676,6 +708,37 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { brows(w.attn, T)); } +/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's + * earlier rows (the slices run in order, each storing its own keys first), `used` ends the context + * at the slice's last row, the kernel counts each row's position back from there, and the key + * tiles start at the sequence's first key in both cases. The prologue is a row at a time. */ +void Gemma4Attn::attend_rows(RadCtx* c, const RadBatch* batch, int64_t r0, int64_t n, + RadOperand used) const { + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); + const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0); + const bool row = fused && op_qnr; + const RadOperand Q = row ? bcol_at(w.qkv, r0, qkvd, 0, qd, n) : brow_slice(w.q, r0, n, qd); + const RadOperand K = row ? bcol_at(w.qkv, r0, qkvd, qd, kvd, n) : brow_slice(w.k, r0, n, kvd); + const RadOperand V = row && cls.has_v ? bcol_at(w.qkv, r0, qkvd, qd + kvd, kvd, n) + : brow_slice(w.v, r0, n, kvd); + RAD_ISSUE_N(c, op_qnr_kv, n, Q, K, V, praw(batch->positions + r0, RAD_I32, n), RAD_W(w_qn), + RAD_W(w_kn), praw(slot ? slot + r0 : nullptr, RAD_I32, n), kv_cache(kv, layer)); + rad_op a_op = op_attn; + RadOperand a_q = brow_slice(w.q, r0, n, qd); + if (op_attn_row) { + a_op = op_attn_row; + a_q = Q; + } else if (row) { + RAD_ISSUE_N(c, op_lift_q, n, Q, a_q); + } + RAD_ISSUE_N(c, a_op, n, a_q, kv_cache(kv, layer), + praw2(table, RAD_I32, 1, kvb ? kvb->block_table_pitch : 0), used, + RAD_NONE, RAD_NONE, RAD_NONE, brow_slice(w.attn, r0, n, qd)); +} + /* ---- the feed-forward: GELU (not SwiGLU), with a second norm on the down-projection output. */ struct Gemma4Mlp { struct Wire { rad_buf x = 0, h = 0, gu = 0, ffn = 0; }; @@ -688,6 +751,10 @@ struct Gemma4Mlp { rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0; /* gelu_mul and down's quantiser as one, where it resolves (libr4d `gelu_mul_quant_i8`) */ rad_op op_gq = 0; + /* the next layer's q|k|v read into the cache beside this block's all-reduce, or 0 (see + * "Prefetch beside the reductions") */ + rad_op op_pf = 0; + rad_weight pf_w = 0; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre); void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, @@ -791,6 +858,7 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai RAD_ISSUE(c, op_act, brows(w.gu, T), brows(w.ffn, T)); ln_down.step(c, w.ffn, w.h, T); } + prefetch_beside(c, op_pf, pf_w, prefetch_height(batch)); /* The all-reduce before the post-norm, as in the attention block: down_proj is column-sharded. */ if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); if (tail_fused) return; @@ -1362,6 +1430,17 @@ struct Layer { G4Junction j_am{}, j_ma{}; /* the DFlash drafter's tap: this layer's output into its column slice of `dflash_src` */ rad_op op_tap = 0; + /* The prefill overlap's reductions (trunk_overlap): attn.op_ar and mlp.op_ar at `overlap` 1, + * the narrow launch that leaves the CUs to the other slice's compute; 0 where not declared. */ + rad_op op_ar_att_ov = 0, op_ar_ff_ov = 0; +}; + +/* The prefill overlap's attention per slice (trunk_overlap): slice A's context end, one + * kv_len_trim a KV group the attention reads. */ +struct SliceTrim { + rad_kvgroup kv = 0; + rad_op op = 0; + rad_buf used = 0; /* [max_seqs] int32 */ }; struct Model { @@ -1417,6 +1496,10 @@ struct Model { Dflash2 df2{}; Dflash2::Wire df2w{}; bool have_df2 = false; + /* The prefill overlap runs attention per slice: a trim a KV group (sliding, global). */ + SliceTrim trim[2]{}; + int n_trim = 0; + bool slice_attn = false; }; static Model g_model[MAX_RANKS]; @@ -1483,6 +1566,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui dc.group = df2_geti(meta, "conv_group_size", 16); dc.sel_rank = df2_geti(meta, "selector_rank", 0); dc.sel_topk = df2_geti(meta, "selector_top_k", 0); + dc.prefetch = gemma4::kPrefetchBytes; if (dc.sel_rank <= 0 || dc.sel_topk <= 0) { fprintf(stderr, "radiance: gemma4: the DFlash2 drafter states no selector geometry (rank " "%lld, top_k %lld)\n", (long long)dc.sel_rank, (long long)dc.sel_topk); @@ -1881,6 +1965,32 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.ar_rows = ar ? rows : 0; } + /* ---- prefetch beside the reductions (see prefetch_beside): gate_up's first 20 MB beside the + * attention block's all-reduce and the next layer's q|k|v's (q alone, unfused; after the last + * layer, the lm_head's) beside the feed-forward's (gemma4::kPrefetchBytes), then down_proj's + * first 9 MB beside the attention (gemma4::kPrefetchDownBytes). Only at more than one rank, + * where there are reductions to sit beside. RADIANCE_PREFETCH=0 declares none + * (decl_prefetch). */ + if (g.world > 1 && rad_op_declared(b, "prefetch")) { + for (size_t l = 0; l < m.layers.size(); ++l) { + Layer& lay = m.layers[l]; + lay.attn.pf_w = lay.mlp.ln_gu.w; + lay.attn.op_pf = decl_prefetch(b, lay.attn.pf_w, gemma4::kPrefetchBytes); + /* after the last layer the lm_head is the next weight streamed */ + if (l + 1 < m.layers.size()) { + const Gemma4Attn& nx = m.layers[l + 1].attn; + lay.mlp.pf_w = nx.fused ? nx.ln_qkv.w : nx.ln_q.w; + } else { + lay.mlp.pf_w = m.w_lm; + } + lay.mlp.op_pf = decl_prefetch(b, lay.mlp.pf_w, gemma4::kPrefetchBytes); + } + for (Layer& lay : m.layers) { + lay.attn.pfd_w = lay.mlp.ln_down.w; + lay.attn.op_pfd = decl_prefetch(b, lay.attn.pfd_w, gemma4::kPrefetchDownBytes); + } + } + /* ---- the prefill overlap (trunk_overlap). It needs a reduction to hide, every junction fused * (the slices issue only the fused forms), and the exact wire, the one shown to give a slice * the bits it gives the whole. The buffer the second lane reduces in place is taken out of the @@ -1892,6 +2002,64 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c for (const Layer& lay : m.layers) m.overlap = m.overlap && lay.attn.op_ar && lay.mlp.op_ar; if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h)); + /* The reductions the overlap runs on lane 1 are their own ops at `overlap` 1. Declared like + * op_ar, they resolve to the wide launch: the exact two-shot over every word of a 512- to + * 1024-row slice takes nb_for_shard's ceiling, 24 blocks of 1024 threads, each a whole CU + * spinning on a peer flag for the ~1 ms the link takes -- a third of the card held away from + * the other slice's GEMMs. At `overlap` 1 the row is ar_twoshot_4rank_exact_lane: the same + * entry and the same fold per word (the block count moves no byte), four blocks by default + * (tArTs4Lane). Its range starts at a slice, which is above every one-shot band. */ + if (m.overlap) { + auto lane_ar = [&]() { + return rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", kOverlapRows * g.n_embd, + g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes), + RAD_INT("overlap", 1)), + RAD_NOWEIGHTS), + {m.b_h}, {m.b_h}); + }; + for (Layer& lay : m.layers) { + lay.op_ar_att_ov = lane_ar(); + lay.op_ar_ff_ov = lane_ar(); + } + } + /* ...and with attention per slice. Run whole between the slices, a layer's attention leaves + * slice A's attention-side reduction only slice B's o_proj to hide behind, and slice B's + * feed-forward reduction only slice A's junction and q|k|v. Per slice (A's projection, + * prologue, attention and o_proj, then B's), each of the four reductions sits beside a whole + * block: on 4x R9700 the exact two-shot of a 1024-row slice takes ~1.05 ms alone and ~1.4x + * that beside any card-filling compute (a four-card microbenchmark, 2026-10-18). Slice A's + * attention reads its context end from kv_len_trim, one a KV group. A one-sequence step only + * (the slices' rows are then one sequence's), with the one-launch prologue and no + * multi-component rotary. Byte-identical: every greedy reply matches the whole attention's + * (4x R9700, two rounds, and 16 of 16 fresh starts on a 5310-token prompt); prefill +5%. */ + if (m.overlap) { + bool ok = !g.rope_mc && rad_op_declared(b, "kv_len_trim"); + for (const Layer& lay : m.layers) ok = ok && lay.attn.slicable(); + for (const Layer& lay : m.layers) { + if (!ok) break; + int i = 0; + while (i < m.n_trim && m.trim[i].kv != lay.attn.kv) ++i; + if (i < m.n_trim) continue; + if (m.n_trim == 2) { ok = false; break; } + SliceTrim& t = m.trim[m.n_trim]; + t.kv = lay.attn.kv; + t.used = decl_b(b, nm.f("slice_used_%d", m.n_trim), RAD_I32, {g.max_seqs}); + ok = t.used && rad_buf_concurrent(b, t.used) == RAD_OK; + t.op = ok ? rw(b, RAD_OP(b, "kv_len_trim", + RAD_PARAMS(RAD_RANGE("trim", 1, g.max_tok), + RAD_INT("max_seqs", g.max_seqs)), + RAD_NOWEIGHTS), + {}, {t.used}) + : 0; + ok = ok && t.op; + ++m.n_trim; + } + m.slice_attn = ok && m.n_trim > 0; + } /* ---- the tail: final norm, the sampled rows, the lm_head, and the soft-cap. */ m.op_final = rw(b, RAD_OP(b, "rmsnorm", @@ -2088,6 +2256,60 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6 m.j0.step(c, T); const size_t L = m.layers.size(); + if (m.slice_attn && batch->n_seq == 1) { + /* Attention per slice (see Model::slice_attn): slice A's context end first, then each + * layer as A's attention block, B's beside A's attention-side reduction, A's feed-forward + * beside B's, B's feed-forward beside A's, and the next layer's A block beside B's. Each + * join is issued before the reduction it must not wait for, so it orders lane 0 behind + * exactly the ones issued so far; lane 1 always reduces rows of `h` lane 0 is not + * touching. */ + auto used_of = [&](rad_kvgroup kv, bool slice_a) -> RadOperand { + if (slice_a) + for (int i = 0; i < m.n_trim; ++i) + if (m.trim[i].kv == kv) return brows(m.trim[i].used, 1); + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + return praw(kvb ? kvb->seqused : nullptr, RAD_I32, 1); + }; + for (int i = 0; i < m.n_trim; ++i) { + const RadKVGroupBatch* kvb = kv_batch(batch, m.trim[i].kv); + /* the trim is `tail`'s extent, slice B's rows: a launch reads its ranged parameter + * as the band's upper bound, not as bn */ + RAD_ISSUE_N(c, m.trim[i].op, bn, praw(kvb ? kvb->seqused : nullptr, RAD_I32, 1), + praw(batch->positions + b0, RAD_I32, bn), brows(m.trim[i].used, 1)); + } + for (size_t li = 0; li < L; ++li) { + const Layer& y = m.layers[li]; + const rad_op ar_att = y.op_ar_att_ov ? y.op_ar_att_ov : y.attn.op_ar; + const rad_op ar_ff = y.op_ar_ff_ov ? y.op_ar_ff_ov : y.mlp.op_ar; + if (li > 0) join_ff(li - 1, a0, an); /* its reduction was waited for below */ + y.attn.project(c, a0, an); + y.attn.attend_rows(c, batch, a0, an, used_of(y.attn.kv, true)); + y.attn.out_proj(c, a0, an); + if (li > 0) join_back(); /* the last layer's feed-forward, slice B */ + reduce(ar_att, a0, an); + if (li > 0) join_ff(li - 1, b0, bn); + y.attn.project(c, b0, bn); + y.attn.attend_rows(c, batch, b0, bn, used_of(y.attn.kv, false)); + y.attn.out_proj(c, b0, bn); + join_back(); /* attention, slice A */ + reduce(ar_att, b0, bn); + y.j_am.step_rows(c, E, a0, an); + y.mlp.arm(c, a0, an); + join_back(); /* attention, slice B */ + reduce(ar_ff, a0, an); + y.j_am.step_rows(c, E, b0, bn); + y.mlp.arm(c, b0, bn); + join_back(); /* the feed-forward, slice A */ + reduce(ar_ff, b0, bn); + } + join_ff(L - 1, a0, an); + join_back(); /* the last feed-forward, slice B */ + join_ff(L - 1, b0, bn); + if (!lanes_ok) + rad_step_fail(c, "gemma4_bf16: the prefill overlap could not order its second lane " + "against the first"); + return; + } for (size_t li = 0; li < L; ++li) { const Layer& y = m.layers[li]; if (li == 0) { @@ -2101,19 +2323,21 @@ static void trunk_overlap(RadCtx* c, const Model& m, const RadBatch* batch, int6 y.attn.project(c, b0, bn); } y.attn.attend(c, batch); + const rad_op ar_att = y.op_ar_att_ov ? y.op_ar_att_ov : y.attn.op_ar; + const rad_op ar_ff = y.op_ar_ff_ov ? y.op_ar_ff_ov : y.mlp.op_ar; y.attn.out_proj(c, a0, an); - reduce(y.attn.op_ar, a0, an); + reduce(ar_att, a0, an); y.attn.out_proj(c, b0, bn); join_back(); /* attention, slice A */ - reduce(y.attn.op_ar, b0, bn); + reduce(ar_att, b0, bn); y.j_am.step_rows(c, E, a0, an); y.mlp.arm(c, a0, an); join_back(); /* attention, slice B */ - reduce(y.mlp.op_ar, a0, an); + reduce(ar_ff, a0, an); y.j_am.step_rows(c, E, b0, bn); y.mlp.arm(c, b0, bn); join_back(); /* the feed-forward, slice A */ - reduce(y.mlp.op_ar, b0, bn); + reduce(ar_ff, b0, bn); } join_ff(L - 1, a0, an); join_back(); /* the last feed-forward, slice B */ diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index e97cac62..3ff32f5e 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1966,6 +1966,8 @@ void Builder::finish_layouts() { const int st = ki->layout ? ki->layout(r.geom.params(), r.geom.n_params(), operand, &w.enc, w.sel, t, w.n_sel, &L) : RAD_E_UNSUPPORTED; + /* Reads the bytes uninterpreted (a prefetch): no claim (rad_abi.h). */ + if (st == RAD_LAYOUT_ANY) continue; char enc[256]; rad_enc_format(&w.enc, enc, sizeof enc); if (st == RAD_E_DTYPE) { @@ -2353,6 +2355,8 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo); } +int rad_chain_on(void) { return rad_dev_chain_enabled(); } + int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { if (!b) return RAD_E_INVAL; return B(b)->declare_encoder(d); diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 23fd93f8..96da9b75 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -161,6 +161,9 @@ struct KernelRec { int32_t hid[16]; /* offset of each Hidden kind, or -1 */ uint8_t hid_size[16]; std::string name; + /* A chained form (RadKernelChainFn): its name carries "r4dchain". Only such a kernel gets a + * chain record and may lose its barrier bit; a row's other kernels keep the bit. */ + bool chained = false; }; struct ModuleImage { @@ -509,6 +512,7 @@ KernelRec* resolve(Func* fn, int ord) { } auto k = std::make_unique(); k->name = fn->name; + k->chained = k->name.find("r4dchain") != std::string::npos; hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT, &k->object); hsa_executable_symbol_get_info(s, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE, &k->kernarg_size); @@ -596,6 +600,16 @@ struct Stream { std::atomic fault{0}; char* bounce = nullptr; /* pinned, for pageable copies */ std::mutex bounce_mu; + /* Chained launches (RadKernelChainFn): the completion counter every block of a chained kernel + * adds 1 to (in the slot after the argument ring), the blocks of chained kernels issued so + * far, and whether the last packet on the queue was a chained kernel. */ + uint64_t* chain_ctr = nullptr; + uint64_t chain_issued = 0; + bool prev_chained = false; + /* Whether a packet that adds nothing to the counter (a plain kernel) may still be running: one + * launched since the last packet whose barrier bit held it behind everything before. A chained + * kernel's wait covers only chained blocks, so while this is set the next one keeps its bit. */ + bool plain_inflight = false; void lock() { while (busy.exchange(true, std::memory_order_acquire)) @@ -955,6 +969,9 @@ struct TapeRec { * on the queue still run. Set only where the dispatch touches nothing those packets write * (tape_set_overlap). */ uint8_t overlap = 0; + /* A chained kernel (RadKernelChainFn): played from the queue's own argument slot with a chain + * record, and without the barrier bit behind another chained kernel. */ + uint8_t chain = 0; }; struct Tape { @@ -975,11 +992,12 @@ inline bool capturing() { return t_tape && t_tape_pause == 0; } /* A dispatch just written at `p` on `s`, with its argument block `ka`. */ void tape_note_dispatch(Stream* s, const hsa_kernel_dispatch_packet_t* p, uint16_t setup, - const unsigned char* ka, uint32_t n, uint8_t fence) { + const unsigned char* ka, uint32_t n, uint8_t fence, bool chain) { Tape* t = t_tape; TapeRec r; r.kind = kTapeDispatch; r.fence = fence; + r.chain = chain ? 1 : 0; r.s = s; r.pkt = *p; r.pkt.header = 0; @@ -1014,12 +1032,32 @@ inline int acquire_scope(Stream* s, uint64_t idx, bool forced) { return HSA_FENCE_SCOPE_AGENT; } +/* The chain record of a chained launch (RadKernelChainFn) at `slot`: wait for every chained + * block issued before it on `s`. `on` false writes a record no kernel accepts. */ +inline void chain_record(Stream* s, char* slot, bool on) { + uint64_t rec[4]; + rec[0] = on ? RAD_CHAIN_MAGIC : 0; + rec[1] = s->chain_issued; + rec[2] = (uint64_t)(uintptr_t)s->chain_ctr; + rec[3] = rec[0] ^ rec[1] ^ rec[2] ^ RAD_CHAIN_CHECK; + std::memcpy(slot + RAD_CHAIN_KARG_OFF, rec, sizeof rec); +} +inline uint64_t blocks_of(const hsa_kernel_dispatch_packet_t* p) { + auto n = [](uint32_t g, uint16_t b) { return b ? (uint64_t)((g + b - 1u) / b) : 1u; }; + return n(p->grid_size_x, p->workgroup_size_x) * n(p->grid_size_y, p->workgroup_size_y) * + n(p->grid_size_z, p->workgroup_size_z); +} +static_assert(RAD_CHAIN_KARG_OFF >= kKargMax && RAD_CHAIN_KARG_OFF + RAD_CHAIN_REC_BYTES <= kKargSlot, + "the chain record sits in an argument slot's tail, past every kernel's arguments"); + int barrier(Stream* s, hsa_signal_t dep, hsa_signal_t done, int acq, int rel, uint64_t* out_idx = nullptr) { s->lock(); uint64_t idx = 0; const int rc = reserve(s, &idx); if (rc < 0) { s->unlock(); return rc; } + s->prev_chained = false; + s->plain_inflight = false; if (out_idx) *out_idx = idx; auto* p = reinterpret_cast( static_cast(s->q->base_address) + (idx & s->mask)); @@ -1079,7 +1117,11 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t p->reserved2 = 0; p->completion_signal.handle = 0; constexpr uint16_t setup = 3u << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS; - if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence); + /* A chained kernel (RadKernelChainFn, named r4dchain*): its record in the slot's tail. */ + const bool chain = k->chained && rad_dev_chain_enabled() && s->chain_ctr && + n <= RAD_CHAIN_KARG_OFF; + if (k->chained) chain_record(s, slot, chain); + if (capturing()) tape_note_dispatch(s, p, setup, ka, n, fence, chain); /* Attach the ride after the tape copied the packet: a recorded packet carries no signal, and * a play attaches whichever ride is pending then (PlayRun::put). */ if (s->ride.handle) { @@ -1088,7 +1130,13 @@ int dispatch(Stream* s, const KernelRec* k, dim3 g, dim3 b, void** args, size_t } const int acq = acquire_scope(s, idx, (fence & kFenceAcquireSystem) != 0); const int rel = (fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT; - publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel), setup); + /* Behind another chained kernel a chained one waits in its prologue; a completion signal keeps + * the bit, since its completion must cover everything before it. */ + const bool keep = !(chain && s->prev_chained && !s->plain_inflight && !p->completion_signal.handle); + publish(s, idx, header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, keep), setup); + if (chain) s->chain_issued += blocks_of(p); + s->prev_chained = chain; + s->plain_inflight = keep ? !chain : s->plain_inflight || !chain; s->unlock(); return RAD_OK; } @@ -1110,6 +1158,7 @@ constexpr int kPlayLeft = 8; thread_local PlayLeft t_left[kPlayLeft]; struct PlayRun { + const Tape* tape = nullptr; /* the tape played, for a chained record's argument bytes */ Stream* s = nullptr; uint64_t next = 0; /* the write index after the last packet written */ int unrung = 0; @@ -1167,16 +1216,38 @@ struct PlayRun { s->ride.handle = 0; } if (done.handle) p->completion_signal = done; + /* A chained record plays from this queue's own argument slot, where its chain record goes: + * the tape's copy is shared by every play, and the next step's play may be written while + * this one runs. */ + bool chain = false; + if (r.chain && tape) { + char* slot = s->karg + (size_t)(idx & s->mask) * kKargSlot; + chain = s->chain_ctr && r.karg_len <= RAD_CHAIN_KARG_OFF; + if (chain) { + std::memcpy(slot, tape->karg_host.data() + r.karg_off, r.karg_len); + p->kernarg_address = slot; + chain_record(s, slot, true); + } + } const int acq = acquire_scope(s, idx, (r.fence & kFenceAcquireSystem) != 0); int rel = (r.fence & kFenceReleaseSystem) ? HSA_FENCE_SCOPE_SYSTEM : HSA_FENCE_SCOPE_AGENT; if (rel < rel_min) rel = rel_min; /* A dispatch carrying a record keeps the bit: its completion must cover everything before - * it on the queue, which an unordered dispatch's does not. */ - const bool ordered = foreign || !r.overlap || done.handle; + * it on the queue, which an unordered dispatch's does not. A chained kernel behind another chained one + * on this queue waits in its prologue instead. */ + bool ordered = foreign || !r.overlap || done.handle; + /* Not while a plain packet may still run: a played plain kernel the overlap analysis let + * start early (it touched nothing in flight) adds nothing to the counter, so a chained + * kernel that reads its output and sits behind a chained one (a cache read beside a + * collective, say) would wait for the chained blocks only. */ + if (chain && s->prev_chained && !s->plain_inflight && !foreign && !done.handle) ordered = false; const uint16_t h = header(HSA_PACKET_TYPE_KERNEL_DISPATCH, acq, rel, ordered); __atomic_store_n(reinterpret_cast(p), (uint32_t)h | ((uint32_t)r.pkt.setup << 16), __ATOMIC_RELEASE); foreign = false; + if (chain) s->chain_issued += blocks_of(p); + s->prev_chained = chain; + s->plain_inflight = ordered ? !chain : s->plain_inflight || !chain; s->wr = idx + 1; next = idx + 1; *out_idx = idx; @@ -1423,7 +1494,7 @@ int a_stream_create(RadStream* out, int high_priority) { void* ka = nullptr; hsa_amd_memory_pool_t kpool = d.host_kargs ? G().host_fine : d.vram; hsa_agent_t kpeer = d.host_kargs ? d.agent : G().cpu; - if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 1) * kKargSlot, 0, &ka) != + if (hsa_amd_memory_pool_allocate(kpool, (size_t)(s->mask + 2) * kKargSlot, 0, &ka) != HSA_STATUS_SUCCESS || hsa_amd_agents_allow_access(1, &kpeer, nullptr, ka) != HSA_STATUS_SUCCESS) { hsa_queue_destroy(s->q); @@ -1432,6 +1503,9 @@ int a_stream_create(RadStream* out, int high_priority) { return RAD_E_DEVICE; } s->karg = static_cast(ka); + s->chain_ctr = reinterpret_cast(s->karg + (size_t)(s->mask + 1) * kKargSlot); + *reinterpret_cast(s->chain_ctr) = 0; + _mm_sfence(); void* bb = nullptr; if (hsa_amd_memory_pool_allocate(G().host_fine, kBounceBytes, 0, &bb) != HSA_STATUS_SUCCESS || hsa_amd_agents_allow_access(1, &d.agent, nullptr, bb) != HSA_STATUS_SUCCESS) { @@ -1441,7 +1515,7 @@ int a_stream_create(RadStream* out, int high_priority) { return RAD_E_NOMEM; } s->bounce = static_cast(bb); - note_alloc(ka, (int64_t)(s->mask + 1) * kKargSlot, -1); + note_alloc(ka, (int64_t)(s->mask + 2) * kKargSlot, -1); note_alloc(bb, kBounceBytes, -1); s->id = g_next_queue_id.fetch_add(1, std::memory_order_relaxed); if (s->id >= kMaxQueues) { @@ -1802,9 +1876,12 @@ RadTape a_tape_end(int keep) { if (!t->karg_host.empty()) { const Dev& d = G().dev[(size_t)ord]; void* ka = nullptr; + /* Padded by a slot: a chained kernel played from here reads its record's place + * (RAD_CHAIN_KARG_OFF) past its own arguments. */ hsa_amd_memory_pool_t pool = d.host_kargs ? G().host_fine : d.vram; hsa_agent_t peer = d.host_kargs ? d.agent : G().cpu; - if (hsa_amd_memory_pool_allocate(pool, t->karg_host.size(), 0, &ka) != HSA_STATUS_SUCCESS || + if (hsa_amd_memory_pool_allocate(pool, t->karg_host.size() + kKargSlot, 0, &ka) != + HSA_STATUS_SUCCESS || hsa_amd_agents_allow_access(1, &peer, nullptr, ka) != HSA_STATUS_SUCCESS) { if (ka) hsa_amd_memory_pool_free(ka); device_set_error("the pass cannot be recorded: %zu bytes of kernel arguments could " @@ -1854,6 +1931,7 @@ int a_tape_play(RadTape rt, int from, int to) { ++t_tape_pause; int rc = RAD_OK; PlayRun run; + run.tape = t; for (int i = from; i < to && rc >= 0; ++i) { const TapeRec& r = t->rec[(size_t)i]; if (r.kind == kTapeDispatch) { diff --git a/core/device/device.h b/core/device/device.h index f5f8b78a..a14df707 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -36,6 +36,15 @@ extern "C" int rad_event_create_as(RadEvent* out, unsigned flags); /* The host has just written memory that a kernel issued after this call reads, with no host wait * in between (e.g. a host-site op's output read over the link by the next device op). */ extern "C" void rad_dev_host_wrote(void); +/* Chained launches: chainable rows run their chained forms (RadKernelChainFn), and the backend + * lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit. + * Only on the AQL backend, whose queues keep the completion counter. On by default where the + * model's plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays: the + * Gemma 4 31B and 26B) and that drafter decodes speculatively (rad_dev_chain_infer, from the + * engine before any row resolves). RADIANCE_CHAIN=0 turns them off and =1 on wherever the backend + * chains; `auto` is the default. */ +extern "C" int rad_dev_chain_enabled(void); +extern "C" void rad_dev_chain_infer(int pays); /* One range of a ranged copy: `bytes` from source offset `src` to destination offset `dst`, all * three multiples of four. */ diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index a5694a6e..f0599462 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -556,6 +556,29 @@ int rad_event_sync(RadEvent e) { return dev()->event_sync(e); } void rad_dev_host_wrote(void) { dev()->host_wrote(); } + +/* Chaining's default, from the engine (rad_dev_chain_infer), and the answer once taken. Only + * where the backend chains: the AQL backend writes the record a chained form reads, while a HIP + * launch carries only the kernel's own arguments. */ +static std::atomic g_chain_pays{0}; +static std::atomic g_chain{-1}; +void rad_dev_chain_infer(int pays) { + g_chain_pays.store(pays ? 1 : 0, std::memory_order_relaxed); + g_chain.store(-1, std::memory_order_relaxed); +} +int rad_dev_chain_enabled(void) { + int on = g_chain.load(std::memory_order_relaxed); + if (on < 0) { + const char* e = std::getenv("RADIANCE_CHAIN"); + const bool want = e && *e && std::strcmp(e, "auto") != 0 + ? *e != '0' + : g_chain_pays.load(std::memory_order_relaxed) != 0; + on = want && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0; + g_chain.store(on, std::memory_order_relaxed); + } + return on; +} + int rad_event_elapsed_ms(RadEvent a, RadEvent b, float* out) { return dev()->event_elapsed_ms(a, b, out); } diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index c42871ca..caf81846 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -1026,6 +1026,25 @@ int Engine::declare() { cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point" : "this container carries no draft head"); } + /* Chained launches pay on some speculative steps and cost plain decode (4x R9700: the 31B + * with DFlash2 +13%, the 26B-A4B with DFlash +1%, Qwen3.8-27B with DFlash2 even; the 31B with + * no drafter -6.5%), so they are on by default only where the model's plugin measured a gain + * with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes + * speculatively. */ + { + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + rad_dev_chain_infer(cfg_.n_spec > 0 && pb.chain_pays); + const char* e = std::getenv("RADIANCE_CHAIN"); + const bool on = rad_dev_chain_enabled() != 0; + const char* why = e && *e && std::strcmp(e, "auto") != 0 + ? (on || *e == '0' ? "RADIANCE_CHAIN says so" : "the backend does not chain") + : on ? "the model's plugin measured a gain with its speculative drafter" + : "no drafter whose plugin measured a gain with them decodes " + "speculatively, or the backend does not chain"; + RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why); + decide("RADIANCE_CHAIN", on ? "1" : "0", why); + } /* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio * encoder (`radiance.encoder` names one) and the deployment is not text-only. */ if (cfg_.mm_audio_frames < 0) { diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 8af65715..0e39344d 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -441,6 +441,7 @@ int Registry::commit_(Staged& s, int order) { } const auto concurrent = dl_fn(s.handle, "rad_kernel_concurrent"); const auto collective = dl_fn(s.handle, "rad_kernel_collective"); + const auto chainable = dl_fn(s.handle, "rad_kernel_chain"); for (const auto& sr : staged_rows) { KernelRow row; row.info = sr.first; @@ -452,6 +453,7 @@ int Registry::commit_(Staged& s, int order) { row.collective = coll != 0; row.releases_link = coll == 2; row.reference = p.reference; + row.chain = chainable && chainable(sr.second) != 0; rows_.push_back(row); } diff --git a/core/plugin/select.cpp b/core/plugin/select.cpp index edda4446..99ca6f16 100644 --- a/core/plugin/select.cpp +++ b/core/plugin/select.cpp @@ -5,6 +5,7 @@ * one. A match is necessary, not sufficient: strides, contiguity, alignment and buffer sizes are * properties of a call, and the entry point still rejects what it cannot run. */ +#include "../device/device.h" #include "registry.h" #include @@ -384,6 +385,10 @@ Resolved Registry::resolve(std::string_view op, const Geometry& g, int domain, S for (const auto& kv : chosen) r.geom.set_i(kv.first, kv.second); r.choice = TuneCache::canon_choice(chosen); } + /* A chainable row runs its chained form wherever chaining is on (RadKernelChainFn); the + * parameter is outside the tune cache's key, which was taken above. */ + if (r.row->chain && rad_dev_chain_enabled()) + r.geom.set_i("chain", 1); /* scratch_bytes stays 0: the scratch hook needs a RadArgs with the operand tensors, which the * builder owns and sizes the arena with. */ diff --git a/core/plugin/testplugin/testplugin.cc b/core/plugin/testplugin/testplugin.cc index 7c28d052..7c9cf587 100644 --- a/core/plugin/testplugin/testplugin.cc +++ b/core/plugin/testplugin/testplugin.cc @@ -346,8 +346,8 @@ extern "C" int rad_plugin_reference(void) { return 1; } /* ================================================================== radtest_extra */ /* Rows for rules the base plugin's ops do not reach: a constraint on the ranged key that is not an - * interval, a tunable axis with a cross-axis test, a kernel that relayouts its weight, and a - * capacity parameter. In testkernels/extra, so loading testkernels/ alone is unchanged. */ + * interval, a tunable axis with a cross-axis test, a kernel that relayouts its weight, a kernel + * that reads any stored form, and a capacity parameter. In testkernels/extra, so loading testkernels/ alone is unchanged. */ #elif defined(RADTEST_EXTRA) static const RadOperandSpec kOpdCap[] = { @@ -368,6 +368,8 @@ static const RadOpSchema kSchemas[] = { "a kernel that stores its weight in its own layout" }, { "t_join", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "a weight of several planes: a device kernel's own form, a host kernel's joined one" }, + { "t_any", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), + "a kernel that reads its weight's stored bytes uninterpreted (a prefetch)" }, { "t_cap", kPCap, NELEM(kPCap), kOpdCap, NELEM(kOpdCap), "a capacity a sizing declare may shrink" }, }; @@ -417,6 +419,12 @@ static int t_join_host_layout(const RadParam* p, int n_p, int operand, const Rad return rad_planes_layout(enc, sel, planes, n_planes, out); } +/* Reads the stored bytes without interpreting them: any form, and claims none. */ +static int t_any_layout(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*) { + return RAD_LAYOUT_ANY; +} + static const RadConstraint kCLayTiled[] = { RAD_CLE("M", 16) }; static const RadConstraint kCLayPlain[] = { RAD_CLE("M", 4096) }; @@ -462,6 +470,11 @@ static const RadKernelInfo kKernels[] = { .domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch, .layout = t_join_host_layout }, + { .name = "t_any_read", .op = "t_any", .family = "misc", + .computes = "nothing; a registry row", .shape = "any", .dtypes = "any stored form", + .domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch, + .layout = t_any_layout }, + { .name = "t_cap_any", .op = "t_cap", .family = "norm", .computes = "nothing; a registry row", .shape = "any", .dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch }, diff --git a/core/rad_core.h b/core/rad_core.h index c6447c01..62329504 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -57,6 +57,8 @@ struct KernelRow { bool releases_link = false; /* The row's plugin declared itself a reference implementation (RadPluginReferenceFn). */ bool reference = false; + /* rad_kernel_chain: its launches can wait in the kernel instead of behind the barrier bit. */ + bool chain = false; }; /* A kernel bound to one geometry, one domain and one variant, with init() already run. */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 64487a86..a66d0e26 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -455,6 +455,7 @@ int Ctx::check_domain_layout(rad_op h, int domain, std::string* why) const { const int st = ki->layout ? ki->layout(ip.args.p, ip.args.n_p, opd, &w.enc, w.sel, t, w.n_sel, &L) : RAD_E_UNSUPPORTED; + if (st == RAD_LAYOUT_ANY) continue; /* reads the bytes as they lie (rad_abi.h) */ const std::string tag = st == RAD_OK ? (L.tag && *L.tag ? L.tag : ki->name) : std::string(); if (st >= 0 || st == RAD_E_UNSUPPORTED) { diff --git a/core/sched/advance.hip b/core/sched/advance.hip index 463fd95f..0d35d4ad 100644 --- a/core/sched/advance.hip +++ b/core/sched/advance.hip @@ -5,7 +5,12 @@ */ #include +#include + #include "advance_impl.h" +#include "rad_abi.h" + +extern "C" int rad_dev_chain_enabled(void); /* core/device/device.h */ namespace { @@ -16,12 +21,56 @@ __global__ __launch_bounds__(kThreads) void rad_step_advance(rad::AdvanceArgs a) if (i < a.n_seq) rad::adv_row(a, i); } +/* The chained form (RadKernelChainFn, abi/rad_abi.h): the backend gives a kernel named r4dchain* + * a record at RAD_CHAIN_KARG_OFF and drops its barrier bit behind another chained kernel. Before + * the first read one lane waits for the queue's counter to reach the record's target; after the + * last write the block releases and adds 1. A record that does not check out means: run plain. */ +struct ChainRec { + unsigned long long magic, target; + unsigned long long* ctr; + unsigned long long check; +}; +__device__ __forceinline__ const ChainRec* chain_rec() { + const ChainRec* r = (const ChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() + + RAD_CHAIN_KARG_OFF); + const unsigned long long magic = r->magic, target = r->target, check = r->check; + if (magic != RAD_CHAIN_MAGIC || + check != (magic ^ target ^ (unsigned long long)(uintptr_t)r->ctr ^ RAD_CHAIN_CHECK)) + return nullptr; + return r; +} + +__global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceArgs a) { + const ChainRec* r = chain_rec(); + if (r) { + if (threadIdx.x == 0) + while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target) + __builtin_amdgcn_s_sleep(1); + __syncthreads(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + } + const int i = (int)(blockIdx.x * kThreads + threadIdx.x); + if (i < a.n_seq) rad::adv_row(a, i); + if (r) { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent"); + __syncthreads(); + if (threadIdx.x == 0) + __hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT); + } +} + } // namespace extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) { if (!args || args->n_seq <= 0) return 0; const unsigned blocks = (unsigned)((args->n_seq + kThreads - 1) / kThreads); - hipLaunchKernelGGL(rad_step_advance, dim3(blocks), dim3(kThreads), 0, (hipStream_t)stream, - *args); + /* The chained form only where launches chain (rad_dev_chain_enabled): there the backend writes + * its record; elsewhere a launch carries only these arguments, so the plain kernel runs. */ + if (!rad_dev_chain_enabled()) + hipLaunchKernelGGL(rad_step_advance, dim3(blocks), dim3(kThreads), 0, (hipStream_t)stream, + *args); + else + hipLaunchKernelGGL(r4dchain_step_advance, dim3(blocks), dim3(kThreads), 0, + (hipStream_t)stream, *args); return hipGetLastError() == hipSuccess ? 0 : -1; } diff --git a/docs/GUIDE.md b/docs/GUIDE.md index faa248ca..f20be2fb 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -3086,6 +3086,8 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp | `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) | | `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) | | `RADIANCE_AR_FENCE_FROM` | four-rank all-reduces of at least this many elements take a full fence before their flag (default 131072: prefill chunks, never decode or verify); cures a rare fresh-start divergence on the 31B at tp 4; `0` turns it off | +| `RADIANCE_PREFETCH` | `0` declares none of the weight reads the Gemma 4 31B and its DFlash2 drafter issue beside each all-reduce at decode and verify heights (libr4d `prefetch`: the next GEMM's leading weight bytes read into the on-die cache while the collective leaves the memory idle); on by default at more than one rank where the kernel library serves the op | +| `RADIANCE_CHAIN` | chained launches, where a dependent kernel waits for the one before it in its own prologue rather than behind the queue's barrier bit: on by default on the AQL backend where the model's plugin measured a gain with its speculative drafter (the Gemma 4 31B and 26B) and that drafter decodes speculatively (`auto`, the default); `0` turns them off, `1` on wherever the backend chains | | `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) | | `RADIANCE_GEMMA4_OVERLAP` | the Gemma 4 31B's prefill overlap (`arch/gemma4_bf16`, two or more ranks, fused junctions, the exact all-reduce wire): a prefill step of 1024 rows or more runs as two slices, each slice's all-reduces on a second stream beside the other's compute. On by default; `0` turns it off and runs every step whole (the startup notes say which) | | `RADIANCE_AR8_SHARD_WEIGHTS`, `RADIANCE_AR8_PIECES` | the eight-rank two-shot's shard weights (`auto`, the default, reads the PCIe links; `off`; or eight integers) and piece count, with `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` for the message size each starts at (§4.7) | diff --git a/docs/OPS.md b/docs/OPS.md index 5621f5cb..7e7a3d26 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -811,6 +811,32 @@ tiled rows over row tiles that outrank them: a WMMA shrink whose summation order and `R`, and an expand that stages `lora_b[s]` in LDS for a tile of rows and computes libref's bytes). +### `kv_len_trim` (device-only) + +| op | params | operands | +|---|---|---| +| `kv_len_trim` | `trim` `max_seqs` | `seqused`, `tail` → `out` | + +`out[s] = max(seqused[s] - trim, 0)` for each of the batch's sequences, `trim` the extent of +`tail`: the rows past the slice (their positions; the values are not read). A step's attention +over a slice of its rows that ends `trim` rows before the step does takes `out` as its `seqused`: +those rows then see exactly the keys they see in the whole step, and the positions the kernel +counts back from the context's end are theirs. `trim` is the op's ranged parameter, issued at the +count, but a launch sees every parameter collapsed to its band's upper bound, so the kernel takes +the count from `tail`, as a GEMM takes its M from its operands. + +### `prefetch` (device-only) + +| op | params | operands | +|---|---|---| +| `prefetch` | `bytes` | `w`w | + +Reads the first `bytes` of a weight's stored form and writes nothing, so a kernel that streams the +weight next finds those bytes in the on-die cache (64 MB on gfx1201). It is issued on the second +lane beside a collective that leaves the card's memory idle (`rad_lane`); on the same lane it would +only add its own time. Its layout hook answers RAD_LAYOUT_ANY (abi/rad_abi.h): it takes the bytes +as the weight's GEMM stored them and claims no form. It changes no value. + ## Attention | op | params | operands | diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 8efe1975..959bdcdc 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -161,6 +161,10 @@ set(R4D_UNITS "r4d_quant_act_i8|" "r4d_rmsnorm_quant_i8|" "r4d_qkv_norm_rope|" + # A batch's context lengths less a runtime trim (the 31B's per-slice prefill attention). + "r4d_kv_len_trim|" + # A weight read into the on-die cache beside a collective (the prefetch op). + "r4d_prefetch|" "r4d_gelu_mul_quant_i8|" "r4d_had_quant_act_i8|" "r4d_rmsnorm_had_quant_i8|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index c159bfd3..f1cbc8e6 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -79,6 +79,9 @@ struct R4DArgs { // rows of q_len * GQA: the 31B's DFlash drafter, gqa 8 at a block of 16, on the gqa-4 kernel. long q_ld; int kv_rep; + // The engine's chained launch (RadKernelChainFn, r4d_chain.h): the decode path launches its + // chained forms. fill_paged sets it from the resolved `chain` parameter. + int chain; }; // Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook @@ -428,7 +431,7 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, - long acq, long pub, long gate, long gate_ctr); + long acq, long pub, long gate, long gate_ctr, long chain); void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -799,7 +802,8 @@ int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long int sc_f32, long y, long q, long s, int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int rank, long stream, int nblocks, int drain, int acq, int pub, - long gate, long gate_ctr, long tail_ctr, int tail_nbt); + long gate, long gate_ctr, long tail_ctr, int tail_nbt, + int chain); // ---- sampling ---------------------------------------------------------------------------------- // diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index f0d6ef8a..cdd6f42f 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -675,6 +675,12 @@ static int nb_for(long words16, int max_nb) { * rows (2688 words, four blocks either way) the two rules agree (4x R9700, a four-card * microbenchmark of this kernel, 2026-10-17). The block count moves no byte: every word is folded * by one thread in ascending rank order whatever the grid. */ +/* The chained two-shot (r4d_chain.h) where the row resolved with `chain`, for a decode-sized + * message only (64 rows of an 8192-wide residual): DFlash2's verify-height reductions. */ +static long ar_chain(const RadArgs* a, long numel) { + return r4d_geti_or(a, "chain", 0) != 0 && numel <= 64L * 8192L ? 1L : 0L; +} + static int nb_for_shard(long shard16, int max_nb) { long nb = shard16 / 672; if (nb < 2) nb = 2; @@ -752,7 +758,7 @@ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - long gate, long gate_ctr, long dpitch, long spitch); + long gate, long gate_ctr, long dpitch, long spitch, long chain); extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -876,7 +882,8 @@ extern "C" int r4d_rad_ar_gather_4rank(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, c.pub, - early, early ? in->gate_ctr : 0L, (long)dpitch, (long)spitch)); + early, early ? in->gate_ctr : 0L, (long)dpitch, (long)spitch, + ar_chain(a, c.numel))); return early ? RAD_LINK_ENDED : RAD_OK; } @@ -1026,7 +1033,8 @@ extern "C" int r4d_rad_ar_oneshot_4rank_exact(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, nb, c.nthreads, c.drain, c.acq, - c.pub, early, early ? in->gate_ctr : 0L)); + c.pub, early, early ? in->gate_ctr : 0L, + ar_chain(a, c.numel))); return early ? RAD_LINK_ENDED : RAD_OK; } /* The wide release, the two-rank family's rule: over P2P the kernel ends the engine's hold @@ -1115,7 +1123,8 @@ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub, early, early ? in->gate_ctr : 0L)); + c.pub, early, early ? in->gate_ctr : 0L, + ar_chain(a, c.numel))); return early ? RAD_LINK_ENDED : RAD_OK; } @@ -1549,7 +1558,8 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)v.M, (int)v.K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (int)in->rank, (long)(uintptr_t)s, nblocks, - cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L, tail_ctr, tail_nbt); + cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L, tail_ctr, tail_nbt, + r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0); if (e != 0) return RAD_E_SHAPE; return early ? RAD_LINK_ENDED : RAD_OK; } diff --git a/libr4d/r4d_ar_gather_Nrank.hip b/libr4d/r4d_ar_gather_Nrank.hip index 5d27155e..8bde6dc8 100644 --- a/libr4d/r4d_ar_gather_Nrank.hip +++ b/libr4d/r4d_ar_gather_Nrank.hip @@ -20,6 +20,7 @@ // the peer arrays. #include "r4d.h" #include "r4d_ar_wide.h" +#include "r4d_chain.h" #include #include #include @@ -40,7 +41,7 @@ extern "C" void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - long gate, long gate_ctr, long dpitch, long spitch); + long gate, long gate_ctr, long dpitch, long spitch, long chain); extern "C" void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -70,8 +71,11 @@ __device__ __forceinline__ int r4d_g_src_ws(int k, int row16, int n16, int sp16) // Block b owns words [start,end) of the 16B-word space and drives its own handshake; no cross-block // sync, as in the all-reduce. +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. The chained form +// waits before the sequence take, so a block of the next launch on the instance never starts +// ahead of this one's; no block returns early. template -__global__ void r4d_ar_gather_wide_kernel( +__device__ __forceinline__ void r4d_ar_gather_wide_body( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, int4* __restrict__ out4, unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, @@ -156,6 +160,28 @@ __global__ void r4d_ar_gather_wide_kernel( } } } +template +__global__ void r4d_ar_gather_wide_kernel( + const int4* __restrict__ in4, R4DArWidePeers peers, + const int4* __restrict__ my_base, int4* __restrict__ out4, + unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, + int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq, + int pub, long long* gate, unsigned int* gate_ctr) { + r4d_ar_gather_wide_body(in4, peers, my_base, out4, my_flags, seq_ctrs, n16, slot_stride16, + rank, row16, dp16, sp16, drain, acq, pub, gate, gate_ctr); +} +template +__global__ void r4dchain_ar_gather_wide( + const int4* __restrict__ in4, R4DArWidePeers peers, + const int4* __restrict__ my_base, int4* __restrict__ out4, + unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, + int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq, + int pub, long long* gate, unsigned int* gate_ctr) { + r4d_chain_wait(); + r4d_ar_gather_wide_body(in4, peers, my_base, out4, my_flags, seq_ctrs, n16, slot_stride16, + rank, row16, dp16, sp16, drain, acq, pub, gate, gate_ctr); + r4d_chain_done(); +} // --- host side --- // `row_elems` is the row width in elements, 0 for plain concatenation. The entry point checks it @@ -165,7 +191,8 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream_i, long nblocks, long nthreads, long drain, long acq, - long pub, long gate, long gate_ctr, long dpitch, long spitch) { + long pub, long gate, long gate_ctr, long dpitch, long spitch, + bool chain = false) { constexpr int NPEERS = WS - 1; static_assert(NPEERS <= R4D_AR_WIDE_MAX_PEERS, "npeers exceeds the peer bundle bound"); @@ -236,7 +263,7 @@ static void ar_gather_wide_launch(const long* peer_scratch, const long* peer_fla } hipStream_t st = (hipStream_t)stream_i; - r4d_ar_gather_wide_kernel<<>>( + (chain ? r4dchain_ar_gather_wide : r4d_ar_gather_wide_kernel)<<>>( (const int4*)inp, peers, (const int4*)my_scratch, (int4*)out, (unsigned int*)my_flags, (unsigned int*)seq_ctrs, n16, (int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, (int)acq, (int)pub, (long long*)gate, (unsigned int*)gate_ctr); @@ -262,12 +289,12 @@ void r4d_ar_gather_4rank(long peer_scratch0, long peer_scratch1, long peer_scrat long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, long pub, long gate, - long gate_ctr, long dpitch, long spitch) { + long gate_ctr, long dpitch, long spitch, long chain) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_gather_wide_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, row_elems, stream, nblocks, nthreads, drain, acq, pub, - gate, gate_ctr, dpitch, spitch); + gate, gate_ctr, dpitch, spitch, chain != 0); } void r4d_ar_gather_8rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index 98b0e6f2..cdb2f249 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -30,6 +30,7 @@ #include "r4d.h" #include "r4d_ar_wide.h" #include "r4d_ar_shards.h" +#include "r4d_chain.h" #include #include @@ -40,13 +41,16 @@ struct R4DArShardOff { }; // PIECED false fixes pieces at 1, so the unpipelined launch keeps the straight-line kernel. -template -__global__ void r4d_ar_twoshot_wide_exact_kernel( +// CHAIN: the chained form's wait (before the sequence take, so a block of the next launch on the +// instance never starts ahead of this one's) and add (r4d_chain.h); no block returns early. +template +__device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff sh, int slot_stride16, int rank, int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr, int pieces_arg) { + if (CHAIN) r4d_chain_wait(); constexpr int NPEERS = WS - 1; const int pieces = PIECED ? pieces_arg : 1; const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; @@ -151,8 +155,27 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel( assemble(pieces - 1); #undef R4D_TS_OFF #undef R4D_TS_LEN + if (CHAIN) r4d_chain_done(); } +#define R4D_ARTS_PARAMS const int4* __restrict__ in4, R4DArWidePeers peers, \ + const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \ + int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff sh, \ + int slot_stride16, int rank, int drain, int acq, int pub, long long* gate, \ + unsigned int* gate_ctr, int pieces_arg +#define R4D_ARTS_ARGS in4, peers, my_base, my_flags, out4, seq_ctrs, sh, slot_stride16, rank, \ + drain, acq, pub, gate, gate_ctr, pieces_arg +template +__global__ void r4d_ar_twoshot_wide_exact_kernel(R4D_ARTS_PARAMS) { + r4d_ar_twoshot_wide_exact_body(R4D_ARTS_ARGS); +} +template +__global__ void r4dchain_ar_twoshot_wide_exact(R4D_ARTS_PARAMS) { + r4d_ar_twoshot_wide_exact_body(R4D_ARTS_ARGS); +} +#undef R4D_ARTS_ARGS +#undef R4D_ARTS_PARAMS + // --- host side --- template static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long my_scratch, @@ -160,7 +183,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long out, long n_elem, long dtype, long rank, long stream_i, long nblocks, long nthreads, long drain, long acq, long pub, long gate, long gate_ctr, const int* shard_weights, - long pieces) { + long pieces, bool chain = false) { constexpr int NPEERS = WS - 1; if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce: rank " + std::to_string(rank) + @@ -238,7 +261,8 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, hipStream_t st = (hipStream_t)stream_i; #define R4D_AR_TS_LAUNCH_P(T, LN, P) \ - r4d_ar_twoshot_wide_exact_kernel<<>>( \ + (chain ? r4dchain_ar_twoshot_wide_exact \ + : r4d_ar_twoshot_wide_exact_kernel)<<>>( \ (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ (int4*)out, (unsigned int*)seq_ctrs, sh, (int)slot_stride16, \ (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \ @@ -274,12 +298,12 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, - long acq, long pub, long gate, long gate_ctr) { + long acq, long pub, long gate, long gate_ctr, long chain) { const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr, - nullptr, 1L); + nullptr, 1L, chain != 0); } void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, diff --git a/libr4d/r4d_args.h b/libr4d/r4d_args.h index 1d024781..26118345 100644 --- a/libr4d/r4d_args.h +++ b/libr4d/r4d_args.h @@ -362,6 +362,8 @@ int r4d_cfg_ar_tail(const RadArgs*); /* The four-rank exact one-shot's size, in elements, from which it takes the exact two-shot instead * (0: never); the all-reduce rows' `ts_min` axis. */ long r4d_cfg_ar_ts_min(const RadArgs*); +/* The prefetch's workgroup count (the row's `nb` axis). */ +int r4d_cfg_prefetch_nb(const RadArgs*); void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*); void r4d_cfg_mv (const RadArgs*, struct R4dMvCfg*); /* rmsnorm_quant_i8's decode form: 1 the row's operands in registers before the reductions, 0 the diff --git a/libr4d/r4d_attn_args.h b/libr4d/r4d_attn_args.h index 7814715a..667abccc 100644 --- a/libr4d/r4d_attn_args.h +++ b/libr4d/r4d_attn_args.h @@ -154,6 +154,7 @@ static inline int fill_paged_row(const RadArgs* a, R4DArgs* r, int expect_head_d /* Set by the caller from the tuned `splits`; 0 means libr4d's own split law. */ r->splits = 0; + r->chain = r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0; return RAD_OK; } diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index 228fe7de..b8fddb0f 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -15,6 +15,7 @@ #include "r4d_common.h" #include "r4d_dt16.h" #include "r4d_q8.h" // the gate quantiser's 8-bit codes: E4M3, or int8 (GQ == 2) +#include "r4d_chain.h" #include #include @@ -80,10 +81,12 @@ __host__ __device__ __forceinline__ int r4d_attn_used(int ctx, int tile, int spl // WIN enables a sliding window (a.window positions ending at each row's causal limit). As a // template parameter defaulting to 0, full attention compiles with no window code. +// The body: its blocks return early (empty slots, tiles past the window), so the chained form +// (r4d_chain.h) wraps it below rather than bracketing it in place. template -__global__ __launch_bounds__(NWARPS * 32) -void r4d_attn_decode_kernel(const R4DArgs a, int splits) +__device__ __forceinline__ +void r4d_attn_decode_body(const R4DArgs& a, int splits) { constexpr int F16 = (OPT & O_F16) ? 1 : 0; constexpr int MSKIP = (OPT & O_MSKIP) ? 1 : 0; @@ -598,6 +601,24 @@ __device__ __forceinline__ uint16_t r4d_gq_gate(uint16_t gb, uint16_t xb) { } __device__ __forceinline__ float r4d_gq_clamp(float v) { return fminf(fmaxf(v, -448.0f), 448.0f); } +// The plain decode kernel, and the chained one (r4dchain*, r4d_chain.h) over the same body. +template +__global__ __launch_bounds__(NWARPS * 32) +void r4d_attn_decode_kernel(const R4DArgs a, int splits) +{ + r4d_attn_decode_body(a, splits); +} +template +__global__ __launch_bounds__(NWARPS * 32) +void r4dchain_attn_decode(const R4DArgs a, int splits) +{ + r4d_chain_wait(); + r4d_attn_decode_body(a, splits); + r4d_chain_done(); +} + // Vectorised merge, used by the h256 launcher whenever the split count fits a wave. Bit-identical // to splitkv_combine_body below; only the thread map differs. One wave owns one output row and // each lane HEAD_DIM/32 dims, so a segment is one 16-byte load per lane; a block carries JPB rows. @@ -767,6 +788,15 @@ void r4d_attn_splitkv_combine_vec_kernel(const R4DArgs a, int splits, int tile) splitkv_combine_vec_body(a, splits, tile, R4DGateQuant{}); } +template +__global__ __launch_bounds__(32 * JPB) +void r4dchain_attn_splitkv_combine_vec(const R4DArgs a, int splits, int tile) +{ + r4d_chain_wait(); + splitkv_combine_vec_body(a, splits, tile, + R4DGateQuant{}); + r4d_chain_done(); +} template __global__ __launch_bounds__(32 * JPB) void r4d_attn_splitkv_combine_vec_gq_kernel(const R4DArgs a, int splits, int tile, @@ -901,6 +931,14 @@ void r4d_attn_splitkv_combine_kernel(const R4DArgs a, int splits, int tile) { splitkv_combine_body(a, splits, tile, R4DGateQuant{}); } +template +__global__ __launch_bounds__(HEAD_DIM) +void r4dchain_attn_splitkv_combine(const R4DArgs a, int splits, int tile) +{ + r4d_chain_wait(); + splitkv_combine_body(a, splits, tile, R4DGateQuant{}); + r4d_chain_done(); +} template __global__ __launch_bounds__(HEAD_DIM) void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile, @@ -978,9 +1016,13 @@ static int r4d_decode_launch_win(const R4DArgs* a, hipStream_t s) { if (rows > 64) return -4; const int nw = (rows + 15) / 16; const int splits = r4d_decode_splits_win(a, TILE); -#define R4D_WIN_LAUNCH(NW) \ +#define R4D_WIN_LAUNCH(NW) do { if (a->chain) \ + hipLaunchKernelGGL((r4dchain_attn_decode), \ + dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits); \ + else \ hipLaunchKernelGGL((r4d_attn_decode_kernel), \ - dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits) + dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits); \ + } while (0) if (nw == 1) R4D_WIN_LAUNCH(1); else if (nw == 2) R4D_WIN_LAUNCH(2); else if (nw == 3) R4D_WIN_LAUNCH(3); @@ -990,9 +1032,15 @@ static int r4d_decode_launch_win(const R4DArgs* a, hipStream_t s) { if (e != hipSuccess) return -100 - (int)e; const int jobs3 = r4d_q_total(*a) * a->q_heads; - if (splits <= 64 && jobs3 >= VECMIN) + if (splits <= 64 && jobs3 >= VECMIN && a->chain) + hipLaunchKernelGGL((r4dchain_attn_splitkv_combine_vec), + dim3((jobs3 + JPB - 1) / JPB), dim3(32 * JPB), 0, s, *a, splits, TILE); + else if (splits <= 64 && jobs3 >= VECMIN) hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel), dim3((jobs3 + JPB - 1) / JPB), dim3(32 * JPB), 0, s, *a, splits, TILE); + else if (a->chain) + hipLaunchKernelGGL((r4dchain_attn_splitkv_combine), dim3(jobs3), + dim3(HEAD_DIM), splits * sizeof(float), s, *a, splits, TILE); else hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), dim3(HEAD_DIM), splits * sizeof(float), s, *a, splits, TILE); diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip index 1e66221d..7bca949b 100644 --- a/libr4d/r4d_attn_paged_window.hip +++ b/libr4d/r4d_attn_paged_window.hip @@ -42,6 +42,7 @@ #include "r4d_plugin.h" #include "r4d_launch.h" +#include "r4d_chain.h" #include "rad_plugin.h" #if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE) && __AMDGCN_WAVEFRONT_SIZE != 32 @@ -232,8 +233,10 @@ __device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int* } /* ------------------------------------------------------------------ the attention kernel */ +/* The body; attn_kernel and its chained form r4dchain_attn_window (r4d_chain.h) wrap it below, + * since its blocks return early. */ template -__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { +__device__ __forceinline__ void attn_body(AttnArgs A) { constexpr int R = Geo::R, BK = Geo::BK, RW = R / kWaves, BQ = R / GQA; constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */ constexpr int ESZ = KV8 ? 1 : 2; @@ -830,7 +833,7 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { * (kMaxSplit is 64), so the row max and denominator are one wave reduction each. Then one sweep * over the splits that saw a key, four at a time, each lane accumulating its 4 * NC dims. */ template -__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { +__device__ __forceinline__ void merge_body(AttnArgs A) { constexpr int R = Geo::R, NC = HD / 128; static_assert(kMaxSplit <= 64, "two splits a lane"); const int tile = (int)blockIdx.x, kh = (int)blockIdx.y; @@ -964,6 +967,25 @@ static constexpr int64_t scratch_need() { return part_bytes() + (int64_t)kTinfoMax * 2 * (int64_t)sizeof(int); } +/* The plain kernels and their chained forms (r4dchain*, RadKernelChainFn): the chained ones wait + * for the kernels before them on the queue in their prologue and count themselves in at the end. */ +template +__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { attn_body(A); } +template +__global__ __launch_bounds__(kThreads) void r4dchain_attn_window(AttnArgs A) { + r4d_chain_wait(); + attn_body(A); + r4d_chain_done(); +} +template +__global__ __launch_bounds__(kThreads) void merge_kernel(AttnArgs A) { merge_body(A); } +template +__global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) { + r4d_chain_wait(); + merge_body(A); + r4d_chain_done(); +} + template static int launch_attn(const RadArgs* a, RadStream stream) { constexpr int R = Geo::R, BK = Geo::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2; @@ -1134,11 +1156,23 @@ static int launch_attn(const RadArgs* a, RadStream stream) { A.n_split = (int)ns; hipStream_t s = (hipStream_t)stream; - R4D_KLAUNCH(R4D_KNAME(attn_kernel), dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), - dim3(kThreads), s, A); - if (ns > 1) - R4D_KLAUNCH(R4D_KNAME(merge_kernel), dim3((unsigned)nt, (unsigned)kvh), dim3(kThreads), - s, A); + /* The chained forms where the row resolved with `chain` (a chainable row, RADIANCE_CHAIN), at + * decode heights only: the 31B's full layers at a verify. */ + const bool chain = rad_args_geti_or(a, "chain", 0) != 0 && rows <= 64; + if (chain) + R4D_KLAUNCH(R4D_KNAME(r4dchain_attn_window), + dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A); + else + R4D_KLAUNCH(R4D_KNAME(attn_kernel), + dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A); + if (ns > 1) { + if (chain) + R4D_KLAUNCH(R4D_KNAME(r4dchain_merge_window), dim3((unsigned)nt, (unsigned)kvh), + dim3(kThreads), s, A); + else + R4D_KLAUNCH(R4D_KNAME(merge_kernel), dim3((unsigned)nt, (unsigned)kvh), + dim3(kThreads), s, A); + } return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } diff --git a/libr4d/r4d_chain.h b/libr4d/r4d_chain.h new file mode 100644 index 00000000..d5a3b7b9 --- /dev/null +++ b/libr4d/r4d_chain.h @@ -0,0 +1,85 @@ +// r4d_chain.h -- a chained launch's wait and completion (RadKernelChainFn, abi/rad_abi.h). +// +// Between two dependent kernels on one queue the packet processor waits for the first to finish +// before it launches the second (the AQL barrier bit): ~1.3 ms of a 14 ms DFlash2 step on the 31B +// (4x R9700, 2026-10-17). A chained launch drops the bit. The engine writes a record into the +// kernel's argument slot, and the kernel waits for its queue's completion counter to reach the +// blocks issued before it, then adds its own blocks as they finish. A kernel's chained form +// (`CHAIN` true) brackets its body with r4d_chain_wait / r4d_chain_done; the plain form never reads +// the record, so a launch from outside the engine (r4d_selftest, rad-kbench) is untouched. +// +// Every block must reach r4d_chain_done exactly once, so a kernel whose blocks return early keeps +// its body in a __device__ function called from the chained wrapper. +#pragma once +#include +#include "rad_abi.h" + +#if !defined(__HIP__) +/* The host SIMT emulator (tests/r4d_emu) compiles some of these sources as C++: no engine record + * ever reaches a launch there, so a chained form is its plain form. */ +__device__ __forceinline__ void r4d_chain_wait() {} +__device__ __forceinline__ void r4d_chain_done() {} +#else + +struct R4dChainRec { + unsigned long long magic, target; + unsigned long long* ctr; + unsigned long long check; +}; + +// The record, or null where it is not the engine's. Read from the argument segment (scalar loads) +// at both ends of the kernel, so nothing is held across the body: a register-heavy body (the +// split-KV decode attention) would otherwise pay for the pointer. +__device__ __forceinline__ const R4dChainRec* r4d_chain_rec() { + const R4dChainRec* r = (const R4dChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() + + RAD_CHAIN_KARG_OFF); + const unsigned long long magic = r->magic, target = r->target, check = r->check; + const unsigned long long* ctr = r->ctr; + if (magic != RAD_CHAIN_MAGIC || + check != (magic ^ target ^ (unsigned long long)(uintptr_t)ctr ^ RAD_CHAIN_CHECK)) + return nullptr; + return r; +} + +// Before the first read of an operand: one lane waits for the counter to reach the target. +// Every resident block polls the same word, so a wide kernel launched behind a long one (a GEMM +// behind a junction's all-reduce) would put hundreds of loads into one L2 channel every few dozen +// clocks for as long as the wait lasts, slowing whatever else that channel serves. The first +// R4D_CHAIN_FAST polls are ~64 clocks apart, the rest R4D_CHAIN_SLOW x 64: a long wait ends at most +// that much late and puts 1/R4D_CHAIN_SLOW of the load on the channel. +#ifndef R4D_CHAIN_FAST +#define R4D_CHAIN_FAST 8 +#endif +#ifndef R4D_CHAIN_SLOW +#define R4D_CHAIN_SLOW 16 +#endif +__device__ __forceinline__ void r4d_chain_wait() { + const R4dChainRec* r = r4d_chain_rec(); + if (!r) return; + if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) { + const unsigned long long target = r->target; + unsigned long long* ctr = r->ctr; + int n = 0; + while (__hip_atomic_load(ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < target) { + if (n < R4D_CHAIN_FAST) { + __builtin_amdgcn_s_sleep(1); + ++n; + } else { + __builtin_amdgcn_s_sleep(R4D_CHAIN_SLOW); + } + } + } + __syncthreads(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); +} + +// After the block's last write: release, then one add a block. +__device__ __forceinline__ void r4d_chain_done() { + const R4dChainRec* r = r4d_chain_rec(); + if (!r) return; + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent"); + __syncthreads(); + if (threadIdx.x == 0 && threadIdx.y == 0 && threadIdx.z == 0) + __hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT); +} +#endif /* __HIP__ */ diff --git a/libr4d/r4d_dflash_conv_t2_g16_bf16.hip b/libr4d/r4d_dflash_conv_t2_g16_bf16.hip index 489efba0..60d874f9 100644 --- a/libr4d/r4d_dflash_conv_t2_g16_bf16.hip +++ b/libr4d/r4d_dflash_conv_t2_g16_bf16.hip @@ -4,6 +4,7 @@ #include #include "r4d_gdn_args.h" #include "r4d_dflash_conv_body.h" +#include "r4d_chain.h" #define DFC_THREADS 128 #define DFC_VEC 8 // bf16 lanes per thread: one dwordx4 in and one out @@ -19,15 +20,40 @@ __global__ __launch_bounds__(DFC_THREADS) void r4d_dflash_conv_kernel( blockmask, blockIdx.y, hv); } +// The chained form (r4d_chain.h): the body returns for lanes past the row, the block still adds. +template +__global__ __launch_bounds__(DFC_THREADS) void r4dchain_dflash_conv( + const r4d_u16* __restrict__ x, const r4d_u16* __restrict__ delta, + const r4d_u16* __restrict__ base, r4d_u16* __restrict__ out, + int H, int dpitch, int NG, int vpr, int blockmask) +{ + r4d_chain_wait(); + const int hv = blockIdx.x * DFC_THREADS + threadIdx.x; + r4d_dflash_conv_body(x, delta, base, out, H, dpitch, NG, vpr, + blockmask, blockIdx.y, hv); + r4d_chain_done(); +} + // x [T, H] bf16, row pitch H // delta [T, taps, NG] bf16, row pitch dpitch: a slice of the [T, 2, taps, NG] kernel projection, // so dpitch is 2*taps*NG. The packed pitch (taps*NG) would silently read the // other half's coefficients. // base [taps, H] bf16, contiguous // out [T, H] bf16. Must not alias x: tap 1 of row t reads input row t-1. +static int dflash_conv_launch(const void* x, const void* delta, const void* base, void* out, + int T, int H, int dpitch, int NG, int taps, int group, + int block_size, void* stream, bool chain); extern "C" int r4d_dflash_conv_t2_g16_bf16( const void* x, const void* delta, const void* base, void* out, int T, int H, int dpitch, int NG, int taps, int group, int block_size, void* stream) +{ + return dflash_conv_launch(x, delta, base, out, T, H, dpitch, NG, taps, group, block_size, + stream, false); +} +/* `chain`: the chained form at decode heights (r4d_rad_dflash_conv passes the row's parameter). */ +static int dflash_conv_launch(const void* x, const void* delta, const void* base, void* out, + int T, int H, int dpitch, int NG, int taps, int group, + int block_size, void* stream, bool chain) { if (taps != 2 || group != 16) return -1; if (H % (group * DFC_VEC) || NG != H / group) return -1; @@ -36,7 +62,9 @@ extern "C" int r4d_dflash_conv_t2_g16_bf16( const int vpr = H / DFC_VEC; dim3 grid((vpr + DFC_THREADS - 1) / DFC_THREADS, T), blk(DFC_THREADS); - hipLaunchKernelGGL((r4d_dflash_conv_kernel<2, 16>), grid, blk, 0, (hipStream_t)stream, + hipLaunchKernelGGL((chain && T <= 64 ? r4dchain_dflash_conv<2, 16> + : r4d_dflash_conv_kernel<2, 16>), + grid, blk, 0, (hipStream_t)stream, (const r4d_u16*)x, (const r4d_u16*)delta, (const r4d_u16*)base, (r4d_u16*)out, H, dpitch, NG, vpr, block_size - 1); return (int)hipGetLastError(); @@ -79,7 +107,8 @@ extern "C" int r4d_rad_dflash_conv(const RadArgs* a, RadStream s) { if (bsz & (bsz - 1)) return R4D_NO(RAD_E_INVAL); if (dpitch != 2LL * taps * NG) return R4D_NO(RAD_E_STRIDE); - return R4D_RAW(r4d_dflash_conv_t2_g16_bf16(x->data, d->data, bs->data, o->data, (int)T, - (int)H, (int)dpitch, NG, taps, group, bsz, s)); + return R4D_RAW(dflash_conv_launch(x->data, d->data, bs->data, o->data, (int)T, + (int)H, (int)dpitch, NG, taps, group, bsz, s, + r4d_geti_or(a, "chain", 0) != 0)); } diff --git a/libr4d/r4d_dflash_select_bf16.hip b/libr4d/r4d_dflash_select_bf16.hip index e0f0069f..b1e2566a 100644 --- a/libr4d/r4d_dflash_select_bf16.hip +++ b/libr4d/r4d_dflash_select_bf16.hip @@ -29,6 +29,7 @@ #include "r4d_gdn_args.h" #include "r4d_dflash_conv_body.h" // r4d_bf2f, r4d_u16 #include "r4d_common.h" // r4d_wave_sum +#include "r4d_chain.h" #define DSL_THREADS 256 #define DSL_WAVE 32 @@ -47,7 +48,8 @@ // Ids outside [0, V) do occur (row_topk_merge reports an unfilled slot as -1, and step 0's // predecessor is whatever the anchor plane holds). As in ref_dflash_select, an out-of-range // predecessor contributes nothing and an out-of-range candidate scores its unary term alone. -__global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. +__device__ __forceinline__ void r4d_dflash_select_body( const int* __restrict__ cand, const float* __restrict__ unary, const r4d_u16* __restrict__ hp, const int* __restrict__ anchor, const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ, @@ -134,12 +136,49 @@ __global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( __syncthreads(); } } +__global__ __launch_bounds__(DSL_THREADS) void r4d_dflash_select_kernel( + const int* __restrict__ cand, const float* __restrict__ unary, + const r4d_u16* __restrict__ hp, const int* __restrict__ anchor, + const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ, + int* __restrict__ out, int steps, int K, int R, int V, + int cand_ld, int hp_ld, int out_ld, int anchor_stride) { + r4d_dflash_select_body(cand, unary, hp, anchor, pred, succ, out, steps, K, R, V, cand_ld, hp_ld, + out_ld, anchor_stride); +} +__global__ __launch_bounds__(DSL_THREADS) void r4dchain_dflash_select( + const int* __restrict__ cand, const float* __restrict__ unary, + const r4d_u16* __restrict__ hp, const int* __restrict__ anchor, + const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ, + int* __restrict__ out, int steps, int K, int R, int V, + int cand_ld, int hp_ld, int out_ld, int anchor_stride) { + r4d_chain_wait(); + r4d_dflash_select_body(cand, unary, hp, anchor, pred, succ, out, steps, K, R, V, cand_ld, hp_ld, + out_ld, anchor_stride); + r4d_chain_done(); +} + +/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */ +static int dflash_select_emit( + const void* cand, const void* unary, const void* hp, const void* anchor, + const void* pred, const void* succ, void* out, + int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld, + int anchor_stride, void* stream, bool chain); extern "C" int r4d_dflash_select_bf16( const void* cand, const void* unary, const void* hp, const void* anchor, const void* pred, const void* succ, void* out, int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld, int anchor_stride, void* stream) +{ + return dflash_select_emit(cand, unary, hp, anchor, pred, succ, out, M, steps, K, R, V, cand_ld, + hp_ld, out_ld, anchor_stride, stream, false); +} + +static int dflash_select_emit( + const void* cand, const void* unary, const void* hp, const void* anchor, + const void* pred, const void* succ, void* out, + int M, int steps, int K, int R, int V, int cand_ld, int hp_ld, int out_ld, + int anchor_stride, void* stream, bool chain) { if (M <= 0 || steps <= 0) return 0; if (K < 1 || K > DSL_MAX_K) return -1; @@ -149,7 +188,8 @@ extern "C" int r4d_dflash_select_bf16( /* hp may be null (the bigram form); then hp_ld is unused. */ if (hp && hp_ld < R) return -1; - hipLaunchKernelGGL(r4d_dflash_select_kernel, dim3(M), dim3(DSL_THREADS), 0, (hipStream_t)stream, + hipLaunchKernelGGL((chain ? r4dchain_dflash_select : r4d_dflash_select_kernel), dim3(M), + dim3(DSL_THREADS), 0, (hipStream_t)stream, (const int*)cand, (const float*)unary, (const r4d_u16*)hp, (const int*)anchor, (const r4d_u16*)pred, (const r4d_u16*)succ, (int*)out, steps, K, R, V, cand_ld, hp_ld, out_ld, anchor_stride); @@ -222,8 +262,10 @@ extern "C" int r4d_rad_dflash_select(const RadArgs* a, RadStream s) { if (astr < 1 || !r4d_contig(anc)) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(anc) < (M - 1) * astr + 1) return R4D_NO(RAD_E_SHAPE); - return R4D_RAW(r4d_dflash_select_bf16(cand->data, un->data, has_hp ? hp->data : nullptr, - anc->data, pr->data, sc->data, - out->data, (int)M, (int)steps, (int)K, (int)R, (int)V, - (int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s)); + /* The chained form at decode heights, where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; + return R4D_RAW(dflash_select_emit(cand->data, un->data, has_hp ? hp->data : nullptr, + anc->data, pr->data, sc->data, + out->data, (int)M, (int)steps, (int)K, (int)R, (int)V, + (int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr, s, ch)); } diff --git a/libr4d/r4d_gelu_mul_quant_i8.hip b/libr4d/r4d_gelu_mul_quant_i8.hip index 6da55173..cba89d44 100644 --- a/libr4d/r4d_gelu_mul_quant_i8.hip +++ b/libr4d/r4d_gelu_mul_quant_i8.hip @@ -9,14 +9,18 @@ #include "r4d_args.h" #include "r4d_emit.h" #include "r4d_common.h" +#include "r4d_chain.h" #include namespace { -template -__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel( +// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); every block runs +// to the end. The plain kernel and the chained one (r4dchain*) follow. +template +__device__ __forceinline__ void gelu_mul_quant_i8_body( const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { + if (CHAIN) r4d_chain_wait(); extern __shared__ uint16_t ybuf[]; __shared__ float lm[THR / 32]; const uint32_t row = blockIdx.x; @@ -49,6 +53,20 @@ __global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel( const int t = __float2int_rn(bf16_to_f32(ybuf[src]) * inv); qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); } + if (CHAIN) r4d_chain_done(); +} + +template +__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel( + const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S, + uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { + gelu_mul_quant_i8_body(gu, q, S, yo, n, gu_ld, y_ld); +} +template +__global__ __launch_bounds__(THR) void r4dchain_gelu_mul_quant_i8( + const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S, + uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { + gelu_mul_quant_i8_body(gu, q, S, yo, n, gu_ld, y_ld); } } // namespace @@ -79,13 +97,17 @@ extern "C" int r4d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream stream) { const size_t lds = (size_t)n * sizeof(uint16_t); if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE); const int thr = r4d_act_threads((int)M, (int)n); -#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(stream, (gelu_mul_quant_i8_kernel), dim3((uint32_t)M), dim3(T), lds, \ + const bool chain = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */ +#define R4D_GMQ_C(T, C) R4D_EMIT(stream, (C ? r4dchain_gelu_mul_quant_i8 : gelu_mul_quant_i8_kernel), \ + dim3((uint32_t)M), dim3(T), lds, \ (const uint16_t*)r4d_p(gu), (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), \ (uint32_t)n, (uint32_t)gp, (uint32_t)yp) +#define R4D_GMQ_T(T) emit_rc = chain ? R4D_GMQ_C(T, true) : R4D_GMQ_C(T, false) if (thr == 1024) R4D_GMQ_T(1024); else if (thr == 512) R4D_GMQ_T(512); else if (thr == 256) R4D_GMQ_T(256); else return R4D_NO(RAD_E_INVAL); #undef R4D_GMQ_T +#undef R4D_GMQ_C return emit_rc; } diff --git a/libr4d/r4d_gemm_bf16_nt_m64.hip b/libr4d/r4d_gemm_bf16_nt_m64.hip index e383d27d..21ce9470 100644 --- a/libr4d/r4d_gemm_bf16_nt_m64.hip +++ b/libr4d/r4d_gemm_bf16_nt_m64.hip @@ -19,6 +19,7 @@ #include "r4d.h" #include "r4d_gemm_args.h" #include "r4d_gdn_wmma.h" +#include "r4d_chain.h" #include #include #include @@ -48,10 +49,13 @@ __device__ __forceinline__ v8bf fragU(r4d_gu2 p, int u) { // More amortises each weight fragment, fewer puts more blocks on the machine, so MT is tunable. // KU is the k-step unroll; see the loop. constexpr int KU = 8; -template -__global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel( +// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); no block returns +// early. r4d_gemm_bf16_nt_m64_kernel and r4dchain_gemm_bf16_nt_m64 below wrap it. +template +__device__ __forceinline__ void r4d_gemm_bf16_nt_m64_body( const unsigned short* __restrict__ A, const unsigned short* __restrict__ W, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { + if (CHAIN) r4d_chain_wait(); extern __shared__ float red[]; // WV*SK*256 floats: one 16x16 tile per (column, split) const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32; const int col_local = wave / SK, ksplit = wave % SK; @@ -124,12 +128,33 @@ __global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel( if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)v; } } + if (CHAIN) r4d_chain_done(); +} + +template +__global__ __launch_bounds__(1024) void r4d_gemm_bf16_nt_m64_kernel( + const unsigned short* __restrict__ A, const unsigned short* __restrict__ W, + __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { + r4d_gemm_bf16_nt_m64_body(A, W, C, M, K, N, WV, SK); +} +template +__global__ __launch_bounds__(1024) void r4dchain_gemm_bf16_nt_m64( + const unsigned short* __restrict__ A, const unsigned short* __restrict__ W, + __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { + r4d_gemm_bf16_nt_m64_body(A, W, C, M, K, N, WV, SK); } // grid = ceil(ceil(N/16)/WV) x ceil(ceil(M/16)/MB) blocks; block = WV*SK waves. MT = MB is // compile-time so the accumulators are sized exactly. +static void gemm_bf16_m64_launch(long a, long w, long c, int M, int K, int N, int WV, int SK, + int MB, long stream, bool chain); void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, int SK, int MB, long stream) { + gemm_bf16_m64_launch(a, w, c, M, K, N, WV, SK, MB, stream, false); +} +/* `chain`: the chained form (r4d_rad_gemm_bf16_m64 passes the row's parameter; M <= 64 always). */ +static void gemm_bf16_m64_launch(long a, long w, long c, int M, int K, int N, int WV, int SK, + int MB, long stream, bool chain) { if (M < 1 || M > R4D_GEMM64_MAX_M) throw std::runtime_error("r4d gemm_bf16_nt_m64: M out of range"); if (K % (SK * 16)) throw std::runtime_error("r4d gemm_bf16_nt_m64: K must be divisible by SK*16"); if (WV * SK * WAVE32 > 1024) throw std::runtime_error("r4d gemm_bf16_nt_m64: threads/block > 1024"); @@ -140,8 +165,9 @@ void r4d_gemm_bf16_nt_m64(long a, long w, long c, int M, int K, int N, int WV, i auto Ap = (const unsigned short*)a; auto Wp = (const unsigned short*)w; auto Cp = (__hip_bfloat16*)c; hipStream_t st = (hipStream_t)stream; -#define LAUNCH(MT) hipLaunchKernelGGL(r4d_gemm_bf16_nt_m64_kernel, grid, block, smem, st, \ - Ap, Wp, Cp, M, K, N, WV, SK) +#define LAUNCH(MT) hipLaunchKernelGGL((chain ? r4dchain_gemm_bf16_nt_m64 \ + : r4d_gemm_bf16_nt_m64_kernel), \ + grid, block, smem, st, Ap, Wp, Cp, M, K, N, WV, SK) switch (MB) { case 1: LAUNCH(1); break; case 2: LAUNCH(2); break; @@ -166,9 +192,9 @@ extern "C" int r4d_rad_gemm_bf16_m64(const RadArgs* a, RadStream s) { rc = cfg_for(a, g.K, g.M, 16, BR_FLAT, &c, (g.N + 15) / 16); /* "K divisible by SK*16" */ if (rc != RAD_OK) return rc; R4D_TRY("gemm_bf16_nt_m64", - r4d_gemm_bf16_nt_m64(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.y), + gemm_bf16_m64_launch(r4d_addr(g.a), r4d_addr(g.b), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, - (long)(uintptr_t)s)); + (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0)); return RAD_OK; } diff --git a/libr4d/r4d_gemm_fp8a16_nt_m1.hip b/libr4d/r4d_gemm_fp8a16_nt_m1.hip index c7a7ef27..47c09142 100644 --- a/libr4d/r4d_gemm_fp8a16_nt_m1.hip +++ b/libr4d/r4d_gemm_fp8a16_nt_m1.hip @@ -30,6 +30,7 @@ #include "r4d_args.h" #include "r4d_fp8_lm.h" #include "r4d_fp8_wmma.h" +#include "r4d_chain.h" #include @@ -479,8 +480,9 @@ constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) { return fkb == 2u ? 6u : mt >= 4u ? 6u : mt == 3u ? 7u : mt == 2u ? 9u : 12u; } -template -__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel( +// The body; lm_wmma_kernel and its chained form (RadKernelChainFn) wrap it. +template +__device__ __forceinline__ void lm_wmma_body( const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, uint32_t a_ld, float* __restrict__ C, uint32_t c_ld, uint32_t rows, uint32_t cols, uint32_t w_ld, uint32_t m_real) { @@ -597,6 +599,23 @@ __global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm } } } + +#define R4D_LMW_PARAMS const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, \ + uint32_t a_ld, float* __restrict__ C, uint32_t c_ld, uint32_t rows, uint32_t cols, \ + uint32_t w_ld, uint32_t m_real +template +__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel( + R4D_LMW_PARAMS) { + lm_wmma_body(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real); +} +template +__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void r4dchain_lm_wmma( + R4D_LMW_PARAMS) { + r4d_chain_wait(); + lm_wmma_body(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real); + r4d_chain_done(); +} +#undef R4D_LMW_PARAMS } // namespace extern "C" int r4d_gemm_fp8a16_nt_m1_block(void) { return (int)kBlock; } @@ -677,7 +696,7 @@ extern "C" int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c, // core/build/rad_builder.cpp refuses such a split at declare time. template static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld, - int w_ld, long stream); + int w_ld, long stream, bool chain = false); extern "C" int r4d_logits_gemm_fp8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld, int w_ld, long stream) { @@ -691,9 +710,11 @@ extern "C" int r4d_logits_gemm_i8(long a, long wq, long c, int M, int K, int N, return logits_gemm_8(a, wq, c, M, K, N, a_ld, c_ld, w_ld, stream); } +/* `chain`: the WMMA pass's chained form (the plugin entry, where the row resolved with `chain`); + * the matvec below three rows stays plain. */ template static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld, - int w_ld, long stream) { + int w_ld, long stream, bool chain) { if (!a || !wq || !c) return -1; if (M <= 0 || K <= 0 || N <= 0) return -2; if (K % (int)kBlock) return -4; @@ -722,7 +743,8 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, const uint16_t* ac = (const uint16_t*)a + (size_t)m0 * a_ld; float* cc = (float*)c + (size_t)m0 * c_ld; #define R4D_LMW2(MTV, FKV) \ - hipLaunchKernelGGL((lm_wmma_kernel), dim3(blocks), dim3(kDenseThreads), 0, \ + hipLaunchKernelGGL((chain ? r4dchain_lm_wmma : lm_wmma_kernel), \ + dim3(blocks), dim3(kDenseThreads), 0, \ (hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc, \ (uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc) #define R4D_LMW(MTV) do { if (fkb == 2u) R4D_LMW2(MTV, 2); else R4D_LMW2(MTV, 1); } while (0) @@ -836,9 +858,11 @@ static int rad_logits_gemm_8(const RadArgs* a, RadStream s, bool i8) { if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16)) return R4D_NO(RAD_E_ALIGN); - return (i8 ? r4d_logits_gemm_i8 : r4d_logits_gemm_fp8)( + /* The chained form at decode heights, where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; + return (i8 ? logits_gemm_8 : logits_gemm_8)( r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n_embd, (int)n_vocab, - (int)x_ld, (int)y_ld, (int)stride, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + (int)x_ld, (int)y_ld, (int)stride, (long)(uintptr_t)s, ch) == 0 ? RAD_OK : RAD_E_DEVICE; } extern "C" int r4d_rad_logits_gemm_fp8(const RadArgs* a, RadStream s) { diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index e0faee96..763a95e5 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -28,6 +28,7 @@ #include "r4d.h" #include "r4d_fp8_args.h" #include "r4d_emit.h" +#include "r4d_chain.h" #include "r4d_fp8_wmma.h" #include @@ -176,10 +177,12 @@ constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bo // // The narrow tile: MW waves a block, a wave one 16-row weight tile (A, fragments straight from the // plane into registers) against NT 16-token tiles (B, staged through LDS). +/* The body. gemm_fp8a8_kernel and its chained form r4dchain_gemm_fp8a8 (r4d_chain.h) wrap it + * after it: its blocks return early (an empty K slice, the finisher's losers), and every block of + * a chained launch must still count itself in. */ template -__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8)) -void gemm_fp8a8_kernel( +__device__ __forceinline__ void gemm_fp8a8_body( const uint8_t* __restrict__ Ap, const void* __restrict__ Sa, const uint8_t* __restrict__ Bp, const void* __restrict__ Sb, void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr, @@ -591,6 +594,42 @@ void gemm_fp8a8_kernel( } } +#define R4D_F8K_ARGS Ap, Sa, Bp, Sb, Y, C, Ctr, rows, cols, nb, a_ld, b_ld, sa_ld, sb_ld, ck, Q, \ + Sc, Yb, q_ld, s_ld, y_ld, Bias, c_ld +template +__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8)) +void gemm_fp8a8_kernel( + const uint8_t* __restrict__ Ap, const void* __restrict__ Sa, + const uint8_t* __restrict__ Bp, const void* __restrict__ Sb, + void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr, + uint32_t rows, uint32_t cols, uint32_t nb, + uint32_t a_ld, uint32_t b_ld, uint32_t sa_ld, uint32_t sb_ld, uint32_t ck, + uint8_t* __restrict__ Q = nullptr, float* __restrict__ Sc = nullptr, + uint16_t* __restrict__ Yb = nullptr, + uint32_t q_ld = 0, uint32_t s_ld = 0, uint32_t y_ld = 0, + const uint16_t* __restrict__ Bias = nullptr, uint32_t c_ld = 0) { + gemm_fp8a8_body(R4D_F8K_ARGS); +} +template +__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8)) +void r4dchain_gemm_fp8a8( + const uint8_t* __restrict__ Ap, const void* __restrict__ Sa, + const uint8_t* __restrict__ Bp, const void* __restrict__ Sb, + void* __restrict__ Y, void* __restrict__ C, unsigned int* __restrict__ Ctr, + uint32_t rows, uint32_t cols, uint32_t nb, + uint32_t a_ld, uint32_t b_ld, uint32_t sa_ld, uint32_t sb_ld, uint32_t ck, + uint8_t* __restrict__ Q = nullptr, float* __restrict__ Sc = nullptr, + uint16_t* __restrict__ Yb = nullptr, + uint32_t q_ld = 0, uint32_t s_ld = 0, uint32_t y_ld = 0, + const uint16_t* __restrict__ Bias = nullptr, uint32_t c_ld = 0) { + r4d_chain_wait(); + gemm_fp8a8_body(R4D_F8K_ARGS); + r4d_chain_done(); +} +#undef R4D_F8K_ARGS + // Sum the split-K partials into bf16 C, in fixed z order with no atomics. Latency bound, so eight // loads are issued before their adds; the order of the adds is unchanged. __global__ void splitk_reduce_kernel(const float* __restrict__ ws, uint16_t* __restrict__ y, @@ -931,7 +970,7 @@ extern "C" int r4d_gemm_fp8a8_block(void) { return (int)kBlock; } static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, RadStream stream, - bool i8 = false, int split_n = 0); + bool i8 = false, int split_n = 0, bool chain = false); extern "C" int r4d_gemm_fp8a8_nt_m16(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, @@ -990,7 +1029,7 @@ extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) { static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, RadStream stream, bool i8, - int split_n) { + int split_n, bool chain) { int emit_rc = RAD_OK; if (!a || !ascale || !wq || !ws || !c) return -1; if (M <= 0 || K <= 0 || N <= 0) return -2; @@ -1034,7 +1073,9 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, (ksplit > 1 && gx <= kMaxCtr) ? split_ctr(stream, (const void*)c) : nullptr; #define R4D_F8D(f, mw_, nt_, fk_, i8_) \ - emit_rc = R4D_EMIT(stream, (gemm_fp8a8_kernel), \ + emit_rc = R4D_EMIT(stream, \ + (chain ? r4dchain_gemm_fp8a8 \ + : gemm_fp8a8_kernel), \ grid, dim3(mw_ * kWave), \ 0, (const uint8_t*)wq, (const void*)ws, \ (const uint8_t*)a, (const void*)ascale, dst, (void*)c, ctr, \ @@ -1157,11 +1198,23 @@ extern "C" int r4d_gemm_fp8a8_bias_nt_m16(long a, long ascale, long wq, long ws, // The weight is the gate_up plane [2*nout][K], gate first, as the unfused GEMM reads it. extern "C" int r4d_gemm_fp8a8_gated_nt_m16_max_m(void) { return 64; } +static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s, + long y, int act, int M, int K, int nout, int a_ld, int sa_ld, + int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream, + bool chain); extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws, long q, long s, long y, int act, int M, int K, int nout, int a_ld, int sa_ld, int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream) { + return gemm_fp8a8_gated_launch(a, ascale, wq, ws, q, s, y, act, M, K, nout, a_ld, sa_ld, + w_ld, sw_ld, q_ld, s_ld, y_ld, stream, false); +} +/* `chain`: the chained form (r4d_rad_gemm_fp8a8_gated_m16 passes the row's parameter). */ +static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s, + long y, int act, int M, int K, int nout, int a_ld, int sa_ld, + int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream, + bool chain) { if (!a || !ascale || !wq || !ws || !q || !s) return -1; if (M <= 0 || K <= 0 || nout <= 0) return -2; if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return -3; @@ -1194,14 +1247,18 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws const dim3 grid((uint32_t)(nout / 128), 1, 1); #define R4D_F8G_NT(f, nt_) \ - hipLaunchKernelGGL((gemm_fp8a8_kernel), grid, \ + hipLaunchKernelGGL((chain ? r4dchain_gemm_fp8a8 \ + : gemm_fp8a8_kernel), grid, \ dim3(kGmw * kWave), \ 0, (hipStream_t)stream, (const uint8_t*)wq, (const void*)ws, \ (const uint8_t*)a, (const void*)ascale, nullptr, nullptr, nullptr, \ (uint32_t)N, (uint32_t)K, \ (uint32_t)M, (uint32_t)w_ld, (uint32_t)a_ld, (uint32_t)sw_ld, \ (uint32_t)sa_ld, 0u, (uint8_t*)q, (float*)s, (uint16_t*)y, \ - (uint32_t)q_ld, (uint32_t)s_ld, (uint32_t)y_ld) + (uint32_t)q_ld, (uint32_t)s_ld, (uint32_t)y_ld, \ + /* the bias's two, spelled out: a kernel chosen through a pointer takes \ + * no default arguments */ \ + (const uint16_t*)nullptr, 0u) #define R4D_F8G(f) \ do { if (nt == 4u) R4D_F8G_NT(f, 4u); \ else if (nt == 3u) R4D_F8G_NT(f, 3u); \ @@ -1289,7 +1346,7 @@ extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) { r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, false, - (int)r4d_geti_or(a, "split_n", 0)); + (int)r4d_geti_or(a, "split_n", 0), r4d_geti_or(a, "chain", 0) != 0); return e == 0 ? RAD_OK : RAD_E_SHAPE; } @@ -1380,11 +1437,11 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) { const char* act = r4d_gets(a, "act"); if (!act || std::strcmp(act, "silu")) return R4D_NO(RAD_E_UNSUPPORTED); - const int e = r4d_gemm_fp8a8_gated_nt_m16( + const int e = gemm_fp8a8_gated_launch( r4d_addr(x), r4d_addr(xs), r4d_addr(w), r4d_addr(wsc), r4d_addr(q), r4d_addr(sc), y ? r4d_addr(y) : 0, 0, (int)M, (int)K, (int)nout, (int)ap, (int)asp, (int)wp, (int)wsp, - (int)qp, (int)sp, (int)yp, (long)(uintptr_t)s); + (int)qp, (int)sp, (int)yp, (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0); return e == 0 ? RAD_OK : RAD_E_SHAPE; } @@ -1404,7 +1461,7 @@ extern "C" int r4d_rad_gemm_i8a8_m16(const RadArgs* a, RadStream stream) { r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, true, - (int)r4d_geti_or(a, "split_n", 0)); + (int)r4d_geti_or(a, "split_n", 0), r4d_geti_or(a, "chain", 0) != 0); return e == 0 ? RAD_OK : RAD_E_SHAPE; } diff --git a/libr4d/r4d_gemm_w4a8_nt_m64.hip b/libr4d/r4d_gemm_w4a8_nt_m64.hip index 1a7efe1c..da1bc0e5 100644 --- a/libr4d/r4d_gemm_w4a8_nt_m64.hip +++ b/libr4d/r4d_gemm_w4a8_nt_m64.hip @@ -42,6 +42,7 @@ #include "r4d_gemm_args.h" #include "r4d_common.h" #include "r4d_gdn_wmma.h" +#include "r4d_chain.h" #include #include #include @@ -95,12 +96,15 @@ __device__ __forceinline__ v8i mmai(v2i a, v2i b, v8i c) { // limit, so the host checks WV*SK against the same expression. #define R4D_W4A8_BOUNDS(NPW) ((NPW) >= 8 ? 256 : ((NPW) >= 4 ? 512 : 1024)) -template -__global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_kernel( +// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); every block runs +// to the end. The two kernels below are the plain form and the chained one (r4dchain*). +template +__device__ __forceinline__ void r4d_gemm_w4a8_nt_m64_body( const signed char* __restrict__ A, const float* __restrict__ Ascale, const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { + if (CHAIN) r4d_chain_wait(); extern __shared__ float red[]; const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32; const int col_local = wave / SK, ksplit = wave % SK; @@ -252,11 +256,25 @@ __global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_ker if (n < N && m < M) C[(size_t)m * N + n] = (__hip_bfloat16)(v * Ascale[m] * 0.0625f); } } + if (CHAIN) r4d_chain_done(); } +#define R4D_W4A8_PARAMS const signed char* __restrict__ A, const float* __restrict__ Ascale, \ + const unsigned* __restrict__ Wq, const unsigned* __restrict__ Ws, \ + const float* __restrict__ Asum, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK +template +__global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4d_gemm_w4a8_nt_m64_kernel(R4D_W4A8_PARAMS) { + r4d_gemm_w4a8_nt_m64_body(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK); +} +template +__global__ __launch_bounds__(R4D_W4A8_BOUNDS(NPW)) void r4dchain_gemm_w4a8_nt_m64(R4D_W4A8_PARAMS) { + r4d_gemm_w4a8_nt_m64_body(A, Ascale, Wq, Ws, Asum, C, M, K, N, WV, SK); +} +#undef R4D_W4A8_PARAMS + static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, - bool asym, long stream) { + bool asym, long stream, bool chain = false) { if (M < 1 || M > R4D_GEMM_W4A8_MAX_M) throw std::runtime_error("r4d gemm_w4a8_nt_m64: M out of range"); if (N % 16) throw std::runtime_error("r4d gemm_w4a8_nt_m64: N must be a multiple of 16"); @@ -279,8 +297,11 @@ static void r4d_gemm_w4a8_impl(long a, long ascale, long wq, long ws, long asum, auto Up = (const float*)asum; auto Cp = (__hip_bfloat16*)c; hipStream_t st = (hipStream_t)stream; -#define LAUNCH(MT, NP, TT, AS) hipLaunchKernelGGL((r4d_gemm_w4a8_nt_m64_kernel), \ - grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK) +#define LAUNCH(MT, NP, TT, AS) do { if (chain) \ + hipLaunchKernelGGL((r4dchain_gemm_w4a8_nt_m64), \ + grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK); else \ + hipLaunchKernelGGL((r4d_gemm_w4a8_nt_m64_kernel), \ + grid, block, smem, st, Ap, Sp, Wp, Zp, Up, Cp, M, K, N, WV, SK); } while (0) #define LAUNCH_MB(NP, TT, AS) switch (MB) { \ case 1: LAUNCH(1, NP, TT, AS); break; \ case 2: LAUNCH(2, NP, TT, AS); break; \ @@ -340,20 +361,22 @@ extern "C" int r4d_rad_gemm_w4a8_m64(const RadArgs* a, RadStream s) { rc = cfg_for(a, g.K, g.M, group, BR_NPW, &c); if (rc != RAD_OK) return rc; + /* the engine's chained launch (RadKernelChainFn), at decode heights only */ + const bool chain = r4d_geti_or(a, "chain", 0) != 0 && g.M <= 64; if (is_asym(a)) { if (!g.asum) return R4D_NO(RAD_E_INVAL); /* the entry point throws "asum is required" */ R4D_TRY("gemm_w4a8_asym_nt_m64", - r4d_gemm_w4a8_asym_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), - r4d_addr(g.bscale), r4d_addr(g.asum), r4d_addr(g.y), - (int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, - c.nt, (long)(uintptr_t)s)); + r4d_gemm_w4a8_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), + r4d_addr(g.bscale), r4d_addr(g.asum), r4d_addr(g.y), + (int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, + c.nt, true, (long)(uintptr_t)s, chain)); return RAD_OK; } R4D_TRY("gemm_w4a8_nt_m64", - r4d_gemm_w4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), - r4d_addr(g.bscale), r4d_addr(g.y), - (int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt, - (long)(uintptr_t)s)); + r4d_gemm_w4a8_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), + r4d_addr(g.bscale), 0, r4d_addr(g.y), + (int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt, + false, (long)(uintptr_t)s, chain)); return RAD_OK; } diff --git a/libr4d/r4d_gemm_w8a8_nt_m64.hip b/libr4d/r4d_gemm_w8a8_nt_m64.hip index f45814e5..f72a98ed 100644 --- a/libr4d/r4d_gemm_w8a8_nt_m64.hip +++ b/libr4d/r4d_gemm_w8a8_nt_m64.hip @@ -28,6 +28,7 @@ #include "r4d_gemm_args.h" #include "r4d_common.h" #include "r4d_gdn_wmma.h" +#include "r4d_chain.h" #include #include #include @@ -68,8 +69,10 @@ __device__ __forceinline__ v8i mmai8(v2i a, v2i b, v8i c) { // VGPRs. The bound is a hard launch limit, so the host checks WV*SK against the same expression. #define R4D_W8A8_BOUNDS(MT, NPW) ((MT) * (NPW) >= 8 ? 256 : ((MT) * (NPW) >= 4 ? 512 : 1024)) +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. Its early returns +// sit after its last barrier, so every block still reaches the wrapper's add. template -__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64_kernel( +__device__ __forceinline__ void r4d_gemm_w8a8_nt_m64_body( const signed char* __restrict__ A, const float* __restrict__ Ascale, const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws, __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { @@ -219,9 +222,34 @@ __global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64 } } } +template +__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4d_gemm_w8a8_nt_m64_kernel( + const signed char* __restrict__ A, const float* __restrict__ Ascale, + const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws, + __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { + r4d_gemm_w8a8_nt_m64_body(A, Ascale, Wq, Ws, C, M, K, N, WV, SK); +} +template +__global__ __launch_bounds__(R4D_W8A8_BOUNDS(MT, NPW)) void r4dchain_gemm_w8a8_nt_m64( + const signed char* __restrict__ A, const float* __restrict__ Ascale, + const unsigned* __restrict__ Wq, const unsigned short* __restrict__ Ws, + __hip_bfloat16* __restrict__ C, int M, int K, int N, int WV, int SK) { + r4d_chain_wait(); + r4d_gemm_w8a8_nt_m64_body(A, Ascale, Wq, Ws, C, M, K, N, WV, SK); + r4d_chain_done(); +} + +/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */ +static void gemm_w8a8_m64_impl(long a, long ascale, long wq, long ws, long c, int M, int K, int N, + int WV, int SK, int MB, int NPW, int NT, long stream, bool chain); void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int WV, int SK, int MB, int NPW, int NT, long stream) { + gemm_w8a8_m64_impl(a, ascale, wq, ws, c, M, K, N, WV, SK, MB, NPW, NT, stream, false); +} + +static void gemm_w8a8_m64_impl(long a, long ascale, long wq, long ws, long c, int M, int K, int N, + int WV, int SK, int MB, int NPW, int NT, long stream, bool chain) { if (M < 1 || M > R4D_GEMM_W8A8_MAX_M) throw std::runtime_error("r4d gemm_w8a8_nt_m64: M out of range"); if (N % 16) throw std::runtime_error("r4d gemm_w8a8_nt_m64: N must be a multiple of 16"); @@ -244,7 +272,8 @@ void r4d_gemm_w8a8_nt_m64(long a, long ascale, long wq, long ws, long c, int M, auto Zp = (const unsigned short*)ws; auto Cp = (__hip_bfloat16*)c; hipStream_t st = (hipStream_t)stream; -#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((r4d_gemm_w8a8_nt_m64_kernel), \ +#define LAUNCH8(MT, NP, TT) hipLaunchKernelGGL((chain ? r4dchain_gemm_w8a8_nt_m64 \ + : r4d_gemm_w8a8_nt_m64_kernel), \ grid, block, smem, st, Ap, Sp, Wp, Zp, Cp, M, K, N, WV, SK) // Only tiles with MT*NPW <= 8 are built: a tile costs about 16*MT*NPW + 40 VGPRs against the 256 // cap. @@ -293,11 +322,13 @@ extern "C" int r4d_rad_gemm_w8a8_m64(const RadArgs* a, RadStream s) { Cfg c; rc = cfg_for(a, g.K, g.M, group, BR_MBNPW, &c); if (rc != RAD_OK) return rc; + /* the engine's chained launch (RadKernelChainFn), at decode heights only */ + const bool chain = r4d_geti_or(a, "chain", 0) != 0 && g.M <= 64; R4D_TRY("gemm_w8a8_nt_m64", - r4d_gemm_w8a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), - r4d_addr(g.bscale), r4d_addr(g.y), - (int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt, - (long)(uintptr_t)s)); + gemm_w8a8_m64_impl(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), + r4d_addr(g.bscale), r4d_addr(g.y), + (int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw, c.nt, + (long)(uintptr_t)s, chain)); return RAD_OK; } diff --git a/libr4d/r4d_kv_len_trim.hip b/libr4d/r4d_kv_len_trim.hip new file mode 100644 index 00000000..5fec5a65 --- /dev/null +++ b/libr4d/r4d_kv_len_trim.hip @@ -0,0 +1,40 @@ +// r4d_kv_len_trim.hip - r4d_rad_kv_len_trim: a batch's per-sequence context lengths less `trim`. +// +// The 31B's prefill overlap runs attention per slice of a one-sequence step: slice A's rows are the +// step's first rows, so its attention must see the context ending at its own last row, not the +// step's (rows past it are not yet in the cache, and their positions are counted from the end). +// `trim` is the rows after the slice, a runtime count. A launch sees its op's parameters collapsed +// to the band's upper bound (RadArgs.p), so the count is the extent of operand `tail`, those rows' +// positions, whose values are never read; the ranged parameter only picks the band. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_emit.h" +#include + +namespace { + +__global__ __launch_bounds__(64) void kv_len_trim_kernel(const int32_t* __restrict__ in, + int32_t* __restrict__ out, int n, + int trim) { + const int i = (int)threadIdx.x; + if (i < n) { + const int v = in[i] - trim; + out[i] = v > 0 ? v : 0; + } +} + +} // namespace + +extern "C" int r4d_rad_kv_len_trim(const RadArgs* a, RadStream stream) { + const RadTensor* in = r4d_opt(a, 0); + const RadTensor* tail = r4d_opt(a, 1); + const RadTensor* out = r4d_opt(a, 2); + if (!in || !tail || !out || !in->data || !out->data) return R4D_NO(RAD_E_INVAL); + if (in->dtype != RAD_I32 || out->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_numel(in); + if (n < 1 || n > 64 || r4d_numel(out) < n) return R4D_NO(RAD_E_SHAPE); + const long long trim = tail->rank ? r4d_numel(tail) : 0; + if (trim < 0 || trim > 0x7fffffffLL) return R4D_NO(RAD_E_SHAPE); + return R4D_EMIT(stream, kv_len_trim_kernel, dim3(1), dim3(64), 0, (const int32_t*)in->data, + (int32_t*)out->data, (int)n, (int)trim); +} diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index e41f1f73..ca6b653e 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -28,6 +28,7 @@ #include "r4d_common.h" #include "rad_yarn.h" #include "r4d_fp8_wmma.h" +#include "r4d_chain.h" #include #include @@ -61,7 +62,9 @@ __device__ __forceinline__ float block_sum(float v, float* lds) { // ids stay global, a rank subtracts the offset, and another rank's token takes the zero-row path. // Summing the ranks reconstructs x. `mult` scales every entry with one rounding (Gemma's // sqrt(hidden)); 1 is a plain copy. -__global__ __launch_bounds__(kThreads) void embed_lookup_kernel( +// +// The body; embed_lookup_kernel and its chained form wrap it (its blocks return early). +__device__ __forceinline__ void embed_lookup_body( const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, uint16_t* __restrict__ x, uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, float mult) { const uint32_t m = blockIdx.x; @@ -79,6 +82,19 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_kernel( for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = f32_to_bf16(bf16_to_f32(src[i]) * mult); } +#define R4D_EL_PARAMS const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, \ + uint16_t* __restrict__ x, uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, \ + float mult +__global__ __launch_bounds__(kThreads) void embed_lookup_kernel(R4D_EL_PARAMS) { + embed_lookup_body(tok, wte, x, n_embd, n_vocab, vocab_off, x_ld, mult); +} +__global__ __launch_bounds__(kThreads) void r4dchain_embed_lookup(R4D_EL_PARAMS) { + r4d_chain_wait(); + embed_lookup_body(tok, wte, x, n_embd, n_vocab, vocab_off, x_ld, mult); + r4d_chain_done(); +} +#undef R4D_EL_PARAMS + // ---------------------------------------------------------------------------- embed_lookup_q // ref_embed_lookup_q. x[m] = bf16(wte[id] * scale), from a table of E4M3 codes with one scale (Q) // or plain bf16; an absent scale is one. This is the n-gram table's gather @@ -137,7 +153,9 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel( // ref_gather_rows. Like the embedding gather, with the same negative-index rule, but the source // row pitch is the caller's: it gathers from padded activation buffers (one logits row per // sequence out of a prefill chunk). -__global__ __launch_bounds__(kThreads) void gather_rows_kernel( +// +// The body; gather_rows_kernel and its chained form wrap it (its blocks return early). +__device__ __forceinline__ void gather_rows_body( const uint16_t* __restrict__ x, const int32_t* __restrict__ idx, uint16_t* __restrict__ y, uint32_t n, int32_t src_rows, uint32_t x_ld, uint32_t y_ld) { const uint32_t m = blockIdx.x; @@ -150,6 +168,17 @@ __global__ __launch_bounds__(kThreads) void gather_rows_kernel( const uint16_t* __restrict__ src = x + (size_t)r * x_ld; for (uint32_t i = threadIdx.x; i < n; i += kThreads) dst[i] = src[i]; } +#define R4D_GR_PARAMS const uint16_t* __restrict__ x, const int32_t* __restrict__ idx, \ + uint16_t* __restrict__ y, uint32_t n, int32_t src_rows, uint32_t x_ld, uint32_t y_ld +__global__ __launch_bounds__(kThreads) void gather_rows_kernel(R4D_GR_PARAMS) { + gather_rows_body(x, idx, y, n, src_rows, x_ld, y_ld); +} +__global__ __launch_bounds__(kThreads) void r4dchain_gather_rows(R4D_GR_PARAMS) { + r4d_chain_wait(); + gather_rows_body(x, idx, y, n, src_rows, x_ld, y_ld); + r4d_chain_done(); +} +#undef R4D_GR_PARAMS // ---------------------------------------------------------------- byte row gather / scatter // @@ -206,8 +235,9 @@ __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel( __device__ __forceinline__ float act_f32(uint16_t v) { return bf16_to_f32(v); } __device__ __forceinline__ float act_f32(float v) { return v; } +// The body; rmsnorm_kernel and its chained form wrap it below (the cliff rows return early). template -__global__ __launch_bounds__(THR) void rmsnorm_kernel( +__device__ __forceinline__ void rmsnorm_body( const TX* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld, uint32_t M) { __shared__ float lds[THR / kWave]; @@ -226,13 +256,28 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel( } } +#define R4D_RN_PARAMS const TX* __restrict__ x, const void* __restrict__ w, \ + uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, \ + uint32_t y_ld, uint32_t M +template +__global__ __launch_bounds__(THR) void rmsnorm_kernel(R4D_RN_PARAMS) { + rmsnorm_body(x, w, y, n, eps, wadd, mult, x_ld, y_ld, M); +} +template +__global__ __launch_bounds__(THR) void r4dchain_rmsnorm(R4D_RN_PARAMS) { + r4d_chain_wait(); + rmsnorm_body(x, w, y, n, eps, wadd, mult, x_ld, y_ld, M); + r4d_chain_done(); +} +#undef R4D_RN_PARAMS + // ---------------------------------------------------------------------------- add_rmsnorm // x = x + a, rounded as `add` rounds it, then y = rmsnorm(x) over the x just written, computed as // rmsnorm_kernel computes it: the same width (r4d_act_threads), the same columns a thread, the same // block_sum. A thread re-reads only the x it wrote itself, so no barrier separates the passes. // Byte-identical to `add` followed by `rmsnorm`, on x and on y. template -__global__ __launch_bounds__(THR) void add_rmsnorm_kernel( +__device__ __forceinline__ void add_rmsnorm_body( uint16_t* __restrict__ x, const uint16_t* __restrict__ a, const void* __restrict__ w, uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t a_ld, uint32_t y_ld, uint32_t M) { @@ -258,6 +303,21 @@ __global__ __launch_bounds__(THR) void add_rmsnorm_kernel( } } +#define R4D_ARN_PARAMS uint16_t* __restrict__ x, const uint16_t* __restrict__ a, \ + const void* __restrict__ w, uint16_t* __restrict__ y, uint32_t n, float eps, float wadd, \ + float mult, uint32_t x_ld, uint32_t a_ld, uint32_t y_ld, uint32_t M +template +__global__ __launch_bounds__(THR) void add_rmsnorm_kernel(R4D_ARN_PARAMS) { + add_rmsnorm_body(x, a, w, y, n, eps, wadd, mult, x_ld, a_ld, y_ld, M); +} +template +__global__ __launch_bounds__(THR) void r4dchain_add_rmsnorm(R4D_ARN_PARAMS) { + r4d_chain_wait(); + add_rmsnorm_body(x, a, w, y, n, eps, wadd, mult, x_ld, a_ld, y_ld, M); + r4d_chain_done(); +} +#undef R4D_ARN_PARAMS + // ---------------------------------------------------------------------------- rmsnorm_p // ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps), rmsnorm with no gain. Gemma's attention applies // it to V (llama.cpp's ggml_rms_norm(V, eps)), which has no checkpoint gain. Accumulates exactly as @@ -388,6 +448,30 @@ __global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32( yr[i] = cap * tanhf(xr[i] / cap); } +/* The chained forms of both legs (RadKernelChainFn): the same loop between the wait and the add. */ +__global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, + uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { + r4d_chain_wait(); + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads) + yr[i] = f32_to_bf16(cap * tanhf(bf16_to_f32(xr[i]) / cap)); + r4d_chain_done(); +} +__global__ __launch_bounds__(kThreads) void r4dchain_logit_softcap_f32( + const float* __restrict__ x, float* __restrict__ y, + uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { + r4d_chain_wait(); + const uint32_t m = blockIdx.x; + const float* __restrict__ xr = x + (size_t)m * x_ld; + float* __restrict__ yr = y + (size_t)m * y_ld; + for (uint32_t i = blockIdx.y * kThreads + threadIdx.x; i < n; i += gridDim.y * kThreads) + yr[i] = cap * tanhf(xr[i] / cap); + r4d_chain_done(); +} + /* Blocks per softcap row: eight elements a thread, at most 64 blocks. */ static uint32_t softcap_blocks_per_row(int n) { uint32_t b = (uint32_t)((n + kThreads * 8 - 1) / (kThreads * 8)); @@ -693,11 +777,13 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8v4_kernel( /* The plugin entry and r4d.h's long-stream entry share this body. */ static int embed_lookup_bf16_emit(long tok, long wte, long x, int M, int n_embd, int n_vocab, - int vocab_off, int x_ld, float mult, RadStream stream) { + int vocab_off, int x_ld, float mult, RadStream stream, + bool chain = false) { if (!tok || !wte || !x) return -1; if (M <= 0 || n_embd <= 0 || n_vocab <= 0 || vocab_off < 0) return -2; if (!x_ld) x_ld = n_embd; - return R4D_EMIT(stream, embed_lookup_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + return R4D_EMIT(stream, (chain ? r4dchain_embed_lookup : embed_lookup_kernel), + dim3((uint32_t)M), dim3(kThreads), 0, (const int32_t*)tok, (const uint16_t*)wte, (uint16_t*)x, (uint32_t)n_embd, (int32_t)n_vocab, (int32_t)vocab_off, (uint32_t)x_ld, mult) == RAD_OK ? 0 : -4; @@ -736,12 +822,13 @@ extern "C" int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, i } static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src_rows, - int x_ld, int y_ld, RadStream stream) { + int x_ld, int y_ld, RadStream stream, bool chain = false) { if (!x || !idx || !y) return -1; if (M <= 0 || n <= 0 || src_rows <= 0) return -2; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - return R4D_EMIT(stream, gather_rows_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + return R4D_EMIT(stream, (chain ? r4dchain_gather_rows : gather_rows_kernel), + dim3((uint32_t)M), dim3(kThreads), 0, (const uint16_t*)x, (const int32_t*)idx, (uint16_t*)y, (uint32_t)n, (int32_t)src_rows, (uint32_t)x_ld, (uint32_t)y_ld) == RAD_OK ? 0 : -4; @@ -794,8 +881,18 @@ extern "C" int r4d_scatter_rows_u8(long v, long idx, long x, int M, int n, int d // `w_f32` selects an f32 or bf16 gain; a null `w` is a gain of one. `mult` scales the row before // its single rounding. +/* `chain`: the chained form, at decode heights (r4d_rad_rmsnorm passes the row's resolved + * parameter; every other caller none). */ +static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd, + float mult, int w_f32, int x_ld, int y_ld, long stream, + bool chain); extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float eps, float wadd, float mult, int w_f32, int x_ld, int y_ld, long stream) { + return rmsnorm_mult_launch(x, w, y, M, n, eps, wadd, mult, w_f32, x_ld, y_ld, stream, false); +} +static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd, + float mult, int w_f32, int x_ld, int y_ld, long stream, + bool chain) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; if (!x_ld) x_ld = n; @@ -806,8 +903,10 @@ extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float // to this one followed by the quantiser. const int thr = r4d_act_threads(M, n); // A drafter's 256-row head norm at 256 threads is exactly a full card; step past the cliff. + const bool ch = chain && M <= 64; #define R4D_RN_T(wf, T) \ - hipLaunchKernelGGL((rmsnorm_kernel), dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), \ + hipLaunchKernelGGL((ch ? r4dchain_rmsnorm : rmsnorm_kernel), \ + dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), \ dim3(T), 0, \ (hipStream_t)stream, (const uint16_t*)x, (const void*)w, (uint16_t*)y, \ (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M) @@ -910,14 +1009,16 @@ extern "C" int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long st return hipGetLastError() == hipSuccess ? 0 : -4; } -extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap, - int x_ld, int y_ld, long stream) { +/* `chain`: the chained form (the plugin entry, where the row resolved with `chain`). */ +static int logit_softcap_bf16_emit(long x, long y, int M, int n, float cap, + int x_ld, int y_ld, long stream, bool chain) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; if (!(cap > 0.0f)) return -3; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M, softcap_blocks_per_row(n)), + hipLaunchKernelGGL((chain ? r4dchain_logit_softcap : logit_softcap_kernel), + dim3((uint32_t)M, softcap_blocks_per_row(n)), dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap, @@ -925,14 +1026,20 @@ extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap, return hipGetLastError() == hipSuccess ? 0 : -4; } -extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap, - int x_ld, int y_ld, long stream) { +extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap, + int x_ld, int y_ld, long stream) { + return logit_softcap_bf16_emit(x, y, M, n, cap, x_ld, y_ld, stream, false); +} + +static int logit_softcap_f32_emit(long x, long y, int M, int n, float cap, + int x_ld, int y_ld, long stream, bool chain) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; if (!(cap > 0.0f)) return -3; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; - hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M, softcap_blocks_per_row(n)), + hipLaunchKernelGGL((chain ? r4dchain_logit_softcap_f32 : logit_softcap_kernel_f32), + dim3((uint32_t)M, softcap_blocks_per_row(n)), dim3(kThreads), 0, (hipStream_t)stream, (const float*)x, (float*)y, (uint32_t)n, cap, @@ -940,6 +1047,11 @@ extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap, return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap, + int x_ld, int y_ld, long stream) { + return logit_softcap_f32_emit(x, y, M, n, cap, x_ld, y_ld, stream, false); +} + extern "C" int r4d_scale_bf16(long x, long s, uint32_t s_dt, long y, int M, int n, int x_ld, int y_ld, long stream) { if (!x || !s || !y) return -1; @@ -1199,9 +1311,11 @@ extern "C" int r4d_rad_embed_lookup(const RadArgs* a, RadStream stream) { if (M <= 0 || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE); const float mult = (float)r4d_getf(a, "mult", 1.0); + /* The chained form at decode heights, where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; return embed_lookup_bf16_emit(r4d_addr(tok), r4d_addr(wte), r4d_addr(x), (int)M, (int)n_embd, (int)n_vocab, (int)voff, (int)x_ld, - mult, stream) == 0 ? RAD_OK : RAD_E_DEVICE; + mult, stream, ch) == 0 ? RAD_OK : RAD_E_DEVICE; } /* ------------------------------------------------------------------ embed_lookup_q */ @@ -1264,9 +1378,10 @@ extern "C" int r4d_rad_gather_rows(const RadArgs* a, RadStream stream) { if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || src <= 0 || r4d_numel(idx) < M) return R4D_NO(RAD_E_SHAPE); + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; return gather_rows_bf16_emit(r4d_addr(x), r4d_addr(idx), r4d_addr(y), (int)M, (int)n, (int)src, (int)x_ld, (int)y_ld, - stream) == 0 ? RAD_OK : RAD_E_DEVICE; + stream, ch) == 0 ? RAD_OK : RAD_E_DEVICE; } /* ------------------------------------------------------------------ byte rows */ @@ -1421,10 +1536,11 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { const long long y_ld = r4d_rows_pitch(y, n, &My); if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); - return r4d_rmsnorm_mult_bf16(r4d_addr(x), 0, r4d_addr(y), (int)M, (int)n, + return rmsnorm_mult_launch(r4d_addr(x), 0, r4d_addr(y), (int)M, (int)n, (float)r4d_getf(a, "eps", 1e-6), 0.0f, (float)r4d_getf(a, "mult", 1.0), 0, (int)x_ld, (int)y_ld, - (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; + (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0) == 0 + ? RAD_OK : RAD_E_DEVICE; } if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); /* The gain may be f32 (as plugins declare norm gains) or bf16; its width is read off the @@ -1446,10 +1562,10 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { return rmsnorm_x_f32((const float*)x->data, w->data, (uint16_t*)y->data, (int)M, (int)n, eps, wadd, (float)r4d_getf(a, "mult", 1.0), w_f32, (int)x_ld, (int)y_ld, s); - return r4d_rmsnorm_mult_bf16(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd, + return rmsnorm_mult_launch(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd, (float)r4d_getf(a, "mult", 1.0), - w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK - : RAD_E_DEVICE; + w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s, + r4d_geti_or(a, "chain", 0) != 0) == 0 ? RAD_OK : RAD_E_DEVICE; } /* ------------------------------------------------------------------ add_rmsnorm */ @@ -1482,12 +1598,20 @@ extern "C" int r4d_rad_add_rmsnorm(const RadArgs* a, RadStream s) { const float mult = (float)r4d_getf(a, "mult", 1.0); /* rmsnorm's width, from the same table (see r4d_rmsnorm_mult_bf16) */ const int thr = r4d_act_threads((int)M, (int)n); + /* The chained form at decode heights, where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; #define R4D_AN_T(wf, T) \ - emit_rc = R4D_EMIT(s, (add_rmsnorm_kernel), \ - dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \ - (uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \ - (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \ - (uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M) + emit_rc = ch \ + ? R4D_EMIT(s, (r4dchain_add_rmsnorm), \ + dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \ + (uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \ + (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \ + (uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M) \ + : R4D_EMIT(s, (add_rmsnorm_kernel), \ + dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), dim3(T), 0, \ + (uint16_t*)r4d_wp(x), (const uint16_t*)r4d_p(ad), r4d_p(w), \ + (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, \ + (uint32_t)a_ld, (uint32_t)y_ld, (uint32_t)M) #define R4D_AN(wf) \ do { if (thr == 1024) R4D_AN_T(wf, 1024); \ else if (thr == 512) R4D_AN_T(wf, 512); \ @@ -1704,11 +1828,13 @@ extern "C" int r4d_rad_logit_softcap(const RadArgs* a, RadStream s) { if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); + /* The chained form at decode heights, where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; const int rc = leg_bf16 - ? r4d_logit_softcap_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap, - (int)x_ld, (int)y_ld, (long)(uintptr_t)s) - : r4d_logit_softcap_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap, - (int)x_ld, (int)y_ld, (long)(uintptr_t)s); + ? logit_softcap_bf16_emit(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap, + (int)x_ld, (int)y_ld, (long)(uintptr_t)s, ch) + : logit_softcap_f32_emit(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap, + (int)x_ld, (int)y_ld, (long)(uintptr_t)s, ch); return rc == 0 ? RAD_OK : RAD_E_DEVICE; } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 8e7fbafe..d9d09a3f 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -469,7 +469,11 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*); /* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */ int r4d_rad_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream); +int r4d_rad_kv_len_trim (const RadArgs*, RadStream); int r4d_rad_add_rmsnorm (const RadArgs*, RadStream); +int r4d_rad_prefetch (const RadArgs*, RadStream); +int r4d_rad_layout_any(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); int r4d_rad_qkv_norm_rope_kv_store(const RadArgs*, RadStream); int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream); int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream); diff --git a/libr4d/r4d_prefetch.hip b/libr4d/r4d_prefetch.hip new file mode 100644 index 00000000..a682b12c --- /dev/null +++ b/libr4d/r4d_prefetch.hip @@ -0,0 +1,83 @@ +// r4d_prefetch.hip - r4d_rad_prefetch: read a weight's leading bytes into the on-die cache. +// +// A decode step at a few rows streams each weight once from memory, and the all-reduce between two +// GEMMs leaves memory idle for its whole round trip: ~20 us at a DFlash2 verify's 8 rows on 4x +// R9700. A read issued on the second lane in that window puts the next GEMM's first bytes in the +// 64 MB Infinity Cache, and the GEMM then streams them from there. On four cards (a microbenchmark +// of the 8-row two-shot and a GEMM-like stream of a cold 29 MB weight, 2026-10-17) 16 MB read beside +// the all-reduce took a layer from 84.0 us to 70.1; the same read on the same stream gained nothing. +// +// It writes nothing at all. Each lane folds its loads into one word and hands it to an empty +// `asm volatile`, which the compiler can neither drop nor see into, so the loads stay. +// +// Nothing here reaches HIP's runtime. The fold once went to a word hipMalloc'ed on the first +// launch, in the middle of a pass; then to a `__device__` word, which HIP's runtime registers and +// places itself (the engine records only fat binaries and functions). That word cost ~8% of a +// DFlash2 step (321 tok/s against 348 in one A/B on 4x R9700, 2026-10-17, every prefetch size +// alike), not through extra hardware queues (every image held 16 on the four cards); the +// mechanism is not pinned down. Neither form was the cause of the fresh-server divergence the +// reads beside a prefill bring (rad_arch.h, kPrefetchRows): with no word at all it is still there. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_chain.h" +#include "r4d_emit.h" +#include + +namespace { + +__global__ __launch_bounds__(256) void prefetch_kernel(const int4* __restrict__ p, size_t n16) { + const size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x; + const size_t nt = (size_t)gridDim.x * blockDim.x; + unsigned acc = 0; + for (size_t i = tid; i < n16; i += nt) { + const int4 v = p[i]; + acc ^= (unsigned)(v.x ^ v.y ^ v.z ^ v.w); + } + asm volatile("" ::"v"(acc)); +} + +/* The chained form (RadKernelChainFn): it waits for the kernels before it on its queue, as every + * chained form does, but adds its blocks to the counter at once, before reading: nothing after it + * reads anything it writes, so the next kernel need not wait for its reads. Issued on lane 0 + * between a GEMM and the collective after it (where launches chain), it starts reading as the + * GEMM's last block ends, with no event between the queues and no barrier bit on the GEMM. */ +__global__ __launch_bounds__(256) void r4dchain_prefetch(const int4* __restrict__ p, size_t n16) { + r4d_chain_wait(); + r4d_chain_done(); + const size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x; + const size_t nt = (size_t)gridDim.x * blockDim.x; + unsigned acc = 0; + for (size_t i = tid; i < n16; i += nt) { + const int4 v = p[i]; + acc ^= (unsigned)(v.x ^ v.y ^ v.z ^ v.w); + } + asm volatile("" ::"v"(acc)); +} + +} // namespace + +extern "C" int r4d_rad_layout_any(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*) { + return RAD_LAYOUT_ANY; +} + +extern "C" int r4d_rad_prefetch(const RadArgs* a, RadStream stream) { + const RadTensor* w = r4d_opt(a, 0); + if (!w || !w->data) return R4D_NO(RAD_E_INVAL); + long long bytes = r4d_geti_or(a, "bytes", 0); + if (bytes <= 0) return RAD_OK; + // Never past what the tensor says it holds, where its dtype says how wide an element is. + const int bits = rad_dtype_bits(w->dtype); + if (bits > 0) { + long long n = 1; + for (uint32_t i = 0; i < w->rank; ++i) n *= w->shape[i]; + const long long have = n * bits / 8; + if (have > 0 && bytes > have) bytes = have; + } + if ((uintptr_t)w->data % 16) return R4D_NO(RAD_E_ALIGN); + int nb = r4d_cfg_prefetch_nb(a); + if (nb < 1) nb = 64; + const bool ch = r4d_geti_or(a, "chain", 0) != 0; + return R4D_EMIT(stream, (ch ? r4dchain_prefetch : prefetch_kernel), dim3((unsigned)nb), dim3(256), 0, + (const int4*)w->data, (size_t)(bytes / 16)); +} diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip index c83a48a3..c3984464 100644 --- a/libr4d/r4d_qkv_norm_rope.hip +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -34,6 +34,7 @@ #include "r4d_args.h" #include "r4d_emit.h" #include "r4d_common.h" +#include "r4d_chain.h" #include #include #include @@ -118,8 +119,10 @@ __device__ __forceinline__ void kv_put(void* __restrict__ kv, size_t off, // KV 1 or 2 also stores each k and v head into the paged cache [n_blocks, nkv, block_size, 2*HD] // at slot[m] (k at column 0, v at HD), for rows m < n_slot whose slot is in range; KV 0 stores // nothing and ignores the cache arguments. +// The body: its blocks return early (rows past the cliff, value heads), so the chained form +// (r4d_chain.h) wraps it below rather than bracketing it in place. template -__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( +__device__ __forceinline__ void qkv_norm_rope_body( uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, @@ -201,6 +204,29 @@ __global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( } } +#define R4D_QNR_PARAMS uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, \ + const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, \ + uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, \ + uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, \ + uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos, \ + uint32_t m_rows, const int32_t* __restrict__ slot, void* __restrict__ kvc, uint32_t n_slot, \ + uint32_t block_size, uint32_t n_blocks, float k_inv, float v_inv, uint32_t vnorm +#define R4D_QNR_ARGS q, k, v, pos, qw, kw, nq, nkv, pq, pk, pv, q_ld, k_ld, v_ld, eps, wadd, rot, nfreq, \ + den, theta, rscale, n_pos, m_rows, slot, kvc, n_slot, block_size, n_blocks, k_inv, v_inv, vnorm +// The plain kernel, and the chained one (r4dchain*, r4d_chain.h) wrapping the same body. +template +__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel(R4D_QNR_PARAMS) { + qkv_norm_rope_body(R4D_QNR_ARGS); +} +template +__global__ __launch_bounds__(HD) void r4dchain_qkv_norm_rope(R4D_QNR_PARAMS) { + r4d_chain_wait(); + qkv_norm_rope_body(R4D_QNR_ARGS); + r4d_chain_done(); +} +#undef R4D_QNR_ARGS +#undef R4D_QNR_PARAMS + } // namespace // ============================================================== the plugin ABI entry points @@ -270,6 +296,7 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store) // A tp-4 verify of the 31B is 16 rows x 16 heads of 8 wavefronts: exactly a full card, the // cliff r4d_cliff_rows steps past with one idle row. const dim3 grid(r4d_cliff_rows((uint32_t)M, heads, (uint32_t)(hd / kWave)), heads); + const bool chain = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; /* RadKernelChainFn, decode */ // The store's geometry, checked as kv_store_geom checks it (r4d_model_bf16.hip). int kvw = 0; // 0 none, 1 E4M3, 2 bf16 @@ -302,7 +329,8 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store) } } -#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = R4D_EMIT(stream, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ +#define R4D_QNR_T(HD, WF, VK, KV) emit_rc = chain ? R4D_QNR_C(HD, WF, VK, KV, true) : R4D_QNR_C(HD, WF, VK, KV, false) +#define R4D_QNR_C(HD, WF, VK, KV, CH) R4D_EMIT(stream, (CH ? r4dchain_qkv_norm_rope : qkv_norm_rope_kernel), grid, dim3(HD), 0, \ (uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \ r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \ (uint32_t)v_ld, eps, wadd, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp, \ @@ -320,6 +348,7 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store) #undef R4D_QNR #undef R4D_QNR_KV #undef R4D_QNR_T +#undef R4D_QNR_C return emit_rc; } diff --git a/libr4d/r4d_quant_act_fp8.hip b/libr4d/r4d_quant_act_fp8.hip index 5804afca..6d50a788 100644 --- a/libr4d/r4d_quant_act_fp8.hip +++ b/libr4d/r4d_quant_act_fp8.hip @@ -25,6 +25,7 @@ #include "r4d_fp8_args.h" #include "r4d_fp8_wmma.h" #include "r4d_fwht.h" +#include "r4d_chain.h" namespace { @@ -43,10 +44,14 @@ constexpr uint32_t kGroup = 128; // // I8 is the same quantiser at int8 codes (quant_act_i8g, had_quant_act_i8g): scale amax/127, // round-to-nearest-even into -127..127, same row-major layout and per-(row, 128) scales. -template -__global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel( +// +// CHAIN brackets the body with the chained launch's wait and add (r4d_chain.h); no block returns +// early. quant_act_fp8_kernel and r4dchain_quant_act_fp8 below are the plain and chained forms. +template +__device__ __forceinline__ void quant_act_fp8_body( const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld) { + if (CHAIN) r4d_chain_wait(); const uint32_t row = blockIdx.x; const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; const size_t xrow = (size_t)row * x_ld; @@ -92,8 +97,21 @@ __global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel( // of the accumulators. The caller must own K rounded up to 4 bytes of `q`. if (c0 < K) *(uint32_t*)(q + qrow + c0) = (uint32_t)pk; } + if (CHAIN) r4d_chain_done(); } +#define R4D_QAF_PARAMS const uint16_t* __restrict__ x, uint8_t* __restrict__ q, \ + float* __restrict__ s, uint32_t K, uint32_t nkb, uint32_t x_ld, uint32_t q_ld, uint32_t s_ld +template +__global__ __launch_bounds__(kThreads) void quant_act_fp8_kernel(R4D_QAF_PARAMS) { + quant_act_fp8_body(x, q, s, K, nkb, x_ld, q_ld, s_ld); +} +template +__global__ __launch_bounds__(kThreads) void r4dchain_quant_act_fp8(R4D_QAF_PARAMS) { + quant_act_fp8_body(x, q, s, K, nkb, x_ld, q_ld, s_ld); +} +#undef R4D_QAF_PARAMS + } // namespace extern "C" int r4d_quant_act_fp8_group(void) { return (int)kGroup; } @@ -105,7 +123,7 @@ extern "C" int r4d_quant_act_fp8_group(void) { return (int)kGroup; } // `rot` runs the 128-wide Hadamard first and additionally requires K % 128 == 0 (see the kernel). static int quant_act_fp8_launch(long a, long q, long s, int M, int K, int x_ld, int q_ld, int s_ld, RadStream stream, bool rot, - bool i8 = false) { + bool i8 = false, bool chain = false) { int emit_rc = RAD_OK; if (!a || !q || !s) return -1; if (M <= 0 || K <= 0) return -2; @@ -115,10 +133,15 @@ static int quant_act_fp8_launch(long a, long q, long s, int M, int K, if (!q_ld) q_ld = K; const int nkb = (K + (int)kGroup - 1) / (int)kGroup; if (!s_ld) s_ld = nkb; + /* The chained form at decode heights, where the row resolved with `chain`. */ + const bool ch = chain && M <= 64; #define R4D_QA(ROT_, I8_) \ - R4D_EMIT(stream, (quant_act_fp8_kernel), dim3((uint32_t)M), dim3(kThreads), 0, \ - (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, (uint32_t)nkb, \ - (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) + (ch ? R4D_EMIT(stream, (r4dchain_quant_act_fp8), dim3((uint32_t)M), \ + dim3(kThreads), 0, (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, \ + (uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld) \ + : R4D_EMIT(stream, (quant_act_fp8_kernel), dim3((uint32_t)M), \ + dim3(kThreads), 0, (const uint16_t*)a, (uint8_t*)q, (float*)s, (uint32_t)K, \ + (uint32_t)nkb, (uint32_t)x_ld, (uint32_t)q_ld, (uint32_t)s_ld)) if (i8) emit_rc = rot ? R4D_QA(true, true) : R4D_QA(false, true); else emit_rc = rot ? R4D_QA(true, false) : R4D_QA(false, false); #undef R4D_QA @@ -163,7 +186,8 @@ static int rad_quant_act_fp8(const RadArgs* a, RadStream stream, bool rot, bool const long long xp = r4d_row_pitch(x), qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc); if (xp < 0 || qp < 0 || sp < 0) return R4D_NO(RAD_E_STRIDE); const int e = quant_act_fp8_launch(r4d_addr(x), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, - (int)xp, (int)qp, (int)sp, stream, rot, i8); + (int)xp, (int)qp, (int)sp, stream, rot, i8, + r4d_geti_or(a, "chain", 0) != 0); return e == 0 ? RAD_OK : RAD_E_SHAPE; } diff --git a/libr4d/r4d_quant_act_i8.hip b/libr4d/r4d_quant_act_i8.hip index ac66d5da..4257e5b0 100644 --- a/libr4d/r4d_quant_act_i8.hip +++ b/libr4d/r4d_quant_act_i8.hip @@ -11,13 +11,17 @@ #include "r4d_args.h" #include "r4d_emit.h" #include "r4d_common.h" +#include "r4d_chain.h" #include #include -template -__global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel( +/* CHAIN: the chained form's wait and add (r4d_chain.h) around the same body; no block returns + * early. */ +template +__device__ __forceinline__ void r4d_quant_act_i8_body( const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S, int K) { + if (CHAIN) r4d_chain_wait(); const int row = blockIdx.x; const __hip_bfloat16* a = A + (size_t)row * K; signed char* q = Q + (size_t)row * K; @@ -47,6 +51,20 @@ __global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel( const int t = __float2int_rn(v); q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); } + if (CHAIN) r4d_chain_done(); +} + +template +__global__ __launch_bounds__(THR) void r4d_quant_act_i8_kernel( + const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S, + int K) { + r4d_quant_act_i8_body(A, Q, S, K); +} +template +__global__ __launch_bounds__(THR) void r4dchain_quant_act_i8( + const __hip_bfloat16* __restrict__ A, signed char* __restrict__ Q, float* __restrict__ S, + int K) { + r4d_quant_act_i8_body(A, Q, S, K); } // --------------------------------------------------------------------------------------------- @@ -126,9 +144,15 @@ extern "C" int r4d_rad_quant_act_i8(const RadArgs* args, RadStream stream) { const int thr = r4d_act_threads((int)M, (int)K); // the workgroup width, from M if (!as) { -#define R4D_QAI8_LAUNCH(T) emit_rc = R4D_EMIT(stream, (r4d_quant_act_i8_kernel), \ - dim3((int)M), dim3(T), 0, (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), \ - (float*)r4d_wp(sc), (int)K) + /* The chained form where the row resolved with `chain`, at decode heights. */ + const bool chain = r4d_geti_or(args, "chain", 0) != 0 && M <= 64; +#define R4D_QAI8_LAUNCH(T) emit_rc = chain \ + ? R4D_EMIT(stream, (r4dchain_quant_act_i8), dim3((int)M), dim3(T), 0, \ + (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), (float*)r4d_wp(sc), \ + (int)K) \ + : R4D_EMIT(stream, (r4d_quant_act_i8_kernel), dim3((int)M), dim3(T), 0, \ + (const __hip_bfloat16*)r4d_p(x), (signed char*)r4d_wp(q), (float*)r4d_wp(sc), \ + (int)K) switch (thr) { case 128: R4D_QAI8_LAUNCH(128); break; case 256: R4D_QAI8_LAUNCH(256); break; diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index 707a644d..638f02cb 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -28,6 +28,7 @@ // pass reads its own writes back. // // Returns a negative code instead of throwing, for the reason given in r4d_gemm_fp8a8.hip. +#include "r4d_chain.h" #include "r4d.h" #include "r4d_args.h" #include "r4d_emit.h" @@ -468,8 +469,11 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel( // // tail[0] counts the transport blocks done, tail[1] the junction blocks done; both start at zero // (the counter allocation is zeroed at init) and the last junction block returns them there. +// The body: transport blocks return after their part, so the chained form (r4d_chain.h) wraps +// it below. The last junction block resets the tail counters inside the body, before the chained +// form's add, so the next launch on the instance never sees them mid-reset. template -__global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_kernel( +__device__ __forceinline__ void ar_rmsnorm_quant_i8_tail_body( uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, @@ -585,6 +589,31 @@ __global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_kernel( } } +#define R4D_ARQ8T_PARAMS uint16_t* __restrict__ x, uint16_t* __restrict__ res, \ + const void* __restrict__ w, const void* __restrict__ wp, const void* __restrict__ sc, \ + uint32_t sc_f32, signed char* __restrict__ q, float* __restrict__ S, \ + uint16_t* __restrict__ yo, R4DArWidePeers peers, \ + const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \ + unsigned int* __restrict__ seq_ctrs, unsigned int* __restrict__ tail, int M, uint32_t n, \ + float eps, float wadd, uint32_t r_ld, uint32_t y_ld, int slot_stride16, int rank, int nbt, \ + int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr +#define R4D_ARQ8T_ARGS x, res, w, wp, sc, sc_f32, q, S, yo, peers, my_base, my_flags, seq_ctrs, tail, \ + M, n, eps, wadd, r_ld, y_ld, slot_stride16, rank, nbt, drain, acq, pub, gate, gate_ctr +// The plain kernel, and the chained one (r4dchain*): its wait comes before anything, the sequence +// take included, so a block of the next launch on the instance never starts ahead of this one's. +template +__global__ __launch_bounds__(1024) void ar_rmsnorm_quant_i8_tail_kernel(R4D_ARQ8T_PARAMS) { + ar_rmsnorm_quant_i8_tail_body(R4D_ARQ8T_ARGS); +} +template +__global__ __launch_bounds__(1024) void r4dchain_ar_rmsnorm_quant_i8_tail(R4D_ARQ8T_PARAMS) { + r4d_chain_wait(); + ar_rmsnorm_quant_i8_tail_body(R4D_ARQ8T_ARGS); + r4d_chain_done(); +} +#undef R4D_ARQ8T_ARGS +#undef R4D_ARQ8T_PARAMS + } // namespace // ============================================================== the plugin ABI entry point @@ -742,7 +771,7 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat float eps, float wadd, int w_f32, int r_ld, int y_ld, int rank, long stream, int nblocks, int drain, int acq, int pub, long gate, long gate_ctr, - long tail_ctr, int tail_nbt) { + long tail_ctr, int tail_nbt, int chain) { constexpr int WS = 4, NPEERS = WS - 1; const long ps[NPEERS] = { peer_scratch0, peer_scratch1, peer_scratch2 }; const long pf[NPEERS] = { peer_flags0, peer_flags1, peer_flags2 }; @@ -803,7 +832,8 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat return -8; } #define R4D_ARQ8T_K(WF, RS, PO, SC, E) \ - hipLaunchKernelGGL((ar_rmsnorm_quant_i8_tail_kernel), \ + hipLaunchKernelGGL((chain ? r4dchain_ar_rmsnorm_quant_i8_tail \ + : ar_rmsnorm_quant_i8_tail_kernel), \ dim3((uint32_t)(tail_nbt + M)), dim3(1024), lds, (hipStream_t)stream, \ (uint16_t*)x, (uint16_t*)res, (const void*)w, (const void*)wp, \ (const void*)sc, (uint32_t)sc_f32, (signed char*)q, (float*)s, \ diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 9a8ba1d0..2d5dae97 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -743,6 +743,25 @@ static const RadOperandSpec oAddRmsNorm[] = { { "w", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 }, }; +/* `kv_len_trim`: a batch's per-sequence context lengths less `trim` (docs/OPS.md). */ +static const RadParamSpec pKvLenTrim[] = { + { "trim", RAD_P_INT, RAD_REQUIRED }, + { "max_seqs", RAD_P_INT, RAD_REQUIRED }, +}; +/* `tail` is the rows past the slice (their positions); its extent is the trim, its values unread. + * A launch's `trim` is the band's upper bound, not the issued count (RadArgs.p). */ +static const RadOperandSpec oKvLenTrim[] = { + { "seqused", RAD_OPD_IN, 0 }, + { "tail", RAD_OPD_IN, 0 }, + { "out", RAD_OPD_OUT, 0 }, +}; +/* `prefetch` reads a weight's leading `bytes` into the cache and writes nothing (docs/OPS.md). */ +static const RadParamSpec pPrefetch[] = { + { "bytes", RAD_P_INT, RAD_REQUIRED }, +}; +static const RadOperandSpec oPrefetch[] = { + { "w", RAD_OPD_WEIGHT, 0 }, +}; static const RadParamSpec pGemmNtQ[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "N", RAD_P_INT, RAD_REQUIRED }, @@ -3150,6 +3169,13 @@ static const RadOpSchema kSchemas[] = { "x = x + a, then y = rmsnorm(x) * (w + wadd) * mult over the x written: a residual add " "and the next norm in one pass, byte-identical to add then rmsnorm. The norm is taken " "over the bf16 sum it stores; rmsnorm_add normalises the unrounded one."), + SCHEMA("kv_len_trim", pKvLenTrim, oKvLenTrim, + "out[s] = max(seqused[s] - trim, 0), trim the extent of `tail` (the rows past the " + "slice): the context a slice of a step's rows ends at, for an attention over that " + "slice alone."), + SCHEMA("prefetch", pPrefetch, oPrefetch, + "read a weight's leading bytes so they are in the cache when the next kernel streams " + "them; writes nothing."), SCHEMA("qkv_norm_rope", pQkvNormRope, oQkvNormRope, "per-head q and k RMS norms, the weightless v norm and the rotary of q and k over separate " "q, k and v projections, in one dispatch; v from the raw k under v_from_k. n_head 0 " @@ -4553,6 +4579,12 @@ static const RadConstraint cRmsNormQuantI8[] = { static const RadConstraint cAddRmsNorm[] = { C_GE("n", 1), C_IN("dtype", "bf16"), }; +static const RadConstraint cKvLenTrim[] = { + C_GE("trim", 0), C_LE("max_seqs", 64), +}; +static const RadConstraint cPrefetch[] = { + C_GE("bytes", 1), +}; static const RadConstraint cQkvNormRope[] = { C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), }; @@ -4970,6 +5002,13 @@ static const RadConstraint cLogitsGemmFp8[] = { C_DIV("n_embd", 128), C_IN("dtyp /* No tunable axes. */ #define NOTUNE nullptr, 0, nullptr +/* The prefetch's workgroups. It runs beside a collective or a latency-bound kernel and should fill + * that window's memory bandwidth without taking the compute units the other lane needs. */ +static const int64_t kPrefetchNb[] = { 64, 32, 128, 256, 16, 24, 48 }; +static const RadTunable tPrefetch[] = { + { "nb", kPrefetchNb, NELEM(kPrefetchNb), 64, "workgroups of 256 lanes reading the weight" }, +}; + /* ---- image generation ------------------------------------------------------------------- */ /* Rows read 16 bytes at a time, so the widths are whole eights. */ static const RadConstraint cGenRows8[] = { C_IN("dtype", "bf16"), C_DIV("n", 8) }; @@ -7837,6 +7876,24 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_add_rmsnorm, nullptr, nullptr, nullptr, r4d_shape_add_rmsnorm, nullptr, r4d_fuse_add_rmsnorm }, +{ "kv_len_trim", "kv_len_trim", "misc", + "a batch's per-sequence context lengths less a runtime trim, one workgroup", + "at most 64 sequences; the trim is the extent of `tail`", + "int32 in, int32 out, clamped at zero", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvLenTrim), NOTUNE, + nullptr, nullptr, r4d_rad_kv_len_trim, nullptr, nullptr, nullptr, nullptr, nullptr }, + +/* Reads its weight's stored bytes, whatever form the weight's GEMM gave them (RAD_LAYOUT_ANY). */ +{ "prefetch", "prefetch", "misc", + "read a weight's leading bytes, 16 a lane over 64 workgroups, so the next kernel streaming the " + "weight finds them in the 64 MB on-die cache; meant for a second lane beside a collective", + "any weight, any stored form; `bytes` clamped to what the tensor states", + "any", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cPrefetch), ROW(tPrefetch), nullptr, + nullptr, nullptr, r4d_rad_prefetch, nullptr, r4d_rad_layout_any, nullptr, nullptr, nullptr }, + { "gelu_mul_quant_i8", "gelu_mul_quant_i8", "quant", "gelu(gate) * up, the tanh form, and quant_act_i8's quantiser in one pass over the row", "n a multiple of 16 and n*2 bytes within LDS; one workgroup per row", @@ -9084,6 +9141,52 @@ extern "C" int rad_kernel_concurrent(int i) { return 1; } +/* Which rows can chain (RadKernelChainFn, rad_abi.h): every kernel their launch emits has a + * chained form (r4d_chain.h) the launch selects from the `chain` parameter. A row joins this list + * only once all of its kernels have one. */ +extern "C" int rad_kernel_chain(int i) { + const RadKernelInfo* k = rad_kernel_at(i); + if (!k) return 0; + static const char* const kChained[] = { + "gemm_w4a8_nt_m64", "gelu_mul_quant_i8", "qkv_norm_rope_bf16", + "qkv_norm_rope_kv_store_fp8", "qkv_norm_rope_kv_store_bf16", + /* the split-KV decode and its merge (r4d_decode_launch_win); their prefill kernel stays + * plain, and the backend chains only the kernels named r4dchain* */ + "attn_decode_h256_gqa2_fp8kv", "attn_decode_h256_gqa2_bf16kv", + "attn_qrow_decode_h256_gqa2_fp8kv", "attn_qrow_decode_h256_gqa2_bf16kv", + /* the fused junction: its tail form (the two-shot with the junction after it) only */ + "ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8_4rank", + /* the 31B's full layers: the windowed attention and its merge (r4d_attn_paged_window.hip, + * at decode heights) and the int8 quantiser before o_proj; h512 at every TP's gqa */ + "attn_qrow_h512_gqa2_fp8kv", "attn_qrow_h512_gqa2_bf16kv", + "attn_qrow_h512_gqa4_fp8kv", "attn_qrow_h512_gqa4_bf16kv", + "attn_qrow_h512_gqa8_fp8kv", "attn_qrow_h512_gqa8_bf16kv", + "quant_act_i8", + /* DFlash2's query and context passes: the narrow fp8 GEMMs (the gated gate_up among + * them), the activation quantiser, the norms, the conv projection, the opening + * convolution and the verify-height reductions */ + "gemm_fp8a8_nt_m16", "gemm_fp8a8_gated_nt_m16", + "gemm_i8a8_nt_m16", "quant_act_fp8", "rmsnorm_bf16", "add_rmsnorm_bf16", + "gemm_bf16_nt_m16", "gemm_bf16_nt_m64", "dflash_conv_t2_g16_bf16", + "ar_oneshot_4rank_exact", "ar_twoshot_4rank_exact", + /* the decode tail: the embedding, the sampled rows' gather, the lm_head's WMMA pass (the + * matvec below three rows stays plain) and the soft-cap */ + "embed_lookup_bf16", "gather_rows_bf16", "logits_gemm_fp8", "logits_gemm_i8", + "logit_softcap_bf16", "logit_softcap_f32", + /* the vocab-parallel sampler's candidate chain (temperature, top-k, the gathered sets' + * merge, the pick) and its all-gather, and DFlash2's draft head, row top-k, merge and + * selector */ + "sample_temp_f32", "sample_topk_f32", "sample_merge_topk_f32", "sample_pick_f32", + "ar_gather_4rank", "gemm_w8a8_nt_m64", "rowtopk_bf16", "rowtopk_merge", + "dflash_select_bf16", + /* the weight read beside a collective (its blocks add before reading, r4d_prefetch.hip) */ + "prefetch", + }; + for (const char* p : kChained) + if (std::strcmp(k->name, p) == 0) return 1; + return 0; +} + /* Which rows are collectives (rad_abi.h): every row whose init builds the all-reduce family's * exchange buffers, peer flags and handshake (standalone all-reduces and gathers, and norms and hc * writes with one folded in), plus each `_host` twin. Keyed on the init, since a cross-rank kernel @@ -9221,6 +9324,9 @@ extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) { extern "C" int r4d_cfg_ar_tail(const RadArgs* a) { return TUNE(a, tArQ84, "tail"); } +extern "C" int r4d_cfg_prefetch_nb(const RadArgs* a) { + return TUNE(a, tPrefetch, "nb"); +} extern "C" long r4d_cfg_ar_ts_min(const RadArgs* a) { return (long)tune_i(a, tAr, NELEM(tAr), "ts_min"); } diff --git a/libr4d/r4d_rowtopk_bf16.hip b/libr4d/r4d_rowtopk_bf16.hip index 48641f71..ca85822c 100644 --- a/libr4d/r4d_rowtopk_bf16.hip +++ b/libr4d/r4d_rowtopk_bf16.hip @@ -48,6 +48,7 @@ #include "r4d_common.h" #include "r4d_fp8_wmma.h" #include "r4d_fp8_lm.h" +#include "r4d_chain.h" #include #include @@ -120,8 +121,10 @@ __device__ __forceinline__ unsigned long long tk_round(unsigned long long* t) { return m; } +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. A wave past the +// chunks returns early; there is no barrier in it. template -__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stage1_kernel( +__device__ __forceinline__ void r4d_rowtopk_stage1_body( const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P, int N, int RC, int NCH, int CH) { // WPB independent waves per block, each on its own chunk, sharing nothing. Grouping them only @@ -179,6 +182,20 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stag if (lane == 0) out[r] = w; } } +template +__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stage1_kernel( + const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P, + int N, int RC, int NCH, int CH) { + r4d_rowtopk_stage1_body(Y, P, N, RC, NCH, CH); +} +template +__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4dchain_rowtopk_stage1( + const unsigned short* __restrict__ Y, unsigned long long* __restrict__ P, + int N, int RC, int NCH, int CH) { + r4d_chain_wait(); + r4d_rowtopk_stage1_body(Y, P, N, RC, NCH, CH); + r4d_chain_done(); +} // `off` is the first global column this rank's plane stands for, and `OP` the optional (id, value) // pair plane an all-gather moves: eight bytes an entry, an int32 id in the first float slot, the @@ -188,7 +205,8 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_TOPK_WPB) void r4d_rowtopk_stag // An empty slot is not token `off`. A chunk that ran out of candidates leaves a zero key; OI gets // column 0 for it, without the offset, so a pad cannot look like this rank's first real token. The // pair plane writes -1, the sentinel the merge drops (not -INFINITY, a valid masked logit). -__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel( +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. +__device__ __forceinline__ void r4d_rowtopk_stage2_body( const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI, float* __restrict__ OP, int off, int R, int n) { const int m = blockIdx.x; @@ -220,6 +238,18 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel( } } } +__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_stage2_kernel( + const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI, + float* __restrict__ OP, int off, int R, int n) { + r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n); +} +__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_stage2( + const unsigned long long* __restrict__ P, float* __restrict__ OV, int* __restrict__ OI, + float* __restrict__ OP, int off, int R, int n) { + r4d_chain_wait(); + r4d_rowtopk_stage2_body(P, OV, OI, OP, off, R, n); + r4d_chain_done(); +} // Chunks are a multiple of eight columns so stage 1 stays on the vector load; the last one is // clamped to N rather than padded (a padded tail would need a mask per element). The caller sizes @@ -239,7 +269,7 @@ int r4d_rowtopk_bf16_chunks(int N, int NCH) { // so ranks can agree on a global top-R without gathering the plane. static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi, long outp, int M, int N, int R, int RC, int NCH, int PT1, int off, - RadStream stream) { + RadStream stream, bool chain = false) { int emit_rc = RAD_OK; // R <= PT2 is what makes stage 2 exact for any candidates; a real limit, so checked, not // clamped. @@ -248,7 +278,8 @@ static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi, return R4D_NO(RAD_E_SHAPE); const int CH = rowtopk_chunk_width(N, NCH); const int nch = (N + CH - 1) / CH; -#define R4D_TK_S1(PT) emit_rc = R4D_EMIT(stream, (r4d_rowtopk_stage1_kernel), \ +#define R4D_TK_S1(PT) emit_rc = R4D_EMIT(stream, (chain ? r4dchain_rowtopk_stage1 \ + : r4d_rowtopk_stage1_kernel), \ dim3((nch + R4D_TOPK_WPB - 1) / R4D_TOPK_WPB, M), \ dim3(R4D_TOPK_WAVE * R4D_TOPK_WPB), 0, \ (const unsigned short*)y, (unsigned long long*)partial, N, RC, nch, CH) @@ -261,7 +292,8 @@ static int rowtopk_bf16_sharded_emit(long y, long partial, long outv, long outi, } #undef R4D_TK_S1 if (emit_rc != RAD_OK) return emit_rc; - return R4D_EMIT(stream, r4d_rowtopk_stage2_kernel, dim3(M), dim3(R4D_TOPK_WAVE), 0, + return R4D_EMIT(stream, (chain ? r4dchain_rowtopk_stage2 : r4d_rowtopk_stage2_kernel), dim3(M), + dim3(R4D_TOPK_WAVE), 0, (const unsigned long long*)partial, (float*)outv, (int*)outi, (float*)outp, off, R, nch * RC); } @@ -284,7 +316,8 @@ __device__ __forceinline__ unsigned long long tk_key_f32(float v, unsigned id) { return ((unsigned long long)u << 32) | (unsigned)(0xFFFFFFFFu - id); } -__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel( +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. +__device__ __forceinline__ void r4d_rowtopk_merge_body( const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) { const int m = blockIdx.x; const int lane = threadIdx.x; @@ -309,6 +342,16 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel( } } } +__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4d_rowtopk_merge_kernel( + const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) { + r4d_rowtopk_merge_body(G, OV, OI, R, n); +} +__global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_merge( + const float* __restrict__ G, float* __restrict__ OV, int* __restrict__ OI, int R, int n) { + r4d_chain_wait(); + r4d_rowtopk_merge_body(G, OV, OI, R, n); + r4d_chain_done(); +} // ============================================================== logit_rerank // @@ -490,9 +533,11 @@ extern "C" int r4d_rad_rowtopk(const RadArgs* a, RadStream stream) { if (r4d_numel(pairs) < M * R * 2) return R4D_NO(RAD_E_SHAPE); } + /* The chained forms at decode heights, where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; return rowtopk_bf16_sharded_emit(r4d_addr(x), (long)(uintptr_t)a->scratch, r4d_addr(val), r4d_addr(idx), pairs ? r4d_addr(pairs) : 0, - (int)M, (int)N, (int)R, RC, NCH, PT1, (int)off, stream); + (int)M, (int)N, (int)R, RC, NCH, PT1, (int)off, stream, ch); } /* ------------------------------------------------------------------ row_topk_merge @@ -519,7 +564,8 @@ extern "C" int r4d_rad_rowtopk_merge(const RadArgs* a, RadStream s) { if (r4d_numel(idx) < M * R || r4d_numel(val) < M * R) return R4D_NO(RAD_E_SHAPE); /* R <= PT2 makes the merge exact for any candidates (one lane can hold the whole answer). */ - return R4D_EMIT(s, r4d_rowtopk_merge_kernel, dim3((unsigned)M), + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; + return R4D_EMIT(s, (ch ? r4dchain_rowtopk_merge : r4d_rowtopk_merge_kernel), dim3((unsigned)M), dim3(R4D_TOPK_WAVE), 0, (const float*)g->data, (float*)val->data, (int*)idx->data, (int)R, (int)(W * R)); } diff --git a/libr4d/r4d_sample_stages_f32.hip b/libr4d/r4d_sample_stages_f32.hip index c6543014..a7bdd464 100644 --- a/libr4d/r4d_sample_stages_f32.hip +++ b/libr4d/r4d_sample_stages_f32.hip @@ -35,6 +35,7 @@ #include "r4d.h" #include "r4d_args.h" #include "r4d_common.h" +#include "r4d_chain.h" #include @@ -140,7 +141,8 @@ __device__ __forceinline__ float block_max(float v, float* lds) { // ---------------------------------------------------------------------------- sample_temp // ref_sample_temp. temp <= 0 leaves the row alone: greedy is `sample_argmax`, and a temperature of // zero silently meaning something else would make the chain unreadable. -__global__ __launch_bounds__(kThreads) void temp_kernel( +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. +__device__ __forceinline__ void temp_body( float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) { const uint32_t m = blockIdx.x; const float t = sp[m].temp; @@ -150,6 +152,16 @@ __global__ __launch_bounds__(kThreads) void temp_kernel( for (uint32_t i = threadIdx.x + blockIdx.y * kThreads; i < n_vocab; i += kThreads * gridDim.y) row[i] *= inv; } +__global__ __launch_bounds__(kThreads) void temp_kernel( + float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) { + temp_body(lg, sp, n_vocab, lg_ld); +} +__global__ __launch_bounds__(kThreads) void r4dchain_sample_temp( + float* __restrict__ lg, const SP* __restrict__ sp, uint32_t n_vocab, uint32_t lg_ld) { + r4d_chain_wait(); + temp_body(lg, sp, n_vocab, lg_ld); + r4d_chain_done(); +} // ---------------------------------------------------------------------------- sample_mask // ref_sample_mask. A set bit means allowed: the mask is the grammar's admissible set. Word w bit b @@ -461,7 +473,9 @@ __device__ uint32_t radix_select(const float* __restrict__ row, uint32_t n, uint return prefix; } -__global__ __launch_bounds__(kTopkThreads) void topk_kernel( +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. A greedy row's whole +// block returns early, together. +__device__ __forceinline__ void topk_body( const float* __restrict__ lg, const SP* __restrict__ sp, int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr, uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld, @@ -630,6 +644,22 @@ __global__ __launch_bounds__(kTopkThreads) void topk_kernel( } } } +__global__ __launch_bounds__(kTopkThreads) void topk_kernel( + const float* __restrict__ lg, const SP* __restrict__ sp, + int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr, + uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld, + uint32_t pr_ld, int32_t vocab_off, uint32_t pad) { + topk_body(lg, sp, ci, cv, pr, n_vocab, n_cand, lg_ld, ci_ld, cv_ld, pr_ld, vocab_off, pad); +} +__global__ __launch_bounds__(kTopkThreads) void r4dchain_sample_topk( + const float* __restrict__ lg, const SP* __restrict__ sp, + int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t* __restrict__ pr, + uint32_t n_vocab, uint32_t n_cand, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld, + uint32_t pr_ld, int32_t vocab_off, uint32_t pad) { + r4d_chain_wait(); + topk_body(lg, sp, ci, cv, pr, n_vocab, n_cand, lg_ld, ci_ld, cv_ld, pr_ld, vocab_off, pad); + r4d_chain_done(); +} // ---------------------------------------------------------------------------- sample_logprobs // ref_sample_logprobs. For a row with RAD_SP_LOGPROBS: [max, sum of exp(l - max), k (id, logit) @@ -909,7 +939,9 @@ __global__ __launch_bounds__(kThreads) void narrow_kernel( // the comparison never chooses one, and the fallback must not either. // // A greedy row is not touched: its token is the argmax's, written before the chain ran. -__global__ __launch_bounds__(kThreads) void pick_kernel( +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. Its returns are +// a whole block's, or every thread but the walker's after the last barrier. +__device__ __forceinline__ void pick_body( const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp, int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) { __shared__ float red[kWaves]; @@ -947,6 +979,18 @@ __global__ __launch_bounds__(kThreads) void pick_kernel( } tok[m] = chosen >= 0 ? chosen : last; } +__global__ __launch_bounds__(kThreads) void pick_kernel( + const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp, + int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) { + pick_body(ci, cv, sp, tok, n_cand, ci_ld, cv_ld); +} +__global__ __launch_bounds__(kThreads) void r4dchain_sample_pick( + const int32_t* __restrict__ ci, const float* __restrict__ cv, const SP* __restrict__ sp, + int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) { + r4d_chain_wait(); + pick_body(ci, cv, sp, tok, n_cand, ci_ld, cv_ld); + r4d_chain_done(); +} // ---------------------------------------------------------------------------- sample_merge_topk // The vocab-parallel merge. Each rank runs top-k over its own lm_head shard and the candidate sets @@ -956,7 +1000,8 @@ __global__ __launch_bounds__(kThreads) void pick_kernel( // // One block per row, with the top-k's packed (key, ~id) word, so descending order and the lower-id // tie rule come from the same code. n_in is world_size * n_cand, a few thousand. -__global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel( +// The body; the plain kernel and its chained form (r4d_chain.h) wrap it below. +__device__ __forceinline__ void merge_topk_body( const uint32_t* __restrict__ gt, const SP* __restrict__ sp, int32_t* __restrict__ ci, float* __restrict__ cv, uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) { @@ -1020,6 +1065,20 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel( ov[r] = __builtin_bit_cast(float, (key & 0x80000000u) ? (key & 0x7fffffffu) : ~key); } } +__global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel( + const uint32_t* __restrict__ gt, const SP* __restrict__ sp, + int32_t* __restrict__ ci, float* __restrict__ cv, + uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) { + merge_topk_body(gt, sp, ci, cv, n_in, n_cand, gt_ld, ci_ld, cv_ld, pad); +} +__global__ __launch_bounds__(kTopkThreads) void r4dchain_sample_merge_topk( + const uint32_t* __restrict__ gt, const SP* __restrict__ sp, + int32_t* __restrict__ ci, float* __restrict__ cv, + uint32_t n_in, uint32_t n_cand, uint32_t gt_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pad) { + r4d_chain_wait(); + merge_topk_body(gt, sp, ci, cv, n_in, n_cand, gt_ld, ci_ld, cv_ld, pad); + r4d_chain_done(); +} } // namespace @@ -1031,12 +1090,13 @@ __global__ __launch_bounds__(kTopkThreads) void merge_topk_kernel( static uint32_t host_pow2(uint32_t v) { uint32_t p = 1; while (p < v) p <<= 1; return p; } static int r4d_sample_temp_f32(long lg, long params, int M, int n_vocab, int lg_ld, - long stream) { + long stream, bool chain = false) { if (!lg || !params) return R4D_NO(RAD_E_INVAL); if (M <= 0 || n_vocab <= 0) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; const uint32_t gy = ((uint32_t)n_vocab + kThreads - 1) / kThreads; - hipLaunchKernelGGL(temp_kernel, dim3((uint32_t)M, gy > 256u ? 256u : gy), dim3(kThreads), 0, + hipLaunchKernelGGL((chain ? r4dchain_sample_temp : temp_kernel), + dim3((uint32_t)M, gy > 256u ? 256u : gy), dim3(kThreads), 0, (hipStream_t)stream, (float*)lg, (const SP*)params, (uint32_t)n_vocab, (uint32_t)lg_ld); return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); @@ -1120,7 +1180,7 @@ static int r4d_sample_logprobs_f32(long lg, long params, long stats, int M, int static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_val, long pairs, int M, int n_vocab, int n_cand, int lg_ld, int ci_ld, int cv_ld, int pr_ld, int vocab_off, - long stream) { + long stream, bool chain = false) { if (!lg || !params || !cand_idx || !cand_val) return R4D_NO(RAD_E_INVAL); if (M <= 0 || n_vocab <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE); if ((uint32_t)n_cand > kMaxCand) return R4D_NO(RAD_E_SHAPE); @@ -1129,7 +1189,8 @@ static int r4d_sample_topk_f32(long lg, long params, long cand_idx, long cand_va if (!cv_ld) cv_ld = n_cand; if (!pr_ld) pr_ld = 2 * n_cand; const uint32_t pad = host_pow2((uint32_t)n_cand); - hipLaunchKernelGGL(topk_kernel, dim3((uint32_t)M), dim3(kTopkThreads), + hipLaunchKernelGGL((chain ? r4dchain_sample_topk : topk_kernel), dim3((uint32_t)M), + dim3(kTopkThreads), pad * sizeof(unsigned long long), (hipStream_t)stream, (const float*)lg, (const SP*)params, (int32_t*)cand_idx, (float*)cand_val, (uint32_t*)pairs, @@ -1154,12 +1215,14 @@ static int r4d_sample_narrow_f32(long cand_idx, long cand_val, long params, int } static int r4d_sample_pick_f32(long cand_idx, long cand_val, long params, long tok, - int M, int n_cand, int ci_ld, int cv_ld, long stream) { + int M, int n_cand, int ci_ld, int cv_ld, long stream, + bool chain = false) { if (!cand_idx || !cand_val || !params || !tok) return R4D_NO(RAD_E_INVAL); if (M <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE); if (!ci_ld) ci_ld = n_cand; if (!cv_ld) cv_ld = n_cand; - hipLaunchKernelGGL(pick_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, + hipLaunchKernelGGL((chain ? r4dchain_sample_pick : pick_kernel), dim3((uint32_t)M), + dim3(kThreads), 0, (hipStream_t)stream, (const int32_t*)cand_idx, (const float*)cand_val, (const SP*)params, (int32_t*)tok, (uint32_t)n_cand, (uint32_t)ci_ld, (uint32_t)cv_ld); return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); @@ -1167,7 +1230,8 @@ static int r4d_sample_pick_f32(long cand_idx, long cand_val, long params, long t static int r4d_sample_merge_topk_f32(long gathered, long params, long cand_idx, long cand_val, int M, int n_in, int n_cand, - int gt_ld, int ci_ld, int cv_ld, long stream) { + int gt_ld, int ci_ld, int cv_ld, long stream, + bool chain = false) { if (!gathered || !params || !cand_idx || !cand_val) return R4D_NO(RAD_E_INVAL); if (M <= 0 || n_in <= 0 || n_cand <= 0) return R4D_NO(RAD_E_SHAPE); if ((uint32_t)n_in > kMaxCand) return R4D_NO(RAD_E_SHAPE); @@ -1175,7 +1239,8 @@ static int r4d_sample_merge_topk_f32(long gathered, long params, long cand_idx, if (!ci_ld) ci_ld = n_cand; if (!cv_ld) cv_ld = n_cand; const uint32_t pad = host_pow2((uint32_t)n_in); - hipLaunchKernelGGL(merge_topk_kernel, dim3((uint32_t)M), dim3(kTopkThreads), + hipLaunchKernelGGL((chain ? r4dchain_sample_merge_topk : merge_topk_kernel), dim3((uint32_t)M), + dim3(kTopkThreads), pad * sizeof(unsigned long long), (hipStream_t)stream, (const uint32_t*)gathered, (const SP*)params, (int32_t*)cand_idx, (float*)cand_val, @@ -1243,8 +1308,10 @@ extern "C" int r4d_rad_sample_temp(const RadArgs* a, RadStream s) { R4D_NEED(logits_of(a, &lg, &M, &nv, &ld)); const RadTensor* pr = r4d_opt(a, V_PARAMS); R4D_NEED(params_ok(pr, M)); + /* The chained form at decode heights, where the row resolved with `chain`. */ + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; return r4d_sample_temp_f32(r4d_addr(lg), r4d_addr(pr), (int)M, (int)nv, (int)ld, - (long)(uintptr_t)s); + (long)(uintptr_t)s, ch); } extern "C" int r4d_rad_sample_mask(const RadArgs* a, RadStream s) { @@ -1378,10 +1445,11 @@ extern "C" int r4d_rad_sample_topk(const RadArgs* a, RadStream s) { } const long long voff = r4d_pgeti_or(a->p, a->n_p, "vocab_off", 0); + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; return r4d_sample_topk_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv), pp ? r4d_addr(pp) : 0, (int)M, (int)nv, (int)n_cand, (int)ld, (int)ci_ld, (int)cv_ld, - (int)pr_ld, (int)voff, (long)(uintptr_t)s); + (int)pr_ld, (int)voff, (long)(uintptr_t)s, ch); } /* ------------------------------------------------------------------ the narrowing stages */ @@ -1439,9 +1507,10 @@ extern "C" int r4d_rad_sample_pick(const RadArgs* a, RadStream s) { if (M <= 0 || Mv < M || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE); R4D_NEED(params_ok(pr, M)); + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; return r4d_sample_pick_f32(r4d_addr(ci), r4d_addr(cv), r4d_addr(pr), r4d_addr(tok), (int)M, (int)n_cand, (int)ci_ld, (int)cv_ld, - (long)(uintptr_t)s); + (long)(uintptr_t)s, ch); } /* ------------------------------------------------------------------ merge_topk */ @@ -1474,7 +1543,8 @@ extern "C" int r4d_rad_sample_merge_topk(const RadArgs* a, RadStream s) { const long long n_in = per_row / 2; if (n_in <= 0 || n_in > (int)kMaxCand) return R4D_NO(RAD_E_SHAPE); + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; return r4d_sample_merge_topk_f32(r4d_addr(gt), r4d_addr(pr), r4d_addr(ci), r4d_addr(cv), (int)M, (int)n_in, (int)n_cand, (int)per_row, (int)ci_ld, - (int)cv_ld, (long)(uintptr_t)s); + (int)cv_ld, (long)(uintptr_t)s, ch); } diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 47fe35a0..1c3aaa26 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -764,6 +764,7 @@ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int6 run_case(r, ts, ps); } + static void gemm_case(const Plugin& pl, const char* name, const char* dtype, int64_t M, int64_t N, int64_t K, uint32_t adt, int need_ascale, int need_asum, int need_bref, int64_t wbytes, int64_t sbytes) { @@ -940,6 +941,102 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8 for (int64_t d = 0; d < head_dim; ++d) out[d] *= inv; } +/* kv_len_trim takes its trim from `tail`'s extent: a launch sees the op's ranged parameter at its + * band's upper bound (RadArgs.p), so `trim` here is 4096 while the issued count, and `tail`'s + * extent, is 1024. 90ede42 read the parameter, trimmed a 2048-key context to 0, and the attention + * over slice A's rows wrote nothing. */ +static void kv_len_trim_case(const Plugin& pl) { + const char* name = "kv_len_trim"; + if (!sel(name)) return; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const std::vector used = { 2048, 1500, 1024, 7 }; + void* d_out = dalloc(16); + if (!d_out) { ok(name, false, "hipMalloc failed"); return; } + std::vector ts = { + TI32({ 4 }, used), + TI32({ 1024 }, iota_i32(1024)), + T(d_out, RAD_I32, { 4 }), + }; + std::vector ps = { PI("trim", 4096), PI("max_seqs", 4) }; + run_case(r, ts, ps); + int32_t h[4] = { -1, -1, -1, -1 }; + st_memcpy(h, d_out, sizeof h, hipMemcpyDeviceToHost); + const bool good = h[0] == 1024 && h[1] == 476 && h[2] == 0 && h[3] == 0; + ok("kv_len_trim: the trim is tail's extent, not the collapsed parameter", good, + good ? std::string() : "out " + std::to_string(h[0]) + " " + std::to_string(h[1]) + " " + + std::to_string(h[2]) + " " + std::to_string(h[3]) + + ", want 1024 476 0 0"); +} + +/* An attention over a slice of a step's rows against the whole step's (the 31B's prefill overlap, + * attention per slice): one sequence, `nt` query rows ending a context of `ctx`, run whole and as + * rows [0, cut) with seqused ctx - (T - cut) and rows [cut, nt) with seqused ctx. Every output + * byte must match, since each row attends to the same keys. Reports the first differing row. */ +static void attn_slice_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa, + int64_t kv_heads, int64_t nt, int64_t cut, int64_t ctx, int window) { + if (!sel(name) && !sel("attn_slice")) return; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t bs = 16, q_heads = kv_heads * gqa; + const int64_t blocks = (ctx + bs - 1) / bs; + const bool fp8 = std::strstr(name, "fp8kv") != nullptr; + const uint32_t kvdt = fp8 ? RAD_F8E4M3 : RAD_BF16; + const int64_t ew = fp8 ? 1 : 2; + const int64_t qn = nt * q_heads * head_dim, kvn = blocks * kv_heads * bs * 2 * head_dim; + std::vector hq((size_t)qn); + for (int64_t i = 0; i < qn; ++i) hq[(size_t)i] = st_rand_bf16((uint32_t)i); + std::vector hkv((size_t)(kvn * ew)); + if (fp8) for (int64_t i = 0; i < kvn; ++i) hkv[(size_t)i] = st_rand_e4m3((uint32_t)i); + else for (int64_t i = 0; i < kvn; ++i) ((uint16_t*)hkv.data())[i] = st_rand_bf16((uint32_t)i + 7u); + void* d_q = dalloc((size_t)qn * 2); + void* d_kv = dalloc((size_t)(kvn * ew)); + void* d_ow = dalloc((size_t)qn * 2); + void* d_os = dalloc((size_t)qn * 2); + if (!d_q || !d_kv || !d_ow || !d_os) { ok(name, false, "hipMalloc failed"); return; } + st_memcpy(d_q, hq.data(), hq.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_kv, hkv.data(), hkv.size(), hipMemcpyHostToDevice); + auto run = [&](int64_t r0, int64_t n, int32_t used, void* out) { + std::vector ts = { + T((char*)d_q + (size_t)(r0 * q_heads * head_dim * 2), RAD_BF16, { n, q_heads, head_dim }), + T(d_kv, kvdt, { blocks, kv_heads, bs, 2 * head_dim }), + TI32({ 1, blocks }, iota_i32(blocks)), + TI32({ 1 }, rep_i32(1, used)), + TF32({ 1, kv_heads }, 1.0f), + TF32({ 1, kv_heads }, 1.0f), + T(nullptr, RAD_I32, { 2 }), + T((char*)out + (size_t)(r0 * q_heads * head_dim * 2), RAD_BF16, { n, q_heads, head_dim }), + }; + if (!fp8) { absent(ts[4]); absent(ts[5]); } + absent(ts[6]); + std::vector ps = { + PI("q_len", n), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs), + PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), + PS("kv_dtype", fp8 ? "fp8_e4m3" : "bf16"), + }; + run_case(r, ts, ps); + }; + st_memset(d_ow, 0, (size_t)qn * 2); + st_memset(d_os, 0, (size_t)qn * 2); + run(0, nt, (int32_t)ctx, d_ow); + run(0, cut, (int32_t)(ctx - (nt - cut)), d_os); + run(cut, nt - cut, (int32_t)ctx, d_os); + std::vector ow((size_t)qn), os((size_t)qn); + st_memcpy(ow.data(), d_ow, ow.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(os.data(), d_os, os.size() * 2, hipMemcpyDeviceToHost); + int64_t first = -1, ndiff = 0; + const int64_t rowsz = q_heads * head_dim; + for (int64_t i = 0; i < qn; ++i) + if (ow[(size_t)i] != os[(size_t)i]) { if (first < 0) first = i / rowsz; ++ndiff; } + std::string why; + if (ndiff) + why = std::to_string((long long)ndiff) + " elements differ, first at row " + + std::to_string((long long)first); + ok((std::string(name) + ": a slice's rows equal the whole step's, T " + std::to_string((long long)nt) + + " cut " + std::to_string((long long)cut) + " ctx " + std::to_string((long long)ctx)).c_str(), + ndiff == 0, why); +} + /* Numeric attention check: fill q and the paged k/v with avalanche-random data, run the row, and * compare the bf16 output against the oracle above. A negative control corrupts part of the * reference and requires the comparison to fail. */ @@ -23954,6 +24051,23 @@ static void device_phase(const Plugin& pl) { embed_lookup_q_case(pl); lora_case(pl); + /* --- a weight read into the cache (prefetch): it runs, and takes any stored form --- */ + if (sel("prefetch")) { + const RadKernelInfo* r = find(pl, "prefetch"); + if (!r) { + ok("prefetch", false, "row absent"); + } else { + void* d = dalloc((size_t)1 << 20); + std::vector ts = { T(d, RAD_U8, { (int64_t)1 << 20 }) }; + std::vector ps = { PI("bytes", (int64_t)1 << 20) }; + run_case(r, ts, ps); + RadLayout L{}; + const int st = r->layout ? r->layout(nullptr, 0, 0, nullptr, nullptr, nullptr, 0, &L) : 0; + ok("prefetch's layout hook takes any stored form (RAD_LAYOUT_ANY)", st == RAD_LAYOUT_ANY, + "returned " + std::to_string(st)); + } + } + /* --- the paged cache's write side --- */ kv_store_case(pl, "kv_store_bf16", "bf16"); kv_store_case(pl, "kv_store_bf16", "bf16", true); @@ -23997,6 +24111,14 @@ static void device_phase(const Plugin& pl) { /* Gemma 4 dense global: head_dim 512, full attention, on the windowed kernel (one row for every * q_len): a prefill-shaped launch (q_len 32) and a decode one (1); numeric checks follow. */ attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1); + /* The 31B's prefill overlap at tp 4: sliding h256 gqa 2 (4 kv heads a rank, window 1024) and + * global h512 gqa 8 (1 kv head), a 2048-row chunk cut at 1024, first chunk and a later one. */ + kv_len_trim_case(pl); + for (const int64_t ctx : { (int64_t)2048, (int64_t)4096 }) { + attn_slice_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 4, 2048, 1024, ctx, 1024); + attn_slice_case(pl, "attn_qrow_h512_gqa8_fp8kv", 512, 8, 1, 2048, 1024, ctx, 0); + attn_slice_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, 2048, 1024, ctx, 0); + } attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1); attn_case(pl, "attn_window_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); attn_case(pl, "attn_window_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 8fa48a77..e95bb306 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -17,6 +17,7 @@ ABI_FIELD(RadArchProbe, gen_audio) ABI_FIELD(RadArchProbe, gen_ctx) ABI_FIELD(RadArchProbe, gen_video) ABI_FIELD(RadArchProbe, kv_quant_ok) +ABI_FIELD(RadArchProbe, chain_pays) ABI_STRUCT(RadArgs) ABI_FIELD(RadArgs, t) ABI_FIELD(RadArgs, n_t) diff --git a/tests/arch_fakes.h b/tests/arch_fakes.h index 824e2eb3..03902ae4 100644 --- a/tests/arch_fakes.h +++ b/tests/arch_fakes.h @@ -341,6 +341,14 @@ extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { b->drafter_pos = pos_offset; return RAD_OK; } +/* The core's chaining decision as the recorder answers it (it has no chaining backend): 0 unless a + * test holds a ChainOn, to see where a plugin places work when launches chain. */ +static int g_chain_on = 0; +extern "C" int rad_chain_on(void) { return g_chain_on; } +struct ChainOn { + explicit ChainOn(int on) { g_chain_on = on; } + ~ChainOn() { g_chain_on = 0; } +}; extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { if (!b || !d || !d->name || !d->modalities) return RAD_E_INVAL; if (d->modalities == RAD_MM_AUDIO) { diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 56b3d8bb..4453d187 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3515,15 +3515,19 @@ static std::vector gemma4_w4_step(const std::set& refu /* At two ranks the all-reduce before each junction is folded into it; only the embedding's and * the last feed-forward's (which feeds the final norm, not a quantiser) remain standalone. Without - * the fused collective, junctions keep their preceding all-reduces. */ + * the fused collective, junctions keep their preceding all-reduces. Beside each reduction a + * prefetch of the next GEMM's weight (the lm_head after the last), and down_proj's beside the + * attention (prefetch_beside). */ TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) { std::vector want = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" }; for (int l = 0; l < 12; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q"); - for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", - "ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) + for (const char* s : { "prefetch", "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", + "gemm_nt_q", "prefetch", "ar_rmsnorm_quant_i8", "gemm_nt_q", + "gelu_mul_quant_i8", "gemm_nt_q" }) want.push_back(s); + want.push_back("prefetch"); if (l < 11) want.push_back("ar_rmsnorm_quant_i8"); else for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) want.push_back(s); } @@ -3535,10 +3539,12 @@ TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) { for (int l = 0; l < 12; ++l) { const bool global = (l + 1) % 6 == 0; for (int i = 0; i < (global ? 2 : 3); ++i) plain.push_back("gemm_nt_q"); - for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", - "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", - "gemm_nt_q", "all_reduce" }) + for (const char* s : { "prefetch", "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", + "gemm_nt_q", "prefetch", "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", + "gelu_mul_quant_i8", "gemm_nt_q" }) plain.push_back(s); + plain.push_back("prefetch"); + plain.push_back("all_reduce"); if (l < 11) plain.push_back("rmsnorm_quant_i8"); else for (const char* s : { "rmsnorm", "add", "scale" }) plain.push_back(s); } @@ -3811,6 +3817,7 @@ TEST(gemma4_probe_names_the_heads_operating_depth) { CHECK_OK(gemma4_bf16::probe(&with, &p)); CHECK_EQ(p.draft_depth, gemma4_bf16::kHeadDepth); CHECK_EQ(p.draft_depth_fixed, 0); + CHECK_EQ(p.chain_pays, 0); /* chained launches never measured with the head */ RadArchProbe q{}; RadModelMeta without = gemma4_meta(); CHECK_OK(gemma4_bf16::probe(&without, &q)); @@ -4033,6 +4040,7 @@ TEST(gemma4_probe_names_the_dflash_blocks_depth) { CHECK_OK(gemma4::probe(&meta, &p)); CHECK_EQ(p.draft_depth, 15); CHECK_EQ(p.draft_depth_fixed, 1); + CHECK_EQ(p.chain_pays, 1); /* chained launches measured a gain with DFlash */ for (size_t i = 0; i < keys.size(); ++i) if (!std::strcmp(keys[i], "draft.architectures")) vals[i] = "[\"DFlash2DraftModel\"]"; @@ -4610,30 +4618,56 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ const int L = 12; std::vector folded = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" }; std::vector apart = folded; + /* beside each reduction, up to a step of 16 rows: a prefetch (prefetch_beside) */ + auto pf = [](std::vector& v, std::vector s, bool next) { + std::vector out = { "prefetch" }; /* o_proj's, beside the attention */ + for (const auto& x : s) { + if ((x == "ar_rmsnorm_quant_i8" || x == "all_reduce") && (next || &x != &s.back())) + out.push_back("prefetch"); + out.push_back(x); + } + v.insert(v.end(), out.begin(), out.end()); + }; + std::vector apart_tall = folded, folded_bare = folded; for (int l = 0; l < L; ++l) { const bool global = (l + 1) % 6 == 0; - for (int i = 0; i < (global ? 2 : 3); ++i) { folded.push_back("gemm_nt_q"); apart.push_back("gemm_nt_q"); } - for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", - "ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) - folded.push_back(s); - for (const char* s : { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", - "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", - "gemm_nt_q", "all_reduce" }) - apart.push_back(s); + for (int i = 0; i < (global ? 2 : 3); ++i) + for (auto* v : { &folded, &apart, &apart_tall, &folded_bare }) v->push_back("gemm_nt_q"); + const std::vector fs = { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", + "gemm_nt_q", "ar_rmsnorm_quant_i8", "gemm_nt_q", + "gelu_mul_quant_i8", "gemm_nt_q" }; + const std::vector as = { "qkv_norm_rope_kv_store", "attn_paged", "quant_act_i8", + "gemm_nt_q", "all_reduce", "rmsnorm_quant_i8", + "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q", + "all_reduce" }; + pf(folded, fs, true); + folded_bare.insert(folded_bare.end(), fs.begin(), fs.end()); + pf(apart, as, true); + apart_tall.insert(apart_tall.end(), as.begin(), as.end()); if (l < L - 1) { + folded.push_back("prefetch"); + apart_tall.push_back("rmsnorm_quant_i8"); + folded_bare.push_back("ar_rmsnorm_quant_i8"); folded.push_back("ar_rmsnorm_quant_i8"); apart.push_back("rmsnorm_quant_i8"); } else { - for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) folded.push_back(s); - for (const char* s : { "rmsnorm", "add", "scale" }) apart.push_back(s); + folded.push_back("prefetch"); /* the lm_head's */ + for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) { + folded.push_back(s); + folded_bare.push_back(s); + } + for (const char* s : { "rmsnorm", "add", "scale" }) { + apart.push_back(s); + apart_tall.push_back(s); + } } } - for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) { - folded.push_back(s); - apart.push_back(s); - } + for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) + for (auto* v : { &folded, &apart, &apart_tall, &folded_bare }) v->push_back(s); /* a decode step folds */ CHECK_EQ(join(gemma4_w4_step({}, 4)), join(folded)); + /* where the library refuses `prefetch`, no reads */ + CHECK_EQ(join(gemma4_w4_step({ "prefetch" }, 4)), join(folded_bare)); auto declare4 = [](RadBuilder& b) { const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); @@ -4662,14 +4696,35 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ CHECK_EQ(fold_hi(b, &n_ar), 16); CHECK_EQ(n_ar, 2 * L - 1); - /* a verify's height folds (libr4d's tail form) and a step past 16 rows issues the pair */ + /* 20 MB of gate_up beside the attention's reduction and of the next layer's q beside the + * feed-forward's, and 9 MB of down_proj beside the attention */ + int n_pf = 0, n_pf9 = 0; + for (const auto& o : b.ops) + if (o.op == "prefetch") { + ++n_pf; + if (pint(&o, "bytes") == (int64_t)9 << 20) ++n_pf9; + else CHECK_EQ(pint(&o, "bytes"), (int64_t)20 << 20); + } + CHECK_EQ(n_pf, 3 * L); + CHECK_EQ(n_pf9, (int)L); + + /* a verify's height folds (libr4d's tail form) and a step past 16 rows issues the pair; the + * prefetches ride a decode step's (a verify's) 16 rows, never a prompt's rows and not a step + * past 16 */ const int32_t out[1] = { 127 }; for (int rows : { 16, 128 }) { RadBatch tall = one_prompt(rows, out); RadCtx c; c.b = &b; c.rank = 0; c.world = 4; c.batch = &tall; gemma4_bf16::step(&c, &tall); CHECK(c.step_fail.empty()); - CHECK_EQ(join(issued_ops(b, c)), join(rows <= 16 ? folded : apart)); + /* a prompt's rows: no reads */ + CHECK_EQ(join(issued_ops(b, c)), join(rows <= 16 ? folded_bare : apart_tall)); + /* the same rows as a decode step (a verify's) take them, up to 16 */ + tall.phase = RAD_PHASE_DECODE; + RadCtx d; d.b = &b; d.rank = 0; d.world = 4; d.batch = &tall; + gemma4_bf16::step(&d, &tall); + CHECK(d.step_fail.empty()); + CHECK_EQ(join(issued_ops(b, d)), join(rows <= 16 ? folded : apart_tall)); } @@ -4841,6 +4896,7 @@ TEST(gemma4_31b_declares_dflash_as_a_block_drafter_past_its_trunk) { CHECK_OK(gemma4_bf16::probe(&meta, &p)); CHECK_EQ(p.draft_depth, 15); CHECK_EQ(p.draft_depth_fixed, 1); + CHECK_EQ(p.chain_pays, 1); /* no speculation: no drafter, no taps */ RadBuilder b0; @@ -5133,8 +5189,12 @@ TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_sec RadBuilder b; CHECK_OK(model(b, false)); CHECK(noted(b, "prefill overlap: a step of 1024 rows or more runs as two slices")); - REQUIRE(b.concurrent.size() == 1); + /* `h`, and slice A's context end a KV group the attention reads (per-slice + * attention: the sliding and the global class) */ + REQUIRE(b.concurrent.size() == 3); CHECK_EQ(b.concurrent[0], (rad_buf)buf_named(b, "h")); + CHECK_EQ(b.concurrent[1], (rad_buf)buf_named(b, "slice_used_0")); + CHECK_EQ(b.concurrent[2], (rad_buf)buf_named(b, "slice_used_1")); RadBatch batch = one_prompt(k.T, out); RadCtx c; run(b, c, batch); @@ -5148,8 +5208,13 @@ TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_sec if (i.lane != 1) continue; const RecOp* o = b.op_of(i.op); REQUIRE(o != nullptr); - if (o->op == "all_reduce") lane1.push_back(i.n); - else ++other1; + if (o->op == "all_reduce") { + lane1.push_back(i.n); + /* the narrow launch beside compute, not the wide one op_ar resolves to */ + CHECK_EQ(pint(o, "overlap"), 1); + } else { + ++other1; + } } CHECK_EQ(other1, 0); if (k.cut == 0) { @@ -5177,6 +5242,14 @@ TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_sec CHECK(wc.step_fail.empty()); for (const auto& i : wc.issues) CHECK_EQ(i.lane, 0); std::map sliced = rows_by_op(b, c, k.T), whole = rows_by_op(w, wc, k.T); + if (k.cut) { + /* attention once a slice, slice A's over its context end: one kv_len_trim a KV + * group, which the whole step has no use for */ + CHECK_EQ((int)ns_of(b, c, "kv_len_trim").size(), 2); + CHECK_EQ((int)ns_of(b, c, "attn_paged").size() + (int)ns_of(b, c, "attn_paged_qrow").size(), + 2 * (int)L); + sliced.erase("kv_len_trim"); + } if (world == 2 && k.cut == 0) { /* At two ranks on the exact wire a step that runs whole folds all but two of its * reductions -- the embedding's and the last layer's feed-forward -- into its @@ -5190,21 +5263,53 @@ TEST(a_gemma4_31b_prefill_step_runs_as_two_slices_with_its_reductions_on_the_sec CHECK_EQ((int)ns_of(b, c, "cast").size(), k.cut ? 6 : 3); /* three taps, a slice each */ } - /* a decode step runs whole: every reduction on lane 0, nothing on lane 1 */ - RadBuilder b; - CHECK_OK(model(b, false)); - RadBatch d = decode_batch(); - RadCtx c; - run(b, c, d); - CHECK(c.step_fail.empty()); - CHECK(c.joins.empty()); - for (const auto& i : c.issues) CHECK_EQ(i.lane, 0); - /* folded where the plugin declares the fold at this rank count (two ranks; four with the - * four-rank junction), every junction but the last layer's feed-forward one */ - bool fold = false; - for (const auto& o : b.ops) fold = fold || o.op == "ar_rmsnorm_quant_i8"; - CHECK(fold || world == 4); - CHECK_EQ(count_issued(issued_ops(b, c), "ar_rmsnorm_quant_i8"), fold ? 2 * (int)L - 1 : 0); + /* a library without kv_len_trim: the slices keep each layer's attention whole between them, + * with only `h` out of the arena's sharing and the reductions still on lane 1 */ + { + const int32_t out[1] = { 4095 }; + RadBuilder b; + b.undeclared.insert("kv_len_trim"); + CHECK_OK(model(b, false)); + REQUIRE(b.concurrent.size() == 1); + CHECK_EQ(b.concurrent[0], (rad_buf)buf_named(b, "h")); + RadBatch batch = one_prompt(4096, out); + RadCtx c; + run(b, c, batch); + CHECK(c.step_fail.empty()); + CHECK_EQ(races(b, c), 0); + CHECK(ns_of(b, c, "kv_len_trim").empty()); + CHECK_EQ((int)ns_of(b, c, "attn_paged").size() + (int)ns_of(b, c, "attn_paged_qrow").size(), + (int)L); + int lane1 = 0; + for (const auto& i : c.issues) lane1 += i.lane == 1; + CHECK_EQ(lane1, 4 * (int)L); + } + + /* a decode step runs whole: every reduction on lane 0; the prefetches beside them + * (prefetch_beside) follow lane 0's GEMM before each -- on lane 0 itself where launches + * chain (prefetch_lane0), else on lane 1 behind a join from that GEMM */ + for (const bool pf_lane0 : { false, true }) { + const ChainOn chain(pf_lane0); + RadBuilder b; + CHECK_OK(model(b, false)); + RadBatch d = decode_batch(); + RadCtx c; + run(b, c, d); + CHECK(c.step_fail.empty()); + const std::vector ops = issued_ops(b, c); + int n_pf = 0; + for (size_t i = 0; i < c.issues.size(); ++i) { + const bool pf = ops[i] == "prefetch"; + CHECK_EQ(c.issues[i].lane, pf && !pf_lane0 ? 1 : 0); + if (!pf) continue; + ++n_pf; + CHECK(i > 0 && ops[i - 1] == "gemm_nt_q" && ordered(c, i - 1, i)); + } + CHECK_EQ(n_pf, 3 * (int)L); + CHECK_EQ((int)c.joins.size(), pf_lane0 ? 0 : n_pf); + CHECK_EQ(races(b, c), 0); + CHECK_EQ(count_issued(ops, "ar_rmsnorm_quant_i8"), 2 * (int)L - 1); + } } /* the overlap needs the fused junctions: a bf16 trunk keeps its chain and runs whole */ @@ -5389,6 +5494,7 @@ TEST(gemma4_31b_declares_redhats_dflash2_from_the_speculators_layout) { CHECK_OK(gemma4_bf16::probe(&meta, &p)); CHECK_EQ(p.draft_depth, 7); CHECK_EQ(p.draft_depth_fixed, 1); + CHECK_EQ(p.chain_pays, 1); /* and with DFlash2 */ for (int world : { 1, 4 }) for (int head8 = 0; head8 < 2; ++head8) { @@ -5516,6 +5622,74 @@ TEST(gemma4_31b_dflash2_folds_each_residual_add_into_the_next_norm) { } } +/* DFlash2's query pass reads the next GEMM's weight into the cache beside each of its all-reduces + * (prefetch_beside, rad_arch.h): the layer's gate_up beside the attention's, the next layer's q -- + * after the last layer, the draft head -- beside the feed-forward's, and o's beside the attention, + * 20 MB each, after the GEMM before it: on lane 0 where launches chain (prefetch_lane0), else on + * lane 1 behind a join. One rank has no reduction to sit beside and declares none, and neither + * does a library without `prefetch`. */ +TEST(gemma4_31b_dflash2_query_pass_prefetches_beside_its_all_reduces) { + G431Df2 f; + const RadModelMeta meta = f.meta(); + const int L = 5; + for (int world : { 1, 4 }) + for (int k = 0; k < 4; ++k) { + const int off = k & 1, pf_lane = k < 2 ? 1 : 0; /* lane 0 where launches chain */ + const ChainOn chain(pf_lane == 0); + RadBuilder b; + g431df2_encs(b, true); + if (off) b.undeclared.insert("prefetch"); + RadBuildCtx ctx = build_ctx(0, world); + ctx.max_tok = 2048; + ctx.max_spec = 7; + const int rc = gemma4_bf16::declare(&b, &meta, &ctx); + REQUIRE_EQ(rc, RAD_OK); + const auto qry = query_pass(b, 1, 8, 7); + const auto v = run_passes(b, gemma4_bf16::step, { qry.get() }, 0, world); + REQUIRE(steps_ok(v)); + const RadCtx& c = *v[0]; + const std::vector ops = issued_ops(b, c); + std::vector read; + for (size_t i = 0; i < c.issues.size(); ++i) { + if (ops[i] != "prefetch") { + CHECK_EQ(c.issues[i].lane, 0); + continue; + } + CHECK_EQ(c.issues[i].lane, pf_lane); + size_t g = i; /* the GEMM before this read (and any read issued with it) */ + while (g > 0 && ops[g - 1] == "prefetch") --g; + CHECK(g > 0 && ops[g - 1] == "gemm_nt_q" && + ordered(c, g - 1, i)); + CHECK(i + 1 < ops.size() && + (ops[i + 1] == "all_reduce" || ops[i + 1] == "qkv_norm_rope_kv_store" || + ops[i + 1] == "prefetch")); + const RecOp* o = b.op_of(c.issues[i].op); + REQUIRE(o != nullptr && o->w.size() == 1); + CHECK_EQ(pint(o, "bytes"), (int64_t)20 << 20); + read.push_back(b.weights[o->w[0] - 1].name); + } + CHECK_EQ(races(b, c), 0); + if (world == 1 || off) { + CHECK(read.empty()); + continue; + } + /* a layer: o; the feed-forward's coefficient projection and gate_up; the next + * layer's attention coefficient projection and q -- after the last, the draft head */ + REQUIRE_EQ((int)read.size(), 5 * L - 1); + std::vector want; + for (int l = 0; l < L; ++l) { + const std::string bl = "dflash.blk." + std::to_string(l) + "."; + const std::string nx = "dflash.blk." + std::to_string(l + 1) + "."; + for (const std::string& s : { bl + "attn_output", bl + "ffn_conv_proj", + bl + "ffn_gate_up" }) + want.push_back(s); + if (l + 1 < L) { want.push_back(nx + "attn_conv_proj"); want.push_back(nx + "attn_q"); } + else want.push_back("dflash.draft_head"); + } + for (size_t k = 0; k < want.size(); ++k) CHECK(read[k].find(want[k]) == 0); + } +} + /* Every engine step with RedHatAI's DFlash2 behind the trunk lints clean at one, two and four ranks: * decode, a mixed step, a prefill chunk, and a verify step with the drafter's context and query * passes behind it (block 8). */ @@ -6106,6 +6280,7 @@ TEST(qwen35_fp8_dflash2_drafter_takes_a_power_of_two_block) { CHECK_OK(qwen35_fp8::probe(mk.meta(), &p)); CHECK_EQ(p.draft_depth, 7); CHECK_EQ(p.draft_depth_fixed, 1); + CHECK_EQ(p.chain_pays, 0); /* chained launches measured even here */ } } @@ -6342,6 +6517,7 @@ TEST(gemma3_dflash2_drafter_taps_and_block) { CHECK_OK(gemma3::probe(mk.meta(), &p)); CHECK_EQ(p.draft_depth, 7); CHECK_EQ(p.draft_depth_fixed, 1); + CHECK_EQ(p.chain_pays, 0); /* a block drafter, but chained launches never measured */ MetaKV plain = gemma3_meta(); RadArchProbe q{}; CHECK_OK(gemma3::probe(plain.meta(), &q)); @@ -6840,6 +7016,7 @@ TEST(llama_reads_its_drafters_taps_and_refuses_what_dspark_does_not_implement) { CHECK_OK(llama_fp8::probe(mk.meta(), &p)); CHECK_EQ(p.draft_depth, 7); CHECK_EQ(p.draft_depth_fixed, 1); + CHECK_EQ(p.chain_pays, 0); } /* One graph, two descriptors: llama_dense_fp8 serves the dense checkpoint a recipe quantises @@ -7934,7 +8111,9 @@ struct ArchCases { lfm2_bf16::step, 0, {}, 0x1775b188dc4a5120ull); /* The first three moved only by the attn_qkv name map each layer declares to ask whether * the container holds q, k and v as one linear: with those maps left out of the hash they - * are the earlier pins, 0xafc23087c634a537, 0x719fa07788f8b98a and 0x93b174ab52cc0d31. */ + * are the earlier pins, 0xafc23087c634a537, 0x719fa07788f8b98a and 0x93b174ab52cc0d31. + * The two-rank ones moved with the weight reads beside the reductions (prefetch_beside; + * from 0xade9c0ccfad1fd47 and 0x8808d46c04f12205). */ add("gemma4_bf16", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, gemma4_bf16::step, 0, {}, 0x2ba2f4943031468full); @@ -7943,13 +8122,13 @@ struct ArchCases { gemma4_bf16::step, 0, {}, 0x2e4c6e3235dd3802ull); add("gemma4_bf16, w4a8, two ranks", [this, sc, g4w4](RadBuilder* b) { g4w4(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, - nullptr, 0, {}, 0xade9c0ccfad1fd47ull); + nullptr, 0, {}, 0x3a160b13b3a80d4eull); add("gemma4_bf16, w4a8, fused qkv", [this, sc, g4qkv](RadBuilder* b) { g4qkv(b); auto c = sc(1, 0); return gemma4_bf16::declare(b, &g4, &c); }, gemma4_bf16::step, 0, {}, 0x3913aca59733d0e2ull); add("gemma4_bf16, w4a8, fused qkv, two ranks", [this, sc, g4qkv](RadBuilder* b) { g4qkv(b); auto c = sc(2, 0); return gemma4_bf16::declare(b, &g4, &c); }, - nullptr, 0, {}, 0x8a9935e773f546efull); + nullptr, 0, {}, 0x7be4844610b039d8ull); add("gemma4", [this, sc](RadBuilder* b) { auto c = sc(1, 0); return gemma4::declare(b, &g4m, &c); }, gemma4::step, 0, {}, 0x0f227f5853b6488cull); diff --git a/tests/build_test.cpp b/tests/build_test.cpp index 3f4d2242..4185d8aa 100644 --- a/tests/build_test.cpp +++ b/tests/build_test.cpp @@ -1566,6 +1566,46 @@ TEST(a_two_plane_weight_needs_a_kernel_that_joins_its_planes) { } } +/* A kernel that reads a weight's stored bytes without interpreting them (libr4d's prefetch into + * the cache) answers RAD_LAYOUT_ANY: it takes the form another kernel chose, declared before it or + * after, and claims none, so it never conflicts; a weight only it reads is stored as it is. */ +TEST(a_kernel_that_reads_any_stored_form_claims_none) { + NEED_EXTRA(reg) + const RadParam p[] = { RAD_RANGE("M", 1, 16), RAD_INT("N", 256), RAD_INT("K", 256), + RAD_STR("dtype", "bf16") }; + auto weight = [](Builder& b) { + RadWeightDecl d{}; + d.dtype = RAD_BF16; + d.rank = 2; + d.shape[0] = 256; + d.shape[1] = 256; + d.access = RAD_ACCESS_PER_TOKEN; + d.group = rad_group_layer(0); + return b.decl_weight("w.bf16", &d); + }; + for (bool any_first : { false, true }) { + Builder b(reg, make_meta(), make_ctx()); + const rad_weight w = weight(b); + rad_op a = 0, t = 0; + if (any_first) a = b.decl_op("t_any", p, 4, &w, 1); + t = b.decl_op("t_lay", p, 4, &w, 1); + if (!any_first) a = b.decl_op("t_any", p, 4, &w, 1); + REQUIRE(a != 0 && t != 0); + CHECK_EQ(std::string(device_row(b.program().op(a), 0)), "t_any_read"); + CHECK_EQ(std::string(device_row(b.program().op(t), 0)), "t_lay_tiled"); + CHECK_OK(b.finish()); + CHECK(b.errors().empty()); + CHECK_EQ(b.program().weight(w)->layout_tag, std::string("tiled")); + } + Builder b(reg, make_meta(), make_ctx()); + const rad_weight w = weight(b); + REQUIRE(b.decl_op("t_any", p, 4, &w, 1) != 0); + CHECK_OK(b.finish()); + CHECK(b.errors().empty()); + CHECK(b.program().weight(w)->layout_tag.empty()); + CHECK(b.program().weight(w)->identity); +} + namespace { /* A [256, 256] E4M3 weight with one f32 scale per 128x128 tile, declared over both planes. */ From 5e8bae8ae663301f1e0cabbaaea2fe5c2a54eddc Mon Sep 17 00:00:00 2001 From: Ashlyn Date: Tue, 20 Oct 2026 14:55:09 -0500 Subject: [PATCH 125/152] libr4d, arch, deploy: coded overlap all-reduces, multi-user verify tuning, the split junction, a compose file The prefill overlap's lane all-reduces coded losslessly at ~12.2 bits a value; the verify step's GEMM, norm and all-reduces tuned for 17-64 rows; at 4-16 rows each GPU norms its own rows between a reduce-scatter and an int8 all-gather; deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml. Squashed from: - libr4d: the four-rank exact two-shot coded at ~12.2 bits a bf16 value, for the lane row - libr4d: the prefill overlap's lane all-reduces coded by default - libr4d: decode-sized two-shots take fewer blocks - libr4d: gemm_w4a8_nt_m64 at multi-user verify heights (33-64 rows) -- narrower row tiles, wider N - libr4d: rmsnorm_quant_i8's register form at 512 threads too (33 to 72-120 rows) - libr4d: ar_rmsnorm_quant_i8_4rank's `sp`, the all-reduce split around the junction - arch/gemma4_bf16: the 31B's junctions take libr4d's `sp` at 4-16 rows at four ranks - deploy/compose, README: Gemma 4 31B with RedHatAI's DFlash2 drafter on four cards Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +- arch/gemma4_bf16/gemma4_bf16.cpp | 67 ++++- deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml | 33 +++ docs/OPS.md | 10 +- libr4d/r4d.h | 17 +- libr4d/r4d_ar_entry.hip | 51 +++- libr4d/r4d_ar_twoshot_Nrank_exact.hip | 278 ++++++++++++++++++++ libr4d/r4d_gemm_w4a8_nt_m64.hip | 36 +++ libr4d/r4d_rmsnorm_quant_i8.hip | 277 ++++++++++++++++++- libr4d/r4d_rows.cpp | 11 +- libr4d/r4d_selftest.cpp | 162 +++++++++++- tests/arch_test.cpp | 49 +++- 12 files changed, 950 insertions(+), 44 deletions(-) create mode 100644 deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml diff --git a/README.md b/README.md index 9689564e..887e82f9 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,9 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | | Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` | -| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (20 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-w4a8-df.yaml` | +| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` | | Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` | +| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` | diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 01459f5f..65d5e0e6 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -888,16 +888,40 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai * taller step issues the pair. */ static constexpr int64_t kArOneShotElems = 524288; static constexpr int64_t kAr4FoldRows = 16; +/* From kArSpMinRows rows to the same band's top, libr4d's four-rank row takes `sp` instead: the + * all-reduce split around the junction. Each rank reduces only the rows it owns (a quarter, in + * rank order), runs the junction on them and gathers the int8 codes the next GEMM reads, so the + * second hop carries a byte a column instead of two and the junction a quarter of the rows. The + * fold and the sums are the whole form's, so q and the scales are byte for byte the same; the + * residual stream then holds this rank's rows only, which is all the next junction reads. A + * junction whose stream anything else reads next asks for the residual on every row too (sp 2): + * the layers the drafter taps, and the last layer's attention junction, since that layer's + * feed-forward closes with its own all-reduce, post-norm and add over every row. One launch at a + * time on 4x R9700 (2026-10-19): 19.8 against 21.9 us at 4 rows of 5376 (the one-shot fold), 22.9 + * against 24.5 at 8 and 30.8 against 34.9 at 16 (the tail), 72.3 against 89.2 at 64. Below 4 rows + * a rank would idle (31.7 against 18.7 us at one). + * + * In the engine it pays only where it replaces the fold: a DFlash2 verify (8 rows) ran 402 / 297 / + * 216 / 603 tok/s code / prose / story / long against 392 / 290 / 210 / 585, replies identical, + * but steps of 24-64 rows, where the pair runs instead, lost ~10% under load (4 users 588 against + * 698 aggregate, 8 users 781 against 867; 12 users even; 4x R9700, 2026-10-19). So it serves to + * kArSpMaxRows, the fold's band, within the one-shot's. */ +static constexpr int64_t kArSpMinRows = 4; +static constexpr int64_t kArSpMaxRows = 16; struct G4Junction { rad_op op = 0; rad_op op_ar = 0; /* the same with the exact all-reduce of `x` in front, or 0 */ int64_t ar_rows = 0; /* the most rows op_ar serves: the step's at two ranks, a band at four */ + rad_op op_sp = 0; /* ...with the all-reduce split around it (four ranks), or 0 */ + int64_t sp_hi = 0; /* the most rows op_sp serves, from kArSpMinRows */ rad_buf x = 0, res = 0, q8 = 0, s8 = 0; rad_weight w = 0, wp = 0, sc = 0; + /* `full_res`: something besides the next junction reads the residual stream after this one, + * so the split form must leave it on every row. */ int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_, - rad_weight wp_, rad_weight sc_, const G4Linear& into) { + rad_weight wp_, rad_weight sc_, const G4Linear& into, bool full_res = false) { x = x_; res = res_; w = w_; wp = wp_; sc = sc_; q8 = into.q8; s8 = into.s8; if (!into.quant || into.shared_in || !q8 || !s8 || !w || (sc && !wp) || ((wp || sc) && !res)) return RAD_E_INVAL; @@ -934,11 +958,32 @@ struct G4Junction { rad_op_writes(b, op_ar, wa, 4); ar_rows = hi; } + /* The split form from kArSpMinRows to kArSpMaxRows rows. It needs the post-norm, as + * every trunk junction past the first has; `x` is declared written, as the fold's. */ + const int64_t top = std::min( + std::min(g.max_tok, kArOneShotElems / g.n_embd), kArSpMaxRows); + if (op_ar && four && wp && top >= kArSpMinRows) { + const RadParam ps[] = { RAD_RANGE("M", 1, top), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_INT("world_size", g.world), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd), + RAD_INT("sp", full_res ? 2 : 1) }; + op_sp = rad_decl_op(b, "ar_rmsnorm_quant_i8", ps, (int)(sizeof ps / sizeof ps[0]), + ws, nw); + if (op_sp) { + const rad_buf wa[4] = { x, q8, s8, res }; + rad_op_reads (b, op_sp, rd, 2); + rad_op_writes(b, op_sp, wa, 4); + sp_hi = top; + } + } } return RAD_OK; } + /* The most rows a step may have for step(..., true): the fold's band, and the split form's. */ + int64_t ar_top() const { return op_sp ? std::max(ar_rows, sp_hi) : ar_rows; } void step(RadCtx* c, int64_t T, bool with_ar = false) const { - RAD_ISSUE_N(c, with_ar ? op_ar : op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w), + const rad_op o = !with_ar ? op : (op_sp && T >= kArSpMinRows && T <= sp_hi) ? op_sp : op_ar; + RAD_ISSUE_N(c, o, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w), brows(q8, T), brows(s8, T), RAD_NONE, wp ? RAD_W(wp) : RAD_NONE, sc ? RAD_W(sc) : RAD_NONE); } @@ -1941,13 +1986,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c ok = m.j0.op != 0; for (int64_t l = 0; ok && l < m.n_main; ++l) { Layer& lay = m.layers[(size_t)l]; + /* the split form's residual on every row: before the last layer's feed-forward + * (its own reduction, post-norm and add over every row), and where the drafter + * taps the stream */ + bool tapped = false; + for (int t = 0; t < m.n_taps; ++t) tapped = tapped || m.tap_layer[t] == (int)l; RAD_ARCH_TRY(lay.j_am.declare(b, g, m.b_h, m.b_x, lay.mlp.w_norm, lay.attn.w_post, 0, - lay.mlp.ln_gu)); + lay.mlp.ln_gu, l + 1 == m.n_main)); ok = lay.j_am.op != 0; if (ok && l + 1 < m.n_main) { const Layer& nx = m.layers[(size_t)l + 1]; RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm, lay.mlp.w_post, - lay.w_scalar, nx.attn.ln_in())); + lay.w_scalar, nx.attn.ln_in(), tapped)); ok = lay.j_ma.op != 0; } } @@ -1958,8 +2008,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c for (int64_t l = 0; ar && l < m.n_main; ++l) { const Layer& lay = m.layers[(size_t)l]; ar = lay.j_am.op_ar != 0 && (l + 1 >= m.n_main || lay.j_ma.op_ar != 0); - if (ar) rows = std::min(rows, lay.j_am.ar_rows); - if (ar && l + 1 < m.n_main) rows = std::min(rows, lay.j_ma.ar_rows); + if (ar) rows = std::min(rows, lay.j_am.ar_top()); + if (ar && l + 1 < m.n_main) rows = std::min(rows, lay.j_ma.ar_top()); } m.fuse_ar = ar; m.ar_rows = ar ? rows : 0; @@ -2178,6 +2228,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (m.fuse && (g.world == 2 || g.world == 4)) { if (!m.fuse_ar) rad_note(b, "residual junctions: the all-reduce in front of each issued apart"); + else if (g.world == 4 && m.layers[0].j_am.op_sp) + rad_note(b, "residual junctions: the all-reduce in front of each folded in at steps of " + "%lld rows or fewer (libr4d's four-rank row: the fold to %lld rows, the " + "all-reduce split around the junction from %lld), issued apart above", + (long long)m.ar_rows, (long long)kArSpMinRows - 1, (long long)kArSpMinRows); else if (g.world == 4) rad_note(b, "residual junctions: the all-reduce in front of each folded in at steps of " "%lld rows or fewer (the four-rank one-shot), issued apart above", diff --git a/deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml b/deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml new file mode 100644 index 00000000..24b170ef --- /dev/null +++ b/deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml @@ -0,0 +1,33 @@ +# Gemma 4 31B-it on four cards: int4 trunk (round-to-nearest with a scale search, from the bf16 +# checkpoint; q, k and v as one linear) with int8 activations and lm_head, RedHatAI's DFlash2 +# speculator merged in (gemma-4-31B-it-speculator.dflash2: block 8, 7 drafts a pass, int8 head), and +# the vision tower. Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe, or downloaded +# from https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2. The drafter +# serves the depth it was trained at (`auto`). Sampling defaults are the checkpoint's +# generation_config; thinking is switched per request (chat_template_kwargs). +# +# --tp 4 over four cards; chained launches, the weight reads beside the collectives and the prefill +# overlap turn themselves on there (each has its RADIANCE_* override for an A/B, none needed here). +# A prompt alone takes 8192-token prefill chunks; beside other users a chunk takes at most 512 +# tokens of a step, with one decode-only step after it, so a long prompt holds the others up by a +# fraction of a chunk rather than all of it. 16 sequences, as measured below. +# +# On 4x R9700 (PCIe 4.0 x16), 2026-10-20: one user 390 code / 288 prose / 208 story tok/s, and +# 590 after a 6442-token prompt (prefill 5962 tok/s); 302 / 512 / 658 / 835 / 981 tok/s aggregate +# at 1 / 2 / 4 / 8 / 16 users (BetterBench, thinking off). +# +# Measured with the host CPU's performance governor and its idle states past C1 off. The cards' +# peer-to-peer traffic crosses the root complex, so the host's power state shows in every step, and +# a compose file can't set it. +name: radiance-gemma4-31b-w4a8-df2-tp4 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-gemma4-31b-w4a8-df2-tp4 + command: > + --model /models/gemma4-31b-dense-w4a8-df2-qkv.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 4 --max-num-seqs 16 --max-model-len 65536 --kv-cache-dtype fp8 + --num-speculative-tokens auto --max-num-batched-tokens 8192 + --busy-prefill-chunk 512 --prefill-interleave 1 + --temp 1.0 --top-p 0.95 --top-k 64 diff --git a/docs/OPS.md b/docs/OPS.md index 7e7a3d26..25f4d5ca 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2171,7 +2171,7 @@ device code. | `ar_rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `ar_rmsnorm_post_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w | | `ar_rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | -| `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? | +| `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt `sp`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? | | `ar_hc_write` | `M`(range) `n` `hc` `world_size` `dtype` `wire`/opt | `y`:inout, `inj`, `h`:inout | | `ar_gather_hc_write` | `M`(range) `n` `hc` `top_k` `world_size` `dtype` `act`/opt `wire`/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`?, `y`:inout, `inj`, `h`:inout | | `ar_ln_had_quant_i8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | @@ -2183,6 +2183,14 @@ the message and the input, and the reduced sum lands in it. `ar_rmsnorm_had_quant_i8g` is `ar_rmsnorm_quant_fp8` with `rmsnorm_had_quant_i8g`'s quantiser: `x` and the residual are the same bytes, and the codes are int8 for a weight at `i8a8h`. +`sp` on `ar_rmsnorm_quant_i8` (0 when absent) lets a row split the all-reduce around the +junction: reduce-scatter, the junction on the rows this rank owns (`M` split evenly over the +ranks in rank order), all-gather of what the next GEMM reads. At 1 the op promises `q` and +`scale` on every row and `residual` on this rank's rows only; at 2 `residual` on every row too; +either way `x` is left unspecified. A row may always run the whole form, which keeps every +promise. The caller must not read a residual row it does not own after an `sp` 1 junction +until a junction or reduction writes it whole again. + The norm-carrying forms are two-rank only. `ar_hc_write` and `ar_gather_hc_write` also have an exact-wire four-rank form. At other widths the arch blocks issue the plain ops. diff --git a/libr4d/r4d.h b/libr4d/r4d.h index f1cbc8e6..3a7f50bb 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -432,6 +432,17 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, long gate, long gate_ctr, long chain); +// The four-rank exact two-shot with both pushes coded losslessly at ~12.2 bits a bf16 value (the +// same bytes out; r4d_ar_twoshot_Nrank_exact.hip). r4d_ar_twoshot_coded_ok says whether a message +// and slot fit the coded form: bf16, shards of whole 256-value waves, two coded regions a slot. +int r4d_ar_twoshot_coded_ok(long n_elem, long dtype, long world, long slot_stride16); +void r4d_ar_twoshot_4rank_exact_coded(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_flags0, long peer_flags1, long peer_flags2, + long my_scratch, long my_flags, long seq_ctrs, + long slot_stride16, long inp, long out, long n_elem, + long rank, long stream, long nblocks, long nthreads, + long drain, long acq, long pub, long gate, long gate_ctr, + long chain); void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, @@ -794,7 +805,9 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags // arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, the // engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h), and, with // `tail_nbt` blocks (positive), the standalone two-shot on that many with the junction as its tail, -// counting on the two words at `tail_ctr` (ar_rmsnorm_quant_i8_tail_kernel). +// counting on the two words at `tail_ctr` (ar_rmsnorm_quant_i8_tail_kernel). With `sp` 1 or 2 the +// all-reduce split around the junction instead (ar_rmsnorm_quant_i8_sp_kernel): q and S on every +// row, the residual on this rank's rows (every row at 2), `x` left as it came. int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_flags0, long peer_flags1, long peer_flags2, long my_scratch, long my_flags, long seq_ctrs, @@ -803,7 +816,7 @@ int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scratch1, long float wadd, int w_f32, int r_ld, int y_ld, int rank, long stream, int nblocks, int drain, int acq, int pub, long gate, long gate_ctr, long tail_ctr, int tail_nbt, - int chain); + int chain, int sp); // ---- sampling ---------------------------------------------------------------------------------- // diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index cdd6f42f..0f06e23b 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -667,23 +667,27 @@ static int nb_for(long words16, int max_nb) { return (int)nb; } -/* The four-rank exact one-shot's two-shot band (r4d_rad_ar_oneshot_4rank_exact from ts_min), over - * the words of one shard: one block per 672 words, floor 2, - * ceiling max_nb. A two-shot takes two handshakes, each a PCIe round trip a block, so small shards - * want fewer blocks than nb_for's floor of 4: at a DFlash2 verify's 8 rows of 5376 at tp 4 (1344 - * words a shard) two blocks run the exact two-shot in 20.2 us against 22.8 at four, and from 16 - * rows (2688 words, four blocks either way) the two rules agree (4x R9700, a four-card - * microbenchmark of this kernel, 2026-10-17). The block count moves no byte: every word is folded - * by one thread in ascending rank order whatever the grid. */ +/* The four-rank exact two-shot at decode and verify heights (the one-shot row's band from ts_min, + * the junction's tail form, the two-shot row up to kTsDecodeShard words a shard), over the words of + * one shard: one block per 2688 words, floor 2, ceiling 8 (and max_nb). A two-shot takes two + * handshakes, each a PCIe round trip a block, so a block more costs more than its share of the + * bytes saves until the shards are large. One per 672 (the rule before 2026-10-19) launched 16 + * blocks at 64 rows of 5376, where the multi-user verify runs (8 users x DFlash2's 8 rows): on 4x + * R9700, one launch at a time on the real payload, 64 rows took 85.6 us at 16 blocks against 75.3 + * at 4, 32 rows 58.9 at 16 / 47.1 at 8 against 44.2 at 4, 128 rows 143.5 at 16 against 137.9 at 8; + * 8 rows (two blocks either way) 19.6. The block count moves no byte: every word is folded by one + * thread in ascending rank order whatever the grid. */ /* The chained two-shot (r4d_chain.h) where the row resolved with `chain`, for a decode-sized * message only (64 rows of an 8192-wide residual): DFlash2's verify-height reductions. */ static long ar_chain(const RadArgs* a, long numel) { return r4d_geti_or(a, "chain", 0) != 0 && numel <= 64L * 8192L ? 1L : 0L; } +static constexpr long kTsDecodeShard = 43008; /* 256 rows of 5376 at tp 4 */ static int nb_for_shard(long shard16, int max_nb) { - long nb = shard16 / 672; + long nb = shard16 / 2688; if (nb < 2) nb = 2; + if (nb > 8) nb = 8; if (nb > max_nb) nb = max_nb; if (nb > shard16) nb = shard16 > 0 ? shard16 : 1; return (int)nb; @@ -740,7 +744,9 @@ static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) { * flag rounds cost more than the added reduce bandwidth (8 against 16 blocks measured up to 3 % * faster from 2097152 elements on). */ if (shard_nb && in->world == 8 && cap > 8) cap = 8; - c->nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : nb_for(basis, cap); + /* a decode-sized shard takes the decode rule (nb_for_shard), a prompt-sized one nb_for's */ + c->nblocks = cfgv.nblocks > 0 ? cfgv.nblocks + : (shard_nb && basis <= kTsDecodeShard) ? nb_for_shard(basis, cap) : nb_for(basis, cap); if (c->nblocks > in->max_blocks) c->nblocks = in->max_blocks; return RAD_OK; } @@ -1114,6 +1120,25 @@ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) { if (words16 % c.in->world) return RAD_E_SHAPE; if (2 * (c.numel * c.in->esize) / c.in->world > c.in->slot_bytes) return RAD_E_SCRATCH; const ArInst* in = c.in; + /* A reduction beside compute (overlap 1) carries its pushes coded at ~12.2 bits a bf16 value + * (r4d_ar_twoshot_Nrank_exact.hip, the coded form), at 4 blocks of 1024 threads, wherever the + * message fits that form; the same bytes either way. The 31B's prefill (4x R9700, a + * 5033-token prompt): 5724 -> 5949 tok/s (+3.9%), every reply identical; 8 x 512 gave +2.1%, + * 16 x 256 +1.3%, 6 x 1024 -1.9% (the blocks crowd the GEMM beside them). `coded` 0, a launch + * parameter no declaration carries, keeps the plain wire: r4d_selftest's plain arm. */ + const bool lane = r4d_geti_or(a, "overlap", 0) == 1; + if (lane && r4d_geti_or(a, "coded", 1) != 0 && + r4d_ar_twoshot_coded_ok(c.numel, in->dtype, 4, in->slot16)) { + const long gate = link_gate(a), early = in->host ? 0L : gate; + R4D_TRY("ar_twoshot_4rank_exact (coded)", + r4d_ar_twoshot_4rank_exact_coded(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], + in->peer_flags[0], in->peer_flags[1], in->peer_flags[2], + in->my_scratch, in->my_flags, in->my_seq, in->slot16, + c.inp, c.out, c.numel, in->rank, (long)(uintptr_t)s, + 4, 1024, c.drain, c.acq, c.pub, early, + early ? in->gate_ctr : 0L, ar_chain(a, c.numel))); + return early ? RAD_LINK_ENDED : RAD_OK; + } /* The kernel ends the hold after its second handshake (its reduce is fused with the phase-2 * push); through the host mailbox early stays 0 and the engine releases by barrier. */ const long gate = link_gate(a), early = in->host ? 0L : gate; @@ -1548,6 +1573,10 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) if (tail_nbt > in->max_blocks) tail_nbt = in->max_blocks; } const long tail_ctr = in->my_seq + (2L * in->max_blocks + 8) * 4; + /* `sp` (0 unless asked): the all-reduce split around the junction, P2P only. The host mailbox + * runs the whole form, which leaves every byte the split one does. */ + const long long sp = r4d_geti_or(a, "sp", 0); + if (sp < 0 || sp > 2) return RAD_E_INVAL; /* The junction after the last handshake is local, so either form releases there. */ const long gate = link_gate(a), early = in->host ? 0L : gate; const int e = r4d_ar_rmsnorm_quant_i8_4rank( @@ -1559,7 +1588,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s) (int)v.M, (int)v.K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (int)in->rank, (long)(uintptr_t)s, nblocks, cfgv.drain, cfgv.acq, cfgv.pub, early, early ? in->gate_ctr : 0L, tail_ctr, tail_nbt, - r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0); + r4d_geti_or(a, "chain", 0) != 0 ? 1 : 0, in->host ? 0 : (int)sp); if (e != 0) return RAD_E_SHAPE; return early ? RAD_LINK_ENDED : RAD_OK; } diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index cdb2f249..2b79e64b 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -158,6 +158,222 @@ __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( if (CHAIN) r4d_chain_done(); } +// ---- the coded form: both pushes carry ~12.2 bits a bf16 value instead of 16, losslessly +// +// The prefill overlap's reductions are link-bound, and a residual stream's bf16 words have few +// distinct exponents: on the 31B (4x R9700, 64 groups of 512 x 5376 values from a 9.9k-token +// prefill) 2.5-3.2 bits of exponent entropy against 8 stored. A chunk is one int4 word (8 +// values); 8 consecutive chunks (64 values) form a group that shares a base exponent, and each +// value keeps its sign, its 7 mantissa bits and a 4-bit exponent offset (0 = an exact zero, 1..15 = +// base .. base + 14), 8 values to 3 dwords. A group holding a subnormal, an inf or NaN, or an +// exponent range past 14 (0.02% of groups there) is stored raw in a shadow area, its base byte +// 0xFF. A region (one source's shard in an owner's scratch) is [3 dwords a chunk][a base byte a +// group][the shadow, 16 bytes a chunk]; A and B are two regions in a slot. A wave codes 32 +// consecutive chunks: the group's exponents meet by lane shuffles, and the packed dwords are +// redistributed so every store a wave makes is contiguous, keeping the P2P writes coalesced. +// +// Decoding gives back the same bf16 values, so the reduce folds the same numbers in the same rank +// order: the bytes are the plain kernel's. Four-card microbenchmark (the real payload above, the +// two-shot of a 1024-row slice beside the w4a8 prefill GEMM): byte-identical; the reduction 1383 +// us at the plain lane launch (2 x 256) against 996 us coded at 4 x 1024, with the GEMM beside it +// 746 -> 724 us. Below 1024 threads a launch codes too slowly (2 x 256: 2492 us). +__device__ __forceinline__ unsigned r4d_arc_shfl(unsigned v, int src) { + return (unsigned)__builtin_amdgcn_ds_bpermute(src << 2, (int)v); +} +struct R4dArcEnc { unsigned w[3]; unsigned base; }; +// Code this lane's chunk; every lane of the wave calls (a lane past the end with valid false). +__device__ __forceinline__ R4dArcEnc r4d_arc_enc(int4 v, bool valid) { + const unsigned d[4] = {(unsigned)v.x, (unsigned)v.y, (unsigned)v.z, (unsigned)v.w}; + unsigned emin = 255u, emax = 0u, bad = 0u; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const unsigned u = (d[i >> 1] >> ((i & 1) * 16)) & 0xffffu; + const unsigned e = (u >> 7) & 0xffu, m = u & 0x7fu; + if (e) { emin = e < emin ? e : emin; emax = e > emax ? e : emax; } + bad |= (unsigned)(e == 0u && m != 0u) | (unsigned)(e == 255u); + } + if (!valid) { emin = 255u; emax = 0u; bad = 0u; } + const int lane = (int)(threadIdx.x & 31u); +#pragma unroll + for (int s = 1; s < 8; s <<= 1) { + const unsigned a = r4d_arc_shfl(emin, lane ^ s), b = r4d_arc_shfl(emax, lane ^ s); + const unsigned c = r4d_arc_shfl(bad, lane ^ s); + emin = a < emin ? a : emin; emax = b > emax ? b : emax; bad |= c; + } + R4dArcEnc r; + const unsigned base = emin == 255u ? 1u : emin; + r.base = (bad || emax > base + 14u) ? 0xFFu : base; + unsigned c[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const unsigned u = (d[i >> 1] >> ((i & 1) * 16)) & 0xffffu; + const unsigned e = (u >> 7) & 0xffu, m = u & 0x7fu, sg = u >> 15; + c[i] = (sg << 11) | (m << 4) | (e ? (e - base + 1u) & 15u : 0u); + } + r.w[0] = c[0] | (c[1] << 12) | (c[2] << 24); + r.w[1] = (c[2] >> 8) | (c[3] << 4) | (c[4] << 16) | (c[5] << 28); + r.w[2] = (c[5] >> 4) | (c[6] << 8) | (c[7] << 20); + return r; +} +__device__ __forceinline__ int4 r4d_arc_dec(const unsigned (&w)[3], unsigned base) { + unsigned c[8]; + c[0] = w[0] & 0xfffu; c[1] = (w[0] >> 12) & 0xfffu; c[2] = (w[0] >> 24) | ((w[1] & 0xfu) << 8); + c[3] = (w[1] >> 4) & 0xfffu; c[4] = (w[1] >> 16) & 0xfffu; c[5] = (w[1] >> 28) | ((w[2] & 0xffu) << 4); + c[6] = (w[2] >> 8) & 0xfffu; c[7] = w[2] >> 20; + unsigned u[8]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + const unsigned off = c[i] & 15u; + u[i] = ((c[i] >> 11) << 15) | ((off ? base + off - 1u : 0u) << 7) | ((c[i] >> 4) & 0x7fu); + } + int4 v; + v.x = (int)(u[0] | (u[1] << 16)); v.y = (int)(u[2] | (u[3] << 16)); + v.z = (int)(u[4] | (u[5] << 16)); v.w = (int)(u[6] | (u[7] << 16)); + return v; +} +struct R4dArcRegion { unsigned* packed; unsigned* bases; int4* shadow; }; +__host__ __device__ constexpr size_t r4d_arc_shadow_off(long SL) { + return ((size_t)12 * SL + (size_t)SL / 8 + 15) & ~(size_t)15; +} +__host__ __device__ constexpr size_t r4d_arc_region_bytes(long SL) { + return (r4d_arc_shadow_off(SL) + (size_t)16 * SL + 255) & ~(size_t)255; +} +__device__ __forceinline__ R4dArcRegion r4d_arc_region(const void* p, int SL) { + char* b = (char*)p; + return R4dArcRegion{(unsigned*)b, (unsigned*)(b + (size_t)12 * SL), (int4*)(b + r4d_arc_shadow_off(SL))}; +} +// A wave's coded chunks [k0, k0 + 32) (k0 a multiple of 32) into ND regions, every store contiguous. +template +__device__ __forceinline__ void r4d_arc_put(R4dArcRegion (&dst)[ND], int k0, const R4dArcEnc& e, + int4 raw, bool valid) { + const int lane = (int)(threadIdx.x & 31u); +#pragma unroll + for (int j = 0; j < 3; ++j) { + const int p = 32 * j + lane, sl = p / 3, wi = p - sl * 3; + const unsigned a0 = r4d_arc_shfl(e.w[0], sl), a1 = r4d_arc_shfl(e.w[1], sl); + const unsigned a2 = r4d_arc_shfl(e.w[2], sl), vs = r4d_arc_shfl(valid ? 1u : 0u, sl); + const unsigned val = wi == 0 ? a0 : wi == 1 ? a1 : a2; + if (vs) { +#pragma unroll + for (int q = 0; q < ND; ++q) dst[q].packed[(size_t)k0 * 3 + p] = val; + } + } + const unsigned b0 = r4d_arc_shfl(e.base, 0), b1 = r4d_arc_shfl(e.base, 8); + const unsigned b2 = r4d_arc_shfl(e.base, 16), b3 = r4d_arc_shfl(e.base, 24); + if (lane == 0 && valid) { +#pragma unroll + for (int q = 0; q < ND; ++q) dst[q].bases[k0 / 32] = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); + } + if (valid && e.base == 0xFFu) { +#pragma unroll + for (int q = 0; q < ND; ++q) dst[q].shadow[k0 + lane] = raw; + } +} +// A wave's chunks [k0, k0 + 32) back from a region; every lane calls. +__device__ __forceinline__ int4 r4d_arc_get(const R4dArcRegion& src, int k0, bool valid) { + const int lane = (int)(threadIdx.x & 31u); + unsigned ld[3]; +#pragma unroll + for (int j = 0; j < 3; ++j) ld[j] = valid ? src.packed[(size_t)k0 * 3 + 32 * j + lane] : 0u; + unsigned w[3]; +#pragma unroll + for (int i = 0; i < 3; ++i) { + const int q = 3 * lane + i, sl = q & 31, j = q >> 5; + const unsigned a0 = r4d_arc_shfl(ld[0], sl), a1 = r4d_arc_shfl(ld[1], sl); + const unsigned a2 = r4d_arc_shfl(ld[2], sl); + w[i] = j == 0 ? a0 : j == 1 ? a1 : a2; + } + const unsigned base = ((valid ? src.bases[k0 / 32] : 0u) >> ((lane >> 3) * 8)) & 0xffu; + if (base == 0xFFu) return valid ? src.shadow[k0 + lane] : make_int4(0, 0, 0, 0); + return r4d_arc_dec(w, base); +} + +// The coded two-shot, bf16 only; the launcher checks that each shard is a whole number of waves' +// 32 chunks and that a slot holds two regions. +template +__device__ __forceinline__ void r4d_ar_twoshot_coded_body( + const int4* __restrict__ in4, R4DArWidePeers peers, + const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, + int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16, + int slot_stride16, int rank, int drain, int acq, int pub, + long long* gate, unsigned int* gate_ctr) { + if (CHAIN) r4d_chain_wait(); + constexpr int NPEERS = WS - 1; + const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; + __shared__ unsigned int s_seq, s_slot; + const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); + r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); + const unsigned int s = s_seq; + const int parity = (int)s_slot; + const int SL = n16 / WS; /* every shard: a multiple of 32 chunks */ + int w = (SL + nb - 1) / nb; + w = (w + 31) & ~31; + const int w0 = b * w; + int w1 = w0 + w; if (w1 > SL) w1 = SL; + const size_t RB = r4d_arc_region_bytes(SL); + const int lane = tid & 31; + + // phase 1: my contribution to each peer-owned shard, coded, into the owner's region A for me + for (int p = 0; p < NPEERS; ++p) { + const int owner = peers.rank[p]; + const int4* src = in4 + (size_t)owner * SL; + R4dArcRegion dst[1] = {r4d_arc_region(peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16, SL)}; + for (int k = w0 + tid; k - lane < w1; k += nt) { + const bool valid = k < w1; + const int4 v = valid ? src[k] : make_int4(0, 0, 0, 0); + r4d_arc_put<1>(dst, k - lane, r4d_arc_enc(v, valid), v, valid); + } + } + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub); + + // reduce my shard (fp32, ascending rank, my own contribution raw from the input), code it once, + // and push it to every peer's region B + R4dArcRegion srcA[WS], dstB[NPEERS]; +#pragma unroll + for (int r = 0; r < WS; ++r) + srcA[r] = r4d_arc_region(my_base + ((size_t)parity * WS + r) * (size_t)slot_stride16, SL); +#pragma unroll + for (int p = 0; p < NPEERS; ++p) + dstB[p] = r4d_arc_region((const char*)(peers.scratch[p] + ((size_t)parity * WS + rank) * (size_t)slot_stride16) + RB, SL); + const int4* own = in4 + (size_t)rank * SL; + int4* my_out = out4 + (size_t)rank * SL; + for (int k = w0 + tid; k - lane < w1; k += nt) { + const bool valid = k < w1; + const int k0 = k - lane; + float acc[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] = 0.0f; +#pragma unroll + for (int r = 0; r < WS; ++r) { + const int4 v = (r == rank) ? (valid ? own[k] : make_int4(0, 0, 0, 0)) : r4d_arc_get(srcA[r], k0, valid); + const __hip_bfloat16* pv = reinterpret_cast(&v); +#pragma unroll + for (int j = 0; j < 8; ++j) acc[j] += (float)pv[j]; + } + int4 o; + __hip_bfloat16* po = reinterpret_cast<__hip_bfloat16*>(&o); +#pragma unroll + for (int j = 0; j < 8; ++j) po[j] = (__hip_bfloat16)acc[j]; + if (valid) my_out[k] = o; + r4d_arc_put(dstB, k0, r4d_arc_enc(o, valid), o, valid); + } + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); + + // assemble: every peer-owned shard from my region B + for (int p = 0; p < NPEERS; ++p) { + const int owner = peers.rank[p]; + const R4dArcRegion src = r4d_arc_region((const char*)(my_base + ((size_t)parity * WS + owner) * (size_t)slot_stride16) + RB, SL); + int4* dst = out4 + (size_t)owner * SL; + for (int k = w0 + tid; k - lane < w1; k += nt) { + const bool valid = k < w1; + const int4 v = r4d_arc_get(src, k - lane, valid); + if (valid) dst[k] = v; + } + } + if (CHAIN) r4d_chain_done(); +} + #define R4D_ARTS_PARAMS const int4* __restrict__ in4, R4DArWidePeers peers, \ const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \ int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff sh, \ @@ -175,6 +391,24 @@ __global__ void r4dchain_ar_twoshot_wide_exact(R4D_ARTS_PARAMS) { } #undef R4D_ARTS_ARGS #undef R4D_ARTS_PARAMS +// The coded form keeps the even split (its launcher checks every shard is whole waves' chunks), so +// it takes the message length, not the plain form's shard table and pieces. +#define R4D_ARTC_PARAMS const int4* __restrict__ in4, R4DArWidePeers peers, \ + const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \ + int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16, int slot_stride16, \ + int rank, int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr +#define R4D_ARTC_ARGS in4, peers, my_base, my_flags, out4, seq_ctrs, n16, slot_stride16, rank, \ + drain, acq, pub, gate, gate_ctr +template +__global__ void r4d_ar_twoshot_coded_kernel(R4D_ARTC_PARAMS) { + r4d_ar_twoshot_coded_body(R4D_ARTC_ARGS); +} +template +__global__ void r4dchain_ar_twoshot_coded(R4D_ARTC_PARAMS) { + r4d_ar_twoshot_coded_body(R4D_ARTC_ARGS); +} +#undef R4D_ARTC_ARGS +#undef R4D_ARTC_PARAMS // --- host side --- template @@ -306,6 +540,50 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee nullptr, 1L, chain != 0); } +/* The coded form's conditions: bf16, a message that shards evenly into whole waves' 32 chunks + * (256 values) a rank, and a slot that holds two coded regions. */ +int r4d_ar_twoshot_coded_ok(long n_elem, long dtype, long world, long slot_stride16) { + if (dtype != 0 || world <= 0 || n_elem % (world * 256) != 0) return 0; + const long SL = n_elem / 8 / world; + return 2 * r4d_arc_region_bytes(SL) <= (size_t)slot_stride16 * 16 ? 1 : 0; +} + +void r4d_ar_twoshot_4rank_exact_coded(long peer_scratch0, long peer_scratch1, long peer_scratch2, + long peer_flags0, long peer_flags1, long peer_flags2, + long my_scratch, long my_flags, long seq_ctrs, + long slot_stride16, long inp, long out, long n_elem, + long rank, long stream, long nblocks, long nthreads, + long drain, long acq, long pub, long gate, long gate_ctr, + long chain) { + constexpr int WS = 4; + if (!r4d_ar_twoshot_coded_ok(n_elem, 0, WS, slot_stride16)) + throw std::runtime_error("all_reduce (coded): message or slot outside the coded form"); + if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce (coded): rank out of range"); + const long n16 = n_elem / 8, SL = n16 / WS; + int nb = (int)nblocks; + if (nb < 1) nb = 4; + if (nb > R4D_AR_WIDE_MAX_BLOCKS) nb = R4D_AR_WIDE_MAX_BLOCKS; + if (nb > SL / 32) nb = (int)(SL / 32); + int nt = (int)nthreads; + if (nt < 256) nt = 256; + if (nt > 1024) nt = 1024; + nt &= ~31; + R4DArWidePeers peers{}; + const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; + const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; + for (int i = 0; i < WS - 1; ++i) { + if (!ps[i] || !pf[i]) throw std::runtime_error("all_reduce (coded): null peer pointer"); + peers.scratch[i] = (int4*)ps[i]; + peers.flags[i] = (unsigned int*)pf[i]; + peers.rank[i] = (i < (int)rank) ? i : i + 1; + } + hipStream_t st = (hipStream_t)stream; + (chain ? r4dchain_ar_twoshot_coded : r4d_ar_twoshot_coded_kernel)<<>>( + (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, (int4*)out, + (unsigned int*)seq_ctrs, (int)n16, (int)slot_stride16, (int)rank, (int)drain, (int)acq, + (int)pub, (long long*)gate, (unsigned int*)gate_ctr); +} + void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, long peer_scratch3, long peer_scratch4, long peer_scratch5, long peer_scratch6, long peer_flags0, long peer_flags1, diff --git a/libr4d/r4d_gemm_w4a8_nt_m64.hip b/libr4d/r4d_gemm_w4a8_nt_m64.hip index da1bc0e5..594bf80f 100644 --- a/libr4d/r4d_gemm_w4a8_nt_m64.hip +++ b/libr4d/r4d_gemm_w4a8_nt_m64.hip @@ -347,6 +347,41 @@ int r4d_gemm_w4a8_nt_m64_group(void) { return R4D_GEMM_W4A8_GROUP; } // The operand reader and the split law are in r4d_gemm_args.h; see libr4d/r4d_args.h. /* ------------------------------------------------------------------ int8-activation grids */ +/* The multi-user verify heights (33 to 64 rows: five to eight users of a DFlash2 verify, 8 rows a + * user). The law's point there covers every row tile in one block at one N tile a wave (mb = all, + * npw = 1), which re-reads the activation once a 16-column tile and holds MT accumulators a wave; + * on 4x R9700 (one card, the 31B's per-card trunk shapes, every point byte-identical to the law's) + * it ran a layer's four GEMMs in 259 us at 64 rows against 157 us here: + * + * q|k|v 3584x5376 o_proj 5376x2048 gate_up 10752x5376 down 5376x5376 + * 40 rows law 46.4 27.4 67.1 36.4 + * here 22.0 (mb1 npw2) 21.1 (mb1 npw2) 58.8 (mb1 npw4) 30.8 (mb1 npw2) + * 48 rows law 31.4 30.4 71.9 42.4 + * here 22.2 21.2 58.9 31.6 + * 56 rows law 56.8 35.0 94.2 62.4 + * here 24.0 (mb1 npw2) 22.3 (mb2 npw1) 69.0 (mb2 npw4) 43.0 (mb1 npw2) + * 64 rows law 58.6 37.3 97.6 65.2 + * here 24.7 22.7 69.6 44.0 + * + * Neither axis moves a byte: the split stays the law's (a point whose wider block cannot hold it + * is not taken, since a smaller split would regroup the K partials), and every output element + * keeps its accumulation order. Only where neither `mb` nor `npw` was tuned. */ +static void multi_user_point(const RadArgs* a, long long M, long long N, long long K, Cfg* c) { + if (M <= 32 || M > 64) return; + R4dGemmCfg cv; + r4d_cfg_gemm(a, &cv); + if (cv.mb > 0 || cv.npw > 1) return; + int mb, npw; + if (M <= 48) { mb = 1; npw = N >= 8192 ? 4 : 2; } + else if (N >= 8192) { mb = 2; npw = 4; } + else if (K <= 2048) { mb = 2; npw = 1; } + else { mb = 1; npw = 2; } + if (c->wv * c->sk * WAVE32 > block_bound(BR_NPW, mb, npw)) return; + if ((size_t)c->wv * npw * c->sk * 256 * sizeof(float) > 64 * 1024) return; + c->mb = mb; + c->npw = npw; +} + /* The asymmetric grid is selected by `dtype`, not by the presence of a_sum (see is_asym). */ extern "C" int r4d_rad_gemm_w4a8_m64(const RadArgs* a, RadStream s) { @@ -360,6 +395,7 @@ extern "C" int r4d_rad_gemm_w4a8_m64(const RadArgs* a, RadStream s) { Cfg c; rc = cfg_for(a, g.K, g.M, group, BR_NPW, &c); if (rc != RAD_OK) return rc; + multi_user_point(a, g.M, g.N, g.K, &c); /* the engine's chained launch (RadKernelChainFn), at decode heights only */ const bool chain = r4d_geti_or(a, "chain", 0) != 0 && g.M <= 64; diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index 638f02cb..a19eb8d6 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -614,6 +614,212 @@ __global__ __launch_bounds__(1024) void r4dchain_ar_rmsnorm_quant_i8_tail(R4D_AR #undef R4D_ARQ8T_ARGS #undef R4D_ARQ8T_PARAMS +// --------------------------------------------------------------------------------------------- +// The junction with the all-reduce split around it (`sp`): reduce-scatter, the junction on the rows +// this rank owns, all-gather of what the next GEMM reads. Rank r owns rows [r0(r), r0(r) + nr(r)), +// M split as evenly as the rank order allows, and block b serves local row b of every rank: +// +// 1. it pushes this rank's partial sums of each peer's local row b into that peer's slot (bf16, +// the two-shot's first hop) and takes the handshake; +// 2. on its own row it folds the four partials in rank order -- r4d_ar_to_f, f32, rank 0 first, +// r4d_ar_from_f, the standalone exact all-reduce's fold, so the same bf16 sum -- and runs the +// junction on it in the register form at the standalone norm's width (r4d_act_threads), each +// thread holding the columns the standalone's does, so every sum is the standalone's; it +// stores the residual row and pushes the row's int8 codes and scale (and with `gres` the +// residual row) into every peer's slot past the first hop's region, then takes the handshake; +// 3. it copies the peers' local row b of codes and scales (and residual) into place. +// +// So every rank leaves q and S on every row, byte for byte the chain's (all_reduce, then +// rmsnorm_quant_i8), and the residual on its own rows only -- on every row with `gres`. `x` keeps +// this rank's partial sums: nothing past the junction reads the reduced branch output. Against the +// tail form the second hop carries int8 instead of bf16 and no block waits beside the transport; +// one launch at a time on 4x R9700 (2026-10-19) it took 22.9 against 24.5 us at 8 rows of 5376, +// 30.8 against 34.9 at 16, 72.3 against 89.2 at 64, and 19.8 against the one-shot's 21.9 at 4. +template +__device__ __forceinline__ void ar_rmsnorm_quant_i8_sp_body( + const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, uint32_t wf32, + uint32_t gres, signed char* __restrict__ q, float* __restrict__ S, + R4DArWidePeers peers, const int4* __restrict__ my_base, + unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, int M, uint32_t n, + float eps, float wadd, uint32_t r_ld, int slot_stride16, int rank, int drain, int acq, int pub, + long long* gate, unsigned int* gate_ctr) { + constexpr int NPEERS = WS - 1; + extern __shared__ uint16_t ybuf[]; + signed char* const cbuf = (signed char*)(ybuf + n); + __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; + __shared__ unsigned int s_seq, s_slot; + const int b = (int)blockIdx.x; + const uint32_t tid = threadIdx.x; + const long long gate_word = r4d_ar_link_word(gate, tid); + r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot); + const unsigned int s = s_seq; + const int parity = (int)s_slot; + const int base = M / WS, rem = M % WS; +#define R4D_SP_R0(r) ((r) * base + ((r) < rem ? (r) : rem)) +#define R4D_SP_NR(r) (base + ((r) < rem ? 1 : 0)) + const int n16 = (int)(n >> 3), c16 = (int)(n >> 4); + const size_t offB = (size_t)(base + (rem ? 1 : 0)) * n16; /* past the first hop's rows */ + const size_t rowB = (size_t)c16 + 1 + (gres ? n16 : 0); /* codes, a scale word, residual */ + const size_t my_slot = ((size_t)parity * WS + rank) * (size_t)slot_stride16; + + // ---- the first hop: this rank's partials of each peer's local row b + for (int p = 0; p < NPEERS; ++p) { + const int d = peers.rank[p]; + if (b >= R4D_SP_NR(d)) continue; + const int4* src = (const int4*)(x + (size_t)(R4D_SP_R0(d) + b) * n); + int4* dst = peers.scratch[p] + my_slot + (size_t)b * n16; + for (int k = (int)tid; k < n16; k += (int)THR) dst[k] = src[k]; + } + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s - 1u, drain, acq, pub); + + if (b < R4D_SP_NR(rank)) { + const int row = R4D_SP_R0(rank) + b; + const __hip_bfloat16* srcs[WS]; +#pragma unroll + for (int r = 0; r < WS; ++r) + srcs[r] = r == rank ? (const __hip_bfloat16*)(x + (size_t)row * n) + : (const __hip_bfloat16*)(my_base + ((size_t)parity * WS + r) * + (size_t)slot_stride16 + (size_t)b * n16); + uint16_t* const rr = res + (size_t)row * r_ld; + uint16_t xv[EPT], rv[EPT]; + float gp[EPT], gw[EPT]; +#pragma unroll + for (uint32_t e = 0; e < EPT; ++e) { + const uint32_t i = tid + e * THR; + xv[e] = 0; rv[e] = 0; gp[e] = 0.0f; gw[e] = 0.0f; + if (i < n) { + float acc = 0.0f; +#pragma unroll + for (int r = 0; r < WS; ++r) acc += r4d_ar_to_f(srcs[r][i]); + __hip_bfloat16 o; + r4d_ar_from_f(acc, o); + __builtin_memcpy(&xv[e], &o, 2); + rv[e] = rr[i]; + gp[e] = gain(wp, i, wf32) + wadd; + gw[e] = gain(w, i, wf32) + wadd; + } + } + const float sv = sc ? scalar_of(sc, sc_f32) : 1.0f; + + // ---- junction_reg_row's passes over the folded row: the post-norm's sum of squares, + // the post-norm, add and scalar with the norm's sum of squares, the norm and its absmax + float ss = 0.0f; +#pragma unroll + for (uint32_t e = 0; e < EPT; ++e) + if (tid + e * THR < n) { const float v = bf2f(xv[e]); ss += v * v; } + const float s1 = rsqrtf(block_sum(ss, l1) / (float)n + eps); + float ss2 = 0.0f; +#pragma unroll + for (uint32_t e = 0; e < EPT; ++e) { + const uint32_t i = tid + e * THR; + if (i < n) { + uint16_t v = f32_to_bf16(bf2f(xv[e]) * s1 * gp[e]); + v = f32_to_bf16(bf2f(rv[e]) + bf2f(v)); + if (sc) v = f32_to_bf16(bf2f(v) * sv); + rr[i] = v; + xv[e] = v; + const float f = bf2f(v); + ss2 += f * f; + } + } + const float s2 = rsqrtf(block_sum(ss2, l2) / (float)n + eps); + float m = 0.0f; +#pragma unroll + for (uint32_t e = 0; e < EPT; ++e) { + const uint32_t i = tid + e * THR; + if (i < n) { + const uint16_t y = f32_to_bf16(bf2f(xv[e]) * s2 * gw[e]); + ybuf[i] = y; + m = fmaxf(m, fabsf(bf2f(y))); + } + } + m = r4d_wave_max(m); + if ((tid & 31) == 0) lm[tid >> 5] = m; + __syncthreads(); // also publishes ybuf to every thread + m = lm[0]; +#pragma unroll + for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]); + const float scale = fmaxf(m, 1e-8f) / 127.f; + const float inv = 1.f / scale; + // ---- the codes, in junction_row's fragment order, into LDS + for (uint32_t i = tid; i < n; i += THR) { + const uint32_t sg = i >> 4, j = i & 15; + const uint32_t src = (sg << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); + const int t = __float2int_rn(bf2f(ybuf[src]) * inv); + cbuf[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); + } + __syncthreads(); // the codes, and this block's residual row in memory, whole + // ---- the second hop: the row's codes and scale (and residual) to every peer, and here + const int4* const c4 = (const int4*)cbuf; + int4* const q4 = (int4*)(q + (size_t)row * n); + int4* dB[NPEERS]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) dB[p] = peers.scratch[p] + my_slot + offB + (size_t)b * rowB; + for (int k = (int)tid; k < c16; k += (int)THR) { + const int4 v = c4[k]; + q4[k] = v; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) dB[p][k] = v; + } + if (gres) { + const int4* const r4 = (const int4*)rr; + for (int k = (int)tid; k < n16; k += (int)THR) { + const int4 v = r4[k]; +#pragma unroll + for (int p = 0; p < NPEERS; ++p) dB[p][c16 + 1 + k] = v; + } + } + if (tid == 0) { + S[row] = scale; + const int4 sw = make_int4(__float_as_int(scale), 0, 0, 0); +#pragma unroll + for (int p = 0; p < NPEERS; ++p) dB[p][c16] = sw; + } + } + r4d_ar_handshake(peers, my_flags, b, rank, 2u * s, drain, acq, pub); + r4d_ar_link_landed(gate, gate_word, gate_ctr, gridDim.x, tid); + // ---- the peers' local row b, codes and scale (and residual), into place + for (int p = 0; p < NPEERS; ++p) { + const int sr = peers.rank[p]; + if (b >= R4D_SP_NR(sr)) continue; + const int4* const src = my_base + ((size_t)parity * WS + sr) * (size_t)slot_stride16 + offB + + (size_t)b * rowB; + const int row = R4D_SP_R0(sr) + b; + int4* const q4 = (int4*)(q + (size_t)row * n); + for (int k = (int)tid; k < c16; k += (int)THR) q4[k] = src[k]; + if (gres) { + int4* const r4 = (int4*)(res + (size_t)row * r_ld); + for (int k = (int)tid; k < n16; k += (int)THR) r4[k] = src[c16 + 1 + k]; + } + if (tid == 0) S[row] = __int_as_float(src[c16].x); + } +#undef R4D_SP_R0 +#undef R4D_SP_NR +} + +#define R4D_ARQ8S_PARAMS const uint16_t* __restrict__ x, uint16_t* __restrict__ res, \ + const void* __restrict__ w, const void* __restrict__ wp, const void* __restrict__ sc, \ + uint32_t sc_f32, uint32_t wf32, uint32_t gres, signed char* __restrict__ q, \ + float* __restrict__ S, R4DArWidePeers peers, const int4* __restrict__ my_base, \ + unsigned int* __restrict__ my_flags, unsigned int* __restrict__ seq_ctrs, int M, uint32_t n, \ + float eps, float wadd, uint32_t r_ld, int slot_stride16, int rank, int drain, int acq, int pub, \ + long long* gate, unsigned int* gate_ctr +#define R4D_ARQ8S_ARGS x, res, w, wp, sc, sc_f32, wf32, gres, q, S, peers, my_base, my_flags, \ + seq_ctrs, M, n, eps, wadd, r_ld, slot_stride16, rank, drain, acq, pub, gate, gate_ctr +template +__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_sp_kernel(R4D_ARQ8S_PARAMS) { + ar_rmsnorm_quant_i8_sp_body(R4D_ARQ8S_ARGS); +} +template +__global__ __launch_bounds__(THR) void r4dchain_ar_rmsnorm_quant_i8_sp(R4D_ARQ8S_PARAMS) { + r4d_chain_wait(); + ar_rmsnorm_quant_i8_sp_body(R4D_ARQ8S_ARGS); + r4d_chain_done(); +} +#undef R4D_ARQ8S_ARGS +#undef R4D_ARQ8S_PARAMS + } // namespace // ============================================================== the plugin ABI entry point @@ -667,24 +873,33 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) { const float wadd = (float)r4d_getf(a, "wadd", 0.0); const uint32_t scf = sc ? (sc->dtype == RAD_F32) : 0u; - // The decode form keeps a thread's columns in registers: at 1024 threads, EPT of them. - const int ept = (thr != 1024 || !r4d_cfg_rmsq8_reg(a)) ? 0 - : n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0; + // The decode form keeps a thread's columns in registers, EPT of them: at 1024 threads (to 32 + // rows) and at 512 (33 to 72-120 rows, r4d_act_threads), the same partition and arithmetic as + // the re-read form at that width, so the same bytes. At 512 it serves the multi-user verify + // (five to fifteen users of a DFlash2 verify, 8 rows a user), where the re-read form took ~14 us + // a junction under --profile-ops at 64 rows of 5376. + const int ept = !r4d_cfg_rmsq8_reg(a) ? 0 + : thr == 1024 ? (n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0) + : thr == 512 ? (n <= 4096 ? 8 : n <= 6144 ? 12 : n <= 8192 ? 16 : 0) + : 0; #define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(stream, \ (rmsnorm_quant_i8_kernel), dim3((uint32_t)M), dim3(T), lds, \ (const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \ (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \ (uint32_t)xp, (uint32_t)rp, (uint32_t)yp) -#define R4D_RQI8_R(WF, RS, PO, SC, E) emit_rc = R4D_EMIT(stream, \ - (rmsnorm_quant_i8_reg_kernel), dim3((uint32_t)M), dim3(1024), lds, \ +#define R4D_RQI8_R(WF, RS, PO, SC, T, E) emit_rc = R4D_EMIT(stream, \ + (rmsnorm_quant_i8_reg_kernel), dim3((uint32_t)M), dim3(T), lds, \ (const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \ (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \ (uint32_t)xp, (uint32_t)rp, (uint32_t)yp) #define R4D_RQI8(WF, RS, PO, SC) \ - do { if (ept == 4) R4D_RQI8_R(WF, RS, PO, SC, 4); \ - else if (ept == 6) R4D_RQI8_R(WF, RS, PO, SC, 6); \ - else if (ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 8); \ + do { if (thr == 1024 && ept == 4) R4D_RQI8_R(WF, RS, PO, SC, 1024, 4); \ + else if (thr == 1024 && ept == 6) R4D_RQI8_R(WF, RS, PO, SC, 1024, 6); \ + else if (thr == 1024 && ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 1024, 8); \ + else if (thr == 512 && ept == 8) R4D_RQI8_R(WF, RS, PO, SC, 512, 8); \ + else if (thr == 512 && ept == 12) R4D_RQI8_R(WF, RS, PO, SC, 512, 12); \ + else if (thr == 512 && ept == 16) R4D_RQI8_R(WF, RS, PO, SC, 512, 16); \ else if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024); \ else if (thr == 512) R4D_RQI8_T(WF, RS, PO, SC, 512); \ else if (thr == 256) R4D_RQI8_T(WF, RS, PO, SC, 256); \ @@ -771,7 +986,7 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat float eps, float wadd, int w_f32, int r_ld, int y_ld, int rank, long stream, int nblocks, int drain, int acq, int pub, long gate, long gate_ctr, - long tail_ctr, int tail_nbt, int chain) { + long tail_ctr, int tail_nbt, int chain, int sp) { constexpr int WS = 4, NPEERS = WS - 1; const long ps[NPEERS] = { peer_scratch0, peer_scratch1, peer_scratch2 }; const long pf[NPEERS] = { peer_flags0, peer_flags1, peer_flags2 }; @@ -815,6 +1030,50 @@ extern "C" int r4d_ar_rmsnorm_quant_i8_4rank(long peer_scratch0, long peer_scrat const int thr = r4d_act_threads(M, n); const size_t lds = (size_t)n * sizeof(uint16_t); + /* The all-reduce split around the junction (ar_rmsnorm_quant_i8_sp_kernel): `sp` 1, or 2 with + * the residual gathered too. A block a local row, ceil(M / 4) of them; its two hops in the slot + * the message would fill. Where it cannot run (no residual or post-norm, a width without a + * register form, rows past the flag array or the slot, a residual pitch off 16 bytes) the + * forms below run instead, which leave every byte this one does and more. It leaves no bf16 + * norm output, so one asked for (`y`) takes those forms too. */ + if (sp > 0 && res && wp && !y) { + const int ep = thr == 1024 ? (n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0) + : thr == 512 ? (n <= 4096 ? 8 : n <= 6144 ? 12 : n <= 8192 ? 16 : 0) : 0; + const int nbs = (M + WS - 1) / WS; + const long need = (long)nbs * (n / 8) + (long)nbs * (n / 16 + 1 + (sp == 2 ? n / 8 : 0)); + if (ep > 0 && nbs <= R4D_AR_WIDE_MAX_BLOCKS && need <= slot_stride16 && + (sp != 2 || r_ld % 8 == 0)) { + try { + const long fb = (long)nbs * WS * (long)sizeof(unsigned int); + r4d_ar_check_extent(my_flags, fb, "ar_rmsnorm_quant_i8", "my_flags"); + for (int i = 0; i < NPEERS; ++i) + r4d_ar_check_extent(pf[i], fb, "ar_rmsnorm_quant_i8", "peer flags"); + } catch (...) { + return -8; + } + const size_t lds_sp = (size_t)n * (sizeof(uint16_t) + 1); +#define R4D_ARQ8S_K(E, T) \ + hipLaunchKernelGGL((chain ? r4dchain_ar_rmsnorm_quant_i8_sp \ + : ar_rmsnorm_quant_i8_sp_kernel), \ + dim3((uint32_t)nbs), dim3(T), lds_sp, (hipStream_t)stream, \ + (const uint16_t*)x, (uint16_t*)res, (const void*)w, \ + (const void*)wp, (const void*)sc, (uint32_t)sc_f32, \ + (uint32_t)w_f32, (uint32_t)(sp == 2), (signed char*)q, (float*)s, \ + peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ + (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, wadd, \ + (uint32_t)r_ld, (int)slot_stride16, rank, drain, acq, pub, \ + (long long*)gate, (unsigned int*)gate_ctr) + if (thr == 1024 && ep == 4) R4D_ARQ8S_K(4, 1024); + else if (thr == 1024 && ep == 6) R4D_ARQ8S_K(6, 1024); + else if (thr == 1024) R4D_ARQ8S_K(8, 1024); + else if (ep == 8) R4D_ARQ8S_K(8, 512); + else if (ep == 12) R4D_ARQ8S_K(12, 512); + else R4D_ARQ8S_K(16, 512); +#undef R4D_ARQ8S_K + return hipGetLastError() == hipSuccess ? 0 : -4; + } + } + /* The junction as the standalone two-shot's tail (ar_rmsnorm_quant_i8_tail_kernel): at the * junction's register width (1024 threads), up to R4D_ARQ8_TAIL_MAX_ROWS rows. */ const int ept = n <= 4096 ? 4 : n <= 6144 ? 6 : n <= 8192 ? 8 : 0; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 2d5dae97..18121753 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1499,7 +1499,11 @@ static const RadOperandSpec oGeluMulQuantI8[] = { }; /* `ar_rmsnorm_quant_i8` is rmsnorm_quant_i8 with the two-rank exact all-reduce of `x` in front: - * same operands with `x` inout (it receives the reduced sum), plus `world_size`. */ + * same operands with `x` inout (it receives the reduced sum), plus `world_size`. `sp` (optional, + * 0) lets a row split the all-reduce around the junction at tensor parallel: 1 asks only for q and + * the scales on every row and the residual on the rows this rank owns (M split evenly over the + * ranks in rank order), 2 for the residual on every row too; `x` is then left unspecified. A row + * may always do more than asked (the whole form). */ static const RadParamSpec pArRmsNormQuantI8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1507,6 +1511,7 @@ static const RadParamSpec pArRmsNormQuantI8[] = { { "world_size", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, P_F64O("wadd"), + P_INTO("sp"), }; static const RadOperandSpec oArRmsNormQuantI8[] = { { "x", RAD_OPD_INOUT, 0 }, @@ -7923,7 +7928,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, "sum, residual add, scalar, RMS norm and quant_act_i8's quantiser -- in one kernel", "exactly 4 ranks; n a multiple of 16, x unpitched (it is the message); a block owns whole rows; " "exact wire; one-shot ((ranks - 1) x the message a rank) -- for decode heights; from 5 to 32 " - "rows (axis `tail`) the standalone two-shot with the junction as its tail", + "rows (axis `tail`) the standalone two-shot with the junction as its tail; with `sp` the " + "all-reduce split around the junction (reduce-scatter, the junction on this rank's rows, " + "all-gather of the int8 codes), a block per local row, P2P", "bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale; the reduced sum " "rounded to bf16 as the standalone exact all-reduce stores it", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 1c3aaa26..4db1345c 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -11326,7 +11326,9 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) { /* The row's reg axis at 1024 threads: 1 (the default) holds a thread's columns in registers, * 0 re-reads the row each pass; both must leave the chain's bytes. */ struct RqCase { int64_t M; int reg; }; - for (const RqCase rqc : { RqCase{ 1, 1 }, RqCase{ 8, 1 }, RqCase{ 8, 0 }, RqCase{ 40, 1 } }) { + /* 40 and 64 rows: the 512-thread width, its register form and its re-read form */ + for (const RqCase rqc : { RqCase{ 1, 1 }, RqCase{ 8, 1 }, RqCase{ 8, 0 }, RqCase{ 40, 1 }, + RqCase{ 40, 0 }, RqCase{ 64, 1 } }) { const int64_t M = rqc.M; const std::string form = rqc.reg ? "" : " (re-read form)"; const int64_t K = 5376; /* Gemma 4 31B's hidden width: 336 sixteen-byte k steps */ @@ -21734,6 +21736,9 @@ struct ArPattern { std::vector sizes; int out_of_place = -1; /* index into sizes, or -1 */ std::vector pieces; /* per size: a launch `pieces` parameter, 0 or absent none */ + int overlap = 0; /* 1: launched as beside compute (the lane rows) */ + int coded_pattern = 0; /* 1: ar_coded_value, not ar_pattern_value */ + int coded = -1; /* >= 0: the lane row's `coded` launch parameter */ void* inst = nullptr; int rc_init = RAD_E_STATE, rc_launch = RAD_OK; std::vector> out; @@ -21745,6 +21750,30 @@ static float ar_pattern_value(int rank, int64_t i) { return (float)((int)((i * 37 + (int64_t)rank * 101) % 509) - 254) / 64.0f; } +/* The pattern for the two-shot's coded form (r4d_ar_twoshot_Nrank_exact.hip), which codes a group + * of 64 consecutive values on a shared exponent and sends a group it cannot code raw: the + * per-element pattern, with groups sent down each path -- an exponent range of exactly 14 (coded) + * and 15 (raw), one far past it, a subnormal, an infinity, all zeros, and exponents near the top. + * Every shard starts on a group, so an element's group is its index over 64; each path holds on + * both pushes (the inputs and the folded shard). */ +static float ar_coded_value(int rank, int64_t i) { + const int64_t g = i / 64, j = i % 64; + const float sg = (j & 1) ? -1.0f : 1.0f; + switch (g % 16) { + case 3: return std::ldexp(ar_pattern_value(rank, i), 3 * (int)(j % 8)); + case 5: return j == 17 ? (rank == 1 ? h_bf16(0x0005) : 1.0f) : ar_pattern_value(rank, i); + case 7: return (j == 40 && rank == 0) ? INFINITY : ar_pattern_value(rank, i); + case 9: return 0.0f; + case 11: return sg * (j == 5 ? 16384.0f : 1.0f); + case 13: return sg * (j == 5 ? 32768.0f : 1.0f); + case 14: return std::ldexp(ar_pattern_value(rank, i), 100); + default: return ar_pattern_value(rank, i); + } +} +static float ar_value(int coded_pattern, int rank, int64_t i) { + return coded_pattern ? ar_coded_value(rank, i) : ar_pattern_value(rank, i); +} + static void ar_pattern_worker(ArPattern* t) { if (st_set_device(t->dev) != hipSuccess) { t->rc_init = RAD_E_DEVICE; return; } const bool bf = !std::strcmp(t->dtype, "bf16"); @@ -21754,6 +21783,7 @@ static void ar_pattern_worker(ArPattern* t) { std::vector ps = { PI("world_size", t->world), PI("numel", most), PS("dtype", t->dtype), PI("exact", 1), }; + if (t->overlap) ps.push_back(PI("overlap", 1)); t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, t->world, &t->inst); if (t->rc_init != RAD_OK) return; void* in = nullptr; @@ -21764,7 +21794,7 @@ static void ar_pattern_worker(ArPattern* t) { for (size_t k = 0; k < t->sizes.size(); ++k) { const int64_t n = t->sizes[k]; for (int64_t i = 0; i < n; ++i) { - const float v = ar_pattern_value(t->rank, i); + const float v = ar_value(t->coded_pattern, t->rank, i); if (bf) { const uint16_t b = h_to_bf16(v); std::memcpy(&h[(size_t)i * 2], &b, 2); } else std::memcpy(&h[(size_t)i * 4], &v, 4); } @@ -21778,6 +21808,7 @@ static void ar_pattern_worker(ArPattern* t) { a.t = ts; a.n_t = oop ? 2 : 1; std::vector lp = ps; if (k < t->pieces.size() && t->pieces[k] > 0) lp.push_back(PI("pieces", t->pieces[k])); + if (t->coded >= 0) lp.push_back(PI("coded", t->coded)); a.p = lp.data(); a.n_p = (int)lp.size(); a.instance = t->inst; a.rank = t->rank; @@ -22420,6 +22451,91 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty } } +/* The four-rank two-shot's lane row (overlap 1: the prefill's reductions beside compute) in both + * its forms, which the `coded` launch parameter picks: the narrow plain launch (0), and the coded + * one (1), whose pushes carry ~12.2 bits a bf16 value. Each must equal the fp32 ascending-rank + * fold bit for bit, on the per-element pattern and on ar_coded_value. A message outside the coded + * form (shards that are not whole 256-value waves, or fp32) runs plain whatever the parameter + * says; each label says which form a size took, by the library's rule restated here. */ +static bool ar_coded_fits(const char* dtype, int64_t n, int64_t most) { + if (std::strcmp(dtype, "bf16") != 0 || n % 1024 != 0) return false; + const int64_t SL = n / 32; /* a shard's 16-byte chunks */ + const int64_t shadow = (12 * SL + SL / 8 + 15) & ~(int64_t)15; + const int64_t region = (shadow + 16 * SL + 255) & ~(int64_t)255; + return 2 * region <= ((most * 2 + 15) & ~(int64_t)15); +} +static void ar_lane_forms(const Plugin& pl, const std::vector& devs, const char* name) { + const RadKernelInfo* row = find(pl, name); + if (!row) { ok(name, false, "row absent"); return; } + if ((int)devs.size() < 4) { skip(name, "needs 4 gfx1201 cards"); return; } + struct Run { bool coded; int pat; const char* dtype; std::vector sizes; int oop; }; + /* 1024: one wave a shard; 1055744: 1031 waves, an odd split over the blocks; 524352: bf16 + * outside the coded form; 46137344: the feed-forward reduce at an 8192-token chunk. */ + const std::vector runs = { + { false, 0, "bf16", { 4194304, 524352, 1055744, 20971520 }, 1 }, + { true, 0, "bf16", { 4194304, 1024, 524352, 1055744, 20971520, 4194304 }, 3 }, + { true, 1, "bf16", { 4194304, 1024, 1055744, 46137344, 4194304 }, 2 }, + { true, 0, "fp32", { 524352 }, 0 }, + }; + for (const Run& run : runs) { + std::vector t(4); + std::vector th; + for (int r = 0; r < 4; ++r) { + t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; + t[(size_t)r].world = 4; + t[(size_t)r].dtype = run.dtype; t[(size_t)r].sizes = run.sizes; + t[(size_t)r].out_of_place = run.oop; + t[(size_t)r].overlap = 1; + t[(size_t)r].coded_pattern = run.pat; + t[(size_t)r].coded = run.coded ? 1 : 0; + th.emplace_back(ar_pattern_worker, &t[(size_t)r]); + } + for (std::thread& x : th) x.join(); + const std::string what = std::string(name) + " " + run.dtype + + (run.coded ? ", coded 1" : ", coded 0") + + (run.pat ? ", the coded form's pattern" : ""); + bool up = true, ran = true; + std::string rcs; + for (const ArPattern& a : t) { + up = up && a.rc_init == RAD_OK; ran = ran && a.rc_launch == RAD_OK; + rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; + } + ok((what + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); + if (!up) return; + ok((what + " launches").c_str(), ran, "init/launch rc " + rcs); + int64_t most = 0; + for (int64_t n : run.sizes) most = n > most ? n : most; + if (ran) { + const bool bf = !std::strcmp(run.dtype, "bf16"); + for (size_t k = 0; k < run.sizes.size(); ++k) { + const int64_t n = run.sizes[k]; + int64_t bad = 0, first = -1; + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int r = 0; r < 4; ++r) { + const float v = ar_value(run.pat, r, i); + acc += bf ? h_bf16(h_to_bf16(v)) : v; + } + const float want = bf ? h_bf16(h_to_bf16(acc)) : acc; + for (int r = 0; r < 4; ++r) + if (t[(size_t)r].out.size() <= k || t[(size_t)r].out[k][(size_t)i] != want) { + if (first < 0) first = i; + ++bad; + } + } + const bool coded = run.coded && ar_coded_fits(run.dtype, n, most); + const std::string label = + what + " numel " + std::to_string(n) + " (" + (coded ? "coded" : "plain") + + ((int)k == run.oop ? ", out of place" : ", in place") + + ") == fp32 ascending-rank fold on every rank, bit for bit"; + ok(label.c_str(), bad == 0, + std::to_string(bad) + " elements wrong, first at " + std::to_string(first)); + } + } + if (row->fini) for (ArPattern& a : t) if (a.inst) row->fini(a.inst); + } +} + /* The three-rank tiered-int8 wire. * * Exact: every rank ends with the same bytes (the owner stores the decode of what it published), @@ -23060,6 +23176,7 @@ struct ArQ8 { bool gated = false; /* hand the launch an odd `link_gate` word */ long long gate_after = -1; /* ...and what the launch left in it */ int tail = -1; /* the `tail` axis pinned, or -1: the default */ + int sp = 0; /* `sp`: the all-reduce split around the junction */ void* inst = nullptr; int rc_init = RAD_E_STATE, rc_launch = RAD_OK; const std::vector* r_in = nullptr; /* the replicated residual, w and w_post */ @@ -23081,6 +23198,7 @@ static void ar_q8_worker(ArQ8* t) { if (t->rc_init != RAD_OK) return; /* The tuned point arrives as a parameter of the launch, as the core appends it. */ if (t->tail >= 0) ps.push_back(PI("tail", t->tail)); + if (t->sp > 0) ps.push_back(PI("sp", t->sp)); /* Allocated here and not through dalloc, whose list four rank threads would race on. */ void* x = nullptr; void* r = nullptr; void* w = nullptr; void* wp = nullptr; void* sc = nullptr; @@ -23111,6 +23229,7 @@ static void ar_q8_worker(ArQ8* t) { T(wp, RAD_BF16, { K }), T(sc, RAD_BF16, { 1 }) }; if (!t->res) { absent(ts[1]); absent(ts[6]); } if (!t->scal) absent(ts[7]); + if (t->sp) absent(ts[5]); /* the split form leaves no bf16 output */ RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); @@ -23149,12 +23268,19 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector(x.rank, rem); + const int64_t na = base + (x.rank < rem ? 1 : 0); for (int64_t i = 0; i < M * K; ++i) { - bx += x.x_out[(size_t)i] != xsum[(size_t)i]; - if (res) br += x.r_out[(size_t)i] != want_r[(size_t)i]; - by += x.y_out[(size_t)i] != want_y[(size_t)i]; + const int64_t row = i / K; + if (!sh.sp) bx += x.x_out[(size_t)i] != xsum[(size_t)i]; + if (res && (sh.sp != 1 || (row >= a && row < a + na))) + br += x.r_out[(size_t)i] != want_r[(size_t)i]; + if (!sh.sp) by += x.y_out[(size_t)i] != want_y[(size_t)i]; bq += x.q_out[(size_t)i] != want_q[(size_t)i]; } for (int64_t i = 0; i < M; ++i) @@ -26509,6 +26646,13 @@ static void device_phase(const Plugin& pl) { } } } + /* The four-rank two-shot's lane row and its host twin, plain and coded (ar_lane_forms). */ + for (const char* n : { "ar_twoshot_4rank_exact_lane", "ar_twoshot_4rank_exact_lane_host" }) { + if (!sel(n)) continue; + if (!g_case) std::printf("\ncross-rank, beside compute (overlap 1)\n"); + std::printf(" %s\n", n); + ar_lane_forms(pl, devs, n); + } /* The fused write rows at both widths and both gathers. The `_host` twins take the same * calls; they differ only in where the mailbox lives. */ for (const char* base : { "ar_hc_write", "ar_gather_hc_write", diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 4453d187..4170cd29 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -4612,8 +4612,9 @@ TEST(gemma4_attention_join_writes_the_routed_inputs_on_fp8_experts) { * at two ranks (only the embedding's and the last layer's feed-forward reduction stand alone), * through ar_rmsnorm_quant_i8 declared at world_size 4 up to 16 rows (kAr4FoldRows: a DFlash * verify's rows, which libr4d folds in its tail form, inside its one-shot band of 524288 / 5376 = - * 97). A taller step issues each reduction and its junction apart, and where no library declares - * the fold every step issues the pair. */ + * 97), and beside each the same op with `sp` (the all-reduce split around the junction) over the + * same 16 rows, which a step from 4 rows takes. A taller step issues each reduction and its + * junction apart, and where no library declares the fold every step issues the pair. */ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_decode_heights) { const int L = 12; std::vector folded = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" }; @@ -4684,7 +4685,7 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ int64_t hi = -1; *n = 0; for (const auto& o : bb.ops) { - if (o.op != "ar_rmsnorm_quant_i8") continue; + if (o.op != "ar_rmsnorm_quant_i8" || pint(&o, "sp") != -12345) continue; ++*n; CHECK_EQ(pint(&o, "world_size"), 4); for (const auto& p : o.p) @@ -4695,6 +4696,37 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ int n_ar = 0; CHECK_EQ(fold_hi(b, &n_ar), 16); CHECK_EQ(n_ar, 2 * L - 1); + /* the split form beside each fold, over its 16 rows; the residual on every row (sp 2) only + * before the last layer's feed-forward, with no drafter tapping the stream here */ + auto sp_hi = [](const RadBuilder& bb, int* n, int* n2) { + int64_t hi = -1; + *n = 0; *n2 = 0; + for (const auto& o : bb.ops) { + if (o.op != "ar_rmsnorm_quant_i8" || pint(&o, "sp") == -12345) continue; + ++*n; + if (pint(&o, "sp") == 2) ++*n2; + else CHECK_EQ(pint(&o, "sp"), 1); + CHECK_EQ(pint(&o, "world_size"), 4); + for (const auto& p : o.p) + if (p.key == "M") hi = p.ihi; + } + return hi; + }; + int n_sp = 0, n_sp2 = 0; + CHECK_EQ(sp_hi(b, &n_sp, &n_sp2), 16); + CHECK_EQ(n_sp, 2 * L - 1); + CHECK_EQ(n_sp2, 1); + /* which form a step's junctions take: the split one from 4 rows, the fold below */ + auto sp_issued = [&b](const RadCtx& c) { + int n = 0, folds = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o || o->op != "ar_rmsnorm_quant_i8") continue; + ++folds; + if (pint(o, "sp") != -12345) ++n; + } + return std::make_pair(n, folds); + }; /* 20 MB of gate_up beside the attention's reduction and of the next layer's q beside the * feed-forward's, and 9 MB of down_proj beside the attention */ @@ -4725,6 +4757,17 @@ TEST(a_gemma4_w4a8_step_at_four_ranks_folds_the_all_reduce_into_the_junction_at_ gemma4_bf16::step(&d, &tall); CHECK(d.step_fail.empty()); CHECK_EQ(join(issued_ops(b, d)), join(rows <= 16 ? folded : apart_tall)); + if (rows <= 16) CHECK(sp_issued(d) == std::make_pair(2 * L - 1, 2 * L - 1)); + } + /* three rows: the fold; eight users' verify (64 rows): the pair */ + for (int rows : { 3, 64 }) { + RadBatch v = one_prompt(rows, out); + v.phase = RAD_PHASE_DECODE; + RadCtx d; d.b = &b; d.rank = 0; d.world = 4; d.batch = &v; + gemma4_bf16::step(&d, &v); + CHECK(d.step_fail.empty()); + if (rows == 64) CHECK_EQ(join(issued_ops(b, d)), join(apart_tall)); + CHECK(sp_issued(d) == (rows == 3 ? std::make_pair(0, 2 * L - 1) : std::make_pair(0, 0))); } From afe5318259344adb4ec604e908c24bfffe4fe9f0 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:11 +0200 Subject: [PATCH 126/152] dsa_score: row_part -- score one run of a step's query rows, and rebase cu for the selection after it With `row_part` p, `score` holds R rows and row i is query row p * R + i; `q`, `q_scale` and `gate` stay the whole step's, so a run is the unsplit op's rows bit for bit. A row past the last sequence scores -inf, so every rank's run can be the same length whatever the step's. The optional output `cu_part` receives cu - p * R, under which qsa_select runs over the run's own rows (pos offset by p * R) and finds each row's sequence unchanged; qsa_select itself is untouched. This is what an indexer split over tensor-parallel ranks by query rows needs from the op: the scoring is the only per-row work in GLM-5.3's indexer that grows with the context. libr4d offsets the query operands and compares row0 + r against cu; libref and libavx index the same way. Without `row_part` nothing changes. Tests: the selftest scores each case's rows in equal runs and holds every run to the unsplit rows' bytes and cu_part to the rebased bounds; ref_test checks a run, a run past the step and a short query plane; r4d_emu_dsa (r4d_dsa.hip now runs on the emulator) splits decode rows beside a prefill chunk at 2, 4 and 8 ranks, selects with the rebased bounds and joins the runs as the all_gather does, byte for byte against the unsplit scorer and selection, ties and signed gates included. Co-Authored-By: Claude Fable 5.1 --- docs/OPS.md | 19 ++- libavx/avx_dsa.cpp | 28 +++-- libavx/avx_registry.cpp | 4 +- libr4d/r4d_dsa.hip | 52 ++++++-- libr4d/r4d_rows.cpp | 6 +- libr4d/r4d_selftest.cpp | 37 ++++++ libr4d/r4d_shapes.cpp | 3 +- libref/ref_dsa.cpp | 28 +++-- libref/ref_registry.cpp | 4 +- libref/ref_shapes.cpp | 1 + tests/CMakeLists.txt | 26 ++-- tests/r4d_emu/test_dsa.cpp | 247 +++++++++++++++++++++++++++++++++++++ tests/ref_test.cpp | 43 +++++++ 13 files changed, 451 insertions(+), 47 deletions(-) create mode 100644 tests/r4d_emu/test_dsa.cpp diff --git a/docs/OPS.md b/docs/OPS.md index 25f4d5ca..bfc09401 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2569,7 +2569,7 @@ order, not a slow one. | `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `k`, `w`w, `page`?, `pos`? → `out` | | `dsa_pool` | `M`(range) `n` `ratio` `dtype` `block_size`/opt | `kg`, `ape`w → `q`, `scale`; `page`?, `cache`:inout? | | `dsa_query` | `M`(range) `n` `dtype` | `x` → `q`, `scale` | -| `dsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `q_scale`, `gate`, `k`, `k_scale`?, `bt`, `cu`, `nc` → `score` | +| `dsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` `row_part`/opt | `q`, `q_scale`, `gate`, `k`, `k_scale`?, `bt`, `cu`, `nc` → `score`, `cu_part`? | | `mla_attn` | `M`(range) `latent_dim` `heads` `blocks` `block_size` `scale`:f64 `dtype` | `q`, `kv`, `bt`, `length` → `out` | | `mla_project` | `M`(range) `heads` `head_dim` `latent_dim` `mode` `dtype` | `a`, `b`w → `y` | | `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` | @@ -2813,10 +2813,19 @@ history makes no future block eligible. embedded scale are read in place. `q` may be flattened `[M*heads, n]` with `q_scale` `[M*heads, 1]`, each with its own row pitch, which is `dsa_query`'s output as written. -libr4d's `dsa_score_fp8` serves `n` 128 and 32 heads, `M` up to 65535, both key forms and both -query forms. A block of two waves covers the 32 heads of one query row against one or two 16-key -tiles (two past 32 blocks); the dot products run on fp8 WMMA, and scales and gates fold only after -each head's ReLU. +`row_part` scores one run of a step's query rows, for an indexer split over tensor-parallel ranks +by rows. With `row_part` p, `score` holds R rows and score row i is query row `p * R + i`; `q`, +`q_scale` and `gate` are the whole step's and hold at least `(p + 1) * R` rows, so a run is the +unsplit op's rows, bit for bit. A row past the last sequence in `cu` scores `-inf` everywhere, +which lets every rank's run be the same length whatever the step's. `cu_part`, `[seqs + 1]` i32 +and only with `row_part`, receives `cu - p * R`: the bounds rebased to the run's first row, under +which an op that reads `cu` over the run's own rows (`qsa_select`, with `pos` offset by `p * R`) +finds each row's sequence unchanged. + +libr4d's `dsa_score_fp8` serves `n` 128 and 32 heads, `M` up to 65535, both key forms, both +query forms and `row_part`. A block of two waves covers the 32 heads of one query row against one +or two 16-key tiles (two past 32 blocks); the dot products run on fp8 WMMA, and scales and gates +fold only after each head's ReLU. `mla_attn` is absorbed latent attention: one latent vector per token is both key and value. `q` and `out` are `[M, heads, latent_dim]`, `kv` is `[pages, 1, block_size, latent_dim]`, and diff --git a/libavx/avx_dsa.cpp b/libavx/avx_dsa.cpp index 08f25015..d98637dd 100644 --- a/libavx/avx_dsa.cpp +++ b/libavx/avx_dsa.cpp @@ -64,17 +64,19 @@ AVX_KERNEL(dsa_score) { k.stride[1] = 1; } const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &out = a->t[8]; + const RadTensor* cu_part = rad_arg_in(a, 9); const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0); - if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && - q.shape[0] == out.shape[0] * h && qs.shape[0] == q.shape[0]) { + const int64_t part = p_int(a, "row_part", -1); + if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && g.rank == 2 && + q.shape[0] == g.shape[0] * h && qs.shape[0] == q.shape[0]) { q.rank = 3; - q.shape[0] = out.shape[0]; + q.shape[0] = g.shape[0]; q.shape[2] = q.shape[1]; q.shape[1] = h; q.stride[2] = q.stride[1]; q.stride[1] = q.stride[0]; q.stride[0] *= h; - qs.shape[0] = out.shape[0]; + qs.shape[0] = g.shape[0]; qs.shape[1] = h; qs.stride[1] = qs.stride[0]; qs.stride[0] *= h; @@ -84,9 +86,14 @@ AVX_KERNEL(dsa_score) { g.shape[0] != q.shape[0] || qs.shape[1] != h || g.shape[1] != h || k.rank != 2 || k.shape[1] != n || ks.rank != 1 || ks.shape[0] != k.shape[0] || bt.rank != 2 || cu.rank != 1 || nc.rank != 1 || cu.shape[0] != bt.shape[0] + 1 || - nc.shape[0] != bt.shape[0] || out.rank != 2 || out.shape[0] != q.shape[0] || + nc.shape[0] != bt.shape[0] || out.rank != 2 || + (part < 0 ? out.shape[0] != q.shape[0] + : out.shape[0] < 1 || q.shape[0] < (part + 1) * out.shape[0]) || out.shape[1] > bt.shape[1]) return RAD_E_SHAPE; + if (cu_part && (part < 0 || cu_part->rank != 1 || cu_part->shape[0] != cu.shape[0])) + return part < 0 ? RAD_E_INVAL : RAD_E_SHAPE; + if (cu_part && cu_part->dtype != RAD_I32) return RAD_E_DTYPE; if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 || ks.dtype != RAD_F32 || g.dtype != RAD_F32 || bt.dtype != RAD_I32 || cu.dtype != RAD_I32 || nc.dtype != RAD_I32 || out.dtype != RAD_F32) @@ -94,8 +101,15 @@ AVX_KERNEL(dsa_score) { for (int i = 0; i < 9; ++i) if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL; const float norm = 1.0f / std::sqrt((float)(h * n)); + /* A part scores out's rows from step row part * rows; the query operands span the step. */ + const int64_t row0 = part > 0 ? part * out.shape[0] : 0; + if (cu_part) + for (int64_t s = 0; s < cu.shape[0]; ++s) + st_int_dt(RAD_I32, cu_part->data, s * cu_part->stride[0], + ld_int_dt(cu.dtype, cu.data, s * cu.stride[0]) - row0); AVX_PARALLEL_FOR_IF(q.shape[0] * out.shape[1] * h * n >= AVX_PAR_MIN) - for (int64_t r = 0; r < q.shape[0]; ++r) { + for (int64_t o = 0; o < out.shape[0]; ++o) { + const int64_t r = row0 + o; int64_t seq = -1; for (int64_t s = 0; s < bt.shape[0]; ++s) if (r >= ld_int_dt(cu.dtype, cu.data, s * cu.stride[0]) && @@ -123,7 +137,7 @@ AVX_KERNEL(dsa_score) { } result *= ldt(&ks, page * ks.stride[0]) * norm; } - stt(&out, r * out.stride[0] + b * out.stride[1], result); + stt(&out, o * out.stride[0] + b * out.stride[1], result); } } return RAD_OK; diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 6eb8f1b3..97b80f71 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -142,9 +142,9 @@ static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("h P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") }; static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") }; static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), - P_INT("blocks"), P_INT("seqs"), P_STR("dtype") }; + P_INT("blocks"), P_INT("seqs"), P_STR("dtype"), P_INTO("row_part") }; static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"), - OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") }; + OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score"), OUT_O("cu_part") }; static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT("scale"), OPD_O("page"), INOUT_O("cache") }; static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), diff --git a/libr4d/r4d_dsa.hip b/libr4d/r4d_dsa.hip index 839a2f8e..124b8a57 100644 --- a/libr4d/r4d_dsa.hip +++ b/libr4d/r4d_dsa.hip @@ -53,7 +53,7 @@ int query_body(const RadArgs* a, RadStream stream) { } struct ScoreMeta { long qr, qh, qsr, qsc, gr, gc, kr, ksr, btr, btc, cur, ncr, op; - int rows, blocks, seqs, pages; + int rows, blocks, seqs, pages, row0; }; __device__ uint32_t bytes4(const uint8_t* p) { if (!((uintptr_t)p & 3)) return *(const uint32_t*)p; @@ -61,7 +61,8 @@ __device__ uint32_t bytes4(const uint8_t* p) { } /* Two waves cover all 32 heads and reuse the query across `kScoreTiles` 16-key tiles, one up to 32 * blocks and two past them. FP8 dot products stay on WMMA; scales and the signed per-head gates - * fold only after the per-head ReLU. */ + * fold only after the per-head ReLU. The query operands start at a part's first row, so only the + * sequence lookup sees the step row (`row0 + r`). */ template __global__ void dsa_score_kernel(const uint8_t* q, const float* qs, const float* gate, const uint8_t* k, const float* ks, const int* bt, const int* cu, @@ -75,7 +76,7 @@ __global__ void dsa_score_kernel(const uint8_t* q, const float* qs, const float* if (!tid) { seq = -1; for (int s = 0; s < m.seqs; ++s) - if (r >= cu[(long)s * m.cur] && r < cu[(long)(s + 1) * m.cur]) { + if (m.row0 + r >= cu[(long)s * m.cur] && m.row0 + r < cu[(long)(s + 1) * m.cur]) { seq = s; break; } @@ -133,10 +134,14 @@ __global__ void dsa_score_kernel(const uint8_t* q, const float* qs, const float* out[(long)r * m.op + b0 + i] = pages[i] >= 0 ? (partial[0][i] + partial[1][i]) * scales[i] * 0.015625f : -INFINITY; } +/* The step's cu rebased to a part's first row: an op that reads cu over the part's own rows + * (qsa_select) then finds each row's sequence unchanged. */ +__global__ void dsa_rebase_kernel(const int* cu, int* out, long cs, long os, int n, int row0) { + for (int i = threadIdx.x; i < n; i += blockDim.x) out[(long)i * os] = cu[(long)i * cs] - row0; +} int score_body(const RadArgs* a, RadStream stream) { if (!a || a->n_t < 9) return RAD_E_INVAL; - RadTensor q = a->t[0], qs = a->t[1]; - const auto& g = a->t[2]; + RadTensor q = a->t[0], qs = a->t[1], g = a->t[2]; RadTensor k = a->t[3], ks = a->t[4]; const bool packed = k.dtype == RAD_U8; if (packed) { @@ -156,20 +161,41 @@ int score_body(const RadArgs* a, RadStream stream) { k.stride[1] = 1; } const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &o = a->t[8]; - if (q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && q.shape[0] == o.shape[0] * 32 && - qs.shape[0] == q.shape[0]) { + const RadTensor* cu_part = rad_arg_in(a, 9); + const long long part = r4d_geti_or(a, "row_part", -1); + if (q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && g.rank == 2 && + q.shape[0] == g.shape[0] * 32 && qs.shape[0] == q.shape[0]) { q.rank = 3; - q.shape[0] = o.shape[0]; + q.shape[0] = g.shape[0]; q.shape[2] = q.shape[1]; q.shape[1] = 32; q.stride[2] = q.stride[1]; q.stride[1] = q.stride[0]; q.stride[0] *= 32; - qs.shape[0] = o.shape[0]; + qs.shape[0] = g.shape[0]; qs.shape[1] = 32; qs.stride[1] = qs.stride[0]; qs.stride[0] *= 32; } + /* A part scores o's rows from step row part * rows; the query operands span the step. */ + const long long rows = o.rank == 2 ? o.shape[0] : 0, row0 = part > 0 ? part * rows : 0; + if (part >= 0) { + if (q.rank != 3 || qs.rank != 2 || g.rank != 2 || rows < 1 || part > INT_MAX / rows || + q.shape[0] < row0 + rows || qs.shape[0] != q.shape[0] || g.shape[0] != q.shape[0]) + return RAD_E_SHAPE; + if (q.data && qs.data && g.data) { + q.data = (uint8_t*)q.data + row0 * q.stride[0]; + qs.data = (float*)qs.data + row0 * qs.stride[0]; + g.data = (float*)g.data + row0 * g.stride[0]; + } + q.shape[0] = qs.shape[0] = g.shape[0] = rows; + } + if (cu_part) { + if (part < 0) return RAD_E_INVAL; + if (cu_part->dtype != RAD_I32) return RAD_E_DTYPE; + if (cu_part->rank != 1 || cu_part->shape[0] != cu.shape[0] || cu_part->stride[0] < 1) + return RAD_E_SHAPE; + } if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 || g.dtype != RAD_F32 || ks.dtype != RAD_F32 || o.dtype != RAD_F32 || bt.dtype != RAD_I32 || cu.dtype != RAD_I32 || nc.dtype != RAD_I32) @@ -194,7 +220,13 @@ int score_body(const RadArgs* a, RadStream stream) { ScoreMeta m{ q.stride[0], q.stride[1], qs.stride[0], qs.stride[1], g.stride[0], g.stride[1], k.stride[0], ks.stride[0], bt.stride[0], bt.stride[1], cu.stride[0], nc.stride[0], o.stride[0], (int)q.shape[0], (int)o.shape[1], - (int)bt.shape[0], (int)k.shape[0] }; + (int)bt.shape[0], (int)k.shape[0], (int)row0 }; + if (cu_part) { + const int rc = R4D_EMIT(stream, dsa_rebase_kernel, dim3(1), dim3(64), 0, + (const int*)cu.data, (int*)cu_part->data, cu.stride[0], + cu_part->stride[0], (int)cu.shape[0], (int)row0); + if (rc != RAD_OK) return rc; + } #define SCORE(NT) \ R4D_EMIT(stream, (dsa_score_kernel), dim3((m.blocks + 16 * NT - 1) / (16 * NT), m.rows), \ dim3(64), 0, (const uint8_t*)q.data, (const float*)qs.data, (const float*)g.data, \ diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 18121753..04afa4b6 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1748,11 +1748,13 @@ static const RadOperandSpec oMlaAttn[] = { { "q", RAD_OPD_IN, 0 }, { "length", RAD_OPD_IN, 0 }, { "out", RAD_OPD_OUT, 0 } }; static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), - P_INT("blocks"), P_INT("seqs"), P_STR("dtype") }; + P_INT("blocks"), P_INT("seqs"), P_STR("dtype"), + P_INTO("row_part") }; static const RadOperandSpec oDsaScore[] = { { "q", RAD_OPD_IN, 0 }, { "q_scale", RAD_OPD_IN, 0 }, { "gate", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, { "k_scale", RAD_OPD_IN, 1 }, { "bt", RAD_OPD_IN, 0 }, - { "cu", RAD_OPD_IN, 0 }, { "nc", RAD_OPD_IN, 0 }, { "score", RAD_OPD_OUT, 0 } + { "cu", RAD_OPD_IN, 0 }, { "nc", RAD_OPD_IN, 0 }, { "score", RAD_OPD_OUT, 0 }, + { "cu_part", RAD_OPD_OUT, 1 } }; static const RadOperandSpec oDsaPool[] = { { "kg", RAD_OPD_IN, 0 }, { "ape", RAD_OPD_WEIGHT, 0 }, { "q", RAD_OPD_OUT, 0 }, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 4db1345c..fbd56c2d 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -13481,6 +13481,43 @@ static void dsa_score_check(const Plugin& pl, int64_t rows, int64_t blocks, bool .c_str(), matches); ok("DSA scorer guards and pitched output", guards); + if (matches) { + /* The rows split into `parts` equal runs, each scored with `row_part` into its own + * plane: every run must be the unsplit rows' bytes, and cu_part the rebased bounds. */ + int64_t parts = rows; + for (int64_t d = 2; d < rows; ++d) + if (rows % d == 0) { + parts = d; + break; + } + const int64_t R = rows / parts, S = host[6].shape[0]; + bool same = true; + for (int64_t part = 0; part < parts && same; ++part) { + std::vector split = device; + split.push_back(T(nullptr, RAD_I32, { S })); + split[8] = T(nullptr, RAD_F32, { R, blocks }); + std::vector sp = ps; + sp[0] = PI("M", R); + sp.push_back(PI("row_part", part)); + run_case(row, split, sp); + std::vector plane((size_t)(R * blocks)); + std::vector cu_part((size_t)S); + st_memcpy(plane.data(), split[8].data, plane.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(cu_part.data(), split[9].data, cu_part.size() * 4, hipMemcpyDeviceToHost); + for (int64_t r = 0; r < R; ++r) + same = same && std::memcmp(&plane[(size_t)(r * blocks)], + got.data() + 128 + + (size_t)((part * R + r) * out.stride[0]) * 4, + (size_t)blocks * 4) == 0; + for (int64_t i = 0; i < S; ++i) + same = same && cu_part[(size_t)i] == + ((int32_t*)host[6].data)[i * host[6].stride[0]] - part * R; + } + ok(fmt("DSA scorer split into %lld row parts: each the unsplit rows' bytes, cu rebased", + (long long)parts) + .c_str(), + same); + } if (packed) { std::vector after(packed_bytes.size()); st_memcpy(after.data(), packed_device, after.size(), hipMemcpyDeviceToHost); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 075a34e3..35d281e5 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -674,7 +674,8 @@ extern "C" int r4d_shape_dsa_score(const RadParam* p, int n_p, int operand, RadO opd_idx(S, B, pages), opd_idx(S + 1, 0, M, -1, RAD_OPD_F_IDX_CU), opd_idx(S, 0, 0, B), - opd((uint32_t)RAD_F32, M, B) }; + opd((uint32_t)RAD_F32, M, B), + opd_none() }; R4D_PICK(l); } extern "C" int r4d_shape_mla_attn(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/libref/ref_dsa.cpp b/libref/ref_dsa.cpp index 8ce2a790..bf53ce1b 100644 --- a/libref/ref_dsa.cpp +++ b/libref/ref_dsa.cpp @@ -67,17 +67,19 @@ int ref_dsa_score(const RadArgs* a, RadStream) { k.stride[1] = 1; } const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &out = a->t[8]; + const RadTensor* cu_part = rad_arg_in(a, 9); const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0); - if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && - q.shape[0] == out.shape[0] * h && qs.shape[0] == q.shape[0]) { + const int64_t part = p_int(a, "row_part", -1); + if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && gate.rank == 2 && + q.shape[0] == gate.shape[0] * h && qs.shape[0] == q.shape[0]) { q.rank = 3; - q.shape[0] = out.shape[0]; + q.shape[0] = gate.shape[0]; q.shape[2] = q.shape[1]; q.shape[1] = h; q.stride[2] = q.stride[1]; q.stride[1] = q.stride[0]; q.stride[0] *= h; - qs.shape[0] = out.shape[0]; + qs.shape[0] = gate.shape[0]; qs.shape[1] = h; qs.stride[1] = qs.stride[0]; qs.stride[0] *= h; @@ -87,9 +89,14 @@ int ref_dsa_score(const RadArgs* a, RadStream) { gate.shape[0] != q.shape[0] || qs.shape[1] != h || gate.shape[1] != h || k.rank != 2 || k.shape[1] != n || ks.rank != 1 || ks.shape[0] != k.shape[0] || bt.rank != 2 || cu.rank != 1 || nc.rank != 1 || cu.shape[0] != bt.shape[0] + 1 || - nc.shape[0] != bt.shape[0] || out.rank != 2 || out.shape[0] != q.shape[0] || + nc.shape[0] != bt.shape[0] || out.rank != 2 || + (part < 0 ? out.shape[0] != q.shape[0] + : out.shape[0] < 1 || q.shape[0] < (part + 1) * out.shape[0]) || out.shape[1] > bt.shape[1]) return RAD_E_SHAPE; + if (cu_part && (part < 0 || cu_part->rank != 1 || cu_part->shape[0] != cu.shape[0])) + return part < 0 ? RAD_E_INVAL : RAD_E_SHAPE; + if (cu_part && cu_part->dtype != RAD_I32) return RAD_E_DTYPE; if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 || ks.dtype != RAD_F32 || gate.dtype != RAD_F32 || bt.dtype != RAD_I32 || cu.dtype != RAD_I32 || nc.dtype != RAD_I32 || out.dtype != RAD_F32) @@ -97,8 +104,15 @@ int ref_dsa_score(const RadArgs* a, RadStream) { for (int i = 0; i < 9; ++i) if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL; const float norm = 1.0f / std::sqrt((float)(h * n)); + /* A part scores out's rows from step row part * rows; the query operands span the step. */ + const int64_t row0 = part > 0 ? part * out.shape[0] : 0; + if (cu_part) + for (int64_t s = 0; s < cu.shape[0]; ++s) + st_int(RAD_I32, cu_part->data, s * cu_part->stride[0], + ld_int(cu.dtype, cu.data, s * cu.stride[0]) - row0); #pragma omp parallel for schedule(static) - for (int64_t r = 0; r < q.shape[0]; ++r) { + for (int64_t o = 0; o < out.shape[0]; ++o) { + const int64_t r = row0 + o; int64_t seq = -1; for (int64_t s = 0; s < bt.shape[0]; ++s) if (r >= ld_int(cu.dtype, cu.data, s * cu.stride[0]) && @@ -126,7 +140,7 @@ int ref_dsa_score(const RadArgs* a, RadStream) { } result *= ldt(&ks, page * ks.stride[0]) * norm; } - stt(&out, r * out.stride[0] + b * out.stride[1], result); + stt(&out, o * out.stride[0] + b * out.stride[1], result); } } return RAD_OK; diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index f7da5fa3..86e6dd0b 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -170,9 +170,9 @@ static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("h P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") }; static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") }; static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), - P_INT("blocks"), P_INT("seqs"), P_STR("dtype") }; + P_INT("blocks"), P_INT("seqs"), P_STR("dtype"), P_INTO("row_part") }; static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"), - OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") }; + OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score"), OUT_O("cu_part") }; static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT("scale"), OPD_O("page"), INOUT_O("cache") }; static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index cb0d7f21..48470cc3 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -737,6 +737,7 @@ int ref_dsa_score_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out o.t_idx({ S + 1 }, M, -1, RAD_OPD_F_IDX_CU); o.t_idx({ S }, 0, B, 0); o.t(RAD_F32, { M, B }); + o.skip(); // cu_part: a part's rebased bounds, exercised by the split's own tests. return o.finish("dsa_score", operand, out); } int ref_mla_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 74a07b0b..bab5307a 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -361,16 +361,18 @@ endif() # ================================================================== libr4d's kernels, on the host # # Some libr4d ops (the sandwich-norm joins, expert_scale) have no libref oracle by design -# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of thirteen units +# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of fourteen units # written against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins, # expert_scale, the QSA block selection, the runtime-LoRA pair, the F32 routing projection's tile # forms, GLM's mHC read with its chunk split, the F32-scale E4M3 GEMM's forms, GLM's KDA -# recurrence, the MXFP4 expert GEMM's forms, the MLA matrix row's pairings and GLM's MoE decode -# fusions, whose kernels a card-less build otherwise never runs. emu/hip/hip_runtime.h supplies the -# HIP names, each GPU thread is a fiber, and __syncthreads and cross-lane ops are barriers (one not -# reached uniformly is reported as a deadlock). Checked against ports of libref's ref_attn_paged and -# ref_qsa_select, the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, -# for the LoRA pair libref itself when the test can load it, and for KDA libref itself. +# recurrence, the MXFP4 expert GEMM's forms, the MLA matrix row's pairings, GLM's MoE decode +# fusions and GLM's DSA scoring split by query rows, whose kernels a card-less build otherwise +# never runs. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread is a fiber, and +# __syncthreads and cross-lane ops are barriers (one not reached uniformly is reported as a +# deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select, the host +# arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, for the LoRA pair libref +# itself when the test can load it, for KDA libref itself, and for the DSA split the unsplit +# kernels. # # Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang # C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so @@ -384,8 +386,9 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_ ${R4D_DIR}/r4d_norm_join_bf16.hip ${R4D_DIR}/r4d_expert_scale_bf16.hip ${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip ${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip - ${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip) -set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse) + ${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip + ${R4D_DIR}/r4d_dsa.hip) +set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa) set(R4D_EMU_BUILT OFF) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") # No fiber switch for this ISA. @@ -424,7 +427,7 @@ else() ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp ${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp ${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp - ${R4D_EMU}/test_moefuse.cpp) + ${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp) get_filename_component(stem ${src} NAME_WE) set(lang "") if(src MATCHES "\\.hip$") @@ -461,7 +464,7 @@ else() endif() endif() if(R4D_EMU_BUILT) - foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse) + foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa) add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t}) endforeach() # The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel, @@ -472,6 +475,7 @@ if(R4D_EMU_BUILT) endforeach() set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse + r4d_emu_dsa PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT}) # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can # load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within diff --git a/tests/r4d_emu/test_dsa.cpp b/tests/r4d_emu/test_dsa.cpp new file mode 100644 index 00000000..bfe879be --- /dev/null +++ b/tests/r4d_emu/test_dsa.cpp @@ -0,0 +1,247 @@ +/* tests/r4d_emu: GLM's DSA scoring and selection split over the tensor-parallel ranks by query + * rows (r4d_dsa.hip, then r4d_qsa_select_bf16.hip) on the host SIMT emulator. + * + * Each rank scores its run of R = 4 * ceil(M / (4 * world)) rows with `row_part`, selects over + * the rows of that run that exist with the rebased bounds the scorer wrote (`cu_part`), and the + * runs are laid end to end as the all_gather concatenates them. The joined table, nsel and + * seqused must equal the unsplit scorer and selection byte for byte on every row of the step; a + * run's scores must equal the unsplit scores' rows, and its rows past the step score -inf. The + * fixtures mix decode rows with a prefill chunk, a missing page, duplicated keys (exact ties) and + * signed gates, at world sizes where every rank has rows and where the last ranks have none. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int kHeads = 32, kN = 128, kRatio = 4, kPitch = 136; + +RadTensor tens(void* p, uint32_t dt, std::vector shape) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + t.shape[i] = shape[i]; + t.stride[i] = st; + st *= shape[i]; + } + return t; +} + +struct Fix { + int S = 0, M = 0, nb = 0, pages = 0, topk = 0; + std::vector cu, nc, pos, bt; + std::vector q, cache; /* [M*32, 128] codes; [pages, 1, 4, 34] packed keys */ + std::vector qs, gate; /* [M*32, 1], [M, 32] */ +}; + +/* `decode` one-row sequences, then one prefill chunk of `chunk` rows at `start`. */ +Fix make(uint32_t seed, int decode, int chunk, int start, int topk) { + std::mt19937 rng(seed); + std::uniform_int_distribution byte(0, 255), coin(0, 99); + std::normal_distribution nd(0.f, 1.f); + Fix f; + f.S = decode + 1; + f.M = decode + chunk; + f.topk = topk; + f.cu.push_back(0); + for (int s = 0; s < decode; ++s) { + const int p = 40 + 37 * s + byte(rng) % 50; + f.pos.push_back(p); + f.cu.push_back(f.cu.back() + 1); + f.nc.push_back((p + 1) / kRatio); + } + for (int i = 0; i < chunk; ++i) f.pos.push_back(start + i); + f.cu.push_back(f.M); + f.nc.push_back((start + chunk) / kRatio); + for (int c : f.nc) f.nb = std::max(f.nb, c + 2); + f.pages = f.S * f.nb + 3; + f.bt.assign((size_t)f.S * f.nb, -1); + for (int s = 0; s < f.S; ++s) + for (int b = 0; b <= f.nc[s] && b < f.nb; ++b) + f.bt[(size_t)s * f.nb + b] = (s * f.nb + b * 7) % f.pages; + f.bt[(size_t)(f.S - 1) * f.nb + 3] = -1; + auto code = [&] { + int v; + do v = byte(rng); + while ((v & 0x7f) == 0x7f); + return (uint8_t)v; + }; + f.cache.assign((size_t)f.pages * kPitch, 0); + for (int p = 0; p < f.pages; ++p) { + uint8_t* page = &f.cache[(size_t)p * kPitch]; + /* Every fifth page repeats its predecessor's key: equal scores on one row. */ + if (p % 5 == 4) + std::memcpy(page, page - kPitch, kPitch); + else { + for (int d = 0; d < kN; ++d) page[d] = code(); + const float scale = std::ldexp(1.0f, -6 - p % 3); + std::memcpy(page + kN, &scale, 4); + } + } + f.q.resize((size_t)f.M * kHeads * kN); + for (auto& v : f.q) v = code(); + f.qs.resize((size_t)f.M * kHeads); + for (size_t i = 0; i < f.qs.size(); ++i) f.qs[i] = std::ldexp(1.0f, -5 - (int)(i % 3)); + f.gate.resize((size_t)f.M * kHeads); + for (auto& v : f.gate) v = nd(rng) * (coin(rng) < 10 ? 0.0f : 1.0f); + return f; +} + +RadParam pint(const char* k, long long v) { return { k, RAD_P_INT, v, 0, nullptr }; } + +/* Scores `rows` score rows from step row `part * rows` (part < 0: the whole step, no row_part). */ +int score(const Fix& f, const uint8_t* q, const float* qs, const float* gate, int64_t qrows, + int part, int rows, float* out, int32_t* cu_part) { + RadTensor t[10] = { + tens((void*)q, RAD_F8E4M3, { qrows * kHeads, kN }), + tens((void*)qs, RAD_F32, { qrows * kHeads, 1 }), + tens((void*)gate, RAD_F32, { qrows, kHeads }), + tens((void*)f.cache.data(), RAD_U8, { f.pages, 1, 4, 34 }), + RadTensor{}, + tens((void*)f.bt.data(), RAD_I32, { f.S, f.nb }), + tens((void*)f.cu.data(), RAD_I32, { f.S + 1 }), + tens((void*)f.nc.data(), RAD_I32, { f.S }), + tens(out, RAD_F32, { rows, f.nb }), + cu_part ? tens(cu_part, RAD_I32, { f.S + 1 }) : RadTensor{}, + }; + t[3].stride[0] = kPitch; + RadParam p[7] = { pint("M", rows), pint("n", kN), pint("heads", kHeads), pint("blocks", f.nb), + pint("seqs", f.S), { "dtype", RAD_P_STR, 0, 0, "fp8_e4m3" }, + pint("row_part", part) }; + RadArgs a{}; + a.t = t; + a.n_t = 10; + a.p = p; + a.n_p = part < 0 ? 6 : 7; + return r4d_rad_dsa_score(&a, nullptr); +} + +int select(const Fix& f, const float* sc, int rows, const int32_t* pos, const int32_t* cu, + int32_t* sel, int32_t* nsel, int32_t* seqused) { + RadTensor t[8] = { + tens((void*)sc, RAD_F32, { rows, f.nb }), + tens((void*)f.bt.data(), RAD_I32, { f.S, f.nb }), + tens((void*)f.nc.data(), RAD_I32, { f.S }), + tens((void*)pos, RAD_I32, { rows }), + tens((void*)cu, RAD_I32, { f.S + 1 }), + tens(sel, RAD_I32, { rows, f.topk + 1 }), + tens(nsel, RAD_I32, { rows }), + tens(seqused, RAD_I32, { rows }), + }; + RadParam p[6] = { pint("M", rows), pint("blocks", f.nb), pint("topk", f.topk), + pint("ratio", kRatio), pint("seqs", f.S), pint("signed", 1) }; + RadArgs a{}; + a.t = t; + a.n_t = 8; + a.p = p; + a.n_p = 6; + const int64_t need = r4d_rad_qsa_select_scratch(&a); + std::vector scratch((size_t)(need / 4 + 1), 0xA5A5A5A5u); + a.scratch = scratch.data(); + a.scratch_bytes = need; + return r4d_rad_qsa_select(&a, nullptr); +} + +int check(const char* name, const Fix& f) { + const int M = f.M, K = f.topk + 1; + std::vector want_sc((size_t)M * f.nb); + std::vector want_sel((size_t)M * K, 0x55555555), want_n(M), want_su(M); + if (score(f, f.q.data(), f.qs.data(), f.gate.data(), M, -1, M, want_sc.data(), nullptr) || + select(f, want_sc.data(), M, f.pos.data(), f.cu.data(), want_sel.data(), want_n.data(), + want_su.data())) { + std::printf("FAIL %s: the unsplit launch\n", name); + return 1; + } + int fails = 0; + for (int world : { 2, 4, 8 }) { + const int R = 4 * ((M + 4 * world - 1) / (4 * world)); + const int64_t padded = (int64_t)world * R; + /* The step's query rows, then rows past the step that a last run reads no further than. */ + std::vector q((size_t)padded * kHeads * kN, 0x38); + std::vector qs((size_t)padded * kHeads, 1.0f), gate((size_t)padded * kHeads, 3.0f); + std::memcpy(q.data(), f.q.data(), f.q.size()); + std::memcpy(qs.data(), f.qs.data(), f.qs.size() * 4); + std::memcpy(gate.data(), f.gate.data(), f.gate.size() * 4); + std::vector sel((size_t)padded * K, 0x55555555), ns(padded, 0x55555555), + su(padded, 0x55555555); + bool ok = true; + const char* why = ""; + for (int part = 0; part < world && ok; ++part) { + const int r0 = part * R, have = std::min(R, M - r0); + std::vector sc((size_t)R * f.nb, 7.0f); + std::vector cu_part(f.S + 1, 0x55555555); + if (score(f, q.data(), qs.data(), gate.data(), padded, part, R, sc.data(), + cu_part.data())) { + ok = false, why = "score launch"; + break; + } + for (int s = 0; s <= f.S; ++s) ok = ok && cu_part[s] == f.cu[s] - r0; + if (!ok) { + why = "cu_part"; + break; + } + for (int i = 0; i < R && ok; ++i) + for (int b = 0; b < f.nb && ok; ++b) { + const float v = sc[(size_t)i * f.nb + b]; + ok = i < have ? std::memcmp(&v, &want_sc[(size_t)(r0 + i) * f.nb + b], 4) == 0 + : v == -INFINITY; + } + if (!ok) { + why = "scores"; + break; + } + if (have <= 0) continue; + if (select(f, sc.data(), have, f.pos.data() + r0, cu_part.data(), &sel[(size_t)r0 * K], + &ns[r0], &su[r0])) { + ok = false, why = "select launch"; + break; + } + } + if (ok) { + ok = std::memcmp(sel.data(), want_sel.data(), want_sel.size() * 4) == 0; + why = "selection"; + } + if (ok) { + ok = std::memcmp(ns.data(), want_n.data(), (size_t)M * 4) == 0 && + std::memcmp(su.data(), want_su.data(), (size_t)M * 4) == 0; + why = "nsel or seqused"; + } + if (!ok) { + std::printf("FAIL %s world %d (R %d): %s differs\n", name, world, R, why); + ++fails; + } + } + return fails; +} + +} // namespace + +int main() { + int fails = 0, cases = 0; + struct Case { + const char* name; + uint32_t seed; + int decode, chunk, start, topk; + } cases_[] = { + { "prefill chunk alone", 1, 0, 64, 300, 16 }, + { "decode rows beside a chunk", 2, 6, 61, 517, 32 }, + { "chunk from position 0, short history", 3, 2, 37, 0, 8 }, + { "rows below topk blocks", 4, 3, 29, 20, 64 }, + }; + for (const auto& c : cases_) { + fails += check(c.name, make(c.seed, c.decode, c.chunk, c.start, c.topk)); + ++cases; + } + std::printf("dsa split: %d fixture(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index df09db24..620d2e63 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -486,6 +486,49 @@ TEST(dsa_score_relu_is_per_head_before_signed_weights_and_masks_invalid_history) CHECK_EQ(out.at(0), -INFINITY); } +TEST(dsa_score_row_part_scores_its_run_of_rows_and_rebases_cu) { + T q(RAD_F8E4M3, { 2, 2, 2 }), qs(RAD_F32, { 2, 2 }), gate(RAD_F32, { 2, 2 }); + T k(RAD_F8E4M3, { 3, 2 }), ks(RAD_F32, { 3 }), bt(RAD_I32, { 2, 3 }); + T cu(RAD_I32, { 3 }), nc(RAD_I32, { 2 }), out(RAD_F32, { 1, 3 }), cu_part(RAD_I32, { 3 }); + q.f({ 1, 0, 0, 1, -1, 0, 0, -1 }); + qs.f({ 2, 0.5, 1, 1 }); + gate.f({ -1, 4, 2, -1 }); + k.f({ 1, -1, 2, 3, -2, -4 }); + ks.f({ 0.25, 0.5, 1 }); + bt.n({ 0, 1, -1, 2, 0, 1 }); + cu.n({ 0, 1, 2 }); + nc.n({ 2, 1 }); + A a; + a.t(q).t(qs).t(gate).t(k).t(ks).t(bt).t(cu).t(nc).t(out).t(cu_part); + a.i("M", 1).i("n", 2).i("heads", 2).i("blocks", 3).i("seqs", 2).s("dtype", "fp8_e4m3"); + a.i("row_part", 1); + REQUIRE_EQ(run("dsa_score", a), RAD_OK); + CHECK_EQ(out.at(0), 0); + CHECK_EQ(out.at(1), -INFINITY); + CHECK_EQ(out.at(2), -INFINITY); + CHECK_EQ(cu_part.at(0), -1); + CHECK_EQ(cu_part.at(1), 0); + CHECK_EQ(cu_part.at(2), 1); + /* Part 2 of one-row runs is past the step: no sequence holds its row. */ + T q3(RAD_F8E4M3, { 3, 2, 2 }), qs3(RAD_F32, { 3, 2 }), gate3(RAD_F32, { 3, 2 }); + q3.f({ 1, 0, 0, 1, -1, 0, 0, -1, 1, 1, 1, 1 }); + qs3.f({ 2, 0.5, 1, 1, 1, 1 }); + gate3.f({ -1, 4, 2, -1, 1, 1 }); + A past; + past.t(q3).t(qs3).t(gate3).t(k).t(ks).t(bt).t(cu).t(nc).t(out).t(cu_part); + past.i("M", 1).i("n", 2).i("heads", 2).i("blocks", 3).i("seqs", 2).s("dtype", "fp8_e4m3"); + past.i("row_part", 2); + REQUIRE_EQ(run("dsa_score", past), RAD_OK); + for (int i : { 0, 1, 2 }) CHECK_EQ(out.at(i), -INFINITY); + CHECK_EQ(cu_part.at(2), 0); + /* A part needs query rows for its whole run. */ + A short_q; + short_q.t(q).t(qs).t(gate).t(k).t(ks).t(bt).t(cu).t(nc).t(out).t(cu_part); + short_q.i("M", 1).i("n", 2).i("heads", 2).i("blocks", 3).i("seqs", 2).s("dtype", "fp8_e4m3"); + short_q.i("row_part", 2); + CHECK_EQ(run("dsa_score", short_q), RAD_E_SHAPE); +} + TEST(kda_anchor_replays_only_the_accepted_prefix_of_the_previous_window) { constexpr int D = 128; for (int accepted : { 1, 2, 3 }) { From 66812280bb7da08198002f445a22da45109503fb Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:11 +0200 Subject: [PATCH 127/152] r4d_selftest: --perfdsa -- GLM's DSA indexer timed at a context length, whole and as one rank's run dsa_score scores every complete block of each row's sequence and qsa_select ranks them, so both grow with the context in decode as in prefill. --perfdsa CTX [M] [iters] times them at M rows in the packed-cache form glm5next issues, and as one rank's run of a step split over 2, 4 and 8 ranks by rows (dsa_score's row_part), printing what the split saves before its two all_gathers. On one R9700, 48 rows (eight sequences verifying five drafts) take 273 + 155 us at 60k of context and a run of 8 rows 53 + 21 us; six rows save 9 us. qsa_select at 4000 blocks takes 89 us for any row count up to 32: its split path needs two chunks of 4096, so a list of 3500 to 4096 blocks falls to the single-workgroup kernel past its key cache. Co-Authored-By: Claude Fable 5.1 --- libr4d/r4d_selftest.cpp | 138 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 137 insertions(+), 1 deletion(-) diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index fbd56c2d..f6a5e42f 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -12660,6 +12660,122 @@ static void qsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { (double)M * live * 8.0); } +/* ------------------------------------------------------------- GLM's DSA indexer, timed at length + * + * dsa_score scores every complete block of a row's sequence and qsa_select ranks them, so both + * grow with context, in decode as in prefill. Timed whole at M rows, and as one rank's run of a + * step split over 2, 4 and 8 ranks by rows (`row_part`, R = 4 * ceil(M / (4 * ranks)) rows): the + * difference is what a split saves before its two all_gathers. The packed cache form, the + * declared width the live reach plus one, as glm5next issues them. */ +static void dsa_perf(const Plugin& pl, int64_t ctx, int64_t M, int iters) { + if (iters <= 0) iters = 100; + const int64_t heads = 32, n = 128, ratio = 4, topk = 512; + const int64_t live = ctx / ratio, nb = live + 2, pages = live + 1; + if (live < 1 || M < 1) { std::printf("--perfdsa: ctx or M out of range\n"); return; } + const int64_t rows = std::max(M, 8 * 4 * ((M + 31) / 32)); /* every run fits */ + std::printf("dsa indexer at ctx=%lld (%lld blocks), M=%lld, %d launches\n", (long long)ctx, + (long long)live, (long long)M, iters); + std::vector qh((size_t)(rows * heads * n)), kh((size_t)(pages * 136), 0); + for (size_t i = 0; i < qh.size(); ++i) qh[i] = (uint8_t)((i * 37 + 11) % 0x7e); + for (int64_t p = 0; p < pages; ++p) { + for (int64_t d = 0; d < n; ++d) kh[(size_t)(p * 136 + d)] = (uint8_t)((p * 29 + d * 7) % 0x7e); + const float sc = std::ldexp(1.0f, -6 - (int)(p % 3)); + std::memcpy(&kh[(size_t)(p * 136 + 128)], &sc, 4); + } + std::vector qsh((size_t)(rows * heads)), gh((size_t)(rows * heads)); + for (size_t i = 0; i < qsh.size(); ++i) { + qsh[i] = std::ldexp(1.0f, -5 - (int)(i % 3)); + gh[i] = (float)((int)((i * 53) % 201) - 100) / 100.0f; + } + std::vector bth((size_t)nb, -1), nch(1, (int32_t)live), cuh = { 0, (int32_t)M }, + posh((size_t)rows); + for (int64_t b = 0; b <= live; ++b) bth[(size_t)b] = (int32_t)((b * 7919 + 13) % pages); + for (int64_t m = 0; m < rows; ++m) posh[(size_t)m] = (int32_t)(ctx - M + std::min(m, M - 1)); + void *d_q = dalloc(qh.size()), *d_qs = dalloc(qsh.size() * 4), *d_g = dalloc(gh.size() * 4), + *d_k = dalloc(kh.size()), *d_bt = dalloc(bth.size() * 4), *d_nc = dalloc(4), + *d_cu = dalloc(8), *d_cp = dalloc(8), *d_po = dalloc(posh.size() * 4), + *d_sc = dalloc((size_t)(rows * nb) * 4), *d_se = dalloc((size_t)(rows * (topk + 1)) * 4), + *d_ns = dalloc((size_t)rows * 4), *d_su = dalloc((size_t)rows * 4); + if (!d_q || !d_qs || !d_g || !d_k || !d_bt || !d_nc || !d_cu || !d_cp || !d_po || !d_sc || + !d_se || !d_ns || !d_su) { + std::printf(" alloc failed\n"); + return; + } + st_memcpy(d_q, qh.data(), qh.size(), hipMemcpyHostToDevice); + st_memcpy(d_qs, qsh.data(), qsh.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_g, gh.data(), gh.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_k, kh.data(), kh.size(), hipMemcpyHostToDevice); + st_memcpy(d_bt, bth.data(), bth.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_nc, nch.data(), 4, hipMemcpyHostToDevice); + st_memcpy(d_cu, cuh.data(), 8, hipMemcpyHostToDevice); + st_memcpy(d_po, posh.data(), posh.size() * 4, hipMemcpyHostToDevice); + auto run = [&](const char* row, std::vector ts, std::vector ps) { + const RadKernelInfo* r = find(pl, row); + if (!r) return -1.0; + 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(); + if (r->scratch) { + const int64_t need = r->scratch(&a); + if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; } + } + if (r->launch(&a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return -1.0; + hipEvent_t w0, w1; /* clocks up first, as in qsa_perf */ + st_ev_create(&w0); st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0.0f; + for (int guard = 0; guard < 100000 && wms < 300.0f; ++guard) { + for (int i = 0; i < 32; ++i) r->launch(&a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); st_ev_destroy(w1); + return st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + }; + auto score = [&](int64_t R, bool part) { + RadTensor sc = T(d_sc, RAD_F32, { R, nb }); + sc.shape[1] = live + 1; + std::vector ts = { T(d_q, RAD_F8E4M3, { rows * heads, n }), + T(d_qs, RAD_F32, { rows * heads, 1 }), + T(d_g, RAD_F32, { rows, heads }), + T(d_k, RAD_U8, { pages, 1, 4, 34 }), RadTensor{}, + T(d_bt, RAD_I32, { 1, nb }), T(d_cu, RAD_I32, { 2 }), + T(d_nc, RAD_I32, { 1 }), sc, + part ? T(d_cp, RAD_I32, { 2 }) : RadTensor{} }; + std::vector ps = { PI("M", R), PI("n", n), PI("heads", heads), + PI("blocks", nb), PI("seqs", 1), PS("dtype", "fp8_e4m3") }; + if (part) ps.push_back(PI("row_part", 0)); + else { + ts[0].shape[0] = R * heads; /* whole: the query planes are the step's M rows */ + ts[1].shape[0] = R * heads; + ts[2].shape[0] = R; + } + return run("dsa_score_fp8", ts, ps); + }; + auto select = [&](int64_t R) { + RadTensor sc = T(d_sc, RAD_F32, { R, nb }); + sc.shape[1] = live + 1; + return run("qsa_select_i32", + { sc, T(d_bt, RAD_I32, { 1, nb }), T(d_nc, RAD_I32, { 1 }), + T(d_po, RAD_I32, { R }), T(d_cu, RAD_I32, { 2 }), + T(d_se, RAD_I32, { R, topk + 1 }), T(d_ns, RAD_I32, { R }), + T(d_su, RAD_I32, { R }) }, + { PI("M", R), PI("blocks", nb), PI("topk", topk), PI("ratio", ratio), + PI("seqs", 1), PI("signed", 1) }); + }; + const double s_all = score(M, false), q_all = select(M); + std::printf(" whole, %5lld rows dsa_score %9.2f us qsa_select %9.2f us\n", + (long long)M, s_all, q_all); + for (int64_t world : { 2, 4, 8 }) { + const int64_t R = 4 * ((M + 4 * world - 1) / (4 * world)), have = std::min(R, M); + const double s = score(R, true), q = select(have); + std::printf(" run of %lld ranks, %5lld rows dsa_score %9.2f us qsa_select %9.2f us " + "saves %8.2f us before its gathers\n", + (long long)world, (long long)R, s, q, s_all + q_all - s - q); + } +} /* The routed-expert GEMM at a prefill chunk, both projections, every prefill form. * @@ -26900,6 +27016,9 @@ static void usage(void) { " own top blocks-1 in block order, d blocks exchanged between\n" " neighbours (context 16*(blocks-1) tokens by default). Each matrix\n" " form also reports its second passes.\n" + " --perfdsa CTX [M] [iters]: GLM's DSA indexer (dsa_score, qsa_select) at a\n" + " real context length and M rows, whole and as one rank's run of a\n" + " step split over 2, 4 and 8 ranks by rows.\n" " --perfqsa CTX [M] [iters]: the QSA indexer at a real context length. It is\n" " the only decode op that grows with context, and at 200K it is\n" " about a third of the step. M is 1 + n_spec.\n" @@ -26916,7 +27035,8 @@ int main(int argc, char** argv) { int perf_it = 50, perf_w2 = 0, perf_bf = 0, perf_w8 = 0, perf_f32 = 0, perf_q = 0; long long sop_m = 0, sop_k = 0; int sop_it = 2000; - long long qsa_ctx = 0, qsa_m = 4; + long long qsa_ctx = 0, qsa_m = 4, dsa_ctx = 0, dsa_m = 6; + int dsa_it = 100; long long mla_m = 0, mla_blocks = 0, mla_heads = 0; int mla_it = 20; const char* mla_fill = "prefill"; @@ -27008,6 +27128,12 @@ int main(int argc, char** argv) { perf_k = std::strtoll(argv[++i], nullptr, 0); perf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfdsa")) { + /* GLM's DSA indexer at a real context length, whole and as a rank's run. */ + if (i + 1 >= argc) { usage(); return 2; } + dsa_ctx = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) dsa_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) dsa_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfqsa")) { /* The indexer at a real context length (the only decode op that grows with it). */ if (i + 1 >= argc) { usage(); return 2; } @@ -27296,6 +27422,16 @@ int main(int argc, char** argv) { dfree_all(); #else skip("MLA attention timing", "built without HIP"); +#endif + return 0; + } + if (dsa_ctx) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + dsa_perf(pl, dsa_ctx, dsa_m, dsa_it); + dfree_all(); +#else + skip("dsa indexer timing", "built without HIP"); #endif return 0; } From 1ad675e10c267dfcd6382327875834f330b9e746 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:11 +0200 Subject: [PATCH 128/152] glm5next: the DSA indexer scores and selects by query rows over the ranks -- the prefill op that grows with context runs a run of rows a rank, bit for bit Every rank scored every query row of a step against every complete block of its sequence and selected its 512 blocks, the same work eight times: 58 ms of a 1029 ms step at a 4096-row chunk and 20k of context, about 185 ms at 64k, the largest op that grows with the context. From GlmTp::kSplitRows each rank now scores one run of the step's rows with dsa_score's row_part, selects for the rows of its run under the bounds the scorer rebased (cu_part), and two all_gathers lay the page tables and lengths end to end (8 MiB a layer at 4096 rows). The key side stays replicated. The run's queries are all a rank needs, so the query projection, its quantiser and the head gates run on the run's rows too, and the gates lose their column split and gather; the bf16 projection stays on the step's rows where a run would be 64 rows or fewer, the skinny band whose split count a tuned configuration may set. Each row's selection is the same kernels' answer to the same operands, so the joined table is bit-identical to the replicated one and MLA reads it unchanged. The rule for a run is GlmTp's, stated once: ceil(T / world) rows rounded up to whole 16-byte words of the gathered row, because an all_gather moves whole words; the indexer gathers one i32 length a row, so its runs are multiples of four (DsaCache::part_rows). A rank whose run lies wholly past a small step takes the first run and computes dead rows, so every plane it gathers is written (GlmTp::run_of). The selection planes hold world runs, which can reach past the step, and the score plane shrinks to one run, 256 MiB to 32 MiB at 64k of context and a 4096-row chunk. A decode step splits too once rows x live blocks reach 2^18 from 16 rows (GlmTp::kSplitWork): eight sequences verifying five drafts from about 22k of context, where scoring 48 rows over 8000 blocks (250 us on one R9700) outweighs the two eight-rank gathers (about 50 us); a single sequence's six rows never pay. The replicated issue passes cu_part absent as its tenth operand, because the engine counts operands against the schema and refused the nine-operand issue at a served engine's first long prompt. On eight R9700s (TP8, two ranks on Gen4 x8 that day) a 19887-token prompt prefills 3927 tok/s against 3748 on 1.9.0, 7881 tokens 3990 against 3655, 2k 3849 against 3663; greedy text with the adaptive draft window is identical. r4d_emu splits decode rows beside a prefill chunk at 2, 4 and 8 ranks and joins the runs as the gather does, byte for byte against the unsplit scorer; glm5next_test declares the split at 2 and 8 ranks with the lint, holds the row rule to the formula it replaced at every world, and pins the graph and steps (world 1 0xed3fc26c486ea1b5 / 0x33e5f136f0dbba15, world 8 0x712f01858dbe1047 / 0xf9e357b1333c638f). dsa_score_fp8's selftest passes 62 of 62 on eight cards, and --perfdsa times the indexer whole and as one rank's run. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- arch/common/rad_block_glm_indexer.h | 159 +++++++++++++++--- arch/common/rad_glm_tp.h | 60 +++++-- arch/glm5next/glm5next.cpp | 30 +++- docs/ARCHITECTURES.md | 41 ++++- tests/glm5next_test.cpp | 242 ++++++++++++++++++++++++++-- 5 files changed, 474 insertions(+), 58 deletions(-) diff --git a/arch/common/rad_block_glm_indexer.h b/arch/common/rad_block_glm_indexer.h index 18ed8c56..de68ff66 100644 --- a/arch/common/rad_block_glm_indexer.h +++ b/arch/common/rad_block_glm_indexer.h @@ -5,9 +5,13 @@ * gates. No RoPE; the only rotation is the Hadamard inside dsa_query. Selected pages belong to * the MLA. * - * Under tensor parallelism the indexer is replicated whole: every rank pools into the whole index - * cache, scores every query row against it and selects for every row. Only the head gates' f32 - * projection splits its columns from GlmTp::kSplitRows (SplitF32Proj). */ + * Under tensor parallelism the key side stays replicated (every rank pools into the whole index + * cache and scores against it), but from GlmTp::kSplitRows rows, or a smaller step whose rows x + * live blocks reach GlmTp::kSplitWork, each rank scores and selects for its own run of query rows + * (GlmTp::run_of) and two all_gathers join the runs' page tables and lengths: every row's + * selection is computed by the same kernels from the same operands as on one rank, so the joined + * table is the replicated one's bits. The query side (projection, head gates, quantiser) then runs + * on this rank's run of rows only, since no other rank reads them. */ #ifndef RAD_BLOCK_GLM_INDEXER_H #define RAD_BLOCK_GLM_INDEXER_H #include "rad_fp8.h" @@ -23,7 +27,16 @@ struct DsaCache { rad_buf query = 0, codes = 0, scales = 0, gate = 0, kg = 0; rad_buf stage = 0, page = 0, bpos = 0, nc = 0, pooled = 0, pool_scale = 0; rad_buf score = 0, selected = 0, nsel = 0, length = 0; + /* TP only: a rank's rebased bounds, page tables and lengths before the gathers. */ + rad_buf cu_part = 0, sel_part = 0, len_part = 0; }; + /* The narrower of the two gathered rows, one i32 length a query row (the page table's 513 a + * row is a multiple of it), so a run is whole 16-byte words of both: a multiple of four rows. + * The query and output planes hold world times this. */ + static constexpr int64_t kGatherRowBytes = 4; + static int64_t part_rows(int64_t rows, int world) { + return GlmTp::run_rows(rows, world, kGatherRowBytes); + } Geom g{}; Config c{}; Wire w{}; @@ -31,6 +44,7 @@ struct DsaCache { rad_kvgroup index = 0, tail = 0, attention = 0; rad_weight ape = 0; rad_op op_query = 0, op_work = 0, op_pool = 0, op_tail = 0, op_score = 0, op_select = 0; + rad_op op_score_part = 0, op_select_part = 0, op_gather_sel = 0, op_gather_len = 0; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Config& cfg, const Wire& wire, rad_kvgroup attn, rad_kvgroup tail_group, @@ -102,6 +116,19 @@ struct DsaCache { RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3")), RAD_NOWEIGHTS), { w.codes, w.scales, w.gate, w.nc }, { w.score }); + const bool split = g.world > 1; + const int64_t part = split ? part_rows(g.max_tok, g.world) : 0; + if (split && (!w.cu_part || !w.sel_part || !w.len_part)) return RAD_E_INVAL; + if (split) + op_score_part = + rw(b, + RAD_OP(b, "dsa_score", + RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("n", 128), + RAD_INT("heads", 32), RAD_INT("blocks", c.blocks), + RAD_INT("seqs", g.max_seqs), RAD_STR("dtype", "fp8_e4m3"), + RAD_INT("row_part", g.rank)), + RAD_NOWEIGHTS), + { w.codes, w.scales, w.gate, w.nc }, { w.score, w.cu_part }); op_select = rw(b, RAD_OP(b, "qsa_select", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", c.blocks), @@ -109,8 +136,66 @@ struct DsaCache { RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)), RAD_NOWEIGHTS), { w.score, w.nc }, { w.selected, w.nsel, w.length }); + if (split) { + op_select_part = rw( + b, + RAD_OP(b, "qsa_select", + RAD_PARAMS(RAD_RANGE("M", 1, part), RAD_INT("blocks", c.blocks), + RAD_INT("topk", 512), RAD_INT("ratio", 4), + RAD_INT("seqs", g.max_seqs), RAD_INT("signed", 1)), + RAD_NOWEIGHTS), + { w.score, w.nc, w.cu_part }, { w.sel_part, w.nsel, w.len_part }); + op_gather_sel = rw(b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4 * 513, part * 513), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { w.sel_part }, { w.selected }); + op_gather_len = rw(b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4, part), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + { w.len_part }, { w.length }); + if (!op_score_part || !op_select_part || !op_gather_sel || !op_gather_len) + return RAD_E_INVAL; + } return op_query && op_work && op_tail && op_score && op_select ? RAD_OK : RAD_E_INVAL; } + /* The columns a step scores: the live reach the batch bounds on the host. */ + int64_t live_blocks(const RadBatch* batch) const { + const auto* ib = kv_batch(batch, index); + int64_t live = ((int64_t)batch->max_ctx_len + batch->n_tok + batch->n_spec + 4) / 4 + 1; + if (live > c.blocks) live = c.blocks; + // T is the total across sequences, so the conservative bound can exceed the + // per-sequence page table. Columns without a table entry cannot be scored. + if (ib && live > ib->block_table_pitch) live = ib->block_table_pitch; + return live < 1 ? 1 : live; + } + /* The decision reads the same host bound as the score plane's width (max_ctx_len, rounded by + * the core), so every rank takes the same path and a recorded decode pass changes it only when + * that bound moves. */ + bool splits(const RadBatch* batch) const { + const int64_t T = batch->n_tok; + return op_score_part && (GlmTp::splits(T, g.world) || + (T >= GlmTp::kSplitWorkRows && + T * live_blocks(batch) >= GlmTp::kSplitWork)); + } + /* The query rows this rank runs: the whole step, or its run of a split step (GlmTp::run_of). + * A rank whose run lies wholly past a small step runs the step's first R rows instead: no + * sequence holds its run, so its scores are -inf, and its answers land past T. The caller's + * projections into `query` and `gate` cover the same rows. */ + void query_rows(const RadBatch* batch, int64_t* r0, int64_t* rows) const { + const int64_t T = batch->n_tok; + *r0 = 0; + *rows = T; + if (!splits(batch)) return; + const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kGatherRowBytes); + *r0 = run.first; + *rows = run.rows; + } void step(RadCtx* ctx, const RadBatch* batch) const { const auto* ib = kv_batch(batch, index); const auto* tb = kv_batch(batch, tail); @@ -122,8 +207,11 @@ struct DsaCache { const int64_t T = batch->n_tok, S = batch->n_seq; const int64_t work = (T + 3) / 4 + S, pitch = tb->state_index_pitch > 0 ? tb->state_index_pitch : 1; - RAD_ISSUE_N(ctx, op_query, T * 32, brows(w.query, T * 32), brows(w.codes, T * 32), - brows(w.scales, T * 32)); + int64_t q0 = 0, qn = T; + query_rows(batch, &q0, &qn); + RAD_ISSUE_N(ctx, op_query, qn * 32, brow_slice(w.query, q0 * 32, qn * 32, 128), + brow_slice(w.codes, q0 * 32, qn * 32, 128), + brow_slice(w.scales, q0 * 32, qn * 32, 1)); RAD_ISSUE_N(ctx, op_work, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), praw2(tb->state_index, RAD_I32, S, pitch), @@ -136,22 +224,45 @@ struct DsaCache { RAD_ISSUE_N(ctx, op_tail, T, brows(w.kg, T), praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1), kv_cache(tail, layer), praw2(tb->state_index, RAD_I32, S, pitch)); - int64_t live = ((int64_t)batch->max_ctx_len + T + batch->n_spec + 4) / 4 + 1; - if (live > c.blocks) live = c.blocks; - // T is the total across sequences, so the conservative bound can exceed the - // per-sequence page table. Columns without a table entry cannot be scored. - if (live > ib->block_table_pitch) live = ib->block_table_pitch; - if (live < 1) live = 1; + const int64_t live = live_blocks(batch); + if (splits(batch)) { + step_split(ctx, batch, live); + return; + } + // dsa_score declares ten operands, cu_part the optional tenth; the engine counts them. RAD_ISSUE_N(ctx, op_score, T, brows(w.codes, T * 32), brows(w.scales, T * 32), brows(w.gate, T), kv_cache(index, layer), RAD_NONE, praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S), - bcol_at(w.score, 0, c.blocks, 0, live, T)); + bcol_at(w.score, 0, c.blocks, 0, live, T), RAD_NONE); RAD_ISSUE_N(ctx, op_select, T, bcol_at(w.score, 0, c.blocks, 0, live, T), praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S), praw(batch->positions, RAD_I32, T), praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.selected, T), brows(w.nsel, T), brows(w.length, T)); } + /* Rank r scores rows [r R, r R + R) (rows past the step score -inf) and selects for those + * that exist (query_rows), against the bounds the scorer rebased to its first row. The + * gathers lay the runs end to end, so rows past the step land past T, where nothing reads + * them. */ + void step_split(RadCtx* ctx, const RadBatch* batch, int64_t live) const { + const auto* ib = kv_batch(batch, index); + const auto* ab = kv_batch(batch, attention); + const int64_t T = batch->n_tok, S = batch->n_seq, W = g.world; + const int64_t R = part_rows(T, g.world); + int64_t p0 = 0, rows = 0; + query_rows(batch, &p0, &rows); + RAD_ISSUE_N(ctx, op_score_part, R, brows(w.codes, W * R * 32), + brows(w.scales, W * R * 32), brows(w.gate, W * R), kv_cache(index, layer), + RAD_NONE, praw2(ib->block_table, RAD_I32, S, ib->block_table_pitch), + praw(batch->cu_seqlens, RAD_I32, S + 1), brows(w.nc, S), + bcol_at(w.score, 0, c.blocks, 0, live, R), brows(w.cu_part, S + 1)); + RAD_ISSUE_N(ctx, op_select_part, rows, bcol_at(w.score, 0, c.blocks, 0, live, rows), + praw2(ab->block_table, RAD_I32, S, ab->block_table_pitch), brows(w.nc, S), + praw(batch->positions + p0, RAD_I32, rows), brows(w.cu_part, S + 1), + brows(w.sel_part, rows), brows(w.nsel, rows), brows(w.len_part, rows)); + RAD_ISSUE_N(ctx, op_gather_sel, R * 513, brows(w.sel_part, R), brows(w.selected, W * R)); + RAD_ISSUE_N(ctx, op_gather_len, R, brows(w.len_part, R), brows(w.length, W * R)); + } }; struct GlmIndexer { @@ -165,7 +276,6 @@ struct GlmIndexer { DsaCache cache{}; rad_weight gain = 0, bias = 0, head_weight = 0; rad_op op_norm = 0, op_query_copy = 0, op_gate_copy = 0, op_head = 0; - SplitF32Proj head_split{}; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* prefix, const DsaCache::Config& cfg, rad_kvgroup attention, rad_kvgroup tail, rad_kvgroup* index) { @@ -222,8 +332,6 @@ struct GlmIndexer { RAD_INT("K", 4096), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(head_weight)), { w.input }, { w.cache.gate }); - RAD_ARCH_TRY(head_split.declare(b, nm, g, nm.f("blk.%d.index_head", l), g.max_tok, 32, 4096, - head_weight, w.input, w.cache.gate)); RAD_ARCH_TRY(cache.declare(b, nm, g, l, cfg, w.cache, attention, tail, index, nm.ckpt("%s.index_kpool_compress_ape", prefix))); return op_norm && op_query_copy && op_gate_copy && op_head ? RAD_OK : RAD_E_INVAL; @@ -235,18 +343,25 @@ struct GlmIndexer { a.x = x; return a; }; - query.step(ctx, act(w.q_low), w.q_wide, T); - RAD_ISSUE_N(ctx, op_query_copy, T * 32, brows(w.q_wide, T), brows(w.cache.query, T * 32)); + int64_t r0 = 0, rows = T; + cache.query_rows(batch, &r0, &rows); + /* Every output row of these ops is independent of the others and of how many there are, + * except the bf16 projection's at 64 rows and under, a band whose split count a tuned + * configuration may set: it stays on the step's rows unless every run is wider. */ + const bool runs = cache.splits(batch); + if (runs && T - (g.world - 1) * DsaCache::part_rows(T, g.world) > 64) + query.step(ctx, act(w.q_low), w.q_wide, T, r0, rows); + else + query.step(ctx, act(w.q_low), w.q_wide, T); + RAD_ISSUE_N(ctx, op_query_copy, rows * 32, brow_slice(w.q_wide, r0, rows, 4096), + brow_slice(w.cache.query, r0 * 32, rows * 32, 128)); key_gate.step(ctx, act(w.input), w.kg_raw, T); RAD_ISSUE_N(ctx, op_norm, T, bcol(w.kg_raw, 0, 128, T), RAD_W(gain), RAD_W(bias), bcol(w.cache.kg, 0, 128, T)); RAD_ISSUE_N(ctx, op_gate_copy, T, bcol(w.kg_raw, 128, 128, T), bcol(w.cache.kg, 128, 128, T)); - if (head_split.takes(T)) - head_split.step(ctx, T, brows(w.input, T), head_weight, brows(w.cache.gate, T)); - else - RAD_ISSUE_N(ctx, op_head, T, brows(w.input, T), RAD_W(head_weight), - brows(w.cache.gate, T)); + RAD_ISSUE_N(ctx, op_head, rows, brow_slice(w.input, r0, rows, 4096), RAD_W(head_weight), + brow_slice(w.cache.gate, r0, rows, 32)); cache.step(ctx, batch); } }; diff --git a/arch/common/rad_glm_tp.h b/arch/common/rad_glm_tp.h index 52ceab6b..39a3d589 100644 --- a/arch/common/rad_glm_tp.h +++ b/arch/common/rad_glm_tp.h @@ -1,18 +1,26 @@ /* GLM-5.3's tensor parallelism in one place: what a rank's shard of the model is, from which step - * size a replicated piece of work splits over the ranks instead, and the column split of a - * replicated F32 projection. + * size a replicated or head-split piece of work splits over the ranks instead, how a step's rows + * fall into one run a rank, and the column split of a replicated F32 projection. * - * The residual stream is replicated (spec.md §9). Two kinds of split share the ranks' work: + * The residual stream is replicated (spec.md §9). Three kinds of split share the ranks' work: * * heads the MLA and KDA heads, with them the rows of their projections, the KDA state and * the convolution history; the experts' and the dense feed-forward's width * (`heads`, `kda_width`, `expert_width`, `dense_width`); joined by an all_reduce - * columns a replicated F32 projection's output columns (SplitF32Proj), or the mHC read's - * input chunks (ManifoldConn); joined by an all_gather, bit for bit the replicated - * computation */ + * rows a prefill-sized step's rows, one run a rank, each rank computing its run with the + * unsplit kernels (`run_rows`, `run_of`); joined by an all_gather of whole runs + * columns a replicated F32 projection's output columns (SplitF32Proj); joined by a + * row-interleaved all_gather, bit for bit the replicated projection + * + * The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered + * row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside + * its page tables, so its runs are multiples of four rows. The last rank's run may be short, or + * lie wholly past a small step (`run_of`). */ #ifndef RAD_GLM_TP_H #define RAD_GLM_TP_H #include "rad_arch.h" +#include +#include namespace rad { namespace arch { @@ -28,10 +36,44 @@ struct GlmTp { static int64_t expert_width(int world) { return kExpertFF / world; } static int64_t dense_width(int world) { return kDenseFF / world; } - /* Rows from which a replicated piece of work splits over the ranks. Below it, as in decode, - * the collective's latency outweighs the saved arithmetic and every rank runs the replicated - * form. */ + /* Rows from which a step splits by rows or columns over the ranks. Below it, as in decode, the + * collective's latency outweighs the saved arithmetic and every rank runs the replicated or + * head-split form. */ static constexpr int64_t kSplitRows = 256; + /* Rows x live blocks from which the indexer splits a smaller step as well: a decode step at + * long context, where scoring every query row against every block of its sequence outweighs + * the two gathers. On one R9700 48 rows over 8000 blocks (32k of context) score and select in + * about 250 us and a run of 8 in 50, against roughly 50 us for the two eight-rank gathers; + * over 4000 blocks the saving is about the gathers' cost, and six rows never pay. From 16 + * rows, so that at least four ranks share the work and every run fits in the step. */ + static constexpr int64_t kSplitWork = 1 << 18, kSplitWorkRows = 16; + static bool splits(int64_t rows, int world) { return world > 1 && rows >= kSplitRows; } + + /* A rank's run of a step of `rows`, gathered as rows of `row_bytes`: ceil(rows / world) rounded + * up to whole 16-byte words of the gathered row. Every rank but possibly the last takes a whole + * run; the planes a split writes hold world runs, which can reach past the step. */ + static int64_t run_rows(int64_t rows, int world, int64_t row_bytes) { + const int64_t word = 16 / std::gcd(16, row_bytes); + return word * ((rows + word * world - 1) / (word * world)); + } + struct Run { + int64_t run = 0, first = 0, rows = 0; + }; + /* Rank `rank`'s rows [first, first + rows) of a step of `rows`. A rank whose run lies wholly + * past a small step takes the step's first run instead, so every plane it computes from and + * gathers is written; what it computes there is dead rows past the step, and the gather lays + * them past T, where nothing reads them. */ + static Run run_of(int64_t rows, int world, int rank, int64_t row_bytes) { + Run r; + r.run = run_rows(rows, world, row_bytes); + r.first = rank * r.run; + r.rows = std::min(r.run, rows - r.first); + if (r.rows <= 0) { + r.first = 0; + r.rows = r.run; + } + return r; + } /* The all_reduce of a replicated 4096-wide bf16 row over the ranks: the embedding's (exact) * and each head-split block's (the deployment's wire). */ diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index 73dd4db6..e0bf619e 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -12,7 +12,7 @@ * rad_block_glm_indexer.h GlmIndexer the DSA indexer, DsaCache its key cache and selection * rad_block_glm_router.h GlmRouter the correction-bias router (through MoeFP8) * rad_block_glm_mtp.h GlmMtp the draft head around the plugin's layer 45 - * rad_glm_tp.h GlmTp the shards and the split threshold + * rad_glm_tp.h GlmTp the shards, the row runs and the split thresholds * * This file declares the buffers the blocks share, places the blocks and issues the step's * order. Declaration order is liveness (the buffer plan takes lifetimes from it) and the issue @@ -125,7 +125,9 @@ static int kda_buffers(RadBuilder* b, Model& m) { kw.core.out = bf("recurrent_out", W); return RAD_OK; } -/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. */ +/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under + * TP the selection planes hold every rank's run of rows, which can reach past the step + * (DsaCache::part_rows). */ static int mla_buffers(RadBuilder* b, Model& m) { auto& g = m.g; auto& nm = m.nm; @@ -147,14 +149,18 @@ static int mla_buffers(RadBuilder* b, Model& m) { aw.attn.x = bf("expanded", Q); RAD_ARCH_TRY(aw.attn.declare_qs(b, nm, g, "expanded", Q)); aw.core.out = aw.attn.x; - aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { T, 513 }); - aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { T }); + const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0; + const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T; + aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 }); + aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ }); return RAD_OK; } static int indexer_buffers(RadBuilder* b, Model& m) { auto& g = m.g; auto& nm = m.nm; const int64_t T = g.max_tok; + const int64_t part = g.world > 1 ? DsaCache::part_rows(T, g.world) : 0; + const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T; const int64_t work = (T + 3) / 4 + g.max_seqs, blocks = (g.max_ctx + 3) / 4 + 1; auto bf = [&](const char* n, int64_t width) { return decl_b(b, nm.f("%s", n), RAD_BF16, { T, width }); @@ -166,9 +172,9 @@ static int indexer_buffers(RadBuilder* b, Model& m) { iw.kg_raw = bf("index_key_gate", 256); auto& c = iw.cache; c.query = decl_b(b, nm.f("index_heads"), RAD_BF16, { T * 32, 128 }); - c.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { T * 32, 128 }); - c.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { T * 32, 1 }); - c.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { T, 32 }); + c.codes = decl_b(b, nm.f("index_codes"), RAD_F8E4M3, { TQ * 32, 128 }); + c.scales = decl_b(b, nm.f("index_scales"), RAD_F32, { TQ * 32, 1 }); + c.gate = decl_b(b, nm.f("index_head_weights"), RAD_F32, { TQ, 32 }); c.kg = bf("index_normalized_key_gate", 256); c.stage = decl_b(b, nm.f("pool_stage"), RAD_BF16, { work * 4, 256 }); c.page = decl_b(b, nm.f("pool_page"), RAD_I32, { work }); @@ -176,10 +182,18 @@ static int indexer_buffers(RadBuilder* b, Model& m) { c.nc = decl_b(b, nm.f("pool_count"), RAD_I32, { g.max_seqs }); c.pooled = decl_b(b, nm.f("pool_codes"), RAD_F8E4M3, { work, 128 }); c.pool_scale = decl_b(b, nm.f("pool_scales"), RAD_F32, { work, 1 }); - c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { T, blocks }); + /* A split step scores one run of rows a rank and an unsplit one is under GlmTp::kSplitRows: + * at 64k of context the whole step's plane would be 256 MiB. */ + const int64_t scored = g.world > 1 ? std::min(T, std::max(part, GlmTp::kSplitRows)) : T; + c.score = decl_b(b, nm.f("index_scores"), RAD_F32, { scored, blocks }); c.selected = m.aw.core.selected; c.length = m.aw.core.length; c.nsel = decl_b(b, nm.f("selected_count"), RAD_I32, { T }); + if (g.world > 1) { + c.cu_part = decl_b(b, nm.f("index_part_bounds"), RAD_I32, { g.max_seqs + 1 }); + c.sel_part = decl_b(b, nm.f("selected_part"), RAD_I32, { part, 513 }); + c.len_part = decl_b(b, nm.f("length_part"), RAD_I32, { part }); + } return RAD_OK; } static int ffn_buffers(RadBuilder* b, Model& m) { diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 58e8f307..0cbfd6da 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -519,9 +519,18 @@ layer's latent, index and tail for every row and runs its MoE on the proposal ro **Tensor parallelism.** At 1, 2, 4 or 8 ranks; declare refuses any other. `tests/glm5next_test.cpp` declares and steps the whole plugin at 1, 4 and 8, against pinned graph and step hashes at 1 and -8, the connection, router and index-gate splits at 1, 2, 4 and 8, each issue's operand count -against the loaded kernel libraries' schemas, and every declared weight against the served -container's names and encodings. +8, the connection, router and index-gate splits at 1, 2, 4 and 8, the indexer's row split at 2 +and 8, the row rule at every world, each issue's operand count against the loaded kernel +libraries' schemas, and every declared weight against the served container's names and encodings. + +One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated +piece of work splits by rows over the ranks instead, each rank taking one run of ceil(T / world) +rows rounded up to whole 16-byte words of the row it gathers, because an `all_gather` moves whole +words: multiples of four rows for the indexer's one i32 length a row. The last run may be short; +a rank whose run lies wholly past a small step takes the first run and computes dead rows, so +every plane it gathers is written (`GlmTp::run_of`). The indexer also splits a smaller step, from +16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in +decode, the collective costs more than it saves and every rank runs the replicated form. - The routed and the shared experts split their 2048 width into equal contiguous slices, 256 a rank at eight; each rank computes its slice of every expert, and the block's all-reduce sums @@ -530,15 +539,33 @@ container's names and encodings. of o. q_a, kv_a and the latent are replicated. - KDA splits its 64 heads, with them the q/k/v rows, the convolution taps and the state; the two rank-128 projections into the gates are replicated. -- The indexer is replicated whole. +- The indexer's key side is replicated: every rank keeps the whole index cache and its tail. Its + query side splits by rows from the threshold: each rank scores its run under the row rule, + R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache + (`dsa_score` with `row_part`, the last run's rows past the step scoring `-inf`) and selects for + the rows of its run that exist, under the bounds the scorer rebased to the run's first row + (`cu_part`, docs/OPS.md); two `all_gather`s lay the runs' page tables and lengths end to end, + 513 and 1 i32 a row, 8 MiB a layer at a 4096-row chunk. The run's queries are all a rank needs, + so the query projection, its quantiser and the head gates run on the run's rows too, and the + gates need no gather; the bf16 projection stays on the step's rows where a run would be 64 rows + or fewer, the skinny band whose split count a tuned configuration may set. Each row's selection + is the same kernels' answer to the same operands, so the joined table is bit-identical to one + rank's and MLA reads it unchanged. The scoring grows with the context (every row scores every + complete block of its sequence), so this is where long prompts gain: the score plane shrinks to + one run (256 MiB to 32 MiB at 64k of context and a 4096-row chunk). A smaller step splits too + from 16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`): eight sequences + verifying five drafts from about 22k of context, where the scoring of 48 rows outweighs the two + gathers; a single sequence's decode never does, and below both thresholds the indexer runs + whole. - The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact. - The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each connection's mHC projection of 24 x 16384) are replicated. From a pass of 256 rows (`GlmTp::kSplitRows`; `SplitF32Proj` in `arch/common/rad_glm_tp.h`), each rank computes a disjoint part with the replicated kernel and an `all_gather` joins the parts, so every value is - bit-identical: the router and the head gates split their output columns, the mHC projection - its 16384-wide input into eight 2048-column chunks, whose partials `mhc_pre_finish` completes - on every rank. Below the threshold, as in decode, the collective costs more than it saves. + bit-identical: the router splits its output columns, the mHC projection its 16384-wide input + into eight 2048-column chunks, whose partials `mhc_pre_finish` completes on every rank, and the + head gates go with the indexer's rows (above). Below the threshold, as in decode, the + collective costs more than it saves. **MoE decode fusions.** Three, each byte-identical to the launches it replaces, declared wherever a loaded library serves the fused op (the separate launches otherwise): diff --git a/tests/glm5next_test.cpp b/tests/glm5next_test.cpp index f6c7adfb..1205eca2 100644 --- a/tests/glm5next_test.cpp +++ b/tests/glm5next_test.cpp @@ -433,8 +433,9 @@ TEST( CHECK_EQ(std::count(ops.begin(), ops.end(), "all_gather"), 0); // The split is declared on every rank whatever its step size; only rank 0 issues it here. const bool split = world > 1; - // 43 routers and 12 index heads (MTP included), and the 90 mHC reads. - CHECK_EQ(count_op(b, "all_gather"), split ? 55 + 90 : 0); + // 43 routers (MTP included), the 90 mHC reads, and each of the 12 indexers' page + // tables and lengths; the index head gates follow the indexer's rows, ungathered. + CHECK_EQ(count_op(b, "all_gather"), split ? 43 + 90 + 24 : 0); CHECK_EQ(count_op(b, "mhc_pre_partial"), split ? 90 : 0); ctx.issues.clear(); batch.draft_pass = -1; @@ -480,12 +481,13 @@ TEST( glm5next::step(&ctx, &batch); CHECK(ctx.step_fail.empty()); { - // 512 rows reach the split: each projection runs on its column slice and each - // mHC read on its chunks, both gathered; at TP1 nothing changes. + // 512 rows reach the split: each router runs on its column slice, each mHC + // read on its chunks and each indexer, its head gates included, on its run + // of query rows, all gathered but the gates; at TP1 nothing changes. const auto long_ops = issued_ops(b, ctx); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "gemm_nt_f32"), 53); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "all_gather"), - world > 1 ? 53 + 90 : 0); + world > 1 ? 42 + 90 + 22 : 0); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre"), world > 1 ? 0 : 90); CHECK_EQ(std::count(long_ops.begin(), long_ops.end(), "mhc_pre_finish"), @@ -493,12 +495,14 @@ TEST( for (const auto& issue : ctx.issues) { if (b.ops[issue.op - 1].op != "gemm_nt_f32") continue; const int64_t n = pint(&b.ops[issue.op - 1], "N"); - if (world == 1) + if (world == 1 || n == 32) CHECK(n == 288 || n == 32); else { - CHECK(n == 288 / world || n == 32 / world); + CHECK_EQ(n, 288 / world); CHECK_EQ(issue.opd[1].rows, n); } + if (world > 1 && n == 32) + CHECK_EQ(issue.opd[0].rows, DsaCache::part_rows(512, world)); } } for (int l = 3; l < 45; ++l) { @@ -547,6 +551,177 @@ TEST( } } +/* From the split threshold each rank scores its run of the step's query rows (rows past the step + * included, which score -inf) and selects for the rows of it that exist, against the bounds the + * scorer rebased to the run's first row; two all_gathers join the runs' page tables and lengths + * into planes that hold every run. The query side (projection, cast, quantiser, head gates) runs + * on the run's rows that exist. Below the threshold the indexer stays replicated. */ +TEST(glm53_indexer_scores_and_selects_one_run_of_query_rows_per_rank) { + using namespace rad::arch; + const char* keys[] = { "num_nextn_predict_layers", "hc_mult", "n_routed_experts", + "index_topk" }; + const char* vals[] = { "1", "4", "288", "2048" }; + RadModelMeta meta{}; + meta.n_layers = 45; + meta.n_embd = 4096; + meta.n_vocab = 154880; + meta.rms_eps = 1e-5f; + meta.n_kv = 4; + meta.kv_key = keys; + meta.kv_val = vals; + const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); + const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); + for (int world : { 2, 8 }) + for (int rank : { 0, world - 1 }) { + RadBuilder b; + b.kv_block = 4; + b.encs = { { "mtp.blk.45.ffn_gate_up_exps", fp8 }, + { "mtp.blk.45.ffn_down_exps", fp8 }, + { "ffn_gate_up_exps", mx }, + { "ffn_down_exps", mx }, + { "ffn_gate_up_shexp", mx }, + { "ffn_down_shexp", mx }, + { "ffn_gate_up.weight", fp8 }, + { "ffn_down.weight", fp8 } }; + RadBuildCtx build{}; + build.rank = rank; + build.world_size = world; + build.max_tok = 512; + build.max_seqs = 8; + build.max_ctx = 65536; + build.max_spec = 5; + REQUIRE_EQ(glm5next::declare(&b, &meta, &build), RAD_OK); + const auto& m = *glm5next::models[rank]; + const auto& cache = m.layers[3].index.cache; + const auto& w = m.iw.cache; + const int64_t most = DsaCache::part_rows(512, world); + const RecOp* score = b.op_of(cache.op_score_part); + const RecOp* sel = b.op_of(cache.op_gather_sel); + const RecOp* len = b.op_of(cache.op_gather_len); + REQUIRE(score && sel && len && cache.op_select_part); + CHECK_EQ(pint(score, "row_part"), rank); + CHECK_EQ(param(score, "M")->ihi, most); + CHECK(score->writes == std::vector({ w.score, w.cu_part })); + CHECK_EQ(param(sel, "numel")->ival, 4 * 513); + CHECK_EQ(param(sel, "numel")->ihi, most * 513); + CHECK_EQ(param(len, "numel")->ihi, most); + CHECK(sel->reads == std::vector({ w.sel_part })); + CHECK(sel->writes == std::vector({ w.selected })); + CHECK(len->writes == std::vector({ w.length })); + CHECK_EQ(b.bufs[w.selected - 1].d.shape[0], world * most); + CHECK_EQ(b.bufs[w.codes - 1].d.shape[0], world * most * 32); + CHECK_EQ(b.bufs[w.sel_part - 1].d.shape[0], most); + // Two decode rows beside a 498-row chunk: 500 rows, runs of R. + auto k = kit(b, { 1, 1 }, { 498 }, 100); + const int64_t T = 500, R = DsaCache::part_rows(T, world), r0 = rank * R, + have = std::min(R, T - r0); + auto passes = run_passes(b, glm5next::step, { k.get() }, rank, world); + CHECK_PASSES(b, passes); + const auto& index = m.layers[3].index; + // The bf16 query projection follows the runs only where every run is over 64 rows. + const bool projected = T - (world - 1) * R > 64; + int scored = 0, selected = 0, gathered = 0, replicated = 0, fronts = 0; + for (const auto& issue : passes[0]->issues) { + if (issue.op == index.query.op) { + ++fronts; + CHECK_EQ(issue.opd[0].rows, projected ? have : T); + CHECK_EQ(issue.opd[0].offset, projected ? r0 * 1536 : 0); + } + if (issue.op == index.op_query_copy || issue.op == cache.op_query) { + ++fronts; + CHECK_EQ(issue.n, have * 32); + CHECK_EQ(issue.opd[1].offset, r0 * 32 * 128); + } + if (issue.op == index.op_head) { + ++fronts; + CHECK_EQ(issue.n, have); + CHECK_EQ(issue.opd[0].offset, r0 * 4096); + CHECK_EQ(issue.opd[2].offset, r0 * 32); + } + if (issue.op == cache.op_score) ++replicated; + if (issue.op == cache.op_score_part) { + ++scored; + CHECK_EQ(issue.n, R); + CHECK_EQ(issue.opd[0].rows, world * R * 32); + CHECK_EQ(issue.opd[2].rows, world * R); + CHECK_EQ(issue.opd[8].rows, R); + CHECK_EQ(issue.opd[9].handle, w.cu_part); + } + if (issue.op == cache.op_select_part) { + ++selected; + CHECK_EQ(issue.n, have); + CHECK(issue.opd[3].raw == (void*)(k->pos.data() + r0)); + CHECK_EQ(issue.opd[3].rows, have); + CHECK_EQ(issue.opd[4].handle, w.cu_part); + CHECK_EQ(issue.opd[5].handle, w.sel_part); + CHECK_EQ(issue.opd[7].handle, w.len_part); + } + if (issue.op == cache.op_gather_sel) { + ++gathered; + CHECK_EQ(issue.n, R * 513); + CHECK_EQ(issue.opd[1].rows, world * R); + } + if (issue.op == cache.op_gather_len) CHECK_EQ(issue.n, R); + } + // The handles are layer 3's: one issue each. + CHECK_EQ(scored, 1); + CHECK_EQ(selected, have > 0 ? 1 : 0); + CHECK_EQ(gathered, 1); + CHECK_EQ(replicated, 0); + CHECK_EQ(fronts, 4); + // Under the threshold every rank scores and selects the whole step. + auto small = kit(b, {}, { 255 }); + auto under = run_passes(b, glm5next::step, { small.get() }, rank, world); + CHECK_PASSES(b, under); + int whole = 0; + for (const auto& issue : under[0]->issues) { + CHECK(issue.op != cache.op_score_part && issue.op != cache.op_gather_sel); + whole += issue.op == cache.op_score; + // The engine refuses an issue whose operand count is not the schema's: dsa_score + // declares ten (cu_part optional, passed absent). + if (issue.op == cache.op_score || issue.op == cache.op_score_part) + CHECK_EQ(issue.opd.size(), (size_t)10); + if (issue.op == index.op_head) CHECK_EQ(issue.n, 255); + } + CHECK_EQ(whole, 1); + // A verify of eight sequences at 32k of context (48 rows x 8014 blocks) splits too, a + // single sequence's six rows do not; a rank whose run lies past the step still writes + // the runs it gathers. + for (int seqs : { 8, 1 }) { + auto dec = kit(b, std::vector((size_t)seqs, 6), {}); + const int64_t pitch = 8192; + dec->table.resize((size_t)(seqs * pitch)); + for (int64_t i = 0; i < seqs * pitch; ++i) dec->table[(size_t)i] = (int32_t)i; + for (auto& g : dec->kv) { + g.block_table = dec->table.data(); + g.block_table_pitch = g.max_blocks = pitch; + } + dec->b.max_ctx_len = 32000; + auto v = run_passes(b, glm5next::step, { dec.get() }, rank, world); + CHECK_PASSES(b, v); + const int64_t Td = 6 * seqs, Rd = DsaCache::part_rows(Td, world); + const bool split_d = seqs == 8; + int parts = 0, gathers = 0, wholes = 0; + for (const auto& issue : v[0]->issues) { + parts += issue.op == cache.op_score_part; + gathers += issue.op == cache.op_gather_sel; + wholes += issue.op == cache.op_score; + if (issue.op == cache.op_score_part) CHECK_EQ(issue.n, Rd); + if (issue.op == cache.op_score || issue.op == cache.op_score_part) + CHECK_EQ(issue.opd.size(), (size_t)10); + if (split_d && + (issue.op == cache.op_select_part || issue.op == cache.op_query)) { + const int64_t rows_d = rank * Rd < Td ? std::min(Rd, Td - rank * Rd) : Rd; + CHECK_EQ(issue.n, issue.op == cache.op_query ? rows_d * 32 : rows_d); + } + } + CHECK_EQ(gathers, split_d ? 1 : 0); + CHECK_EQ(parts, split_d ? 1 : 0); + CHECK_EQ(wholes, split_d ? 0 : 1); + } + } +} + /* The engine's arena levels declare again at a smaller max_tok (RadBuildCtx::shape_probe) and * must get the real declare's graph: the same ops with the same fixed parameters, only ranged row * counts and buffer rows smaller. The TP split declares its ops whatever the step size and its @@ -1176,8 +1351,8 @@ TEST(glm53_is_the_pinned_graph_and_steps) { int world; uint64_t graph, steps; }; - const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x98ba2952bb37b075ull }, - { 8, 0x8204e073efdeee0cull, 0x1279aecfe4e32d9aull } }; + const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x33e5f136f0dbba15ull }, + { 8, 0x712f01858dbe1047ull, 0xf9e357b1333c638full } }; for (const Case& cs : cases) { RadBuilder b; b.kv_block = 4; @@ -1248,6 +1423,48 @@ RadBuildCtx glm53_ctx(int rank, int world, int max_spec = 3) { RAD_TEST_MAIN() +/* ==================================================================== the row rule */ + +/* GlmTp::run_rows is the one rule the indexer's runs follow, and it is the formula it replaced: + * 4 * ceil(T / (4 * world)) for the indexer's 4-byte lengths, ceil(T / world) for a row of whole + * 16-byte words. At the split threshold, around a chunk and at the largest step, for every + * world: run_of covers the step once with no overlap, the last run short where the step ends + * inside it, and a rank whose run lies wholly past a small step takes the first run instead, so + * the planes it writes and gathers are never unwritten. */ +TEST(glm_tp_row_rule_is_the_old_formula_and_covers_a_step_once) { + using namespace rad::arch; + for (int world : { 1, 2, 4, 8 }) + for (int64_t T : { 1, 5, 6, 48, 255, 256, 257, 300, 2047, 2048, 2049, 4096 }) { + const int64_t wide = GlmTp::run_rows(T, world, 8192); + const int64_t narrow = GlmTp::run_rows(T, world, 4); + CHECK_EQ(wide, (T + world - 1) / world); + CHECK_EQ(narrow, 4 * ((T + 4 * world - 1) / (4 * world))); + CHECK_EQ(DsaCache::part_rows(T, world), narrow); + CHECK(world * wide >= T); + CHECK(world * narrow >= T); + CHECK_EQ(narrow % 4, 0); + for (int64_t row_bytes : { 8192, 4 }) { + const int64_t run = GlmTp::run_rows(T, world, row_bytes); + int64_t covered = 0, next = 0; + for (int rank = 0; rank < world; ++rank) { + const GlmTp::Run r = GlmTp::run_of(T, world, rank, row_bytes); + CHECK_EQ(r.run, run); + CHECK(r.rows >= 1 && r.rows <= run); + if ((int64_t)rank * run < T) { + CHECK_EQ(r.first, next); + CHECK_EQ(r.rows, std::min(run, T - r.first)); + next = r.first + r.rows; + covered += r.rows; + } else { + CHECK_EQ(r.first, 0); + CHECK_EQ(r.rows, run); + } + } + CHECK_EQ(covered, T); + } + } +} + /* ==================================================================== the op schemas */ namespace { @@ -1305,9 +1522,10 @@ const LoadedSchemas& loaded_schemas() { * declares names as many weights as rad_builder.cpp admits. The steps: at eight ranks and at * one, a mixed step over the split threshold (two decode rows beside a 498-row chunk), a step * under it, a six-row verify and six single-row decodes, each with its history pass and a draft - * round, and a verify of eight sequences at 32k of context. The engine refuses a step at the - * first mismatch, and the fakes alone cannot see one: an issue short of an optional operand - * passes every host test and stops a served engine at its first step through that op. */ + * round, and a verify of eight sequences at 32k of context, where the indexer splits a decode. + * The engine refuses a step at the first mismatch, and the fakes alone cannot see one: a + * replicated dsa_score issued with nine operands passed every host test and stopped a served + * engine at its first long prompt. */ TEST(glm53_issues_every_op_with_the_operand_count_its_schema_declares) { const LoadedSchemas& lib = loaded_schemas(); if (lib.ops.empty()) { From 7d392b0400fef36c215e6c3916ca19a41f744fdd Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:24:29 +0200 Subject: [PATCH 129/152] mem_test: a conversation restored from the host tier comes back no further than the free list A restore reserves only from the free list, so after the reserve's trim has left a quarter of the pool free, a session larger than that comes back partly, and the lookup stops at the first block still on the host. On a hybrid model the hit then resumes at the deepest snapshot below that point, which the retention ladder can put far down the chain. These tests drive the engine's restore against the real cache, tiers and manager: two conversations of 0.6 of the pool, the second admitted by pressure and published, then the first restored. Red on this tree: the first comes back as far as the free list reaches, the hybrid one resumes below its tip, and a restore the pool cannot hold is cut where the reservation ended, not at a snapshot. Co-Authored-By: Claude Opus 5.5 --- tests/mem_test.cpp | 150 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 148 insertions(+), 2 deletions(-) diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 31279fcd..07ba5c45 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -3303,8 +3303,8 @@ struct TierFixture { Fixture f; IdleTiers t; int64_t per = 0; - int build() { - int s = f.build(/*with_linear=*/false, /*ckpt_slots=*/0); + int build(bool with_linear = false, int64_t ckpt_slots = 0) { + int s = f.build(with_linear, ckpt_slots); if (s < 0) return s; s = t.configure(tier_config(1 << 20, 1024)); if (s < 0) return s; @@ -6089,6 +6089,152 @@ TEST(the_cache_tiers_and_pool_agree_over_random_interleavings) { CHECK_EQ(run.x.t.arena().used_slots(), 0ll); } +/* ================================================================== a restore makes room + * + * A conversation whose blocks went to the host tier comes back whole on its next turn, when the + * pool can be made to hold it. The reserve's trim leaves a quarter of the pool free after every + * publish; a restore larger than that gives up VRAM copies other idle conversations keep on the + * host as well, the same way pressure does, rather than stopping where the free list ends. These + * drive the engine's restore against the real cache, tiers and manager, with no bytes moving. + */ + +/* The engine's restore (the binding's restore_fn) without the transfer: which entries come back, + * into which blocks, and what the tiers and the cache are told. Returns how many came back. */ +static int64_t engine_restore(TierFixture& x, PCBinding& b, const Request& r) { + (void)b; + const std::vector want = x.f.pc.restorable_from(r.prompt, {}); + std::vector jobs; + for (const BlockHash& h : want) { + TierJob j; + if (!x.t.plan_promote(h, &j)) break; + jobs.push_back(std::move(j)); + } + std::vector ids; + const int64_t m = x.f.kv.reserve_blocks(G_FULL, (int64_t)jobs.size(), &ids); + int64_t back = 0; + for (size_t i = 0; i < jobs.size(); ++i) { + TierJob& j = jobs[i]; + const bool ok = (int64_t)i < m; + j.started = ok; + j.blocks.clear(); + if (ok) j.blocks.push_back(ids[i]); + x.t.report(j, ok, rad_mono_ns()); + if (ok) { CHECK_OK(x.f.pc.rebind(j.key, j.blocks)); ++back; } + } + return back; +} + +/* Two conversations of 0.6 of the pool each, as the scheduler leaves them: A published and copied + * to the host, B admitted by giving up A's VRAM under pressure, published, and the reserve's trim + * run while B's sequence still holds its blocks (Scheduler::close_request publishes before it + * frees). A ends up mostly on the host with its first blocks still in VRAM. `b_live` keeps B's + * sequence running; otherwise it ends with no host copy yet. */ +struct TwoSessions { + int64_t n = 0; /* blocks each conversation published */ + std::vector a, b; /* prompts that hit the whole of each */ + std::vector ha; +}; +static TwoSessions two_sessions(TierFixture& x, bool b_live, bool a_snapshots) { + TwoSessions s; + const int64_t total = x.f.kv.total_blocks(G_FULL); + s.n = (total * 3 / 5) & ~(int64_t)3; /* on the 64-token checkpoint interval */ + CHECK(2 * s.n <= x.t.arena().capacity()); + s.a = tok_run(100000, (int)(s.n * 16 + 16)); + s.b = tok_run(900000, (int)(s.n * 16 + 16)); + s.ha = chain_of(s.a); + + publish(x.f, 1, s.a, s.n * 16); + if (a_snapshots) { + /* A snapshot on every interval, retention after each, as a long prefill leaves them. */ + for (int64_t pos = 64; pos <= s.n * 16; pos += 64) { + x.f.pc.begin_step(); + ckpt_at(x.f, 1, s.ha, pos); + x.f.pc.retain(1); + } + x.f.pc.begin_step(); + } + x.f.kv.free_sequence(1); + copy_now(x.t); + + const int64_t room = total - x.f.kv.held_blocks(G_FULL); + CHECK_EQ(x.f.pc.trim(s.n + 1 - room), s.n + 1 - room); + publish(x.f, 2, s.b, s.n * 16); + const int64_t short_by = total / 4 - (total - x.f.kv.held_blocks(G_FULL)); + if (short_by > 0) (void)x.f.pc.trim(short_by); + if (!b_live) x.f.kv.free_sequence(2); + return s; +} + +TEST(a_restore_gives_up_other_clean_copies_to_bring_the_whole_chain_back) { + TierFixture x; + CHECK_OK(x.build()); + const TwoSessions s = two_sessions(x, /*b_live=*/false, /*a_snapshots=*/false); + const int64_t off = (int64_t)x.f.pc.restorable_from(s.a, {}).size(); + const int64_t free_now = x.f.kv.total_blocks(G_FULL) - x.f.kv.held_blocks(G_FULL); + REQUIRE(off > free_now); /* the free list alone cannot hold it */ + const int64_t evictions = x.f.pc.stats().evictions; + + PCBinding b(&x.f.pc); + int flushes = 0; + b.flush_fn = [&]() { ++flushes; return !copy_now(x.t).empty(); }; + CHECK_EQ(engine_restore(x, b, turn(3, s.a, {})), off); + CHECK_EQ(x.f.pc.lookup(s.a, {}).n_attn_tokens, (int32_t)(s.n * 16)); + /* B had no host copy yet: its copies were landed first, then its VRAM went. Nothing lost. */ + CHECK_EQ(flushes, 1); + CHECK_EQ(x.f.pc.stats().evictions, evictions); + CHECK_EQ(x.f.pc.size(), 2 * s.n); + CHECK_EQ((int64_t)x.f.pc.restorable_from(s.b, {}).size(), 2 * s.n - x.f.pc.resident()); +} + +/* With recurrent state the hit resumes at the deepest snapshot the restored prefix reaches. Cut + * at the free list, that is somewhere down the retention ladder, far below the tip. */ +TEST(a_restored_hybrid_conversation_resumes_at_its_tip_snapshot) { + TierFixture x; + CHECK_OK(x.build(/*with_linear=*/true, /*ckpt_slots=*/32)); + x.f.pc.set_policy(std::make_unique(64)); + const TwoSessions s = two_sessions(x, /*b_live=*/false, /*a_snapshots=*/true); + REQUIRE_EQ(x.f.pc.checkpoints(1).back(), s.n * 16); + + PCBinding b(&x.f.pc); + b.flush_fn = [&]() { return !copy_now(x.t).empty(); }; + (void)engine_restore(x, b, turn(3, s.a, {})); + const CacheHit hit = x.f.pc.lookup(s.a, {}); + CHECK_EQ(hit.n_attn_tokens, (int32_t)(s.n * 16)); + CHECK_EQ(hit.n_linear_tokens, (int32_t)(s.n * 16)); +} + +/* When the pool cannot be made to hold the chain, what comes back ends at a snapshot: blocks past + * the deepest snapshot the shorter prefix reaches would be restored for nothing. Making room + * never takes the conversation's own blocks, which would only have to come back too, nor a chain + * a running sequence reads, which frees nothing. */ +TEST(a_restore_the_pool_cannot_hold_stops_at_a_snapshot_and_spares_its_own_chain) { + TierFixture x; + CHECK_OK(x.build(/*with_linear=*/true, /*ckpt_slots=*/32)); + x.f.pc.set_policy(std::make_unique(64)); + const TwoSessions s = two_sessions(x, /*b_live=*/true, /*a_snapshots=*/true); + const int64_t off = (int64_t)x.f.pc.restorable_from(s.a, {}).size(); + const int64_t resident = s.n - off; /* A's first blocks, still in VRAM */ + const int64_t room = x.f.kv.total_blocks(G_FULL) - x.f.kv.held_blocks(G_FULL); + REQUIRE(resident > 0); + REQUIRE(room < off); + /* The deepest snapshot the prefix reaches with `room` more blocks. */ + int64_t snap = 0; + for (int64_t p : x.f.pc.checkpoints(1)) + if (p <= (resident + room) * 16) snap = p; + REQUIRE(snap > 0); + const int64_t drops = x.f.pc.stats().drops; + + PCBinding b(&x.f.pc); + b.flush_fn = [&]() { return !copy_now(x.t).empty(); }; + const int64_t back = engine_restore(x, b, turn(3, s.a, {})); + CHECK_EQ(back, std::max(0, snap / 16 - resident)); + CHECK_EQ(x.f.pc.stats().drops, drops); /* no VRAM copy given up: A's own, or B's */ + const CacheHit hit = x.f.pc.lookup(s.a, {}); + CHECK_EQ(hit.n_linear_tokens, (int32_t)snap); + CHECK_EQ(hit.n_attn_tokens, (int32_t)std::max(snap, resident * 16)); + CHECK_EQ(x.f.pc.lookup(s.b, {}).n_attn_tokens, (int32_t)(s.n * 16)); +} + /* Tools and tests build and tear down the tier executors and pools repeatedly, and on a card every * event is a hardware resource and every committed byte VRAM. A two-rank transfer pass gives back * every event and device byte it took. */ From 4be0a347919518047f9e956d966f233ede4969cd Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:24:29 +0200 Subject: [PATCH 130/152] kv tiers: a restore makes room the way pressure does, and a chain the pool cannot hold stops at a snapshot A restore reserved only from the free list. The reserve's trim leaves a quarter of the pool free after every publish, so a returning conversation larger than that came back as far as the free list reached, and the lookup stopped at the first block still on the host. On GLM-5.3-Flash at eight ranks, two conversations of 314K tokens in a 446,832-token pool: the second turn of the first brought back exactly the 27,930 free blocks, hit 111,772 tokens, and on its hybrid state resumed at the snapshot at 1,024, since geometric backoff keeps nothing between 1,024 and 131,072. Its prefill took 84 s instead of under one. PCBinding::restore_plan now makes room before the engine plans the restore, the same way PCBinding::evict does for an admission: PrefixCache::trim_for drops entries whose host copy has landed, the engine lands pending copies (flush_fn), and it drops again. It never erases one, spares the restoring chain itself and every chain a waiting request holds, and like trim never touches one a running sequence reads. The free quarter may go; the reserve's trim after the next publish frees it again. One block table serves every rank, so the room rank 0's cache makes is room on every rank, as with evict. When the pool still cannot hold the chain, PrefixCache::restorable_from cuts it at the deepest valid snapshot the shorter prefix reaches, so no block comes back past the point the hit resumes from; without recurrent state it cuts where the room ends. TierExec::issue_restore keeps its own cut as the backstop. Both cuts are counted: radiance:prefix_restore_cuts_total for restores the pool could not hold whole (/sessions moved.restore_cuts), and radiance:prefix_hit_cuts_total{reason="resumed_below"} for admissions that resumed more than one checkpoint interval below their attention hit, which hit_cut_tokens alone did not tell apart from many small tails (/stats and /sessions hit_cuts). Co-Authored-By: Claude Opus 5.5 --- core/engine.cpp | 9 ++--- core/mem/prefix.cpp | 76 ++++++++++++++++++++++++++++----------- core/mem/prefix.h | 30 ++++++++++++++-- core/sched/mem_iface.h | 18 ++++++++++ core/sched/metrics.h | 12 +++++-- core/sched/scheduler.cpp | 7 ++++ core/sched/scheduler.h | 5 +-- core/server/adapters.h | 2 ++ core/server/dashboard.cpp | 7 ++-- core/server/iface.h | 3 ++ core/server/metrics.cpp | 15 ++++++-- core/server/metrics.h | 3 +- tests/dashboard_test.cpp | 4 +++ tests/mem_test.cpp | 29 +++++++++++++-- tests/sched_test.cpp | 21 +++++++++++ tests/server_test.cpp | 3 ++ 16 files changed, 205 insertions(+), 39 deletions(-) diff --git a/core/engine.cpp b/core/engine.cpp index f5d0d25e..7af29aab 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1479,13 +1479,14 @@ int Engine::serve(std::unique_ptr watch) { auto* b = static_cast*>(pc_iface_.get()); /* Called inside Scheduler::step() under its lock, which makes touching the cache and rank * 0's manager safe; nothing here may call back into the scheduler. */ - b->restore_fn = [this](const Request& req) { + b->restore_fn = [this, b](const Request& req) { const uint64_t t0 = rad_mono_ns(); PrefixCache& pc = ranks_[0]->prefix; - std::vector mk; - media_keys(req, &mk, cvec_salt_for(req.sp.use_control_vector)); + /* Room is made before anything is planned (PCBinding::restore_plan): a chain the free + * list cannot hold would otherwise come back only as far as it reaches. One block + * table serves every rank, so what rank 0's cache gives up is room on every rank. */ const std::vector want = - pc.restorable_from(req.prompt, mk); + b->restore_plan(req, cvec_salt_for(req.sp.use_control_vector)); if (want.empty()) return; /* The whole chain in one restore. With 4-token blocks a long conversation is tens of * thousands of entries; batched, it is one launch per (group, layer) per staging batch diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index 820e1abb..a2a418d8 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -5,6 +5,7 @@ #include #include +#include namespace rad { @@ -241,6 +242,22 @@ std::vector PrefixCache::chain_all(const std::vector& tokens return hs; } +/* A snapshot is on the chain when its key equals the chain hash at its position. */ +std::unordered_map::iterator +PrefixCache::deepest_ckpt(const std::vector& hs, int64_t limit) const { + auto best = ck_by_prefix_.end(); + for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) { + const Ckpt& c = it->second; + if (!c.valid || c.slot < 0 || c.pos <= 0 || c.pos > limit || c.pos % block_size_ != 0 || + c.pos / block_size_ > (int64_t)hs.size()) + continue; + if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue; + if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue; + best = it; + } + return best; +} + void PrefixCache::touch(const BlockHash& h, uint64_t now_ns) const { auto it = map_.find(h); if (it == map_.end() || !it->second.in_lru) return; @@ -274,23 +291,7 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, /* Back a full hit off by one block so one token remains to compute a logit from. */ if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched; - /* Deepest valid snapshot at or below `limit` on this chain. Checkpoints sit on the interval or - * at a prompt's tail (Scheduler::plan_chunk), i.e. on any block boundary, so iterate the - * snapshots (a few hundred) rather than the block positions (tens of thousands); a snapshot is - * on this chain when its key equals the chain hash at its position. */ - auto deepest = [&](int64_t limit) { - auto best = ck_by_prefix_.end(); - for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) { - const Ckpt& c = it->second; - if (!c.valid || c.slot < 0 || c.pos <= 0 || c.pos > limit || - c.pos % block_size_ != 0) - continue; - if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue; - if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue; - best = it; - } - return best; - }; + auto deepest = [&](int64_t limit) { return deepest_ckpt(hs, limit); }; /* Tokens a hit of `m` blocks lets a sequence skip: all of them, or with recurrent state only * up to the deepest checkpoint (Scheduler::admit_one resumes there). */ auto reusable = [&](int64_t m) -> int64_t { @@ -460,7 +461,8 @@ void PrefixCache::take_over(uint64_t session, const std::vector& hs, /* ------------------------------------------------------------------ idle session tiers */ std::vector PrefixCache::restorable_from(const std::vector& tokens, - const std::vector& mm) const { + const std::vector& mm, + int64_t fit) const { std::vector out; if (!enabled_ || !tiers_ || tokens.empty()) return out; @@ -474,15 +476,45 @@ std::vector PrefixCache::restorable_from(const std::vector& * how far the maintenance pass had got; the scheduler chunks the rest of the prefill against * that length, and greedy output is tie-level sensitive to the GEMM shapes (§19). Restoring * the whole chain makes the hit length a function of the prompt. */ + std::vector at; /* each entry's block on the chain */ for (int64_t b = 0; b < n_full; ++b) { auto it = map_.find(hs[(size_t)b]); if (it == map_.end()) break; if (!same_tokens(it->second, tokens.data() + b * block_size_)) break; - if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]); + if (!tiers_->resident_off_device(hs[(size_t)b])) continue; + out.push_back(hs[(size_t)b]); + at.push_back(b); } + if (out.empty() || (int64_t)out.size() <= fit) return out; + + /* Restored up to `fit`, the hit ends at the first entry left behind. */ + ++stats_.restore_cuts; + int64_t keep = std::max(0, fit); + if (has_linear_) { + const auto best = deepest_ckpt(hs, at[(size_t)keep] * block_size_); + const int64_t upto = best == ck_by_prefix_.end() ? 0 : best->second.pos / block_size_; + keep = std::lower_bound(at.begin(), at.begin() + keep, upto) - at.begin(); + } + out.resize((size_t)keep); return out; } +int64_t PrefixCache::restore_room() const { + if (!kv_ || groups_.empty()) return 0; + int64_t room = INT64_MAX; + for (int32_t g : groups_) room = std::min(room, kv_->total_blocks(g) - kv_->held_blocks(g)); + return std::max(0, room); +} + +int64_t PrefixCache::trim_for(const std::vector& tokens, + const std::vector& mm, int64_t n_blocks) { + if (!enabled_ || n_blocks <= 0) return 0; + const std::vector hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_); + std::unordered_set spare(hs.begin(), hs.end()); + for (const auto& h : held_) spare.insert(h.first); + return trim_sparing(n_blocks, &spare); +} + void PrefixCache::drop_offdevice(const BlockHash& key) { auto it = map_.find(key); if (it == map_.end()) return; @@ -569,7 +601,10 @@ int64_t PrefixCache::evict_lru(int64_t n) { return done; } -int64_t PrefixCache::trim(int64_t n_blocks) { +int64_t PrefixCache::trim(int64_t n_blocks) { return trim_sparing(n_blocks, nullptr); } + +int64_t PrefixCache::trim_sparing(int64_t n_blocks, + const std::unordered_set* spare) { /* Tiers attached but off count as no tiers: no copy will ever land, so do not wait for one. */ const bool keep = tiers_ && tiers_->host_on(); const uint64_t now = rad_mono_ns(); @@ -581,6 +616,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) { auto m = map_.find(h); if (m == map_.end()) { it = lru_.erase(it); continue; } Entry& e = m->second; + if (spare && spare->count(h)) { ++it; continue; } if (shared_with_live(e)) { /* In use: to the back, as in evict_lru. */ auto next = std::next(it); diff --git a/core/mem/prefix.h b/core/mem/prefix.h index 2f171fb1..c88c405a 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -44,6 +44,7 @@ #include #include #include +#include #include namespace rad { @@ -253,9 +254,24 @@ public: /* The off-device entries this prompt's chain would hit if restored, in order, from where * lookup stopped. The caller promotes them and looks up again; empty means the prefix ended * on a miss or token mismatch. Separate from lookup because lookup is const and has no - * device; a promotion allocates blocks and runs a scatter between steps. */ + * device; a promotion allocates blocks and runs a scatter between steps. + * + * `fit` is how many entries the pool can take. A longer chain is cut, and counted + * (Stats::restore_cuts): with recurrent state at the deepest snapshot the shorter prefix + * reaches, since the hit resumes there and blocks past it would come back for nothing; + * without, at `fit`. */ std::vector restorable_from(const std::vector& tokens, - const std::vector& mm) const; + const std::vector& mm, + int64_t fit = INT64_MAX) const; + /* Entries a restore can place now: free blocks against the carve, the least over the cached + * groups. Lent blocks count, since KVManager::reserve_blocks recalls the loan for them. */ + int64_t restore_room() const; + /* Room for a restore of this prompt's chain: trim(), sparing the chain itself (its blocks + * would only have to come back too) and every chain a waiting request holds (hold()), whose + * next attempt would restore it again. Nothing is lost; the reserve's trim after the next + * publish puts the pool's free quarter back. */ + int64_t trim_for(const std::vector& tokens, const std::vector& mm, + int64_t n_blocks); /* The tiers lost the bytes. Erases the entry without releasing blocks: an off-device entry * owns none, and its recorded ids now belong to other sequences. Installed as @@ -341,6 +357,8 @@ public: int64_t drops = 0; /* Entries and snapshots removed by --prefix-cache-ttl, from any tier. */ int64_t expired = 0, ckpt_expired = 0; + /* Restores from the host tier cut short because the pool could not hold the chain. */ + int64_t restore_cuts = 0; }; const Stats& stats() const { return stats_; } @@ -376,6 +394,9 @@ private: const std::vector& mm, int64_t n_blocks) const; void touch(const BlockHash& h, uint64_t now_ns) const; + /* trim(), leaving the entries in `spare` (when given) where they are. */ + int64_t trim_sparing(int64_t n_blocks, + const std::unordered_set* spare); /* A live sequence also holds one of this entry's blocks, so releasing it frees nothing. */ bool shared_with_live(const Entry& e) const; /* Whether `e` holds the block_size_ token ids at `src`, so a hash collision is a miss. */ @@ -396,6 +417,11 @@ private: /* For the debug lines: whether `c` is its session's deepest snapshot, and seconds since a * monotonic stamp. */ bool is_tip(const Ckpt& c) const; + /* The deepest valid snapshot on the chain `hs` at or below `limit` tokens; end() if none. + * Checkpoints sit on any block boundary (the interval or a prompt's tail), so this walks the + * snapshots, a few hundred, rather than the chain's blocks. */ + std::unordered_map::iterator + deepest_ckpt(const std::vector& hs, int64_t limit) const; static double idle_s(uint64_t used_ns); KVManager* kv_ = nullptr; diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index 40c3fc90..05934b33 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -170,6 +170,8 @@ struct IPrefixCache { virtual CkptCounts ckpt_counts() const { return {}; } /* Entries expired by --prefix-cache-ttl; not counted as evictions. */ virtual int64_t expired() const { return 0; } + /* Restores the pool could not hold whole (PrefixCache::Stats::restore_cuts). */ + virtual int64_t restore_cuts() const { return 0; } virtual int64_t ckpt_expired() const { return 0; } /* Tokens of context held only by the cache right now. Blocks a running sequence also reads @@ -346,6 +348,21 @@ struct PCBinding final : IPrefixCache { void restore(const Request& r) override { if (restore_fn) restore_fn(r); } + /* The entries restore_fn brings back, in chain order: the whole chain if the pool can be made + * to hold it, otherwise cut (PrefixCache::restorable_from). Room is made as evict() makes it, + * dropping entries with a landed host copy, then landing pending copies and dropping those, but + * never erasing one: a restore is worth no lost conversation. The pool's free quarter can go + * to it; the reserve's trim after the next publish frees it again. */ + std::vector restore_plan(const Request& r, uint64_t salt) { + media_keys(r, &mm_, salt); + std::vector want = m->restorable_from(r.prompt, mm_); + const int64_t need = (int64_t)want.size() - m->restore_room(); + if (need <= 0) return want; + const int64_t k = m->trim_for(r.prompt, mm_, need); + if (k < need && flush_fn && flush_fn()) (void)m->trim_for(r.prompt, mm_, need - k); + /* Landing copies may have moved records; take the chain again against the room made. */ + return m->restorable_from(r.prompt, mm_, m->restore_room()); + } void begin_step() override { m->begin_step(); } void hold(const Request& r) override { media_keys(r, &mm_, salt_id); @@ -405,6 +422,7 @@ struct PCBinding final : IPrefixCache { return { st.ckpt_retired, st.ckpt_lru, st.ckpt_refused }; } int64_t expired() const override { return m->stats().expired; } + int64_t restore_cuts() const override { return m->stats().restore_cuts; } int64_t ckpt_expired() const override { return m->stats().ckpt_expired; } int64_t held_tokens() const override { return m->unshared_tokens(); } diff --git a/core/sched/metrics.h b/core/sched/metrics.h index 801cec72..a4aa80cf 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -94,11 +94,17 @@ struct SchedMetrics { int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* --prefix-cache-ttl */ /* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent * state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks - * that could not be adopted. `hit_cut_tokens` is the checkpoint shortfall: prompt tokens the - * attention cache held and the admission computed again, because the hit resumed at a - * snapshot below it or was cut to nothing. */ + * that could not be adopted. `hit_cut_resumed_below` counts those that resumed at a + * snapshot more than one checkpoint interval below the hit: the retention ladder had + * nothing nearer, or the restore brought back only part of the chain. `hit_cut_tokens` is + * the checkpoint shortfall: prompt tokens the attention cache held and the admission + * computed again, because the hit resumed at a snapshot below it or was cut to nothing. */ int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0; + int64_t hit_cut_resumed_below = 0; int64_t hit_cut_tokens = 0; + /* Restores from the host tier the pool could not hold whole, even after giving up the VRAM + * copies of other conversations (PrefixCache::Stats::restore_cuts). */ + int64_t prefix_restore_cuts = 0; /* Tokens of context held only by the cache, i.e. what eviction would free. Excludes blocks * shared with a running sequence. Same token axis as the paged groups, so comparable with * kv_tokens_used. */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index f2bac4e9..7a5667db 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -973,6 +973,11 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { RAD_DEBUG("admit %llu: prefix hit of %lld tokens reuses nothing -- no snapshot at or " "below it", (unsigned long long)r.id, (long long)h.n_attn_tokens); } else if (reuse < h.n_attn_tokens) { + /* Within an interval of the hit is the ordinary case: a turn's tail past its last + * checkpoint. Further down, the snapshots in between are gone, or the attention + * blocks reach past what the tiers could restore of the chain. */ + if (geo_.checkpoints() && h.n_attn_tokens - reuse > geo_.checkpoint_interval) + s.hit_cut = SchedReq::HitCut::ResumedBelow; RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at the snapshot at %lld", (unsigned long long)r.id, (long long)h.n_attn_tokens, (long long)reuse); } @@ -1092,6 +1097,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { case SchedReq::HitCut::NoSnapshot: ++m_.hit_cut_no_snapshot; break; case SchedReq::HitCut::Window: ++m_.hit_cut_window; break; case SchedReq::HitCut::Adopt: ++m_.hit_cut_adopt; break; + case SchedReq::HitCut::ResumedBelow: ++m_.hit_cut_resumed_below; break; case SchedReq::HitCut::None: break; } } @@ -2625,6 +2631,7 @@ SchedMetrics Scheduler::metrics_locked() const { m.prefix_ckpt_refused = cc.refused; m.prefix_expired = pc_->expired(); m.prefix_ckpt_expired = pc_->ckpt_expired(); + m.prefix_restore_cuts = pc_->restore_cuts(); m.prefix_held_tokens = pc_->held_tokens(); } m.attn_hit_rate = m.prompt_tokens ? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f; diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 7919e54e..d89c323e 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -107,8 +107,9 @@ struct SchedReq { * fit would inflate the prompt and hit totals. */ int32_t hit_attn = 0; bool hit_owed = false; - /* Why that hit was cut to nothing, for the counters (SchedMetrics::hit_cut_*). */ - enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt }; + /* Why that hit was cut, for the counters (SchedMetrics::hit_cut_*): to nothing, or to a + * snapshot more than an interval below it. */ + enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt, ResumedBelow }; HitCut hit_cut = HitCut::None; /* The whole sequence is prompt ++ output; n_computed indexes into it. */ diff --git a/core/server/adapters.h b/core/server/adapters.h index 6da4c418..a624d5e7 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -102,6 +102,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) { o.hit_cut_no_snapshot = m.hit_cut_no_snapshot; o.hit_cut_window = m.hit_cut_window; o.hit_cut_adopt = m.hit_cut_adopt; + o.hit_cut_resumed_below = m.hit_cut_resumed_below; + o.prefix_restore_cuts = m.prefix_restore_cuts; o.hit_cut_tokens = m.hit_cut_tokens; o.prefix_expired = m.prefix_expired; o.prefix_ckpt_expired = m.prefix_ckpt_expired; diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 9a383322..53b976ba 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -131,6 +131,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped }, { "promoted", c.promoted }, { "host_drops", c.host_drops }, { "held_back", c.held_back }, + { "restore_cuts", sm.prefix_restore_cuts }, { "failures", c.failures } }; /* Snapshot store on a hybrid model: bytes per snapshot and slot count. `bytes_each` is 0 * on a model with no recurrent state. */ @@ -150,7 +151,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { { "refused", sm.prefix_ckpt_refused }, { "hit_cuts", { { "no_snapshot", sm.hit_cut_no_snapshot }, { "windowed_group", sm.hit_cut_window }, - { "adopt_failed", sm.hit_cut_adopt } } }, + { "adopt_failed", sm.hit_cut_adopt }, + { "resumed_below", sm.hit_cut_resumed_below } } }, { "hit_cut_tokens", sm.hit_cut_tokens } }; /* Whether a tier exists to move sessions to. A session is recorded whether or not it can be * demoted, so a non-empty table only says something is held. */ @@ -222,7 +224,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) { o["ckpt_refused"] = m.prefix_ckpt_refused; o["hit_cuts"] = { { "no_snapshot", m.hit_cut_no_snapshot }, { "windowed_group", m.hit_cut_window }, - { "adopt_failed", m.hit_cut_adopt } }; + { "adopt_failed", m.hit_cut_adopt }, + { "resumed_below", m.hit_cut_resumed_below } }; o["hit_cut_tokens"] = (double)m.hit_cut_tokens; o["prefill_tps"] = m.prefill_tps; o["decode_tps"] = m.decode_tps; diff --git a/core/server/iface.h b/core/server/iface.h index 8cd70dd4..a017ca6e 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -72,7 +72,10 @@ struct SchedMetrics { /* Admissions whose prefix hit was cut to nothing, by reason, and the checkpoint shortfall: * attention-cached prompt tokens computed again (rad::SchedMetrics::hit_cut_tokens). */ int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0; + int64_t hit_cut_resumed_below = 0; /* resumed more than an interval below the hit */ int64_t hit_cut_tokens = 0; + /* Host-tier restores the pool could not hold whole (rad::SchedMetrics::prefix_restore_cuts). */ + int64_t prefix_restore_cuts = 0; /* Removed by --prefix-cache-ttl, cumulative. Not evictions: nothing wanted the memory. */ int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* Decoupled prefix caching (spec §7.3). `prefix_hit_rate` is the attention hit rate, as in diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index f258d219..8bae8246 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -196,6 +196,8 @@ void Metrics::sample(const SchedMetrics& m) { c_cut_no_snapshot_.advance_to(m.hit_cut_no_snapshot); c_cut_window_.advance_to(m.hit_cut_window); c_cut_adopt_.advance_to(m.hit_cut_adopt); + c_cut_resumed_below_.advance_to(m.hit_cut_resumed_below); + c_restore_cuts_.advance_to(m.prefix_restore_cuts); c_cut_tokens_.advance_to(m.hit_cut_tokens); g_linear_hit_.set(m.linear_hit_rate); } @@ -449,13 +451,20 @@ std::string Metrics::render() const { "Checkpoints not written because every snapshot slot was in use by a restore " "in the same step.", L, c_ckpt_refused_.get()); w.help("radiance:prefix_hit_cuts_total", - "Admissions whose prefix hit reused nothing, by reason: no snapshot at or below " - "the hit, a windowed group no window snapshot covers, or blocks that could not be " - "adopted.", "counter"); + "Admissions whose prefix hit was cut, by reason: reused nothing for want of a " + "snapshot at or below the hit, for a windowed group no window snapshot covers, or " + "for blocks that could not be adopted; or resumed at a snapshot more than one " + "checkpoint interval below the hit.", "counter"); labelled("radiance:prefix_hit_cuts_total", "reason", "no_snapshot", c_cut_no_snapshot_.get()); labelled("radiance:prefix_hit_cuts_total", "reason", "windowed_group", c_cut_window_.get()); labelled("radiance:prefix_hit_cuts_total", "reason", "adopt_failed", c_cut_adopt_.get()); + labelled("radiance:prefix_hit_cuts_total", "reason", "resumed_below", + c_cut_resumed_below_.get()); + w.counter("radiance:prefix_restore_cuts_total", + "Restores from the host tier the pool could not hold whole, even after giving " + "up the VRAM copies of other stored conversations; each came back to a " + "snapshot short of its end.", L, c_restore_cuts_.get()); w.counter("radiance:prefix_hit_cut_tokens_total", "Prompt tokens the attention cache held and admission computed again, because " "the hit resumed at a snapshot below it or reused nothing.", L, diff --git a/core/server/metrics.h b/core/server/metrics.h index 11ba72c4..a4aedb0e 100644 --- a/core/server/metrics.h +++ b/core/server/metrics.h @@ -153,7 +153,8 @@ private: Counter c_prefix_evict_, c_prefix_ckpt_evict_; Counter c_prefix_expired_, c_prefix_ckpt_expired_; Counter c_ckpt_retired_, c_ckpt_lru_, c_ckpt_refused_; - Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_tokens_; + Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_resumed_below_, c_cut_tokens_; + Counter c_restore_cuts_; Gauge g_linear_hit_; Counter c_success_[(size_t)SuccessReason::N_]; Counter c_rejected_, c_disconnect_, c_overflow_; diff --git a/tests/dashboard_test.cpp b/tests/dashboard_test.cpp index 86c41002..e8f0126b 100644 --- a/tests/dashboard_test.cpp +++ b/tests/dashboard_test.cpp @@ -122,6 +122,8 @@ struct Dash { sched.m.prefix_ckpt_lru = 3; sched.m.hit_cut_no_snapshot = 2; sched.m.hit_cut_tokens = 9000; + sched.m.hit_cut_resumed_below = 4; + sched.m.prefix_restore_cuts = 1; sched.m.draft_depth_seen = 2; sched.m.draft_pos_reached[0] = 10; sched.m.draft_pos_accepted[0] = 8; sched.m.draft_pos_reached[1] = 8; sched.m.draft_pos_accepted[1] = 2; @@ -239,6 +241,8 @@ TEST(sessions_lists_each_conversation_and_what_the_tiers_did) { CHECK(s.value("enabled", false)); CHECK_EQ(s["linear"]["evictions"].value("store_full", (int64_t)0), (int64_t)3); CHECK_EQ(s["linear"]["hit_cuts"].value("no_snapshot", (int64_t)0), (int64_t)2); + CHECK_EQ(s["linear"]["hit_cuts"].value("resumed_below", (int64_t)0), (int64_t)4); + CHECK_EQ(s["moved"].value("restore_cuts", (int64_t)0), (int64_t)1); CHECK_EQ(s["linear"].value("hit_cut_tokens", (int64_t)0), (int64_t)9000); } diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 07ba5c45..2ad190f4 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -6101,8 +6101,7 @@ TEST(the_cache_tiers_and_pool_agree_over_random_interleavings) { /* The engine's restore (the binding's restore_fn) without the transfer: which entries come back, * into which blocks, and what the tiers and the cache are told. Returns how many came back. */ static int64_t engine_restore(TierFixture& x, PCBinding& b, const Request& r) { - (void)b; - const std::vector want = x.f.pc.restorable_from(r.prompt, {}); + const std::vector want = b.restore_plan(r, 0); std::vector jobs; for (const BlockHash& h : want) { TierJob j; @@ -6184,6 +6183,7 @@ TEST(a_restore_gives_up_other_clean_copies_to_bring_the_whole_chain_back) { CHECK_EQ(x.f.pc.stats().evictions, evictions); CHECK_EQ(x.f.pc.size(), 2 * s.n); CHECK_EQ((int64_t)x.f.pc.restorable_from(s.b, {}).size(), 2 * s.n - x.f.pc.resident()); + CHECK_EQ(x.f.pc.stats().restore_cuts, 0ll); } /* With recurrent state the hit resumes at the deepest snapshot the restored prefix reaches. Cut @@ -6201,6 +6201,7 @@ TEST(a_restored_hybrid_conversation_resumes_at_its_tip_snapshot) { const CacheHit hit = x.f.pc.lookup(s.a, {}); CHECK_EQ(hit.n_attn_tokens, (int32_t)(s.n * 16)); CHECK_EQ(hit.n_linear_tokens, (int32_t)(s.n * 16)); + CHECK_EQ(x.f.pc.stats().restore_cuts, 0ll); } /* When the pool cannot be made to hold the chain, what comes back ends at a snapshot: blocks past @@ -6233,6 +6234,30 @@ TEST(a_restore_the_pool_cannot_hold_stops_at_a_snapshot_and_spares_its_own_chain CHECK_EQ(hit.n_linear_tokens, (int32_t)snap); CHECK_EQ(hit.n_attn_tokens, (int32_t)std::max(snap, resident * 16)); CHECK_EQ(x.f.pc.lookup(s.b, {}).n_attn_tokens, (int32_t)(s.n * 16)); + CHECK_EQ(x.f.pc.stats().restore_cuts, 1ll); +} + +/* A chain another waiting request holds is kept too: that request restored it and was refused, + * and taking it would only have its next attempt restore it again. */ +TEST(a_restore_does_not_take_a_chain_a_waiting_request_holds) { + TierFixture x; + CHECK_OK(x.build()); + const TwoSessions s = two_sessions(x, /*b_live=*/false, /*a_snapshots=*/false); + copy_now(x.t); /* B is clean, so a trim could take it */ + x.f.pc.hold(9, s.b, {}); + const int64_t room = x.f.kv.total_blocks(G_FULL) - x.f.kv.held_blocks(G_FULL); + const int64_t drops = x.f.pc.stats().drops; + + PCBinding b(&x.f.pc); + CHECK_EQ(engine_restore(x, b, turn(3, s.a, {})), room); + CHECK_EQ(x.f.pc.stats().drops, drops); + CHECK_EQ(x.f.pc.lookup(s.b, {}).n_attn_tokens, (int32_t)(s.n * 16)); + CHECK_EQ(x.f.pc.stats().restore_cuts, 1ll); + + x.f.pc.release(9); + const int64_t rest = (int64_t)x.f.pc.restorable_from(s.a, {}).size(); + CHECK_EQ(engine_restore(x, b, turn(3, s.a, {})), rest); + CHECK_EQ(x.f.pc.lookup(s.a, {}).n_attn_tokens, (int32_t)(s.n * 16)); } /* Tools and tests build and tear down the tier executors and pools repeatedly, and on a card every diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 294e8b7b..f4983389 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -824,6 +824,7 @@ TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) { /* The checkpoint shortfall: the 48 cached tokens above the snapshot are computed again. */ CHECK_EQ(m.hit_cut_tokens, 48); CHECK_EQ(m.hit_cut_no_snapshot, 0); + CHECK_EQ(m.hit_cut_resumed_below, 0); /* within an interval: a turn's ordinary tail */ /* The snapshot this step takes is not offered to anyone until the step has run: the * reservation happens when the chunk is planned, the state exists only afterwards. */ @@ -833,6 +834,26 @@ TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) { CHECK_EQ(f.pc.committed[0], 512); /* ctx_len 256 + ckpt_tok 255 + 1 */ } +/* A hit that resumes more than an interval below the attention blocks is counted with its own + * reason: the snapshots in between are gone, or a restore brought back only part of the chain, + * and hit_cut_tokens alone would not say how many admissions it was. */ +TEST(a_hit_resuming_far_below_its_blocks_is_counted_as_cut) { + Fixture f; + f.build(); + CHECK_OK(f.start()); + f.pc.seed(784); /* 49 blocks */ + f.pc.lin = 256; /* 528 tokens below, past the 256-token interval */ + f.pc.src = 3; + + uint64_t a = f.submit(1000, 8); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 256); + const SchedMetrics m = f.sch.metrics(); + CHECK_EQ(m.hit_cut_resumed_below, 1); + CHECK_EQ(m.hit_cut_no_snapshot, 0); + CHECK_EQ(m.hit_cut_tokens, 528); +} + /* A hit that skipped tokens with no snapshot to resume from would corrupt the linear state, so it * is refused outright rather than served with a zeroed state. */ TEST(a_hit_with_no_checkpoint_slot_reuses_nothing) { diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 0c6cf36a..4ed78b23 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -2391,6 +2391,7 @@ TEST(snapshot_evictions_and_cut_hits_are_counted_by_reason) { server::SchedMetrics s; s.prefix_ckpt_retired = 5; s.prefix_ckpt_lru = 3; s.prefix_ckpt_refused = 1; s.hit_cut_no_snapshot = 2; s.hit_cut_window = 0; s.hit_cut_adopt = 4; + s.hit_cut_resumed_below = 6; s.prefix_restore_cuts = 7; s.hit_cut_tokens = 76092; m.sample(s); PromDoc d = parse_prom(m.render()); @@ -2411,6 +2412,8 @@ TEST(snapshot_evictions_and_cut_hits_are_counted_by_reason) { CHECK_NEAR(value(C + ",reason=\"no_snapshot\"}"), 2.0, 1e-9); CHECK_NEAR(value(C + ",reason=\"windowed_group\"}"), 0.0, 1e-9); CHECK_NEAR(value(C + ",reason=\"adopt_failed\"}"), 4.0, 1e-9); + CHECK_NEAR(value(C + ",reason=\"resumed_below\"}"), 6.0, 1e-9); + CHECK_NEAR(value("radiance:prefix_restore_cuts_total" + L + "}"), 7.0, 1e-9); CHECK_NEAR(value("radiance:prefix_hit_cut_tokens_total" + L + "}"), 76092.0, 1e-9); } From 332b5fa9861ced86e9a8bd3de3babbd940912bbd Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:24:29 +0200 Subject: [PATCH 131/152] docs/GUIDE: a restore gives up other conversations' VRAM; prefix_restore_cuts_total, resumed_below Co-Authored-By: Claude Opus 5.5 --- docs/GUIDE.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index f20be2fb..cd93f658 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1184,6 +1184,16 @@ before that resumes from VRAM; one that returns after is restored from host memo copy, so its next turn copies only what that turn added. A full host tier drops its least recently used conversations. Nothing is written to a drive. +A restore is one of the requests VRAM is given up for. The cache keeps a quarter of the pool free +after each turn, and a returning conversation larger than that takes the VRAM copies of other +stored conversations too, the way an admission under pressure does: those with a host copy first, +then those whose copy was still on its way, once it lands. Nothing is lost by it, since each keeps +its host copy, and it never takes the returning conversation's own blocks, a conversation a +running request reads, or one a waiting request has just brought back. Only when the pool cannot +hold the whole conversation even then does it come back in part, and on a hybrid model it then ends +at the deepest snapshot it reaches, where its next turn resumes; `radiance:prefix_restore_cuts_total` +counts these (`/sessions` `moved.restore_cuts`). + Every stored conversation expires: one unused for `--prefix-cache-ttl` seconds is removed from whichever tier holds it (VRAM blocks to the pool, host slot to the arena, snapshots to the store). A hit or a new turn counts as a use, and a system prompt shared by several conversations stays while @@ -2886,7 +2896,8 @@ there is none. | `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | | | `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | | | `prefix_cache_ckpt_evictions_by_reason_total{reason}`, `prefix_cache_ckpt_refused_total` | snapshots released by `--checkpoint-policy` (`retention`) or as the least recently used of a full store (`store_full`); checkpoints not written for want of a slot | -| `prefix_hit_cuts_total{reason}`, `prefix_hit_cut_tokens_total` | admissions whose hit reused nothing (`no_snapshot`, `windowed_group`, `adopt_failed`), and the checkpoint shortfall: cached prompt tokens computed again because the hit resumed at a snapshot below it. `/stats` and `/sessions` carry the same counts; `RADIANCE_LOG=debug` logs each eviction and each cut hit | +| `prefix_hit_cuts_total{reason}`, `prefix_hit_cut_tokens_total` | admissions whose hit reused nothing (`no_snapshot`, `windowed_group`, `adopt_failed`) or resumed at a snapshot more than one checkpoint interval below it (`resumed_below`), and the checkpoint shortfall: cached prompt tokens computed again because the hit resumed at a snapshot below it. `/stats` and `/sessions` carry the same counts; `RADIANCE_LOG=debug` logs each eviction and each cut hit | +| `prefix_restore_cuts_total` | restores from the host tier the pool could not hold whole, even after giving up other conversations' VRAM copies (§4.8) | | `prefix_cache_expired_total`, `prefix_cache_ckpt_expired_total` | what `--prefix-cache-ttl` removed (§4.8) | | `num_requests_preempted` | | | `http_queue_depth`, `http_responses_total`, `http_admission_rejected_total` | | From 961a9b3f135cc065cc27fe64ec7ffcba3bb96ce1 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:12 +0200 Subject: [PATCH 132/152] libr4d: moe_gemm_mxfp4a8's small-M form at GLM's TP8 slices -- a one-stream verify pass is a chain of short expert launches At 1 to 48 tokens a chunk (8 to 384 routed rows) the expert-major forms spent their time around the loads rather than on them. Taking the loads out left gate_up at 72 of its 115 us at six tokens; what remained was the skeleton of each block: 289 grid rows for the few touched experts, activation scales read row by row from LDS behind a divergent branch, weight rows loaded through generic pointers (flat loads, which every LDS wait also waits for), loads behind branches so each store waited for the whole prefetch, and __syncthreads' workgroup fence. With 160 blocks resident at 21.8 KiB of LDS each, the last round of an expert-major launch ran nearly empty, at the latency of one block's chain. moe_mxfp4_small_kernel keeps the expert-major per-element sequence, and so its bytes: - block row y takes the y-th touched expert, counted by ballot over the offsets, so the grid has min(experts, rows) + 1 rows; - weight codes stay packed in LDS and are decoded at the fragment read, halving the weight tile; gate_up stages 512 of K, reading 256 bytes of each weight row at once, down its 128-byte rows whole over four column tiles; - loads are unconditional from clamped addresses and masked at the store, weight rows load through global pointers, the barriers order LDS only, and a 128 of K reads its activation scales and eight fragment pairs before its WMMA chains. The rule takes it at GLM's TP8 slices for gate_up to 384 routed rows and down to 32; from five tokens down reads 3 to 5 % slower than the staged form and keeps it. Other shapes are unchanged. A deeper register prefetch, a barrier-free form with B straight from global memory and A tiles sized to the chunk's tokens measured no faster. Measured at the TP8 slices (r4d_selftest --cold 256 --perfmx), expert-major against small-M: tokens 1 3 6 8 16 48 gate_up, us 36.8 79.5 120.5 145.0 230.3 416.7 31.4 69.5 101.4 122.4 206.8 390.0 tokens 1 2 3 4 down, us 21.2 26.0 34.3 39.5 16.4 22.5 33.2 37.9 Byte for byte against the expert-major forms over 1 to 48 tokens at every form tried (perfmx with the old form kept beside it during the work), and in r4d_emu against the host restatement: three GLM TP8 cases, with runs longer than one tile, dropped slots and E8M0 codes 0 and 255. r4d_selftest checks the new band against libref at 1 to 48 tokens, and --perfmx names the form. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_moe_mxfp4.hip | 239 +++++++++++++++++++++++++++++++++++ libr4d/r4d_selftest.cpp | 18 ++- tests/r4d_emu/test_moemx.cpp | 42 +++++- 3 files changed, 293 insertions(+), 6 deletions(-) diff --git a/libr4d/r4d_moe_mxfp4.hip b/libr4d/r4d_moe_mxfp4.hip index 4217fd53..8d565b85 100644 --- a/libr4d/r4d_moe_mxfp4.hip +++ b/libr4d/r4d_moe_mxfp4.hip @@ -837,6 +837,228 @@ __global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel( } } +/* The small-M form at GLM's TP8 slices: expert-major with the same per-element sequence as the two + * forms above, so their bytes. A verify pass of one stream routes 8 to 48 rows over as many + * experts, and there those forms spend their time around the loads: an expert's block was a long + * chain of short stages, and the blocks the LDS admitted came in rounds whose last one ran nearly + * empty. This form shortens and thins the chain: + * - Block row y takes the y-th touched expert (a wave counts the non-empty runs by ballot), so the + * grid has min(experts, rows) + 1 rows rather than one an expert, most of them idle. + * - Weight codes stay packed in LDS and are decoded at the fragment read, which halves the + * weight tile; gate_up stages 512 of K, so a stage reads 256 bytes of each weight row where the + * 256 stage read 128, and down reads its 128-byte rows whole over four column tiles. + * - Loads are unconditional from clamped addresses and masked at the store, so a store waits for + * its own stage and not the prefetch; weight rows load through global pointers, the barriers + * order LDS only, and a 128 of K reads its activation scales and eight fragment pairs before its + * WMMA chains. */ +template +struct MxSmall { + static constexpr int Threads = 128, BN = 64, KB = StageK / 128, PA = StageK + 8, + PB = StageK / 2 + 8; + static constexpr int AChunks = StageK / Threads, WChunks = BN * StageK / 32 / Threads, + SChunks = (BN * KB + Threads - 1) / Threads; + mx_u4 a[AChunks], w[WChunks]; + uint32_t s[SChunks]; + float sa; + uint32_t ok; +}; +template +__global__ __launch_bounds__(128) void moe_mxfp4_small_kernel( + const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, + const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + using St = MxSmall; + constexpr int BN = St::BN, Threads = St::Threads, KB = St::KB, PA = St::PA, PB = St::PB; + static_assert(St::AChunks <= 8 && St::WChunks <= 16 && St::SChunks <= 4 && + 16 * KB <= Threads && BN * PB >= 4 * 513, + "stage chunks must fit the load mask and the offsets the weight tile"); + __shared__ __align__(16) uint8_t aa[16 * PA], bb[BN * PB]; + __shared__ uint32_t ss[BN * KB]; + __shared__ float sa[16 * KB]; + __shared__ int src[16]; + __shared__ int pick; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int colb = blockIdx.x * (BN * ColTiles); + if ((int)blockIdx.y == (int)gridDim.y - 1) { + const int r0 = offset[m.experts]; + for (long i = tid; i < (long)(m.T - r0) * BN * ColTiles; i += Threads) { + const int n = colb + (int)(i % (BN * ColTiles)); + if (n < m.N) y[(long)(r0 + i / (BN * ColTiles)) * m.yr + n] = 0; + } + return; + } + { + // The offsets in the weight tile, whose bytes are free until the first stage. + int* offs = reinterpret_cast(bb); +#pragma unroll + for (int q = 0; q < 5; ++q) { + const int x = tid + q * Threads; + if (x <= m.experts) offs[x] = offset[x]; + } + lds_barrier(); + if (wave == 0) { + int want = blockIdx.y, found = -1; + for (int base = 0; base < m.experts; base += 32) { + const int x = base + lane; + const bool live = x < m.experts && offs[x + 1] > offs[x]; + const uint32_t mask = __builtin_amdgcn_ballot_w32(live); + const int n = __builtin_popcount(mask); + if (want < n) { + const uint32_t below = mask & ((1u << lane) - 1u); + found = base + __builtin_ctz(__builtin_amdgcn_ballot_w32( + live && __builtin_popcount(below) == want)); + break; + } + want -= n; + } + if (lane == 0) pick = found; + } + lds_barrier(); + } + const int e = pick; + if (e < 0) return; + const int lo = offset[e], hi = offset[e + 1]; + const int cls = e & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], e / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], e / 2); + const int ksn = (kc + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + BN - 1) / BN), + S = tiles * ksn; + const int rowbase = (lane >> 4) * 8, mycol = wave * 16 + (lane & 15); + auto wrow = [&](int n, bool& valid) { + const int within = n % pw; + valid = n < m.N && within < cw; + return (n / pw) * cw + within; + }; + for (int r0 = lo; r0 < hi; r0 += 16) { + lds_barrier(); + if (tid < 16) { + const int r = r0 + tid, flat = r < hi ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + lds_barrier(); + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = src[rowbase + j] >= 0; + auto load = [&](int s, St& L) { + const int col0 = colb + (s / ksn) * BN, k0 = (s % ksn) * StageK; + uint32_t ok = 0; +#pragma unroll + for (int i = 0; i < St::AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16, ar = src[r]; + const bool v = ar >= 0 && k0 + d < kc; + __builtin_memcpy(&L.a[i], a + (v ? (long)ar * m.ar + k0 + d : 0), 16); + ok |= (uint32_t)v << i; + } +#pragma unroll + for (int i = 0; i < St::WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; + bool valid; + const int wn = wrow(col0 + c, valid); + const bool v = valid && k0 + 2 * d < kc; + const r4d_u32x4 q = mx_ldg16(w + (v ? (long)wn * m.wrow[cls] + k0 / 2 + d : 0)); + L.w[i] = mx_u4{ q[0], q[1], q[2], q[3] }; + ok |= (uint32_t)v << (8 + i); + } +#pragma unroll + for (int i = 0; i < St::SChunks; ++i) { + const int j = tid + i * Threads, c = j / KB, kb = k0 + (j % KB) * 128; + bool valid; + const int wn = wrow(col0 + c, valid); + const bool v = j < BN * KB && valid && kb < kc; + L.s[i] = mx_ldg4(ws + (v ? (long)wn * m.srow[cls] + kb / 32 : 0)); + ok |= (uint32_t)v << (24 + i); + } + { + const int ar = src[(tid / KB) & 15], kb = k0 + (tid % KB) * 128; + const bool v = tid < 16 * KB && ar >= 0 && kb < kc; + L.sa = as[v ? (long)ar * m.asr + kb / 128 : 0]; + ok |= (uint32_t)v << 28; + } + L.ok = ok; + }; + auto store = [&](const St& L) { +#pragma unroll + for (int i = 0; i < St::AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16; + *reinterpret_cast(aa + r * PA + d) = + (L.ok >> i) & 1u ? L.a[i] : mx_u4{ 0, 0, 0, 0 }; + } +#pragma unroll + for (int i = 0; i < St::WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; + const mx_u4 q = (L.ok >> (8 + i)) & 1u ? L.w[i] : mx_u4{ 0, 0, 0, 0 }; + *reinterpret_cast(bb + c * PB + d) = uint2{ q[0], q[1] }; + *reinterpret_cast(bb + c * PB + d + 8) = uint2{ q[2], q[3] }; + } +#pragma unroll + for (int i = 0; i < St::SChunks; ++i) { + const int j = tid + i * Threads; + if (j < BN * KB) ss[j] = (L.ok >> (24 + i)) & 1u ? L.s[i] : 0x7f7f7f7fu; + } + if (tid < 16 * KB) sa[(tid % KB) * 16 + tid / KB] = (L.ok >> 28) & 1u ? L.sa : 0.f; + }; + auto total = r4d_fp8::acc_zero(); + auto compute = [&](int s) { + const int k0 = (s % ksn) * StageK; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= kc) break; + const uint32_t exps = ss[mycol * KB + kb]; + float act[8]; +#pragma unroll + for (int row = 0; row < 8; ++row) act[row] = sa[kb * 16 + rowbase + row]; + r4d_fp8::i2v fa[8], fb[8]; +#pragma unroll + for (int t = 0; t < 8; ++t) { + const int k = kb * 128 + 16 * t; + fa[t] = r4d_fp8::frag(aa, 0, k, lane); + const uint2 v = mx_codes8( + *reinterpret_cast(bb + mycol * PB + (k + rowbase) / 2)); + fb[t] = r4d_fp8::i2v{ (int)v.x, (int)v.y }; + } + r4d_fp8::f8v raw[4]; +#pragma unroll + for (int g = 0; g < 4; ++g) + raw[g] = r4d_fp8::mma(fa[2 * g], fb[2 * g], r4d_fp8::acc_zero()); +#pragma unroll + for (int g = 0; g < 4; ++g) raw[g] = r4d_fp8::mma(fa[2 * g + 1], fb[2 * g + 1], raw[g]); +#pragma unroll + for (int g = 0; g < 4; ++g) { + const uint32_t exp = (exps >> (8 * g)) & 0xffu; + const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? (exp << 23) + : 0x00400000u); +#pragma unroll + for (int row = 0; row < 8; ++row) + if (rv[row]) total[row] += raw[g][row] * act[row] * scale; + } + } + if (s % ksn == ksn - 1) { + const int n = colb + (s / ksn) * BN + mycol; +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = r0 + rowbase + row; + if (r < hi && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]); + } + total = r4d_fp8::acc_zero(); + } + }; + St L; + load(0, L); + for (int s = 0; s < S; ++s) { + store(L); + lds_barrier(); + if (s + 1 < S) load(s + 1, L); + compute(s); + lds_barrier(); + } + } +} + int table(const RadTensor* t, uint32_t dtype, int bits, long experts, long n, long k, long* step, int* row) { if (!t || !t->data || t->rank != 3 || t->dtype != dtype || t->shape[0] < experts || @@ -934,6 +1156,23 @@ int body(const RadArgs* a, RadStream stream) { if (wide) return MX_P64(64, 128, 128, 1, false); return bm == 64 ? MX_P64(64, 64, 256, 1, false) : MX_P64(32, 64, 256, 1, false); #undef MX_P64 + } + /* The small-M form at GLM's TP8 slices, ahead of the expert-major band: gate_up up to 384 + * routed rows, down up to 32, where it stops gaining (at 5 to 8 tokens it reads 3 to 5 % + * slower than the staged form). Measured at those slices (perfmx, cold), expert-major against + * small-M: gate_up at 1, 3, 6, 8, 16 and 48 tokens 36.8/31.4, 79.5/69.5, 120.5/101.4, + * 145.0/122.4, 230.3/206.8 and 416.7/390.0 us; down at 1, 2 and 4 tokens 21.2/16.4, 26.0/22.5 + * and 39.5/37.9 us. */ + if (tp8 && m.T <= (m.K <= 256 ? 32 : 384)) { + const long rows = std::min(m.experts, m.T) + 1; +#define MX_SMALL(SK, CT) \ + R4D_EMIT(stream, (moe_mxfp4_small_kernel), \ + dim3(((long)m.N + 64 * CT - 1) / (64 * CT), rows), dim3(128), 0, \ + (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \ + w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \ + (uint16_t*)y->data, m) + return m.K <= 256 ? MX_SMALL(256, 4) : MX_SMALL(512, 1); +#undef MX_SMALL } /* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted * rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index f6a5e42f..af2e207c 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -15007,8 +15007,8 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co * * The form is the launcher's rule, mirrored here only to name it and count the expert slices it * streams: a (job, expert) pair reads the whole slice across the column blocks, so row groups - * re-read an expert once per group its run spans, the expert-major decode form once per 16 of its - * rows, and the P64 and GLM prefill forms once per job. */ + * re-read an expert once per group its run spans, the expert-major and small-M forms once per 16 + * of its rows, and the P64 and GLM prefill forms once per job. */ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_t top_k, bool f8 = false, const char* skew = nullptr) { if (iters <= 0) iters = 100; @@ -15235,11 +15235,12 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ const int64_t pbm = pwide || (K > 256 && Tr >= 12288) ? 64 : 32; const bool p64 = glm && Tr >= (P.srt ? 5760 : 769) && (Tr + pbm - 1) / pbm + E <= 65535; - const bool expert = !p64 && (f8 || Tr <= (glm ? (P.srt ? 6143 : 768) : 511)); - const bool pipe = !p64 && !expert && glm; + const bool small = glm && Tr <= (P.srt ? 32 : 384); + const bool expert = !p64 && !small && (f8 || Tr <= (glm ? (P.srt ? 6143 : 768) : 511)); + const bool pipe = !p64 && !small && !expert && glm; const int64_t jr = p64 ? pbm : pipe ? 32 : 16; int64_t streams = 0; - if (p64 || pipe || expert) + if (p64 || pipe || expert || small) for (int64_t e = 0; e < E; ++e) streams += (off[(size_t)(e + 1)] - off[(size_t)e] + jr - 1) / jr; else @@ -15249,6 +15250,7 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ p64 ? fmt("P64 BM%lld BN%d K%d", (long long)pbm, pwide ? 128 : 64, K > 256 && !pwide ? 256 : 128) + (K <= 256 ? " x4, A resident" : "") + (pwide ? ", LDS out" : "") + : small ? fmt("small-M K%d x%d tiles", K <= 256 ? 256 : 512, K <= 256 ? 4 : 1) : expert ? fmt("expert-major K%d x%d tiles", K <= 256 ? 128 : 256, K <= 256 || (f8 && Tr < 128) ? 4 : 1) : pipe ? std::string("GLM prefill form, jobs of 32 rows") @@ -26495,6 +26497,12 @@ static void device_phase(const Plugin& pl) { mx_experts_check(pl, m, shape % 2 ? 2 : 1, false, shape == 2 ? "sorted" : "token", shape, true, 288, 8); } + // At GLM's TP8 slices the small-M form for gate_up to 384 routed rows and down to 32, + // the expert-major form for down above, with dropped slots. + for (int m : { 1, 3, 4, 6, 8, 12, 48 }) { + mx_experts_check(pl, m, 2, m % 2 == 0, "token", 3, false, 288, 8, true); + mx_experts_check(pl, m, 1, m % 2 != 0, "sorted", 4, m == 3, 288, 8, true); + } // At GLM's TP8 slices the expert-major form to its bound (gate_up 768 rows, down below // P64's 5760), then P64 by its rule: gate_up BM32 BN64 K256 from 769 rows, BM64 BN64 K256 // from 12288 and BM64 BN128 K128 with the LDS output from 24576; down BM32 BN64 K128 x4 diff --git a/tests/r4d_emu/test_moemx.cpp b/tests/r4d_emu/test_moemx.cpp index 63f461b2..a76f4865 100644 --- a/tests/r4d_emu/test_moemx.cpp +++ b/tests/r4d_emu/test_moemx.cpp @@ -7,7 +7,8 @@ * slice the P64 form with streamed A. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, dropped * slots inside runs and past the routed rows, columns an odd expert does not have, a shorter K for * odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes and pointer - * tables. The table decode is also held to the arithmetic one over every code. */ + * tables. At GLM's TP8 slices below P64 the small-M form, with runs longer than one tile. The + * table decode is also held to the arithmetic one over every code. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -201,6 +202,45 @@ int main() { glm_runs({ 200, 33, 300, 31, 200 }), 20, "(moe_mxfp4_p64_kernel<32, 64, 256, 1, false>)" }, + { "GLM TP8 gate_up, small-M form, four tokens", + 512, + 4096, + 512, + 4096, + 2, + 8, + false, + true, + false, + glm_runs({ 1, 2, 1, 3, 1, 6, 1, 2, 9, 1 }), + 5, + "(moe_mxfp4_small_kernel<512, 1>)" }, + { "GLM TP8 gate_up, small-M form, runs past one tile", + 512, + 4096, + 512, + 4096, + 2, + 8, + false, + true, + true, + glm_runs({ 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }), + 2, + "(moe_mxfp4_small_kernel<512, 1>)" }, + { "GLM TP8 down, small-M form, a run past one tile", + 4096, + 256, + 4096, + 256, + 1, + 8, + true, + true, + true, + glm_runs({ 3, 1, 17, 2, 1, 1, 1 }), + 5, + "(moe_mxfp4_small_kernel<256, 4>)" }, { "GLM TP8 down, P64 BM32 BN64 K128 x4, A resident", 4096, 256, From 4fdc7863323d1d52dd0a63e6f3c76a567cd34a39 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:12 +0200 Subject: [PATCH 133/152] libr4d: moe_gemm_fp8a8_f32scale's small-M form at GLM's MTP gate_up slice -- a draft pass routes one token Every draft pass runs the MTP layer's experts on one token: eight experts, and the expert-major form's four column tiles a block below 128 routed rows left sixteen blocks, each a chain of 64 stages of 256 K. fp8_f32scale_small takes one column tile of the y-th touched expert a block (grid rows min(experts, rows) + 1, as the MXFP4 small-M form), stages of 512 K, unconditional loads masked at the store, LDS-only barriers, and a 128 of K's eight fragment pairs loaded before its WMMA chain; the per-element sequence is the expert-major form's, so are the bytes. The rule takes it at the MTP gate_up slice (288 experts, top 8, 512 x 4096) to 384 routed rows. Down's K of 256 gains nothing from it (within a few percent, a quarter slower at three tokens) and keeps the expert-major form. Measured (r4d_selftest --cold 256 --perfmxf8), expert-major against small-M, us: tokens 1 2 4 8 16 73.6 83.6 118.4 214.0 375.6 36.7 65.8 114.9 203.9 343.9 Byte for byte against the expert-major form at 1 to 16 tokens during the work, and in r4d_emu, whose grouped cases hold both forms at GLM's MTP slices to a host restatement of the sequence. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_fp8_f32scale.hip | 188 ++++++++++++++++++++++++++++++++++ libr4d/r4d_selftest.cpp | 3 +- tests/r4d_emu/test_fp8f32.cpp | 159 +++++++++++++++++++++++++++- 3 files changed, 348 insertions(+), 2 deletions(-) diff --git a/libr4d/r4d_fp8_f32scale.hip b/libr4d/r4d_fp8_f32scale.hip index b961814d..d0776e1d 100644 --- a/libr4d/r4d_fp8_f32scale.hip +++ b/libr4d/r4d_fp8_f32scale.hip @@ -203,6 +203,184 @@ __global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, co } } } +/* The small-M grouped form at GLM's MTP gate_up slice, with fp8_f32scale_experts' per-element + * sequence and so its bytes. A draft pass routes one token to eight experts, and the four column + * tiles a block of the form above leave sixteen blocks, each a chain of 64 stages of 256 K. Here a + * block takes one column tile of the y-th touched expert (the grid has min(experts, rows) + 1 + * rows, as at the MXFP4 small-M form), in stages of 512 K, with loads unconditional from clamped + * addresses and masked at the store, barriers that order LDS only, and a 128 of K's eight fragment + * pairs loaded before its WMMA chain. */ +typedef unsigned f8_g16 __attribute__((ext_vector_type(4), aligned(1))); +__device__ __forceinline__ f8_u4 f8_ldg16(const uint8_t* p) { + return *(const __attribute__((address_space(1))) f8_g16*)p; +} +__device__ __forceinline__ float f8_ldgf(const float* p) { + return *(const __attribute__((address_space(1))) float*)p; +} +template +struct F8Small { + static constexpr int Threads = 128, KB = StageK / 128, P = StageK + 8; + static constexpr int AChunks = StageK / Threads, WChunks = 64 * StageK / 16 / Threads; + f8_u4 a[AChunks], w[WChunks]; + float wsc[KB], sa; + uint32_t ok; +}; +template +__global__ __launch_bounds__(128) void fp8_f32scale_small(const uint8_t* a, const float* as, + const void* w0, const void* s0, + const void* w1, const void* s1, + const int* sorted, const int* offsets, + uint16_t* y, Meta m) { + using St = F8Small; + constexpr int KB = St::KB, P = St::P, Threads = St::Threads; + static_assert(St::AChunks <= 8 && St::WChunks <= 16 && KB <= 4 && 16 * KB <= Threads && + 64 * P >= 4 * 513, + "stage chunks must fit the load mask and the offsets the weight tile"); + __shared__ __align__(16) uint8_t qa[16 * P], wb[64 * P]; + __shared__ float sa[16 * KB]; + __shared__ int source[16]; + __shared__ int pick; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, col0 = blockIdx.x * 64; + if ((int)blockIdx.y == (int)gridDim.y - 1) { + const int r0 = offsets[m.experts]; + for (long i = tid; i < (long)(m.T - r0) * 64; i += Threads) { + const int c = col0 + (int)(i % 64); + if (c < m.N) y[(long)(r0 + i / 64) * m.yr + c] = 0; + } + return; + } + { + // The offsets in the weight tile, whose bytes are free until the first stage. + int* offs = reinterpret_cast(wb); +#pragma unroll + for (int q = 0; q < 5; ++q) { + const int x = tid + q * Threads; + if (x <= m.experts) offs[x] = offsets[x]; + } + lds_barrier(); + if (wave == 0) { + int want = blockIdx.y, found = -1; + for (int base = 0; base < m.experts; base += 32) { + const int x = base + lane; + const bool live = x < m.experts && offs[x + 1] > offs[x]; + const uint32_t mask = __builtin_amdgcn_ballot_w32(live); + const int n = __builtin_popcount(mask); + if (want < n) { + const uint32_t below = mask & ((1u << lane) - 1u); + found = base + __builtin_ctz(__builtin_amdgcn_ballot_w32( + live && __builtin_popcount(below) == want)); + break; + } + want -= n; + } + if (lane == 0) pick = found; + } + lds_barrier(); + } + const int e = pick; + if (e < 0) return; + const int lo = offsets[e], hi = offsets[e + 1]; + const int parity = e & 1; + const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e / 2); + const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e / 2); + const int S = (m.K + StageK - 1) / StageK, rowbase = (lane >> 4) * 8; + for (int r0 = lo; r0 < hi; r0 += 16) { + lds_barrier(); + if (tid < 16) { + const int r = r0 + tid, flat = r < hi ? sorted[r] : -1; + source[tid] = flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1; + } + lds_barrier(); + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = source[rowbase + j] >= 0; + auto load = [&](int s, St& L) { + const int k0 = s * StageK; + uint32_t ok = 0; +#pragma unroll + for (int i = 0; i < St::AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16, + src = source[r]; + const bool v = src >= 0 && k0 + c < m.K; + __builtin_memcpy(&L.a[i], a + (v ? (long)src * m.ar + k0 + c : 0), 16); + ok |= (uint32_t)v << i; + } +#pragma unroll + for (int i = 0; i < St::WChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + const bool v = k0 + c < m.K; + L.w[i] = f8_ldg16(w + (v ? (long)(col0 + r) * m.wr + k0 + c : 0)); + ok |= (uint32_t)v << (8 + i); + } +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + const bool v = k0 + kb * 128 < m.K; + L.wsc[kb] = + f8_ldgf(ws + (v ? (long)(col0 / 128) * m.sr + (k0 + kb * 128) / 128 : 0)); + ok |= (uint32_t)v << (24 + kb); + } + { + const int src = source[(tid / KB) & 15], kb = k0 + (tid % KB) * 128; + const bool v = tid < 16 * KB && src >= 0 && kb < m.K; + L.sa = as[v ? (long)src * m.asr + kb / 128 : 0]; + ok |= (uint32_t)v << 28; + } + L.ok = ok; + }; + auto store = [&](const St& L) { +#pragma unroll + for (int i = 0; i < St::AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + *reinterpret_cast(qa + r * P + c) = + (L.ok >> i) & 1u ? L.a[i] : f8_u4{ 0, 0, 0, 0 }; + } +#pragma unroll + for (int i = 0; i < St::WChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + *reinterpret_cast(wb + r * P + c) = + (L.ok >> (8 + i)) & 1u ? L.w[i] : f8_u4{ 0, 0, 0, 0 }; + } + if (tid < 16 * KB) sa[(tid % KB) * 16 + tid / KB] = (L.ok >> 28) & 1u ? L.sa : 0.f; + }; + auto acc = r4d_fp8::acc_zero(); + St L; + load(0, L); + for (int s = 0; s < S; ++s) { + store(L); + float wsc[KB]; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) wsc[kb] = (L.ok >> (24 + kb)) & 1u ? L.wsc[kb] : 0.f; + lds_barrier(); + if (s + 1 < S) load(s + 1, L); + const int k0 = s * StageK; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= m.K) break; + r4d_fp8::i2v fa[8], fb[8]; +#pragma unroll + for (int t = 0; t < 8; ++t) { + fa[t] = r4d_fp8::frag(qa, 0, kb * 128 + 16 * t, lane); + fb[t] = r4d_fp8::frag(wb, wave * 16, kb * 128 + 16 * t, lane); + } + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int t = 0; t < 8; ++t) raw = r4d_fp8::mma(fa[t], fb[t], raw); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float scale = rv[j] ? sa[kb * 16 + rowbase + j] * wsc[kb] : 0; + acc[j] += raw[j] * scale; + } + } + lds_barrier(); + } + const int c = col0 + wave * 16 + (lane & 15); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = r0 + rowbase + j; + if (r < hi) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]); + } + } +} // Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same // eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's // row segment, which the legacy form copies through LDS unchanged), then acc += raw * (a_scale * @@ -504,6 +682,16 @@ int body(const RadArgs* a, RadStream stream, bool grouped) { m.sstep[0] = ws.stride[0] * 4; m.sstep[1] = so.stride[0] * 4; if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE; + /* The small-M form at the MTP layer's gate_up slice up to 384 routed rows: a draft pass routes + * one token, a verify pass a few. Measured there (perfmxf8, cold), expert-major against + * small-M at 1, 2, 4, 8 and 16 tokens: 73.6/36.7, 83.6/65.8, 118.4/114.9, 214.0/203.9 and + * 375.6/343.9 us. Down's K of 256 gains nothing from it (within a few percent, a quarter slower + * at three tokens). */ + if (m.experts == 288 && m.topk == 8 && N == 512 && K == 4096 && m.T <= 384) + return R4D_EMIT(stream, fp8_f32scale_small<512>, + dim3(N / 64, (m.T < m.experts ? m.T : m.experts) + 1), dim3(128), 0, + (const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data, + so.data, (const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m); /* The expert-major form at every routed-row count. Measured at GLM's TP8 slices: a long K * (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and under 128 routed rows * four tiles a block on top; at down's K of 256 every variant reads within a few percent of diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index af2e207c..1796b119 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -15235,7 +15235,8 @@ static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_ const int64_t pbm = pwide || (K > 256 && Tr >= 12288) ? 64 : 32; const bool p64 = glm && Tr >= (P.srt ? 5760 : 769) && (Tr + pbm - 1) / pbm + E <= 65535; - const bool small = glm && Tr <= (P.srt ? 32 : 384); + const bool small = (glm && Tr <= (P.srt ? 32 : 384)) || + (f8 && E == 288 && top_k == 8 && !P.srt && Tr <= 384); const bool expert = !p64 && !small && (f8 || Tr <= (glm ? (P.srt ? 6143 : 768) : 511)); const bool pipe = !p64 && !small && !expert && glm; const int64_t jr = p64 ? pbm : pipe ? 32 : 16; diff --git a/tests/r4d_emu/test_fp8f32.cpp b/tests/r4d_emu/test_fp8f32.cpp index a8eadeec..ed13c58a 100644 --- a/tests/r4d_emu/test_fp8f32.cpp +++ b/tests/r4d_emu/test_fp8f32.cpp @@ -4,7 +4,8 @@ * which serves an activation pitch off 16 bytes, bit for bit: the same fragments, the same mma * chain per 128-K block and the same fold order. Ragged row counts, pitched rows and a K that * leaves the decode form's last wave group partly idle are covered; the output's pitch padding - * stays untouched. */ + * stays untouched. The grouped row at GLM's MTP slices is held to a host restatement + * (grouped_cases). */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -29,6 +30,161 @@ static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t l return t; } +/* The grouped row at GLM's MTP slices (288 experts, top 8) below 384 routed rows -- the small-M + * form at gate_up, the expert-major form at down -- against a host restatement of the + * per-element sequence: per 128 of K in order, the + * 128-product sum of the emulated WMMA chain from zero, folded as raw * (activation scale * + * weight scale) and added. Dropped slots inside runs and past the routed rows, runs longer than an + * A tile, token and sorted rows, pointer tables over three slices a class. */ +static int grouped_cases(int& cases) { + struct G { + const char* name; + int N, K; + bool sorted_a; + std::vector live; + int tail; + const char* kernel; + }; + const G all[] = { + { "MTP gate_up, one token", 512, 4096, false, { 1, 1, 1, 1, 1, 1, 1, 1 }, 0, + "fp8_f32scale_small<512>" }, + { "MTP gate_up, runs past one tile", 512, 4096, false, { 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }, 2, + "fp8_f32scale_small<512>" }, + { "MTP down, six tokens", 4096, 256, true, { 3, 1, 10, 2, 1, 5, 1, 1, 17, 4 }, + 3, "(fp8_f32scale_experts<128, 4>)" }, + }; + static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 }; + int fails = 0; + std::mt19937 rng(77); + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution oct(-6.f, 6.f); + for (const G& g : all) { + const int E = 288, top = 8, N = g.N, K = g.K, kb = K / 128; + std::vector runs(E, 0); + for (size_t i = 0; i < g.live.size(); ++i) runs[at[i]] = g.live[i]; + int routed = 0; + for (int r : runs) routed += r; + const int T = (routed + g.tail + top - 1) / top * top; + const int Arows = g.sorted_a ? T : T / top, ap = K + 16, yp = N + 8; + std::vector a((size_t)Arows * ap); + for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng)); + std::vector as((size_t)Arows * kb); + for (auto& v : as) v = std::exp2(oct(rng)); + std::vector offsets(E + 1, 0), sorted(T, -1), owner(T, -1); + for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + runs[e]; + for (int e = 0; e < E; ++e) + for (int r = offsets[e]; r < offsets[e + 1]; ++r) { + owner[r] = e; + sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T); + } + std::vector w[2]; + std::vector s[2]; + std::vector wt[2], st[2]; + for (int q = 0; q < 2; ++q) { + w[q].resize((size_t)3 * N * K); + s[q].resize((size_t)3 * (N / 128) * kb); + for (auto& v : w[q]) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f); + for (auto& v : s[q]) v = std::exp2(oct(rng)) * 0.01f; + for (int x = 0; x < E / 2; ++x) { + wt[q].push_back(w[q].data() + (size_t)(x % 3) * N * K); + st[q].push_back(s[q].data() + (size_t)(x % 3) * (N / 128) * kb); + } + } + std::vector ref((size_t)T * yp, 0x7777), got((size_t)T * yp, 0x7777); + for (int r = 0; r < T; ++r) + for (int n = 0; n < N; ++n) { + uint16_t& out = ref[(size_t)r * yp + n]; + out = 0; + if (owner[r] < 0) continue; + const int e = owner[r], q = e & 1; + const bool rv = sorted[r] >= 0; + const int ar = !rv ? -1 : g.sorted_a ? r : sorted[r] / top; + const uint8_t* wr = (const uint8_t*)wt[q][(size_t)(e / 2)] + (size_t)n * K; + const float* sr = (const float*)st[q][(size_t)(e / 2)] + (size_t)(n / 128) * kb; + float acc = 0.f; + for (int b = 0; b < kb; ++b) { + float raw = 0.f; + if (rv) + for (int k = b * 128; k < b * 128 + 128; ++k) + raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + k]) * + rad_fp8e4m3_to_f32(wr[k]); + const float scale = rv ? as[(size_t)ar * kb + b] * sr[b] : 0.f; + const float t = raw * scale; + acc = acc + t; + } + uint32_t u; + std::memcpy(&u, &acc, 4); + out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); + } + auto ten3 = [](const void* const* tab, uint32_t dt, int64_t n0, int64_t n1, int64_t n2) { + RadTensor t{}; + t.data = (void*)tab; + t.dtype = dt; + t.rank = 3; + t.shape[0] = n0; + t.shape[1] = n1; + t.shape[2] = n2; + t.stride[0] = 0; + t.stride[1] = n2; + t.stride[2] = 1; + return t; + }; + RadTensor t[9] = { mat(a.data(), RAD_F8E4M3, Arows, K, ap), + mat(as.data(), RAD_F32, Arows, kb, kb), + ten3(wt[0].data(), RAD_F8E4M3, E / 2, N, K), + ten3(st[0].data(), RAD_F32, E / 2, N / 128, kb), + RadTensor{}, + RadTensor{}, + ten3(wt[1].data(), RAD_F8E4M3, E / 2, N, K), + ten3(st[1].data(), RAD_F32, E / 2, N / 128, kb), + mat(got.data(), RAD_BF16, T, N, yp) }; + t[4].data = sorted.data(); + t[4].dtype = RAD_I32; + t[4].rank = 1; + t[4].shape[0] = T; + t[4].stride[0] = 1; + t[5].data = offsets.data(); + t[5].dtype = RAD_I32; + t[5].rank = 1; + t[5].shape[0] = E + 1; + t[5].stride[0] = 1; + RadParam p[10]{}; + p[0] = { "M", RAD_P_INT, T / top }; + p[1] = { "N", RAD_P_INT, N }; + p[2] = { "K", RAD_P_INT, K }; + p[3] = { "N_odd", RAD_P_INT, N }; + p[4] = { "K_odd", RAD_P_INT, K }; + p[5] = { "n_expert", RAD_P_INT, E }; + p[6] = { "top_k", RAD_P_INT, top }; + p[7] = { "group", RAD_P_INT, 128 }; + p[8].key = "a_order"; + p[8].kind = RAD_P_STR; + p[8].sval = g.sorted_a ? "sorted" : "token"; + p[9].key = "dtype"; + p[9].kind = RAD_P_STR; + p[9].sval = "fp8a8f32"; + RadArgs ar{}; + ar.t = t; + ar.n_t = 9; + ar.p = p; + ar.n_p = 10; + emu_last_kernel = ""; + ++cases; + const int rc = r4d_rad_moe_fp8_f32scale(&ar, nullptr); + size_t i = 0; + while (i < got.size() && got[i] == ref[i]) ++i; + int live = 0; + for (uint16_t v : ref) live += v != 0 && v != 0x7777; + if (rc != RAD_OK || std::strcmp(emu_last_kernel, g.kernel) || i != got.size() || + live < routed * N / 2) { + std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu of %zu, %d live\n", + g.name, T, emu_last_kernel, g.kernel, rc, i, got.size(), live); + ++fails; + } + } + return fails; +} + int main() { std::mt19937 rng(31); std::normal_distribution nd(0.f, 1.f); @@ -113,6 +269,7 @@ int main() { ++fails; } } + fails += grouped_cases(cases); std::printf("%d case(s), %d failure(s)\n", cases, fails); return fails ? 1 : 0; } From 1ff9abe2baa0a737ee0504ef415ae793364c22b7 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:12 +0200 Subject: [PATCH 134/152] libr4d: gemm_nt_f32 keeps steps of k in flight below 64 rows -- GLM's router read its weights at 150 GB/s The router (288 x 4096 f32, every MoE layer, the MTP layer in every draft pass) and the index head gates (32 x 4096) took 26 to 36 us a call at decode's few rows: a lane loaded one weight a step and fed it straight to its FMA, so a wave had one request in flight. The tile kernel now loads U steps of k before their FMAs; each lane keeps its ascending fmaf chain and the butterfly, so every form gives the same bytes, and U = 1 is the tile form as it was. Below 64 rows the rule takes 2 x 2 tiles with 16 steps, at the router's width from 17 rows 8 x 1 with 8; the wave-per-output kernel for one row goes. Measured (r4d_selftest --cold 256 --perff32, K 4096), us: rows 1 4 8 16 24 48 N 288, before 28.1 36.0 36.3 41.9 45.4 47.9 after 14.4 14.5 15.0 19.1 21.6 35.5 N 32, before 27.3 33.3 32.9 36.4 36.2 36.1 after 9.8 9.8 9.9 9.9 10.0 10.2 r4d_selftest's byte comparison with the host arithmetic passes at every form tried, r4d_emu gains three shapes with K short of and past whole groups of steps. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d_glm.hip | 72 +++++++++++++++++++++----------------- tests/r4d_emu/test_f32.cpp | 15 ++++---- 2 files changed, 48 insertions(+), 39 deletions(-) diff --git a/libr4d/r4d_glm.hip b/libr4d/r4d_glm.hip index 6cd8560c..88e81e90 100644 --- a/libr4d/r4d_glm.hip +++ b/libr4d/r4d_glm.hip @@ -7,23 +7,13 @@ #include namespace { -__global__ void gemm_nt_f32_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, - long yp, int n, int k) { - const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), r = blockIdx.y; - if (col >= n) return; - float sum = 0; - for (int j = lane; j < k; j += 32) - sum = fmaf(bf16_to_f32(x[(long)r * xp + j]), w[(long)col * wp + j], sum); -#pragma unroll - for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32); - if (!lane) y[(long)r * yp + col] = sum; -} - // One wave computes R rows by C columns, so each loaded weight serves R rows and each input -// C columns. Every output keeps gemm_nt_f32_kernel's arithmetic: lane l accumulates -// k = l, l+32, ... in ascending order with fmaf, then the same xor butterfly. Tail rows and +// C columns. Every output has the same arithmetic: lane l accumulates k = l, l+32, ... in +// ascending order with fmaf, then the xor butterfly over 16, 8, 4, 2, 1. A lane loads U steps of +// k before their FMAs: at a decode pass's few rows a wave streams its weight row with no other +// work to hide the load behind, and one step in flight left the router at 150 GB/s. Tail rows and // columns read a clamped valid address and are never stored. -template +template __global__ void __launch_bounds__(128) gemm_nt_f32_tile_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, long yp, int m, int n, int k) { @@ -41,15 +31,33 @@ __global__ void __launch_bounds__(128) for (int q = 0; q < R; ++q) #pragma unroll for (int c = 0; c < C; ++c) sum[q][c] = 0; - for (int j = lane; j < k; j += 32) { - float weight[C]; + int j = lane; + for (; j + 32 * (U - 1) < k; j += 32 * U) { + float weight[U][C]; + uint16_t in[U][R]; #pragma unroll - for (int c = 0; c < C; ++c) weight[c] = wc[c][j]; + for (int u = 0; u < U; ++u) +#pragma unroll + for (int c = 0; c < C; ++c) weight[u][c] = wc[c][j + 32 * u]; +#pragma unroll + for (int u = 0; u < U; ++u) +#pragma unroll + for (int q = 0; q < R; ++q) in[u][q] = xr[q][j + 32 * u]; +#pragma unroll + for (int u = 0; u < U; ++u) +#pragma unroll + for (int q = 0; q < R; ++q) { + const float v = bf16_to_f32(in[u][q]); +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, weight[u][c], sum[q][c]); + } + } + for (; j < k; j += 32) { #pragma unroll for (int q = 0; q < R; ++q) { const float v = bf16_to_f32(xr[q][j]); #pragma unroll - for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, weight[c], sum[q][c]); + for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, wc[c][j], sum[q][c]); } } #pragma unroll @@ -68,11 +76,11 @@ __global__ void __launch_bounds__(128) if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c]; } -template +template int gemm_f32_tile(RadStream stream, const RadTensor& x, const RadTensor& w, const RadTensor& y, long n, long k) { const long m = x.shape[0]; - return R4D_EMIT(stream, (gemm_nt_f32_tile_kernel), + return R4D_EMIT(stream, (gemm_nt_f32_tile_kernel), dim3((unsigned)((n + 4 * C - 1) / (4 * C)), (unsigned)((m + R - 1) / R)), dim3(128), 0, (const uint16_t*)x.data, (const float*)w.data, (float*)y.data, x.stride[0], w.stride[0], y.stride[0], (int)m, (int)n, (int)k); @@ -89,19 +97,19 @@ int gemm_f32_body(const RadArgs* a, RadStream stream) { w.stride[1] != 1 || y.stride[1] != 1 || x.stride[0] < k || w.stride[0] < k || y.stride[0] < n) return RAD_E_SHAPE; - /* The tile form, rows x columns per wave, by M; all forms are byte-identical, so the choice is - * speed only. Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096. - * 16x4 gains 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every - * width. A projection of a few columns has too few waves for wide tiles at any M. */ + /* The tile form, rows x columns per wave and steps of k in flight, by M; all forms are + * byte-identical, so the choice is speed only. Measured on gfx1201 (r4d_selftest --perff32, + * cold) at N 4/32/36/288, K 4096: 16x4 gains 3-5 % at N 288/32 above 64 rows but loses 16 % at + * N 36; 8x4 holds at every width. Below 64 rows the steps in flight decide: at N 288 one step + * a lane took 28.1 / 36.0 / 36.3 / 41.9 / 45.4 / 47.9 us at 1 / 4 / 8 / 16 / 24 / 48 rows, + * 2x2 with 16 steps 14.4 / 14.5 / 15.0 / 19.1 us to 16 rows and 8x1 with 8 steps 21.6 / 35.5 + * us at 24 / 48; at N 32 2x2 with 16 steps 9.8 to 10.2 us at every count below 64, where one + * step took 27.3 to 36.4. + * A projection of a few columns has too few waves for wide tiles at any M. */ const long rows = x.shape[0]; if (n <= 8) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k); - if (rows <= 1) - return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0, - (const uint16_t*)x.data, (const float*)w.data, (float*)y.data, - x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k); - if (rows <= 2) return gemm_f32_tile<2, 1>(stream, x, w, y, n, k); - if (rows < 16) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k); - if (rows < 64) return gemm_f32_tile<4, 4>(stream, x, w, y, n, k); + if (rows <= 16 || (rows < 64 && n < 128)) return gemm_f32_tile<2, 2, 16>(stream, x, w, y, n, k); + if (rows < 64) return gemm_f32_tile<8, 1, 8>(stream, x, w, y, n, k); return gemm_f32_tile<8, 4>(stream, x, w, y, n, k); } // router_sigmoid_topk in one wave per row: p = sigmoid(logit), the top_k largest ranks p + bias diff --git a/tests/r4d_emu/test_f32.cpp b/tests/r4d_emu/test_f32.cpp index b67b6533..060d3fd2 100644 --- a/tests/r4d_emu/test_f32.cpp +++ b/tests/r4d_emu/test_f32.cpp @@ -1,8 +1,8 @@ /* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. The form the launcher picks - * at each shape (one wave an output at one row, else a tile of rows x columns a wave, by M; the - * shapes reach every one) must match the arithmetic written out here bit for bit: lane l folds - * k = l, l+32, ... with fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns - * and the pitch's padding stay untouched. + * at each shape (a tile of rows x columns a wave with its steps of k in flight, by M and N; the + * shapes reach every one, with K past and short of whole groups of steps) must match the + * arithmetic written out here bit for bit: lane l folds k = l, l+32, ... with fmaf, then the xor + * butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding stay untouched. * * router_sigmoid_topk from the same unit: the wave-per-row select must match a serial scan written * out here bit for bit, on random and on tied ranks, with the outputs' pitch padding untouched. */ @@ -147,9 +147,10 @@ int main() { int M, N, K; }; // One wave an output (M 1), the 2x1, 4x1 (M under 16 or N up to 8), 4x4 and 8x4 tiles. - const Shape shapes[] = { { 1, 288, 512 }, { 2, 288, 129 }, { 3, 36, 129 }, - { 8, 288, 129 }, { 33, 32, 512 }, { 70, 36, 129 }, - { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } }; + const Shape shapes[] = { { 1, 288, 512 }, { 2, 288, 129 }, { 3, 36, 129 }, + { 8, 288, 129 }, { 33, 32, 512 }, { 70, 36, 129 }, + { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 }, + { 16, 288, 1056 }, { 24, 288, 1040 }, { 40, 36, 1024 } }; int fails = 0, cases = 0; for (const Shape& sh : shapes) { const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3; From f909576d09dcb5f5aaed9dda890ead274359077b Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:12 +0200 Subject: [PATCH 135/152] libr4d: logits_gemm_bf16_cols -- the bf16 head without a block per column at n_embd 4096 logits_gemm_bf16 runs a 256-thread block per vocabulary column. At n_embd 4096 a thread makes two 16-byte weight loads before the block-wide sum, and each row widens both operands for its own product: GLM-5.3's TP8 slice (19360 columns) took 303 us at six rows and 1133 at 24, where a verify pass of eight streams lands, against 235 at one. The new row runs a wave per four columns: lane l takes, in turn, threads 32q + l of the old block for q = 0..7 -- the same 8-wide k chunks summed from 0 and added in k order, the same lane butterfly per q, the eight wave sums added in q order from 0 -- so each column gets the old row's bytes. bf16 widens to f32 exactly, so each weight is widened once for every row and each activation once for every column. It outranks the block row at n_embd 4096 only; the block row is unchanged and serves every other width. Measured at the TP8 slice (r4d_selftest --perflogits), us: rows 1 6 8 16 24 48 logits_gemm_bf16 239.1 303.2 378.2 741.4 1133.2 2354.5 ..._cols 235.5 247.5 250.4 404.5 635.6 1220.1 Two columns a wave and 16 rows a pass measured slower. r4d_selftest compares both rows byte for byte from one row to past one 8-row chunk, at a vocabulary off the column step and a pitched activation with a NaN and a signed zero. Co-Authored-By: Claude Opus 5.5 --- libr4d/r4d.h | 3 + libr4d/r4d_model_bf16.hip | 136 ++++++++++++++++++++++++++++++++++++++ libr4d/r4d_plugin.h | 4 ++ libr4d/r4d_rows.cpp | 11 +++ libr4d/r4d_selftest.cpp | 91 +++++++++++++++++++++++++ 5 files changed, 245 insertions(+) diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 3a7f50bb..08552a34 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -965,6 +965,9 @@ int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, // that compares neighbouring probabilities. K must be a multiple of 8. int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N, int a_ld, int c_ld, long stream); +// The same bytes from a wave per four vocabulary columns; K must be 4096. +int r4d_logits_gemm_bf16_cols(long a, long w, long c, int M, int K, int N, int a_ld, int c_ld, + long stream); // Scatter into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim]: K at [.., d], V at // [.., head_dim + d], slot decomposing as block = slot / block_size, offset = slot % block_size. int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads, diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index ca6b653e..74355602 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -1240,6 +1240,99 @@ __global__ __launch_bounds__(kThreads) void logits_gemm_kernel( } } + +// The same projection with each wave taking four whole vocabulary columns, for a head where the +// 256-thread block per column is the cost: at n_embd 4096 a thread of that kernel makes two 16-byte +// weight loads before the block-wide sum, and each row widens both operands for its own product. +// +// BYTE-IDENTICAL to logits_gemm_kernel: lane l of a wave runs, in turn, threads 32q + l of that +// kernel's block for q = 0..7 -- the same 8-wide k chunks, each summed from 0 and added to the +// thread's accumulator in k order -- reduces each q with the same lane butterfly, and adds the +// eight wave sums in q order from 0. Only where the threads run changes, and bf16 widens to f32 +// exactly, so each weight is widened once for every row and each activation once for every +// column. A q's loads (four columns and up to kLgRows rows, two chunks each) are issued before its +// arithmetic. +constexpr uint32_t kLgCols = 4, kLgKi = 2; // columns a wave; 2048-wide chunks of n_embd 4096 +__global__ __launch_bounds__(kThreads) void logits_gemm_cols_kernel( + const uint16_t* __restrict__ a, const uint16_t* __restrict__ w, float* __restrict__ c, + uint32_t M, uint32_t N, uint32_t a_ld, uint32_t c_ld) { + constexpr uint32_t C = kLgCols, KI = kLgKi, K = KI * kThreads * kLgVec, V = KI * kLgVec; + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + const uint32_t j0 = (blockIdx.x * kWaves + wave) * C; + if (j0 >= N) return; + for (uint32_t r0 = 0; r0 < M; r0 += kLgRows) { + const uint32_t nr = (M - r0) < kLgRows ? (M - r0) : kLgRows; + float v[C][kLgRows]; +#pragma unroll + for (uint32_t x = 0; x < C; ++x) +#pragma unroll + for (uint32_t i = 0; i < kLgRows; ++i) v[x][i] = 0.0f; +#pragma unroll 1 + for (uint32_t q = 0; q < kWaves; ++q) { + const uint32_t k0 = (q * kWave + lane) * kLgVec; + uint4 wv[C][KI], av[kLgRows][KI]; +#pragma unroll + for (uint32_t x = 0; x < C; ++x) { + const uint16_t* wr = w + (size_t)(j0 + x < N ? j0 + x : N - 1) * K + k0; +#pragma unroll + for (uint32_t t = 0; t < KI; ++t) + wv[x][t] = *(const uint4*)(wr + t * kThreads * kLgVec); + } +#pragma unroll + for (uint32_t i = 0; i < kLgRows; ++i) { + if (i >= nr) break; + const uint16_t* ar = a + (size_t)(r0 + i) * a_ld + k0; +#pragma unroll + for (uint32_t t = 0; t < KI; ++t) + av[i][t] = *(const uint4*)(ar + t * kThreads * kLgVec); + } + float wf[C][V]; +#pragma unroll + for (uint32_t x = 0; x < C; ++x) +#pragma unroll + for (uint32_t t = 0; t < KI; ++t) { + const uint32_t ww[4] = { wv[x][t].x, wv[x][t].y, wv[x][t].z, wv[x][t].w }; +#pragma unroll + for (uint32_t p = 0; p < kLgVec; ++p) + wf[x][t * kLgVec + p] = bf16_to_f32((uint16_t)(ww[p / 2] >> (16 * (p & 1)))); + } +#pragma unroll + for (uint32_t i = 0; i < kLgRows; ++i) { + if (i >= nr) break; + float af[V]; +#pragma unroll + for (uint32_t t = 0; t < KI; ++t) { + const uint32_t aw[4] = { av[i][t].x, av[i][t].y, av[i][t].z, av[i][t].w }; +#pragma unroll + for (uint32_t p = 0; p < kLgVec; ++p) + af[t * kLgVec + p] = bf16_to_f32((uint16_t)(aw[p / 2] >> (16 * (p & 1)))); + } +#pragma unroll + for (uint32_t x = 0; x < C; ++x) { + float acc = 0.0f; +#pragma unroll + for (uint32_t t = 0; t < KI; ++t) { + float s = 0.0f; +#pragma unroll + for (uint32_t p = 0; p < kLgVec; ++p) + s += af[t * kLgVec + p] * wf[x][t * kLgVec + p]; + acc += s; + } + v[x][i] += r4d_wave_sum(acc); + } + } + } +#pragma unroll + for (uint32_t x = 0; x < C; ++x) { + float out = 0.0f; +#pragma unroll + for (uint32_t i = 0; i < kLgRows; ++i) + if (i == lane) out = v[x][i]; + if (lane < nr && j0 + x < N) c[(size_t)(r0 + lane) * c_ld + j0 + x] = out; + } + } +} + } // namespace // a [M][K] bf16, `a_ld` elements a row (0 = K) @@ -1258,6 +1351,21 @@ extern "C" int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N, return hipGetLastError() == hipSuccess ? 0 : -4; } +// The column form; n_embd must be 4096 and an activation row whole 16 bytes. +extern "C" int r4d_logits_gemm_bf16_cols(long a, long w, long c, int M, int K, int N, int a_ld, + int c_ld, long stream) { + if (!a || !w || !c) return -1; + if (M <= 0 || N <= 0) return -2; + if (!a_ld) a_ld = K; + if (!c_ld) c_ld = N; + if (K != (int)(kLgKi * kThreads * kLgVec) || a_ld % (int)kLgVec) return -3; + const uint32_t per = kWaves * kLgCols; + hipLaunchKernelGGL(logits_gemm_cols_kernel, dim3(((uint32_t)N + per - 1) / per), dim3(kThreads), + 0, (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)w, (float*)c, + (uint32_t)M, (uint32_t)N, (uint32_t)a_ld, (uint32_t)c_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + // ============================================================== the plugin ABI entry points // // Unpacking RadArgs and deriving row pitches belongs to the kernel library (libr4d/r4d_args.h). @@ -2148,3 +2256,31 @@ extern "C" int r4d_rad_logits_gemm(const RadArgs* a, RadStream s) { (int)n_vocab, (int)x_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; } + +/* logits_gemm_bf16_cols: the operands and checks above, then the column form at the n_embd of its + * row's constraint, with the activation's rows whole 16 bytes. */ +extern "C" int r4d_rad_logits_gemm_cols(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, LG_X); + const RadTensor* w = r4d_opt(a, LG_W); + const RadTensor* y = r4d_opt(a, LG_Y); + if (!x || !w || !y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(x)); + R4D_NEED(dt_bf16(w)); + if (y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE); + const long long n_vocab = r4d_geti_or(a, "n_vocab", r4d_dim(w, 0)); + const long long n_embd = r4d_geti_or(a, "n_embd", r4d_dim(w, 1)); + if (n_vocab <= 0 || n_embd != 4096) return R4D_NO(RAD_E_SHAPE); + if (w->rank != 2 || w->shape[0] != n_vocab || w->shape[1] != n_embd) + return R4D_NO(RAD_E_SHAPE); + long long M = 0, My = 0; + const long long x_ld = r4d_rows_pitch(x, n_embd, &M); + const long long y_ld = r4d_rows_pitch(y, n_vocab, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); + if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || x_ld % 8) + return R4D_NO(RAD_E_ALIGN); + return r4d_logits_gemm_bf16_cols(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n_embd, + (int)n_vocab, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index d9d09a3f..c3e4c7aa 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -67,6 +67,9 @@ enum { * these rows' layout hooks refuse a bf16 head, and the bf16 row has no hook for a scaled * one. */ R4D_PRIO_LOGITS_FP8 = 60, + /* The bf16 head's column form, above the block-per-column row whose bytes it gives, at the + * n_embd it is built for. */ + R4D_PRIO_LOGITS_COLS = 55, /* Runtime LoRA: the tiled rows serve a subset of the scalar rows' dtypes at every M, so they * must outrank them to be reached; the scalar rows keep f16 / f32 activations (no exact WMMA) @@ -718,6 +721,7 @@ int r4d_rad_kv_store_fp8 (const RadArgs*, RadStream); int r4d_rad_kv_store_fp8v4 (const RadArgs*, RadStream); int r4d_rad_kv_store_k6v4 (const RadArgs*, RadStream); int r4d_rad_logits_gemm (const RadArgs*, RadStream); +int r4d_rad_logits_gemm_cols(const RadArgs*, RadStream); /* -- the decomposed sampler chain (r4d_sample_stages_f32.hip) -- * diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 04afa4b6..746340cb 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4995,6 +4995,7 @@ static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 4 static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) }; /* The activation width the column loop vectorises over; M is unbounded -- the kernel chunks rows. */ static const RadConstraint cLogitsGemm[] = { C_DIV("n_embd", 8), C_IN("dtype", "bf16") }; +static const RadConstraint cLogitsGemmCols[] = { C_EQ("n_embd", 4096), C_IN("dtype", "bf16") }; /* The fp8 head: n_embd on the 128 scale block, and no cap on M. The row relayouts the weight, so * it must cover the whole range; above a cap the bf16 projection would read the E4M3 codes as bf16. * The kernel chunks above 32, and core/build/rad_builder.cpp refuses a capped arrangement. @@ -5684,6 +5685,16 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_logits_gemm, nullptr, nullptr, nullptr, r4d_shape_logits_gemm }, +{ "logits_gemm_bf16_cols", "logits_gemm", "vocab", + "logits_gemm_bf16 with a wave per four vocabulary columns: lane l runs that row's threads 32q + l " + "in turn, so each column keeps its k chunks, lane butterfly and wave order", + "any M and any vocabulary; n_embd 4096 exactly; the activation's row pitch whole 16 bytes", + "bf16 x and lm_head, F32 LOGITS OUT, fp32 accumulate. BYTE-IDENTICAL to logits_gemm_bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_LOGITS_COLS, + ROW(cLogitsGemmCols), NOTUNE, + nullptr, nullptr, r4d_rad_logits_gemm_cols, nullptr, nullptr, nullptr, + r4d_shape_logits_gemm }, + { "logits_gemm_fp8", "logits_gemm", "vocab", "the lm_head projection over an fp8 head: C[M, n_vocab] f32 = x[M, n_embd] @ dequant(W)^T, " "one wave a vocabulary row, the row's own scales in its tail", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 1796b119..4cd9b8a3 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -14994,6 +14994,72 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co dlclose(ref); } +/* logits_gemm_bf16_cols against logits_gemm_bf16 on the same operands: the column form must give + * the block-per-column row's bytes. M from one row to past the 8-row chunk, a vocabulary not a + * multiple of the four columns a wave takes, an activation row pitch past n_embd, and a NaN and + * signed zeros in the activation, which the per-thread sums must carry the same way. With `iters` + * both rows are also timed at GLM-5.3's TP8 slice, where the weight is past the last-level cache + * and every launch reads it from memory. */ +static void logits_cols_check(const Plugin& pl, int64_t M, int64_t N, int iters = 0) { + const RadKernelInfo* ref = find(pl, "logits_gemm_bf16"); + const RadKernelInfo* cols = find(pl, "logits_gemm_bf16_cols"); + if (!ref || !cols) { + ok("logits_gemm_bf16_cols", false, "row absent"); + return; + } + const int64_t K = 4096, xp = K + 8; + std::vector hx((size_t)(M * xp), 0), hw((size_t)(N * K)); + for (int64_t r = 0; r < M; ++r) + for (int64_t k = 0; k < K; ++k) + hx[(size_t)(r * xp + k)] = st_rand_bf16((uint32_t)(r * K + k)); + hx[3] = 0x8000; + if (M > 1) hx[(size_t)(xp + 7)] = 0x7fc0; + for (size_t i = 0; i < hw.size(); ++i) hw[i] = st_rand_bf16((uint32_t)i + 0x51ed27u); + void* dx = dalloc(hx.size() * 2); + void* dw = dalloc(hw.size() * 2); + void* dy = dalloc((size_t)(M * N) * 4); + if (!dx || !dw || !dy) { + ok("logits_gemm_bf16_cols allocation", false); + dfree_all(); + return; + } + st_memcpy(dx, hx.data(), hx.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dw, hw.data(), hw.size() * 2, hipMemcpyHostToDevice); + std::vector ts = { T(dx, RAD_BF16, { M, K }), T(dw, RAD_BF16, { N, K }), + T(dy, RAD_F32, { M, N }) }; + ts[0].stride[0] = xp; + std::vector ps = { PI("M", M), PI("n_vocab", N), PI("n_embd", K), + PS("dtype", "bf16") }; + std::vector want((size_t)(M * N) * 4), got(want.size()); + st_memset(dy, 0xa5, want.size()); + run_case(ref, ts, ps); + st_memcpy(want.data(), dy, want.size(), hipMemcpyDeviceToHost); + st_memset(dy, 0x5a, got.size()); + run_case(cols, ts, ps); + st_memcpy(got.data(), dy, got.size(), hipMemcpyDeviceToHost); + ok(fmt("logits_gemm_bf16_cols M=%lld N=%lld: the bytes of logits_gemm_bf16", (long long)M, + (long long)N) + .c_str(), + got == want); + if (iters > 0) { + 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; + const double bytes = (double)(N * K * 2); + for (const RadKernelInfo* r : { ref, cols }) { + for (int i = 0; i < 3; ++i) r->launch(&a, nullptr); + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + std::printf(" %-22s M=%-3lld %9.1f us %6.1f GB/s of weight\n", r->name, (long long)M, + us, bytes / (us * 1e3)); + } + } + dfree_all(); +} + /* The MXFP4 expert GEMM at GLM's TP8 slices (mx_experts_check's model shapes 3 and 4): gate_up * 512 x 4096 over token rows (parts 2), down 4096 x 256 over sorted rows, over an M-token chunk. * @@ -26705,6 +26771,13 @@ static void device_phase(const Plugin& pl) { for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)33 }) fp8_logits_numeric(pl, 2560, 2560, M); } + /* The bf16 head's column form against the block-per-column row, to past one 8-row chunk. */ + if (sel("logits_gemm_bf16_cols")) { + for (const int64_t M : { (int64_t)1, (int64_t)2, (int64_t)6, (int64_t)8, (int64_t)9, + (int64_t)17 }) + logits_cols_check(pl, M, 2051); + logits_cols_check(pl, 6, 19360); + } /* The int8 head over the same stored row: both forms, and the padded K = 2560 row. */ if (sel("logits_gemm_i8") || sel("logit_rerank_i8")) { for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)33, (int64_t)64 }) @@ -27008,6 +27081,8 @@ static void usage(void) { " --perfkda M [iters]: kda_update at GLM's TP8 shape: prefill of M tokens (one\n" " sequence, and three anchored) and the 8x6 verify step, timed.\n" " --perfproject M [iters]: mla_project at GLM's TP8 shape, both modes, timed.\n" + " --perflogits M [iters]: logits_gemm_bf16 and logits_gemm_bf16_cols at\n" + " GLM-5.3's TP8 head slice (19360 x 4096), M rows, bytes compared.\n" " --perfmx M [iters] [experts] [top_k] [skew]: the MXFP4 expert GEMM at GLM's\n" " TP8 slices (gate_up 512 x 4096, down 4096 x 256) over a routing of an\n" " M-token chunk (288 experts, top 8 by default; uniform, or `skew` a Gamma\n" @@ -27072,6 +27147,8 @@ int main(int argc, char** argv) { long long ar8_n = -1; int ar8_it = 200; const char* ar8_dt = "bf16"; + long long lg_m = 0; + int lg_it = 200; long long mx_m = 0, mx_e = 288, mx_k = 8; const char* mx_skew = nullptr; bool mx_f8 = false; @@ -27238,6 +27315,11 @@ int main(int argc, char** argv) { if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_e = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_k = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_skew = argv[++i]; + } else if (!std::strcmp(argv[i], "--perflogits")) { + /* Both bf16 head rows at GLM-5.3's TP8 slice over M rows. */ + if (i + 1 >= argc) { usage(); return 2; } + lg_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) lg_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfhc")) { /* The gated residual's read at M rows. */ if (i + 1 >= argc) { usage(); return 2; } @@ -27411,6 +27493,15 @@ int main(int argc, char** argv) { dfree_all(); #else skip("kda_update and mla_project timing", "built without HIP"); +#endif + return 0; + } + if (lg_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + logits_cols_check(pl, lg_m, 19360, lg_it); +#else + skip("bf16 head timing", "built without HIP"); #endif return 0; } From b86b25e40685f2096b71845856512c19a958e1f0 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:12 +0200 Subject: [PATCH 136/152] arch/common: GLM KDA issues both low-rank down-projections before either up-projection -- one ordered point fewer a layer A KDA layer projects its input seven times: qkv, beta, the two rank-128 down-projections into the forget and gate paths, their two up-projections, and the output. The block issued forget's down- and up-projection, then gate's: a recorded pass orders the input's four readers, then forget_b, then gate_a reading the input again, three ordered points where two would do. Both down-projections now issue before either up-projection, in declare as in step, because the buffer plan takes lifetimes from the declaration order and forget_low and gate_low must not share bytes while both are live. The same GEMMs over the same operands, so the bytes are the same; the pinned step hashes move with the order (world 1 0x906897570034f5f5 / 0x68ffc03d2b640d51, world 8 0x9f39f6f7a04dc4d3 / 0x3818eedb4ac10d1b), and the block's test holds the four readers first. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- arch/common/rad_block_glm_kda.h | 13 +++++++++---- tests/glm5next_test.cpp | 9 +++++++-- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/arch/common/rad_block_glm_kda.h b/arch/common/rad_block_glm_kda.h index ab8b4e61..feacfde7 100644 --- a/arch/common/rad_block_glm_kda.h +++ b/arch/common/rad_block_glm_kda.h @@ -170,15 +170,20 @@ struct GlmKda { RAD_ARCH_TRY(beta.declare(b, nm, bg, nm.f("blk.%d.attn_beta", layer), heads, 4096, RAD_SHARD_ROW, group, { nm.ckpt("%s.b_proj.weight", prefix) }, input, w.core.beta)); + /* Both low-rank down-projections before either up-projection, in step() as here: the + * four reads of the input then share one ordered point of a recorded pass and the two + * up-projections the next, where forget_b between them cost a third. Declared in the + * issue order because the buffer plan takes lifetimes from this list, and forget_low and + * gate_low must not share bytes while both are live. */ RAD_ARCH_TRY(forget_a.declare( b, nm, bg, nm.f("blk.%d.attn_forget_a", layer), 128, 4096, RAD_SHARD_NONE, group, { nm.ckpt("%s.f_a_proj.weight", prefix) }, input, w.forget_low)); - RAD_ARCH_TRY(forget_b.declare( - b, nm, bg, nm.f("blk.%d.attn_forget_b", layer), width, 128, RAD_SHARD_ROW, group, - { nm.ckpt("%s.f_b_proj.weight", prefix) }, act(w.forget_low), w.core.a)); RAD_ARCH_TRY(gate_a.declare(b, nm, bg, nm.f("blk.%d.attn_gate_a", layer), 128, 4096, RAD_SHARD_NONE, group, { nm.ckpt("%s.g_a_proj.weight", prefix) }, input, w.gate_low)); + RAD_ARCH_TRY(forget_b.declare( + b, nm, bg, nm.f("blk.%d.attn_forget_b", layer), width, 128, RAD_SHARD_ROW, group, + { nm.ckpt("%s.f_b_proj.weight", prefix) }, act(w.forget_low), w.core.a)); RAD_ARCH_TRY(gate_b.declare(b, nm, bg, nm.f("blk.%d.attn_gate_b", layer), width, 128, RAD_SHARD_ROW, group, { nm.ckpt("%s.g_b_proj.weight", prefix) }, act(w.gate_low), w.core.gate)); @@ -205,8 +210,8 @@ struct GlmKda { qkv.step(ctx, input, w.core.qkv, T); beta.step(ctx, input, w.core.beta, T); forget_a.step(ctx, input, w.forget_low, T); - forget_b.step(ctx, act(w.forget_low), w.core.a, T); gate_a.step(ctx, input, w.gate_low, T); + forget_b.step(ctx, act(w.forget_low), w.core.a, T); gate_b.step(ctx, act(w.gate_low), w.core.gate, T); core.step(ctx, batch); output.step(ctx, act(w.core.out), w.out, T); diff --git a/tests/glm5next_test.cpp b/tests/glm5next_test.cpp index 1205eca2..7bd28b4b 100644 --- a/tests/glm5next_test.cpp +++ b/tests/glm5next_test.cpp @@ -1234,6 +1234,11 @@ TEST(glm_kda_projects_local_heads_and_reduces_only_after_the_output_projection) CHECK_EQ(std::count(ops.begin(), ops.end(), "gemm_nt"), 7); CHECK_EQ(std::count(ops.begin(), ops.end(), "silu"), 0); REQUIRE_EQ(ctx.issues.size(), (size_t)11); + // The input's four readers first, then both up-projections. + CHECK_EQ(ctx.issues[2].op, block.forget_a.op); + CHECK_EQ(ctx.issues[3].op, block.gate_a.op); + CHECK_EQ(ctx.issues[4].op, block.forget_b.op); + CHECK_EQ(ctx.issues[5].op, block.gate_b.op); CHECK_EQ(ctx.issues[9].op, block.output.op); CHECK_EQ(ctx.issues[10].op, block.op_ar); CHECK_EQ(ctx.issues[10].opd[0].handle, w.out); @@ -1351,8 +1356,8 @@ TEST(glm53_is_the_pinned_graph_and_steps) { int world; uint64_t graph, steps; }; - const Case cases[] = { { 1, 0xed3fc26c486ea1b5ull, 0x33e5f136f0dbba15ull }, - { 8, 0x712f01858dbe1047ull, 0xf9e357b1333c638full } }; + const Case cases[] = { { 1, 0x906897570034f5f5ull, 0x68ffc03d2b640d51ull }, + { 8, 0x9f39f6f7a04dc4d3ull, 0x3818eedb4ac10d1bull } }; for (const Case& cs : cases) { RadBuilder b; b.kv_block = 4; From 69f4906a5c6154752150d0be123711711f716455 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:12 +0200 Subject: [PATCH 137/152] docs: GLM-5.3's decode at a few rows The five changes for decode's few rows in the glm5next section, where they apply and their kernel times. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURES.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 0cbfd6da..0dfe6317 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -580,6 +580,22 @@ wherever a loaded library serves the fused op (the separate launches otherwise): the eight R9700s below, greedy text at a fixed draft depth of 3 is identical with and without them, and eight agent streams decode 456 tok/s against 452, one 144 against 140. +**Decode at a few rows.** A verify pass of one stream carries two to six rows (the draft window +and one), a draft pass one; there a step is a chain of short launches, each bound by its own +latency rather than by bandwidth. Five changes serve those rows, each byte-identical to what it +replaces. Kernel times on one R9700 at the TP8 slices (r4d_selftest's perf modes, `--cold 256`): + +| change | where it applies | before / after, us | +|---|---|---| +| `moe_gemm_q` mxfp4a8 takes the small-M form (`moe_mxfp4_small_kernel`): blocks walk the touched experts only, weight codes stay packed in LDS, gate_up stages 512 of K, down reads its rows whole | gate_up to 384 routed rows, down to 32 | gate_up at 1 / 4 / 6 / 16 / 48 tokens: 36.8 / 31.4, 90.0 / 79.7, 120.5 / 101.4, 230.3 / 206.8, 416.7 / 390.0; down at 1 / 2 / 4: 21.2 / 16.4, 26.0 / 22.5, 39.5 / 37.9 | +| `moe_gemm_q` fp8a8f32 takes the same form (`fp8_f32scale_small`) for the MTP layer's gate_up | to 384 routed rows | at 1 / 2 / 8 tokens: 73.6 / 36.7, 83.6 / 65.8, 214.0 / 203.9 | +| `gemm_nt_f32` keeps 16 steps of k in flight a lane (8 from 17 rows at the router's width) | below 64 rows | router (N 288) at 1 / 4 / 8 / 24 rows: 28.1 / 14.4, 36.0 / 14.5, 36.3 / 15.0, 45.4 / 21.6; index head gates (N 32) at 1 / 24: 27.3 / 9.8, 36.2 / 10.0 | +| `logits_gemm` takes `logits_gemm_bf16_cols`, a wave per four vocabulary columns | n_embd 4096 | at 1 / 6 / 8 / 24 / 48 rows: 239.1 / 235.5, 303.2 / 247.5, 378.2 / 250.4, 1133.2 / 635.6, 2354.5 / 1220.1 | +| KDA issues both low-rank down-projections before either up-projection, so a recorded pass orders the four readers of the layer input once and the two up-projections once | every KDA layer | one ordered point fewer a layer | + +`r4d_emu` holds both expert forms and the f32 tiles to the host restatement of their per-element +sequence, and `r4d_selftest` compares the head's column form with the block row byte for byte. + **Measured** on eight R9700s (gfx1201, 32 GB; four on PCIe Gen5 x16, four on Gen5 x8) at TP8 with the flags of `deploy/compose/glm53-flash.yaml` (32768 tokens of context, eight sequences, MTP with an adaptive window up to 5, reasoning effort low). BetterBench quick, temperature 0.7, cold From b0bcb74c5b965d81f173821019c3bf8328ae1d98 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:14 +0200 Subject: [PATCH 138/152] core/mm: GLM-5.3's processor -- a canvas within a token budget, padded rather than stretched A fourth processor family beside Qwen-VL, Gemma 4 and LFM2-VL, chosen by vision_config.model_type glm5_next_vision, as transformers' Glm5NextImageProcessor (torchvision backend) computes it: - The canvas: both sides rounded up to patch * merge (28), grown by the area ratio under min_image_tokens, and fitted by the reference's binary search over the picture's height past max_image_tokens, a token being two frames of 28 x 28 pixels. - The picture keeps its aspect ratio, is never enlarged while it reaches the floor, is resized with torchvision's fixed-point bicubic only when its size changes, and sits in the top left of a canvas of zero bytes, which the normalisation turns into each channel's -mean / std as it does the reference's padding. Patches as Qwen-VL's (merge-block order, (channel, frame, y, x), the picture in both frames, CLIP's mean and deviation from processor_config.json). - <|begin_of_image|>, one <|image|> a token, <|end_of_image|>; the tokens rotate at their positions (the language model has no rotary). Pictures only. The budget is in tokens and comes from processor.image_processor.{min,max}_image_tokens; one encoder pass bounds it, so it is lowered to max_patches / merge^2, as a Qwen-VL pixel band is (4096 tokens at --mm-max-patches auto, the checkpoint's 8000 at 32000). --image-tokens sets the ceiling; the pixel-band and video flags, a request's image_tokens and a video are refused by name. tests/mkglm5golden.py writes glm5_golden.h from Glm5NextProcessor; mm_test checks canvases over a grid of sizes and both budgets, and whole pictures (padded only, grown under the floor, shrunk to a budget) patch for patch and token for token, all bit-exact, and the processor read from a container's keys. Co-Authored-By: Claude Opus 5.5 --- core/config.cpp | 5 +- core/engine.cpp | 33 ++++++++- core/mm/processor.cpp | 167 +++++++++++++++++++++++++++++++++++++++++- core/mm/processor.h | 21 +++++- tests/glm5_golden.h | 73 ++++++++++++++++++ tests/mkglm5golden.py | 118 +++++++++++++++++++++++++++++ tests/mm_test.cpp | 166 ++++++++++++++++++++++++++++++++++++++++- 7 files changed, 575 insertions(+), 8 deletions(-) create mode 100644 tests/glm5_golden.h create mode 100644 tests/mkglm5golden.py diff --git a/core/config.cpp b/core/config.cpp index 812ac10b..812fd72f 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -240,8 +240,9 @@ static const Flag g_flags[] = { { "--video-max-frames", "N", "the most frames sampled from a video" }, { "--video-max-frame-tokens", "N", "the most prompt tokens one video frame may become; 0 is no cap (a token\n" " budget processor -- Gemma 4's -- takes 70, 140, 280, 560 or 1120)" }, - { "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120;\n" - " default the container's); a request's `image_tokens` overrides it" }, + { "--image-tokens", "N", "a token-budget processor's image budget (Gemma 4: 70, 140, 280, 560, 1120,\n" + " which a request's `image_tokens` overrides; GLM-5.3: the most tokens an\n" + " image becomes, at most --mm-max-patches / 4; default the container's)" }, { "--max-source-pixels", "N", "the largest image or video frame the decoder accepts, before any resize\n" " (default 67108864). The media flags above default to what the container\n" " states, and do nothing for a model that takes no media" }, diff --git a/core/engine.cpp b/core/engine.cpp index 7af29aab..8569750f 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2231,7 +2231,7 @@ int Engine::run_server() { * are refused by name: LFM2-VL takes pictures only, and a token-budget processor (Gemma * 4's) sizes by soft tokens (--image-tokens, --video-max-frame-tokens), not pixel * bands. */ - if (vc.family == mm::Family::Lfm2 && + if ((vc.family == mm::Family::Lfm2 || vc.family == mm::Family::Glm5Next) && (cfg_.video_min_pixels || cfg_.video_max_pixels || cfg_.video_min_frames || cfg_.video_max_frames || cfg_.video_fps || cfg_.video_max_frame_tokens)) { RAD_ERR("media: this model's processor takes pictures, not video, so the --video-* " @@ -2249,6 +2249,16 @@ int Engine::run_server() { } if (cfg_.image_tokens) vc.image_soft_tokens = *cfg_.image_tokens; if (cfg_.video_max_frame_tokens) vc.video_soft_tokens = *cfg_.video_max_frame_tokens; + } else if (vc.family == mm::Family::Glm5Next) { + /* GLM-5.3 budgets an image in tokens (max_image_tokens), so --image-tokens is its + * ceiling and the pixel bands do not apply. */ + if (cfg_.image_min_pixels || cfg_.image_max_pixels) { + RAD_ERR("media: this model's processor sizes images by a token budget, so " + "--image-min-pixels and --image-max-pixels do nothing; use " + "--image-tokens"); + return RAD_E_INVAL; + } + if (cfg_.image_tokens) vc.max_image_tokens = *cfg_.image_tokens; } else { if (cfg_.image_tokens) { RAD_ERR("media: --image-tokens is a token budget, and this model's processor " @@ -2284,6 +2294,16 @@ int Engine::run_server() { (long long)encd.patch_dim, (long long)encd.merge); return RAD_E_INVAL; } + /* An explicit budget past one pass is refused; the container's is lowered to fit + * (Processor::init), as a pixel band is. */ + if (vc.family == mm::Family::Glm5Next && cfg_.image_tokens && + (int64_t)*cfg_.image_tokens * vc.merge * vc.merge > encd.max_patches) { + RAD_ERR("media: --image-tokens %d is more patches than one encoder pass holds " + "(--mm-max-patches %lld, %lld tokens)", *cfg_.image_tokens, + (long long)encd.max_patches, + (long long)(encd.max_patches / ((int64_t)vc.merge * vc.merge))); + return RAD_E_INVAL; + } if (vc.family == mm::Family::Gemma4 && (int64_t)std::max(vc.image_soft_tokens, vc.video_soft_tokens) * vc.merge * vc.merge > encd.max_patches) { @@ -2320,6 +2340,17 @@ int Engine::run_server() { mm_proc->config().max_pixels_tolerance, mm_proc->config().min_tiles, mm_proc->config().max_tiles, mm_proc->config().tile, (long long)encd.max_patches); + else if (mm_proc->config().family == mm::Family::Glm5Next) { + RAD_INFO("media: images through '%s'; an image becomes %d..%d tokens, padded to its " + "canvas rather than stretched; %lld patches a pass", + ranks_[0]->program.encoder_name.c_str(), mm_proc->config().min_image_tokens, + mm_proc->config().max_image_tokens, (long long)encd.max_patches); + if (mm_proc->config().max_image_tokens < vc.max_image_tokens) + RAD_INFO("media: the budget of %d tokens an image is lowered to %d, what one " + "encoder pass holds; --mm-max-patches %lld serves it whole", + vc.max_image_tokens, mm_proc->config().max_image_tokens, + (long long)vc.max_image_tokens * vc.merge * vc.merge); + } else if (mm_proc->config().family == mm::Family::Gemma4) RAD_INFO("media: %s%s through '%s'; an image becomes at most %d soft tokens (a " "request's image_tokens may ask for 70..1120), a video %d a frame at %.3g " diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index 4c304232..40bb2d21 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -90,6 +90,65 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { return RAD_OK; } const char* mt = rad_meta_gets(&m, "vision_config.model_type", ""); + /* GLM-5.3 states its processor only in processor_config.json's image_processor, with a token + * budget and no pixel band; the tower's geometry is the fallback, as the processor class + * defaults to it. */ + if (mt && !std::strcmp(mt, "glm5_next_vision")) { + family = Family::Glm5Next; + auto geti = [&](const char* k, const char* tower, int64_t dflt) { + const std::string key = std::string("processor.image_processor.") + k; + return rad_meta_geti(&m, key.c_str(), rad_meta_geti(&m, tower, dflt)); + }; + patch = (int32_t)geti("patch_size", "vision_config.patch_size", 0); + temporal = (int32_t)geti("temporal_patch_size", "vision_config.temporal_patch_size", 0); + merge = (int32_t)geti("merge_size", "vision_config.spatial_merge_size", 0); + if (patch <= 0 || temporal <= 0 || merge <= 0) { + if (why) *why = "the container states no vision tower geometry (vision_config." + "patch_size, temporal_patch_size, spatial_merge_size)"; + return RAD_E_NOTFOUND; + } + /* The expand factor multiplies the canvas's alignment without changing the patches; the + * checkpoints ship 1, and another one is a canvas this processor does not make. */ + const int64_t expand = + rad_meta_geti(&m, "processor.image_processor.patch_expand_factor", 1); + if (expand != 1) { + if (why) *why = "processor.image_processor.patch_expand_factor is " + + std::to_string(expand) + "; this processor serves 1"; + return RAD_E_UNSUPPORTED; + } + tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1); + tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1); + tok_start = (int32_t)rad_meta_geti(&m, "image_start_token_id", -1); + tok_end = (int32_t)rad_meta_geti(&m, "image_end_token_id", -1); + if (tok_image < 0 || tok_start < 0 || tok_end < 0) { + if (why) *why = "the container states no media token ids (image_token_id, " + "image_start_token_id, image_end_token_id)"; + return RAD_E_NOTFOUND; + } + min_image_tokens = (int32_t)rad_meta_geti(&m, "processor.image_processor.min_image_tokens", + 16); + max_image_tokens = (int32_t)rad_meta_geti(&m, "processor.image_processor.max_image_tokens", + 8000); + /* OpenAI CLIP's, the processor class's default. */ + const float clip_mean[3] = { 0.48145466f, 0.4578275f, 0.40821073f }; + const float clip_std[3] = { 0.26862954f, 0.26130258f, 0.27577711f }; + std::copy(clip_mean, clip_mean + 3, mean); + std::copy(clip_std, clip_std + 3, stdv); + read_triple(m, "processor.image_processor.image_mean", mean); + read_triple(m, "processor.image_processor.image_std", stdv); + /* The pixel bands are QwenVL's; here they only have to be consistent for check(). */ + const int64_t f2 = (int64_t)factor() * factor(); + image_min_pixels = video_min_pixels = std::max(1, min_image_tokens) * f2; + image_max_pixels = video_max_pixels = + std::max(image_min_pixels, (int64_t)max_image_tokens * f2); + std::string bad; + if (check(&bad) < 0) { + if (why) + *why = "the container's GLM-5.3 processor configuration is inconsistent: " + bad; + return RAD_E_INVAL; + } + return RAD_OK; + } if (mt && !std::strcmp(mt, "gemma4_vision")) { family = Family::Gemma4; patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0); @@ -200,6 +259,9 @@ int VisionConfig::check(std::string* why) const { if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0) return no("max_pixels_tolerance and max_num_patches must be positive"); } + if (family == Family::Glm5Next && (min_image_tokens < 1 || max_image_tokens < min_image_tokens)) + return no("the image token band [" + std::to_string(min_image_tokens) + ", " + + std::to_string(max_image_tokens) + "] is empty"); if (family == Family::Gemma4) { if (!soft_budget_ok(image_soft_tokens)) return no("the image soft-token budget " + std::to_string(image_soft_tokens) + @@ -323,6 +385,51 @@ int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_p return RAD_OK; } +/* Glm5NextImageProcessor's smart_resize and the size its resize() gives the picture, in Python's + * doubles. A token is `temporal` frames of factor x factor pixels, and a picture counts as + * `temporal` frames. The canvas's sides are rounded up to whole factors; under the floor the + * picture is scaled up by the area ratio and rounded up again; over the budget a binary search over + * the picture's height finds the largest canvas inside it. The picture then scales by the smaller + * side ratio, never up while it reaches the floor, truncated. */ +int glm5next_size(int64_t h, int64_t w, int32_t temporal, int32_t factor, int64_t min_tok, + int64_t max_tok, int64_t* oh, int64_t* ow, int64_t* ch, int64_t* cw, + std::string* why) { + if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; } + const int64_t per_tok = (int64_t)temporal * factor * factor; + const int64_t min_px = min_tok * per_tok, max_px = max_tok * per_tok; + if (max_px < per_tok) { + if (why) *why = "the token budget is less than one merged patch"; + return RAD_E_INVAL; + } + auto align = [factor](int64_t v) { return (v + factor - 1) / factor * factor; }; + int64_t ah = align(h), aw = align(w); + if (temporal * ah * aw < min_px) { + const double scale = std::sqrt((double)min_px / ((double)temporal * (double)h * (double)w)); + ah = align(std::max(1, (int64_t)std::ceil((double)h * scale))); + aw = align(std::max(1, (int64_t)std::ceil((double)w * scale))); + } + if (temporal * ah * aw > max_px) { + int64_t lo = 1, hi = h, bh = factor, bw = factor; + while (lo <= hi) { + const int64_t mid = (lo + hi) / 2; + const int64_t wid = std::max(1, (int64_t)std::floor((double)(w * mid) / + (double)h)); + const int64_t th = align(mid), tw = align(wid); + if (temporal * th * tw <= max_px) { bh = th; bw = tw; lo = mid + 1; } + else hi = mid - 1; + } + ah = bh; + aw = bw; + } + double scale = std::min((double)ah / (double)h, (double)aw / (double)w); + if (temporal * h * w >= per_tok * min_tok) scale = std::min(1.0, scale); + *oh = ah; + *ow = aw; + *ch = std::max(1, std::min(ah, (int64_t)std::floor((double)h * scale))); + *cw = std::max(1, std::min(aw, (int64_t)std::floor((double)w * scale))); + return RAD_OK; +} + /* The reference's (EmbeddingGemma2VideoProcessor.sample_frames): the stream's duration at `fps`, * one frame each 1/fps seconds as int(i * native_fps / fps), then `max_frames` of those chosen by * numpy's linspace truncated to integers. */ @@ -670,6 +777,15 @@ int Processor::init(const VisionConfig& cfg, encode_text_ = std::move(encode_text); return RAD_OK; } + if (cfg.family == Family::Glm5Next) { + /* A token is merge^2 patches and an image is one segment of one pass, so the budget is + * lowered to what a pass holds. */ + const int64_t pass_tok = cfg.max_patches / ((int64_t)cfg.merge * cfg.merge); + if (pass_tok < cfg.min_image_tokens) return RAD_E_INVAL; + if (cfg_.max_image_tokens > pass_tok) cfg_.max_image_tokens = (int32_t)pass_tok; + encode_text_ = std::move(encode_text); + return RAD_OK; + } if (cfg.family == Family::Gemma4) { /* A budget is a patch count, and an image is one segment of one pass. */ if ((int64_t)cfg.image_soft_tokens * cfg.merge * cfg.merge > cfg.max_patches || @@ -804,10 +920,50 @@ int Processor::image_lfm2(const Frame& f, std::shared_ptr* out, std::strin return RAD_OK; } +/* GLM-5.3's image processor (transformers' Glm5NextImageProcessor, torchvision backend): the + * picture, resized only when its size changes, in the top left of a canvas of zero bytes, which + * the normalisation turns into each channel's -mean / std as it does the reference's padding. */ +int Processor::image_glm5next(const Frame& f, std::shared_ptr* out, std::string* why) const { + const VisionConfig& c = cfg_; + int64_t h = 0, w = 0, ch = 0, cw = 0; + RAD_TRY(glm5next_size(f.h, f.w, c.temporal, c.factor(), c.min_image_tokens, + c.max_image_tokens, &h, &w, &ch, &cw, why)); + Frame r; + const Frame* src = &f; + if (ch != f.h || cw != f.w) { + resize_bicubic_torch(f, (int32_t)cw, (int32_t)ch, &r); + src = &r; + } + Frame canvas; + canvas.w = (int32_t)w; + canvas.h = (int32_t)h; + canvas.rgb.assign((size_t)w * h * 3, 0); + for (int64_t y = 0; y < ch; ++y) + std::memcpy(canvas.rgb.data() + (size_t)y * w * 3, src->rgb.data() + (size_t)y * cw * 3, + (size_t)cw * 3); + auto it = std::make_shared(); + it->kind = Kind::Image; + it->grid_t = 1; + it->grid_h = (int32_t)(h / c.patch); + it->grid_w = (int32_t)(w / c.patch); + it->rope_1d = true; + finish_item(c, it.get()); + if (it->n_patch > c.max_patches) { + if (why) *why = "the image resizes to more patches than one encoder pass holds"; + return RAD_E_INVAL; + } + std::vector frames((size_t)c.temporal, &canvas); + patchify(c, frames, it.get()); + one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end); + *out = std::move(it); + return RAD_OK; +} + int Processor::image_from(const Frame& f, std::shared_ptr* out, std::string* why) const { const VisionConfig& c = cfg_; if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why); if (c.family == Family::Lfm2) return image_lfm2(f, out, why); + if (c.family == Family::Glm5Next) return image_glm5next(f, out, why); int64_t h = 0, w = 0; RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels, &h, &w, why)); @@ -900,6 +1056,10 @@ int Processor::video_gemma4(const Video& v, std::shared_ptr* out, std::str int Processor::video_from(const Video& v, std::shared_ptr* out, std::string* why) const { const VisionConfig& c = cfg_; if (c.family == Family::Gemma4) return video_gemma4(v, out, why); + if (c.family == Family::Glm5Next) { + if (why) *why = "this model's processor takes pictures, not video"; + return RAD_E_UNSUPPORTED; + } if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; } /* Pad the frames and their indices to whole temporal groups by repeating the last; a clip * shorter than one group becomes one group. */ @@ -981,6 +1141,11 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr* out, std::string* why, int64_t max_pixels) const { if (image_tokens != 0) { + if (cfg_.family == Family::Glm5Next) { + if (why) *why = "this model's image token budget is the server's (--image-tokens), " + "not a request's"; + return RAD_E_UNSUPPORTED; + } if (cfg_.family != Family::Gemma4) { if (why) *why = "this model's processor sizes an image by its pixels, not by a token " "budget"; @@ -1017,7 +1182,7 @@ std::vector sample_cb(const VideoInfo& info, const void* user) { int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const { - if (cfg_.family == Family::Lfm2) { + if (cfg_.family == Family::Lfm2 || cfg_.family == Family::Glm5Next) { if (why) *why = "this model's processor takes pictures, not video"; return RAD_E_UNSUPPORTED; } diff --git a/core/mm/processor.h b/core/mm/processor.h index 5be2cf42..c3f90e08 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -55,8 +55,16 @@ enum class Kind { Image, Video, Audio }; * is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its * own, followed by the whole picture at the budgeted size as a thumbnail. Patches * (y, x, channel) normalised by the mean and deviation, resized with torchvision's - * fixed-point bicubic; images only, and the tokens rotate at their positions. */ -enum class Family { QwenVL, Gemma4, Lfm2 }; + * fixed-point bicubic; images only, and the tokens rotate at their positions. + * Glm5Next GLM-5.3's: a canvas whose sides are multiples of patch * merge and whose tokens fall + * in [min_image_tokens, max_image_tokens] (the sides rounded up, a picture under the + * floor grown, one over the budget fitted by the reference's search); the picture keeps + * its aspect ratio, is never enlarged above the floor, and is resized with torchvision's + * fixed-point bicubic only when its size changes; the rest of the canvas, right and + * bottom, is zero bytes. Patches as QwenVL's. Images only, spelled + * placeholders , the tokens at their positions (the language model has no + * rotary). */ +enum class Family { QwenVL, Gemma4, Lfm2, Glm5Next }; struct VisionConfig { Family family = Family::QwenVL; @@ -66,6 +74,8 @@ struct VisionConfig { int32_t image_soft_tokens = 0, video_soft_tokens = 0; int64_t image_min_pixels = 0, image_max_pixels = 0; int64_t video_min_pixels = 0, video_max_pixels = 0; + /* Glm5Next: the band an image's canvas falls in, in output rows (tokens). */ + int32_t min_image_tokens = 0, max_image_tokens = 0; double fps = 2.0; int32_t min_frames = 4, max_frames = 768; /* Per-frame ceiling on a video's resolution, in output rows (the reference processor's @@ -332,6 +342,7 @@ private: int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr* out, std::string* why) const; int image_lfm2(const Frame& f, std::shared_ptr* out, std::string* why) const; + int image_glm5next(const Frame& f, std::shared_ptr* out, std::string* why) const; /* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */ int32_t tok_thumbnail_ = -1; std::vector tok_tiles_; @@ -373,6 +384,12 @@ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out); /* ...and torchvision's on a uint8 tensor (ATen's CPU kernel), which is the same filter with the * coefficients at the most precision 16 bits hold, chosen per axis, rather than PIL's 22. */ void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out); +/* GLM-5.3's smart_resize: the (oh, ow) canvas, multiples of `factor`, for an h x w picture whose + * `temporal` frames take [min_tok, max_tok] tokens of temporal * factor^2 pixels each; and the + * (ch, cw) the picture is resized to inside it, top left, aspect ratio kept. */ +int glm5next_size(int64_t h, int64_t w, int32_t temporal, int32_t factor, int64_t min_tok, + int64_t max_tok, int64_t* oh, int64_t* ow, int64_t* ch, int64_t* cw, + std::string* why); /* LFM2-VL's smart_resize: (height, width) to multiples of `factor`, at least one each, pixels * within [min_px, max_px] where the rounding left them outside. */ void lfm2_size(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px, diff --git a/tests/glm5_golden.h b/tests/glm5_golden.h new file mode 100644 index 00000000..3e781c59 --- /dev/null +++ b/tests/glm5_golden.h @@ -0,0 +1,73 @@ +/* glm5_golden.h -- GENERATED by mkglm5golden.py from transformers 5.21.0.dev0; do not edit. */ +#pragma once +#include + +static const int32_t kGlm5Patch = 14, kGlm5Merge = 2, kGlm5Temporal = 2, kGlm5MinTok = 16, kGlm5MaxTok = 8000; +static const int32_t kGlm5Image = 154854, kGlm5Start = 154830, kGlm5End = 154831; +static const float kGlm5Mean[3] = { 0.48145466f, 0.4578275f, 0.40821073f }, kGlm5Std[3] = { 0.26862954f, 0.26130258f, 0.27577711f }; + +struct GoldGlm5Size { int64_t h, w; int32_t budget; int64_t oh, ow, patches; }; +static const GoldGlm5Size kGoldGlm5Size[] = { + { 1, 1, 8000, 112, 112, 64 }, + { 1, 1, 4096, 112, 112, 64 }, + { 100, 100, 8000, 112, 112, 64 }, + { 100, 100, 4096, 112, 112, 64 }, + { 61, 97, 8000, 112, 168, 96 }, + { 61, 97, 4096, 112, 168, 96 }, + { 3, 4000, 8000, 28, 4004, 572 }, + { 3, 4000, 4096, 28, 4004, 572 }, + { 448, 448, 8000, 448, 448, 1024 }, + { 448, 448, 4096, 448, 448, 1024 }, + { 300, 500, 8000, 308, 504, 792 }, + { 300, 500, 4096, 308, 504, 792 }, + { 768, 1024, 8000, 784, 1036, 4144 }, + { 768, 1024, 4096, 784, 1036, 4144 }, + { 1080, 1920, 8000, 1092, 1932, 10764 }, + { 1080, 1920, 4096, 1092, 1932, 10764 }, + { 2048, 2048, 8000, 2072, 2072, 21904 }, + { 2048, 2048, 4096, 1792, 1792, 16384 }, + { 3000, 4000, 8000, 2156, 2884, 31724 }, + { 3000, 4000, 4096, 1540, 2072, 16280 }, + { 4000, 3000, 8000, 2884, 2156, 31724 }, + { 4000, 3000, 4096, 2072, 1540, 16280 }, + { 20, 1500, 8000, 28, 1512, 216 }, + { 20, 1500, 4096, 28, 1512, 216 }, + { 1500, 20, 8000, 1512, 28, 216 }, + { 1500, 20, 4096, 1512, 28, 216 }, + { 111, 113, 8000, 112, 140, 80 }, + { 111, 113, 4096, 112, 140, 80 }, + { 112, 112, 8000, 112, 112, 64 }, + { 112, 112, 4096, 112, 112, 64 }, + { 113, 111, 8000, 140, 112, 80 }, + { 113, 111, 4096, 140, 112, 80 }, + { 2300, 2900, 8000, 2240, 2800, 32000 }, + { 2300, 2900, 4096, 1596, 1988, 16188 }, + { 7000, 120, 8000, 7000, 140, 5000 }, + { 7000, 120, 4096, 7000, 140, 5000 }, + { 120, 7000, 8000, 140, 7000, 5000 }, + { 120, 7000, 4096, 140, 7000, 5000 }, + { 5000, 5000, 8000, 2492, 2492, 31684 }, + { 5000, 5000, 4096, 1792, 1792, 16384 }, + { 12000, 9000, 8000, 2884, 2156, 31724 }, + { 12000, 9000, 4096, 2072, 1540, 16280 }, + { 2160, 3840, 8000, 1876, 3332, 31892 }, + { 2160, 3840, 4096, 1344, 2380, 16320 }, + { 1, 30000, 8000, 28, 30016, 4288 }, + { 1, 30000, 4096, 28, 30016, 4288 }, + { 900, 1400, 8000, 924, 1400, 6600 }, + { 900, 1400, 4096, 924, 1400, 6600 }, +}; + +struct GoldGlm5Pic { int32_t f, h, w, budget, grid_h, grid_w; uint64_t fnv; int32_t n_ids; uint64_t ids_fnv; uint16_t head[8]; }; +static const GoldGlm5Pic kGoldGlm5Pics[] = { + { 0, 448, 448, 8000, 32, 32, 0xd1a1afd8f20ac789ull, 258, 0x72139e1c3f39bf1cull, { 0xbf1c, 0xbfc0, 0x3e0a, 0x3fc6, 0xbf7d, 0x3e64, 0x3f8e, 0x3f87 } }, + { 1, 300, 500, 8000, 22, 36, 0x7be72496cfec045dull, 200, 0x255584700075589cull, { 0x3f0b, 0xbe30, 0xbf91, 0x3fdb, 0xbfe2, 0xbe6c, 0x3f4b, 0x3fa7 } }, + { 2, 61, 97, 8000, 8, 12, 0xfedf63278fd84bf1ull, 26, 0x257747e49c4ee91cull, { 0x3ff1, 0x3fce, 0x3f96, 0x3fa9, 0x3fb2, 0x3f4e, 0x3f13, 0x3f47 } }, + { 3, 3, 400, 8000, 2, 94, 0x26cc3ab47053bc9dull, 49, 0xfbf168ec084616acull, { 0xbfe5, 0xbfda, 0xbf5f, 0x3ef8, 0x3fe3, 0x3ff7, 0x3fdf, 0x3f96 } }, + { 4, 20, 1500, 8000, 2, 108, 0x2fd52c52ec4a00a9ull, 56, 0x47537633a0505c9cull, { 0x3f94, 0xbeb2, 0xbf3e, 0x3e64, 0xbfc9, 0xbed0, 0x3f5a, 0xbf41 } }, + { 5, 900, 1400, 256, 26, 38, 0x398290b8912d19d9ull, 249, 0x355dfb37a793d4acull, { 0x3f34, 0xbec1, 0xbf11, 0xbe12, 0xbe85, 0x3d9c, 0x3c93, 0x3f29 } }, + { 6, 1200, 1700, 4096, 86, 122, 0x5fd09cd1af13ba41ull, 2625, 0xf9b8b842d63572acull, { 0xbf8f, 0x3fa5, 0xbf6b, 0x3f61, 0x3fac, 0xbf67, 0xbf18, 0x3df6 } }, + { 7, 2300, 2900, 8000, 160, 200, 0x267b44f24a266119ull, 8002, 0x41e705bec95caf1cull, { 0xbf3a, 0x3fc1, 0xbe94, 0xbfc0, 0xbfa0, 0xbe94, 0xbf7a, 0xbf9b } }, + { 8, 1, 1, 8000, 8, 8, 0xb8835c50fee76f25ull, 18, 0xb05a4c2103cd9b1cull, { 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1, 0xbfb1 } }, + { 9, 113, 111, 8000, 10, 8, 0x4ae29fe59e7b4e15ull, 22, 0xd734c8e25ac1621cull, { 0xbfba, 0x3fe4, 0xbf11, 0xbf33, 0x3ed3, 0x3f43, 0xbfc9, 0xbfbc } }, +}; diff --git a/tests/mkglm5golden.py b/tests/mkglm5golden.py new file mode 100644 index 00000000..33845f55 --- /dev/null +++ b/tests/mkglm5golden.py @@ -0,0 +1,118 @@ +"""mkglm5golden.py MODELDIR OUT.h -- goldens for tests/mm_test.cpp's GLM-5.3 vision cases, every number +from transformers' own Glm5NextProcessor as MODELDIR's processor_config.json sets it up (run in a +venv with a transformers that has glm5_next, torch, torchvision, numpy and Pillow). + +The reference is the processor AutoProcessor loads: Glm5NextImageProcessor, transformers' torchvision +backend, which resizes the uint8 picture with torchvision's antialiased bicubic (ATen's fixed-point +kernel), pads it right and bottom with zero bytes, and normalises in float32 with the rescale fused +into the mean and deviation. + + * smart_resize over a grid of picture sizes and two token budgets (the checkpoint's 8000, and + the 4096 an encoder pass of 16384 patches holds): the canvas and the patch count, the latter + from get_number_of_image_patches; + * whole pictures, some only padded, some grown under the token floor, some shrunk to a budget: + the patch grid and the FNV-1a of every patch as the tower reads it (float32, then bfloat16), + in the reference's own order, which is merge-block order; and the token ids Glm5NextProcessor + makes of <|begin_of_image|><|image|><|end_of_image|>. + +The pixel at (frame f, row y, column x, channel c) is mm_test's splitmix hash. +""" +import sys + +import numpy as np +import torch +import transformers +from transformers import AutoProcessor +from transformers.models.glm5_next.image_processing_glm5_next import smart_resize + +U = np.uint64 + + +def picture(f, h, w): + """[h, w, 3] uint8, mm_test's pix(f, y, x, c).""" + with np.errstate(over="ignore"): + y = np.arange(h, dtype=U).reshape(h, 1, 1) + x = np.arange(w, dtype=U).reshape(1, w, 1) + c = np.arange(3, dtype=U).reshape(1, 1, 3) + z = (U(f) * U(0x9E3779B97F4A7C15) + y * U(0xBF58476D1CE4E5B9) + + x * U(0x94D049BB133111EB) + c * U(0x2545F4914F6CDD1D) + U(12345)) + z = (z ^ (z >> U(30))) * U(0xBF58476D1CE4E5B9) + z = (z ^ (z >> U(27))) * U(0x94D049BB133111EB) + return ((z ^ (z >> U(31))) & U(255)).astype(np.uint8) + + +def fnv(data): + h = 0xcbf29ce484222325 + for b in np.frombuffer(data, dtype=np.uint8).tolist(): + h = ((h ^ b) * 0x100000001b3) & ((1 << 64) - 1) + return h + + +def main(): + model_dir, out = sys.argv[1], sys.argv[2] + P = AutoProcessor.from_pretrained(model_dir) + IP = P.image_processor + tok = P.tokenizer + T, F = IP.temporal_patch_size, IP.patch_size * IP.merge_size * IP.patch_expand_factor + L = ["/* glm5_golden.h -- GENERATED by mkglm5golden.py from transformers %s; do not edit. */" + % transformers.__version__, "#pragma once", "#include ", ""] + L.append(f"static const int32_t kGlm5Patch = {IP.patch_size}, kGlm5Merge = {IP.merge_size}, " + f"kGlm5Temporal = {T}, kGlm5MinTok = {IP.min_image_tokens}, " + f"kGlm5MaxTok = {IP.max_image_tokens};") + ids = [tok.convert_tokens_to_ids(t) for t in ("<|image|>", "<|begin_of_image|>", "<|end_of_image|>")] + L.append(f"static const int32_t kGlm5Image = {ids[0]}, kGlm5Start = {ids[1]}, kGlm5End = {ids[2]};") + L.append("static const float kGlm5Mean[3] = { %s }, kGlm5Std[3] = { %s };" % + (", ".join(f"{v!r}f" for v in IP.image_mean), ", ".join(f"{v!r}f" for v in IP.image_std))) + L.append("") + + # ---- smart_resize: the canvas, and the patch count the processor reports for it + sizes = [(1, 1), (100, 100), (61, 97), (3, 4000), (448, 448), (300, 500), (768, 1024), + (1080, 1920), (2048, 2048), (3000, 4000), (4000, 3000), (20, 1500), (1500, 20), + (111, 113), (112, 112), (113, 111), (2300, 2900), (7000, 120), (120, 7000), + (5000, 5000), (12000, 9000), (2160, 3840), (1, 30000), (900, 1400)] + L.append("struct GoldGlm5Size { int64_t h, w; int32_t budget; int64_t oh, ow, patches; };") + L.append("static const GoldGlm5Size kGoldGlm5Size[] = {") + for h, w in sizes: + for budget in (IP.max_image_tokens, 4096): + oh, ow = smart_resize(num_frames=T, height=h, width=w, temporal_factor=T, factor=F, + min_pixels=IP.min_image_tokens, max_pixels=budget) + n = IP.get_number_of_image_patches(h, w, {"max_image_tokens": budget}) + assert n == (oh // IP.patch_size) * (ow // IP.patch_size) + L.append(f" {{ {h}, {w}, {budget}, {oh}, {ow}, {n} }},") + L.append("};") + L.append("") + + # ---- whole pictures: padded only, grown under the floor, shrunk to a budget + pics = [(0, 448, 448, IP.max_image_tokens), (1, 300, 500, IP.max_image_tokens), + (2, 61, 97, IP.max_image_tokens), (3, 3, 400, IP.max_image_tokens), + (4, 20, 1500, IP.max_image_tokens), (5, 900, 1400, 256), (6, 1200, 1700, 4096), + (7, 2300, 2900, IP.max_image_tokens), (8, 1, 1, IP.max_image_tokens), + (9, 113, 111, IP.max_image_tokens)] + L.append("struct GoldGlm5Pic { int32_t f, h, w, budget, grid_h, grid_w; uint64_t fnv; " + "int32_t n_ids; uint64_t ids_fnv; uint16_t head[8]; };") + L.append("static const GoldGlm5Pic kGoldGlm5Pics[] = {") + for f, h, w, budget in pics: + im = picture(f, h, w) + o = IP(images=[torch.from_numpy(im).permute(2, 0, 1)], max_image_tokens=budget, + return_tensors="pt") + thw = o["image_grid_thw"][0].tolist() + assert thw[0] == 1 + pv = o["pixel_values"].to(torch.bfloat16).view(torch.int16).numpy().astype(np.uint16) + assert pv.shape == (thw[1] * thw[2], 3 * T * IP.patch_size ** 2) + po = P(text=["<|begin_of_image|><|image|><|end_of_image|>"], + images=[torch.from_numpy(im).permute(2, 0, 1)], max_image_tokens=budget, + return_tensors="pt") + tid = po["input_ids"][0].to(torch.int32).numpy().astype(" @@ -726,6 +729,165 @@ TEST(gemma4_frames_are_sampled_as_the_reference_does) { } } +/* ================================================================== GLM-5.3's processor + * + * glm5_golden.h: Glm5NextProcessor as the checkpoint's processor_config.json sets it up + * (Glm5NextImageProcessor, torchvision backend): canvases, patch counts, patches as the tower reads + * them, and the token ids around a picture. The reference's patches are in merge-block order, as + * this processor's are, so they compare without reordering. */ +namespace { + +VisionConfig glm5_cfg(int32_t max_tok, int64_t max_patches) { + VisionConfig c; + c.family = Family::Glm5Next; + c.patch = kGlm5Patch; + c.merge = kGlm5Merge; + c.temporal = kGlm5Temporal; + c.min_image_tokens = kGlm5MinTok; + c.max_image_tokens = max_tok; + for (int i = 0; i < 3; ++i) { + c.mean[i] = kGlm5Mean[i]; + c.stdv[i] = kGlm5Std[i]; + } + const int64_t f2 = (int64_t)c.factor() * c.factor(); + c.image_min_pixels = c.video_min_pixels = kGlm5MinTok * f2; + c.image_max_pixels = c.video_max_pixels = (int64_t)max_tok * f2; + c.tok_image = kGlm5Image; + c.tok_video = 154855; + c.tok_start = kGlm5Start; + c.tok_end = kGlm5End; + c.max_patches = max_patches; + return c; +} + +} /* namespace */ + +/* Canvases: sides rounded up to 28, grown under 16 tokens, the budget's binary search over 8000 + * and over the 4096 a pass of 16384 patches holds, aspect ratios to 30000:1. */ +TEST(glm5_canvases_are_the_references) { + for (const GoldGlm5Size& g : kGoldGlm5Size) { + int64_t oh = 0, ow = 0, ch = 0, cw = 0; + std::string why; + CHECK_OK(glm5next_size(g.h, g.w, kGlm5Temporal, kGlm5Patch * kGlm5Merge, kGlm5MinTok, + g.budget, &oh, &ow, &ch, &cw, &why)); + if (oh != g.oh || ow != g.ow) + std::fprintf(stderr, " %lld x %lld at %d tokens: %lld x %lld, reference %lld x " + "%lld\n", (long long)g.h, (long long)g.w, g.budget, (long long)oh, + (long long)ow, (long long)g.oh, (long long)g.ow); + CHECK_EQ(oh, g.oh); + CHECK_EQ(ow, g.ow); + CHECK_EQ((oh / kGlm5Patch) * (ow / kGlm5Patch), g.patches); + CHECK(ch <= oh && cw <= ow); + } +} + +/* Whole pictures: padded only (448 x 448 is the one with no padding), grown under the floor (the + * 1 x 1, 61 x 97 and 3 x 400 ones), shrunk to a budget (900 x 1400 at 256 tokens, 2300 x 2900 at + * 8000), every patch value exactly, and <|begin_of_image|>, one <|image|> a token, + * <|end_of_image|>, as the reference processor expands the template's triple. */ +TEST(glm5_pictures_are_the_references) { + for (const GoldGlm5Pic& g : kGoldGlm5Pics) { + Processor p; + REQUIRE_EQ(p.init(glm5_cfg(g.budget, 32768), [](const std::string&) { + return std::vector{}; + }), RAD_OK); + std::shared_ptr it; + std::string why; + CHECK_OK(p.image_from(frame(g.f, g.h, g.w), &it, &why)); + REQUIRE(it != nullptr); + CHECK_EQ(it->grid_t, 1); + CHECK_EQ(it->grid_h, g.grid_h); + CHECK_EQ(it->grid_w, g.grid_w); + CHECK(it->rope_1d); + REQUIRE_EQ(it->patch_dim, (int64_t)3 * kGlm5Temporal * kGlm5Patch * kGlm5Patch); + REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * (size_t)it->patch_dim); + for (int i = 0; i < 8; ++i) CHECK_EQ(it->pixels[(size_t)i], g.head[i]); + if (fnv(it->pixels) != g.fnv) + std::fprintf(stderr, " picture %d x %d at %d tokens: patches differ\n", g.h, g.w, + g.budget); + CHECK_EQ(fnv(it->pixels), g.fnv); + const int64_t rows = (int64_t)g.grid_h * g.grid_w / (kGlm5Merge * kGlm5Merge); + CHECK_EQ(it->n_rows(), rows); + CHECK_EQ((int32_t)it->expand.size(), g.n_ids); + CHECK_EQ(fnv(it->expand), g.ids_fnv); + REQUIRE_EQ(it->expand.size(), (size_t)rows + 2); + CHECK_EQ(it->expand.front(), kGlm5Start); + CHECK_EQ(it->expand.back(), kGlm5End); + CHECK_EQ((int64_t)std::count(it->expand.begin(), it->expand.end(), kGlm5Image), rows); + REQUIRE_EQ(it->seg_at.size(), (size_t)1); + CHECK_EQ(it->seg_at[0], 1); + } +} + +/* The checkpoint's budget is lowered to what one encoder pass holds (a token is four patches), + * as a pixel band is; a pass that holds less than the floor is refused. Video and a request's own + * budget are refused by name. */ +TEST(glm5_budget_is_one_pass_and_pictures_only) { + Processor p; + REQUIRE_EQ(p.init(glm5_cfg(kGlm5MaxTok, 16384), [](const std::string&) { + return std::vector{}; + }), RAD_OK); + CHECK_EQ(p.config().max_image_tokens, 4096); + std::shared_ptr it; + std::string why; + CHECK_OK(p.image_from(frame(0, 2048, 2048), &it, &why)); + REQUIRE(it != nullptr); + CHECK_EQ(it->grid_h, 128); + CHECK_EQ(it->grid_w, 128); + CHECK_EQ(it->n_rows(), (int64_t)4096); + Processor q; + CHECK_EQ(q.init(glm5_cfg(kGlm5MaxTok, 60), [](const std::string&) { + return std::vector{}; + }), RAD_E_INVAL); + Video v; + v.frames.push_back(frame(0, 64, 64)); + v.frames.push_back(frame(1, 64, 64)); + CHECK_EQ(p.video_from(v, &it, &why), RAD_E_UNSUPPORTED); + CHECK(why.find("pictures, not video") != std::string::npos); + const uint8_t png_magic[8] = { 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a }; + CHECK_EQ(p.image(png_magic, sizeof png_magic, 280, &it, &why), RAD_E_UNSUPPORTED); + CHECK(why.find("--image-tokens") != std::string::npos); +} + +/* A converted GLM-5.3 container states the processor under `processor.image_processor.*` and + * the media ids under their own names, not Qwen's vision_start / vision_end. */ +TEST(glm5_reads_its_processor_from_the_container) { + const char* keys[] = { + "vision_config.model_type", "vision_config.patch_size", "vision_config.temporal_patch_size", + "vision_config.spatial_merge_size", "image_token_id", "video_token_id", + "image_start_token_id", "image_end_token_id", "processor.image_processor.min_image_tokens", + "processor.image_processor.max_image_tokens", "processor.image_processor.image_mean", + "processor.image_processor.image_std", "processor.image_processor.patch_expand_factor", + }; + const char* vals[] = { + "glm5_next_vision", "14", "2", "2", "154854", "154855", "154830", "154831", "16", "8000", + "0.48145465999999998 0.4578275 0.40821073000000002", + "0.26862954 0.26130258000000001 0.27577710999999999", "1", + }; + RadModelMeta m{}; + m.n_kv = (int)(sizeof(keys) / sizeof(keys[0])); + m.kv_key = keys; + m.kv_val = vals; + VisionConfig c; + std::string why; + CHECK_OK(c.from_meta(m, &why)); + CHECK(c.family == Family::Glm5Next); + CHECK_EQ(c.patch_dim(), (int64_t)1176); + CHECK_EQ(c.factor(), 28); + CHECK_EQ(c.min_image_tokens, 16); + CHECK_EQ(c.max_image_tokens, 8000); + CHECK_EQ(c.tok_image, kGlm5Image); + CHECK_EQ(c.tok_start, kGlm5Start); + CHECK_EQ(c.tok_end, kGlm5End); + for (int i = 0; i < 3; ++i) { + CHECK_EQ(c.mean[i], kGlm5Mean[i]); + CHECK_EQ(c.stdv[i], kGlm5Std[i]); + } + vals[12] = "2"; + CHECK_EQ(c.from_meta(m, &why), RAD_E_UNSUPPORTED); + CHECK(why.find("patch_expand_factor") != std::string::npos); +} + /* ================================================================== Pillow's arithmetic * * imaging_golden.h: Image.resize(LANCZOS) of an RGBA splitmix picture at sizes that shrink, grow, From b8885461ee8d05cc03f688b789c38500d6abd331 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:14 +0200 Subject: [PATCH 139/152] arch/common: GLM-5.3's vision tower -- an axial rotary, a 2 x 2 downsample through conv2d_unfold rad_block_glm_vision.h, transformers' Glm5NextVisionModel: the Conv3d patch embedding as a biased linear with no position table; 24 pre-norm blocks of RMSNorm, a biased qkv whose q and k are RMS-normed per head and turned by a 2-D rotary (qk_norm_rope's axial mode, the row on the first quarter of the frequencies and the column on the second, NeoX pairs across the whole head), attention within a picture, and a SwiGLU clipped at swiglu_limit (gate above, up both ways, with gate and up joined into one GEMM); post_layernorm; the 2 x 2 stride-2 downsample; the merger's bias-free projection, LayerNorm, exact GELU and clipped SwiGLU. The downsample needs no new op and no weight permutation: the processor stages patches in merge-block order, so conv2d_unfold (two input rows of two patches a block) writes each merged block as one row in the checkpoint weight's own (channel, kernel row, kernel column) order, and the [4096, 1024, 2, 2] weight is read as a [4096, 4096] linear as stored. Every op has rows in libref, libavx and libr4d. Weights are replicated and RAD_ACCESS_PER_REQUEST, a group a block, as rad_block_vit.h's are; a sizing declare sizes the activations at the probe's rows and declares nothing to the core. A tower with another activation, rotary, no swiglu_limit, no attention bias or rows of another width than the model's is refused by name. Co-Authored-By: Claude Opus 5.5 --- arch/common/rad_block_glm_vision.h | 379 +++++++++++++++++++++++++++++ 1 file changed, 379 insertions(+) create mode 100644 arch/common/rad_block_glm_vision.h diff --git a/arch/common/rad_block_glm_vision.h b/arch/common/rad_block_glm_vision.h new file mode 100644 index 00000000..83b85ec6 --- /dev/null +++ b/arch/common/rad_block_glm_vision.h @@ -0,0 +1,379 @@ +/* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by + * glm5next. + * + * WHAT IT COMPUTES, per encoder pass (RadBatch::enc): + * + * x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a + * patch row is (channel, frame, y, x), no position + * table + * depth times: + * h = RMS(x) gain only + * q, k, v = qkv(h) with bias; q and k RMS-normed per head with a + * gain, then a 2-D rotary over (row, column): + * `axial` over NeoX pairs (i, i + head_dim / 2), + * the row on the first head_dim / 4 frequencies and + * the column on the next, each on its own ladder + * x += proj(attn(q, k, v)) full attention within a segment (one picture) + * x += down(silu(min(g, L)) * clamp(u, -L, L)), g | u = gate_up(RMS(x)) all with bias + * y = RMS(x) post_layernorm + * d = conv2d(y viewed [rows / 2, 2, 2, width], 2 x 2, stride 2) + bd the downsample: one row + * a merged block of merge x merge patches + * out = down'(silu(min(g', L)) * clamp(u', -L, L)), g' | u' = gate_up'(gelu(LN(proj'(d)))) + * the merger: no biases but the LayerNorm's, exact + * GELU, the clip of the blocks + * + * which is the reference module for module. The processor stages patches in merge-block order (the + * merge x merge patches of one output row consecutive), so the downsample's input view is the + * reference's own: `conv2d_unfold` writes each merged block's receptive field as one row, its + * columns in the checkpoint weight's order (channel, kernel row, kernel column), and the weight is + * read as stored. Every linear with a bias is `gemm_nt_bias`, its residual in the epilogue. + * + * Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the + * weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx:: + * max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's + * step and nothing is declared to the core. */ +#ifndef RAD_BLOCK_GLM_VISION_H +#define RAD_BLOCK_GLM_VISION_H + +#include "rad_arch.h" + +#include +#include +#include +#include + +namespace rad { +namespace arch { + +struct GlmVision { + /* Geometry, from the container's vision_config. */ + int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0; + int64_t chans = 0, merge = 0, n_embd = 0, proj_ff = 0, patch_dim = 0, P = 0; + double eps = 1e-5, theta = 10000.0, limit = 0.0; + bool on = false; + + struct Layer { + rad_weight n1 = 0, qkv_w = 0, qkv_b = 0, q_norm = 0, k_norm = 0, out_w = 0, out_b = 0; + rad_weight n2 = 0, gu_w = 0, gu_b = 0, down_w = 0, down_b = 0; + rad_op op_n1 = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_proj = 0, op_n2 = 0, op_gu = 0; + rad_op op_act = 0, op_down = 0; + }; + std::vector L; + rad_weight w_patch = 0, b_patch = 0, w_post = 0, w_ds = 0, b_ds = 0; + rad_weight w_mproj = 0, w_mln = 0, b_mln = 0, w_mgu = 0, w_mdown = 0; + rad_op op_patch = 0, op_post = 0, op_unfold = 0, op_ds = 0, op_mproj = 0, op_mln = 0; + rad_op op_gelu = 0, op_mgu = 0, op_mact = 0, op_mdown = 0; + rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_post = 0, b_unf = 0; + rad_buf b_d = 0, b_m = 0, b_mgu = 0, b_mff = 0, b_out = 0; + char sec[48] = {}; + + /* Whether the container carries GLM-5.3's tower. */ + static bool present(const RadModelMeta* m) { + const char* t = rad_meta_gets(m, "vision_config.model_type", ""); + return t && !std::strcmp(t, "glm5_next_vision"); + } + + int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, + int64_t model_embd, int first_group); + void step(RadCtx* c, const RadBatch* batch) const; +}; + +inline int GlmVision::declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, + Names& nm, int64_t model_embd, int first_group) { + on = false; + if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK; + + depth = rad_meta_geti(m, "vision_config.depth", 0); + width = rad_meta_geti(m, "vision_config.hidden_size", 0); + heads = rad_meta_geti(m, "vision_config.num_heads", 0); + ff = rad_meta_geti(m, "vision_config.intermediate_size", 0); + patch = rad_meta_geti(m, "vision_config.patch_size", 0); + temporal = rad_meta_geti(m, "vision_config.temporal_patch_size", 0); + chans = rad_meta_geti(m, "vision_config.in_channels", 3); + merge = rad_meta_geti(m, "vision_config.spatial_merge_size", 0); + n_embd = rad_meta_geti(m, "vision_config.out_hidden_size", 0); + proj_ff = rad_meta_geti(m, "vision_config.projection_intermediate_size", 0); + eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-5); + limit = rad_meta_getf(m, "vision_config.swiglu_limit", 0.0); + /* The checkpoint states no rotary; the reference's default is axial at 10000. */ + theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0); + const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial"); + const char* act = rad_meta_gets(m, "vision_config.hidden_act", ""); + const bool bias = rad_meta_geti(m, "vision_config.attention_bias", 1) != 0; + if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || temporal <= 0 || + chans <= 0 || merge <= 0 || n_embd <= 0 || proj_ff <= 0 || width % heads || + (width / heads) % 4 || !(eps > 0) || !(theta > 0)) { + fprintf(stderr, "radiance: glm5next: the container's vision_config is incomplete or " + "inconsistent (depth %lld, hidden %lld, heads %lld, ff %lld, patch %lld, " + "merge %lld, out %lld, projection %lld)\n", (long long)depth, + (long long)width, (long long)heads, (long long)ff, (long long)patch, + (long long)merge, (long long)n_embd, (long long)proj_ff); + return RAD_E_INVAL; + } + /* The clipped SwiGLU, the axial rotary and the biased linears are what this tower is; a + * checkpoint that turns one of them off is another tower. */ + if (std::strcmp(act, "silu") || !(limit > 0) || !std::isfinite(limit) || + std::strcmp(rt, "axial") || !bias) { + fprintf(stderr, "radiance: glm5next: this vision tower has a '%s' activation, swiglu_limit " + "%g, a '%s' rotary or no attention bias; it serves silu, a positive " + "limit, axial and biased linears\n", act, limit, rt); + return RAD_E_UNSUPPORTED; + } + /* The merger's rows replace token embeddings, so they must be the model's width. */ + if (n_embd != model_embd) { + fprintf(stderr, "radiance: glm5next: the vision tower emits %lld-wide rows and the model " + "embeds %lld-wide tokens\n", (long long)n_embd, (long long)model_embd); + return RAD_E_INVAL; + } + head_dim = width / heads; + patch_dim = chans * temporal * patch * patch; + std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4), + (long long)(head_dim / 4)); + + const int64_t mm = merge * merge; + P = ctx->max_enc_patches; + /* The longest segment attention may see: the real pass size, even in a sizing declare (see + * rad_block_vit.h). */ + const int64_t max_seg = P; + if (ctx->shape_probe) { + const int64_t r = std::min(P, ctx->max_tok); + P = std::max(mm, r / mm * mm); + } + if (P % mm) return RAD_E_SHAPE; + const int64_t R = P / mm; + const int ACC = RAD_ACCESS_PER_REQUEST; + + /* ---- weights, replicated: model-level groups for the stem, downsample and merger, one group + * a block from `first_group` on. gate and up are joined into one GEMM, gate first, as + * swiglu_clamped splits its operand. */ + auto copy = [&](const char* dn, const char* src, std::initializer_list shp, + RadWeightGroup g) -> rad_weight { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g); + }; + auto join = [&](const char* dn, const char* gate, const char* up, + std::initializer_list shp, RadWeightGroup g) -> rad_weight { + if (map_concat(b, dn, { gate, up }) < 0) return 0; + return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g); + }; + const char* V = "model.visual"; + w_patch = copy(nm.f("v.patch.weight"), nm.ckpt("%s.patch_embed.proj.weight", V), + { width, patch_dim }, grp_model()); + b_patch = copy(nm.f("v.patch.bias"), nm.ckpt("%s.patch_embed.proj.bias", V), { width }, + grp_model()); + L.assign((size_t)depth, Layer{}); + for (int64_t i = 0; i < depth; ++i) { + Layer& l = L[(size_t)i]; + const RadWeightGroup g = grp_layer(first_group + (int)i); + const int li = (int)i; + auto src = [&](const char* s) { return nm.ckpt("%s.blocks.%d.%s", V, li, s); }; + auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); }; + l.n1 = copy(dn("norm1.weight"), src("norm1.weight"), { width }, g); + l.qkv_w = copy(dn("qkv.weight"), src("attn.qkv.weight"), { 3 * width, width }, g); + l.qkv_b = copy(dn("qkv.bias"), src("attn.qkv.bias"), { 3 * width }, g); + l.q_norm = copy(dn("q_norm.weight"), src("attn.q_norm.weight"), { head_dim }, g); + l.k_norm = copy(dn("k_norm.weight"), src("attn.k_norm.weight"), { head_dim }, g); + l.out_w = copy(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g); + l.out_b = copy(dn("proj.bias"), src("attn.proj.bias"), { width }, g); + l.n2 = copy(dn("norm2.weight"), src("norm2.weight"), { width }, g); + l.gu_w = join(dn("gate_up.weight"), src("mlp.gate_proj.weight"), src("mlp.up_proj.weight"), + { 2 * ff, width }, g); + l.gu_b = join(dn("gate_up.bias"), src("mlp.gate_proj.bias"), src("mlp.up_proj.bias"), + { 2 * ff }, g); + l.down_w = copy(dn("down.weight"), src("mlp.down_proj.weight"), { width, ff }, g); + l.down_b = copy(dn("down.bias"), src("mlp.down_proj.bias"), { width }, g); + if (!l.n1 || !l.qkv_w || !l.qkv_b || !l.q_norm || !l.k_norm || !l.out_w || !l.out_b || + !l.n2 || !l.gu_w || !l.gu_b || !l.down_w || !l.down_b) + return RAD_E_INVAL; + } + w_post = copy(nm.f("v.post_norm.weight"), nm.ckpt("%s.post_layernorm.weight", V), { width }, + grp_model()); + /* [out, width, merge, merge] read as [out, width * merge^2]: conv2d_unfold's column order. */ + w_ds = copy(nm.f("v.downsample.weight"), nm.ckpt("%s.downsample.weight", V), + { n_embd, mm * width }, grp_model()); + b_ds = copy(nm.f("v.downsample.bias"), nm.ckpt("%s.downsample.bias", V), { n_embd }, + grp_model()); + w_mproj = copy(nm.f("v.merger.proj.weight"), nm.ckpt("%s.merger.proj.weight", V), + { n_embd, n_embd }, grp_model()); + w_mln = copy(nm.f("v.merger.norm.weight"), + nm.ckpt("%s.merger.post_projection_norm.weight", V), { n_embd }, grp_model()); + b_mln = copy(nm.f("v.merger.norm.bias"), nm.ckpt("%s.merger.post_projection_norm.bias", V), + { n_embd }, grp_model()); + w_mgu = join(nm.f("v.merger.gate_up.weight"), nm.ckpt("%s.merger.gate_proj.weight", V), + nm.ckpt("%s.merger.up_proj.weight", V), { 2 * proj_ff, n_embd }, grp_model()); + w_mdown = copy(nm.f("v.merger.down.weight"), nm.ckpt("%s.merger.down_proj.weight", V), + { n_embd, proj_ff }, grp_model()); + if (!w_patch || !b_patch || !w_post || !w_ds || !b_ds || !w_mproj || !w_mln || !b_mln || + !w_mgu || !w_mdown) + return RAD_E_INVAL; + + /* ---- activations. `post` is declared at merge x width: the norm writes P rows of `width` + * and conv2d_unfold reads the same bytes as P / merge rows of `merge` columns (dh rows of dw + * columns), the reference's view() with no copy. */ + b_x = decl_b(b, nm.f("v.x"), RAD_BF16, { P, width }); + b_h = decl_b(b, nm.f("v.h"), RAD_BF16, { P, width }); + b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, { P, 3 * width }); + b_att = decl_b(b, nm.f("v.att"), RAD_BF16, { P, width }); + b_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, { P, 2 * ff }); + b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff }); + b_post = decl_b(b, nm.f("v.post"), RAD_BF16, { P / merge, merge * width }); + b_unf = decl_b(b, nm.f("v.unf"), RAD_BF16, { R, mm * width }); + b_d = decl_b(b, nm.f("v.d"), RAD_BF16, { R, n_embd }); + b_m = decl_b(b, nm.f("v.m"), RAD_BF16, { R, n_embd }); + b_mgu = decl_b(b, nm.f("v.mgu"), RAD_BF16, { R, 2 * proj_ff }); + b_mff = decl_b(b, nm.f("v.mff"), RAD_BF16, { R, proj_ff }); + b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd }); + if (!b_x || !b_h || !b_qkv || !b_att || !b_gu || !b_ff || !b_post || !b_unf || !b_d || !b_m || + !b_mgu || !b_mff || !b_out) + return RAD_E_INVAL; + + auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, rad_weight w, rad_weight bw) -> rad_op { + return RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16"), RAD_STR("act", "none")), + RAD_WEIGHTS(w, bw)); + }; + auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op { + return RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto rms = [&](int64_t rows, rad_weight w) -> rad_op { + return RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_F64("eps", eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto swiglu = [&](int64_t rows, int64_t n) -> rad_op { + return RAD_OP(b, "swiglu_clamped", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_F64("limit", limit), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + }; + + op_patch = rw(b, gemm_b(P, width, patch_dim, w_patch, b_patch), {}, { b_x }); + for (Layer& l : L) { + l.op_n1 = rw(b, rms(P, l.n1), { b_x }, { b_h }); + l.op_qkv = rw(b, gemm_b(P, 3 * width, width, l.qkv_w, l.qkv_b), { b_h }, { b_qkv }); + l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "axial"), + RAD_INT("rotary_dim", head_dim), + RAD_STR("sections", sec)), + RAD_WEIGHTS(l.q_norm, l.k_norm)), + { b_qkv }, { b_qkv }); + l.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)), + RAD_INT("max_seqlen", max_seg)), + RAD_NOWEIGHTS), + { b_qkv }, { b_att }); + l.op_proj = rw(b, gemm_b(P, width, width, l.out_w, l.out_b), { b_att, b_x }, { b_x }); + l.op_n2 = rw(b, rms(P, l.n2), { b_x }, { b_h }); + l.op_gu = rw(b, gemm_b(P, 2 * ff, width, l.gu_w, l.gu_b), { b_h }, { b_gu }); + l.op_act = rw(b, swiglu(P, ff), { b_gu }, { b_ff }); + l.op_down = rw(b, gemm_b(P, width, ff, l.down_w, l.down_b), { b_ff, b_x }, { b_x }); + } + op_post = rw(b, rms(P, w_post), { b_x }, { b_post }); + /* Input rows are P / merge (one kernel row of merge patches each) and a segment's rows are its + * patches over merge, so a picture of whole merged blocks starts on an even row. */ + op_unfold = rw(b, RAD_OP(b, "conv2d_unfold", + RAD_PARAMS(RAD_RANGE("M", 1, P / merge), RAD_INT("width", merge), + RAD_INT("cin", width), RAD_INT("kh", merge), + RAD_INT("kw", merge), RAD_INT("stride", merge), + RAD_INT("pad", 0), RAD_INT("cu_div", merge), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_post }, { b_unf }); + op_ds = rw(b, gemm_b(R, n_embd, mm * width, w_ds, b_ds), { b_unf }, { b_d }); + op_mproj = rw(b, gemm(R, n_embd, n_embd, w_mproj), { b_d }, { b_m }); + /* torch.nn.LayerNorm's default eps: the merger states none. */ + op_mln = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd), + RAD_F64("eps", 1e-5), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_mln, b_mln)), + { b_m }, { b_d }); + op_gelu = rw(b, RAD_OP(b, "gelu", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_d }, { b_m }); + op_mgu = rw(b, gemm(R, 2 * proj_ff, n_embd, w_mgu), { b_m }, { b_mgu }); + op_mact = rw(b, swiglu(R, proj_ff), { b_mgu }, { b_mff }); + op_mdown = rw(b, gemm(R, n_embd, proj_ff, w_mdown), { b_mff }, { b_out }); + + if (!ctx->shape_probe) { + RadEncoderDecl e{}; + e.name = "vision"; + e.modalities = RAD_MM_IMAGE; + e.patch_dim = patch_dim; + e.merge = mm; + e.max_patches = P; + e.n_embd = n_embd; + e.out = b_out; + RAD_ARCH_TRY(rad_declare_encoder(b, &e)); + rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld clipped at %g, " + "patch %lld x %lld x %lld, %lld x %lld downsample, merger %lld; %lld patches a " + "pass -> %lld rows of %lld", (long long)depth, (long long)width, + (long long)heads, (long long)head_dim, (long long)ff, limit, (long long)temporal, + (long long)patch, (long long)patch, (long long)merge, (long long)merge, + (long long)proj_ff, (long long)P, (long long)R, (long long)n_embd); + } + on = true; + return RAD_OK; +} + +inline void GlmVision::step(RadCtx* c, const RadBatch* batch) const { + const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg; + const int64_t mm = merge * merge, Rn = Pn / mm; + if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0) { + rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or " + "more patches than it was declared for, or not whole merged rows"); + return; + } + /* Patches, coordinates (planes 0-1 a dense [2, P] of (row, column)) and segment boundaries, + * staged by the core. */ + const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim); + const RadOperand rc = praw2(batch->enc_coord, RAD_I32, 2, Pn); + const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1); + + RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, brows(b_x, Pn)); + for (const Layer& l : L) { + RAD_ISSUE_N(c, l.op_n1, Pn, brows(b_x, Pn), RAD_W(l.n1), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE, + brows(b_qkv, Pn)); + RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm)); + RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn), + bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn)); + RAD_ISSUE_N(c, l.op_proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b), + brows(b_x, Pn), brows(b_x, Pn)); + RAD_ISSUE_N(c, l.op_n2, Pn, brows(b_x, Pn), RAD_W(l.n2), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gu_w), RAD_W(l.gu_b), RAD_NONE, + brows(b_gu, Pn)); + RAD_ISSUE_N(c, l.op_act, Pn, brows(b_gu, Pn), brows(b_ff, Pn)); + RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b), + brows(b_x, Pn), brows(b_x, Pn)); + } + /* The norm writes Pn rows of `width`; the unfold reads them as Pn / merge rows. */ + RAD_ISSUE_N(c, op_post, Pn, brows(b_x, Pn), RAD_W(w_post), brows(b_post, Pn / merge)); + RAD_ISSUE_N(c, op_unfold, Pn / merge, brows(b_post, Pn / merge), cu, RAD_NONE, + brows(b_unf, Rn)); + RAD_ISSUE_N(c, op_ds, Rn, brows(b_unf, Rn), RAD_W(w_ds), RAD_W(b_ds), RAD_NONE, + brows(b_d, Rn)); + RAD_ISSUE_N(c, op_mproj, Rn, brows(b_d, Rn), RAD_W(w_mproj), brows(b_m, Rn)); + RAD_ISSUE_N(c, op_mln, Rn, brows(b_m, Rn), RAD_W(w_mln), RAD_W(b_mln), brows(b_d, Rn)); + RAD_ISSUE_N(c, op_gelu, Rn, brows(b_d, Rn), brows(b_m, Rn)); + RAD_ISSUE_N(c, op_mgu, Rn, brows(b_m, Rn), RAD_W(w_mgu), brows(b_mgu, Rn)); + RAD_ISSUE_N(c, op_mact, Rn, brows(b_mgu, Rn), brows(b_mff, Rn)); + RAD_ISSUE_N(c, op_mdown, Rn, brows(b_mff, Rn), RAD_W(w_mdown), brows(b_out, Rn)); +} + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_BLOCK_GLM_VISION_H */ From 2387a23e00b6786cc3b3c337653810b81aa7fa01 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:14 +0200 Subject: [PATCH 140/152] glm5next: pictures -- the tower last, its rows over the trunk's and the draft head's embeddings With the container's tower and an encoder budget (--mm-max-patches), glm5next declares rad_block_glm_vision.h's tower after every text and draft op, its weight groups from 46, past the MTP layer's; an encoder pass issues only the tower. The encoder's rows overwrite the placeholders' embeddings before the vocab-sharded lookup's reduction (MediaRows), in the trunk and in the draft head's own lookup (GlmMtp::declare_inputs with `media`), which is what SGLang feeds its draft model: without them the drafts read the placeholder's embedding and acceptance falls on a prompt with a picture. The model has no rotary, so nothing else changes in a step. The probe states the tower's merged block (enc_merge 4). glm5next_test: the tower only with an encoder budget, at one and eight ranks, its maps, groups, rotary, unfold and clips; the refusals; an encoder pass issues the tower and nothing else over two pictures; a prefill with a picture scatters its rows before the all-reduce in the trunk and in the draft head's history pass, a text step none; a sizing declare with the tower is the real graph. The operand-count and container cases run on the container with the tower. The pinned text graph and steps are unchanged. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- arch/common/rad_block_glm_mtp.h | 13 +- arch/glm5next/glm5next.cpp | 33 ++- tests/glm5next_test.cpp | 367 ++++++++++++++++++++++++++++++-- 3 files changed, 386 insertions(+), 27 deletions(-) diff --git a/arch/common/rad_block_glm_mtp.h b/arch/common/rad_block_glm_mtp.h index 964700f9..4e188626 100644 --- a/arch/common/rad_block_glm_mtp.h +++ b/arch/common/rad_block_glm_mtp.h @@ -2,7 +2,7 @@ * one MLA + indexer + MoE layer the plugin declares and steps itself. * * h = gather(the trunk's final hidden states, at the rows this pass continues from) - * e = embed(the token one position on) + * e = embed(the token one position on), the encoder's rows over its placeholders * x = eh_proj( concat( enorm(e), hnorm(h) ) ) the normalized embedding first * x += attention(norm(x)); the proposal rows: x += moe(norm(x)) <- the plugin's layer * h' = shared_head.norm(x); logits = the trunk's lm_head over h' @@ -20,6 +20,7 @@ #ifndef RAD_BLOCK_GLM_MTP_H #define RAD_BLOCK_GLM_MTP_H #include "rad_glm_tp.h" +#include "rad_block_vit.h" namespace rad { namespace arch { @@ -38,9 +39,13 @@ struct GlmMtp { rad_op op_prev = 0, op_embed = 0, op_embed_ar = 0, op_en = 0, op_hn = 0, op_eh = 0; rad_op op_residual = 0, op_select = 0, op_back = 0; rad_op op_norm = 0, op_copy = 0, op_head = 0; + MediaRows mrows{}; - /* The buffers, the weights, and the ops up to the layer's input. */ - int declare_inputs(RadBuilder* b, const Geom& geom, const Wire& wire) { + /* The buffers, the weights, and the ops up to the layer's input. `media`: the encoder's rows + * replace the placeholders' embeddings, as the target's do (SGLang feeds its draft model the + * target's image rows); without them the drafts read the placeholder's embedding and + * acceptance falls on a prompt with a picture. */ + int declare_inputs(RadBuilder* b, const Geom& geom, const Wire& wire, bool media) { g = geom; w = wire; if (!b || !w.final_hidden || !w.logits || !w.token || !w.head || g.max_spec < 1) @@ -78,6 +83,7 @@ struct GlmMtp { RAD_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(w.token)), {}, { embedding }); + if (media) RAD_ARCH_TRY(mrows.declare(b, g.max_tok, 4096, embedding)); op_embed_ar = GlmTp::reduce(b, g, embedding, true); op_en = rmsnorm(b, en, embedding, concat); op_hn = rmsnorm(b, hn, hidden, concat); @@ -143,6 +149,7 @@ struct GlmMtp { praw(batch->out_ids, RAD_I32, batch->n_out), brows(hidden, batch->n_out)); RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w.token), brows(embedding, T)); + mrows.step(c, batch, embedding, T); if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * 4096, brows(embedding, T), RAD_NONE); RAD_ISSUE_N(c, op_en, T, brows(embedding, T), RAD_W(en), bcol(concat, 0, 4096, T)); RAD_ISSUE_N(c, op_hn, T, brows(hidden, T), RAD_W(hn), bcol(concat, 4096, 4096, T)); diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index e0bf619e..0b535c51 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -1,8 +1,9 @@ /* glm5next -- GLM-5.3-Flash (`model_type: glm5_next`) from AMD's Quark MXFP4 export: four mHC * residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers behind a DSA indexer, * 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 - * scales, each weight served as the container stores it; its MTP layer is a serial drafter. - * docs/ARCHITECTURES.md describes the model and its traps. + * scales, each weight served as the container stores it; its MTP layer is a serial drafter, and + * its vision tower is declared when the container carries it and the deployment asks for an + * encoder. docs/ARCHITECTURES.md describes the model and its traps. * * The blocks live in arch/common (installed as ), one a file: * @@ -12,6 +13,7 @@ * rad_block_glm_indexer.h GlmIndexer the DSA indexer, DsaCache its key cache and selection * rad_block_glm_router.h GlmRouter the correction-bias router (through MoeFP8) * rad_block_glm_mtp.h GlmMtp the draft head around the plugin's layer 45 + * rad_block_glm_vision.h GlmVision the tower, MediaRows its rows over the embeddings * rad_glm_tp.h GlmTp the shards, the row runs and the split thresholds * * This file declares the buffers the blocks share, places the blocks and issues the step's @@ -23,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -61,6 +64,10 @@ struct Model { bool have_mtp = false; GlmMtp mtp{}; Layer draft{}; + /* Media: the tower, and its rows over the trunk's embedding (the draft head scatters its own). */ + bool media = false; + GlmVision vit{}; + MediaRows mrows{}; }; static std::unique_ptr models[MAX_RANKS]; static thread_local std::unique_ptr probe_model; @@ -416,6 +423,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(m.token)), {}, { m.x }); + // The encoder's rows overwrite the lookup before its reduction (MediaRows). + m.media = GlmVision::present(meta) && ctx->max_enc_patches > 0; + if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, 4096, m.x)); m.embed_ar = GlmTp::reduce(b, g, m.x, true); m.expand = copy(b, g, m.x, m.h0); m.layers.resize(45); @@ -442,14 +452,18 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c { m.logit_input }, { m.logits }); if (g.max_spec > 0) { GlmMtp::Wire tw{ m.final_hidden, m.logits, m.token, m.head }; - RAD_ARCH_TRY(m.mtp.declare_inputs(b, g, tw)); + RAD_ARCH_TRY(m.mtp.declare_inputs(b, g, tw, m.media)); RAD_ARCH_TRY(layer(b, m, m.draft, m.mtp.nm, 45, true)); RAD_ARCH_TRY(m.mtp.declare_head(b)); m.have_mtp = true; } + // The tower, last: an encoder pass issues nothing else, so its activations share the arena + // with every buffer above. Its weight groups follow the 45 layers and the MTP layer's. + if (m.media) RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, 4096, 46)); rad_note(b, - "GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP %s", - world, m.have_mtp ? "enabled" : "disabled"); + "GLM-5.3: TP%d, 45 mHC layers, 34 KDA + 11 sparse MLA, mixed MXFP4/FP8, native MTP " + "%s, vision %s", + world, m.have_mtp ? "enabled" : "disabled", m.media ? "enabled" : "disabled"); return RAD_OK; } @@ -484,8 +498,9 @@ static void draft_pass(RadCtx* c, Model& m, const RadBatch* batch) { static void step(RadCtx* c, const RadBatch* batch) { auto& m = *models[rad_rank(c)]; const int64_t T = batch->n_tok; + // An encoder pass runs only the vision tower (RadBatch::enc). if (batch->enc) { - rad_step_fail(c, "GLM vision is not implemented by this text plugin"); + m.vit.step(c, batch); return; } if (batch->draft_pass) { @@ -493,6 +508,7 @@ static void step(RadCtx* c, const RadBatch* batch) { return; } RAD_ISSUE_N(c, m.embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.token), brows(m.x, T)); + m.mrows.step(c, batch, m.x, T); if (m.embed_ar) RAD_ISSUE_N(c, m.embed_ar, T * 4096, brows(m.x, T), RAD_NONE); for (int i = 0; i < 4; ++i) RAD_ISSUE_N(c, m.expand, T, brows(m.x, T), bcol(m.h0, i * 4096, 4096, T)); @@ -521,6 +537,11 @@ static void step(RadCtx* c, const RadBatch* batch) { static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (!meta || !out) return RAD_E_INVAL; if (cfg(meta, "num_nextn_predict_layers", 0) == 1) out->draft_depth = GlmMtp::kDepth; + // The tower's merged block, so a pass size the core picks itself is whole output rows. + if (GlmVision::present(meta)) { + const int64_t k = rad_meta_geti(meta, "vision_config.spatial_merge_size", 0); + if (k > 0) out->enc_merge = k * k; + } out->shape_probe_ok = 1; return RAD_OK; } diff --git a/tests/glm5next_test.cpp b/tests/glm5next_test.cpp index 7bd28b4b..c6ce1adf 100644 --- a/tests/glm5next_test.cpp +++ b/tests/glm5next_test.cpp @@ -1383,11 +1383,12 @@ TEST(glm53_is_the_pinned_graph_and_steps) { } } -/* ==================================================================== fixtures */ +/* ==================================================================== GLM-5.3's vision tower */ namespace { -/* GLM-5.3-Flash's container keys, the four the plugin reads. */ -MetaKV glm53_meta() { +/* GLM-5.3-Flash's container keys with its vision_config, the tower cut to two blocks at the real + * widths, enough to see a block repeat. */ +MetaKV glm53_vl_meta() { RadModelMeta m{}; m.n_layers = 45; m.n_embd = 4096; @@ -1395,12 +1396,25 @@ MetaKV glm53_meta() { m.rms_eps = 1e-5f; MetaKV k(m); k.set("num_nextn_predict_layers", "1").set("hc_mult", "4").set("n_routed_experts", "288") - .set("index_topk", "2048"); + .set("index_topk", "2048") + .set("vision_config.model_type", "glm5_next_vision") + .set("vision_config.depth", "2") + .set("vision_config.hidden_size", "1024") + .set("vision_config.num_heads", "16") + .set("vision_config.intermediate_size", "4096") + .set("vision_config.patch_size", "14") + .set("vision_config.temporal_patch_size", "2") + .set("vision_config.in_channels", "3") + .set("vision_config.spatial_merge_size", "2") + .set("vision_config.out_hidden_size", "4096") + .set("vision_config.projection_intermediate_size", "10240") + .set("vision_config.swiglu_limit", "10") + .set("vision_config.hidden_act", "silu") + .set("vision_config.attention_bias", "1") + .set("vision_config.rms_norm_eps", "1.0000000000000001e-05"); return k; } -/* The served container's encodings: block fp8 at f32 scales for the attention and dense linears - * and the MTP layer's experts, MXFP4 for the trunk's experts. */ void glm53_encs(RadBuilder& b) { const auto mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32); const auto fp8 = rad_enc_affine(RAD_F8E4M3, RAD_F32, 128, 128); @@ -1415,17 +1429,310 @@ void glm53_encs(RadBuilder& b) { { "ffn_down.weight", fp8 } }; } -/* A deployment of 512 rows a step, four sequences, 4k of context. */ -RadBuildCtx glm53_ctx(int rank, int world, int max_spec = 3) { +RadBuildCtx glm53_vl_ctx(int rank, int world, int64_t patches, int max_spec = 3) { RadBuildCtx c = spec_ctx(rank, world, max_spec); c.max_tok = 512; c.max_seqs = 4; c.max_ctx = 4096; + c.max_enc_patches = patches; return c; } } /* namespace */ +/* The tower is declared only with an encoder budget, last, its weights replicated in their own + * groups past the 45 layers and the MTP layer's, its 2-D rotary the axial one at sixteen + * frequencies an axis, gate and up joined gate first; one scatter over the trunk's embedding and + * one over the draft head's. */ +TEST(glm53_declares_its_vision_tower_when_the_engine_asks_for_it) { + MetaKV mk = glm53_vl_meta(); + for (int world : { 1, 8 }) { + const int rank = world - 1; + { + RadBuilder b; + glm53_encs(b); + RadBuildCtx ctx = glm53_vl_ctx(rank, world, 0); + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK(b.encoder_name.empty()); + CHECK(find_w(b, "v.patch.weight") == nullptr); + CHECK_EQ(count_op(b, "scatter_rows"), 0); + } + RadBuilder b; + glm53_encs(b); + RadBuildCtx ctx = glm53_vl_ctx(rank, world, 1024); + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + const auto& m = *glm5next::models[rank]; + CHECK_EQ(b.encoder_name, std::string("vision")); + CHECK_EQ(b.encoder.modalities, (uint32_t)RAD_MM_IMAGE); + CHECK_EQ(b.encoder.patch_dim, 3 * 2 * 14 * 14); + CHECK_EQ(b.encoder.merge, 4); + CHECK_EQ(b.encoder.max_patches, 1024); + CHECK_EQ(b.encoder.n_embd, 4096); + const RecBuf* out = find_b(b, "v.out"); + REQUIRE(out != nullptr); + CHECK_EQ(out->d.shape[0], 256); + CHECK_EQ(out->d.shape[1], 4096); + CHECK_EQ(count_op(b, "scatter_rows"), 2); + CHECK(m.mrows.op < m.embed_ar || world == 1); + CHECK(m.mtp.mrows.op > m.mtp.op_embed); + /* Declared after every text and draft op. */ + CHECK(m.vit.op_patch > m.mtp.op_head); + + /* 2 stem + 12 a block + 8 downsample and merger, each from model.visual.*. */ + int nv = 0; + for (const auto& w : b.weights) + if (w.name.rfind("v.", 0) == 0) { + ++nv; + const RecMap* mp = find_map(b, w.name); + REQUIRE(mp != nullptr); + for (const auto& s : mp->src) CHECK(s.rfind("model.visual.", 0) == 0); + CHECK_EQ(w.d.shard, (int)RAD_SHARD_NONE); + CHECK(w.d.group.layer == -1 || w.d.group.layer >= 46); + } + CHECK_EQ(nv, 2 + 12 * 2 + 8); + const RecWeight* blk1 = find_w(b, "v.blk.1.qkv.weight"); + REQUIRE(blk1 != nullptr); + CHECK_EQ(blk1->d.group.layer, 47); + const RecMap* gu = find_map(b, "v.blk.1.gate_up.weight"); + REQUIRE(gu != nullptr); + CHECK_EQ(gu->mode, (int)RAD_MAP_CONCAT); + REQUIRE_EQ(gu->src.size(), (size_t)2); + CHECK_EQ(gu->src[0], std::string("model.visual.blocks.1.mlp.gate_proj.weight")); + CHECK_EQ(gu->src[1], std::string("model.visual.blocks.1.mlp.up_proj.weight")); + const RecWeight* ds = find_w(b, "v.downsample.weight"); + REQUIRE(ds != nullptr); + CHECK_EQ(ds->d.shape[0], 4096); + CHECK_EQ(ds->d.shape[1], 4096); + const RecWeight* pe = find_w(b, "v.patch.weight"); + REQUIRE(pe != nullptr); + CHECK_EQ(pe->d.shape[1], 1176); + + int qk = 0; + for (const auto& o : b.ops) + if (o.op == "qk_norm_rope") { + ++qk; + CHECK_EQ(pstr(&o, "mode"), std::string("axial")); + CHECK_EQ(pstr(&o, "sections"), std::string("16 16")); + CHECK_EQ(pint(&o, "head_dim"), 64); + CHECK_EQ(pint(&o, "rotary_dim"), 64); + CHECK_EQ(pint(&o, "n_head"), 16); + CHECK_EQ(pflt(&o, "theta"), 10000.0); + CHECK_EQ(o.w.size(), (size_t)2); + } + CHECK_EQ(qk, 2); + const RecOp* unf = find_op(b, "conv2d_unfold"); + REQUIRE(unf != nullptr); + CHECK_EQ(pint(unf, "width"), 2); + CHECK_EQ(pint(unf, "cin"), 1024); + CHECK_EQ(pint(unf, "kh"), 2); + CHECK_EQ(pint(unf, "stride"), 2); + CHECK_EQ(pint(unf, "cu_div"), 2); + int clipped_tower = 0, clipped_merger = 0; + for (const auto& o : b.ops) + if (o.op == "swiglu_clamped") { + clipped_tower += pint(&o, "n") == 4096; + clipped_merger += pint(&o, "n") == 10240; + CHECK_EQ(pflt(&o, "limit"), 10.0); + } + CHECK_EQ(clipped_tower, 2); + CHECK_EQ(clipped_merger, 1); + CHECK_EQ(count_op(b, "gelu"), 1); + int merger_ln = 0; + for (const auto& o : b.ops) merger_ln += o.op == "layernorm" && pint(&o, "n") == 4096; + CHECK_EQ(merger_ln, 1); + } + /* Without speculation the draft head and its scatter are not declared. */ + RadBuilder nb; + glm53_encs(nb); + RadBuildCtx nc = glm53_vl_ctx(0, 1, 1024, 0); + REQUIRE_EQ(glm5next::declare(&nb, mk.meta(), &nc), RAD_OK); + CHECK_EQ(count_op(nb, "scatter_rows"), 1); + RadArchProbe p{}; + CHECK_OK(glm5next::probe(mk.meta(), &p)); + CHECK_EQ(p.enc_merge, 4); +} + +/* What the tower does not serve is refused by name at declare, not computed as another model. */ +TEST(glm53_refuses_a_vision_tower_it_does_not_serve) { + const struct { const char* key; const char* val; int rc; } kCases[] = { + { "vision_config.hidden_act", "gelu", RAD_E_UNSUPPORTED }, + { "vision_config.rope_parameters.rope_type", "default", RAD_E_UNSUPPORTED }, + { "vision_config.out_hidden_size", "2048", RAD_E_INVAL }, + }; + for (const auto& kc : kCases) { + MetaKV mk = glm53_vl_meta(); + mk.set(kc.key, kc.val); + RadBuilder b; + glm53_encs(b); + RadBuildCtx ctx = glm53_vl_ctx(0, 1, 1024); + const int rc = stderr_of_rc([&] { return glm5next::declare(&b, mk.meta(), &ctx); }); + if (rc != kc.rc) fprintf(stderr, " %s = %s: %d\n", kc.key, kc.val, rc); + CHECK_EQ(rc, kc.rc); + } +} + +/* An encoder pass issues the tower and nothing else: the stem, two blocks, the post-norm, the + * downsample's unfold and GEMM, and the merger, over two pictures of 8 x 8 patches. The rotary + * reads the row and column planes, attention and the unfold the segment bounds. */ +TEST(a_glm53_encoder_pass_issues_the_tower_and_nothing_else) { + MetaKV mk = glm53_vl_meta(); + for (int world : { 1, 8 }) { + const int rank = world - 1; + RadBuilder b; + glm53_encs(b); + RadBuildCtx ctx = glm53_vl_ctx(rank, world, 1024); + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + static uint16_t pix[128 * 1176]; + static int32_t coord[4 * 128]; + static const int32_t cu[] = { 0, 64, 128 }; + RadBatch batch{}; + batch.enc = 1; + batch.enc_n_patch = 128; + batch.enc_pixels = pix; + batch.enc_coord = coord; + batch.enc_n_seg = 2; + batch.enc_cu = cu; + batch.enc_max_seg = 64; + RadCtx c{ .b = &b, .batch = &batch }; + c.rank = rank; + c.world = world; + glm5next::step(&c, &batch); + CHECK_LINT(b, &c); + CHECK(c.step_fail.empty()); + + std::vector want = { "gemm_nt_bias" }; + for (int l = 0; l < 2; ++l) + for (const char* s : { "rmsnorm", "gemm_nt_bias", "qk_norm_rope", "attn_dense", + "gemm_nt_bias", "rmsnorm", "gemm_nt_bias", "swiglu_clamped", + "gemm_nt_bias" }) + want.push_back(s); + for (const char* s : { "rmsnorm", "conv2d_unfold", "gemm_nt_bias", "gemm_nt", "layernorm", + "gelu", "gemm_nt", "swiglu_clamped", "gemm_nt" }) + want.push_back(s); + CHECK_EQ(join(issued_ops(b, c)), join(want)); + CHECK_EQ(c.issues.back().n, 32); + const RecIssue* qk = issue_of(b, c, "qk_norm_rope"); + REQUIRE(qk != nullptr); + CHECK(qk->opd[1].raw == coord); + CHECK_EQ(qk->opd[1].rows, 2); + CHECK_EQ(qk->opd[1].cols, 128); + const RecIssue* at = issue_of(b, c, "attn_dense"); + REQUIRE(at != nullptr); + CHECK_EQ(at->opd[0].cols, 1024); + CHECK_EQ(at->opd[1].offset, 1024); + CHECK_EQ(at->opd[2].offset, 2048); + CHECK(at->opd[3].raw == cu); + /* The unfold reads the post-norm as 64 rows of two patches and writes 32 merged rows. */ + const RecIssue* un = issue_of(b, c, "conv2d_unfold"); + REQUIRE(un != nullptr); + CHECK_EQ(un->n, 64); + CHECK_EQ(un->opd[0].rows, 64); + CHECK(un->opd[1].raw == cu); + CHECK_EQ(un->opd[3].rows, 32); + + RadBatch big = batch; + big.enc_n_patch = 2048; + RadCtx c2{ .b = &b, .batch = &big }; + glm5next::step(&c2, &big); + CHECK(!c2.step_fail.empty()); + CHECK(c2.issues.empty()); + } +} + +/* A prefill chunk whose tokens 1..4 are a picture's rows: the trunk writes them over the lookup + * before the embedding's all-reduce, and so does the draft head's history pass over its own + * lookup; a text-only step on the same program issues no scatter. */ +TEST(a_glm53_step_with_a_picture_scatters_its_rows_in_the_trunk_and_the_draft_head) { + MetaKV mk = glm53_vl_meta(); + for (int world : { 1, 4 }) { + RadBuilder b; + glm53_encs(b); + RadBuildCtx ctx = glm53_vl_ctx(0, world, 1024); + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + static const int32_t rows[] = { 1, 2, 3, 4 }; + static uint16_t embd[4 * 4096]; + auto pf = kit(b, {}, { 6 }); + pf->b.n_mm_rows = 4; + pf->b.mm_rows = rows; + pf->b.mm_embd = embd; + auto his = history_pass(b, *pf); + his->b.n_mm_rows = 4; + his->b.mm_rows = rows; + his->b.mm_embd = embd; + auto v = run_passes(b, glm5next::step, { pf.get(), his.get() }, 0, world); + CHECK_PASSES(b, v); + for (int p = 0; p < 2; ++p) { + const std::vector ops = issued_ops(b, *v[(size_t)p]); + REQUIRE(ops.size() > 3); + const size_t at = (size_t)(std::find(ops.begin(), ops.end(), "embed_lookup") - + ops.begin()); + REQUIRE(at + 1 < ops.size()); + CHECK_EQ(ops[at + 1], std::string("scatter_rows")); + if (world > 1) CHECK_EQ(ops[at + 2], std::string("all_reduce")); + const RecIssue* sc = issue_of(b, *v[(size_t)p], "scatter_rows"); + REQUIRE(sc != nullptr); + CHECK_EQ(sc->n, 4); + CHECK(sc->opd[0].raw == embd); + CHECK_EQ(sc->opd[0].cols, 4096); + CHECK(sc->opd[1].raw == rows); + CHECK_EQ(sc->opd[2].rows, 6); + CHECK_EQ(count_issued(ops, "scatter_rows"), 1); + } + auto dc = kit(b, { 1, 1 }, {}); + auto t = run_passes(b, glm5next::step, { dc.get() }, 0, world); + CHECK_PASSES(b, t); + CHECK(issue_of(b, *t[0], "scatter_rows") == nullptr); + } +} + +/* A sizing declare with the tower is the real graph at fewer rows: the same ops with the same + * fixed parameters (the attention's longest segment included), and nothing declared to the core. */ +TEST(glm53_sizing_declares_with_the_vision_tower_match_the_real_graph) { + MetaKV mk = glm53_vl_meta(); + for (int64_t R : { 256 }) { + RadBuildCtx c = glm53_vl_ctx(3, 8, 16384); + c.max_tok = 4096; + c.max_seqs = 8; + c.max_ctx = 32768; + RadBuilder full; + glm53_encs(full); + REQUIRE_EQ(glm5next::declare(&full, mk.meta(), &c), RAD_OK); + CHECK_EQ(full.encoder_name, std::string("vision")); + RadBuildCtx p = c; + p.max_tok = R; + p.shape_probe = 1; + RadBuilder small; + glm53_encs(small); + REQUIRE_EQ(glm5next::declare(&small, mk.meta(), &p), RAD_OK); + CHECK(small.encoder_name.empty()); + REQUIRE_EQ(small.ops.size(), full.ops.size()); + int differ = 0; + for (size_t i = 0; i < full.ops.size(); ++i) { + if (small.ops[i].op != full.ops[i].op) { ++differ; continue; } + REQUIRE_EQ(small.ops[i].p.size(), full.ops[i].p.size()); + for (size_t k = 0; k < full.ops[i].p.size(); ++k) { + const RecParam& a = full.ops[i].p[k]; + const RecParam& q = small.ops[i].p[k]; + if (a.kind == RAD_P_RANGE) continue; + if (full.ops[i].op == "qsa_work" && a.key == "work" && q.ival <= a.ival) continue; + if (a.ival != q.ival || a.sval != q.sval || a.dval != q.dval) { + fprintf(stderr, " R %lld: op %zu '%s' param '%s': %lld real, %lld small\n", + (long long)R, i, full.ops[i].op.c_str(), a.key.c_str(), a.ival, + q.ival); + ++differ; + } + } + } + CHECK_EQ(differ, 0); + REQUIRE_EQ(small.bufs.size(), full.bufs.size()); + for (size_t i = 0; i < full.bufs.size(); ++i) { + for (uint32_t d = 1; d < full.bufs[i].d.rank; ++d) + CHECK_EQ(small.bufs[i].d.shape[d], full.bufs[i].d.shape[d]); + CHECK(small.bufs[i].d.shape[0] <= full.bufs[i].d.shape[0]); + } + } +} + RAD_TEST_MAIN() /* ==================================================================== the row rule */ @@ -1537,13 +1844,13 @@ TEST(glm53_issues_every_op_with_the_operand_count_its_schema_declares) { fprintf(stderr, " no kernel library under $RADIANCE_HOME/kernels; nothing to count\n"); return; } - MetaKV mk = glm53_meta(); + MetaKV mk = glm53_vl_meta(); std::set uncovered, wrong; for (int world : { 8, 1 }) { const int rank = world == 8 ? 3 : 0; RadBuilder b; glm53_encs(b); - RadBuildCtx ctx = glm53_ctx(rank, world, 5); + RadBuildCtx ctx = glm53_vl_ctx(rank, world, 1024, 5); ctx.max_tok = 4096; ctx.max_seqs = 8; ctx.max_ctx = 65536; @@ -1616,11 +1923,11 @@ TEST(glm53_issues_every_op_with_the_operand_count_its_schema_declares) { /* ==================================================================== the container's names */ namespace { -/* The served container, GLM-5.3-Flash-Quark-MXFP4.rad, as `rad-info -v` lists it: each weight's - * name and stored encoding, for the model, one KDA layer (0, with the dense feed-forward of - * layers 0 to 2), one MLA layer (3, with its experts 0 and 287) and the MTP layer under its - * `mtp.` scope (the fp8 linears of its layer under `mtp.mtp.`, as the converter wrote them). The - * other layers of a kind carry the same names at their own index. */ +/* The served container, GLM-5.3-Flash-Quark-MXFP4-vision.rad, as `rad-info -v` lists it: each + * weight's name and stored encoding, for the model, one KDA layer (0, with the dense feed-forward + * of layers 0 to 2), one MLA layer (3, with its experts 0 and 287), the MTP layer under its + * `mtp.` scope (the fp8 linears of its layer under `mtp.mtp.`, as the converter wrote them) and + * the tower's first block. The other layers of a kind carry the same names at their own index. */ struct ContainerWeight { const char* name; const char* enc; @@ -1629,6 +1936,16 @@ const ContainerWeight kGlm53Container[] = { { "output.weight", "bf16" }, { "output_norm.weight", "bf16" }, { "token_embd.weight", "bf16" }, + { "v.downsample.bias", "bf16" }, + { "v.downsample.weight", "bf16" }, + { "v.merger.down.weight", "bf16" }, + { "v.merger.gate_up.weight", "bf16" }, + { "v.merger.norm.bias", "bf16" }, + { "v.merger.norm.weight", "bf16" }, + { "v.merger.proj.weight", "bf16" }, + { "v.patch.bias", "bf16" }, + { "v.patch.weight", "bf16" }, + { "v.post_norm.weight", "bf16" }, { "blk.0.attn_beta.weight", "bf16" }, { "blk.0.attn_forget_a.weight", "bf16" }, { "blk.0.attn_forget_b.weight", "bf16" }, @@ -1706,6 +2023,18 @@ const ContainerWeight kGlm53Container[] = { { "mtp.blk.45.ffn_down_exps.0.weight", "fp8_e4m3*f32[128x128]" }, { "mtp.blk.45.ffn_gate_up_exps.287.weight", "fp8_e4m3*f32[128x128]" }, { "mtp.blk.45.ffn_down_exps.287.weight", "fp8_e4m3*f32[128x128]" }, + { "v.blk.0.down.bias", "bf16" }, + { "v.blk.0.down.weight", "bf16" }, + { "v.blk.0.gate_up.bias", "bf16" }, + { "v.blk.0.gate_up.weight", "bf16" }, + { "v.blk.0.k_norm.weight", "bf16" }, + { "v.blk.0.norm1.weight", "bf16" }, + { "v.blk.0.norm2.weight", "bf16" }, + { "v.blk.0.proj.bias", "bf16" }, + { "v.blk.0.proj.weight", "bf16" }, + { "v.blk.0.q_norm.weight", "bf16" }, + { "v.blk.0.qkv.bias", "bf16" }, + { "v.blk.0.qkv.weight", "bf16" }, }; RadEncoding container_enc(const std::string& e) { @@ -1718,7 +2047,7 @@ RadEncoding container_enc(const std::string& e) { /* The table above expanded to every layer: a KDA layer's names from layer 0 (its dense * feed-forward in layers 0 to 2 only), an MLA layer's from layer 3, the MoE's from layer 3 into - * every layer from 3. `encs` answers rad_weight_encoding as + * every layer from 3, the tower's 24 blocks from block 0. `encs` answers rad_weight_encoding as * the container would; an expert's key stands without its index, so every expert matches it, * and the keys run longest first, because the fake matches a key anywhere in the name asked * (`output.weight` is inside `blk.3.attn_output.weight`). */ @@ -1755,6 +2084,8 @@ const Glm53Container& glm53_container() { n.find(".glm_router.") != std::string::npos; for (int l = 3; l < 45; ++l) if (moe || l % 4 == 3) put(at_layer(n, 6, l), w.enc); + } else if (n.rfind("v.blk.0.", 0) == 0) { + for (int l = 0; l < 24; ++l) put("v.blk." + std::to_string(l) + "." + n.substr(8), w.enc); } else { put(n, w.enc); } @@ -1784,12 +2115,12 @@ std::string as_expert_zero(std::string n) { * the eight-card start. */ TEST(glm53_declares_the_served_containers_names_and_their_encodings) { const Glm53Container& c = glm53_container(); - MetaKV mk = glm53_meta(); + MetaKV mk = glm53_vl_meta(); for (int world : { 8, 1 }) { RadBuilder b; b.kv_block = 4; b.encs = c.encs; - RadBuildCtx ctx = glm53_ctx(world == 8 ? 5 : 0, world); + RadBuildCtx ctx = glm53_vl_ctx(world == 8 ? 5 : 0, world, 1024); REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); std::map declared; for (const RecWeight& w : b.weights) declared[w.name] = &w; From 1f7e1faa73bb2bd03b2881fe9c73c52ed4e62348 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:14 +0200 Subject: [PATCH 141/152] tests: GLM-5.3's template renders a picture as the reference does; its tower against transformers The golden renders gain GLM-5.3's picture between text: the engine's media marker becomes <|begin_of_image|><|image|><|end_of_image|> with no separator, as the template's own emit_image() writes it (tests/mkchatgolden.py). tests/glm5_vision_reference.py runs transformers' tower alone on the CPU (only model.visual.*, about 3 GB) over the pictures of one encoder pass and writes the processor's patches and the merger's rows, with --taps the tensors on the way (the patch embedding, block 0's q and k after the rotary, blocks 0, 11 and 23, the post-norm, the downsample), in bf16 or f32. With --compare it checks what an engine wrote with RADIANCE_DEBUG_MM_DUMP: patches bit for bit, rows to a cosine of 0.99 and a median per-row relative error of 0.08 against the bf16 reference. Co-Authored-By: Claude Opus 5.5 --- tests/chat_test.cpp | 2 +- .../glm53/golden/a_picture_between_text.txt | 1 + tests/data/chat/golden/cases.json | 4 +- tests/glm5_vision_reference.py | 183 ++++++++++++++++++ 4 files changed, 187 insertions(+), 3 deletions(-) create mode 100644 tests/data/chat/glm53/golden/a_picture_between_text.txt create mode 100644 tests/glm5_vision_reference.py diff --git a/tests/chat_test.cpp b/tests/chat_test.cpp index 5a2bd8db..7d7ac5f8 100644 --- a/tests/chat_test.cpp +++ b/tests/chat_test.cpp @@ -289,7 +289,7 @@ TEST(every_shipped_template_renders_as_reference_jinja_does) { } } /* Five templates, every case each one renders. */ - CHECK(compared >= 73); + CHECK(compared >= 74); } /* ------------------------------------------------------------------ reading the reply back */ diff --git a/tests/data/chat/glm53/golden/a_picture_between_text.txt b/tests/data/chat/glm53/golden/a_picture_between_text.txt new file mode 100644 index 00000000..a7ee2bd5 --- /dev/null +++ b/tests/data/chat/glm53/golden/a_picture_between_text.txt @@ -0,0 +1 @@ +[gMASK]<|system|>Reasoning Effort: Max<|user|>Describe<|begin_of_image|><|image|><|end_of_image|>briefly.<|assistant|> \ No newline at end of file diff --git a/tests/data/chat/golden/cases.json b/tests/data/chat/golden/cases.json index 9c7aaaf1..8ef53395 100644 --- a/tests/data/chat/golden/cases.json +++ b/tests/data/chat/golden/cases.json @@ -5,7 +5,7 @@ "qwen3.6": { "bos": "", "eos": "<|im_end|>", "media": "<|vision_start|><|image_pad|><|vision_end|>" }, "minicpm5": { "bos": "", "eos": "", "media": "" }, "gemma4": { "bos": "", "eos": "", "media": "<|image|>" }, - "glm53": { "bos": "", "eos": "<|endoftext|>", "media": "" } + "glm53": { "bos": "", "eos": "<|endoftext|>", "media": "<|begin_of_image|><|image|><|end_of_image|>" } }, "tools": [ { "type": "function", "function": { "name": "read", "description": "Read a file.", @@ -117,7 +117,7 @@ "kwargs": { "reasoning_effort": "high" }, "messages": [ { "role": "user", "content": "Hi." } ] }, { "name": "a_picture_between_text", - "models": ["qwen3.8", "qwen3.6", "gemma4"], + "models": ["qwen3.8", "qwen3.6", "gemma4", "glm53"], "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe" }, diff --git a/tests/glm5_vision_reference.py b/tests/glm5_vision_reference.py new file mode 100644 index 00000000..b682ff86 --- /dev/null +++ b/tests/glm5_vision_reference.py @@ -0,0 +1,183 @@ +"""glm5_vision_reference.py MODEL_DIR OUT_DIR IMAGE [IMAGE ...] [--dtype bfloat16|float32] [--taps] + [--max-image-tokens N] [--compare DUMP_DIR] + +Transformers' own GLM-5.3 vision tower, run on the CPU, as the reference arch/glm5next's tower is +checked against. Only `model.visual.*` is loaded (the checkpoint keeps the whole tower, bf16, in its +last shard), so this needs about 3 GB of memory, not the model's 180. + +All the pictures go through the tower in one call, as one encoder pass carries them: one attention +segment each. For each picture it writes, under OUT_DIR//: + + pix.bf16 the patches Glm5NextProcessor makes [P, 1176], merge-block order, bf16 -- the + layout core/mm stages and RADIANCE_DEBUG_MM_DUMP writes as .pix.bf16 + out.f32 the merger's rows [P / 4, 4096], the rows that replace the picture's placeholders + meta.json the grid, the patch and token counts, the dtype, and the prompt ids the processor + makes of <|begin_of_image|><|image|><|end_of_image|> + +and with --taps the tensors on the way, each as f32 in the tower's own order: + + patch.f32 the patch embedding [P, 1024] + q0.f32 k0.f32 block 0's q and k after the per-head norm and the rotary [P, 16 * 64] + blk0.f32 blk11.f32 blk23.f32 the residual stream after those blocks [P, 1024] + post.f32 post_layernorm [P, 1024] + down.f32 the 2 x 2 downsample [P / 4, 4096] + +--max-image-tokens is the processor's budget, the checkpoint's 8000 by default: a server whose +encoder pass holds fewer (--mm-max-patches auto is 4096 tokens) sizes a large picture smaller, and +the reference must be asked for the same budget. + +The tower's input is the processor's patches rounded to bf16 in both dtypes, which is what the +engine stages: --dtype float32 then measures the tower's arithmetic alone. Every number here comes +from transformers, not from this script. + +--compare DUMP_DIR reads what an engine serving the same pictures wrote with +RADIANCE_DEBUG_MM_DUMP=DUMP_DIR (mm__1xHxW.pix.bf16 and .bf16, matched to the pictures by +grid) and checks it against the reference: the staged patches bit for bit, and the encoder rows to +the tolerance of two bf16 computations of the same tower -- a cosine of at least 0.99 over the +picture and a median per-row relative error of at most 0.08 against the bfloat16 reference. +Measured against it on the CPU (libref, libavx) and one R9700 (libr4d): cosine 0.996 to 0.998 and +a median per-row error of 0.03 to 0.045 at up to 4144 patches, 0.993 and 0.049 at 16384, the same +order as the bfloat16 reference's own against float32; a handful of rows with a small norm differ +more in both (docs/ARCHITECTURES.md). Exits 1 past either bound.""" +import argparse, json, os + +import numpy as np +import torch +from PIL import Image +from safetensors import safe_open +from transformers import AutoConfig, AutoProcessor +from transformers.models.glm5_next import modeling_glm5_next as M + + +def load_tower(model_dir, dtype): + cfg = AutoConfig.from_pretrained(model_dir).vision_config + cfg._attn_implementation = "sdpa" + tower = M.Glm5NextVisionModel(cfg) + index = json.load(open(os.path.join(model_dir, "model.safetensors.index.json"))) + want = {k: v for k, v in index["weight_map"].items() if k.startswith("model.visual.")} + state = {} + for shard in sorted(set(want.values())): + with safe_open(os.path.join(model_dir, shard), "pt") as f: + for k in f.keys(): + if k in want: + state[k[len("model.visual."):]] = f.get_tensor(k) + missing, unexpected = tower.load_state_dict(state, strict=False) + if unexpected or [k for k in missing if "inv_freq" not in k]: + raise SystemExit(f"tower weights: missing {missing}, unexpected {unexpected}") + return tower.to(dtype).eval() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("model") + ap.add_argument("out") + ap.add_argument("images", nargs="+") + ap.add_argument("--dtype", default="bfloat16", choices=["bfloat16", "float32"]) + ap.add_argument("--taps", action="store_true") + ap.add_argument("--threads", type=int, default=0) + ap.add_argument("--max-image-tokens", type=int, default=0) + ap.add_argument("--compare", default=None, metavar="DUMP_DIR") + a = ap.parse_args() + if a.threads: + torch.set_num_threads(a.threads) + dtype = getattr(torch, a.dtype) + proc = AutoProcessor.from_pretrained(a.model) + tower = load_tower(a.model, dtype) + + pics = [Image.open(p).convert("RGB") for p in a.images] + budget = {"max_image_tokens": a.max_image_tokens} if a.max_image_tokens else {} + enc = proc.image_processor(images=pics, return_tensors="pt", **budget) + pv, thw = enc["pixel_values"], enc["image_grid_thw"] + counts = [int(t.prod()) for t in thw] + pv16 = pv.to(torch.bfloat16) + + taps = {} + hooks = [] + if a.taps: + def keep(name, fn=lambda o: o): + return lambda mod, inp, out: taps.__setitem__(name, fn(out).detach().float()) + hooks.append(tower.patch_embed.register_forward_hook(keep("patch"))) + for i in (0, 11, len(tower.blocks) - 1): + hooks.append(tower.blocks[i].register_forward_hook(keep(f"blk{i}"))) + hooks.append(tower.post_layernorm.register_forward_hook(keep("post"))) + hooks.append(tower.downsample.register_forward_hook( + keep("down", lambda o: o.reshape(-1, o.shape[1])))) + rope = M.apply_rotary_pos_emb_vision + + def rope_tap(q, k, cos, sin): + qe, ke = rope(q, k, cos, sin) + if "q0" not in taps: + taps["q0"] = qe.detach().float().reshape(qe.shape[0], -1) + taps["k0"] = ke.detach().float().reshape(ke.shape[0], -1) + return qe, ke + M.apply_rotary_pos_emb_vision = rope_tap + with torch.no_grad(): + out = tower(pv16.to(dtype), grid_thw=thw).pooler_output.float() + if a.taps: + M.apply_rotary_pos_emb_vision = rope + for h in hooks: + h.remove() + + p0 = r0 = 0 + for path, im, t, n in zip(a.images, pics, thw.tolist(), counts): + d = os.path.join(a.out, os.path.basename(path)) + os.makedirs(d, exist_ok=True) + r = n // 4 + pv16[p0:p0 + n].view(torch.int16).numpy().astype("<|image|><|end_of_image|>"], images=[im], + return_tensors="pt", **budget)["input_ids"][0].tolist() + json.dump({"grid_thw": t, "patches": n, "tokens": r, "dtype": a.dtype, + "prompt_ids_len": len(ids), "prompt_ids_head": ids[:3], "prompt_ids_tail": ids[-2:], + "taps": sorted(taps)}, open(os.path.join(d, "meta.json"), "w"), indent=1) + p0 += n + r0 += r + print(f"wrote {len(a.images)} picture(s) to {a.out}: {counts} patches, dtype {a.dtype}") + if a.compare: + raise SystemExit(compare(a.compare, a.images, thw.tolist(), pv16, out, counts)) + + +def compare(dump, images, grids, pv16, out, counts): + """The engine's patches and rows against the reference's; 0 when every picture is within.""" + def bf16(path): + return (np.fromfile(path, dtype="= 0.99 and med <= 0.08 + bad += not ok + print(f" {name}: patches {'identical' if same else 'DIFFER'}; rows: cosine {cos:.5f}, " + f"per-row relative error median {med:.4f}, largest {worst:.4f} -- " + f"{'within' if ok else 'OUTSIDE'}") + p0 += n + r0 += r + return 1 if bad else 0 + + +if __name__ == "__main__": + main() From c4a47673f24235bf67b057a572d648f84f925798 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:14 +0200 Subject: [PATCH 142/152] docs: GLM-5.3's vision -- the tower, its processor and traps, converting, serving MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ARCHITECTURES.md's glm5next section describes the tower, the processor's budget against the encoder pass, and the readings that are wrong without an error (the downsample's column order, the rotary's pairing, no rotary in the language model, the draft head's image rows), with what the tower measured against transformers. GUIDE.md, spec.md §11, PLUGIN.md, the README and the compose file say GLM-5.3 takes pictures and how a container gains the tower. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++-- deploy/compose/glm53-flash.yaml | 3 +- docs/ARCHITECTURES.md | 78 ++++++++++++++++++++++++++++++--- docs/GUIDE.md | 12 ++--- docs/PLUGIN.md | 5 ++- spec.md | 9 +++- 6 files changed, 96 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 887e82f9..5d136741 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` | | Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | | TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` | -| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, eight cards | `glm53-flash-mxfp4.rad` (171 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` | +| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, vision, eight cards | `glm53-flash-mxfp4.rad` (172 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` | | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | | Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | `sdxl.yaml` | @@ -81,10 +81,12 @@ client sends on `/v1/completions` the prompt the checkpoint's template renders. GLM-5.3-Flash is converted from AMD's Quark export (`amd/GLM-5.3-Flash-Quark-MXFP4`) with `data/recipes/glm53-mxfp4.recipe`, which keeps every weight as stored except the latent -attention's small kv_b, decoded to bf16. At 171 GiB it takes eight R9700s (`--tp 8`), every expert +attention's small kv_b, decoded to bf16. At 172 GiB it takes eight R9700s (`--tp 8`), every expert resident, and its own MTP layer drafts. On eight R9700s it prefills 3958 tok/s at 6k tokens, decodes 166 tok/s on one stream and 426 over eight, and 506 under eight streams of agent turns. -It serves text only, with a bf16 KV cache. Its template knows the reasoning efforts `low` and +Pictures go through its own vision tower, up to 4096 tokens an image at the default encoder pass +(`--mm-max-patches 32000` serves the checkpoint's 8000); the KV cache is bf16. Its template knows +the reasoning efforts `low` and `high` and renders any other as its maximum, so `glm53-flash.yaml` maps `medium` and `xhigh` to `high`. diff --git a/deploy/compose/glm53-flash.yaml b/deploy/compose/glm53-flash.yaml index da2f8374..67210b82 100644 --- a/deploy/compose/glm53-flash.yaml +++ b/deploy/compose/glm53-flash.yaml @@ -1,6 +1,7 @@ # GLM-5.3-Flash from AMD's Quark export (data/recipes/glm53-mxfp4.recipe): MXFP4 experts, # block-FP8 attention, the native MTP layer as the drafter. It takes eight 32 GB cards with the -# whole expert plane in VRAM; text only. The KV cache is bf16, the only one the plugin declares. +# whole expert plane in VRAM; a container with the vision tower serves pictures too, at the +# default encoder pass. The KV cache is bf16, the only one the plugin declares. # # A hybrid reuses a cached prefix only from a recurrent-state checkpoint at or below it, so the # interval is 1024, which keeps a 1.5k-token system prompt's first 1024 tokens; --prefill-span 4 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 0dfe6317..7a259aab 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -14,7 +14,7 @@ plugin claims. | `arch/qwen35_w8a8` | `qwen35` | `w8a8_fwht128` | `qwen35_fp8` with an int8 trunk: i8 weights with a bf16 scale per 128 of K, rotated by a 128-wide Hadamard, against int8 activations under the same rotation (`data/recipes/q38-27b-w8a8-df2.recipe`) | | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert | -| `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Text only, bf16 KV | +| `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Pictures through its vision tower (`arch/common/rad_block_glm_vision.h`); bf16 KV | | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | | `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`), or RedHatAI's DFlash2 speculator (`arch/common/rad_block_dflash2.h`) | @@ -411,9 +411,10 @@ The vision tower is declared when the container carries one and `--mm-max-patche `arch/glm5next` serves the language model of GLM-5.3-Flash (`model_type: glm5_next`) from AMD's Quark export, `amd/GLM-5.3-Flash-Quark-MXFP4`. Quark is an import path, not an execution format: the plugin claims the empty descriptor and reads each weight's encoding from the container -(`data/recipes/glm53-mxfp4.recipe` changes one weight a layer, below). The vision tower is not -mapped, so never converted, and an image request fails its step. The reference is SGLang's -`glm5_next.py` and `glm5_next_nextn.py` at AMD's pinned commit 654df43. +(`data/recipes/glm53-mxfp4.recipe` changes one weight a layer, below). Its vision tower is +declared beside it when the container carries the tower and the deployment asks for an encoder +(below). The reference is SGLang's `glm5_next.py` and `glm5_next_nextn.py` at AMD's pinned commit +654df43; for the tower and its processor, transformers' `glm5_next`. The plugin is one file over blocks in `arch/common`, one block a file; it declares the buffers the blocks share, places them and issues the step's order. @@ -426,6 +427,7 @@ the blocks share, places them and issues the step's order. | `rad_block_glm_indexer.h` | `GlmIndexer`, `DsaCache` | the DSA indexer, its key cache and selection | | `rad_block_glm_router.h` | `GlmRouter` | the correction-bias router, through `MoeFP8` | | `rad_block_glm_mtp.h` | `GlmMtp` | the draft head around the plugin's layer 45 | +| `rad_block_glm_vision.h` | `GlmVision`, `MediaRows` | the tower, and its rows over the embeddings | | `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the split threshold, the column split of a replicated f32 projection | ``` @@ -510,8 +512,8 @@ hybrid, so a prefix-cache hit is usable only from a state checkpoint at or below | router, index head gates, mHC projections | f32 | `gemm_nt_f32`, `mhc_pre` | | embedding, lm_head, MTP eh_proj | bf16 | `embed_lookup`, `logits_gemm`, `gemm_nt` | -The container holds 25845 weights, 171.32 GiB; at eight ranks each card holds 22.06 GiB of them, -19.67 GiB the routed experts. +The text container holds 25845 weights, 171.32 GiB, the one with the tower 26143 and 172.37 GiB; +at eight ranks each card holds 22.06 GiB of them, 19.67 GiB the routed experts. **MTP.** The plugin declares checkpoint layer 45 as a serial drafter (`RAD_DRAFT_SERIAL`), depth 3 unless `--num-speculative-tokens` says otherwise (at most 31). Its history pass writes the draft @@ -567,6 +569,70 @@ decode, the collective costs more than it saves and every rank runs the replicat head gates go with the indexer's rows (above). Below the threshold, as in decode, the collective costs more than it saves. +**Vision.** The tower (`arch/common/rad_block_glm_vision.h`, transformers' `Glm5NextVisionModel`) +is declared last, so an encoder pass shares the arena with the step's buffers. Every rank runs it +whole: its weights are replicated, `RAD_ACCESS_PER_REQUEST`, a group a block from 46, past the MTP +layer's. Its rows replace the `<|image|>` placeholders' embeddings unscaled, before the embedding's +reduction (`MediaRows`), in the trunk and in the draft head's lookup, as SGLang feeds its draft +model the target's image rows. + +``` +24 blocks, width 1024, 16 heads of 64, SwiGLU 4096; patch 14 x 14, two frames: 1176-wide rows +patch embedding: the Conv3d as a linear with bias; no position table +block: RMSNorm; qkv with bias; q and k RMS-normed per head with a gain; a 2-D rotary over + (row, column), 16 frequencies an axis at theta 10000; attention within a picture at 1/8; proj + with bias; RMSNorm; gate|up with bias, silu(min(g, 10)) * clamp(u, -10, 10), down with bias +post_layernorm (RMSNorm), then a 2 x 2 stride-2 Conv2d 1024 -> 4096 over each merged block +merger: proj 4096 -> 4096, LayerNorm (affine, eps 1e-5), exact GELU, the clipped SwiGLU through + 10240; no biases but the norm's. One row a merged block: an image of P patches is P / 4 tokens +``` + +The processor is `core/mm`'s `Glm5Next` family (`core/mm/processor.h`). A picture's canvas has sides +in multiples of 28 and 16 to `max_image_tokens` tokens; the picture keeps its aspect ratio, is +resized only when it is under the floor or over the budget (torchvision's bicubic), and the rest +of the canvas, right and bottom, is black. It is spelled `<|begin_of_image|>`, one `<|image|>` a +token, `<|end_of_image|>`. The checkpoint allows 8000 tokens (32000 patches); one encoder pass +bounds it, so `--mm-max-patches auto` (16384) serves at most 4096, and `--mm-max-patches 32000` +the checkpoint's budget. `--image-tokens` lowers it. Video is refused. + +Traps: + +- **The downsample reads the processor's merge-block order as stored.** The reference views the + post-norm rows as `[blocks, 2, 2, 1024]`, which in merge-block order is four consecutive rows; + `conv2d_unfold` (width 2, two input rows a block) writes each block as one row in the weight's + own column order `(channel, kernel row, kernel column)`, so the checkpoint's `[4096, 1024, 2, 2]` + is read as a `[4096, 4096]` linear unchanged. The 4096-wide view of the four rows without the + unfold is `(kernel row, kernel column, channel)`, and multiplied by the stored weight it is another + model. +- **The rotary pairs across the whole head.** NeoX pairs `(i, i + 32)`, the row on frequencies + 0-15 and the column on 16-31, each section on its own ladder `theta^(-2j / 32)`: `qk_norm_rope`'s + `axial`, not the `blocks` mode of Gemma 4's tower, which rotates each half on its own. +- **No rotary in the language model.** An image's tokens take their token positions + (`Item::rope_1d`), and the indexer pools and selects them as text. +- **Without the image rows in the draft head's lookup** the drafts read the placeholder's + embedding: the text stays the trunk's, only acceptance falls on a prompt with a picture. +- **The canvas is padded, not stretched**, and an image under the budget is not resampled at all: + its patches are the reference processor's bit for bit (`tests/mm_test.cpp`, every case of + `tests/glm5_golden.h`, the resampled ones included). + +An existing container gains the tower with `rad-convert --reuse ` (298 weights, +1.05 GiB, all bf16 as the checkpoint holds them); `--in-place` extends the container itself. + +**Measured** against transformers' tower on the CPU (`tests/glm5_vision_reference.py`), the tower +alone, on libref, libavx and one R9700 (libr4d). Three pictures in one pass (1024, 4144 and 792 +patches, the last padded): the staged patches are the reference processor's bit for bit; the +merger's rows reach a cosine of 0.9955 to 0.9970 against the f32 reference, a median per-row +relative error of 0.029 to 0.044, where transformers in bf16 reaches 0.9967 to 0.9984 and 0.029 to +0.044; against the bf16 reference, 0.9959 to 0.9983. Through block 11 the engine is nearer f32 than +the bf16 reference (block 0 3.6e-3 against 3.8e-3 relative, q and k after the rotary 3.1e-3 +against 3.8e-3); the residual stream then carries a few rows of very large magnitude, and in both a +handful of output rows with a small norm differ by 0.3 to 1.2 relative. A picture's rows are the +same alone and beside two others in its pass. At 16384 patches (a 2048 x 2048 picture at 4096 +tokens) the engine reaches 0.9940 to 0.9947 against f32, transformers in bf16 0.9928; at 32000 +(8000 tokens), 0.994 against the bf16 reference. On one R9700 a pass of 5960 patches takes 92 ms, +16384 patches 0.49 s and 32000 1.5 s, with an activation arena of 0.56 and 1.10 GiB, beside the +tower's 1.05 GiB of weights on every card. + **MoE decode fusions.** Three, each byte-identical to the launches it replaces, declared wherever a loaded library serves the fused op (the separate launches otherwise): diff --git a/docs/GUIDE.md b/docs/GUIDE.md index cd93f658..fd97537d 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -536,8 +536,9 @@ CALIB=/srv/calib/translategemma rad-convert /srv/models/google/translategemma-27 --recipe data/recipes/translategemma-27b-mxfp4-gptq.recipe -o translategemma-27b-mxfp4-gptq.rad # GLM-5.3-Flash from AMD's Quark export: MXFP4 experts and block-FP8 attention kept as stored, -# the latent attention's kv_b decoded to bf16; text only, the vision tower is not converted. -# 171 GiB, served on eight 32 GB cards (docs/ARCHITECTURES.md) +# the latent attention's kv_b decoded to bf16, the vision tower bf16 as it ships. +# 172 GiB, served on eight 32 GB cards (docs/ARCHITECTURES.md). A container converted without the +# tower gains it with --reuse (1.05 GiB written; --in-place extends the old one) rad-convert /srv/models/amd/GLM-5.3-Flash-Quark-MXFP4 \ --recipe data/recipes/glm53-mxfp4.recipe -o glm53-flash-mxfp4.rad @@ -1651,7 +1652,7 @@ The published vector, its JSON and the llama.cpp patches it was built against ar | `--port N` | 8000 | listen port | | `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6) | | `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the loaded one serves it | -| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card | +| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels, 14x14 on GLM-5.3). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card | | `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the container's. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup | | `--max-queued-requests N` | 8 × `--max-num-seqs` | requests admitted and unfinished at once; past it, 429 | | `--http-threads N` | one per hardware thread, at least 4 | HTTP workers kept while idle | @@ -1686,7 +1687,8 @@ The published vector, its JSON and the llama.cpp patches it was built against ar **Media.** Each replaces what the container's preprocessor configuration states, and does nothing for a model that takes no images or video. A Qwen-VL container that states none uses 2 frames a second, -4 to 768 frames and 768 tokens a frame. +4 to 768 frames and 768 tokens a frame. GLM-5.3 takes pictures only, budgeted in tokens: the video +flags are refused on it, and so are the pixel bands. | flag | default | | |---|---|---| @@ -1695,7 +1697,7 @@ a model that takes no images or video. A Qwen-VL container that states none uses | `--video-fps F` | container's | frames sampled per second of video | | `--video-min-frames N`, `--video-max-frames N` | container's | the fewest and most frames sampled from a video | | `--video-max-frame-tokens N` | container's | the most prompt tokens one frame may become; 0 is no cap. A token-budget processor (Gemma 4's) takes 70, 140, 280, 560 or 1120 | -| `--image-tokens N` | container's | a token-budget processor's image budget (Gemma 4's: 70, 140, 280, 560, 1120); a request's `image_tokens` overrides it. The pixel-band flags are refused on such a model | +| `--image-tokens N` | container's | a token-budget processor's image budget: Gemma 4's 70, 140, 280, 560 or 1120, which a request's `image_tokens` overrides; GLM-5.3's ceiling, at most `--mm-max-patches` / 4 (the checkpoint states 8000, which `auto` lowers to 4096). The pixel-band flags are refused on such a model | | `--max-source-pixels N` | 67108864 | the largest image or frame the decoder accepts, before any resize | **Quality measurement**, instead of serving; see [TOOLS.md](TOOLS.md#the-kl-mode) diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md index 87970c5e..48122bdf 100644 --- a/docs/PLUGIN.md +++ b/docs/PLUGIN.md @@ -362,8 +362,9 @@ says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep `qk_norm_rope_gate`. - **Read §8** if the model has a linear or recurrent block. - **Media preprocessing is the core's** (`core/mm`): resizing, patching, placeholder-token - expansion and positions, in three processor families (Qwen-VL, Gemma 4, LFM2-VL) chosen by the - container's `vision_config.model_type`. A vision model with another pipeline needs a core change. + expansion and positions, in four processor families (Qwen-VL, Gemma 4, LFM2-VL, GLM-5.3) chosen + by the container's `vision_config.model_type`. A vision model with another pipeline needs a core + change. Audio goes through one of two feature extractors, Gemma 4's and Qwen3-ASR's (Whisper's), chosen by `audio_config.model_type`. - **A speech model says how it hears**, through the optional diff --git a/spec.md b/spec.md index 8faee7f3..9551f665 100644 --- a/spec.md +++ b/spec.md @@ -1248,7 +1248,8 @@ of a linear-attention kernel pair's schema (`docs/OPS.md`). **Coverage.** Pictures and video on every Qwen container that carries the vision tower (Qwen3.8-27B in bf16 and fp8, Qwen3.6-35B-A3B, Qwen3.8-Flash-Next) and on Gemma 4 31B -(`gemma4_bf16`); pictures on LFM2-VL; pictures, video and audio as EmbeddingGemma 2 input. Media +(`gemma4_bf16`); pictures on LFM2-VL and GLM-5.3-Flash; pictures, video and audio as EmbeddingGemma +2 input. Media arrive as `image_url` / `video_url` chat parts (`input_image` / `input_video` in the Responses API) and audio as `input_audio` / `audio_url`, as `data:` URLs only: fetching a caller's URL would make the server an SSRF proxy. @@ -1266,6 +1267,9 @@ colour matrix and range. The family comes from the container (`core/mm/processor 1120); a video is frames at `fps`, each its own segment at the per-frame budget. - **LFM2-VL.** A picture within its token budget is resized whole; a larger one is cut into tiles followed by a thumbnail. Images only. +- **GLM-5.3.** A canvas of whole merged patches within a token budget; the picture keeps its aspect + ratio, is resized only past the budget or under its floor, and is padded black to the canvas. + Images only, the tokens at their positions (the language model has no rotary). `tests/mm_test.cpp` checks the processor against goldens generated by `tests/mkgolden.py` from transformers' own functions. A media part reaches the chat template as a marker that the part join @@ -1273,7 +1277,8 @@ leaves unpadded, so an image prompt tokenises to the reference's ids. **The encoder is the language model's plugin.** The tower is declared last by the language model's plugin (for Qwen, `arch/common/rad_block_vit.h` in `qwen35_bf16`, `qwen35_fp8`, `qwen35moe_fp8` and -`qwen4exp_fp8`) when the container carries its weights and the deployment asks for an encoder +`qwen4exp_fp8`; for GLM-5.3, `arch/common/rad_block_glm_vision.h` in `glm5next`) when the container +carries its weights and the deployment asks for an encoder (`--mm-max-patches`; `auto` is 16384 patches a pass when the container has a tower, a 2048 x 2048 picture at 16x16 patches; a larger picture is resized to fit, since a segment is never split). Its weights are `RAD_ACCESS_PER_REQUEST` in groups past every text layer, declared with one From ef219c21926c31cf72804df595cc40053ff724f9 Mon Sep 17 00:00:00 2001 From: Juup Date: Wed, 21 Oct 2026 19:09:59 +0000 Subject: [PATCH 143/152] arch, data/recipes, deploy: Sage-A1.5's routed trunk with its vision tower, and DFlash2 in place of the MTP head Sage-A1.5 (InternScience) is Qwen3.5-MoE's routed trunk with the Qwen3.5 vision tower beside it -- a shape qwen35moe_fp8 already declares, but no fixture covered the two together: the MoE fixture had no tower, the VL fixture was dense. arch_test gains q35moe_vl_meta, and checks the tower declares once for the build (not a copy a rank), that it is withheld when no encoder budget is given, and that the routed blocks, the folded shared expert and the MTP layer's own router are still declared beside it. sage-a1.5-fp8.recipe puts every trunk linear -- attention, the delta net's in- and out-projections, the routed and shared experts of all 40 blocks, and the MTP layer at index 40 -- into block fp8, the head likewise, and keeps the routers, the shared-expert gates, the delta net's parameters, the norms, the embedding and the whole vision tower as the checkpoint ships them. recipe_test reads the shipped file and asserts all of that. sage-a1.5-fp8-df2.recipe is the same trunk with incoai/Qwen3.6-35B-A3B-DFlash2's tensors in place of the MTP head, which the shared source declares through declare_dflash2. On two R9700s it decodes 392.9 tok/s against 281.6 with the MTP head, at 49.3% acceptance and depth 7; on one card, 231.6 against 168.3. Compose: sage-a1.5.yaml (two cards, four 32k sessions), sage-a1.5-tp1.yaml (one card, an 8 GiB pinned host pool, one 262,144-token session) and sage-a1.5-df2.yaml. README, DOCKER.md and ARCHITECTURES.md list the containers and the drafter. --- README.md | 2 + data/recipes/sage-a1.5-fp8-df2.recipe | 38 +++++++++++++++++ data/recipes/sage-a1.5-fp8.recipe | 39 +++++++++++++++++ deploy/compose/sage-a1.5-df2.yaml | 18 ++++++++ deploy/compose/sage-a1.5-tp1.yaml | 20 +++++++++ deploy/compose/sage-a1.5.yaml | 21 ++++++++++ docs/ARCHITECTURES.md | 10 +++++ docs/DOCKER.md | 3 ++ tests/arch_test.cpp | 60 +++++++++++++++++++++++++++ tests/recipe_test.cpp | 53 +++++++++++++++++++++++ 10 files changed, 264 insertions(+) create mode 100644 data/recipes/sage-a1.5-fp8-df2.recipe create mode 100644 data/recipes/sage-a1.5-fp8.recipe create mode 100644 deploy/compose/sage-a1.5-df2.yaml create mode 100644 deploy/compose/sage-a1.5-tp1.yaml create mode 100644 deploy/compose/sage-a1.5.yaml diff --git a/README.md b/README.md index 5d136741..b930ef91 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,8 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` | | Ornith-1.5-35B-A3B FP8, MTP, vision | `ornith-1.5-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-fp8) | `ornith-1.5-35b-a3b.yaml` | | Ornith-1.5-35B-A3B w4a8: 4-bit experts (GPTQ), MTP, vision, fits one card | `ornith-1.5-35b-a3b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/ornith-1.5-35b-a3b-w4a8) | `ornith-1.5-35b-a3b-w4a8.yaml` | +| Sage-A1.5 FP8, MTP, vision | `sage-a1.5-fp8.rad` (35 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8) | `sage-a1.5.yaml`, `sage-a1.5-tp1.yaml` | +| Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` | | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | | Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | diff --git a/data/recipes/sage-a1.5-fp8-df2.recipe b/data/recipes/sage-a1.5-fp8-df2.recipe new file mode 100644 index 00000000..92c43e27 --- /dev/null +++ b/data/recipes/sage-a1.5-fp8-df2.recipe @@ -0,0 +1,38 @@ +# sage-a1.5-fp8-df2.recipe -- Sage-A1.5 with incoai's Qwen3.6-35B-A3B DFlash2 drafter merged in +# place of the MTP head. The trunk rules are sage-a1.5-fp8.recipe's unchanged; the drafter's +# linears take the same 128x128 block form as the trunk, and its draft head is the target's +# lm_head as the 2-bit copy the draft rounds read. +# +# rad-convert InternScience/Sage-A1.5-FP8 \ +# --draft-model incoai/Qwen3.6-35B-A3B-DFlash2 \ +# --recipe data/recipes/sage-a1.5-fp8-df2.recipe -o sage-a1.5-fp8-df2.rad +# +# The drafter is a DFlash2DraftModel: six Qwen3-shaped layers at 2048, eight taps +# (target_layer_ids 1 6 11 16 22 27 32 37), block 8, selector rank 256 / top 16, vocab 248320. +# Sage's text_config is Qwen3.6-35B-A3B's key for key, so the drafter's geometry matches the +# trunk it was trained against. qwen35moe_fp8 (qwen35_fp8.cpp with QWEN35_MOE=1) declares it and +# drops the MTP head, which is then neither declared nor carried. +# +# The drafter's norms, the selector's projection and codebooks, and the convolution kernels and +# bases stay bf16/f32 as the checkpoint holds them. + +blk.*.attn_qg.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_inz.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_gate_up_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_gate_up_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/data/recipes/sage-a1.5-fp8.recipe b/data/recipes/sage-a1.5-fp8.recipe new file mode 100644 index 00000000..6810c178 --- /dev/null +++ b/data/recipes/sage-a1.5-fp8.recipe @@ -0,0 +1,39 @@ +# sage-a1.5-fp8.recipe -- Sage-A1.5, InternScience's post-train of Qwen3.5-35B-A3B-VL, as the +# qwen35moe_fp8 plugin serves it (256 experts of 512, top 8, a routed MTP head, the Qwen3.5 +# vision tower). +# +# rad-convert InternScience/Sage-A1.5-FP8 --recipe data/recipes/sage-a1.5-fp8.recipe \ +# -o sage-a1.5-fp8.rad +# +# The published FP8 release is compressed-tensors with one scale an output row, and it leaves +# the vision tower, the routers and the whole MTP head bf16. The engine's expert kernels read +# block-scaled fp8 only (a scale a 128x128 block) and its plugin refuses bf16 experts, so this +# re-expresses every linear into Qwen's own block form, the same weights in the same form as +# qwen3.6-35b-a3b-fp8.rad. From the bf16 release instead, the same recipe applies and the format +# has to be stated too: +# +# rad-convert InternScience/Sage-A1.5 --recipe data/recipes/sage-a1.5-fp8.recipe \ +# --set quantization_config.quant_method=fp8 --set quantization_config.fmt=e4m3 \ +# --set "quantization_config.weight_block_size=128 128" \ +# --set quantization_config.activation_scheme=dynamic -o sage-a1.5-fp8.rad +# +# The linears -- attention q/gate, k, v and output, the delta net's qkv/z and output +# projections, the routed and shared experts of all 40 blocks, and the MTP layer's, which the +# blk.* patterns reach at its own index 40 -- as E4M3 with one bf16 scale a 128x128 block. The +# lm_head likewise, and the MTP head's 2-bit copy of it, which the draft rounds read in place of +# the full head. The routers, the shared-expert gates, the delta net's a/b projection, its conv +# and decay parameters, the norms, the embedding and the vision tower stay as the checkpoint +# holds them. + +blk.*.attn_qg.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_inz.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ssm_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_gate_up_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_exps.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_gate_up_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +blk.*.ffn_down_shexp.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 +mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/deploy/compose/sage-a1.5-df2.yaml b/deploy/compose/sage-a1.5-df2.yaml new file mode 100644 index 00000000..2fae0b59 --- /dev/null +++ b/deploy/compose/sage-a1.5-df2.yaml @@ -0,0 +1,18 @@ +# Sage-A1.5 with incoai's Qwen3.6-35B-A3B DFlash2 drafter in place of the MTP head, made by +# data/recipes/sage-a1.5-fp8-df2.recipe. The drafter proposes seven tokens in one block pass +# (block 8, acceptance ~49% at depth 7); measured 393 tok/s decode on two cards against 282 with +# MTP. Sampling is the model card's (temp 1.0, top_p 0.95, top_k 20, presence 1.5). +# +# The profile below is the measured one: four 32,768-token sessions, the whole expert plane in +# VRAM. A single 262,144-token session instead is `--max-num-seqs 1 --max-model-len 262144`. +name: radiance-sage-a1.5-df2 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-sage-a1.5-df2 + command: > + --model /models/sage-a1.5-fp8-df2.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 4 --max-model-len 32768 --kv-cache-dtype fp8 + --num-speculative-tokens auto --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/sage-a1.5-tp1.yaml b/deploy/compose/sage-a1.5-tp1.yaml new file mode 100644 index 00000000..e54650bb --- /dev/null +++ b/deploy/compose/sage-a1.5-tp1.yaml @@ -0,0 +1,20 @@ +# Sage-A1.5 on one card: the same block-fp8 container, its experts partly in a pinned host pool +# because 34.5 GiB of weights do not fit 31.9 GiB of VRAM. Measured on a R9700 (warm, 3 runs, +# --max-model-len 131072): 168 tok/s decode and ~11,000 tok/s prefill, against 282 tok/s decode +# and ~11,000 tok/s prefill at --tp 2. Prefill is bandwidth-bound and one card does it; the +# second card buys decode only. This profile: 25.12 GiB of experts in VRAM, 5.79 GiB in the 8 +# GiB pool (about 1.5 GiB more than the measured run), the cache holding one full 262,144-token +# session. For two short sessions instead use --max-num-seqs 2 --max-model-len 32768 +# --host-pool-mib 6144 (3.80 GiB of experts in the pool). Sampling is the model card's. +name: radiance-sage-a1.5-tp1 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-sage-a1.5-tp1 + command: > + --model /models/sage-a1.5-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 1 --max-num-seqs 1 --max-model-len 262144 --kv-cache-dtype fp8 + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --placement expert_tiered --host-pool-mib 8192 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/deploy/compose/sage-a1.5.yaml b/deploy/compose/sage-a1.5.yaml new file mode 100644 index 00000000..80babc0f --- /dev/null +++ b/deploy/compose/sage-a1.5.yaml @@ -0,0 +1,21 @@ +# Sage-A1.5, InternScience's Qwen3.5-35B-A3B-VL post-train: FP8 with one scale per 128x128 +# block, its routed MTP head and the vision tower, as data/recipes/sage-a1.5-fp8.recipe makes +# it. Sampling is the model card's (temp 1.0, top_p 0.95, top_k 20, presence 1.5). Thinking and +# the opt-in verification mode are switched per request (chat_template_kwargs). +# +# The profile below is the measured one: four 32,768-token sessions, the whole expert plane in +# VRAM. A single 262,144-token session instead is `--max-num-seqs 1 --max-model-len 262144`: +# the planner charges ~1.5 GiB of KV a card for it (1.49 GiB backs 262,176 tokens in the tp2 +# boot log). Eight of them are ~12 GiB of KV a card, which does not fit beside 15.5 GiB of +# resident experts and 1.9 GiB of static weights once the arena for eight sequences is charged. +name: radiance-sage-a1.5 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-sage-a1.5 + command: > + --model /models/sage-a1.5-fp8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 4 --max-model-len 32768 --kv-cache-dtype fp8 + --num-speculative-tokens 3 --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 7a259aab..8ad2deeb 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -263,6 +263,16 @@ and every difference is behind `#if QWEN35_MOE` in the shared source. It is a se unit rather than a branch on `n_expert` because the id is half the selection key, and one `.so` cannot claim both ids. +**Drafters.** The container's own MTP head is the default, and `rad-convert --draft-model` can +replace it with a DFlash2 block drafter; the shared source declares it (`declare_dflash2`) and +does not declare the MTP head when a DFlash2 drafter is present, so the routed trunk carries a dense drafter +without further work. `sage-a1.5-fp8-df2.rad` is such a container: Sage-A1.5's routed trunk with +`incoai/Qwen3.6-35B-A3B-DFlash2`, whose six 2048-wide layers read eight taps +(`target_layer_ids` 1 6 11 16 22 27 32 37) and propose a block of seven tokens in one pass. At +depth 7 it accepts ~49% of the proposals and decodes 1.40x faster than the same trunk with its MTP +head (393 against 282 tok/s on two R9700s). `--num-speculative-tokens auto` takes the depth the +drafter states. + ## `qwen35_w8a8` The dense build again, behind `#if QWEN35_W8A8`, for a container `data/recipes/q38-27b-w8a8-df2.recipe` diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 4d1bbb43..134ac407 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -131,6 +131,9 @@ the cards the engine runs on. | `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server | | `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 | | `ornith-1.5-35b-a3b.yaml` | `ornith-1.5-35b-a3b-fp8.rad` | Ornith-1.5-35B-A3B, FP8, MTP, vision | +| `sage-a1.5.yaml` | `sage-a1.5-fp8.rad` | Sage-A1.5, FP8, MTP, vision | +| `sage-a1.5-tp1.yaml` | `sage-a1.5-fp8.rad` | The same on one card: the expert plane partly in an 8 GiB pinned host pool, one 262,144-token session | +| `sage-a1.5-df2.yaml` | `sage-a1.5-fp8-df2.rad` | Sage-A1.5 with incoai's Qwen3.6-35B-A3B DFlash2 drafter in place of the MTP head, vision | | `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower | | `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower | | `qwen3.8-27b-paro.yaml` | `qwen3.8-27b-paro-int4.rad` | Qwen3.8-27B ParoQuant int4 (learned rotations) with its DFlash2 drafter and vision tower, on one card; the int5 and MXFP4 containers serve from it too | diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 4170cd29..b2097a34 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -6055,6 +6055,26 @@ MetaKV q35moe_meta() { return k; } +/* The 35B-A3B-VL: the routed trunk with the Qwen3.5 vision tower beside it, as Sage-A1.5 and + * Ornith-1.5 carry it. The fixture's trunk is q35fp8_meta's (5120 wide), so the tower emits + * that width; the shipped checkpoints' tower is 2048, the real trunk's width. */ +MetaKV q35moe_vl_meta() { + MetaKV k = q35moe_meta(); + k.set("vision_config.depth", "2") + .set("vision_config.hidden_size", "1152") + .set("vision_config.num_heads", "16") + .set("vision_config.intermediate_size", "4304") + .set("vision_config.patch_size", "16") + .set("vision_config.temporal_patch_size", "2") + .set("vision_config.in_channels", "3") + .set("vision_config.spatial_merge_size", "2") + .set("vision_config.out_hidden_size", "5120") + .set("vision_config.num_position_embeddings", "2304") + .set("vision_config.deepstack_visual_indexes", "") + .set("vision_config.hidden_act", "gelu_pytorch_tanh"); + return k; +} + /* A DFlash2 drafter merged under `draft.`: two layers reading trunk layers 1, 3 and 5, a block * of 8 (seven drafts), the selector of rank 64 over 8 candidates. */ MetaKV with_dflash2(MetaKV k) { @@ -6701,6 +6721,46 @@ TEST(qwen35moe_fp8_steps_lint_clean_with_its_routed_mtp_head) { lint_qwen35_fp8_family(qwen35moe_fp8::declare, qwen35moe_fp8::step, mk.meta(), 3, false, 0); } +/* The 35B-A3B-VL: the routed trunk and the vision tower declare together, the tower once and + * not a copy a rank, and the routed MTP head beside them -- Sage-A1.5's shape, which no fixture + * covered before (the MoE fixture had no tower, the VL fixture was dense). */ +TEST(qwen35moe_fp8_declares_the_vision_tower_beside_the_routed_trunk) { + MetaKV mk = q35moe_vl_meta(); + /* With no encoder budget the tower is not declared, whatever the container carries. */ + { + RadBuilder b; + RadBuildCtx ctx = vl_ctx(0); + REQUIRE_EQ(qwen35moe_fp8::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK(b.encoder_name.empty()); + CHECK(find_w(b, "v.patch.weight") == nullptr); + CHECK_EQ(count_op(b, "router_topk"), 8); + } + RadBuilder b; + RadBuildCtx ctx = vl_ctx(1024); + ctx.max_spec = 3; + REQUIRE_EQ(qwen35moe_fp8::declare(&b, mk.meta(), &ctx), RAD_OK); + + CHECK_EQ(b.encoder_name, std::string("vision")); + CHECK_EQ(b.encoder.modalities, (uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)); + CHECK_EQ(b.encoder.max_patches, 1024); + CHECK_EQ(b.encoder.n_embd, 5120); + CHECK_EQ(b.encoder.merge, 4); + + /* The trunk is still the routed one (eight blocks, plus the MTP layer's own router under + * --max-spec 3), and the shared expert is still folded in. */ + CHECK_EQ(count_op(b, "router_topk"), 9); + CHECK(count_op(b, "moe_gemm_q") >= 16); + + /* 3 stem + 12 a block + 6 merger, each mapped from the checkpoint's model.visual.*. */ + int nv = 0; + for (const auto& w : b.weights) + if (w.name.rfind("v.", 0) == 0) { + ++nv; + CHECK(find_map(b, w.name) != nullptr); + } + CHECK_EQ(nv, 3 + 12 * 2 + 6); +} + /* `layer_types` is checked against the interval rule, not ignored: a model built with the wrong * layers linear still generates fluent text. A disagreeing, short or unknown schedule is refused * by every plugin of the family; an agreeing one declares. */ diff --git a/tests/recipe_test.cpp b/tests/recipe_test.cpp index 2ac8b009..35fa45a7 100644 --- a/tests/recipe_test.cpp +++ b/tests/recipe_test.cpp @@ -175,4 +175,57 @@ TEST(the_nvfp4_recipe_decides_the_model_it_was_written_for) { CHECK(has_opt(dh, "codes", "u2")); } +/* The Sage-A1.5 recipe as it ships: every trunk linear -- attention, the delta net's in- and + * out-projections, the routed and shared experts of all 40 blocks and the MTP layer at its own + * index 40 -- goes to block fp8, the head likewise, and the routers, the shared-expert gates, + * the delta net's parameters, the norms, the embedding and the vision tower keep the + * checkpoint's form. */ +TEST(the_sage_recipe_decides_the_model_it_was_written_for) { + std::string dir = __FILE__; + dir = dir.substr(0, dir.find_last_of('/')) + "/../data/recipes"; + std::ifstream in(dir + "/sage-a1.5-fp8.recipe"); + REQUIRE(in.good()); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Recipe r; + std::string why; + REQUIRE_EQ(r.add_text(text, "sage-a1.5-fp8.recipe", &why), RAD_OK); + CHECK_EQ(r.rules().size(), (size_t)12); + + const char* linears[] = { "blk.0.attn_qg.weight", "blk.3.attn_qg.weight", "blk.39.attn_qg.weight", + "blk.40.attn_qg.weight", "blk.3.attn_k.weight", "blk.3.attn_v.weight", + "blk.39.attn_output.weight", "blk.0.ssm_inz.weight", "blk.39.ssm_out.weight", + "blk.0.ffn_gate_up_exps.0.weight", "blk.19.ffn_down_exps.255.weight", + "blk.40.ffn_gate_up_exps.0.weight", "blk.40.ffn_down_exps.255.weight", + "blk.0.ffn_gate_up_shexp.weight", "blk.40.ffn_down_shexp.weight" }; + for (const char* n : linears) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK_EQ(m->quantizer, std::string("rtn")); + CHECK(has_opt(m, "codes", "fp8_e4m3")); + CHECK(has_opt(m, "block", "128x128")); + CHECK(has_opt(m, "scale", "bf16")); + } + const RecipeRule* head = r.match("output.weight"); + REQUIRE(head != nullptr); + CHECK(has_opt(head, "codes", "fp8_e4m3")); + CHECK(has_opt(head, "block", "128x128")); + const RecipeRule* dh = r.match("mtp.draft_head.weight"); + REQUIRE(dh != nullptr); + CHECK(has_opt(dh, "codes", "u2")); + CHECK(has_opt(dh, "zero", "u8")); + CHECK(has_opt(dh, "group", "128")); + CHECK(has_opt(dh, "scale", "f16")); + + /* kept as the checkpoint ships them: the routers, the gates, the delta net's parameters, + * the norms, the embedding and the whole vision tower */ + const char* kept[] = { "blk.0.ffn_norm.weight", "blk.0.attn_norm.weight", "blk.0.ssm_ab.weight", + "blk.0.ssm_conv1d.weight", "blk.0.ssm_a_log", "blk.0.ssm_dt.bias", + "blk.0.ssm_norm.weight", "blk.0.ffn_gate_inp.weight", + "blk.0.ffn_gate_shexp.weight", "blk.40.ffn_gate_inp.weight", + "token_embd.weight", "output_norm.weight", "mtp.fc.weight", + "mtp.norm.weight", "v.blk.0.qkv.weight", "v.merger.fc1.weight" }; + for (const char* n : kept) + CHECK(r.match(n) == nullptr); +} + RAD_TEST_MAIN() From 17d004d0d032776325468962d53ddd55c4eb66b1 Mon Sep 17 00:00:00 2001 From: Juup Date: Thu, 22 Oct 2026 07:54:30 +0000 Subject: [PATCH 144/152] data/recipes, deploy: Sage-A1.5 MXFP4 with DFlash2 The trunk linears, the routed and shared experts, and the DFlash2 linears round to OCP-MXFP4 (fp4_e2m1, one e8m0 scale per 32 of K); output.weight stays block FP8 and the draft head its 2-bit copy. 19.52 GiB against the block-FP8 sibling's 34.45, served at 25.8 GiB of VRAM a card on tp2. --- data/recipes/sage-a1.5-mxfp4-df2.recipe | 35 +++++++++++++++++++++++++ deploy/compose/sage-a1.5-mxfp4-df2.yaml | 21 +++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 data/recipes/sage-a1.5-mxfp4-df2.recipe create mode 100644 deploy/compose/sage-a1.5-mxfp4-df2.yaml diff --git a/data/recipes/sage-a1.5-mxfp4-df2.recipe b/data/recipes/sage-a1.5-mxfp4-df2.recipe new file mode 100644 index 00000000..a59d8011 --- /dev/null +++ b/data/recipes/sage-a1.5-mxfp4-df2.recipe @@ -0,0 +1,35 @@ +# sage-a1.5-mxfp4-df2.recipe -- Sage-A1.5 at MXFP4 with incoai's Qwen3.6-35B-A3B DFlash2 drafter +# merged in place of the MTP head. The trunk and the drafter's linears are rounded to MXFP4 +# (`fp4_e2m1`, an e8m0 exponent per 32 of K, the OCP rule), everything else as the checkpoint holds +# it. Trained from bf16 ideally: the source here is Sage-A1.5-FP8's per-row FP8 release, which +# carries one rounding already, so this is a second quantisation of the same weights. +# +# rad-convert InternScience/Sage-A1.5-FP8 --draft-model incoai/Qwen3.6-35B-A3B-DFlash2 \ +# --recipe data/recipes/sage-a1.5-mxfp4-df2.recipe -o sage-a1.5-mxfp4-df2.rad +# +# The trunk's rule set is sage-a1.5-fp8.recipe's, with `codes=fp4_e2m1 group=32 scale=e8m0` in +# place of block fp8 (the OCP rule needs no second level: `mx` is the default for e8m0). The +# DFlash2 drafter uses the same rules as the trunk's linears, and its draft head stays the 2-bit +# copy. + +blk.*.attn_qg.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ssm_inz.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ssm_out.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ffn_gate_up_exps.*.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ffn_down_exps.*.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ffn_gate_up_shexp.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +blk.*.ffn_down_shexp.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 + +output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16 + +dflash.fc.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_q.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_k.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_v.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.attn_output.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_gate_up.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.blk.*.ffn_down.weight rtn codes=fp4_e2m1 group=32 scale=e8m0 +dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16 diff --git a/deploy/compose/sage-a1.5-mxfp4-df2.yaml b/deploy/compose/sage-a1.5-mxfp4-df2.yaml new file mode 100644 index 00000000..db62a6d8 --- /dev/null +++ b/deploy/compose/sage-a1.5-mxfp4-df2.yaml @@ -0,0 +1,21 @@ +# Sage-A1.5 with incoai's Qwen3.6-35B-A3B DFlash2 drafter in place of the MTP head, made by +# data/recipes/sage-a1.5-mxfp4-df2.recipe. The trunk linears, the routed and shared experts and the +# drafter's linears are OCP-MXFP4 (fp4_e2m1, one e8m0 scale per 32 of K); output.weight stays block +# FP8 and the draft head stays the 2-bit copy. The container is 19.52 GiB against 34.45 GiB for the +# block-FP8 sibling, and at tp2 it leaves ~8 GiB a card more VRAM for the cache (25.8 GiB against +# 33.8 GiB of weights+state a card). +# +# The profile below is the measured one on the deployment box: ten 262,144-token sessions, the whole +# expert plane in VRAM. Sampling is the model card's (temp 1.0, top_p 0.95, top_k 20, presence 1.5). +name: radiance-sage-a1.5-mxfp4-df2 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-sage-a1.5-mxfp4-df2 + command: > + --model /models/sage-a1.5-mxfp4-df2.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 10 --max-model-len 262144 --kv-cache-dtype fp8 + --gpu-headroom-mib 96 + --num-speculative-tokens auto --max-num-batched-tokens 2048 + --temp 1.0 --top-p 0.95 --top-k 20 --presence-penalty 1.5 From 66a1d5aa151538a8bd7a7b0f72a3c97ed64cfa5a Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:16 +0200 Subject: [PATCH 145/152] kv tiers: rad_kv_group_replicated -- a group every rank holds whole is kept once a host slot Under tensor parallelism a host slot held every rank's shard of an entry end to end, so a group every rank holds whole (an MLA latent cache computed from a replicated projection) was stored once a rank: on GLM-5.3-Flash at eight ranks 396.75 KiB a 4-token block for 49.59 KiB of distinct bytes. The plugin now says which paged groups are replicated (additive export, RAD_ABI_VERSION does not move), and the slot holds those once, in one window at its front that rank 0 writes and every rank reads back on a restore; the sharded groups follow, one window a rank, as before. Without the declaration nothing changes. TierExec::slot_layout is the one place the slot arithmetic lives: bringup takes the windows from it, and it refuses a group replicated on one rank but zero, unflagged or another width on another. A follower moves only its own window on a copy out (nothing, when every cached group is replicated) and both windows on a restore. The startup log names what is held once and the tokens the tier holds either way. RADIANCE_DEBUG_TIER_VERIFY now covers the claim: each follower gathers the replicated groups into a pinned scratch beside the copy and hashes them once landed, and the engine, once every rank has landed, has the leader compare its window with every follower's sum. mem_test moves a chain through the real TierExec with a replicated and a sharded group at 1, 2 and 8 ranks, the ranks' copies differing on purpose, and checks every rank gets the leader's bytes back; beside a zero group; the verify path alike and differing; and the layout's refusal. Co-Authored-By: Claude Fable 5.1 --- abi/rad_builder.h | 10 ++ core/build/rad_build.h | 1 + core/build/rad_builder.cpp | 33 +++++++ core/engine.cpp | 12 +++ core/engine_bringup.cpp | 40 +++++--- core/mem/kv.cpp | 1 + core/mem/kv.h | 4 + core/mem/kvtier.h | 4 +- core/rad_core.h | 1 + core/runtime/tierexec.cpp | 192 +++++++++++++++++++++++++++++++------ core/runtime/tierexec.h | 88 ++++++++++++++--- docs/GUIDE.md | 16 ++++ spec.md | 17 +++- tests/arch_fakes.h | 13 ++- tests/mem_test.cpp | 145 +++++++++++++++++++++++----- 15 files changed, 490 insertions(+), 87 deletions(-) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index e3a3a477..272987a3 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -451,6 +451,16 @@ int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, * at issue. Additive export. */ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g); +/* Every rank holds the same bytes for this paged group, so a tier stores it once. Under tensor + * parallelism a host slot for a cached entry is otherwise every rank's shard end to end; a group + * declared replicated takes one window at the front of the slot, written by rank 0 and read by + * every rank on a restore. The plugin asserts the replication (an MLA latent cache that every + * rank computes whole, an indexer's key cache every rank pools into); the engine moves bytes and + * cannot know. RADIANCE_DEBUG_TIER_VERIFY checks the claim: each follower hashes what it would + * have written and the leader compares. Paged groups only, and never a group this rank declared + * zero. No effect at one rank. Additive export; RAD_ABI_VERSION does not move. */ +int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g); + #define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \ (int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf)) diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 3b008686..23ea6682 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -144,6 +144,7 @@ public: int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi, const int64_t* total, int n); int kv_group_zero(rad_kvgroup g); + int kv_group_replicated(rad_kvgroup g); /* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns * RAD_OK, or the first structural error class. Resolution misses are not errors here: an diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 3ff32f5e..5de8deb5 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -928,10 +928,38 @@ int Builder::kv_group_zero(rad_kvgroup h) { prog_.kv_groups[h].name.c_str()); return RAD_E_INVAL; } + if (prog_.kv_groups[h].replicated) { + err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group declared replicated; a " + "replicated group is held whole on every rank", prog_.kv_groups[h].name.c_str()); + return RAD_E_INVAL; + } prog_.kv_groups[h].zero = true; return RAD_OK; } +int Builder::kv_group_replicated(rad_kvgroup h) { + if (finished_) { + err(RAD_E_STATE, "kv_group_replicated after declare finished"); + return RAD_E_STATE; + } + if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL; + /* Paged groups only: the tiers move blocks. A linear or conv group's state travels in the + * checkpoint store, which has no such window. */ + const int kind = prog_.kv_groups[h].decl.kind; + if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) { + err(RAD_E_INVAL, "kv group '%s': kv_group_replicated on a group that is not paged", + prog_.kv_groups[h].name.c_str()); + return RAD_E_INVAL; + } + if (prog_.kv_groups[h].zero) { + err(RAD_E_INVAL, "kv group '%s': kv_group_replicated on a group declared zero; a zero " + "rank holds none of it", prog_.kv_groups[h].name.c_str()); + return RAD_E_INVAL; + } + prog_.kv_groups[h].replicated = true; + return RAD_OK; +} + /* ================================================================== name map */ int Builder::decl_name_map(const RadNameMap* m) { if (finished_) { err(RAD_E_STATE, "decl_name_map after declare finished"); return RAD_E_STATE; } @@ -2319,6 +2347,11 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { return B(b)->kv_group_zero(g); } +int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g) { + if (!b) return RAD_E_INVAL; + return B(b)->kv_group_replicated(g); +} + int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) { if (!b) return RAD_E_INVAL; return B(b)->decl_name_map(m); diff --git a/core/engine.cpp b/core/engine.cpp index 8569750f..2921c5cf 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1246,6 +1246,18 @@ void Engine::tier_tick() { } if (ranks_.size() > 1) (void)rad_dev_set(lead.device); if (all) { + /* RADIANCE_DEBUG_TIER_VERIFY: now that every rank's window has landed, each + * follower's hash of the replicated groups it gathered is held against the window + * the leader wrote (rad_kv_group_replicated's claim). The sums are taken either way, + * so a failed batch leaves none behind. */ + if (lead.tierx.verifying_replicated()) { + for (size_t i = 1; i < ranks_.size(); ++i) + for (const TierJob& j : P.copy) { + uint64_t sum = 0; + if (ranks_[i]->tierx.take_replicated_sum(j.key, &sum) && good) + (void)lead.tierx.verify_replicated(j, (int)i, sum); + } + } /* A copy is good only if every rank's shard landed; otherwise the host copy is * partly stale, so the whole batch fails and every slot goes back. */ const std::vector ok(P.copy.size(), good ? 1 : 0); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index caf81846..9b60aaee 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -3050,21 +3050,17 @@ int Engine::configure_kv() { { const bool tier_asked = cfg_.prefix_cache_mib > 0; const std::vector& cg = ranks_[0]->prefix.cached_groups(); - /* One slot holds every rank's shard of an entry; each rank writes only its window. Shards - * can differ or be empty (uneven heads, rad_kv_group_zero), so a slot is the sum and each - * window starts where the previous ends. TierExec::sizes uses the largest rank's entry, - * since the staging ring is per rank. */ - std::vector rank_entry(ranks_.size(), 0), entry_off(ranks_.size(), 0); - int64_t entry_bytes = 0, slot_bytes = 0; - for (size_t i = 0; i < ranks_.size(); ++i) { - for (int32_t g : cg) { - const KVGroupPlan* p = ranks_[i]->kv.plan(g); - if (p && p->paged()) rank_entry[i] += p->bytes_per_block; - } - entry_off[i] = slot_bytes; - slot_bytes += rank_entry[i]; - entry_bytes = std::max(entry_bytes, rank_entry[i]); - } + /* One slot holds the whole engine's entry: the groups every rank holds alike + * (rad_kv_group_replicated) once, at the front, then every rank's own shard in its own + * window. Shards can differ or be empty (uneven heads, rad_kv_group_zero). The layout is + * TierExec's, so the arithmetic here and the copies agree; TierExec::sizes takes the + * largest rank's entry, since the staging ring is per rank. */ + std::vector rank_kv; + for (auto& r : ranks_) rank_kv.push_back(&r->kv); + TierExec::SlotLayout layout; + RAD_TRY(TierExec::slot_layout(rank_kv, cg, &layout)); + const std::vector& entry_off = layout.own_off; + const int64_t entry_bytes = layout.entry_bytes, slot_bytes = layout.slot_bytes; /* Snapshots live in the checkpoint store (--checkpoint-slots); --prefix-cache-mib is for * blocks only. */ @@ -3092,6 +3088,20 @@ int Engine::configure_kv() { * fit is right after the turn. */ const int64_t held = T.arena().capacity() * tc.block_tokens; const int64_t ctx = cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train; + if (layout.rep_bytes > 0 && ranks_.size() > 1) { + /* What the slot would be with every rank's copy of the replicated groups. */ + const int64_t each = slot_bytes + layout.rep_bytes * (int64_t)(ranks_.size() - 1); + std::string names; + for (const std::string& n : layout.replicated) + names += (names.empty() ? "" : ", ") + n; + RAD_INFO("kv tiers: %s (%s of each entry) is the same on every rank and held " + "once a slot: %s a slot rather than %s, so --prefix-cache-mib %lld " + "holds %lld tokens rather than %lld", + names.c_str(), humanb(layout.rep_bytes).c_str(), + humanb(slot_bytes).c_str(), humanb(each).c_str(), + (long long)cfg_.prefix_cache_mib, (long long)held, + (long long)(tc.host_cap_bytes / each * tc.block_tokens)); + } if (held < ctx) RAD_WARN("kv tiers: --prefix-cache-mib %lld holds %lld tokens of context (%s " "per %lld-token block), less than one --max-model-len %lld " diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 2d2eb0cb..d6193736 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -228,6 +228,7 @@ int KVManager::plan_groups(const std::vector& groups, const Config& p.bytes_per_block = 0; p.bytes_per_state = 0; } + p.replicated = g.replicated && p.paged() && !g.zero; plans_.push_back(std::move(p)); } bundling_ = compare_bundling(bundles); diff --git a/core/mem/kv.h b/core/mem/kv.h index a29e8c64..046edb8b 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -73,6 +73,10 @@ struct KVGroupPlan { * block count (one block table serves every rank); its costs are zero and nothing is carved. * No op on this rank names it (issue refuses a group with no pool bound). */ bool zero = false; + /* rad_kv_group_replicated: every rank holds the same bytes, so a tier slot carries this + * group once, in a window at its front that rank 0 writes and every rank reads + * (TierExec::slot_layout). The pool is carved as for any group. */ + bool replicated = false; int64_t n_states = 0; /* LINEAR/CONV: n_seq_states * state_copies */ /* Physical slots per logical state: 1, or 2 under speculation. A verify runs 1 + n_spec * tokens through the recurrence before acceptance is known; libr4d keeps the committed state diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index 585eef76..20eccac2 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -96,7 +96,9 @@ class IdleTiers { public: struct Config { int64_t host_cap_bytes = 0; /* 0 is off */ - int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */ + /* One host slot: every cached group's bytes_per_block, under tensor parallelism every + * rank's own shard end to end and a replicated group once (TierExec::SlotLayout). */ + int64_t entry_bytes = 0; /* ---- the linear half ---- * `ckpt_bytes` is one snapshot including every rank's shard, like `entry_bytes`. The * snapshots live in the engine's checkpoint store, `ckpt_slots` deep; reported here, not diff --git a/core/rad_core.h b/core/rad_core.h index 62329504..6951541f 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -287,6 +287,7 @@ struct KVGroupInfo { int64_t bytes_per_state = 0; /* linear/conv: per sequence */ std::vector layers; bool zero = false; /* rad_kv_group_zero: declared for position, nothing carved */ + bool replicated = false; /* rad_kv_group_replicated: the same bytes on every rank */ /* Bound only at meta.n_layers and above: the drafter's own cache, which no trunk layer reads. * Set at declare (Builder::finish_kv_groups). */ bool drafter = false; diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index b4d4c90a..76f005b3 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -28,7 +28,6 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, shared_ = shared; RAD_TRY(rad_dev_set(device_)); - int64_t off = 0; for (int32_t g : groups) { const KVGroupPlan* p = kv->plan(g); if (!p || !p->paged()) continue; @@ -39,7 +38,7 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, gi.layer_stride = p->layer_stride(); gi.n_blocks = p->n_blocks; gi.base = p->base; - gi.off = off; + gi.replicated = p->replicated; if (p->zero) { gi.zero = true; gi_.push_back(gi); @@ -60,10 +59,18 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, close(); return RAD_E_UNSUPPORTED; } - off += gi.n_layers * gi.frag; gi_.push_back(gi); } if (gi_.empty()) return RAD_E_UNSUPPORTED; + /* The staging entry is the replicated groups first, then this rank's own, each in cached-group + * order, so the two windows of the slot are each one contiguous run of the entry. */ + int64_t off = 0; + for (GroupInfo& gi : gi_) + if (gi.replicated && !gi.zero) { gi.off = off; off += gi.n_layers * gi.frag; } + rep_bytes_ = off; + for (GroupInfo& gi : gi_) + if (!gi.replicated && !gi.zero) { gi.off = off; off += gi.n_layers * gi.frag; } + own_bytes_ = off - rep_bytes_; /* Every cached group is zero on this rank, so its entry would be empty. One rank that cannot * take part turns the tiers off for all. */ if (off == 0) { @@ -75,18 +82,76 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, entry_bytes_ = off; /* Nothing is built on the device here; see device_init(). */ - verify_ = leader && std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr; + verify_ = std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr; + verify_rep_ = verify_ && !leader_ && rep_bytes_ > 0; - char buf[320]; + char buf[400]; std::snprintf(buf, sizeof buf, - "kv tier transfer: %zu paged group(s), %s an entry, batches of %d through " + "kv tier transfer: %zu paged group(s), %s an entry%s%s%s, batches of %d through " "gather_rows/scatter_rows at u8", - gi_.size(), humanb(entry_bytes_).c_str(), max_batch_); + gi_.size(), humanb(entry_bytes_).c_str(), + rep_bytes_ > 0 ? " (" : "", + rep_bytes_ > 0 ? humanb(rep_bytes_).c_str() : "", + rep_bytes_ > 0 ? " of it replicated on every rank and held once a slot)" : "", + max_batch_); report_ = buf; enabled_ = true; return RAD_OK; } +int TierExec::slot_layout(const std::vector& ranks, + const std::vector& groups, SlotLayout* out) { + if (!out || ranks.empty()) return RAD_E_INVAL; + for (const KVManager* kv : ranks) if (!kv) return RAD_E_INVAL; + SlotLayout L; + L.own_off.assign(ranks.size(), 0); + L.own_bytes.assign(ranks.size(), 0); + for (int32_t g : groups) { + const KVGroupPlan* p0 = ranks[0]->plan(g); + if (!p0 || !p0->paged()) continue; + bool replicated = false; + for (size_t i = 0; i < ranks.size(); ++i) { + const KVGroupPlan* p = ranks[i]->plan(g); + replicated = replicated || (p && p->replicated); + } + if (!replicated) { + for (size_t i = 0; i < ranks.size(); ++i) { + const KVGroupPlan* p = ranks[i]->plan(g); + if (p && p->paged()) L.own_bytes[i] += p->bytes_per_block; + } + continue; + } + /* Every rank reads the one window back into its own pool, so the group must be the same + * width everywhere, declared replicated everywhere and carved everywhere. */ + for (size_t i = 0; i < ranks.size(); ++i) { + const KVGroupPlan* p = ranks[i]->plan(g); + const char* why = !p || !p->paged() ? "does not hold it as a paged group" + : p->zero ? "declares it zero (rad_kv_group_zero)" + : !p->replicated ? "does not declare it replicated" + : p->bytes_per_block != p0->bytes_per_block + ? "holds it at another width" + : nullptr; + if (!why) continue; + RAD_ERR("kv tiers: KV group '%s' is declared replicated (rad_kv_group_replicated) on " + "one rank, but rank %zu %s. A replicated group is held whole and alike on " + "every rank, since every rank restores it from the one copy a slot holds.", + p0->name.c_str(), i, why); + return RAD_E_STATE; + } + L.rep_bytes += p0->bytes_per_block; + L.replicated.push_back(p0->name); + } + int64_t slot = L.rep_bytes; + for (size_t i = 0; i < ranks.size(); ++i) { + L.own_off[i] = slot; + slot += L.own_bytes[i]; + L.entry_bytes = std::max(L.entry_bytes, L.rep_bytes + L.own_bytes[i]); + } + L.slot_bytes = slot; + *out = std::move(L); + return RAD_OK; +} + TierExec::Sizes TierExec::sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size) { Sizes s; if (entry_bytes <= 0) return s; @@ -118,6 +183,10 @@ void TierExec::close() { order_.clear(); verify_pending_.clear(); entry_bytes_ = 0; + rep_bytes_ = own_bytes_ = 0; + verify_ = verify_rep_ = false; + out_sum_.clear(); + rep_sum_.clear(); enabled_ = false; leader_ = false; reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; @@ -128,6 +197,7 @@ void TierExec::release_device() { if (stage_) { rad_dev_free(stage_, RAD_MEM_DEVICE); stage_ = nullptr; } if (idx_dev_) { rad_dev_free(idx_dev_, RAD_MEM_DEVICE); idx_dev_ = nullptr; } if (idx_host_) { rad_dev_free(idx_host_, RAD_MEM_HOST_PINNED); idx_host_ = nullptr; } + if (vrep_) { rad_dev_free(vrep_, RAD_MEM_HOST_PINNED); vrep_ = nullptr; } for (int i = 0; i < kRing; ++i) { if (ring_ev_[i]) rad_event_destroy(ring_ev_[i]); ring_ev_[i] = nullptr; @@ -156,7 +226,11 @@ int TierExec::device_init() { bool ev = rad_event_create(&ev_compute_) == RAD_OK && rad_event_create(&ev_copy_) == RAD_OK && rad_event_create(&ev_restore_) == RAD_OK; for (int i = 0; i < kRing && ev; ++i) ev = rad_event_create(&ring_ev_[i]) == RAD_OK; - if (!stage_ || !idx_dev_ || !idx_host_ || !ev) { release_device(); return RAD_E_NOMEM; } + if (verify_rep_) vrep_ = (char*)rad_dev_alloc(copy_idx_ * rep_bytes_, RAD_MEM_HOST_PINNED); + if (!stage_ || !idx_dev_ || !idx_host_ || !ev || (verify_rep_ && !vrep_)) { + release_device(); + return RAD_E_NOMEM; + } /* Borrow the mover's maintenance stream if there is one; both move bytes nobody waits for, * and a fourth hardware queue costs about 13 ms per decode step. Never the step's own * stream, or a copy out would become a dependency of the next token. */ @@ -212,29 +286,62 @@ int TierExec::run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int /* ------------------------------------------------------------------ RADIANCE_DEBUG_TIER_VERIFY */ -static uint64_t tier_fnv(const void* p, int64_t n) { - uint64_t h = 1469598103934665603ull; +/* FNV-1a, continued from `h` so one sum can run over the two windows of a slot. */ +static uint64_t tier_fnv_from(uint64_t h, const void* p, int64_t n) { const unsigned char* b = (const unsigned char*)p; for (int64_t i = 0; i < n; ++i) { h ^= b[i]; h *= 1099511628211ull; } return h; } - -void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n) { - if (!verify_ || !leader_ || !p || n <= 0) return; - out_sum_[key] = tier_fnv(p, n); +static uint64_t tier_fnv(const void* p, int64_t n) { + return tier_fnv_from(1469598103934665603ull, p, n); } -void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n) { - if (!verify_ || !leader_ || !p || n <= 0) return; +/* One sum over the entry as the slot holds it: the replicated window, then this rank's own. */ +uint64_t TierExec::entry_sum(const char* slot) const { + const uint64_t h = tier_fnv(slot, rep_bytes_); + return tier_fnv_from(h, slot + slot_off_, own_bytes_); +} + +void TierExec::verify_note(const BlockHash& key, const char* slot) { + if (!verify_ || !leader_ || !slot) return; + out_sum_[key] = entry_sum(slot); +} + +void TierExec::verify_check(const BlockHash& key, const char* slot) { + if (!verify_ || !leader_ || !slot) return; auto it = out_sum_.find(key); if (it == out_sum_.end()) return; /* never went out through this process */ - const uint64_t back = tier_fnv(p, n); + const uint64_t back = entry_sum(slot); if (back == it->second) return; RAD_ERR("kv tiers: the attention blocks for %s came back different (%016llx out, %016llx in); " "the tier moved the wrong bytes", key.str().c_str(), (unsigned long long)it->second, (unsigned long long)back); } +bool TierExec::take_replicated_sum(const BlockHash& key, uint64_t* sum) { + auto it = rep_sum_.find(key); + if (it == rep_sum_.end()) return false; + if (sum) *sum = it->second; + rep_sum_.erase(it); + return true; +} + +bool TierExec::verify_replicated(const TierJob& j, int rank, uint64_t follower_sum) { + if (!verify_ || !leader_ || rep_bytes_ <= 0 || !tiers_ || j.host_slot < 0) return false; + const char* slot = (const char*)tiers_->arena().at(j.host_slot); + if (!slot) return false; + ++st_.rep_checked; + const uint64_t mine = tier_fnv(slot, rep_bytes_); + if (mine == follower_sum) return true; + ++st_.rep_mismatch; + RAD_ERR("kv tiers: the replicated groups of %s differ between rank 0 (%016llx) and rank %d " + "(%016llx). The plugin declared them replicated (rad_kv_group_replicated) and rank %d " + "holds other bytes; its restore would read rank 0's.", + j.key.str().c_str(), (unsigned long long)mine, rank, (unsigned long long)follower_sum, + rank); + return false; +} + /* ------------------------------------------------------------------ helpers */ /* Like RAD_TRY, but the first failure is logged with the call it came from. A failing tier is @@ -276,11 +383,28 @@ int TierExec::copy_runs(const std::vector& order, size_t first, int64_ while (k + run < n && order[first + (size_t)(k + run)]->host_slot == s0 + run) ++run; char* host = (char*)tiers_->arena().at(s0); if (!host) return RAD_E_STATE; - host += slot_off_; char* dev = (char*)stage_ + k * entry_bytes_; - const int st = out - ? rad_memcpy_2d_async(host, slot_bytes_, dev, entry_bytes_, entry_bytes_, run, stream_) - : rad_memcpy_2d_async(dev, entry_bytes_, host, slot_bytes_, entry_bytes_, run, stream_); + int st = RAD_OK; + if (out) { + /* The replicated window is the leader's to write; a verifying follower keeps its own + * gather beside the copy, indexed by the job's place in the pass. */ + if (rep_bytes_ > 0 && leader_) + st = rad_memcpy_2d_async(host, slot_bytes_, dev, entry_bytes_, rep_bytes_, run, + stream_); + if (st == RAD_OK && verify_rep_ && vrep_) + st = rad_memcpy_2d_async(vrep_ + (int64_t)(first + (size_t)k) * rep_bytes_, + rep_bytes_, dev, entry_bytes_, rep_bytes_, run, stream_); + if (st == RAD_OK && own_bytes_ > 0) + st = rad_memcpy_2d_async(host + slot_off_, slot_bytes_, dev + rep_bytes_, + entry_bytes_, own_bytes_, run, stream_); + } else { + if (rep_bytes_ > 0) + st = rad_memcpy_2d_async(dev, entry_bytes_, host, slot_bytes_, rep_bytes_, run, + stream_); + if (st == RAD_OK && own_bytes_ > 0) + st = rad_memcpy_2d_async(dev + rep_bytes_, entry_bytes_, host + slot_off_, + slot_bytes_, own_bytes_, run, stream_); + } if (st != RAD_OK) return st; k += run; } @@ -326,22 +450,27 @@ int TierExec::enqueue_copy(std::vector& jobs, RadStream compute) { for (int64_t s = 0; s < n; s += max_batch_) { const int64_t c = std::min(max_batch_, n - s); for (size_t gidx = 0; gidx < gi_.size(); ++gidx) - for (int64_t l = 0; l < gi_[gidx].n_layers && !gi_[gidx].zero; ++l) + for (int64_t l = 0; l < gi_[gidx].n_layers && gathers(gi_[gidx]); ++l) TIER_TRY(run_rows(gi_[gidx].gather, /*scatter=*/false, gi_[gidx], l, stage_, idx_dev_ + (int64_t)gidx * n + s, c), "the gather out of the pool"); TIER_TRY(copy_runs(order_, (size_t)s, c, /*out=*/true), "the copy to host memory"); } - st_.bytes_out += n * entry_bytes_; + st_.bytes_out += n * (leader_ ? entry_bytes_ : own_bytes_); } TIER_TRY(rad_event_record(ev_copy_, stream_), "marking the copy"); copy_out_ = true; ++st_.passes; st_.jobs += (int64_t)jobs.size(); - if (verify_) - for (const TierJob& j : jobs) - verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot}); + if (verify_) { + int64_t ord = 0; + for (const TierJob& j : jobs) { + const bool moved = !j.blocks.empty(); + verify_pending_.push_back({j.key, moved ? j.host_slot : -1, moved ? ord : -1}); + if (moved) ++ord; + } + } return RAD_OK; } @@ -353,9 +482,11 @@ int TierExec::copy_state() { copy_out_ = false; if (q > 0 && verify_) { for (const VerifyNote& v : verify_pending_) { - if (v.host_slot >= 0) - verify_note(v.key, (char*)tiers_->arena().at(v.host_slot) + slot_off_, - entry_bytes_); + if (v.host_slot < 0) continue; + if (leader_) + verify_note(v.key, (const char*)tiers_->arena().at(v.host_slot)); + else if (verify_rep_ && vrep_ && v.ord >= 0) + rep_sum_[v.key] = tier_fnv(vrep_ + v.ord * rep_bytes_, rep_bytes_); } } verify_pending_.clear(); @@ -432,8 +563,7 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute, order_.clear(); for (size_t i = 0; i < m; ++i) order_.push_back(&jobs[i]); for (size_t i = 0; i < m; ++i) - verify_check(jobs[i].key, (char*)tiers_->arena().at(jobs[i].host_slot) + slot_off_, - entry_bytes_); + verify_check(jobs[i].key, (const char*)tiers_->arena().at(jobs[i].host_slot)); /* From here a failure leaves blocks partly overwritten. Mark jobs started first, so report() * drops a failed started job instead of trusting its host copy. The compute stream waits on diff --git a/core/runtime/tierexec.h b/core/runtime/tierexec.h index b070cb80..40c2def2 100644 --- a/core/runtime/tierexec.h +++ b/core/runtime/tierexec.h @@ -20,9 +20,15 @@ * per staging batch. * * Staging layout. Device staging is `max_batch * entry_bytes`; one entry is [group][layer][fragment] - * end to end. For a given (group, layer) the destination rows sit at stride `entry_bytes` from a - * base in the first entry, which is `gather_rows`'s `y` pitch, so one launch writes every entry's - * fragment in place and the host side is one strided copy per run of consecutive arena slots. + * end to end, the replicated groups first. For a given (group, layer) the destination rows sit at + * stride `entry_bytes` from a base in the first entry, which is `gather_rows`'s `y` pitch, so one + * launch writes every entry's fragment in place and the host side is one strided copy per window + * per run of consecutive arena slots. + * + * The host slot. Under tensor parallelism a slot holds the whole engine's entry. A group every + * rank holds whole (rad_kv_group_replicated) is in the slot once, in one window at its front + * that rank 0 writes and every rank reads back; the groups each rank holds a shard of follow, + * one window per rank. slot_layout() is the one place the arithmetic lives. */ #pragma once #include "mem/kv.h" @@ -48,6 +54,23 @@ public: const std::vector& groups, int max_batch, int64_t max_copy, int64_t max_chain, bool leader, int device, int64_t slot_off, RadStream shared); + + /* One shared host slot across the ranks. `[0, rep_bytes)` is the replicated window, the + * replicated cached groups in cached-group order; rank r's own groups follow at + * `own_off[r]`, `own_bytes[r]` wide (uneven heads and rad_kv_group_zero make these differ). + * `entry_bytes` is the largest rank's staging entry, rep_bytes + own_bytes, which sizes() + * takes. Checked here: a group replicated on one rank is replicated, not zero and the same + * width on every rank, since every rank reads the one window back; a violation stops bringup + * with the group named (RAD_E_STATE). */ + struct SlotLayout { + int64_t slot_bytes = 0; + int64_t rep_bytes = 0; + int64_t entry_bytes = 0; + std::vector own_off, own_bytes; + std::vector replicated; /* the replicated groups' names, for the report */ + }; + static int slot_layout(const std::vector& ranks, + const std::vector& groups, SlotLayout* out); void close(); bool enabled() const { return enabled_; } std::string report() const { return report_; } @@ -96,7 +119,25 @@ public: * off-device or already has work outstanding. */ bool plan_promote(const BlockHash& key, TierJob* out); /* leader only */ - struct Stats { int64_t passes = 0, jobs = 0, bytes_out = 0, bytes_in = 0; }; + /* ---------------- RADIANCE_DEBUG_TIER_VERIFY, the replicated window ---------------- + * + * A replicated group's bytes are the plugin's claim. Under the variable a follower gathers the + * replicated groups it would otherwise leave to the leader into a pinned scratch beside the + * copy and hashes them once landed; the engine, once every rank has landed, takes each sum + * and has the leader compare it with the window it wrote. Off, a follower moves nothing for + * the replicated groups. */ + bool verifying_replicated() const { return verify_ && rep_bytes_ > 0; } + /* Follower: the sum of the replicated bytes it gathered for `key` in the last copy out, taken + * once. False when there is none (not verifying, no replicated group, or not in that copy). */ + bool take_replicated_sum(const BlockHash& key, uint64_t* sum); + /* Leader: compares `follower_sum` from rank `rank` with the window the slot holds for job + * `j`; a mismatch is logged and counted (Stats::rep_mismatch). */ + bool verify_replicated(const TierJob& j, int rank, uint64_t follower_sum); + + struct Stats { + int64_t passes = 0, jobs = 0, bytes_out = 0, bytes_in = 0; + int64_t rep_checked = 0, rep_mismatch = 0; /* verify_replicated's tallies */ + }; const Stats& stats() const { return st_; } private: @@ -111,6 +152,9 @@ private: /* rad_kv_group_zero: no shard on this rank. Kept in place because a job's block ids are * one per cached group in the same order on every rank; it moves no bytes. */ bool zero = false; + /* rad_kv_group_replicated: staged at the front of the entry and in the slot's replicated + * window; a follower gathers it only to verify, and scatters it on every restore. */ + bool replicated = false; Resolved gather, scatter; }; @@ -127,9 +171,17 @@ private: void warn_once(const char* what, int st); int run_rows(const Resolved& r, bool scatter, const GroupInfo& gi, int64_t layer, void* stage_base, const int32_t* d_idx, int64_t n_jobs); - /* One strided copy per run of consecutive arena slots, `n` entries starting at job `first` of - * `order`. To host when `out`, from host otherwise. */ + /* One strided copy per window per run of consecutive arena slots, `n` entries starting at job + * `first` of `order`. To host when `out` (the replicated window from the leader only), from + * host otherwise. */ int copy_runs(const std::vector& order, size_t first, int64_t n, bool out); + /* Whether this rank gathers group `gi` for a copy out: its own groups always, a replicated + * one as the leader or to verify. */ + bool gathers(const GroupInfo& gi) const { + return !gi.zero && (!gi.replicated || leader_ || verify_rep_); + } + /* The hash of one entry as the slot holds it: the replicated window, then this rank's own. */ + uint64_t entry_sum(const char* slot) const; int enqueue_copy(std::vector& jobs, RadStream compute); bool enabled_ = false; @@ -141,11 +193,13 @@ private: /* This rank's card. Allocations and launches use the current device, and the engine loop leaves * the last rank's device current, so it is set explicitly. */ int device_ = -1; - /* This rank's offset inside a shared host slot. A slot holds the whole engine's entry, which - * under tensor parallelism is n_ranks distinct KV shards, so the slot is n_ranks entries wide - * and each rank touches only its own window. */ + /* This rank's windows of a shared host slot (SlotLayout): its own groups at `slot_off_`, + * `own_bytes_` wide, and the replicated groups at the slot's front, `rep_bytes_` wide, which + * only the leader writes. The staging entry is [replicated][own], entry_bytes_ in all. */ int64_t slot_off_ = 0; - int64_t slot_bytes_ = 0; /* the whole shared slot: n_ranks * entry_bytes_ */ + int64_t slot_bytes_ = 0; /* the whole shared slot */ + int64_t rep_bytes_ = 0; + int64_t own_bytes_ = 0; Registry* reg_ = nullptr; KVManager* kv_ = nullptr; IdleTiers* tiers_ = nullptr; @@ -184,14 +238,18 @@ private: * * Round-trip check: hashes each entry going out and coming back and names the entry when they * differ, separating "the tier moved wrong bytes" from a downstream fault. A diagnostic, not a - * guard: host hashing costs on every entry. Off unless set; leader-only because the map is keyed - * by an object followers do not own. A copy out is hashed once landed (first seen by copy_state). */ + * guard: host hashing costs on every entry. Off unless set. The round trip is the leader's + * (the map is keyed by an object followers do not own); a follower's part is the replicated + * window, above. A copy out is hashed once landed (first seen by copy_state). */ bool verify_ = false; + bool verify_rep_ = false; /* a follower gathering the replicated groups to verify */ std::unordered_map out_sum_; - struct VerifyNote { BlockHash key; int32_t host_slot = -1; }; + std::unordered_map rep_sum_; /* follower */ + struct VerifyNote { BlockHash key; int32_t host_slot = -1; int64_t ord = -1; }; std::vector verify_pending_; - void verify_note(const BlockHash& key, const void* p, int64_t n); - void verify_check(const BlockHash& key, const void* p, int64_t n); + char* vrep_ = nullptr; /* pinned, max_copy_ * rep_bytes_: a follower's gather */ + void verify_note(const BlockHash& key, const char* slot); + void verify_check(const BlockHash& key, const char* slot); std::string report_; Stats st_; diff --git a/docs/GUIDE.md b/docs/GUIDE.md index fd97537d..99fc0402 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1213,6 +1213,22 @@ radiance --model m.rad --prefix-cache-mib 8192 --prefix-cache-ttl 3600 - `--prefix-cache-ttl S`: seconds an unused conversation is kept (default 3600); `0` keeps it until the memory is wanted. +**What a slot holds under tensor parallelism.** One host slot holds the whole engine's entry: each +rank's shard of every cached group, end to end, so a slot is as many entries wide as there are +ranks. A group every rank holds whole, which the architecture plugin declares with +`rad_kv_group_replicated`, is in the slot once: rank 0 writes it and every rank reads it back on a +restore. GLM-5.3-Flash declares both of its cached groups so (the MLA latent, which every rank +computes whole, and the DSA index cache, which every rank pools into), so at `--tp 8` a 4-token +block costs 49.59 KiB a slot (`kv_latent` 48.00 KiB over its 12 layers, `kv_dsa_index` 1.59 KiB) +rather than the 396.75 KiB of eight copies: 12.4 KiB a token rather than 99.2 KiB. +`--prefix-cache-mib 32768` then holds 2.7M tokens rather than 338K, and 80 GiB hold 6.8M rather +than 846K. The startup log names what is held once (`kv tiers: kv_latent, kv_dsa_index ... held +once a slot`) and the tokens the tier holds either way. The claim is the plugin's; under +`RADIANCE_DEBUG_TIER_VERIFY` every follower also hashes what it would have written and the leader +compares, logging `kv tiers: the replicated groups of ... differ between rank 0 and rank N` when +a rank holds other bytes. Sharded groups (a GQA model's K/V heads) are unaffected and still take a +window per rank. + Restoring a 200K-token turn costs a copy over PCIe; recomputing it costs minutes. On a hybrid model the recurrent state matters as much as the attention blocks: restoring the blocks diff --git a/spec.md b/spec.md index 9551f665..2eec3bd9 100644 --- a/spec.md +++ b/spec.md @@ -1082,6 +1082,18 @@ moving blocks one at a time would be all dispatch cost. Within a layer blocks ar packing a set is `gather_rows` and restoring is `scatter_rows` (`docs/OPS.md`): one launch per (group, layer) for a whole batch. +**Under tensor parallelism** the policy describes conversations, which are not sharded, and the +transfer is per rank. One host slot holds the whole engine's entry: a group every rank holds whole +(`rad_kv_group_replicated`, an MLA latent cache) once, in one window at the slot's front that rank +0 writes and every rank reads back; then each rank's own shard of the sharded groups, one window +per rank, which can differ in width (uneven heads, `rad_kv_group_zero`). `TierExec::slot_layout` +is the one place the arithmetic lives, and bringup refuses a group replicated on one rank but zero, +unflagged or another width on another. The leader plans and reports; a follower moves only its own +window and, under `RADIANCE_DEBUG_TIER_VERIFY`, also gathers the replicated groups so the leader +can compare its window with every follower's hash once the batch has landed everywhere, which is +how the plugin's claim is checked. On GLM-5.3-Flash at eight ranks, whose two cached groups are +both replicated, a slot is 49.59 KiB rather than 396.75 KiB. + **Recurrent state.** On a hybrid model a session is blocks plus recurrent state. The state lives in a slot of the snapshot store (pinned host memory, `--checkpoint-slots`), copied off the card after the step that produced it and back before the step that resumes from it, so it never holds VRAM. @@ -1143,7 +1155,10 @@ shows every collective where the plugin put it. The residual stream is replicated: every rank holds the whole hidden state between blocks. Weights that act only on the stream, such as hyper-connection mixing (`arch/common/rad_block_hc.h`), are -replicated too, since sharding them would add a collective at each use. +replicated too, since sharding them would add a collective at each use. A KV group every rank +holds whole, such as an MLA latent cache computed from a replicated projection, is declared +`rad_kv_group_replicated`, and the idle session tiers (§7.3) then keep it once a host slot instead +of once a rank; the core cannot tell from the graph, so the plugin says it. `lm_head` is vocabulary-sharded like any column-parallel weight, so the sampler (§13) runs a distributed top-k: each rank reduces its own shard and only the candidate sets are combined. Full diff --git a/tests/arch_fakes.h b/tests/arch_fakes.h index 03902ae4..f8fd6949 100644 --- a/tests/arch_fakes.h +++ b/tests/arch_fakes.h @@ -71,7 +71,7 @@ struct RecMap { std::vector src; int concat_dim = 0; }; -struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; }; +struct RecKV { std::string name; RadKVGroupDecl d{}; bool zero = false; bool replicated = false; }; struct RecIssue { rad_op op = 0; std::vector opd; @@ -325,9 +325,20 @@ extern "C" int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const in } extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL; + if (b->kv_groups[g - 1].replicated) return RAD_E_INVAL; b->kv_groups[g - 1].zero = true; return RAD_OK; } +/* Recorded like zero, and like the real builder refused on a zero or unpaged group. Not part of + * graph_hash(): the flag changes what a host tier slot holds, not the graph, so the pinned + * graphs stand. */ +extern "C" int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g) { + if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL; + RecKV& k = b->kv_groups[g - 1]; + if (k.zero || (k.d.kind != RAD_KV_FULL && k.d.kind != RAD_KV_WINDOW)) return RAD_E_INVAL; + k.replicated = true; + return RAD_OK; +} extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { if (!b || !d) return RAD_E_INVAL; b->drafter = *d; diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 2ad190f4..0a75602e 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -3930,15 +3930,19 @@ static unsigned char pat(int rank, int64_t layer, int32_t block, int64_t i) { return (unsigned char)(z ^ (z >> 31)); } -static void fill(Fixture& f, int rank) { +/* `alike`: a replicated group holds rank 0's bytes on every rank, as rad_kv_group_replicated + * promises. Without it the ranks differ there on purpose, so a follower restored from its own + * gather rather than the leader's window would show. */ +static void fill(Fixture& f, int rank, bool alike = false) { for (int32_t g : f.pc.cached_groups()) { const KVGroupPlan* p = f.kv.plan(g); if (p->zero) continue; + const int r = alike && p->replicated ? 0 : rank; const int64_t frag = p->layer_bytes_per_block(); for (int64_t l = 0; l < p->n_layers; ++l) for (int32_t b = 0; b < (int32_t)p->n_blocks; ++b) { unsigned char* row = (unsigned char*)p->base + l * p->layer_stride() + b * frag; - for (int64_t i = 0; i < frag; ++i) row[i] = pat(rank, g * 16 + l, b, i); + for (int64_t i = 0; i < frag; ++i) row[i] = pat(r, g * 16 + l, b, i); } } } @@ -3953,7 +3957,8 @@ static void scribble(Fixture& f) { } /* The number of entries whose blocks in `now` hold, in every cached group and layer, exactly what - * their blocks in `was` held before the move. */ + * their blocks in `was` held before the move: this rank's own bytes, and for a replicated group + * rank 0's, the one copy the slot holds. */ static int64_t same_bytes(Fixture& f, int rank, const std::vector>& was, const std::vector>& now) { const std::vector& cg = f.pc.cached_groups(); @@ -3963,12 +3968,13 @@ static int64_t same_bytes(Fixture& f, int rank, const std::vectorzero) continue; + const int r = p->replicated ? 0 : rank; const int64_t frag = p->layer_bytes_per_block(); for (int64_t l = 0; l < p->n_layers && ok; ++l) { const unsigned char* row = (const unsigned char*)p->base + l * p->layer_stride() + now[gi][k] * frag; for (int64_t i = 0; i < frag && ok; ++i) - ok = row[i] == pat(rank, cg[gi] * 16 + l, was[gi][k], i); + ok = row[i] == pat(r, cg[gi] * 16 + l, was[gi][k], i); } } good += ok; @@ -4005,8 +4011,24 @@ static std::vector two_paged_groups() { /* `zero_last`: the last rank keeps no attention cache (rad_kv_group_zero), so its window of a slot * is the narrower group alone and the windows are unequal; every rank still takes part in every - * job. */ -static void run_transfer(int world, bool fragment, bool zero_last = false) { + * job. `replicated`: the attention group is the same on every rank (rad_kv_group_replicated), so + * the slot holds it once at its front, written by rank 0 and read back by all. `verify`: under + * RADIANCE_DEBUG_TIER_VERIFY each follower's gather of the replicated group is compared with the + * leader's window; `alike` fills the replicated group the same on every rank, as the flag + * promises, so the comparison passes, and without it every entry is caught. */ +struct TransferCase { + int world = 1; + bool fragment = false; + bool zero_last = false; + bool replicated = false; + bool alike = false; + bool verify = false; +}; +static void run_transfer(const TransferCase& tc) { + const int world = tc.world; + const bool fragment = tc.fragment, zero_last = tc.zero_last; + if (tc.verify) setenv("RADIANCE_DEBUG_TIER_VERIFY", "1", 1); + else unsetenv("RADIANCE_DEBUG_TIER_VERIFY"); /* Host backend only: the stand-in kernels copy rows on the CPU, where host-backend "device" * memory lives; on a card the staging buffer is VRAM and production kernels apply. */ if (!device_is_host()) { @@ -4023,20 +4045,33 @@ static void run_transfer(int world, bool fragment, bool zero_last = false) { fx.push_back(std::make_unique()); fx.back()->cfg.checkpoint_slots = 0; std::vector groups = two_paged_groups(); - if (zero_last && r == world - 1) groups[1].zero = true; + /* The zero group is the one not replicated: attention, or the key cache beside a + * replicated attention group, which leaves that rank's own window empty. */ + if (zero_last && r == world - 1) groups[tc.replicated ? 2 : 1].zero = true; + if (tc.replicated) groups[1].replicated = true; REQUIRE_EQ(fx.back()->build_groups(groups), RAD_OK); } Fixture& f = *fx[0]; const std::vector& cg = f.pc.cached_groups(); REQUIRE_EQ(cg.size(), 2u); - /* A slot is the sum of the ranks' entries, each rank's window following the previous ones - * (Engine::configure_kv). */ - std::vector win_off((size_t)world, 0); - int64_t slot = 0; - for (int r = 0; r < world; ++r) { - win_off[(size_t)r] = slot; - for (int32_t g : cg) slot += fx[(size_t)r]->kv.plan(g)->bytes_per_block; - } + /* The slot as bringup lays it out: a replicated group once at the front, then each rank's own + * window following the previous ones. Checked against the plain sums here. */ + std::vector kvs; + for (auto& fp : fx) kvs.push_back(&fp->kv); + TierExec::SlotLayout L; + REQUIRE_EQ(TierExec::slot_layout(kvs, cg, &L), RAD_OK); + const int64_t attn = f.kv.plan(cg[0])->bytes_per_block; + int64_t sum = 0; + for (int r = 0; r < world; ++r) + for (int32_t g : cg) sum += fx[(size_t)r]->kv.plan(g)->bytes_per_block; + CHECK_EQ(L.rep_bytes, tc.replicated ? attn : 0); + CHECK_EQ(L.slot_bytes, tc.replicated ? sum - (world - 1) * attn : sum); + CHECK_EQ(L.own_off[0], L.rep_bytes); + for (int r = 1; r < world; ++r) + CHECK_EQ(L.own_off[(size_t)r], L.own_off[(size_t)r - 1] + L.own_bytes[(size_t)r - 1]); + CHECK_EQ(L.own_off[(size_t)world - 1] + L.own_bytes[(size_t)world - 1], L.slot_bytes); + const std::vector& win_off = L.own_off; + const int64_t slot = L.slot_bytes; /* Forty slots. Fragmented, every other one is taken and the copy goes out as twenty runs of * one; whole, as one run of twenty, where a rank's pitch through the shared slots decides where @@ -4075,7 +4110,7 @@ static void run_transfer(int world, bool fragment, bool zero_last = false) { REQUIRE_EQ(f.pc.lookup(prompt, {}, &hit).n_attn_tokens, 320); const std::vector> was = hit; CHECK(was[0][0] != was[1][0]); - for (int r = 0; r < world; ++r) fill(*fx[(size_t)r], r); + for (int r = 0; r < world; ++r) fill(*fx[(size_t)r], r, tc.alike); /* ---- out ---- */ std::vector jobs; @@ -4089,6 +4124,22 @@ static void run_transfer(int world, bool fragment, bool zero_last = false) { usleep(100); CHECK_EQ(st, 1); } + /* Every rank landed: the follower's hash of the replicated group against the leader's window + * (Engine::tier_tick's order). Bytes out: a follower writes only its own window. */ + if (tc.verify && tc.replicated) { + for (int r = 1; r < world; ++r) + for (const TierJob& j : jobs) { + uint64_t sum = 0; + REQUIRE(x[(size_t)r]->take_replicated_sum(j.key, &sum)); + x[0]->verify_replicated(j, r, sum); + CHECK(!x[(size_t)r]->take_replicated_sum(j.key, &sum)); + } + CHECK_EQ(x[0]->stats().rep_checked, 20ll * (world - 1)); + CHECK_EQ(x[0]->stats().rep_mismatch, tc.alike ? 0ll : 20ll * (world - 1)); + } + for (int r = 0; r < world; ++r) + CHECK_EQ(x[(size_t)r]->stats().bytes_out, + 20 * (r == 0 ? L.rep_bytes + L.own_bytes[0] : L.own_bytes[(size_t)r])); x[0]->report_pass(jobs, std::vector(jobs.size(), 1), 0); CHECK_EQ(t.stats().to_host, 20); @@ -4135,19 +4186,67 @@ static void run_transfer(int world, bool fragment, bool zero_last = false) { for (auto& xp : x) xp->close(); for (RadStream s : compute) rad_stream_destroy(s); f.pc.set_tiers(nullptr); + unsetenv("RADIANCE_DEBUG_TIER_VERIFY"); } TEST(a_conversation_restored_from_host_is_byte_identical_in_new_blocks) { - run_transfer(1, /*fragment=*/false); - run_transfer(1, /*fragment=*/true); + run_transfer({ 1, /*fragment=*/false }); + run_transfer({ 1, /*fragment=*/true }); } TEST(each_rank_restores_its_own_window_of_a_shared_slot) { - run_transfer(2, /*fragment=*/false); - run_transfer(2, /*fragment=*/true); + run_transfer({ 2, /*fragment=*/false }); + run_transfer({ 2, /*fragment=*/true }); } TEST(a_rank_with_a_zero_group_moves_only_its_own_groups) { - run_transfer(3, /*fragment=*/false, /*zero_last=*/true); - run_transfer(3, /*fragment=*/true, /*zero_last=*/true); + run_transfer({ 3, /*fragment=*/false, /*zero_last=*/true }); + run_transfer({ 3, /*fragment=*/true, /*zero_last=*/true }); +} +/* The replicated group is in the slot once: the leader writes it, every rank reads it back + * beside its own shard of the other group, and the slot is smaller by (world - 1) copies. At one + * rank nothing changes but the layout's bookkeeping. The ranks' copies differ on purpose, so the + * bytes a follower gets back are provably the leader's. */ +TEST(a_replicated_group_is_held_once_a_slot_and_restored_on_every_rank) { + for (int world : { 1, 2, 8 }) { + run_transfer({ world, /*fragment=*/false, false, /*replicated=*/true }); + run_transfer({ world, /*fragment=*/true, false, /*replicated=*/true }); + } +} +/* A replicated group beside a zero one: the last rank's own window is empty, so it writes nothing + * on a copy out and reads the replicated window alone on a restore. */ +TEST(a_replicated_group_beside_a_zero_rank_keeps_the_windows_apart) { + run_transfer({ 3, /*fragment=*/false, /*zero_last=*/true, /*replicated=*/true }); + run_transfer({ 3, /*fragment=*/true, /*zero_last=*/true, /*replicated=*/true }); +} +/* RADIANCE_DEBUG_TIER_VERIFY: a follower hashes the replicated bytes it would have written and + * the leader compares them with its window. Alike, nothing is reported (seven followers at eight + * ranks); differing, every entry, which the two-rank arm logs twenty times. */ +TEST(tier_verify_catches_a_follower_whose_replicated_group_differs) { + run_transfer({ 2, /*fragment=*/false, false, /*replicated=*/true, /*alike=*/true, /*verify=*/true }); + run_transfer({ 8, /*fragment=*/true, false, /*replicated=*/true, /*alike=*/true, /*verify=*/true }); + run_transfer({ 2, /*fragment=*/true, false, /*replicated=*/true, /*alike=*/false, /*verify=*/true }); +} +/* The flag must agree across the ranks: one rank's replicated group that another rank declared + * zero or did not declare replicated has no one window every rank can read, so bringup stops. */ +TEST(a_group_replicated_on_one_rank_only_is_refused_by_the_slot_layout) { + if (!device_is_host()) { + std::printf(" SKIP the tier layout fixture needs the host backend\n"); + return; + } + for (int bad : { 0, 1 }) { + std::vector> fx; + for (int r = 0; r < 2; ++r) { + fx.push_back(std::make_unique()); + fx.back()->cfg.checkpoint_slots = 0; + std::vector groups = two_paged_groups(); + groups[1].replicated = r == 0 || bad == 1; + if (bad == 1 && r == 1) groups[1].zero = true; + REQUIRE_EQ(fx.back()->build_groups(groups), RAD_OK); + } + std::vector kvs; + for (auto& fp : fx) kvs.push_back(&fp->kv); + TierExec::SlotLayout L; + CHECK_EQ(TierExec::slot_layout(kvs, fx[0]->pc.cached_groups(), &L), RAD_E_STATE); + } } /* With speculation each sequence has two physical state slots while the free list counts logical @@ -6268,7 +6367,7 @@ TEST(a_tier_transfer_gives_back_every_event_and_device_byte) { const int64_t events0 = rad_dev_live_events(); int64_t vram0 = 0, vram1 = 0; CHECK_OK(dev_vram_used(0, &vram0)); - run_transfer(2, /*fragment=*/true); + run_transfer({ 2, /*fragment=*/true }); CHECK_EQ(rad_dev_live_events(), events0); CHECK_OK(dev_vram_used(0, &vram1)); CHECK_EQ(vram1, vram0); From 4f821ce0b9c0f7639e5422b17608ca5f5df1856f Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:16 +0200 Subject: [PATCH 146/152] glm5next: the latent and index caches are declared replicated -- the host tier holds each once a slot Every rank computes the whole normed latent (kv_store over the replicated kv_a) and pools into the whole index cache, in the head form and the row form alike, so both cached groups carry rad_kv_group_replicated. At eight ranks a 4-token block costs 49.59 KiB a slot (kv_latent 48.00 KiB over its 12 layers, kv_dsa_index 1.59 KiB) rather than 396.75 KiB, 12.4 KiB a token rather than 99.2 KiB: --prefix-cache-mib 32768 holds 2.7M tokens rather than 338K. glm5next_test pins the two flags at 1, 2 and 8 ranks; the flag is outside the recording fake's graph hash, so the pinned graphs and steps stand. Co-Authored-By: Claude Fable 5.1 --- arch/glm5next/glm5next.cpp | 4 ++++ docs/ARCHITECTURES.md | 10 +++++++--- tests/glm5next_test.cpp | 29 +++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index 0b535c51..e2cfdc04 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -430,6 +430,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.expand = copy(b, g, m.x, m.h0); m.layers.resize(45); for (int l = 0; l < 45; ++l) RAD_ARCH_TRY(layer(b, m, m.layers[l], nm, l, false)); + // Every rank computes the whole normed latent and pools into the whole index cache + // (rad_block_glm_mla.h, rad_block_glm_indexer.h), so the host tier keeps each once a slot. + RAD_ARCH_TRY(rad_kv_group_replicated(b, m.latent)); + if (m.index) RAD_ARCH_TRY(rad_kv_group_replicated(b, m.index)); m.contract = rw(b, RAD_OP(b, "mhc_contract", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", 4096), diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 8ad2deeb..9cde6552 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -506,9 +506,13 @@ declare. | `kv_kda` | `RAD_KV_LINEAR`, f32, 128 x 128 a head | the recurrent state, 64 / tp heads a rank | 34 KDA | | `kv_kda_conv` | `RAD_KV_CONV`, bf16, width 4 | the convolution history, 3 x 8192 / tp channels a rank | 34 KDA | -The latent and the index are replicated: every rank keeps the whole latent cache. The model is a -hybrid, so a prefix-cache hit is usable only from a state checkpoint at or below it, and -`--checkpoint-interval` decides how much of a shared system prompt is reused. +The latent and the index are replicated: every rank keeps the whole latent cache, and the plugin +declares both so (`rad_kv_group_replicated`), which lets the host tier (`--prefix-cache-mib`) hold +each once a slot: 49.59 KiB a 4-token block at any rank count (`kv_latent` 48.00 KiB over its 12 +layers, `kv_dsa_index` 1.59 KiB), 12.4 KiB a token, where a copy per rank would make a slot +396.75 KiB at eight. The model is a hybrid, so a prefix-cache hit is usable only from a state +checkpoint at or below it, and `--checkpoint-interval` decides how much of a shared system prompt +is reused. **Linears.** Each weight is served as the export stores it: diff --git a/tests/glm5next_test.cpp b/tests/glm5next_test.cpp index c6ce1adf..c646a1c1 100644 --- a/tests/glm5next_test.cpp +++ b/tests/glm5next_test.cpp @@ -1440,6 +1440,35 @@ RadBuildCtx glm53_vl_ctx(int rank, int world, int64_t patches, int max_spec = 3) } /* namespace */ +/* The latent and the index cache are computed whole on every rank (rad_block_glm_mla.h, + * rad_block_glm_indexer.h) and the plugin says so, which lets the host tier keep each once a slot + * under tensor parallelism instead of once a rank. The linear groups travel in the checkpoint + * store and carry no such flag. The flag is outside graph_hash(), so the pinned graphs stand. */ +TEST(glm53_declares_its_latent_and_index_caches_replicated) { + MetaKV mk = glm53_vl_meta(); + auto ends_with = [](const std::string& s, const char* t) { + const size_t n = std::strlen(t); + return s.size() >= n && s.compare(s.size() - n, n, t) == 0; + }; + for (int world : { 1, 2, 8 }) { + for (int rank : { 0, world - 1 }) { + RadBuilder b; + glm53_encs(b); + RadBuildCtx ctx = glm53_vl_ctx(rank, world, 0); + REQUIRE_EQ(glm5next::declare(&b, mk.meta(), &ctx), RAD_OK); + REQUIRE_EQ(b.kv_groups.size(), 5u); + int replicated = 0; + for (const RecKV& g : b.kv_groups) { + const bool want = ends_with(g.name, "kv_latent") || ends_with(g.name, "kv_dsa_index"); + CHECK(g.replicated == want); + CHECK(!g.zero); + replicated += g.replicated; + } + CHECK_EQ(replicated, 2); + } + } +} + /* The tower is declared only with an encoder budget, last, its weights replicated in their own * groups past the 45 layers and the MTP layer's, its 2-D rotary the axial one at sixteen * frequencies an axis, gate and up joined gate first; one scatter over the trunk's embedding and From b34af6c509769bd46df33fe4bfeb9f9fddc90ea7 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:13 +0200 Subject: [PATCH 147/152] libr4d: eight ranks on one card for r4d_selftest -- the eight-rank protocol testable on a box with fewer cards The eight-rank collectives could only run on eight cards, so a change to their protocol, shard table or arithmetic went untested until a TP8 window. Their bits do not need eight cards: a peer on the same card is just another region of its VRAM. build() now skips hipDeviceEnablePeerAccess for a peer on the rank's own card (the runtime refuses it, and nothing needs it). On distinct cards nothing changes. R4D_SELFTEST_ONE_CARD=1 lets --perfar8 run its eight ranks on the first card: each rank takes a non-blocking stream of its own (one stream would serialise ranks that spin on each other), main() raises GPU_MAX_HW_QUEUES to 16 before the runtime starts so the streams get queues of their own, the block counts stay at 4 and 8 so all eight ranks' blocks are resident at once, and the workers meet at a barrier before fini and the frees, which synchronise the card. With a card a rank the worker keeps the legacy stream, so the timed launches are as before. On one card the results are checked against the fold exactly as on eight; the times are not a board's, since the card runs the eight queues in time slices of several milliseconds, and the run says so. Co-Authored-By: Claude Fable 5.1 --- libr4d/r4d_ar_entry.hip | 7 +++-- libr4d/r4d_selftest.cpp | 60 ++++++++++++++++++++++++++++++++--------- 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 0f06e23b..bb3a3e98 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -440,7 +440,9 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, /* Peer access is per context, so each rank enables its own, after the publish barrier where * peer device ordinals are known. A host can expose more HIP devices than ranks (e.g. an - * integrated GPU), so the ordinal comes from the peer rather than the rank. */ + * integrated GPU), so the ordinal comes from the peer rather than the rank. A peer on this + * rank's own card needs none (the runtime refuses to enable it): r4d_selftest runs eight ranks + * on one card that way, each on its own stream. */ int j = 0; for (int r = 0; r < world; ++r) { if (r == rank) continue; @@ -448,7 +450,8 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, in->peer_scratch[j] = g_rv.scratch[r]; in->peer_flags[j] = g_rv.flags[r]; ++j; - if (!host) R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r])); + if (!host && g_rv.dev[r] != dev) + R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r])); } /* Second barrier: no rank may launch until every rank has enabled peer access, or the first diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 4cd9b8a3..a1bed290 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -404,6 +404,17 @@ static void cross_check(const Plugin& pl) { /* --cold MIB: bytes read through the caches before every timed launch; see st_time_us. */ static int64_t g_cold = 0; +/* R4D_SELFTEST_ONE_CARD=1 runs the eight-rank collectives as eight ranks on the first card, each + * on its own non-blocking stream: the protocol, the shard table and the arithmetic, with VRAM in + * place of the links, on a box with fewer cards. The streams need hardware queues of their own, + * so main() raises GPU_MAX_HW_QUEUES before the runtime starts. For bits only: the card runs the + * eight queues in time slices of several milliseconds, so a launch's time is mostly waiting for + * the other ranks' turn. */ +static bool st_one_card() { + const char* e = std::getenv("R4D_SELFTEST_ONE_CARD"); + return e && *e && std::strcmp(e, "0") != 0; +} + #ifdef RAD_HAVE_HIP /* Every hipError_t in this file is checked. A kernel fault leaves a sticky error, so the @@ -22337,6 +22348,9 @@ private: struct Ar8Perf { int rank = 0, dev = 0, world = 8, iters = 0; + /* The legacy stream with a card a rank; a non-blocking stream of its own when the ranks share + * a card (st_one_card), where one stream would serialise ranks that wait for each other. */ + hipStream_t st = nullptr; const char* dtype = "bf16"; std::vector sizes; std::vector rows; @@ -22357,6 +22371,9 @@ static void ar8_perf_worker(Ar8Perf* t) { t->rc.assign(ncfg, RAD_E_STATE); t->bad.assign(ncfg, 0); t->period.assign(ncfg, 0.0f); t->cold.assign(ncfg, {}); if (st_set_device(t->dev) != hipSuccess) t->rc_init = RAD_E_DEVICE; + if (t->rc_init == RAD_OK && st_one_card() && + hipStreamCreateWithFlags(&t->st, hipStreamNonBlocking) != hipSuccess) + t->rc_init = RAD_E_DEVICE; const bool bf = !std::strcmp(t->dtype, "bf16"); const int esz = bf ? 2 : 4; int64_t most = 0; @@ -22414,9 +22431,10 @@ static void ar8_perf_worker(Ar8Perf* t) { t->bar->wait(); int rc = t->rc_init; if (rc == RAD_OK) { - st_memset(out, 0, (size_t)n * esz); - rc = t->rows[j]->launch(&a, nullptr); - if (st_stream_sync(nullptr) != hipSuccess && rc == RAD_OK) rc = RAD_E_DEVICE; + hip_ck(hipMemsetAsync(out, 0, (size_t)n * esz, t->st), "hipMemsetAsync", + __LINE__); + rc = t->rows[j]->launch(&a, t->st); + if (st_stream_sync(t->st) != hipSuccess && rc == RAD_OK) rc = RAD_E_DEVICE; } t->rc[cfg] = rc; t->bar->wait(); @@ -22434,15 +22452,15 @@ static void ar8_perf_worker(Ar8Perf* t) { * clock (the block rule read slower than the same count pinned). */ if (timed) { for (int i = 0; i < std::max(t->iters, 50); ++i) - t->rows[j]->launch(&a, nullptr); - st_stream_sync(nullptr); + t->rows[j]->launch(&a, t->st); + st_stream_sync(t->st); } t->bar->wait(); if (timed) { if (g_cold <= 0) { - st_ev_record(ev[0], nullptr); - for (int i = 0; i < t->iters; ++i) t->rows[j]->launch(&a, nullptr); - st_ev_record(ev[1], nullptr); + st_ev_record(ev[0], t->st); + for (int i = 0; i < t->iters; ++i) t->rows[j]->launch(&a, t->st); + st_ev_record(ev[1], t->st); st_ev_sync(ev[1]); float ms = 0.0f; st_ev_elapsed(&ms, ev[0], ev[1]); @@ -22452,11 +22470,11 @@ static void ar8_perf_worker(Ar8Perf* t) { for (int64_t off = 0; off < g_cold; off += kColdChunk) hip_ck(hipMemcpyAsync(cdst, (const char*)csrc + off, (size_t)std::min(kColdChunk, g_cold - off), - hipMemcpyDeviceToDevice, nullptr), + hipMemcpyDeviceToDevice, t->st), "hipMemcpyAsync", __LINE__); - st_ev_record(ev[2 * (size_t)i], nullptr); - t->rows[j]->launch(&a, nullptr); - st_ev_record(ev[2 * (size_t)i + 1], nullptr); + st_ev_record(ev[2 * (size_t)i], t->st); + t->rows[j]->launch(&a, t->st); + st_ev_record(ev[2 * (size_t)i + 1], t->st); } st_ev_sync(ev[2 * (size_t)t->iters - 1]); t->cold[cfg].resize((size_t)t->iters); @@ -22471,9 +22489,12 @@ static void ar8_perf_worker(Ar8Perf* t) { } } for (hipEvent_t e : ev) st_ev_destroy(e); + /* Frees and fini synchronise the card, which ranks sharing it must reach together. */ + t->bar->wait(); for (size_t j = 0; j < t->rows.size(); ++j) if (inst[j] && t->rows[j]->fini) t->rows[j]->fini(inst[j]); for (void* p : { in, out, csrc, cdst }) if (p) st_free(p); + if (t->st) hip_ck(hipStreamDestroy(t->st), "hipStreamDestroy", __LINE__); } /* The eight-rank two-shot's weights as the plugin derives them at init (r4d_ar_entry.hip, @@ -22535,6 +22556,12 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty !std::strncmp(p.gcnArchName, "gfx1201", 7)) devs.push_back(d); } + if ((int)devs.size() < W && st_one_card() && !devs.empty()) { + std::printf("eight ranks on device %d (R4D_SELFTEST_ONE_CARD): the bits are checked as on " + "eight cards; the times are not a board's, the card time-slices the ranks' " + "queues\n", devs[0]); + devs.assign((size_t)W, devs[0]); + } if ((int)devs.size() < W) { std::printf("--perfar8: needs 8 gfx1201 cards, found %zu\n", devs.size()); return; } std::vector rows; @@ -22549,7 +22576,11 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty ks.push_back(k); } } - const std::vector nbs = { 0, 4, 8, 16, 32, 64 }; + /* Ranks sharing a card must have every block resident at once, since a block spins until its + * twins on the other ranks arrive: eight ranks of at most 8 blocks of 1024 threads fit an R9700, + * and the block rule can ask for 16. */ + const std::vector nbs = devs[0] == devs[W - 1] ? std::vector{ 4, 8 } + : std::vector{ 0, 4, 8, 16, 32, 64 }; std::printf("eight-rank exact all-reduce, %s, %d launches a point, %s\n", dtype, iters, g_cold > 0 ? fmt("cold (%lld MiB read before each; last arriver / with skew, " "medians)", (long long)(g_cold >> 20)).c_str() @@ -27068,6 +27099,7 @@ static void usage(void) { " a card: one-shot and two-shot at the block rule and at 4..64 blocks,\n" " each checked against the rank-order fold; numel 0 runs the decode\n" " and prefill messages at 4096 wide. dtype bf16 (default) or fp32.\n" + " R4D_SELFTEST_ONE_CARD=1 runs the eight ranks on one card.\n" " --perfmxf8 M [iters] [experts] [top_k] [skew]: the same at the FP8 experts with f32\n" " block scales (moe_gemm_fp8a8_f32scale, GLM's MTP layer).\n" " --perfmhcpre M [iters]: mhc_pre (whole, partials alone, finish alone) and\n" @@ -27112,6 +27144,8 @@ static void usage(void) { } int main(int argc, char** argv) { + /* Before the runtime starts: eight ranks on one card need a hardware queue each. */ + if (st_one_card() && !std::getenv("GPU_MAX_HW_QUEUES")) setenv("GPU_MAX_HW_QUEUES", "16", 0); const char* path = nullptr; const char* real_file = nullptr; long long real_woff = 0, real_soff = 0, real_n = 0, real_k = 0; From 91200c900b059ddc4d58e54b339347c9921b1b68 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:13 +0200 Subject: [PATCH 148/152] libr4d: the eight-rank two-shot's timeline -- where a 16 MiB all-reduce spends 1.36 ms against 0.76 ms of link time At 4 x Gen5 x16 + 4 x Gen5 x8 the weighted two-shot moves a 16 MiB message in 1316 to 1340 us (K4 to K8, --perfar8), against 763 us that the x8 cards' links need for its bytes, and measured(K) = f x link time(K) + h x (K + 1) fits f of about 1.45 and h of about 20 us a handshake. Whether that is link efficiency, waiting for the slowest rank, the local reduce or the step boundaries cannot be told from the period alone. A launch now takes an optional `timeline` parameter, a device buffer of nblocks x R4D_AR_TL_WORDS int64 (r4d_ar_shards.h). Every block of the eight-rank two-shot stamps the device wall clock after its sequence step, at each handshake when all its stores have drained (arrive) and when every peer's flag has been seen (release), and after its last local work. The stamps sit in r4d_ar_handshake behind a null check, so a launch without the parameter pays a branch per handshake; no value changes either way. r4d_selftest --perfar8 --timeline launches each two-shot point once more with the stamps on and prints, per rank, the first push, every step's work and wait, and the final assemble. In one piece that is the reduce-scatter's send, its receipt, the reduce with the all-gather's send, its receipt and the local assemble, so the two hops are measured apart; in K pieces it shows which rank works while the others wait. Co-Authored-By: Claude Fable 5.1 --- libr4d/r4d.h | 5 +- libr4d/r4d_ar_entry.hip | 4 +- libr4d/r4d_ar_shards.h | 6 ++ libr4d/r4d_ar_twoshot_Nrank_exact.hip | 32 +++++---- libr4d/r4d_ar_wide.h | 15 ++++- libr4d/r4d_selftest.cpp | 93 ++++++++++++++++++++++++++- 6 files changed, 138 insertions(+), 17 deletions(-) diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 08552a34..5cfb2b09 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -451,7 +451,10 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - const int* shard_weights, long pieces); + const int* shard_weights, long pieces, long timeline); +// `timeline`, a diagnostic, is 0 or a device buffer of nblocks * R4D_AR_TL_WORDS int64 that every +// block of the eight-rank two-shot fills with wall-clock stamps (r4d_ar_wide.h): its start, each +// handshake's arrival and release, its end. r4d_selftest --perfar8 with --timeline reads it. // The tiered int8 wire on both two-shot hops (r4d_ar_twoshot_Nrank_ti8.hip; codec in // r4d_ar_ti8.h), 3 or 4 ranks. Int8 groups of 32 with an fp16 scale and a per-group record // (T1 plain, T2 top-1-exact, T3 wht32), 38 bytes/group; tiering is deterministic and diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index bb3a3e98..3504edaa 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -1174,6 +1174,8 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { const long long asked = r4d_pgeti_or(a->p, a->n_p, "pieces", in->pieces); if (asked < 0 || asked > R4D_AR_TS_MAX_PIECES) return RAD_E_INVAL; const long long pieces = ar8_pieces_for(in, c.numel, asked); + /* A diagnostic: a device buffer of nblocks * R4D_AR_TL_WORDS int64 stamps (r4d.h). */ + const long long timeline = r4d_pgeti_or(a->p, a->n_p, "timeline", 0); R4D_TRY("ar_twoshot_8rank_exact", r4d_ar_twoshot_8rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_scratch[3], in->peer_scratch[4], in->peer_scratch[5], @@ -1184,7 +1186,7 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub, weights, (long)pieces)); + c.pub, weights, (long)pieces, (long)timeline)); return RAD_OK; } diff --git a/libr4d/r4d_ar_shards.h b/libr4d/r4d_ar_shards.h index 6d3de9ab..b7a825e5 100644 --- a/libr4d/r4d_ar_shards.h +++ b/libr4d/r4d_ar_shards.h @@ -109,3 +109,9 @@ inline long r4d_ar_shard_max_bound(long n16, int ws, const int* w) { const long b = n16 * wmax / sum + 1; return b < n16 ? b : n16; } + +// The two-shot timeline, a diagnostic (r4d.h, `timeline`): per block R4D_AR_TL_WORDS stamps of the +// device wall clock (hipDeviceAttributeWallClockRate), [0] after the sequence step, an (arrive, +// release) pair per handshake, then the end of the block's last local work, so a launch in K +// pieces fills 2 + 2 * (K + 1). R4D_AR_TL_BLOCKS is the wide family's block ceiling. +enum { R4D_AR_TL_WORDS = 2 + 2 * (16 + 1), R4D_AR_TL_BLOCKS = 64 }; diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index 2b79e64b..352887fc 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -34,6 +34,9 @@ #include #include +static_assert(R4D_AR_TL_WORDS >= 4 + 2 * R4D_AR_TS_MAX_PIECES, + "a timeline holds the start, a stamp pair a handshake and the end"); + template struct R4DArShardOff { int off[WS + 1]; @@ -49,7 +52,7 @@ __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff sh, int slot_stride16, int rank, int drain, int acq, int pub, - long long* gate, unsigned int* gate_ctr, int pieces_arg) { + long long* gate, unsigned int* gate_ctr, int pieces_arg, long long* tl_all) { if (CHAIN) r4d_chain_wait(); constexpr int NPEERS = WS - 1; const int pieces = PIECED ? pieces_arg : 1; @@ -60,6 +63,8 @@ __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot, (unsigned int)pieces); const unsigned int v0 = 2u * s_seq - 1u; const int parity = (int)s_slot; + long long* const tl = tl_all ? tl_all + (size_t)b * R4D_AR_TL_WORDS : nullptr; + r4d_ar_tl_stamp(tl, 0); const int sh_max = sh.sh_max; #define R4D_TS_OFF(s) (sh.off[s]) @@ -139,12 +144,13 @@ __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( * reduce, flag 2s, assemble. A word is touched by the same thread in all three steps, which keeps * the in-place form safe. */ push1(0); - r4d_ar_handshake(peers, my_flags, b, rank, v0, drain, acq, pub); + r4d_ar_handshake(peers, my_flags, b, rank, v0, drain, acq, pub, tl ? tl + 1 : nullptr); for (int j = 0; j < pieces; ++j) { if (j + 1 < pieces) push1(j + 1); reduce2(j); if (j > 0) assemble(j - 1); - r4d_ar_handshake(peers, my_flags, b, rank, v0 + 1u + (unsigned int)j, drain, acq, pub); + r4d_ar_handshake(peers, my_flags, b, rank, v0 + 1u + (unsigned int)j, drain, acq, pub, + tl ? tl + 3 + 2 * j : nullptr); } /* The hold ends after the last handshake, not the first: the reduce is fused with the phase-2 * push (every reduced word goes to each peer's region B), so until then the link still carries @@ -153,6 +159,10 @@ __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( * assemble of the last piece is left (r4d_ar_seq.h). */ r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); assemble(pieces - 1); + if (tl) { + __syncthreads(); + r4d_ar_tl_stamp(tl, 3 + 2 * pieces); + } #undef R4D_TS_OFF #undef R4D_TS_LEN if (CHAIN) r4d_chain_done(); @@ -378,9 +388,9 @@ __device__ __forceinline__ void r4d_ar_twoshot_coded_body( const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, \ int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff sh, \ int slot_stride16, int rank, int drain, int acq, int pub, long long* gate, \ - unsigned int* gate_ctr, int pieces_arg + unsigned int* gate_ctr, int pieces_arg, long long* tl_all #define R4D_ARTS_ARGS in4, peers, my_base, my_flags, out4, seq_ctrs, sh, slot_stride16, rank, \ - drain, acq, pub, gate, gate_ctr, pieces_arg + drain, acq, pub, gate, gate_ctr, pieces_arg, tl_all template __global__ void r4d_ar_twoshot_wide_exact_kernel(R4D_ARTS_PARAMS) { r4d_ar_twoshot_wide_exact_body(R4D_ARTS_ARGS); @@ -417,7 +427,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long out, long n_elem, long dtype, long rank, long stream_i, long nblocks, long nthreads, long drain, long acq, long pub, long gate, long gate_ctr, const int* shard_weights, - long pieces, bool chain = false) { + long pieces, long timeline, bool chain = false) { constexpr int NPEERS = WS - 1; if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce: rank " + std::to_string(rank) + @@ -500,7 +510,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ (int4*)out, (unsigned int*)seq_ctrs, sh, (int)slot_stride16, \ (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \ - (unsigned int*)gate_ctr, np) + (unsigned int*)gate_ctr, np, (long long*)timeline) #define R4D_AR_TS_LAUNCH(T, LN) \ do { \ if (np > 1) R4D_AR_TS_LAUNCH_P(T, LN, true); \ @@ -524,7 +534,7 @@ void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pee /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, nullptr, - 1L); + 1L, 0L); } void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -537,7 +547,7 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr, - nullptr, 1L, chain != 0); + nullptr, 1L, 0L, chain != 0); } /* The coded form's conditions: bf16, a message that shards evenly into whole waves' 32 chunks @@ -592,7 +602,7 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - const int* shard_weights, long pieces) { + const int* shard_weights, long pieces, long timeline) { const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3, peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, @@ -600,5 +610,5 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, - shard_weights, pieces); + shard_weights, pieces, timeline); } diff --git a/libr4d/r4d_ar_wide.h b/libr4d/r4d_ar_wide.h index 97089d3c..ce313f7f 100644 --- a/libr4d/r4d_ar_wide.h +++ b/libr4d/r4d_ar_wide.h @@ -16,6 +16,7 @@ #include #include #include "r4d_ar_seq.h" +#include "r4d_ar_shards.h" #define R4D_AR_SPIN_MAX 4000000000ULL #define R4D_AR_WIDE_MAX_BLOCKS 64 @@ -66,14 +67,19 @@ __device__ __forceinline__ void r4d_ar_acquire(int acq) { // words has reached or passed it (peers may be a step ahead; counters only grow). One spin lane // per source, wrap-safe monotonic compare, never equality. Every rank publishes before it waits, // so there is no cycle; a handshake that cannot complete traps. +// +// `tl`, when not null, takes two wall-clock stamps: when the whole block has issued and drained +// its stores, and when every peer's flag has been seen. A diagnostic: the eight-rank two-shot +// passes it only for a launch asking for its timeline (r4d_ar_tl_stamp). template __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers& peers, unsigned int* __restrict__ my_flags, int b, int rank, unsigned int val, int drain, int acq, - int pub) { + int pub, long long* tl = nullptr) { r4d_ar_drain(drain); __syncthreads(); const int tid = threadIdx.x; + if (tl && tid == 0) tl[0] = (long long)wall_clock64(); if (tid == 0) { if (drain == 2) __threadfence_system(); if (pub == 2) { @@ -107,9 +113,16 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers } } __syncthreads(); + if (tl && tid == 0) tl[1] = (long long)wall_clock64(); r4d_ar_acquire(acq); } +// The two-shot timeline (layout in r4d_ar_shards.h), one stamp of the device wall clock. +static_assert(R4D_AR_TL_BLOCKS == R4D_AR_WIDE_MAX_BLOCKS, "r4d_ar_shards.h restates the ceiling"); +__device__ __forceinline__ void r4d_ar_tl_stamp(long long* tl, int i) { + if (tl && threadIdx.x == 0) tl[i] = (long long)wall_clock64(); +} + // Host side: checks stride and grid against the real allocations. Every scratch, flag and seq // pointer comes from hipMalloc / hipIpcOpenMemHandle, so the runtime can report its extent; a // pointer it cannot size is refused. diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index a1bed290..fe4faabe 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -403,6 +403,9 @@ static void cross_check(const Plugin& pl) { /* ================================================================== the device phase */ /* --cold MIB: bytes read through the caches before every timed launch; see st_time_us. */ static int64_t g_cold = 0; +/* --timeline: --perfar8 also records the two-shot's per-block stamps (r4d.h) and prints where each + * rank's time goes. */ +static bool g_timeline = false; /* R4D_SELFTEST_ONE_CARD=1 runs the eight-rank collectives as eight ranks on the first card, each * on its own non-blocking stream: the protocol, the shard table and the arithmetic, with VRAM in @@ -22364,12 +22367,15 @@ struct Ar8Perf { std::vector bad; std::vector period; std::vector> cold; + /* --timeline: per config, the two-shot's stamps (nblocks x R4D_AR_TL_WORDS, -1 unset). */ + std::vector> tl; }; static void ar8_perf_worker(Ar8Perf* t) { const size_t ncfg = t->sizes.size() * t->rows.size() * t->nbs.size(); t->rc.assign(ncfg, RAD_E_STATE); t->bad.assign(ncfg, 0); t->period.assign(ncfg, 0.0f); t->cold.assign(ncfg, {}); + t->tl.assign(ncfg, {}); if (st_set_device(t->dev) != hipSuccess) t->rc_init = RAD_E_DEVICE; if (t->rc_init == RAD_OK && st_one_card() && hipStreamCreateWithFlags(&t->st, hipStreamNonBlocking) != hipSuccess) @@ -22384,10 +22390,12 @@ static void ar8_perf_worker(Ar8Perf* t) { }; for (size_t j = 0; j < t->rows.size() && t->rc_init == RAD_OK; ++j) t->rc_init = t->rows[j]->init(ip.data(), (int)ip.size(), t->rank, t->world, &inst[j]); - void *in = nullptr, *out = nullptr, *csrc = nullptr, *cdst = nullptr; + void *in = nullptr, *out = nullptr, *csrc = nullptr, *cdst = nullptr, *tlbuf = nullptr; + const size_t tl_words = (size_t)R4D_AR_TL_BLOCKS * R4D_AR_TL_WORDS; if (t->rc_init == RAD_OK && (hipMalloc(&in, (size_t)most * esz) != hipSuccess || hipMalloc(&out, (size_t)most * esz) != hipSuccess || + (g_timeline && hipMalloc(&tlbuf, tl_words * sizeof(long long)) != hipSuccess) || (g_cold > 0 && (hipMalloc(&csrc, (size_t)g_cold) != hipSuccess || hipMalloc(&cdst, (size_t)std::min(g_cold, kColdChunk)) != hipSuccess)))) t->rc_init = RAD_E_NOMEM; @@ -22484,6 +22492,23 @@ static void ar8_perf_worker(Ar8Perf* t) { } } t->bar->wait(); + /* One more launch, warm, with the stamps on: a two-shot row reads `timeline`, the + * one-shot ignores it and leaves the buffer unset. */ + if (timed && g_timeline && tlbuf) { + std::vector pt = ps; + pt.push_back(PI("timeline", (int64_t)(uintptr_t)tlbuf)); + a.p = pt.data(); a.n_p = (int)pt.size(); + hip_ck(hipMemsetAsync(tlbuf, 0xff, tl_words * sizeof(long long), t->st), + "hipMemsetAsync", __LINE__); + t->bar->wait(); + t->rows[j]->launch(&a, t->st); + st_stream_sync(t->st); + t->tl[cfg].resize(tl_words); + st_memcpy(t->tl[cfg].data(), tlbuf, tl_words * sizeof(long long), + hipMemcpyDeviceToHost); + a.p = ps.data(); a.n_p = (int)ps.size(); + } + t->bar->wait(); ++cfg; } } @@ -22493,10 +22518,63 @@ static void ar8_perf_worker(Ar8Perf* t) { t->bar->wait(); for (size_t j = 0; j < t->rows.size(); ++j) if (inst[j] && t->rows[j]->fini) t->rows[j]->fini(inst[j]); - for (void* p : { in, out, csrc, cdst }) if (p) st_free(p); + for (void* p : { in, out, csrc, cdst, tlbuf }) if (p) st_free(p); if (t->st) hip_ck(hipStreamDestroy(t->st), "hipStreamDestroy", __LINE__); } +/* The two-shot's stamps for one config as each rank's phases, in microseconds. A rank's event is + * its last block's (the rank has issued everything only when every block has); the start is its + * first block's. Steps follow the kernel: push the first piece, wait for every peer's flag, then a + * step a piece (push the next piece's first hop, reduce and send this piece's second, assemble the + * previous one) and its wait, then the last assemble. With one piece the first push is the + * reduce-scatter's send, the first wait its receipt, the step the reduce and the all-gather's + * send, the second wait its receipt and the tail the local assemble. */ +static void ar8_print_timeline(const std::vector& t, size_t cfg, double khz) { + if (khz <= 0) return; + const int W = (int)t.size(); + for (int r = 0; r < W; ++r) { + const std::vector& v = t[(size_t)r].tl[cfg]; + if (v.empty()) return; + int nb = 0, nst = 0; + for (int b = 0; b < R4D_AR_TL_BLOCKS; ++b) { + int k = 0; + while (k < R4D_AR_TL_WORDS && v[(size_t)b * R4D_AR_TL_WORDS + k] >= 0) ++k; + if (k == 0) break; + nb = b + 1; + nst = nst ? std::min(nst, k) : k; + } + if (nb == 0 || nst < 4) { std::printf(" timeline r%d: no stamps\n", r); continue; } + const int pieces = (nst - 4) / 2; /* start, K + 1 pairs, end */ + auto ev = [&](int k, bool first) { + long long m = v[(size_t)k]; + for (int b = 1; b < nb; ++b) { + const long long x = v[(size_t)b * R4D_AR_TL_WORDS + k]; + m = first ? std::min(m, x) : std::max(m, x); + } + return m; + }; + const double us = 1000.0 / khz; + const long long t0 = ev(0, true); + std::string line; + double work = 0, wait = 0; + long long prev = t0; + for (int h = 0; h <= pieces; ++h) { + const long long arr = ev(1 + 2 * h, false), rel = ev(2 + 2 * h, false); + const double w1 = (double)(arr - prev) * us, w2 = (double)(rel - arr) * us; + work += w1; wait += w2; + line += fmt("%s%s %.1f wait %.1f", h ? " | " : "", h ? fmt("s%d", h).c_str() : "push", + w1, w2); + prev = rel; + } + const long long end = ev(3 + 2 * pieces, false); + const double tail = (double)(end - prev) * us; + work += tail; + std::printf(" timeline r%d (%d blocks, K%d): %s | tail %.1f = %.1f us " + "(work %.1f, wait %.1f)\n", r, nb, pieces, line.c_str(), tail, + (double)(end - t0) * us, work, wait); + } +} + /* The eight-rank two-shot's weights as the plugin derives them at init (r4d_ar_entry.hip, * ar8_settle): RADIANCE_AR8_SHARD_WEIGHTS unset or "auto" from each rank's slowest PCIe hop, "off" * or anything invalid even, eight integers as given; equal derived weights are the even split. @@ -22564,6 +22642,10 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty } if ((int)devs.size() < W) { std::printf("--perfar8: needs 8 gfx1201 cards, found %zu\n", devs.size()); return; } + int wall_khz_i = 0; + if (hipDeviceGetAttribute(&wall_khz_i, hipDeviceAttributeWallClockRate, devs[0]) != hipSuccess) + wall_khz_i = 0; + const double wall_khz = (double)wall_khz_i; std::vector rows; std::vector ks; /* The two-shot once a piece count; its instances share one key, so they are one buffer set. */ @@ -22698,6 +22780,7 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty bad ? fmt("%lld elements differ from the fold", (long long)bad).c_str() : "= fold on every rank"); std::printf(" us by rank:%s\n", per_rank.c_str()); + if (g_timeline && two) ar8_print_timeline(t, cfg, wall_khz); ++cfg; } } @@ -27099,7 +27182,9 @@ static void usage(void) { " a card: one-shot and two-shot at the block rule and at 4..64 blocks,\n" " each checked against the rank-order fold; numel 0 runs the decode\n" " and prefill messages at 4096 wide. dtype bf16 (default) or fp32.\n" - " R4D_SELFTEST_ONE_CARD=1 runs the eight ranks on one card.\n" + " With --timeline each two-shot point is launched once more with its\n" + " per-block stamps on, and every rank's push, waits, steps and tail\n" + " are printed. R4D_SELFTEST_ONE_CARD=1 runs the eight ranks on one card.\n" " --perfmxf8 M [iters] [experts] [top_k] [skew]: the same at the FP8 experts with f32\n" " block scales (moe_gemm_fp8a8_f32scale, GLM's MTP layer).\n" " --perfmhcpre M [iters]: mhc_pre (whole, partials alone, finish alone) and\n" @@ -27272,6 +27357,8 @@ int main(int argc, char** argv) { } else if (!std::strcmp(argv[i], "--cold")) { if (i + 1 >= argc) { usage(); return 2; } g_cold = std::strtoll(argv[++i], nullptr, 0) << 20; + } else if (!std::strcmp(argv[i], "--timeline")) { + g_timeline = true; } else if (!std::strcmp(argv[i], "--perfmoe")) { /* The routed-expert GEMM at a prefill chunk of M tokens, every prefill form. */ if (i + 1 >= argc) { usage(); return 2; } From 5b9bc13e5f4c6d3b14a2e0065363dd6ec90c03ba Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:13 +0200 Subject: [PATCH 149/152] libr4d: RADIANCE_AR8_SHARD_WEIGHTS=duplex -- shard weights from the both-directions link model, 8 to 1 instead of 4 to 1 The eight-rank two-shot in pieces runs both hops on a link at once, so each direction of rank r's link carries (1 + 6 x_r) N for a shard fraction x_r: N - x_r N out in the reduce-scatter and 7 x_r N out in the all-gather, the same in. The slowest rank sets the time. The quadratic rule (round(4 (rate / max)^2)) gives four Gen5 x16 and four Gen5 x8 cards 4 and 1: x8 carries 1.3 N at 28.6 GB/s (763 us for 16 MiB) while x16 carries 2.2 N at 57.1 (647 us), so the x16 links idle 15% of the time. r4d_ar_weights_duplex equalises the ranks instead: x_r = (T B_r - 1) / 6 where positive, the x summing to 1, filled from the fastest rank down. On that board it gives x16 2/9 and x8 1/36, weights 64 and 8, and both kinds of card carry the same time's bytes: 7/6 N / 28.6 GB/s, 685 us for 16 MiB, 10% under the quadratic rule's 763. On the earlier board with two Gen4 x8 links it gives 64,9,0,64,0,9,64,64: the Gen4 cards nothing, as the measured best 4,1,0,4,0,1,4,4 did, the Gen5 x8 ones half of what it gave them. It is a new value of the variable, not a new default: unset and "auto" keep the quadratic rule, so nothing runs differently until a measurement on the board says so. Which rank owns a word changes only the link it crosses, not its fold, so the bits are those of every other table. --perfar8 reads the variable the same way. r4d_ar_links_test checks both boards, equal links and that every rank with a shard finishes together. Co-Authored-By: Claude Fable 5.1 --- docs/GUIDE.md | 3 +++ libr4d/r4d_ar_entry.hip | 25 ++++++++++++++-------- libr4d/r4d_ar_links.h | 41 +++++++++++++++++++++++++++++++++++++ libr4d/r4d_selftest.cpp | 9 ++++---- tests/r4d_ar_links_test.cpp | 33 ++++++++++++++++++++++++++--- 5 files changed, 95 insertions(+), 16 deletions(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 99fc0402..a658d6a7 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1169,6 +1169,9 @@ message takes 1360 µs. The links are read once, at startup: a link that drops to a lower speed while the server runs keeps its weight until the next start. `RADIANCE_AR8_SHARD_WEIGHTS` overrides them: `off` keeps the shards even, eight comma-separated integers set them, unset or `auto` reads the links. +`duplex` reads the same links and weights them so that every link's busier direction carries the +same time's bytes when both directions run at once (`r4d_ar_weights_duplex`): x16 64 and x8 8 on +the repaired board, whose link time it puts 10% under the `auto` weights', a Gen4 x8 card nothing. `RADIANCE_AR8_PIECES` (1 to 16) fixes the piece count, and `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` and `RADIANCE_AR8_PIECES_MIN_ELEMS` move the two sizes they start at. Every rank must read the same values; where they differ, every rank stops at startup. diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 3504edaa..400f9147 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -151,18 +151,21 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) { long align16(long v) { return (v + 15) & ~15L; } /* RADIANCE_AR8_SHARD_WEIGHTS, read at every eight-rank build so a process can change it between - * instances: unset or "auto" derives the weights from the links, "off" keeps the shards even, - * eight integers set them. Anything else is "off", with one warning. */ -enum { AR8_EVEN = 0, AR8_SET = 1, AR8_AUTO = 2 }; + * instances: unset or "auto" derives the weights from the links by r4d_ar_weights_from_rates, + * "duplex" from the same links by r4d_ar_weights_duplex, "off" keeps the shards even, eight + * integers set them. Anything else is "off", with one warning. */ +enum { AR8_EVEN = 0, AR8_SET = 1, AR8_AUTO = 2, AR8_DUPLEX = 3 }; int ar8_weights_mode(int* w) { const char* e = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); if (!e || !*e || !std::strcmp(e, "auto")) return AR8_AUTO; + if (!std::strcmp(e, "duplex")) return AR8_DUPLEX; if (!std::strcmp(e, "off")) return AR8_EVEN; if (r4d_ar_shard_weights_parse(e, 8, w)) return AR8_SET; static std::once_flag said; std::call_once(said, [e] { std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs auto, off or eight non-negative " - "integers, comma-separated, sum > 0); eight-rank two-shot shards stay even\n", + "integers, comma-separated, sum > 0, or duplex); eight-rank two-shot shards " + "stay even\n", R4D_AR8_SHARD_WEIGHTS_ENV, e); }); return AR8_EVEN; @@ -237,7 +240,8 @@ int ar8_settle(ArInst* in, int rank, int world) { me.pieces = ar8_pieces(); me.weights_min = ar8_min_elems(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, &said_w); me.pieces_min = ar8_min_elems(R4D_AR8_PIECES_MIN_ENV, &said_p); - if (me.mode == AR8_AUTO && !ar8_own_link(&me.link)) me.link = R4DArLink(); + if ((me.mode == AR8_AUTO || me.mode == AR8_DUPLEX) && !ar8_own_link(&me.link)) + me.link = R4DArLink(); { std::lock_guard lk(g_rv.m); g_rv.ar8[rank] = me; @@ -267,10 +271,12 @@ int ar8_settle(ArInst* in, int rank, int world) { "%d,%d,%d,%d,%d,%d,%d,%d (%s)\n", w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7], R4D_AR8_SHARD_WEIGHTS_ENV); }); - } else if (me.mode == AR8_AUTO) { + } else if (me.mode == AR8_AUTO || me.mode == AR8_DUPLEX) { double gbs[R4D_MAX_RANKS] = { 0 }; for (int r = 0; r < world; ++r) gbs[r] = r4d_ar_link_gbs(all[r].link); - if (!r4d_ar_weights_from_rates(gbs, world, w)) { + const bool known = me.mode == AR8_DUPLEX ? r4d_ar_weights_duplex(gbs, world, w) + : r4d_ar_weights_from_rates(gbs, world, w); + if (!known) { std::call_once(said_unknown, [all, world] { std::string who; for (int r = 0; r < world; ++r) @@ -280,7 +286,8 @@ int ar8_settle(ArInst* in, int rank, int world) { }); return RAD_OK; } - std::call_once(said_links, [all, world, &w] { + const bool duplex = me.mode == AR8_DUPLEX; + std::call_once(said_links, [all, world, duplex, &w] { std::string l; for (int r = 0; r < world; ++r) { char one[96]; @@ -290,7 +297,7 @@ int ar8_settle(ArInst* in, int rank, int world) { l += one; } std::fprintf(stderr, "[r4d] eight-rank two-shot shard weights from the slowest PCIe " - "hop of each card:%s\n", l.c_str()); + "hop of each card%s:%s\n", duplex ? " (duplex)" : "", l.c_str()); }); bool same = true; for (int r = 1; r < world; ++r) same = same && w[r] == w[0]; diff --git a/libr4d/r4d_ar_links.h b/libr4d/r4d_ar_links.h index 32ccfe35..01b5966e 100644 --- a/libr4d/r4d_ar_links.h +++ b/libr4d/r4d_ar_links.h @@ -83,3 +83,44 @@ inline bool r4d_ar_weights_from_rates(const double* gbs, int ws, int* w) { } return true; } + +// RADIANCE_AR8_SHARD_WEIGHTS=duplex: the weights that minimise the two-shot's link time when both +// directions of a link run at once (the pieced kernel's aim). Rank r with shard fraction x_r sends +// (1 - x_r) of the message in the first hop and (ws - 1) x_r in the second, and receives the same, +// so each direction carries (1 + (ws - 2) x_r) N at rate B_r. The slowest rank sets the time T, so +// the best table makes every rank with a shard finish together: x_r = (T B_r - 1) / (ws - 2) where +// that is positive, 0 elsewhere, with the x summing to 1 (water filling from the fastest rank +// down). Four ranks at B and four at B / 2 give x of 2/9 and 1/36, 8 to 1 where the quadratic rule +// above gives 4 to 1, and a time 10% lower (7/6 N / B / 2 against 1.3 N / B / 2). Scaled so the +// largest weight is 64. False when a rank's rate is unknown. +inline bool r4d_ar_weights_duplex(const double* gbs, int ws, int* w) { + if (ws < 3 || ws > 16) return false; + int order[16]; + for (int r = 0; r < ws; ++r) { + if (!(gbs[r] > 0.0)) return false; + order[r] = r; + } + for (int i = 1; i < ws; ++i) + for (int j = i; j > 0 && gbs[order[j]] > gbs[order[j - 1]]; --j) { + const int t = order[j]; order[j] = order[j - 1]; order[j - 1] = t; + } + // With the k fastest ranks holding shards, sum (T B_r - 1) = ws - 2 gives T; the set is right + // when the slowest of them still gets a positive share and the next one would not. + double sum = 0.0, t = 0.0; + int k = 0; + for (int n = 1; n <= ws; ++n) { + sum += gbs[order[n - 1]]; + const double tn = (double)(ws - 2 + n) / sum; + if (tn * gbs[order[n - 1]] <= 1.0) break; + k = n; + t = tn; + } + double x[16] = { 0 }, top = 0.0; + for (int i = 0; i < k; ++i) { + const int r = order[i]; + x[r] = (t * gbs[r] - 1.0) / (double)(ws - 2); + if (x[r] > top) top = x[r]; + } + for (int r = 0; r < ws; ++r) w[r] = (int)std::lround(64.0 * x[r] / top); + return true; +} diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index fe4faabe..f104a698 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -22581,7 +22581,8 @@ static void ar8_print_timeline(const std::vector& t, size_t cfg, double * `how` names the source and, for "auto", every rank's link. */ static bool ar8_weights_as_plugin(const std::vector& devs, int* w, std::string* how) { const char* e = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); - if (e && *e && std::strcmp(e, "auto")) { + const bool duplex = e && !std::strcmp(e, "duplex"); + if (e && *e && std::strcmp(e, "auto") && !duplex) { if (!std::strcmp(e, "off")) { *how = " (off)"; return false; } if (r4d_ar_shard_weights_parse(e, 8, w)) { *how = " (set)"; return true; } *how = fmt(" (%s=\"%s\" is invalid)", R4D_AR8_SHARD_WEIGHTS_ENV, e); @@ -22599,11 +22600,11 @@ static bool ar8_weights_as_plugin(const std::vector& devs, int* w, std::str gbs[r] = r4d_ar_link_gbs(l); links += fmt("%s r%d %.1f GT/s x%d", r ? "," : "", r, l.gts, l.width); } - if (!r4d_ar_weights_from_rates(gbs, 8, w)) { - *how = " (auto: a link is unreadable;" + links + ")"; + if (!(duplex ? r4d_ar_weights_duplex(gbs, 8, w) : r4d_ar_weights_from_rates(gbs, 8, w))) { + *how = fmt(" (%s: a link is unreadable;", duplex ? "duplex" : "auto") + links + ")"; return false; } - *how = " (auto:" + links + ")"; + *how = fmt(" (%s:", duplex ? "duplex" : "auto") + links + ")"; for (int r = 1; r < 8; ++r) if (w[r] != w[0]) return true; return false; } diff --git a/tests/r4d_ar_links_test.cpp b/tests/r4d_ar_links_test.cpp index a91e84f6..6930130f 100644 --- a/tests/r4d_ar_links_test.cpp +++ b/tests/r4d_ar_links_test.cpp @@ -77,8 +77,8 @@ std::string card(const Root& r, int i, const std::string& speed, int width) { struct Slot { const char* speed; int width; }; -/* The weights the eight cards give, or "unknown". */ -std::string weights(const Root& r, const Slot* slots) { +/* The weights the eight cards give, or "unknown", by the quadratic rule or the duplex model. */ +std::string weights(const Root& r, const Slot* slots, bool duplex = false) { std::string bdf[8]; for (int i = 0; i < 8; ++i) bdf[i] = card(r, i, slots[i].speed, slots[i].width); double gbs[8] = { 0 }; @@ -87,7 +87,8 @@ std::string weights(const Root& r, const Slot* slots) { if (r4d_ar_link_bottleneck(r.dir, bdf[i], &l)) gbs[i] = r4d_ar_link_gbs(l); } int w[8]; - if (!r4d_ar_weights_from_rates(gbs, 8, w)) return "unknown"; + if (!(duplex ? r4d_ar_weights_duplex(gbs, 8, w) : r4d_ar_weights_from_rates(gbs, 8, w))) + return "unknown"; std::string s; for (int i = 0; i < 8; ++i) s += (i ? "," : "") + std::to_string(w[i]); return s; @@ -123,6 +124,32 @@ TEST(repaired_links_give_four_and_one) { CHECK_EQ(weights(r, s), std::string("4,1,4,4,1,1,4,4")); } +/* The duplex model on the board after the repair: x16 holds 2/9 of the message and x8 1/36, so + * each direction of every link carries the same time's bytes; on the earlier board the Gen4 x8 + * cards hold nothing (they would need T B > N) and Gen5 x8 one seventh of x16. */ +TEST(the_duplex_model_balances_both_directions_of_every_link) { + Root r; + const Slot fixed[8] = { { G5, 16 }, { G5, 8 }, { G5, 8 }, { G5, 16 }, + { G5, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } }; + CHECK_EQ(weights(r, fixed, true), std::string("64,8,8,64,8,8,64,64")); + Root r2; + const Slot older[8] = { { G5, 16 }, { G5, 8 }, { G4, 8 }, { G5, 16 }, + { G4, 8 }, { G5, 8 }, { G5, 16 }, { G5, 16 } }; + CHECK_EQ(weights(r2, older, true), std::string("64,9,0,64,0,9,64,64")); + Root r3; + Slot even[8]; + for (Slot& x : even) x = { G5, 16 }; + CHECK_EQ(weights(r3, even, true), std::string("64,64,64,64,64,64,64,64")); + /* The time each rank's bytes take, (1 + 6 x) / B, is the same for every rank with a shard. */ + const double gbs[8] = { 63, 31.5, 31.5, 63, 31.5, 31.5, 63, 63 }; + int w[8]; + REQUIRE(r4d_ar_weights_duplex(gbs, 8, w)); + double sum = 0; + for (int i = 0; i < 8; ++i) sum += w[i]; + const double tf = (1 + 6 * w[0] / sum) / gbs[0], ts = (1 + 6 * w[1] / sum) / gbs[1]; + CHECK(std::fabs(tf - ts) / tf < 1e-9); +} + TEST(equal_links_give_equal_weights) { Root r; Slot s[8]; From c25bca83d504b655c0f58601b7bcb4d3f91756eb Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:13 +0200 Subject: [PATCH 150/152] libr4d: RADIANCE_AR8_FORM -- the eight-rank two-shot's steps in ring order, or with a flag after each half instead of a handshake a step The eight-rank two-shot reaches 56% of its link time at 16 MiB (1316 to 1340 us against 763), and measured(K) = f x link time(K) + h x (K + 1) fits f of about 1.45 and h of about 20 us a step: both the transfers and the step boundaries lose time. Two schedules of the same work go after them, each a new form beside the existing one, chosen by RADIANCE_AR8_FORM (unset or lockstep: as before) or per launch by the `form` parameter: - ring: the first hop goes to the peers in ring order from rank + 1 instead of ascending. In the lockstep order every card but rank 0 starts by writing rank 0's shard, then rank 1's, so the seven senders can converge on one receiver while the other links idle; in ring order each card receives from one peer at a time. - split: ring, and the one handshake a step, which waits until every peer has finished the whole step (next piece's first hop, this piece's reduce, the previous piece's assemble), becomes a flag after each half, awaited only before its data is read: before reducing piece j the peers' first hop of j, before assembling j their reduce of j. A card whose half is done goes on with the next piece's first hop while a slower card still reduces, so each link runs at its own pace instead of the slowest card's per step. The flags stay one monotone word per (block, source): the first hop of piece 0 at v0, of piece j + 1 at v0 + 2j + 1, the reduce of piece j at v0 + 2j + 2; the launch reserves pieces + 1 steps for its 2 pieces + 1 values, so it mixes with every other kernel on the instance. A launch still ends only after every peer has published its last reduce inside it, so the slot parity argument holds unchanged. r4d_ar_publish and r4d_ar_await (r4d_ar_wide.h) are the two halves of r4d_ar_handshake. Neither changes which rank folds a word or in what order, so all forms give the bits of the lockstep form, which compiles to the code it was. Ring and split are eight-rank only; the three- and four-rank launches stay lockstep and refuse another form. Every rank must read the same form; init compares it with the other eight-rank settings. --perfar8 numel iters dtype forms (comma-separated) times the forms side by side; the timeline prints a pair a synchronisation (K + 1 handshakes, or 2K awaits split, up to 8 pieces). r4d_selftest's weighted eight-rank runs repeat for ring and split at 1, 4 and 8 pieces over even, uneven, single-owner and zero-weight tables and with the piece count changing launch to launch, and the box's own weights run auto, duplex and off. On one card (R4D_SELFTEST_ONE_CARD) all three forms give the fold on every rank at 65536 to 8388608 elements, even and weighted, bf16 and fp32. Which form is fastest on the board is for the TP8 window to measure. Co-Authored-By: Claude Fable 5.1 --- docs/GUIDE.md | 15 ++- libr4d/r4d.h | 6 +- libr4d/r4d_ar_entry.hip | 38 ++++++- libr4d/r4d_ar_shards.h | 19 ++++ libr4d/r4d_ar_twoshot_Nrank_exact.hip | 139 +++++++++++++++++++------- libr4d/r4d_ar_wide.h | 44 ++++++++ libr4d/r4d_selftest.cpp | 114 ++++++++++++++++----- 7 files changed, 306 insertions(+), 69 deletions(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index a658d6a7..ac38eeb1 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1166,6 +1166,12 @@ checked against the fold (warm, the slowest rank): With the two Gen4 links retrained to Gen5 x8 the weights read 4,1,1,4,1,1,4,4 and the 16 MiB message takes 1360 µs. +That is 56% of the time the x8 cards' links need for its bytes (763 µs). `--perfar8 N iters bf16 +lockstep,ring,split` times the forms below side by side, and `--timeline` adds every rank's first +push, each step's work and wait and the final assemble, which in one piece are the reduce-scatter +and the all-gather apart; `R4D_SELFTEST_ONE_CARD=1` runs the eight ranks on one card, for their +bits only. + The links are read once, at startup: a link that drops to a lower speed while the server runs keeps its weight until the next start. `RADIANCE_AR8_SHARD_WEIGHTS` overrides them: `off` keeps the shards even, eight comma-separated integers set them, unset or `auto` reads the links. @@ -1173,8 +1179,13 @@ the shards even, eight comma-separated integers set them, unset or `auto` reads same time's bytes when both directions run at once (`r4d_ar_weights_duplex`): x16 64 and x8 8 on the repaired board, whose link time it puts 10% under the `auto` weights', a Gen4 x8 card nothing. `RADIANCE_AR8_PIECES` (1 to 16) fixes the piece count, and `RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS` -and `RADIANCE_AR8_PIECES_MIN_ELEMS` move the two sizes they start at. Every rank must read the -same values; where they differ, every rank stops at startup. +and `RADIANCE_AR8_PIECES_MIN_ELEMS` move the two sizes they start at. `RADIANCE_AR8_FORM` chooses +how the steps run, with the same bits: `lockstep` (unset) as above; `ring` sends the first hop to +the other cards in ring order from the next rank, so no card receives from all seven at once; +`split` does that and replaces each step's handshake, which waits for every card to finish the +whole step, by a flag after each half of it, awaited only where its data is read, so a card whose +half is done goes on with the next piece while a slower one still reduces. Every rank must read +the same values; where they differ, every rank stops at startup. ### 4.8 Host tier for finished conversations diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 5cfb2b09..32463fa6 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -451,8 +451,10 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - const int* shard_weights, long pieces, long timeline); -// `timeline`, a diagnostic, is 0 or a device buffer of nblocks * R4D_AR_TL_WORDS int64 that every + const int* shard_weights, long pieces, long timeline, + long form); +// `form` is R4D_AR8_FORM_* (r4d_ar_shards.h), the same on every rank: lockstep, ring or split, +// all with the same bits. `timeline`, a diagnostic, is 0 or a device buffer of nblocks * R4D_AR_TL_WORDS int64 that every // block of the eight-rank two-shot fills with wall-clock stamps (r4d_ar_wide.h): its start, each // handshake's arrival and release, its end. r4d_selftest --perfar8 with --timeline reads it. // The tiered int8 wire on both two-shot hops (r4d_ar_twoshot_Nrank_ti8.hip; codec in diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 400f9147..572f0ac1 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -79,6 +79,7 @@ struct Rendezvous { int w[R4D_MAX_RANKS] = { 0 }; int pieces = 0; long long weights_min = 0, pieces_min = 0; + int form = 0; R4DArLink link; } ar8[R4D_MAX_RANKS]; int failed = 0; @@ -134,6 +135,8 @@ struct ArInst { /* Messages under these sizes (elements) run even and in one piece, whatever is configured. */ long long weights_min = R4D_AR8_MIN_ELEMS_DEFAULT; long long pieces_min = R4D_AR8_MIN_ELEMS_DEFAULT; + /* Its form (RADIANCE_AR8_FORM); a launch's `form` parameter overrides it. */ + int form = R4D_AR8_FORM_LOCKSTEP; }; /* A parameter that may be declared as a range: init gets one band's frozen geometry, and buffers @@ -217,6 +220,21 @@ long long ar8_min_elems(const char* name, std::once_flag* said) { return v; } +/* RADIANCE_AR8_FORM: lockstep (or unset), ring or split. Anything else is lockstep, with one + * warning. */ +int ar8_form() { + const char* e = std::getenv(R4D_AR8_FORM_ENV); + if (!e || !*e) return R4D_AR8_FORM_LOCKSTEP; + const int f = r4d_ar8_form_parse(e); + if (f >= 0) return f; + static std::once_flag said; + std::call_once(said, [e] { + std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs lockstep, ring or split); the " + "eight-rank two-shot runs in lockstep\n", R4D_AR8_FORM_ENV, e); + }); + return R4D_AR8_FORM_LOCKSTEP; +} + /* The eight-rank two-shot's choice for one message, a function of its size and the instance * alone: a recorded launch keeps the table and piece count it was recorded with, and replays of * the same size agree with it. */ @@ -240,6 +258,7 @@ int ar8_settle(ArInst* in, int rank, int world) { me.pieces = ar8_pieces(); me.weights_min = ar8_min_elems(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, &said_w); me.pieces_min = ar8_min_elems(R4D_AR8_PIECES_MIN_ENV, &said_p); + me.form = ar8_form(); if ((me.mode == AR8_AUTO || me.mode == AR8_DUPLEX) && !ar8_own_link(&me.link)) me.link = R4DArLink(); { @@ -253,15 +272,24 @@ int ar8_settle(ArInst* in, int rank, int world) { for (int r = 0; r < world; ++r) if (all[r].mode != me.mode || std::memcmp(all[r].w, me.w, sizeof(me.w)) || all[r].pieces != me.pieces || all[r].weights_min != me.weights_min || - all[r].pieces_min != me.pieces_min) { + all[r].pieces_min != me.pieces_min || all[r].form != me.form) { std::fprintf(stderr, "[r4d] ranks %d and %d read different eight-rank two-shot " - "settings (%s, %s and their _MIN_ELEMS)\n", rank, r, - R4D_AR8_SHARD_WEIGHTS_ENV, R4D_AR8_PIECES_ENV); + "settings (%s, %s and their _MIN_ELEMS, %s)\n", rank, r, + R4D_AR8_SHARD_WEIGHTS_ENV, R4D_AR8_PIECES_ENV, R4D_AR8_FORM_ENV); return RAD_E_STATE; } in->pieces = me.pieces; in->weights_min = me.weights_min; in->pieces_min = me.pieces_min; + in->form = me.form; + if (me.form != R4D_AR8_FORM_LOCKSTEP) { + static std::once_flag said_form; + const int f = me.form; + std::call_once(said_form, [f] { + std::fprintf(stderr, "[r4d] eight-rank two-shot form: %s (%s)\n", + f == R4D_AR8_FORM_RING ? "ring" : "split", R4D_AR8_FORM_ENV); + }); + } int w[R4D_MAX_RANKS] = { 0 }; if (me.mode == AR8_SET) { @@ -1183,6 +1211,8 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { const long long pieces = ar8_pieces_for(in, c.numel, asked); /* A diagnostic: a device buffer of nblocks * R4D_AR_TL_WORDS int64 stamps (r4d.h). */ const long long timeline = r4d_pgeti_or(a->p, a->n_p, "timeline", 0); + const long long form = r4d_pgeti_or(a->p, a->n_p, "form", in->form); + if (form < R4D_AR8_FORM_LOCKSTEP || form > R4D_AR8_FORM_SPLIT) return RAD_E_INVAL; R4D_TRY("ar_twoshot_8rank_exact", r4d_ar_twoshot_8rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_scratch[3], in->peer_scratch[4], in->peer_scratch[5], @@ -1193,7 +1223,7 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub, weights, (long)pieces, (long)timeline)); + c.pub, weights, (long)pieces, (long)timeline, (long)form)); return RAD_OK; } diff --git a/libr4d/r4d_ar_shards.h b/libr4d/r4d_ar_shards.h index b7a825e5..bad8b5b7 100644 --- a/libr4d/r4d_ar_shards.h +++ b/libr4d/r4d_ar_shards.h @@ -13,12 +13,18 @@ #define R4D_AR8_SHARD_WEIGHTS_ENV "RADIANCE_AR8_SHARD_WEIGHTS" #define R4D_AR8_PIECES_ENV "RADIANCE_AR8_PIECES" +// The eight-rank two-shot's form (r4d_ar_twoshot_Nrank_exact.hip): lockstep (unset, the one +// handshake a step), ring (the first hop sent to the ranks in ring order from the next one) or +// split (ring, and a flag after each half of a step, each awaited only where its data is read). +// Every form folds the same words in the same order, so all give the same bits. +#define R4D_AR8_FORM_ENV "RADIANCE_AR8_FORM" // Below these message sizes (elements) the weights and the pieces do not apply: a decode-sized // message pays more for the extra handshakes and the uneven split than its link time saves // (measured on the eight R9700: 196608 elements run fastest even and in one piece, 524288 already // gain from weights and two pieces). #define R4D_AR8_SHARD_WEIGHTS_MIN_ENV "RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS" #define R4D_AR8_PIECES_MIN_ENV "RADIANCE_AR8_PIECES_MIN_ELEMS" +enum { R4D_AR8_FORM_LOCKSTEP = 0, R4D_AR8_FORM_RING = 1, R4D_AR8_FORM_SPLIT = 2 }; enum { R4D_AR_SHARD_WEIGHT_MAX = 65535, R4D_AR8_MIN_ELEMS_DEFAULT = 262144, @@ -36,6 +42,19 @@ inline int r4d_ar8_auto_pieces(long long numel) { return 8; } +// "lockstep", "ring" or "split" as R4D_AR8_FORM_*; -1 for anything else. +inline int r4d_ar8_form_parse(const char* s) { + if (!s) return -1; + const char* names[3] = { "lockstep", "ring", "split" }; + for (int f = 0; f < 3; ++f) { + const char* a = names[f]; + const char* b = s; + while (*a && *a == *b) { ++a; ++b; } + if (!*a && !*b) return f; + } + return -1; +} + // A non-negative decimal integer of at most `max`, nothing else. inline bool r4d_ar_parse_count(const char* s, long long max, long long* out) { if (!s || *s < '0' || *s > '9') return false; diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index 352887fc..e555a84f 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -23,6 +23,17 @@ // piece j+1's phase 1 shares the link with piece j's phase 2. A rank with a short shard then // sends and receives at once instead of one direction per phase. // +// Also at 8 ranks, two more forms of the same work (RADIANCE_AR8_FORM, the `form` parameter): +// * ring sends the first hop to the peers in ring order from rank + 1 instead of ascending, so +// at any moment each card receives from one peer rather than all seven from the same one; +// * split also replaces the one handshake a step, which waits for every peer to finish the whole +// step, by a flag after each half (the first hop of the next piece, the reduce of this one), +// each awaited only before its data is read: before reducing piece j the peers' first hop of +// j, before assembling j their reduce of j. A rank whose own half is done goes on with the +// next piece's first hop while a slower one still reduces, so the links run at their own pace +// instead of in lockstep. 2 * pieces + 1 flag values, pieces + 1 steps reserved. +// The words, their owners and their folds are the lockstep form's, so the bits are too. +// // Shares the wide family's flag/seq/scratch set (r4d_ar_wide.h): it publishes in the 2*seq flag // space plus the 2s-1 half-step (with pieces: pieces+1 values from 2s-1 on, after reserving one // step a piece), so one buffer set can carry any mix of one-shot and two-shot launches. The slot @@ -46,7 +57,7 @@ struct R4DArShardOff { // PIECED false fixes pieces at 1, so the unpipelined launch keeps the straight-line kernel. // CHAIN: the chained form's wait (before the sequence take, so a block of the next launch on the // instance never starts ahead of this one's) and add (r4d_chain.h); no block returns early. -template +template __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, @@ -60,10 +71,14 @@ __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( __shared__ unsigned int s_seq, s_slot; const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); // device-resident, replay-safe; `pieces` steps reserve the 2*pieces flag values this launch uses - r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot, (unsigned int)pieces); + // (the split form publishes 2 * pieces + 1 and reserves one step more) + r4d_ar_seq_take(seq_ctrs, R4D_AR_WIDE_MAX_BLOCKS, s_seq, s_slot, + (unsigned int)(FORM == R4D_AR8_FORM_SPLIT ? pieces + 1 : pieces)); const unsigned int v0 = 2u * s_seq - 1u; const int parity = (int)s_slot; - long long* const tl = tl_all ? tl_all + (size_t)b * R4D_AR_TL_WORDS : nullptr; + // the split form awaits 2 * pieces times, which the timeline holds up to 8 pieces + long long* const tl = tl_all && (FORM != R4D_AR8_FORM_SPLIT || 4 * pieces + 2 <= R4D_AR_TL_WORDS) + ? tl_all + (size_t)b * R4D_AR_TL_WORDS : nullptr; r4d_ar_tl_stamp(tl, 0); const int sh_max = sh.sh_max; @@ -91,7 +106,8 @@ __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( // phase 1: my contribution to each peer-owned shard -> owner's region A auto push1 = [&](int j) { const int p0 = w0 + j * pw, p1 = p0 + pw < w1 ? p0 + pw : w1; - for (int p = 0; p < NPEERS; ++p) { + for (int i = 0; i < NPEERS; ++i) { + const int p = FORM == R4D_AR8_FORM_LOCKSTEP ? i : (i + rank) % NPEERS; const int owner = peers.rank[p]; const int4* s1 = in4 + (size_t)R4D_TS_OFF(owner); int4* dst = pa[p]; @@ -143,25 +159,59 @@ __device__ __forceinline__ void r4d_ar_twoshot_wide_exact_body( * overlap one direction idles in each phase. With one piece the sequence is push, flag 2s-1, * reduce, flag 2s, assemble. A word is touched by the same thread in all three steps, which keeps * the in-place form safe. */ - push1(0); - r4d_ar_handshake(peers, my_flags, b, rank, v0, drain, acq, pub, tl ? tl + 1 : nullptr); - for (int j = 0; j < pieces; ++j) { - if (j + 1 < pieces) push1(j + 1); - reduce2(j); - if (j > 0) assemble(j - 1); - r4d_ar_handshake(peers, my_flags, b, rank, v0 + 1u + (unsigned int)j, drain, acq, pub, - tl ? tl + 3 + 2 * j : nullptr); - } - /* The hold ends after the last handshake, not the first: the reduce is fused with the phase-2 - * push (every reduced word goes to each peer's region B), so until then the link still carries - * this launch's phase-2 bytes. Here every phase-1 and phase-2 remote store has retired behind - * its flag store and every peer's pushes to this rank have been waited on; only the local - * assemble of the last piece is left (r4d_ar_seq.h). */ - r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); - assemble(pieces - 1); - if (tl) { - __syncthreads(); - r4d_ar_tl_stamp(tl, 3 + 2 * pieces); + if constexpr (FORM != R4D_AR8_FORM_SPLIT) { + push1(0); + r4d_ar_handshake(peers, my_flags, b, rank, v0, drain, acq, pub, tl ? tl + 1 : nullptr); + for (int j = 0; j < pieces; ++j) { + if (j + 1 < pieces) push1(j + 1); + reduce2(j); + if (j > 0) assemble(j - 1); + r4d_ar_handshake(peers, my_flags, b, rank, v0 + 1u + (unsigned int)j, drain, acq, pub, + tl ? tl + 3 + 2 * j : nullptr); + } + /* The hold ends after the last handshake, not the first: the reduce is fused with the phase-2 + * push (every reduced word goes to each peer's region B), so until then the link still carries + * this launch's phase-2 bytes. Here every phase-1 and phase-2 remote store has retired behind + * its flag store and every peer's pushes to this rank have been waited on; only the local + * assemble of the last piece is left (r4d_ar_seq.h). */ + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); + assemble(pieces - 1); + if (tl) { + __syncthreads(); + r4d_ar_tl_stamp(tl, 3 + 2 * pieces); + } + } else { + /* The same steps with a flag after each half. Published in program order on one monotone + * word: first hop of piece 0 at v0, of piece j + 1 at v0 + 2j + 1, the reduce of piece j at + * v0 + 2j + 2; so "peer's first hop of j done" is the word at v0 (j = 0) or v0 + 2j - 1, and + * "peer's reduce of j done" at v0 + 2j + 2. A launch completes only after every peer has + * published its last reduce, which it does inside this launch, so the slot parity argument + * of the lockstep form holds unchanged (r4d_ar_seq.h). */ + int n = 0; + auto tlp = [&]() { long long* p = tl ? tl + 1 + 2 * n : nullptr; ++n; return p; }; + push1(0); + r4d_ar_publish(peers, b, rank, v0, drain, pub); + for (int j = 0; j < pieces; ++j) { + if (j + 1 < pieces) { + push1(j + 1); + r4d_ar_publish(peers, b, rank, v0 + 2u * (unsigned int)j + 1u, drain, pub); + } + r4d_ar_await(peers, my_flags, b, j == 0 ? v0 : v0 + 2u * (unsigned int)j - 1u, acq, + tlp()); + reduce2(j); + r4d_ar_publish(peers, b, rank, v0 + 2u * (unsigned int)j + 2u, drain, pub); + if (j > 0) { + r4d_ar_await(peers, my_flags, b, v0 + 2u * (unsigned int)j, acq, tlp()); + assemble(j - 1); + } + } + r4d_ar_await(peers, my_flags, b, v0 + 2u * (unsigned int)pieces, acq, tlp()); + r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); + assemble(pieces - 1); + if (tl) { + __syncthreads(); + r4d_ar_tl_stamp(tl, 1 + 2 * n); + } } #undef R4D_TS_OFF #undef R4D_TS_LEN @@ -391,13 +441,13 @@ __device__ __forceinline__ void r4d_ar_twoshot_coded_body( unsigned int* gate_ctr, int pieces_arg, long long* tl_all #define R4D_ARTS_ARGS in4, peers, my_base, my_flags, out4, seq_ctrs, sh, slot_stride16, rank, \ drain, acq, pub, gate, gate_ctr, pieces_arg, tl_all -template +template __global__ void r4d_ar_twoshot_wide_exact_kernel(R4D_ARTS_PARAMS) { - r4d_ar_twoshot_wide_exact_body(R4D_ARTS_ARGS); + r4d_ar_twoshot_wide_exact_body(R4D_ARTS_ARGS); } -template +template __global__ void r4dchain_ar_twoshot_wide_exact(R4D_ARTS_PARAMS) { - r4d_ar_twoshot_wide_exact_body(R4D_ARTS_ARGS); + r4d_ar_twoshot_wide_exact_body(R4D_ARTS_ARGS); } #undef R4D_ARTS_ARGS #undef R4D_ARTS_PARAMS @@ -427,7 +477,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long out, long n_elem, long dtype, long rank, long stream_i, long nblocks, long nthreads, long drain, long acq, long pub, long gate, long gate_ctr, const int* shard_weights, - long pieces, long timeline, bool chain = false) { + long pieces, long timeline, long form, bool chain = false) { constexpr int NPEERS = WS - 1; if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce: rank " + std::to_string(rank) + @@ -476,6 +526,10 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, if (pieces < 1 || pieces > R4D_AR_TS_MAX_PIECES) throw std::runtime_error("all_reduce: pieces " + std::to_string(pieces) + " outside 1.." + std::to_string((int)R4D_AR_TS_MAX_PIECES)); + if (form < R4D_AR8_FORM_LOCKSTEP || form > R4D_AR8_FORM_SPLIT || + (WS != 8 && form != R4D_AR8_FORM_LOCKSTEP)) + throw std::runtime_error("all_reduce: form " + std::to_string(form) + " at " + + std::to_string(WS) + " ranks (ring and split are eight-rank forms)"); // a block's share of the longest shard bounds the pieces worth a handshake each const long words_a_block = (sh_max + nb - 1) / nb; const int np = (int)(pieces < words_a_block ? pieces : words_a_block); @@ -504,13 +558,26 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, } hipStream_t st = (hipStream_t)stream_i; -#define R4D_AR_TS_LAUNCH_P(T, LN, P) \ - (chain ? r4dchain_ar_twoshot_wide_exact \ - : r4d_ar_twoshot_wide_exact_kernel)<<>>( \ +#define R4D_AR_TS_LAUNCH_F(T, LN, P, F) \ + (chain ? r4dchain_ar_twoshot_wide_exact \ + : r4d_ar_twoshot_wide_exact_kernel)<<>>( \ (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ (int4*)out, (unsigned int*)seq_ctrs, sh, (int)slot_stride16, \ (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \ (unsigned int*)gate_ctr, np, (long long*)timeline) +#define R4D_AR_TS_LAUNCH_P(T, LN, P) \ + do { \ + if constexpr (WS == 8) { \ + if (form == R4D_AR8_FORM_RING) \ + R4D_AR_TS_LAUNCH_F(T, LN, P, R4D_AR8_FORM_RING); \ + else if (form == R4D_AR8_FORM_SPLIT) \ + R4D_AR_TS_LAUNCH_F(T, LN, P, R4D_AR8_FORM_SPLIT); \ + else \ + R4D_AR_TS_LAUNCH_F(T, LN, P, R4D_AR8_FORM_LOCKSTEP); \ + } else { \ + R4D_AR_TS_LAUNCH_F(T, LN, P, R4D_AR8_FORM_LOCKSTEP); \ + } \ + } while (0) #define R4D_AR_TS_LAUNCH(T, LN) \ do { \ if (np > 1) R4D_AR_TS_LAUNCH_P(T, LN, true); \ @@ -522,6 +589,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, else throw std::runtime_error("all_reduce: bad dtype"); #undef R4D_AR_TS_LAUNCH #undef R4D_AR_TS_LAUNCH_P +#undef R4D_AR_TS_LAUNCH_F } void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, @@ -534,7 +602,7 @@ void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pee /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, nullptr, - 1L, 0L); + 1L, 0L, 0L); } void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -547,7 +615,7 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr, - nullptr, 1L, 0L, chain != 0); + nullptr, 1L, 0L, 0L, chain != 0); } /* The coded form's conditions: bf16, a message that shards evenly into whole waves' 32 chunks @@ -602,7 +670,8 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, long nblocks, long nthreads, long drain, long acq, long pub, - const int* shard_weights, long pieces, long timeline) { + const int* shard_weights, long pieces, long timeline, + long form) { const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3, peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, @@ -610,5 +679,5 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, - shard_weights, pieces, timeline); + shard_weights, pieces, timeline, form); } diff --git a/libr4d/r4d_ar_wide.h b/libr4d/r4d_ar_wide.h index ce313f7f..c390615d 100644 --- a/libr4d/r4d_ar_wide.h +++ b/libr4d/r4d_ar_wide.h @@ -117,6 +117,50 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers r4d_ar_acquire(acq); } +// The two halves of r4d_ar_handshake, for a kernel that tells its peers how far it has come before +// it needs to know how far they have (the eight-rank two-shot's split form). Publish: once this +// block's stores have drained, every peer's word [b][rank] takes `val`. +template +__device__ __forceinline__ void r4d_ar_publish(const R4DArWidePeers& peers, int b, + int rank, unsigned int val, int drain, int pub) { + r4d_ar_drain(drain); + __syncthreads(); + if (threadIdx.x == 0) { + if (drain == 2) __threadfence_system(); + if (pub) { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, ""); +#pragma unroll + for (int p = 0; p < NPEERS; ++p) + r4d_ar_store_sys_rlx(&peers.flags[p][(size_t)b * WS + rank], val); + } else { +#pragma unroll + for (int p = 0; p < NPEERS; ++p) + r4d_ar_store_sys_rel(&peers.flags[p][(size_t)b * WS + rank], val); + } + } +} + +// Await: wait until each of this block's words from every peer has reached `val`, then acquire +// what they published before it. `tl` as r4d_ar_handshake's, stamped on entry and on release. +template +__device__ __forceinline__ void r4d_ar_await(const R4DArWidePeers& peers, + unsigned int* __restrict__ my_flags, int b, + unsigned int val, int acq, long long* tl = nullptr) { + const int tid = threadIdx.x; + if (tl && tid == 0) tl[0] = (long long)wall_clock64(); + if (tid < NPEERS) { + const unsigned int* f = &my_flags[(size_t)b * WS + peers.rank[tid]]; + unsigned long long z = 0; + while ((int)(r4d_ar_load_sys_rlx(f) - val) < 0) { + __builtin_amdgcn_s_sleep(2); + if (++z > R4D_AR_SPIN_MAX) __builtin_trap(); // lockstep violation + } + } + __syncthreads(); + if (tl && tid == 0) tl[1] = (long long)wall_clock64(); + r4d_ar_acquire(acq); +} + // The two-shot timeline (layout in r4d_ar_shards.h), one stamp of the device wall clock. static_assert(R4D_AR_TL_BLOCKS == R4D_AR_WIDE_MAX_BLOCKS, "r4d_ar_shards.h restates the ceiling"); __device__ __forceinline__ void r4d_ar_tl_stamp(long long* tl, int i) { diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index f104a698..dafbc6bb 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -22258,10 +22258,39 @@ static void ar_wide_weighted(const Plugin& pl, const std::vector& devs, con mixed); } } - /* The weights from this box's links ("auto", the default) and switched off, at the default - * floors and piece rule: what the engine runs without settings. Bits only, since what auto - * derives depends on the box (the startup line names it). */ - for (const char* mode : { "auto", "off" }) { + /* The ring and split forms (RADIANCE_AR8_FORM) over the same shards and piece counts: other + * link schedules of the same folds, so the oracle is unchanged. The split form takes two flag + * values a piece, so the run changing the piece count from launch to launch is the one a + * wrong reservation would fail. */ + { + ScopedEnv floor_w(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, "0"), floor_k(R4D_AR8_PIECES_MIN_ENV, "0"); + for (const char* form : { "ring", "split" }) { + ScopedEnv env_f(R4D_AR8_FORM_ENV, form); + for (const char* k : { "1", "4", "8" }) { + ScopedEnv env_k(R4D_AR8_PIECES_ENV, k); + for (const char* w : { "", "0,3,1,0,5,1,2,4", "1,0,0,0,0,0,0,0", "4,1,0,4,0,1,4,4" }) { + ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, *w ? w : "off"); + const std::string label = + std::string(name) + " form " + form + " pieces " + k + + (*w ? std::string(" weights ") + w : std::string(" even")); + for (const ArPatternRun& run : *w ? uneven : even) + if (!ar_pattern_check(row, devs, label, W, run)) return; + } + } + ScopedEnv env_k(R4D_AR8_PIECES_ENV, nullptr); + ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, "4,1,0,4,0,1,4,4"); + const ArPatternRun mixed = { + "bf16", { 4194304, 4194304, 8256, 4196352, 72, 4194304, 4194304 }, 3, + { 1, 4, 2, 8, 16, 3, 1 } }; + if (!ar_pattern_check(row, devs, std::string(name) + " form " + form + + " weights 4,1,0,4,0,1,4,4, pieces per launch", W, mixed)) + return; + } + } + /* The weights from this box's links ("auto", the default, and "duplex") and switched off, at + * the default floors and piece rule: what the engine runs without settings. Bits only, since + * what auto and duplex derive depends on the box (the startup line names it). */ + for (const char* mode : { "auto", "duplex", "off" }) { ScopedEnv env_w(R4D_AR8_SHARD_WEIGHTS_ENV, mode); ScopedEnv env_k(R4D_AR8_PIECES_ENV, nullptr); ScopedEnv floor_w(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, nullptr); @@ -22358,6 +22387,7 @@ struct Ar8Perf { std::vector sizes; std::vector rows; std::vector ks; /* per row: the `pieces` parameter, 0 or -1 none */ + std::vector forms; /* per row: the `form` parameter, -1 none */ std::vector nbs; StBarrier* bar = nullptr; int rc_init = RAD_OK; @@ -22428,6 +22458,7 @@ static void ar8_perf_worker(Ar8Perf* t) { std::vector ps = ip; if (nb > 0) ps.push_back(PI("nblocks", nb)); if (t->ks[j] > 0) ps.push_back(PI("pieces", t->ks[j])); + if (t->forms[j] >= 0) ps.push_back(PI("form", t->forms[j])); RadTensor ts[2] = { T(in, dt, { n }), T(out, dt, { n }) }; RadArgs a; std::memset(&a, 0, sizeof(a)); @@ -22544,7 +22575,8 @@ static void ar8_print_timeline(const std::vector& t, size_t cfg, double nst = nst ? std::min(nst, k) : k; } if (nb == 0 || nst < 4) { std::printf(" timeline r%d: no stamps\n", r); continue; } - const int pieces = (nst - 4) / 2; /* start, K + 1 pairs, end */ + /* start, a pair a synchronisation (K + 1 handshakes in lockstep, 2K awaits split), end */ + const int syncs = (nst - 2) / 2; auto ev = [&](int k, bool first) { long long m = v[(size_t)k]; for (int b = 1; b < nb; ++b) { @@ -22558,7 +22590,7 @@ static void ar8_print_timeline(const std::vector& t, size_t cfg, double std::string line; double work = 0, wait = 0; long long prev = t0; - for (int h = 0; h <= pieces; ++h) { + for (int h = 0; h < syncs; ++h) { const long long arr = ev(1 + 2 * h, false), rel = ev(2 + 2 * h, false); const double w1 = (double)(arr - prev) * us, w2 = (double)(rel - arr) * us; work += w1; wait += w2; @@ -22566,11 +22598,11 @@ static void ar8_print_timeline(const std::vector& t, size_t cfg, double w1, w2); prev = rel; } - const long long end = ev(3 + 2 * pieces, false); + const long long end = ev(1 + 2 * syncs, false); const double tail = (double)(end - prev) * us; work += tail; - std::printf(" timeline r%d (%d blocks, K%d): %s | tail %.1f = %.1f us " - "(work %.1f, wait %.1f)\n", r, nb, pieces, line.c_str(), tail, + std::printf(" timeline r%d (%d blocks, %d syncs): %s | tail %.1f = %.1f us " + "(work %.1f, wait %.1f)\n", r, nb, syncs, line.c_str(), tail, (double)(end - t0) * us, work, wait); } } @@ -22609,7 +22641,8 @@ static bool ar8_weights_as_plugin(const std::vector& devs, int* w, std::str return false; } -static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dtype) { +static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dtype, + const char* form_list) { constexpr int W = 8; if (iters <= 0) iters = 200; const bool bf = !std::strcmp(dtype, "bf16"); @@ -22647,18 +22680,39 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty if (hipDeviceGetAttribute(&wall_khz_i, hipDeviceAttributeWallClockRate, devs[0]) != hipSuccess) wall_khz_i = 0; const double wall_khz = (double)wall_khz_i; - std::vector rows; - std::vector ks; - /* The two-shot once a piece count; its instances share one key, so they are one buffer set. */ - for (const char* name : { "ar_oneshot_8rank_exact", "ar_twoshot_8rank_exact" }) { - const RadKernelInfo* r = find(pl, name); - if (!r) { std::printf("--perfar8: row %s absent\n", name); return; } - const bool two = !std::strcmp(name, "ar_twoshot_8rank_exact"); - for (int k : two ? std::vector{ -1, 1, 2, 4, 8 } : std::vector{ 0 }) { - rows.push_back(r); - ks.push_back(k); + /* The forms to time beside each other: "lockstep" alone (the default) passes no `form`, so + * RADIANCE_AR8_FORM decides as in the engine; a list passes each explicitly. */ + std::vector fl; + { + std::string all = form_list ? form_list : "lockstep"; + size_t at = 0; + while (at <= all.size()) { + const size_t comma = all.find(',', at); + const std::string one = all.substr(at, comma == std::string::npos ? std::string::npos + : comma - at); + const int f = r4d_ar8_form_parse(one.c_str()); + if (f < 0) { std::printf("--perfar8: form '%s' (lockstep, ring or split)\n", + one.c_str()); return; } + fl.push_back(f); + if (comma == std::string::npos) break; + at = comma + 1; } } + const bool explicit_forms = !(fl.size() == 1 && fl[0] == R4D_AR8_FORM_LOCKSTEP); + std::vector rows; + std::vector ks, forms; + /* The two-shot once a piece count and form; its instances share one key, so they are one + * buffer set. */ + { + const RadKernelInfo* one = find(pl, "ar_oneshot_8rank_exact"); + const RadKernelInfo* two = find(pl, "ar_twoshot_8rank_exact"); + if (!one || !two) { std::printf("--perfar8: an eight-rank exact row is absent\n"); return; } + rows.push_back(one); ks.push_back(0); forms.push_back(-1); + for (int f : fl) + for (int k : { -1, 1, 2, 4, 8 }) { + rows.push_back(two); ks.push_back(k); forms.push_back(explicit_forms ? f : -1); + } + } /* Ranks sharing a card must have every block resident at once, since a block spins until its * twins on the other ranks arrive: eight ranks of at most 8 blocks of 1024 threads fit an R9700, * and the block rule can ask for 16. */ @@ -22704,7 +22758,7 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty for (int r = 0; r < W; ++r) { Ar8Perf& x = t[(size_t)r]; x.rank = r; x.dev = devs[(size_t)r]; x.iters = iters; x.dtype = dtype; - x.sizes = sizes; x.rows = rows; x.ks = ks; x.nbs = nbs; x.bar = &bar; + x.sizes = sizes; x.rows = rows; x.ks = ks; x.forms = forms; x.nbs = nbs; x.bar = &bar; th.emplace_back(ar8_perf_worker, &x); } for (std::thread& x : th) x.join(); @@ -22735,10 +22789,14 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty /* The piece count the shim runs (before the launcher's words-a-block clamp). */ const int keff = n < kmin ? 1 : ks[j] > 0 ? ks[j] : kenv ? (int)kenv : r4d_ar8_auto_pieces(n); + const char* fam = forms[j] == R4D_AR8_FORM_RING ? "ring" + : forms[j] == R4D_AR8_FORM_SPLIT ? "split" + : forms[j] == R4D_AR8_FORM_LOCKSTEP ? "lockstep" + : "two-shot"; const std::string rname = !two ? std::string("one-shot") - : ks[j] < 0 ? fmt("two-shot set K%d", keff) - : keff != ks[j] ? fmt("two-shot K%d>%d", ks[j], keff) - : fmt("two-shot K%d", ks[j]); + : ks[j] < 0 ? fmt("%s set K%d", fam, keff) + : keff != ks[j] ? fmt("%s K%d>%d", fam, ks[j], keff) + : fmt("%s K%d", fam, ks[j]); const double sent = two ? 2.0 * (W - 1) / W * bytes : (double)(W - 1) * bytes; for (int nb : nbs) { const Ar8Perf& r0 = t[0]; @@ -27179,10 +27237,12 @@ static void usage(void) { " or runs (S contiguous runs). a=bf16 (default) or a=fp8_e4m3 (scale\n" " every 128); y=bf16 (default), y=f16 or y=f32. Each row's t and y are\n" " compared with the first row's; --cold applies.\n" - " --perfar8 numel [iters] [dtype]: the eight-rank exact all-reduce, one thread\n" + " --perfar8 numel [iters] [dtype] [forms]: the eight-rank exact all-reduce, one thread\n" " a card: one-shot and two-shot at the block rule and at 4..64 blocks,\n" " each checked against the rank-order fold; numel 0 runs the decode\n" " and prefill messages at 4096 wide. dtype bf16 (default) or fp32.\n" + " forms: the two-shot's, comma-separated (lockstep, ring, split;\n" + " default lockstep, which leaves RADIANCE_AR8_FORM in charge).\n" " With --timeline each two-shot point is launched once more with its\n" " per-block stamps on, and every rank's push, waits, steps and tail\n" " are printed. R4D_SELFTEST_ONE_CARD=1 runs the eight ranks on one card.\n" @@ -27269,6 +27329,7 @@ int main(int argc, char** argv) { const char* ar8_dt = "bf16"; long long lg_m = 0; int lg_it = 200; + const char* ar8_forms = "lockstep"; long long mx_m = 0, mx_e = 288, mx_k = 8; const char* mx_skew = nullptr; bool mx_f8 = false; @@ -27407,6 +27468,7 @@ int main(int argc, char** argv) { ar8_n = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_it = (int)std::strtol(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_dt = argv[++i]; + if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_forms = argv[++i]; } else if (!std::strcmp(argv[i], "--perfmhcpre")) { /* mhc_pre and mhc_post at GLM's shape, 16-byte rows against pitched ones. */ if (i + 1 >= argc) { usage(); return 2; } @@ -27570,7 +27632,7 @@ int main(int argc, char** argv) { if (ar8_n >= 0) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP - ar8_perf(pl, ar8_n, ar8_it, ar8_dt); + ar8_perf(pl, ar8_n, ar8_it, ar8_dt, ar8_forms); dfree_all(); #else skip("eight-rank all-reduce timing", "built without HIP"); From 7aa51e5b4a3981b6657e695b7998dfe62c24f378 Mon Sep 17 00:00:00 2001 From: Nunze Date: Wed, 21 Oct 2026 08:25:13 +0200 Subject: [PATCH 151/152] libr4d: r4d_selftest folds the exact all-reduces' oracle from inputs whose sum depends on the order -- the old pattern passed any order The eight-rank two-shot claims the same bits whatever the shard weights and piece count: a word is reduced by one thread of its owner, acc = 0.0f, then src[0..7] added in ascending rank order in fp32 and rounded once (reduce2 in r4d_ar_twoshot_Nrank_exact.hip), the one-shot's ar_vsum fold; weights move only which rank owns a word, pieces only which step reduces it, and every form (lockstep, ring, split) keeps both. The selftest's check of that claim was blind, though: ar_pattern_value is k / 64 with |k| <= 254, and eight such values sum exactly in fp32 in any order, so a kernel folding in another order, or twice-rounding a partial sum, passed. ar_rough_value gives bf16 values (8 significant bits) whose exponents span 2^-12 to 2^12, so partial sums round and the order shows: of 20000 elements, 547 fp32 sums differ between ascending order and rank 3 first. The exact wide rows' pattern runs (ar_wide_pattern, the weighted eight-rank runs over weights, pieces and forms) and --perfar8 now fold their oracle from it, ascending from 0.0f, and must match it bit for bit; the lossy and fused cases keep ar_pattern_value, whose bounds assume its range. Co-Authored-By: Claude Fable 5.1 --- libr4d/r4d_selftest.cpp | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index dafbc6bb..0fb90270 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -21986,6 +21986,19 @@ static float ar_pattern_value(int rank, int64_t i) { return (float)((int)((i * 37 + (int64_t)rank * 101) % 509) - 254) / 64.0f; } +/* The exact all-reduces' input. ar_pattern_value's sums are exact in fp32 in any order (eight + * values of 8 significant bits within 2^8 of each other), so a fold in another order would pass + * against them. These are bf16 values (8 significant bits) whose exponents span 2^-12 to 2^12, + * so an fp32 partial sum rounds and only the order the oracle uses, ascending rank from 0.0f, + * gives its bits: whoever owns a word, in however many pieces, must fold it that way. */ +static float ar_rough_value(int rank, int64_t i) { + uint64_t h = (uint64_t)i * 0x9E3779B97F4A7C15ull ^ ((uint64_t)rank + 1) * 0xC2B2AE3D27D4EB4Full; + h ^= h >> 29; h *= 0xBF58476D1CE4E5B9ull; h ^= h >> 32; + const float m = (float)(128 + (int)(h & 127)) / 128.0f; + const int e = (int)((h >> 7) % 25) - 12; + return ((h >> 12) & 1 ? -1.0f : 1.0f) * std::ldexp(m, e); +} + /* The pattern for the two-shot's coded form (r4d_ar_twoshot_Nrank_exact.hip), which codes a group * of 64 consecutive values on a shared exponent and sends a group it cannot code raw: the * per-element pattern, with groups sent down each path -- an exponent range of exactly 14 (coded) @@ -22007,7 +22020,7 @@ static float ar_coded_value(int rank, int64_t i) { } } static float ar_value(int coded_pattern, int rank, int64_t i) { - return coded_pattern ? ar_coded_value(rank, i) : ar_pattern_value(rank, i); + return coded_pattern ? ar_coded_value(rank, i) : ar_rough_value(rank, i); } static void ar_pattern_worker(ArPattern* t) { @@ -22102,7 +22115,7 @@ static bool ar_pattern_check(const RadKernelInfo* row, const std::vector& d for (int64_t i = 0; i < n; ++i) { float acc = 0.0f; for (int r = 0; r < world; ++r) { - const float v = ar_pattern_value(r, i); + const float v = ar_rough_value(r, i); acc += bf ? h_bf16(h_to_bf16(v)) : v; } const float want = bf ? h_bf16(h_to_bf16(acc)) : acc; @@ -22440,10 +22453,10 @@ static void ar8_perf_worker(Ar8Perf* t) { for (int64_t i = 0; i < n; ++i) { float acc = 0.0f; for (int r = 0; r < t->world; ++r) { - const float v = ar_pattern_value(r, i); + const float v = ar_rough_value(r, i); acc += bf ? h_bf16(h_to_bf16(v)) : v; } - const float v = ar_pattern_value(t->rank, i); + const float v = ar_rough_value(t->rank, i); if (bf) { const uint16_t b = h_to_bf16(v), w = h_to_bf16(acc); std::memcpy(&h[(size_t)i * 2], &b, 2); std::memcpy(&want[(size_t)i * 2], &w, 2); From 123c4396842625ae79a14e6e598890c0044a8b91 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 22 Oct 2026 10:38:15 +0200 Subject: [PATCH 152/152] krea2: `rebalance`, the text taps at ConditioningKrea2Rebalance's gains A request may ask for Krea 2's twelve text taps to be multiplied by fixed gains before the text fusion, as ComfyUI's ConditioningKrea2Rebalance (nova452) does at its defaults: multiplier 4 times the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1. `rebalance: true` on /v1/images/generations (JSON or form) sets RAD_GEN_COND_REBALANCE in RadGenBatch::cond_opts, appended in ABI 26; the plugin then scales each tapped layer's rows into te.h2 with chan_affine (f32, rounded once) and scatters those instead of te.x, so the residual stream is untouched. Without the field every pass issues exactly what it did before; other models ignore it. The gains cannot be folded into weights: the taps enter the fusion's layer-wise blocks raw, through a pre-norm residual. Co-Authored-By: Claude Opus 5.5 --- abi/rad_runtime.h | 8 +++++++ arch/krea2/krea2.cpp | 50 ++++++++++++++++++++++++++++++++++++++-- core/gen/driver.cpp | 1 + core/gen/gen.h | 2 ++ core/server/images.cpp | 12 +++++++++- docs/GUIDE.md | 4 +++- tests/abi_layout_rows.h | 1 + tests/abi_layout_table.h | 3 ++- 8 files changed, 76 insertions(+), 5 deletions(-) diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 6fde1f91..c567a630 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -378,8 +378,16 @@ typedef struct RadGenBatch { /* COND: the pass's token ids on the host ([n_tok]), for a plugin whose issue depends on * where a window's end-of-text marker sits. */ const int32_t* tokens_h; + /* ---- appended in ABI 26 (Krea 2's rebalance) */ + /* COND: the request's RAD_GEN_COND_* options, 0 for none. */ + int32_t cond_opts; } RadGenBatch; +/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */ +enum { + RAD_GEN_COND_REBALANCE = 1 /* Krea 2: the text taps at the plugin's fixed rebalance gains */ +}; + /* An entry's flags on a DENOISE pass. */ enum { RAD_GEN_F_FIRST = 1, /* the image's first step: its latent is the noise its seed draws */ diff --git a/arch/krea2/krea2.cpp b/arch/krea2/krea2.cpp index 99300df0..e143ca61 100644 --- a/arch/krea2/krea2.cpp +++ b/arch/krea2/krea2.cpp @@ -73,6 +73,11 @@ enum { kMaxLanes = 8 }; static const int kTaps[] = { 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 }; enum { kNTaps = 12 }; +/* The rebalance a request may ask for (`rebalance`, RAD_GEN_COND_REBALANCE): every tap times a fixed + * gain before the text fusion, ComfyUI's ConditioningKrea2Rebalance (nova452) at its defaults -- + * multiplier 4 times the per-layer weights 1, 1, 1, 1, 1, 1, 1, 2.5, 5, 1.1, 4, 1. */ +static const double kRebalance[] = { 4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4 }; + static const char* kSysPrompt = "Describe the image by detailing the color, shape, size, texture, quantity, text, spatial " "relationships of the objects and background:"; @@ -85,6 +90,8 @@ struct TeLayer { GateQuantFP8 gq{}; rad_op op_n1 = 0, op_qkr = 0, op_attn = 0, op_ar1 = 0, op_add1 = 0; rad_op op_n2 = 0, op_ar2 = 0, op_add2 = 0, op_tap = 0; + rad_op op_gain = 0; /* the tap's rebalance gain into te.h2 */ + rad_op op_tap_g = 0; /* the scatter from te.h2, when rebalanced */ int tap = -1; /* this layer's output is tap `tap`, or none */ }; @@ -131,6 +138,7 @@ struct Model { ActFP8 a_th{}, a_tattn{}, a_tffn{}; std::vector te; rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */ + std::string tap_mul[kNTaps]; /* chan_affine's `mul` for each tap's rebalance gain */ /* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks * over the mixed rows `b_ft` */ @@ -371,6 +379,24 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { else std::snprintf(sections, sizeof sections, "24 20 20"); + /* The rebalance gains, as chan_affine lists: the tap's row seen as rows of 64 channels. The + * scaled copy goes through te.h2, free between a layer's add and the next layer's projections, + * so the residual stream itself is never scaled. */ + enum { kGainCh = 64 }; + if (g.n_embd % kGainCh) return RAD_E_INVAL; + for (int t = 0; t < kNTaps; ++t) { + char v[32]; + std::snprintf(v, sizeof v, "%.9g", kRebalance[t]); + m.tap_mul[t].clear(); + for (int k = 0; k < kGainCh; ++k) { + if (k) m.tap_mul[t] += ' '; + m.tap_mul[t] += v; + } + } + static std::string zeros64; + if (zeros64.empty()) + for (int k = 0; k < kGainCh; ++k) zeros64 += k ? " 0" : "0"; + /* Layers up to the last tap only. */ const int n_run = kTaps[kNTaps - 1]; if (g.n_layer < n_run) { @@ -449,6 +475,22 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { T)); L.op_ar2 = all_reduce(b, g, m.b_th2, T); L.op_add2 = add_op(b, T, g.n_embd, m.b_tx, m.b_th2, m.b_tx); + if (L.tap >= 0) { + /* f32 arithmetic, rounded once into bf16 (`round` 0) */ + L.op_gain = rw(b, RAD_OP(b, "chan_affine", + RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", kGainCh), + RAD_STR("mul", m.tap_mul[L.tap].c_str()), + RAD_STR("add", zeros64.c_str()), + RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"), + RAD_INT("round", 0)), + RAD_NOWEIGHTS), + { m.b_tx }, { m.b_th2 }); + L.op_tap_g = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), + RAD_INT("n", g.n_embd), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_th2, m.b_tidx, m.b_taps }, { m.b_taps }); + } if (L.tap >= 0) L.op_tap = rw(b, RAD_OP(b, "scatter_rows", RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", g.n_embd), @@ -456,7 +498,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { RAD_NOWEIGHTS), { m.b_tx, m.b_tidx, m.b_taps }, { m.b_taps }); if (!L.op_n1 || !L.op_qkr || !L.op_attn || !L.op_add1 || !L.op_n2 || !L.op_add2 || - (L.tap >= 0 && !L.op_tap)) + (L.tap >= 0 && (!L.op_tap || !L.op_gain || !L.op_tap_g))) return RAD_E_INVAL; } return m.op_embed && m.op_iota ? RAD_OK : RAD_E_INVAL; @@ -1157,6 +1199,7 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { const Geom& g = m.gt; const int64_t T = batch->n_tok; const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const bool rebalance = batch->gen_b && (batch->gen_b->cond_opts & RAD_GEN_COND_REBALANCE); RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_tx, T)); RAD_ISSUE_N(c, m.op_iota, T, brows(m.b_tidx, T)); @@ -1180,8 +1223,11 @@ static void step_te(RadCtx* c, const RadBatch* batch, const Model& m) { L.down.step(c, m.a_tffn, m.b_th2, T); if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, T * g.n_embd, brows(m.b_th2, T), RAD_NONE); RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_tx, T), brows(m.b_th2, T), brows(m.b_tx, T)); + if (L.tap >= 0 && rebalance) + RAD_ISSUE_N(c, L.op_gain, T, brows(m.b_tx, T), brows(m.b_th2, T)); if (L.tap >= 0) - RAD_ISSUE_N(c, L.op_tap, T, brows(m.b_tx, T), brows(m.b_tidx, T), + RAD_ISSUE_N(c, rebalance ? L.op_tap_g : L.op_tap, T, + brows(rebalance ? m.b_th2 : m.b_tx, T), brows(m.b_tidx, T), brow_slice(m.b_taps, L.tap, (int64_t)kTeRows * kNTaps - L.tap, g.n_embd)); } diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index 001883cf..20b5d6e6 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -816,6 +816,7 @@ const RadBatch* Driver::build_cond(Job& j, int branch, int step) { G.aux_cu = n_aux ? dptr(ri, R_AUX) : nullptr; G.aux_ids = n_aux ? dptr(ri, R_AUX) + 2 : nullptr; G.tokens_h = hptr(R_TOK); + G.cond_opts = j.req->cond_opts; if (joint()) { B.n_kv_groups = 0; B.kv = nullptr; diff --git a/core/gen/gen.h b/core/gen/gen.h index 597f9361..cd23d240 100644 --- a/core/gen/gen.h +++ b/core/gen/gen.h @@ -118,6 +118,8 @@ struct Request { * for none, and the hold that keeps the slot's adapters in it until the request is done. */ int32_t lora_slot = -1; std::shared_ptr lora_hold; + /* RAD_GEN_COND_* for the plugin's COND passes (`rebalance`: Krea 2's tap gains). */ + int32_t cond_opts = 0; std::shared_ptr ticket; }; diff --git a/core/server/images.cpp b/core/server/images.cpp index 15b44357..95725f77 100644 --- a/core/server/images.cpp +++ b/core/server/images.cpp @@ -65,6 +65,7 @@ struct ImgReq { std::string background = "auto", format = "png", quality = "auto"; int32_t compression = -1; bool stream = false; + bool rebalance = false; std::vector images; bool has_mask = false; mm::FrameRGBA mask; @@ -87,7 +88,7 @@ json form_value(const std::string& key, const std::string& v) { if (e && *e == 0 && !v.empty()) return json(x); return json(v); } - if (key == "stream") { + if (key == "stream" || key == "rebalance") { if (v == "true" || v == "1") return json(true); if (v == "false" || v == "0") return json(false); } @@ -243,6 +244,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { "style", "user", "input_fidelity", "seed", "negative_prompt", "true_cfg_scale", "guidance_scale", "num_inference_steps", "width", "height", "loras", "lora", "sampler", "scheduler", + "rebalance", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; @@ -395,6 +397,13 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { r.seed = (uint64_t)body["seed"].get(); r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get() != -1; } + /* Krea 2's fixed tap gains (ConditioningKrea2Rebalance's defaults, arch/krea2); other models + * ignore it. */ + if (body.contains("rebalance") && !body["rebalance"].is_null()) { + if (!body["rebalance"].is_boolean()) + return error_response(err_bad("rebalance", "expected true or false"), req.peer); + r.rebalance = body["rebalance"].get(); + } if (str("negative_prompt", &r.negative) < 0) return error_response(err_bad("negative_prompt", "expected a string"), req.peer); /* The scale in the model card's terms: off at 0 for a card that states it as @@ -527,6 +536,7 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) { g->scheduler = r.scheduler; g->seed = r.seed; g->previews = r.previews; + g->cond_opts = r.rebalance ? RAD_GEN_COND_REBALANCE : 0; /* The driver guides as uncond + cfg (cond - uncond); a card's cond + s (cond - uncond) is * that at s + 1. */ g->cfg = (float)(info.cfg_original ? r.cfg + 1.0 : r.cfg); diff --git a/docs/GUIDE.md b/docs/GUIDE.md index ac38eeb1..00968f9a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2066,7 +2066,9 @@ under Qwen's research license, non-commercial. (`background: transparent` is a 400), 1024x1024 by default, sides rounded down to multiples of 16, up to 2048x2048 (16384 latent tokens). Krea 2 Raw runs 28 steps at guidance 4.5 against an empty negative prompt and Turbo 8 steps unguided; Krea 2 reads only text, so `/v1/images/edits` answers -501. FLUX.3 [klein] runs 16 steps unguided and its base 50 at guidance 3.5; both edit from up to ten +501. `rebalance: true` multiplies Krea 2's twelve text taps by +fixed gains before the text fusion, as ComfyUI's ConditioningKrea2Rebalance at its defaults +(4, 4, 4, 4, 4, 4, 4, 10, 20, 4.4, 16, 4); other models ignore the field. FLUX.3 [klein] runs 16 steps unguided and its base 50 at guidance 3.5; both edit from up to ten pictures, each shrunk to 1024x1024 of area when larger. The guidance scale is `guidance_scale` or `true_cfg_scale` (one of them), in the model card's terms. FLUX.3's pipeline can rewrite a prompt with a separate language model first; radiance reads the prompt as given. diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index e95bb306..11b06316 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -379,6 +379,7 @@ ABI_FIELD(RadGenBatch, step) ABI_FIELD(RadGenBatch, size_px) ABI_FIELD(RadGenBatch, entry_h) ABI_FIELD(RadGenBatch, tokens_h) +ABI_FIELD(RadGenBatch, cond_opts) ABI_STRUCT(RadGeneratorDecl) ABI_FIELD(RadGeneratorDecl, name) ABI_FIELD(RadGeneratorDecl, layout) diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index dc5940cc..fe5769e5 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -321,7 +321,7 @@ { "RadFuseStep", "n_p", 584, 4 }, { "RadFuseStep", "from", 588, 32 }, { "RadFuseStep", "n_from", 620, 4 }, -{ "RadGenBatch", "", 0, 400 }, +{ "RadGenBatch", "", 0, 408 }, { "RadGenBatch", "rows", 0, 8 }, { "RadGenBatch", "src", 8, 8 }, { "RadGenBatch", "rope", 16, 8 }, @@ -375,6 +375,7 @@ { "RadGenBatch", "size_px", 376, 8 }, { "RadGenBatch", "entry_h", 384, 8 }, { "RadGenBatch", "tokens_h", 392, 8 }, +{ "RadGenBatch", "cond_opts", 400, 4 }, { "RadGeneratorDecl", "", 0, 376 }, { "RadGeneratorDecl", "name", 0, 8 }, { "RadGeneratorDecl", "layout", 8, 4 },