From 469441d90f46c0c79bd9fa1314f58c818a1881b0 Mon Sep 17 00:00:00 2001 From: Deadcode Date: Mon, 5 Oct 2026 16:34:37 +0200 Subject: [PATCH] radiance 1.0.11 - The n-gram embedding table (Qwen3.8-Flash-Next's per-layer embedding) can be gathered on the card. libr4d gains a row for embed_lookup_q whose output is the host gather's to the bit, and --ngram-placement uses it: ram keeps a pinned copy in RAM that the cards read in place over the link, so a step has no host work in it; vram puts the whole table on every card that holds it; disk reads it from the container on the host, as before. auto takes the first of the three that holds the table and prints why it passed over the others. Without a device kernel for the gather, ram is the locked copy the host gather reads and vram is refused, as in 1.0.10. - The pinned copy is not charged to RLIMIT_MEMLOCK; the host gather's locked copy still is, so --ulimit memlock=-1 matters only on a run without the cards. - The idea and a first kernel for the device gather came from Code000. --- CMakeLists.txt | 2 +- NOTICE | 4 +- arch/common/rad_block_ple.h | 24 ++-- core/config.cpp | 12 +- core/engine.cpp | 2 + core/engine.h | 18 ++- core/engine_bringup.cpp | 257 ++++++++++++++++++++++++++---------- core/format/table_copy.cpp | 83 ++++++------ core/format/table_copy.h | 9 +- core/place/planner.cpp | 131 +++++++++++------- core/place/planner.h | 23 +++- core/rad_core.h | 8 +- core/runtime/issue.cpp | 10 +- docs/DOCKER.md | 9 +- docs/GUIDE.md | 28 ++-- docs/OPS.md | 55 +++++--- libavx/README.md | 22 +-- libr4d/r4d_fp8_layout.cpp | 33 +++++ libr4d/r4d_model_bf16.hip | 116 ++++++++++++++++ libr4d/r4d_plugin.h | 7 + libr4d/r4d_rows.cpp | 24 ++++ libr4d/r4d_selftest.cpp | 114 ++++++++++++++++ libr4d/r4d_shapes.cpp | 20 +++ tests/place_test.cpp | 84 ++++++++++-- 24 files changed, 848 insertions(+), 247 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c85afeac..2b3c6f85 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.0.10 LANGUAGES C CXX) +project(radiance VERSION 1.0.11 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/NOTICE b/NOTICE index ca83c120..74d9af1b 100644 --- a/NOTICE +++ b/NOTICE @@ -4,8 +4,8 @@ Copyright 2026 Deadcode and the radiance contributors Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the MXFP4 GEMM and the GDN kernels' overflow guards), goodman-b (four-rank tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank -writes, the n-gram table in RAM and the four-class expert split) and mechkbfan (the token -embedding in the pinned host pool). +writes, the n-gram table in RAM and the four-class expert split), mechkbfan (the token +embedding in the pinned host pool) and Code000 (the n-gram gather on the card). 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/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h index 8a82cfc5..155dee31 100644 --- a/arch/common/rad_block_ple.h +++ b/arch/common/rad_block_ple.h @@ -20,16 +20,19 @@ * * ============================== THE TABLE DECIDES THE SHAPE OF ALL OF THIS ====================== * - * 51.2 GB cannot be on the card and cannot be staged onto it, so `embed_lookup_q` runs on the HOST - * over the container's own mmap and its result crosses the link once -- 5 KB a token at decode. - * libavx/avx_ngram.cpp carries that argument in full. Three consequences reach this file: + * 51.2 GB cannot be staged onto a card, so `embed_lookup_q` reads it where --ngram-placement put + * it: the HOST gather over the container's own mmap or a locked copy in RAM (libavx/avx_ngram.cpp + * carries that argument in full), or a device kernel reading a pinned copy over the link -- or the + * card's own copy, on a card that holds it. Either way its result reaches the card through the + * host arena, 5 KB a token at decode. Three consequences reach this file: * * THE TABLE IS A WEIGHT OPERAND, because the planner puts an op on the host only when every - * weight operand of it is Site::Host. A gather whose source were an activation could never be - * placed there. + * weight operand of it is Site::Host, and decides that from the table's placement. A gather + * whose source were an activation could never be placed there. * - * ITS BUFFERS ARE HOST DOMAIN. `ids` and `e` are read and written by a host kernel, so they live - * in the host arena; everything downstream of `e` is ordinary device work. + * ITS BUFFERS ARE HOST DOMAIN. `ids` and `e` are read and written by the host gather when it + * runs, so they live in the host arena, which a device gather reads and writes over the link + * just as well; everything downstream of `e` is ordinary device work. * * IT IS 128 CHECKPOINT TENSORS. RadNameMap holds eight sources, so the map is declared in pieces * by map_concat_shards() and the order IS the concatenation -- a permuted table is a model that @@ -302,9 +305,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C /* ---- buffers ---------------------------------------------------------------------------- */ /* HOST DOMAIN for the two the gather touches. `ids` is written by ngram_ids and read by the - * host gather; `e` is written by the host gather and read by one device copy onto the card + * gather; `e` is written by the gather and read by one device copy onto the card * (`ple_emb_dev`, below). The host arena is mapped, so the device side of that hand-off is a - * link read (core/runtime/ctx.cpp) -- 5 KB a token at decode. + * link read (core/runtime/ctx.cpp) -- 5 KB a token at decode. Where a device kernel gathers + * (--ngram-placement ram or vram, with libr4d loaded) it reads `ids` and writes `e` over the + * link too, which costs a round trip of those 5 KB and leaves no host op in the step: the + * domain is declared here, before the placement that would say who gathers is decided. * * `ids` IS PERSIST because it is written at the top of the step and read at this layer: the * buffer plan computes liveness in DECLARED order, where the two ops are neighbours, and a diff --git a/core/config.cpp b/core/config.cpp index 5770750b..b5bfcb49 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -62,11 +62,13 @@ static const Flag g_flags[] = { " auto keeps it on the card unless the KV cache could then not\n" " hold one --max-model-len sequence. disk is refused: the lookup\n" " writes the card's activations, which no host read can reach" }, - { "--ngram-placement", "WHERE", "auto (default) | ram | disk: where an n-gram embedding table\n" - " lives (Qwen3.8-Flash-Next: 47.7 GiB). disk reads its rows from\n" - " the container; ram copies it into locked memory at load; auto\n" - " takes ram when free memory, the memlock limit and the cgroup\n" - " allow it. vram is refused: only a host kernel reads the table" }, + { "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n" + " embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n" + " vram puts all of it on every card; ram copies it into\n" + " host memory at load, pinned for the cards to read\n" + " (locked, where only a host kernel reads it); disk reads\n" + " its rows from the container on the host. auto takes the\n" + " first of the three that holds it" }, { "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n" " container on disk (O_DIRECT); a routed expert is read a layer\n" " at a time, so a step is paced by the drive" }, diff --git a/core/engine.cpp b/core/engine.cpp index 6afcb425..8736b0dc 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -82,6 +82,8 @@ Engine::~Engine() { ranks_.clear(); for (TableCopy& c : table_copies_) table_copy_free(&c); table_copies_.clear(); + for (void* p : card_copies_) rad_dev_free(p, RAD_MEM_HOST_MAPPED); + card_copies_.clear(); rad_tools_registry().close(); } diff --git a/core/engine.h b/core/engine.h index 9917e12e..d16a8575 100644 --- a/core/engine.h +++ b/core/engine.h @@ -122,13 +122,19 @@ private: * (engine_bringup.cpp says how auto chooses). */ int resolve_table_placement(const std::vector& facts, const std::vector& emb_bytes, int64_t kv_floor, - int64_t ngram_bytes, bool ngram_device); - /* --ngram-placement ram: the locked copy of the container's [src, src + n), file offset `foff`, - * made once and shared by every rank. */ - int lock_table_copy(const uint8_t* src, int64_t n, int64_t foff, void** out, std::string* why); - /* The copies made, each [base, base + bytes), and the container address each one copies. - * Unlocked and unmapped in ~Engine after the ranks that read them are gone. */ + int64_t ngram_bytes, bool ngram_device, bool ngram_host); + /* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made + * once and shared by every rank -- locked for the host gather, or pinned for a device kernel + * to read over the link (`card`). */ + int copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out, + std::string* why); + /* An auto-chosen pinned copy that could not be made: every rank's n-gram gather to the host. */ + bool ngram_gather_to_host(); + /* The copies made: the locked ones, each [base, base + bytes); the pinned ones, rad_dev_alloc + * RAD_MEM_HOST_MAPPED ranges; and the container address each one copies. Freed in ~Engine + * after the ranks that read them are gone. */ std::vector table_copies_; + std::vector card_copies_; std::vector> table_copy_of_; int load_weights(); int configure_kv(); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index a893dfda..44267188 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -56,9 +56,10 @@ namespace rad { * every one gets a line of its own carrying the geometry and the constraint that refused it. * * A DEVICE miss whose op DID resolve on the host is not a hole at all. The planner puts that op's - * arithmetic on the host and its weights in the container's mapping, which is the whole of how - * `embed_lookup_q` serves a table too large to copy into VRAM. Reporting that as fatal produces - * an error nobody believes, and an error nobody believes is how a real one goes unread. + * arithmetic on the host and its weights in the container's mapping, which is how `embed_lookup_q` + * serves a table too large to copy into VRAM when no device kernel for it is loaded. Reporting + * that as fatal produces an error nobody believes, and an error nobody believes is how a real one + * goes unread. * * A HOST miss removes ONE placement option for ONE op, and for a kernel library written for a GPU * it is the ordinary case rather than news: most ops have no host implementation and never will. @@ -286,13 +287,15 @@ static bool cgroup_room(const std::string& dir, bool v2, int64_t* room) { return true; } -/* WHETHER `need` MORE BYTES CAN BE LOCKED IN HOST MEMORY, after `still` more that this process - * will allocate before the copy is made, or why not. Each limit is one a copy would otherwise meet - * part way through: RLIMIT_MEMLOCK (unless the process holds CAP_IPC_LOCK), the memory the kernel - * reports available, and every memory cgroup from the process's own up to the root it can see, - * which is the limit Docker's --memory sets and the kernel enforces by killing the process. A - * limit that cannot be read is not one; a limit that can is never guessed at. */ -static bool lockable_room(int64_t need, int64_t still, std::string* why) { +/* WHETHER `need` MORE BYTES CAN BE HELD IN HOST MEMORY, after `still` more that this process will + * allocate before the copy is made, or why not. Each limit is one a copy would otherwise meet part + * way through: the memory the kernel reports available, every memory cgroup from the process's own + * up to the root it can see, which is the limit Docker's --memory sets and the kernel enforces by + * killing the process -- and, for a copy mlock()ed for the host gather (`mlocks`), RLIMIT_MEMLOCK + * unless the process holds CAP_IPC_LOCK. Pinned memory a card reads is the driver's userptr + * mapping, the host pools' kind, and RLIMIT_MEMLOCK does not count it. A limit that cannot be read + * is not one; a limit that can is never guessed at. */ +static bool lockable_room(int64_t need, int64_t still, bool mlocks, std::string* why) { long long locked_kb = 0; unsigned long long caps = 0; { @@ -304,7 +307,7 @@ static bool lockable_room(int64_t need, int64_t still, std::string* why) { } } struct rlimit rl {}; - if (!((caps >> 14) & 1) && ::getrlimit(RLIMIT_MEMLOCK, &rl) == 0 && + if (mlocks && !((caps >> 14) & 1) && ::getrlimit(RLIMIT_MEMLOCK, &rl) == 0 && rl.rlim_cur != RLIM_INFINITY && (int64_t)rl.rlim_cur < locked_kb * 1024 + need) { *why = fmt("RLIMIT_MEMLOCK allows %s locked and the copy locks %s (Docker: --ulimit " "memlock=-1; systemd: LimitMEMLOCK=infinity)", humanb((int64_t)rl.rlim_cur).c_str(), @@ -361,25 +364,63 @@ static bool lockable_room(int64_t need, int64_t still, std::string* why) { return true; } -/* --ngram-placement ram: the copy is table_copy_make's (core/format/table_copy.h); this keeps one - * a container address, shared by every rank, and frees them after the ranks in ~Engine. */ -int Engine::lock_table_copy(const uint8_t* src, int64_t n, int64_t foff, void** out, - std::string* why) { +/* --ngram-placement ram: the copy is table_copy_make's (core/format/table_copy.h), or for a card, + * table_copy_fill's into pinned memory every card maps at its host address (rad_dev_alloc + * RAD_MEM_HOST_MAPPED, locked in pieces). This keeps one a container address, shared by every rank, + * and frees them after the ranks in ~Engine. */ +int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out, + std::string* why) { for (const auto& c : table_copy_of_) if (c.first == src) { *out = c.second; return RAD_OK; } const auto t0 = std::chrono::steady_clock::now(); - TableCopy tc; - const int rc = table_copy_make(*file_, src, n, foff, &tc, why); - if (rc != RAD_OK) return rc; - RAD_INFO("placement: n-gram table copied into locked memory, %s in %.1f s", - humanb(n).c_str(), + void* base = nullptr; + if (card) { + base = rad_dev_alloc(n, RAD_MEM_HOST_MAPPED); + if (!base) { + *why = fmt("pinning %s: %s", humanb(n).c_str(), rad_dev_last_error()); + return RAD_E_NOMEM; + } + const int rc = table_copy_fill(*file_, src, n, foff, static_cast(base), why); + if (rc != RAD_OK) { + rad_dev_free(base, RAD_MEM_HOST_MAPPED); + return rc; + } + card_copies_.push_back(base); + } else { + TableCopy tc; + const int rc = table_copy_make(*file_, src, n, foff, &tc, why); + if (rc != RAD_OK) return rc; + table_copies_.push_back(tc); + base = tc.base; + } + RAD_INFO("placement: n-gram table copied into %s, %s in %.1f s", + card ? "pinned memory the cards read" : "locked memory", humanb(n).c_str(), std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); - table_copies_.push_back(tc); - table_copy_of_.push_back({ src, tc.base }); - *out = tc.base; + table_copy_of_.push_back({ src, base }); + *out = base; return RAD_OK; } +/* THE GATHER MOVES TO THE HOST WITH THE TABLE, when --ngram-placement auto chose a pinned copy for + * a card and it could not be made. Every rank's n-gram weights take the host site, on the + * WeightInfo Ctx::init reads to choose the op's domain and on the plan beside it, so the gather and + * its scale move together; a copy some rank already published is host memory, which the host + * gather reads as it reads RAM. False where no host kernel gathers the table. */ +bool Engine::ngram_gather_to_host() { + for (auto& r : ranks_) { + WeightFootprint f; + weight_footprint(r->program, &f, TablePlacement::Vram, TablePlacement::Disk); + if (!f.ngram_host) return false; + } + for (auto& r : ranks_) + for (size_t i = 1; i < r->program.weights.size(); ++i) { + if (!is_ngram_table(r->program, (rad_weight)i)) continue; + r->program.weights[i].site = Site::Host; + if (i < r->plan.weight.size()) r->plan.weight[i].site = Site::Host; + } + return true; +} + /* WHERE THE TWO LOOKUP TABLES GO (--embedding-placement, --ngram-placement), decided once for every * rank before the card is split, and written into Config for the planner and the load phase. * @@ -390,12 +431,15 @@ int Engine::lock_table_copy(const uint8_t* src, int64_t n, int64_t foff, void** * lookup writes the activations a card reads, which a host kernel reading the container cannot * reach -- an architecture declares a buffer's domain, and the token embedding's is the device. * - * THE N-GRAM TABLE: only a host kernel reads one today, so Vram is refused and the choice is - * between a locked copy in RAM and the container. Auto takes RAM when lockable_room says the - * memory, the memlock limit and every cgroup allow it after the pools still to be allocated. */ + * THE N-GRAM TABLE: Vram where a device kernel gathers it and the card holds it; Ram as a copy, + * pinned for that kernel to read over the link or locked for the host gather; Disk in the + * container, read by the host gather. Each tier is refused where no kernel reads it there. Auto + * takes the first that holds the table, in that order: the card's test is the embedding's, and + * RAM's is lockable_room's -- the memory and every cgroup after the pools still to be allocated, + * and the memlock limit for a locked copy. */ int Engine::resolve_table_placement(const std::vector& facts, const std::vector& emb_bytes, int64_t kv_floor, - int64_t ngram_bytes, bool ngram_device) { + int64_t ngram_bytes, bool ngram_device, bool ngram_host) { const int64_t MiB = (int64_t)1 << 20; int64_t emb_max = 0; for (int64_t b : emb_bytes) emb_max = std::max(emb_max, b); @@ -445,44 +489,98 @@ int Engine::resolve_table_placement(const std::vector& facts, TablePlacement ng = cfg_.ngram_placement; std::string ng_why; - if (ngram_device) { - if (ng == TablePlacement::Ram || ng == TablePlacement::Disk) { - RAD_ERR("--ngram-placement %s: a device kernel reads this model's n-gram table, so the " - "placement strategy places it with the other weights; only vram or auto apply", - table_placement_name(ng)); - return RAD_E_INVAL; + /* THE FASTEST TIER WITH THE ROOM, the card first: the table on the card, every rank holding + * all of it (a lookup is not sharded), with the fixed weights and a KV pool for one + * --max-model-len sequence beside it, as the embedding's test is; then a copy in RAM -- pinned + * for a device kernel to read over the link, or locked for the host gather; then the + * container, which only the host gather reads. Each is open only where a kernel reads it. */ + const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB + + cfg_.prefix_cache_host_mib * MiB; + const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20); + const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy"; + auto card_holds = [&](std::string* why) { + std::vector with = facts; + int64_t fixed = 0; + for (VramFacts& f : with) { + f.statics += ngram_bytes; + if (emb == TablePlacement::Ram) f.statics -= emb_max; + fixed = std::max(fixed, f.statics); } - ng = TablePlacement::Vram; - ng_why = "a device kernel reads it; placed with the other weights"; - } else if (ngram_bytes == 0) { + /* `fixed` and not the trial's own statics: the split clamps those to what the card can give + * and serves on, streaming every expert, so the trial alone cannot say they do not fit. */ + VramBudget tb; + const int st = vram_budget_trial(cfg_, with, &tb); + const bool over = st == RAD_OK && fixed >= tb.claimable; + if (st == RAD_OK && !over && (!tb.derived_kv || tb.kv >= kv_floor)) return true; + if (st != RAD_OK) + *why = "the card cannot hold the other weights with it"; + else if (over) + *why = fmt("with it the fixed weights want %s of a card that has %s to give", + humanb(fixed).c_str(), humanb(tb.claimable).c_str()); + else + *why = fmt("with it on the card the KV pool is %s, short of the %s one " + "--max-model-len sequence needs", humanb(tb.kv).c_str(), + humanb(kv_floor).c_str()); + return false; + }; + if (ngram_bytes == 0) { if (ng != TablePlacement::Auto) RAD_WARN("--ngram-placement %s: this model has no n-gram table, so there is nothing to " "place", table_placement_name(ng)); ng = TablePlacement::Disk; } else if (ng == TablePlacement::Vram) { - RAD_ERR("--ngram-placement vram: no loaded kernel plugin reads an n-gram table on a card " - "(embed_lookup_q has host kernels only), so it is read from host memory or the " - "container: ram or disk"); - return RAD_E_INVAL; - } else if (ng == TablePlacement::Ram || ng == TablePlacement::Auto) { - const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB + - cfg_.prefix_cache_host_mib * MiB; - const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20); std::string why; - const bool room = lockable_room(need, still, &why); - if (ng == TablePlacement::Ram && !room) { - RAD_ERR("--ngram-placement ram: the n-gram table (%s) cannot be locked in memory: %s", - humanb(ngram_bytes).c_str(), why.c_str()); + if (!ngram_device) { + RAD_ERR("--ngram-placement vram: no loaded kernel plugin reads an n-gram table on a " + "card (embed_lookup_q has host kernels only), so it is read from host memory " + "or the container: ram or disk"); + return RAD_E_INVAL; + } + if (!card_holds(&why)) { + RAD_ERR("--ngram-placement vram: the n-gram table (%s, all of it on every card) does " + "not fit: %s. Use ram, disk or auto.", humanb(ngram_bytes).c_str(), + why.c_str()); return RAD_E_NOMEM; } - if (ng == TablePlacement::Auto) - ng_why = room ? "the memory, the memlock limit and the cgroups allow a locked copy" - : "a locked copy does not fit: " + why; - else - ng_why = "as asked"; - ng = room ? TablePlacement::Ram : TablePlacement::Disk; - } else { ng_why = "as asked"; + } else if (ng == TablePlacement::Disk) { + if (!ngram_host) { + RAD_ERR("--ngram-placement disk: no loaded kernel plugin gathers an n-gram table on " + "the host, which is what reads it from the container. Use vram, ram or auto."); + return RAD_E_INVAL; + } + ng_why = "as asked"; + } 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); + if (ng == TablePlacement::Ram) { + if (!room) { + RAD_ERR("--ngram-placement ram: the n-gram table (%s) cannot be held in memory as " + "%s: %s", humanb(ngram_bytes).c_str(), copy, ram_why.c_str()); + return RAD_E_NOMEM; + } + ng_why = "as asked"; + } else if (card) { + ng = TablePlacement::Vram; + ng_why = "the card holds it beside the other weights and a KV pool for one " + "--max-model-len sequence"; + } else if (room) { + ng = TablePlacement::Ram; + ng_why = fmt("%sthe memory%s and the cgroups allow %s", + ngram_device ? (card_why + "; ").c_str() : "", + ngram_device ? "" : ", the memlock limit", copy); + } else if (ngram_host) { + ng = TablePlacement::Disk; + ng_why = fmt("%s%s does not fit: %s", ngram_device ? (card_why + "; ").c_str() : "", + copy, ram_why.c_str()); + } else { + RAD_ERR("--ngram-placement auto: the n-gram table (%s) has nowhere to go: %s; %s does " + "not fit (%s); and no loaded kernel plugin gathers it on the host, which is " + "what reads it from the container", humanb(ngram_bytes).c_str(), + card_why.c_str(), copy, ram_why.c_str()); + return RAD_E_NOMEM; + } } cfg_.ngram_resolved = ng; @@ -490,7 +588,7 @@ int Engine::resolve_table_placement(const std::vector& facts, RAD_INFO("placement: token embedding (%s a rank) %s%s: %s", humanb(emb_max).c_str(), table_placement_name(emb), cfg_.embedding_placement == TablePlacement::Auto ? " (auto)" : "", emb_why.c_str()); - if (ngram_bytes > 0 || ngram_device) + if (ngram_bytes > 0) RAD_INFO("placement: n-gram table (%s) %s%s: %s", humanb(ngram_bytes).c_str(), table_placement_name(ng), cfg_.ngram_placement == TablePlacement::Auto ? " (auto)" : "", ng_why.c_str()); @@ -967,7 +1065,7 @@ int Engine::plan() { * where they are not (the n-gram table every rank reads from the one mapping). */ std::vector emb_bytes; int64_t ngram_bytes = 0, kv_floor = 0; - bool ngram_device = false; + bool ngram_device = false, ngram_host = false; const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; for (auto& r : ranks_) { RAD_TRY(rad_dev_set(r->device)); @@ -1005,12 +1103,13 @@ int Engine::plan() { * already this card's even share of the static weights: declare ran once per rank * with every dimension divided. */ WeightFootprint wf; - weight_footprint(r->program, &wf, TablePlacement::Vram); + weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk); f.statics = wf.statics; f.experts = wf.experts; emb_bytes.push_back(wf.embedding); 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 same groups planned for a single * sequence, which is the least a KV pool can hold and still serve every request the * API accepts (configure_kv warns below it). --embedding-placement auto keeps the @@ -1068,7 +1167,11 @@ int Engine::plan() { late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy); facts.push_back(f); } - RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device)); + RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device, + ngram_host)); + /* The n-gram table was counted off the card; on it, it is every rank's whole table. */ + if (cfg_.ngram_resolved == TablePlacement::Vram) + for (VramFacts& f : facts) f.statics += ngram_bytes; if (cfg_.embedding_resolved == TablePlacement::Ram) for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i]; VramBudget vb; @@ -2090,28 +2193,42 @@ int Engine::load_weights() { } w.ptr = (void*)file_->data(p0); w.host_ptr = w.ptr; - /* --ngram-placement ram: the host kernel reads the locked copy instead of the - * mapping. A copy auto chose and could not make leaves the table where it was, and - * says so; one the operator asked for refuses the start. */ + /* --ngram-placement ram: the gather reads a copy instead of the mapping -- pinned + * memory a device kernel reads in place over the link, where the planner put the + * table on the zero-copy site, or locked memory for the host gather. A copy auto + * chose and could not make leaves the table in the container and says so, and a + * card's gather moves to the host with it; one the operator asked for refuses the + * start. */ if (cfg_.ngram_resolved == TablePlacement::Ram && is_ngram_table(r->program, (rad_weight)i)) { + const bool card = w.site == Site::DeviceZeroCopy; void* copy = nullptr; std::string why; - const int cs = lock_table_copy((const uint8_t*)w.ptr, n, (int64_t)p0.offset, - ©, &why); + const int cs = copy_table((const uint8_t*)w.ptr, n, (int64_t)p0.offset, card, + ©, &why); if (cs == RAD_OK) { - w.ptr = copy; + void* on_card = card ? rad_dev_device_ptr(copy) : nullptr; + w.ptr = on_card ? on_card : copy; w.host_ptr = copy; r->mover.publish_mapped((rad_weight)i, w.ptr); - continue; /* reported once, by lock_table_copy, and not as mapped */ + continue; /* reported once, by copy_table, and not as mapped */ } + const char* into = card ? "pinned" : "locked"; if (cfg_.ngram_placement == TablePlacement::Ram) { - RAD_ERR("--ngram-placement ram: '%s' could not be copied into locked " - "memory: %s", w.name.c_str(), why.c_str()); + RAD_ERR("--ngram-placement ram: '%s' could not be copied into %s memory: " + "%s", w.name.c_str(), into, why.c_str()); return cs; } - RAD_WARN("--ngram-placement auto: '%s' could not be copied into locked memory " - "(%s); it is read from the container", w.name.c_str(), why.c_str()); + if (card && !ngram_gather_to_host()) { + RAD_ERR("--ngram-placement auto: '%s' could not be copied into pinned " + "memory (%s), and no loaded kernel plugin gathers it on the host, " + "which is what reads it from the container", w.name.c_str(), + why.c_str()); + return cs; + } + RAD_WARN("--ngram-placement auto: '%s' could not be copied into %s memory " + "(%s); it is read from the container%s", w.name.c_str(), into, + why.c_str(), card ? " by the host gather" : ""); cfg_.ngram_resolved = TablePlacement::Disk; } /* NO READAHEAD ON A MAPPED WEIGHT. What reads one is a host kernel gathering rows diff --git a/core/format/table_copy.cpp b/core/format/table_copy.cpp index 29e20e66..6834f077 100644 --- a/core/format/table_copy.cpp +++ b/core/format/table_copy.cpp @@ -14,6 +14,49 @@ namespace rad { +int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff, + uint8_t* buf, std::string* why) { + if (!why || !src || !buf || n <= 0) return RAD_E_INVAL; + const int64_t huge = (int64_t)2 << 20; + + /* A reader per hardware thread up to sixteen, each reading its own contiguous span in pieces of + * 64 MiB: a drive serves sixteen queued reads at full rate, and the span keeps each reader's + * reads sequential on the file. */ + const int nt = (int)std::max(1u, std::min(16u, std::thread::hardware_concurrency())); + const int64_t piece = (int64_t)64 << 20; + const int64_t span = ((n + nt - 1) / nt + huge - 1) & ~(huge - 1); + std::atomic err{RAD_OK}; + std::vector rd; + for (int i = 0; i < nt; ++i) { + const int64_t lo = (int64_t)i * span, hi = std::min(n, lo + span); + if (lo >= hi) break; + rd.emplace_back([&, lo, hi] { + for (int64_t o = lo; o < hi && err.load() == RAD_OK; o += piece) { + const int64_t b = std::min(piece, hi - o); + const int rc = file.read_at(buf + o, b, foff + o); + if (rc < 0) { err.store(rc); return; } + file.drop_range(foff + o, b); + } + }); + } + for (std::thread& t : rd) t.join(); + + if (err.load() != RAD_OK) { + *why = fmt("reading the container failed (%s)", rad_strerror(err.load())); + return RAD_E_IO; + } + const int64_t probe = std::min(n, 4096); + bool same = std::memcmp(buf, src, (size_t)probe) == 0 && + std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0; + for (int64_t o = 0; same && o + 4096 <= n; o += std::max(n / 64, 4096)) + same = std::memcmp(buf + o, src + o, 4096) == 0; + if (!same) { + *why = "the copy does not match the container's mapping"; + return RAD_E_IO; + } + return RAD_OK; +} + int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff, TableCopy* out, std::string* why) { if (!out || !why || !src || n <= 0) return RAD_E_INVAL; @@ -32,45 +75,11 @@ int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t ::munmap(m, sz); return RAD_E_NOMEM; } - uint8_t* buf = static_cast(m); - - /* A reader per hardware thread up to sixteen, each reading its own contiguous span in pieces of - * 64 MiB: a drive serves sixteen queued reads at full rate, and the span keeps each reader's - * reads sequential on the file. */ - const int nt = (int)std::max(1u, std::min(16u, std::thread::hardware_concurrency())); - const int64_t piece = (int64_t)64 << 20; - const int64_t span = ((n + nt - 1) / nt + (int64_t)huge - 1) & ~((int64_t)huge - 1); - std::atomic err{RAD_OK}; - std::vector rd; - for (int i = 0; i < nt; ++i) { - const int64_t lo = (int64_t)i * span, hi = std::min(n, lo + span); - if (lo >= hi) break; - rd.emplace_back([&, lo, hi] { - for (int64_t o = lo; o < hi && err.load() == RAD_OK; o += piece) { - const int64_t b = std::min(piece, hi - o); - const int rc = file.read_at(buf + o, b, foff + o); - if (rc < 0) { err.store(rc); return; } - file.drop_range(foff + o, b); - } - }); - } - for (std::thread& t : rd) t.join(); - - bool same = err.load() == RAD_OK; - if (same) { - const int64_t probe = std::min(n, 4096); - same = std::memcmp(buf, src, (size_t)probe) == 0 && - std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0; - for (int64_t o = 0; same && o + 4096 <= n; o += std::max(n / 64, 4096)) - same = std::memcmp(buf + o, src + o, 4096) == 0; - if (!same) *why = "the copy does not match the container's mapping"; - } else { - *why = fmt("reading the container failed (%s)", rad_strerror(err.load())); - } - if (!same) { + const int rc = table_copy_fill(file, src, n, foff, static_cast(m), why); + if (rc != RAD_OK) { ::munlock(m, sz); ::munmap(m, sz); - return RAD_E_IO; + return rc; } out->base = m; out->bytes = sz; diff --git a/core/format/table_copy.h b/core/format/table_copy.h index 2d2e2354..68f8e345 100644 --- a/core/format/table_copy.h +++ b/core/format/table_copy.h @@ -1,4 +1,6 @@ -/* table_copy.h -- a container table copied into locked host memory (--ngram-placement ram). +/* table_copy.h -- a container table copied into host memory (--ngram-placement ram): locked memory + * for the host gather, made here, or pinned memory a card reads, which the caller allocates and + * table_copy_fill fills. What follows is about the locked copy; the read and the check are both's. * * A COPY IN HUGE PAGES, NOT THE MAPPING LOCKED. Faulting a container's mapping in costs a fault every * 4 KiB page and leaves every row behind a 4 KiB translation, so a gather of scattered rows walks @@ -28,6 +30,11 @@ struct TableCopy { int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff, TableCopy* out, std::string* why); +/* The read and the check table_copy_make makes, into [dst, dst + n) the caller allocated: pinned + * memory a card reads in place, when a device kernel gathers the table (--ngram-placement ram). */ +int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff, + uint8_t* dst, std::string* why); + /* Unlocks and unmaps it; a copy never made is a no-op. */ void table_copy_free(TableCopy* c); diff --git a/core/place/planner.cpp b/core/place/planner.cpp index 3c005b99..18735ec3 100644 --- a/core/place/planner.cpp +++ b/core/place/planner.cpp @@ -101,25 +101,31 @@ int64_t weight_bytes(const WeightInfo& w) { /* See planner.h. Planner::resolve_sites, Planner::build_units and Planner::pin_mapped, run over * the same program without allocating a Plan -- the budget resolver calls this before a Planner * exists. Kept adjacent to the three so a change to any of them has this in the same diff. */ -void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding) { +void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding, + TablePlacement ngram) { if (!out) return; *out = WeightFootprint{}; /* resolve_sites: a weight every one of whose ops lacks a device band cannot be read on the * card, so it is never copied there whatever the budgets say. */ - std::vector device_ok(prog.weights.size(), 1u); + std::vector device_ok(prog.weights.size(), 1u), host_ok(prog.weights.size(), 1u); for (const OpInfo& o : prog.ops) { - bool dev = !o.bands.empty(); - for (const Band& b : o.bands) if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false; - if (dev) continue; - for (rad_weight w : o.weights) - if (w != RAD_NULL_HANDLE && w < device_ok.size()) device_ok[w] = 0u; + bool dev = !o.bands.empty(), host = !o.bands.empty(); + for (const Band& b : o.bands) { + if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false; + if (!b.dom[RAD_DOMAIN_HOST]) host = false; + } + for (rad_weight w : o.weights) { + if (w == RAD_NULL_HANDLE || w >= device_ok.size()) continue; + if (!dev) device_ok[w] = 0u; + if (!host) host_ok[w] = 0u; + } } /* build_units: a model-level weight is its own unit, everything else groups by the declared * (layer, expert). Ordered, for the same reason build_units is. */ struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false; - bool emb = false, ngram = false; }; + bool emb = false, ngram = false, host = true; }; std::map, size_t> by_group; std::vector units; @@ -148,6 +154,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi); /* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */ if (w < device_ok.size() && !device_ok[w]) mu.mapped = true; + if (w < host_ok.size() && !host_ok[w]) mu.host = false; /* The placement flags' tables: model-level, so the unit is this one weight. */ if (layer < 0) { mu.emb = is_embedding_table(prog, w); @@ -159,19 +166,24 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement * align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw * bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */ std::map layer_experts; + bool ngram_host = true; + for (const U& mu : units) if (mu.ngram && !mu.host) ngram_host = false; for (const U& mu : units) { const int64_t b = align_up(mu.bytes, RAD_ALIGN_UNIT); /* pin_embedding moves a table out of the statics only where nothing has mapped it. */ if (mu.emb && !mu.mapped) out->embedding += b; - if (mu.ngram && mu.mapped) out->ngram += b; + if (mu.ngram) out->ngram += b; if (mu.ngram && !mu.mapped) out->ngram_device = true; - if (mu.mapped) out->mapped += b; + /* pin_mapped: an n-gram table a device kernel reads stays off the card unless it was + * placed in VRAM. */ + if (mu.mapped || (mu.ngram && ngram != TablePlacement::Vram)) out->mapped += b; else if (mu.emb && embedding == TablePlacement::Ram) out->hosted += b; else if (mu.expert >= 0) { out->experts += b; layer_experts[mu.layer] += b; } else out->statics += b; } for (const auto& le : layer_experts) out->expert_layer_max = std::max(out->expert_layer_max, le.second); + out->ngram_host = out->ngram > 0 && ngram_host; out->n_units = (int64_t)units.size(); } std::string weight_class_key(const std::string& name) { @@ -206,9 +218,8 @@ std::string weight_class_key(const std::string& name) { * * Tracking host alone would rest on the argument that a missing device kernel is fatal at declare * and never reaches the planner. That is true only of an op with NO kernel in either domain: an op - * such as `embed_lookup_q` resolves on the host and nowhere else -- deliberately, because its - * table is far too large for the card and must not be copied there -- and declare reports that - * device band as unserved without refusing the model. */ + * such as `embed_lookup_q` resolves on the host and nowhere else when no device kernel for it is + * loaded, and declare reports that device band as unserved without refusing the model. */ void Planner::resolve_sites(const Program& prog) { host_ok_.assign(prog.weights.size(), 1u); device_ok_.assign(prog.weights.size(), 1u); @@ -237,54 +248,75 @@ void Planner::resolve_sites(const Program& prog) { /* ------------------------------------------------------------------ the mapped tier */ /* A weight no device kernel can read is pinned to the container's mapping BEFORE any budget is - * consulted, because it is not a budget question. The other three off-device tiers are what the - * planner falls back to when VRAM runs out; this one is where the weight has to be whatever the - * budgets say, and charging a pool for bytes that are never copied would make the operator size a - * pool against a number that does not exist. + * consulted, because it is not a budget question -- and so is an n-gram table --ngram-placement put + * in RAM or on disk, whatever kernels could read it on a card. The other three off-device tiers are + * what the planner falls back to when VRAM runs out; this one is where the weight has to be + * whatever the budgets say, and charging a pool for bytes that are never copied would make the + * operator size a pool against a number that does not exist. * - * THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped - * one has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY - * weight operand of a host-only op, so the unit's other members are the same op's scale and - * constants. What this does exclude is a plugin that groups a host-only weight with a device one: - * that collapses the whole group onto the host, so the report names it. */ + * THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped one + * has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY weight + * operand of a host-only op, so the unit's other members are the same op's scale and constants. + * What this does exclude is a plugin that groups a host-only weight with a device one: that + * collapses the whole group onto the host, so the report names it. */ void Planner::pin_mapped(const Program& prog, Plan* p) { + const TablePlacement ng = in_.config->ngram_resolved; for (MoveUnit& mu : p->units) { - bool mapped = false; + bool host_only = false; for (rad_weight w : mu.weights) - if (w < device_ok_.size() && !device_ok_[w]) mapped = true; - if (!mapped) continue; + if (w < device_ok_.size() && !device_ok_[w]) host_only = true; + /* --ngram-placement keeps an n-gram table OFF THE CARD unless it says vram, whether or not + * a device kernel could read it there: ram and disk are where the operator put it, and the + * strategies below would otherwise spend the card on 48 GB of rows read sixteen a token. */ + const bool ngram = mu.layer < 0 && !mu.weights.empty() && + is_ngram_table(prog, mu.weights.front()); + if (!host_only && !(ngram && ng != TablePlacement::Vram)) continue; mu.tier = Tier::Mapped; - mu.site = Site::Host; mu.movable = false; - mu.reason = "no device kernel for its op; read from the container's mapping"; - /* --ngram-placement ram: the load phase copies an n-gram table out of the mapping into - * locked memory and publishes the copy, so the host kernel reads RAM instead of the file. - * Every pool still sees the mapped tier; the report shows what the copy costs. */ - if (in_.config->ngram_resolved == TablePlacement::Ram && mu.layer < 0 && - !mu.weights.empty() && is_ngram_table(prog, mu.weights.front())) { - mu.reason = "--ngram-placement ram: a locked copy in RAM, made at load"; + if (host_only) { + mu.site = Site::Host; + mu.reason = "no device kernel for its op; read from the container's mapping"; + } else if (ng == TablePlacement::Ram) { + mu.site = Site::DeviceZeroCopy; + mu.reason = "--ngram-placement ram: a pinned copy in RAM the card reads in place, made " + "at load"; + } else { + mu.site = Site::Host; + mu.reason = "--ngram-placement disk: the host gather reads it from the container"; + for (rad_weight w : mu.weights) + if (w < host_ok_.size() && !host_ok_[w]) + note_unfit(p, mu, "--ngram-placement disk needs a host kernel for its gather, " + "and none was loaded"); + } + /* --ngram-placement ram: the load phase copies an n-gram table out of the mapping and + * publishes the copy -- locked memory the host kernel reads, or pinned memory the card + * reads where a device kernel gathers. Every pool still sees the mapped tier; the report + * shows what the copy costs. */ + if (ngram && ng == TablePlacement::Ram) { + if (host_only) mu.reason = "--ngram-placement ram: a locked copy in RAM, made at load"; + else p->ngram_copy_card = true; p->ngram_copy_bytes += mu.bytes; } - /* AND ONLY WHAT LIES IN THE CONTAINER AS THE KERNEL READS IT can be read from the mapping: - * a weight its kernel rearranges at load, or a shard of one, has no place in the file - * that already looks the way the kernel reads it (spec §5.1). */ + /* AND ONLY WHAT LIES IN THE CONTAINER AS THE KERNEL READS IT can be read from the mapping, + * or copied out of it: a weight its kernel rearranges at load, or a shard of one, has no + * place in the file that already looks the way the kernel reads it (spec §5.1). */ if (!in_.container) - note_unfit(p, mu, "only a host kernel reads it, so it must be read from a " - "container's mapping -- and a checkpoint served directly has " - "none; convert it to a container"); + note_unfit(p, mu, "it is read from a container's mapping or copied out of one -- and " + "a checkpoint served directly has none; convert it to a container"); else for (rad_weight w : mu.weights) if (w < prog.weights.size() && !weight_file_direct(prog.weights[w], prog.ctx.world_size)) - note_unfit(p, mu, "only a host kernel reads it, so it must be read from the " - "container's mapping -- and its stored form is not the " - "container's (a relayout, a widening or a shard)"); - for (rad_weight w : mu.weights) - if (w < device_ok_.size() && device_ok_[w]) - RAD_WARN("placement: '%s' is grouped with a weight only a host kernel can read, " - "so the whole group stays in the container's mapping", - prog.weights[w].name.c_str()); + note_unfit(p, mu, "it is read from the container's mapping or copied out of " + "it -- and its stored form is not the container's (a " + "relayout, a widening or a shard)"); + if (host_only) + for (rad_weight w : mu.weights) + if (w < device_ok_.size() && device_ok_[w]) + RAD_WARN("placement: '%s' is grouped with a weight only a host kernel can " + "read, so the whole group stays in the container's mapping", + prog.weights[w].name.c_str()); } } @@ -1270,8 +1302,9 @@ std::string Plan::report(const Program& prog) const { s += fmt(" embedding %12s %12s (--embedding-placement ram, pinned, read in place)\n", "-", humanb(embedding_host_bytes).c_str()); if (ngram_copy_bytes) - s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, locked RAM, filled at load)\n", - "-", humanb(ngram_copy_bytes).c_str()); + s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, %s, filled at load)\n", + "-", humanb(ngram_copy_bytes).c_str(), + ngram_copy_card ? "pinned RAM the card reads" : "locked RAM"); /* Out of the VRAM weight budget, beside the residents and not among them: the two buffers a * routed layer's file-tier experts are read into, each sized to the layer that puts the most * there. */ diff --git a/core/place/planner.h b/core/place/planner.h index eef2971c..394fcc87 100644 --- a/core/place/planner.h +++ b/core/place/planner.h @@ -249,9 +249,12 @@ public: * `embedding_host_used` is the same tables' weight bytes, the unit the tier totals count in. */ int64_t embedding_host_bytes = 0; int64_t embedding_host_used = 0; - /* --ngram-placement ram: the n-gram tables the load phase copies into locked memory. They stay - * on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM. */ + /* --ngram-placement ram: the n-gram tables the load phase copies into host memory. They stay + * on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM. + * `ngram_copy_card` says which copy: pinned memory a device kernel reads in place over the + * link, or locked memory the host gather reads. */ int64_t ngram_copy_bytes = 0; + bool ngram_copy_card = false; /* ROUTED EXPERTS ON THE FILE TIER have no address of their own: a routed layer's are read into * one of two VRAM buffers before the layer's first expert op and published there until the next * routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's @@ -377,17 +380,23 @@ struct WeightFootprint { int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */ int64_t hosted = 0; /* --embedding-placement ram: in the pinned host pool, off the card */ /* The tables the two placement flags move, wherever the buckets above count them: `embedding` - * is inside statics or hosted, `ngram` inside mapped. */ + * is inside statics or hosted, `ngram` inside statics when a device kernel reads it and it is + * placed in VRAM, inside mapped otherwise. */ int64_t embedding = 0; int64_t ngram = 0; - /* An n-gram table some device kernel reads, which the strategies place like any weight. No - * plugin has one today; it is what makes --ngram-placement vram mean something. */ + /* A device kernel reads the n-gram table, so it can be on the card or read over the link from + * pinned host memory; without one only the host gather reads it, from RAM or the container. */ bool ngram_device = false; + /* A host kernel gathers it, so it can stay in the container (--ngram-placement disk). */ + bool ngram_host = false; int64_t n_units = 0; }; /* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the - * statics. Stated by every caller, so the budget and the planner cannot count it differently. */ -void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding); + * statics. `ngram` is the n-gram table's; only Vram puts it among them, and only where a device + * kernel reads it. Stated by every caller, so the budget and the planner cannot count it + * differently. */ +void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding, + TablePlacement ngram); /* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight * that at least one op reads and that only `embed_lookup` reads is a token embedding table, and diff --git a/core/rad_core.h b/core/rad_core.h index 8fc84e3f..2fc73725 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -109,9 +109,11 @@ struct Band { * beside the mapping that already holds one. A sparse Zipfian gather of a dozen rows out of * hundreds of millions is exactly what a page cache is good at. * - * Only a HOST kernel can read one -- the bytes are pageable and at no device address -- so the - * planner assigns this tier where, and only where, no device kernel for the op exists at all - * (embed_lookup_q, libavx/avx_ngram.cpp, is the one such op in this tree). */ + * Only a HOST kernel can read the mapping -- the bytes are pageable and at no device address -- so + * the planner assigns this tier where no device kernel for the op exists at all, and where + * --ngram-placement keeps an n-gram table off the card (embed_lookup_q, libavx/avx_ngram.cpp). + * Under `ram` the load phase publishes a copy in place of the mapping: locked memory for the host + * gather, or pinned memory a device kernel reads over the link (the zero-copy site). */ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped = 4 }; /* WHERE A LOOKUP TABLE LIVES: the token embedding (--embedding-placement) and an n-gram embedding diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 079fcb4e..23489e9a 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -890,11 +890,11 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { * is the one place it stops being harmless: it runs NOW, on this thread, and reads and writes * the host arena NOW. * - * A PLE gather is exactly that shape. `ngram_ids` writes the hashed row ids into a host-domain - * buffer on the device, and `embed_lookup_q` reads them on the host. With no join the host - * reads whatever the arena holds from an earlier step and gathers the rows of the wrong - * n-gram -- valid ids, valid rows, every kernel agreeing with its oracle, and fluent text that - * is a stable wrong answer rather than an intermittent one. + * A PLE gather on the host is exactly that shape. `ngram_ids` writes the hashed row ids into a + * host-domain buffer on the device, and `embed_lookup_q` reads them on the host. With no join + * the host reads whatever the arena holds from an earlier step and gathers the rows of the + * wrong n-gram -- valid ids, valid rows, every kernel agreeing with its oracle, and fluent text + * that is a stable wrong answer rather than an intermittent one. * * WHAT THE JOIN WAITS FOR is the last device op on each lane that touched the host arena * (host_touch_ev_), not the whole stream. Every hazard a host op has is with such an op -- the diff --git a/docs/DOCKER.md b/docs/DOCKER.md index bfbeb558..18e1bf48 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -88,10 +88,11 @@ Every one of these options is needed: without this the model cannot serve. The profile also refuses the NUMA binding calls the ROCm runtime makes for host memory. - **`--init`**: the engine is not PID 1. It finishes its step and releases the cards on SIGTERM. -- **`--ulimit memlock=-1`**: `--ngram-placement ram` locks a copy of the n-gram table in RAM - (47.7 GiB for Qwen3.8-Flash-Next), far past Docker's default memlock limit. Without it `auto` - reads the table from the container and `ram` refuses the start. `deploy/compose/common.yaml` - sets it. +- **`--ulimit memlock=-1`**: where no device kernel gathers the n-gram table (a run on the host + backend), `--ngram-placement ram` locks a copy of it in RAM -- 47.7 GiB for + Qwen3.8-Flash-Next, far past Docker's default memlock limit -- and without the limit raised + `auto` reads it from the container and `ram` refuses the start. On the cards the copy is pinned + memory the cards read, which the limit does not count. `deploy/compose/common.yaml` sets it. - **`--network host`**: the server binds the host's addresses directly, IPv4 and IPv6, with no NAT in front of it. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 66ed5344..e12da06a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -469,7 +469,7 @@ Related flags: --kv-cache-dtype fp8 # halve what a token of context costs (a real quantisation) --host-pool-mib 8192 # pinned host tier for weights --embedding-placement ram # the token embedding off the card (below) ---ngram-placement ram # an n-gram table in locked RAM instead of read from disk (below) +--ngram-placement ram # an n-gram table in RAM instead of read from disk (below) --weights-disk-tier # stream what fits neither from the container; needs O_DIRECT ``` @@ -479,7 +479,7 @@ never the whole table, so a tier below the card serves them at little or no cost | | `vram` | `ram` | `disk` | |---|---|---|---| | `--embedding-placement` | on the card, with the other weights | the pinned host pool, read over the link in place | refused | -| `--ngram-placement` | refused | a locked copy in RAM, made at load | read from the container through a row cache | +| `--ngram-placement` | on the card, every card holding all of it | a copy in RAM made at load, read by the card over the link | read from the container through a row cache | Both default to `auto`, the fastest tier that has room once every other weight is placed. Startup prints what each resolved to and why. A tier the flag names that cannot be honoured stops the @@ -499,15 +499,19 @@ writes activations the card reads, and a host kernel reading the container canno radiance --model m.rad --tp 2 --host-pool-mib 1280 --embedding-placement ram ``` -**An n-gram table** (Qwen3.8-Flash-Next's is 47.7 GiB) is read by a host kernel only, so it is never -on the card. `disk` reads its rows from the container through a row cache and direct reads; about -half of a step's rows are first-seen, so steps wait on the drive. `ram` copies the whole table into -locked huge pages at load -- 12 to 40 s more startup, depending on the page cache -- and every gather -reads memory. It needs the table's size in memory after the pinned host pools and the prefix -cache's host tier, with 4 GiB to spare, a memlock limit that large (`--ulimit memlock=-1` in Docker, -`LimitMEMLOCK=infinity` under systemd), and room under every memory cgroup the process sits in. -`ram` short of any of them refuses the start and names which; `auto` takes `ram` when all of them -allow it and `disk` otherwise. +**An n-gram table** (Qwen3.8-Flash-Next's is 47.7 GiB) is read a few rows a token, which is why it +can live off the card at all. `disk` reads its rows from the container through a row cache and +direct reads on the host; about half of a step's rows are first-seen, so steps wait on the drive. +`ram` copies the whole table into host memory at load -- 12 to 40 s more startup, depending on the +page cache -- and every gather reads memory: the card's own gather kernel reads a pinned copy over +the link, so a step has no host work in it at all. `vram` puts it on the card, every card holding +all of it, which needs a card that large. `ram` needs the table's size in memory after the pinned +host pools and the prefix cache's host tier, with 4 GiB to spare, and room under every memory cgroup +the process sits in; it refuses the start short of either and names which. `auto` takes the first +of `vram`, `ram` and `disk` that holds the table. Without a device kernel for the gather (a build +with 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). **A model larger than the card and the host pool together still serves with `--weights-disk-tier`** -- and every step is then paced by the drive, which is the trade the flag @@ -893,7 +897,7 @@ one line naming each one the command line moved. | `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` | | `--host-pool-mib N` | 0 | pinned host tier (weights) | | `--embedding-placement WHERE` | auto | `auto`, `vram` or `ram`: the token embedding on the card or in the pinned host pool, read in place; `disk` is refused. See §4.3 | -| `--ngram-placement WHERE` | auto | `auto`, `ram` or `disk`: an n-gram table as a locked copy in RAM made at load, or read from the container; `vram` is refused. See §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. See §4.3 | | `--weights-disk-tier` | off | read weights that fit neither VRAM nor the host pool from the container (O_DIRECT); routed experts a layer at a time | **Idle session tiers** diff --git a/docs/OPS.md b/docs/OPS.md index 0aeed4bf..98ca3581 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -868,11 +868,12 @@ holds only where the rank holds the WHOLE vocabulary -- `world_size` 1, not mere on most steps, so a check keyed on the offset alone refuses correct calls. Bounding ids is the caller's, and the tokeniser and the sampler both already are. -### `embed_lookup_q`, the host gather +### `embed_lookup_q`, the n-gram gather **A gather from a table quantised with ONE scale for all of it**: `x[m] = wte[id] * scale[0]`. Padding and bounds behave exactly as `embed_lookup`'s — a negative id writes a zero row, an id past -the table fails the launch. +the table fails the launch in the host kernels and writes a zero row in the device one, which +cannot read its ids before it runs (libr4d's divergence note). **Why one scale is enough**, measured on the bf16 original: E4M3 carries its own exponent, a row's dynamic range in this table is only 2.3×, and the scale sits on a **three-octave plateau** where @@ -886,21 +887,38 @@ different kernels. It is `gemm_nt_q`'s argument against being a `dtype` on `gemm scale to `embed_lookup` as an optional operand would also have moved `x` from slot 2 to slot 3 for every caller in the tree. -**It runs on the HOST, served by libavx; no device library has a row for it.** The table it -gathers from is 51.2 GB and cannot go anywhere else: staging a whole movement unit to use 5 KB is -the wrong shape, pinning it for zero-copy needs all 51.2 GB pinned in host RAM, and -`hipHostRegister` on the container's mapping would force all of it resident. The container is -mmapped, so the table is at a host address on open. libavx keeps the rows a gather -has touched in a row cache of its own and reads a miss straight from the file with O_DIRECT -(`libavx/avx_ngram.cpp`): the page cache would map a 4 KiB page per 160-byte row. The reads keep -the alignment the filesystem reports for direct I/O, or its block size where it reports none, as -btrfs does; one read of the table proves it before the first row is served. A filesystem with no -direct I/O at all cannot hold a container with this table. +**Where it runs is where `--ngram-placement` puts the table**, because the planner runs an op on +the host when **every weight operand of it** is `Site::Host` and takes that from the table's +placement. The table is 51.2 GB and is never staged a unit at a time — moving a whole unit to use +5 KB is the wrong shape — so it is read where it lies: -The placement planner runs an op on the host when **every weight operand of it** is `Site::Host`, -which is why the table must be a weight operand at all: `gather_rows` takes a plain `IN` operand and -would never trigger it. And the host kernel has to live in a production plugin — libavx, the host -kernel library — because `rad_gate_reference_kernels` refuses to serve on libref by design. +| placement | the table | the gather | +|---|---|---| +| `disk` | the container's mapping | libavx's host kernel | +| `ram`, libr4d loaded | a pinned copy every card maps at its host address | libr4d's device kernel, over the link | +| `ram`, no device kernel | a locked copy (`core/format/table_copy.h`) | libavx's host kernel | +| `vram` | the card, every rank holding all of it | libr4d's device kernel | + +`hipHostRegister` on the container's mapping is not one of them: it would force all of the file +resident. + +**The host gather keeps its own row cache.** The container is mmapped, so the table is at a host +address on open. libavx keeps the rows a gather has touched in a row cache of its own and reads a +miss straight from the file with O_DIRECT (`libavx/avx_ngram.cpp`): the page cache would map a +4 KiB page per 160-byte row. The reads keep the alignment the filesystem reports for direct I/O, or +its block size where it reports none, as btrfs does; one read of the table proves it before the +first row is served. A filesystem with no direct I/O at all cannot hold a container with this table +on `disk`. + +**The device gather is libr4d's `embed_lookup_q_bf16`**: four entries a thread, each E4M3 code +decoded exactly, multiplied by the scale in f32 and rounded to nearest even — the value libavx's +lookup table holds, to the bit. It reads the ids and writes `e` in the host arena, where the +architecture declares them for the host gather, so the step has no host op left in it. + +The table has to be a weight operand at all for the host site to be reachable: `gather_rows` takes +a plain `IN` operand and would never be placed there. And the host kernel has to live in a +production plugin — libavx, the host kernel library — because `rad_gate_reference_kernels` +refuses to serve on libref by design. ### `ngram_ids`, and the gather that is not an op @@ -937,8 +955,9 @@ derives the read cursor for it. operand of it is `Site::Host`, and `gather_rows` takes a plain `IN` operand. **`ahead_ids` and `ahead`: the next chunk's rows, a step early.** A prefill chunk gathers `heads` -rows a token and, on text the row cache has not seen, most of them are random reads of the -container file — ~30 ms a 2048-token chunk on an NVMe, with the card idle behind the host-site op. +rows a token and, with the table on `disk` and text the row cache has not seen, most of them are +random reads of the container file — ~30 ms a 2048-token chunk on an NVMe, with the card idle behind +the host-site op. The next chunk of the prompt is already known (`RadBatch::n_ahead`, which stores it in `token_ids` after the step's own tokens), so: diff --git a/libavx/README.md b/libavx/README.md index 79f2d4f6..fc3b5562 100644 --- a/libavx/README.md +++ b/libavx/README.md @@ -19,16 +19,18 @@ embedding's gather, every step — needs this plugin. ## The embedding gather -`embed_lookup_q` over an E4M3 table into bf16 is the one host op a GPU deployment runs: the -n-gram table is tens of gigabytes in the container's mapping and never on a card. Its rows come -through `avx_ngram.cpp`, compiled baseline so the process has one of each: a row cache shared by -every thread (2^19 rows, eight ways, CLOCK), an O_DIRECT read through io_uring for each miss, the -ranks dividing a call's misses rather than duplicating them, and a reader thread that fetches the -next prefill chunk's rows while the current one runs. The level's kernel decodes the rows: at -AVX-512 the call's 256-entry bf16 table sits in eight registers and four `vpermt2w` look up 32 -codes; below it, one code at a time. The row's layout hook only checks the table's encoding — -E4M3 with one bf16 scale, or the checkpoint's plain bf16 — and asks for no re-layout, because the -gather reads the rows from the container file in the layout they are stored in. +`embed_lookup_q` over an E4M3 table into bf16 is the one host op a GPU deployment runs, wherever +`--ngram-placement` leaves the n-gram table for the host gather: in the container's mapping +(`disk`), or in a locked copy in RAM when no device kernel for the op is loaded (`ram`). Where +libr4d is loaded, `ram` is a pinned copy its kernel reads over the link and this one does not run. +Its rows come through `avx_ngram.cpp`, compiled baseline so the process has one of each: a row +cache shared by every thread (2^19 rows, eight ways, CLOCK), an O_DIRECT read through io_uring for +each miss, the ranks dividing a call's misses rather than duplicating them, and a reader thread +that fetches the next prefill chunk's rows while the current one runs. The level's kernel decodes +the rows: at AVX-512 the call's 256-entry bf16 table sits in eight registers and four `vpermt2w` +look up 32 codes; below it, one code at a time. The row's layout hook only checks the table's +encoding — E4M3 with one bf16 scale, or the checkpoint's plain bf16 — and asks for no re-layout, +because the gather reads the rows from the container file in the layout they are stored in. `rad-avx-check` runs the op over a file-backed table with two ranks and the reader racing, at every level, and compares every row with the file's bytes. diff --git a/libr4d/r4d_fp8_layout.cpp b/libr4d/r4d_fp8_layout.cpp index ddc4a5d6..68534e75 100644 --- a/libr4d/r4d_fp8_layout.cpp +++ b/libr4d/r4d_fp8_layout.cpp @@ -539,3 +539,36 @@ extern "C" int r4d_rad_unrelayout_mtp_e4m3(const RadParam* p, int n_p, int opera if (rc == RAD_OK) rc = hcrows_enc_layout(g, "r4d.mtp.e4m3.g128", enc, sel, pl, n, &L); return rc != RAD_OK ? rc : hcrows_unrelayout(g, src, src_bytes, pl); } + +/* ================================================================= embed_lookup_q's table + * + * The gather reads the table AS IT IS, so this hook only answers whether it can: E4M3 codes with + * ONE bf16 scale for the whole table (`fp8_e4m3*bf16[*x*]`, the n-gram table's recipe), or the + * table as the checkpoint ships it, plain bf16 with no scale. The same two forms libavx's host + * gather accepts (avx_layout_ngram), checked the same way, so a model whose table one of them + * reads is never refused by the other at declare. */ +extern "C" int r4d_rad_layout_embed_q(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) { + (void)out; + enum { EQ_WTE = 1, EQ_SCALE = 2 }; + if (operand != EQ_WTE && operand != EQ_SCALE) return RAD_E_UNSUPPORTED; + const long long rows = rad_param_geti(p, n_p, "n_vocab", 0); + const long long dim = rad_param_geti(p, n_p, "n_embd", 0); + if (rows <= 0 || dim <= 0) return RAD_E_SHAPE; + if (rad_enc_is(enc, "plain") && enc->n_planes == 1 && enc->plane[0].dtype == RAD_BF16) { + if (operand != EQ_WTE) return RAD_E_DTYPE; + if (n != 1 || !pl || !r4d_enc::dims(pl[0], rows, dim)) return RAD_E_SHAPE; + return RAD_E_UNSUPPORTED; + } + 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 || sc->block[0] != 0 || + sc->block[1] != 0) + return RAD_E_DTYPE; + if (n != 1 || !pl || !sel) return RAD_E_SHAPE; + if (!r4d_enc::selects(enc, sel, n, operand == EQ_WTE ? "codes" : "scale")) return RAD_E_SHAPE; + if (!r4d_enc::dims(pl[0], operand == EQ_WTE ? rows : 1, operand == EQ_WTE ? dim : 1)) + return RAD_E_SHAPE; + return RAD_E_UNSUPPORTED; +} diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 67c35973..6fbdae0f 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -113,6 +113,63 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_kernel( for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = src[i]; } +// ---------------------------------------------------------------------------- embed_lookup_q +// ref_embed_lookup_q. x[m] = bf16(wte[id] * scale), from a table stored as E4M3 codes with ONE +// scale (Q) or as plain bf16, where an absent scale is one. This is the n-gram table's gather +// (arch/common/rad_block_ple.h) wherever --ngram-placement lets a card read the table: in VRAM, or +// in pinned host memory the card reads in place over the link. +// +// A THREAD A QUAD OF ENTRIES, NOT A BLOCK A ROW. A row of the n-gram table is 160 entries, so a +// block a row leaves most of its threads idle and the grid is as deep as the chunk's row count. +// Flattened, consecutive threads take consecutive quads, and a row's 40 threads read its 160 +// contiguous bytes. V = 1 is the same walk an entry at a time, for a width or a pitch the quad's +// 4- and 8-byte accesses would misalign. +// +// THE VALUE libavx's LOOKUP TABLE HOLDS, to the bit: a code decodes to f32 exactly +// (v_cvt_pk_f32_fp8, or the software form beside it in r4d_fp8_wmma.h), the product with the +// scale rounds once in f32, and f32_to_bf16 rounds to nearest even. An id outside [0, n_vocab) +// after the offset writes a zero row (the divergence note at the top of this file). +template +__global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel( + const int32_t* __restrict__ tok, const void* __restrict__ wte, const void* __restrict__ sc, + uint32_t sc_f32, uint16_t* __restrict__ x, uint32_t M, uint32_t n_embd, int32_t n_vocab, + int32_t vocab_off, uint32_t x_ld) { + const uint32_t per_row = n_embd / V; + const uint64_t g = (uint64_t)blockIdx.x * kThreads + threadIdx.x; + if (g >= (uint64_t)M * per_row) return; + const uint32_t m = (uint32_t)(g / per_row), j = (uint32_t)(g % per_row) * V; + const int32_t id = tok[m] - vocab_off; + uint16_t* __restrict__ dst = x + (size_t)m * x_ld + j; + if (id < 0 || id >= n_vocab) { + if constexpr (V == 4) *(uint2*)dst = make_uint2(0u, 0u); + else dst[0] = 0; + return; + } + const float s = !sc ? 1.0f : sc_f32 ? *(const float*)sc : bf16_to_f32(*(const uint16_t*)sc); + const size_t at = (size_t)id * n_embd + j; + float v[V]; + if constexpr (Q && V == 4) { + const uint32_t q = *(const uint32_t*)((const uint8_t*)wte + at); + const v2f lo = r4d_fp8::e4m3_pk(q), hi = r4d_fp8::e4m3_pk(q); + v[0] = lo.x; v[1] = lo.y; v[2] = hi.x; v[3] = hi.y; + } else if constexpr (Q) { + v[0] = r4d_fp8::e4m3(((const uint8_t*)wte)[at]); + } else if constexpr (V == 4) { + const uint2 b = *(const uint2*)((const uint16_t*)wte + at); + v[0] = bf16_to_f32((uint16_t)b.x); v[1] = bf16_to_f32((uint16_t)(b.x >> 16)); + v[2] = bf16_to_f32((uint16_t)b.y); v[3] = bf16_to_f32((uint16_t)(b.y >> 16)); + } else { + v[0] = bf16_to_f32(((const uint16_t*)wte)[at]); + } + if constexpr (V == 4) { + *(uint2*)dst = make_uint2( + (uint32_t)f32_to_bf16(v[0] * s) | ((uint32_t)f32_to_bf16(v[1] * s) << 16), + (uint32_t)f32_to_bf16(v[2] * s) | ((uint32_t)f32_to_bf16(v[3] * s) << 16)); + } else { + dst[0] = f32_to_bf16(v[0] * s); + } +} + // ---------------------------------------------------------------------------- gather_rows // ref_gather_rows. Same shape as the embedding gather and the same negative-index rule, but the // source row pitch is the caller's rather than n: a gather off a padded activation buffer is what @@ -535,6 +592,25 @@ extern "C" int r4d_embed_lookup_bf16(long tok, long wte, long x, int M, int n_em return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, sk); } +/* The quad walk when the width, the pitch and both bases allow its 4- and 8-byte accesses (a bf16 + * table's quad is 8 bytes), an entry a thread otherwise. */ +static int embed_lookup_q_emit(const int32_t* tok, const void* wte, bool q, const void* sc, + bool sc_f32, uint16_t* x, long long M, int n_embd, int n_vocab, + int vocab_off, long long x_ld, const R4dSink& sk) { + const bool quad = n_embd % 4 == 0 && x_ld % 4 == 0 && r4d_aligned(x, 8) && + r4d_aligned(wte, q ? 4 : 8); + const uint64_t threads = (uint64_t)M * (uint64_t)(quad ? n_embd / 4 : n_embd); + const dim3 grid((uint32_t)((threads + kThreads - 1) / kThreads)); +#define R4D_ELQ(V, Q) \ + R4D_EMIT(sk, (embed_lookup_q_kernel), grid, dim3(kThreads), 0, tok, wte, sc, \ + (uint32_t)(sc_f32 ? 1u : 0u), x, (uint32_t)M, (uint32_t)n_embd, (int32_t)n_vocab, \ + (int32_t)vocab_off, (uint32_t)x_ld) + const int rc = quad ? (q ? R4D_ELQ(4, true) : R4D_ELQ(4, false)) + : (q ? R4D_ELQ(1, true) : R4D_ELQ(1, false)); +#undef R4D_ELQ + return rc == RAD_OK ? 0 : -4; +} + 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, const R4dSink& sk) { if (!x || !idx || !y) return -1; @@ -893,6 +969,46 @@ static int rad_embed_lookup_body(const RadArgs* a, const R4dSink& sk) { } R4D_ENTRY(r4d_rad_embed_lookup, rad_embed_lookup_body) +/* ------------------------------------------------------------------ embed_lookup_q */ + +/* Operand 4, `ahead`, is not read. It carries the ids of the prompt after this step for a host + * reader that fetches table rows from a file before they are wanted; a card reads its table where + * it already is, so there is nothing to fetch. */ +enum { ELQ_TOK = 0, ELQ_WTE, ELQ_SCALE, ELQ_X }; + +static int rad_embed_lookup_q_body(const RadArgs* a, const R4dSink& sk) { + const RadTensor* tok = r4d_opt(a, ELQ_TOK); + const RadTensor* wte = r4d_opt(a, ELQ_WTE); + const RadTensor* sc = r4d_opt(a, ELQ_SCALE); + const RadTensor* x = r4d_opt(a, ELQ_X); + if (!tok || !wte || !x) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_i32(tok)); + R4D_NEED(dt_bf16(x)); + const bool q = wte->dtype == RAD_F8E4M3; + if (!q && wte->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (sc && sc->dtype != RAD_BF16 && sc->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (sc && r4d_numel(sc) < 1) return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(tok) || !r4d_contig(wte)) return R4D_NO(RAD_E_STRIDE); + + const long long n_embd = r4d_geti_or(a, "n_embd", r4d_dim(wte, (int)wte->rank - 1)); + const long long n_vocab = r4d_geti_or(a, "n_vocab", r4d_dim(wte, (int)wte->rank - 2)); + const long long voff = r4d_geti_or(a, "vocab_offset", 0); + if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(wte) < n_vocab * n_embd) return R4D_NO(RAD_E_SHAPE); + + long long M = 0; + const long long x_ld = r4d_rows_pitch(x, n_embd, &M); + if (x_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE); + + return embed_lookup_q_emit((const int32_t*)r4d_addr(tok), (const void*)r4d_addr(wte), q, + sc ? (const void*)r4d_addr(sc) : nullptr, + sc && sc->dtype == RAD_F32, (uint16_t*)r4d_addr(x), M, + (int)n_embd, (int)n_vocab, (int)voff, x_ld, sk) == 0 + ? RAD_OK : RAD_E_DEVICE; +} +R4D_ENTRY(r4d_rad_embed_lookup_q, rad_embed_lookup_q_body) + /* ------------------------------------------------------------------ gather_rows */ enum { GR_X = 0, GR_IDX, GR_Y }; diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index c368bb7c..5ac110e2 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -340,6 +340,8 @@ R4D_HOOKS(moe_w4_mod4) #undef R4D_HOOKS int r4d_rad_layout_fp8_rowmajor(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); +int r4d_rad_layout_embed_q(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); int r4d_rad_layout_moe_fp8(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r4d_rad_layout_moe_fp8_mod4(const RadParam*, int, int, const RadEncoding*, const int*, @@ -364,6 +366,10 @@ int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const * fatal issue, not a slow one. `logits_gemm` is declared with them. */ int r4d_rad_embed_lookup (const RadArgs*, RadStream); int r4d_rad_embed_lookup_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +/* The quantised gather (embed_lookup_q): the n-gram table's, where a card reads the table -- in + * VRAM, or in pinned host memory over the link. */ +int r4d_rad_embed_lookup_q (const RadArgs*, RadStream); +int r4d_rad_embed_lookup_q_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_ngram_ids (const RadArgs*, RadStream); /* ABI v10: the same dispatch, described. Generated with the launch above by R4D_ENTRY, from one * body, so the two cannot describe different work. */ @@ -427,6 +433,7 @@ int r4d_rad_sample_merge_topk(const RadArgs*, RadStream); * Pure host code, called before anything is allocated, so it includes neither r4d.h nor * -- the same split r4d_rows.cpp and r4d_layout.cpp keep. */ int r4d_shape_embed_lookup (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_embed_lookup_q (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gather_rows (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gather_rows_u8 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scatter_rows_u8(const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 71151e58..6beac273 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -1614,6 +1614,16 @@ static const RadOperandSpec oEmbed[] = { { "wte", RAD_OPD_WEIGHT, 0 }, { "x", RAD_OPD_OUT, 0 }, }; +/* The quantised gather's: libref's list (ref_registry.cpp), which the loader holds every plugin + * serving the op to -- a one-element `scale`, absent for a table stored plain, and `ahead`, the + * next prompt's ids for a host reader that fetches rows from a file. */ +static const RadOperandSpec oEmbedQ[] = { + { "tokens", RAD_OPD_IN, 0 }, + { "wte", RAD_OPD_WEIGHT, 0 }, + { "scale", RAD_OPD_WEIGHT, 1 }, + { "x", RAD_OPD_OUT, 0 }, + { "ahead", RAD_OPD_IN, 1 }, +}; /* PLE's hashed n-gram ids. `state` is a rolling window of committed ids -- RAD_KV_CONV's shape and * ple_conv's contract -- except that a cold window is EOS and not zero, because zero is a real * token id. */ @@ -1821,6 +1831,11 @@ static const RadOpSchema kSchemas[] = { "[vocab_offset, vocab_offset + n_vocab) -- which is what makes the table shardable " "across the vocabulary, the symmetry lm_head already had. Ids stay GLOBAL; summing the " "ranks reconstructs x, so the caller follows this with an exact all_reduce."), + SCHEMA("embed_lookup_q", pEmbed, oEmbedQ, + "the same gather from a table quantised with ONE scale for all of it: x[m] = " + "wte[id] * scale[0], an absent scale being one. Padding and bounds behave exactly as " + "embed_lookup's. `ahead` is the next prompt's ids, for a reader that fetches rows ahead " + "of the step; a kernel that reads its table in place ignores it."), SCHEMA("ple_gate", pPleGate, oPleGate, "PLE's gate. K = grouped_rmsnorm(k) * (w_key + wadd) and Q likewise over `q`, one rsqrt " "per n-wide stream and one gain across all hc*n; s[c] = sum_d K[c][d]*Q[c][d] / sqrt(n); " @@ -3137,6 +3152,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_embed_lookup, nullptr, nullptr, nullptr, r4d_shape_embed_lookup, nullptr, nullptr, r4d_rad_embed_lookup_describe }, +{ "embed_lookup_q_bf16", "embed_lookup_q", "vocab", + "quantised embedding gather, four entries a thread", + "any n_embd and n_vocab; a negative or out-of-range id writes a zero row", + "i32 tokens, an E4M3 table with a bf16 or f32 scale or a plain bf16 one, bf16 output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_embed_lookup_q, nullptr, r4d_rad_layout_embed_q, nullptr, + r4d_shape_embed_lookup_q, nullptr, nullptr, r4d_rad_embed_lookup_q_describe }, + { "ple_gate_bf16", "ple_gate", "norm", "PLE's dot-product gate, one workgroup a (row, stream) pair", "n up to 4096 -- every reduction is over one stream's n and lives in a workgroup", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 40f94c62..745b2846 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -9112,6 +9112,119 @@ static void gather_two_rank(const Plugin& pl, const std::vector& devs) { * `tok` behind them. Their ids must be the ids step two computes running [7, 8, 9] against the * window step one left; that window must be the step's own; and the step's own ids must be the * ones a launch without `ahead_ids` writes. The same property ref_test holds libref to. */ +/* embed_lookup_q against a host gather of the same bytes, through the host side's own conversions. + * + * THE BAR IS THE BIT, not a tolerance. libavx's gather decodes a code as + * rad_f32_to_bf16(rad_fp8e4m3_to_f32(code) * scale), and the device kernel has to produce exactly + * that for every code, or one model reads a different n-gram embedding depending on which tier + * --ngram-placement put its table on. So the oracle is those two functions, the table holds every + * code but the two NaN encodings (no quantiser writes them), and the comparison is of the bytes. + * + * Five launches: the quad walk and the entry walk (the model's width of 160, and 13); an E4M3 + * table with a scale and a plain bf16 one without, whose rows come back unchanged; the table in + * VRAM and in pinned host memory read over the link, the placement this kernel exists for. The ids + * include padding (-1) and one past the table, and both write a zero row. */ +static void embed_lookup_q_case(const Plugin& pl) { + if (!sel("embed_lookup_q_bf16")) return; + const char* what = "embed_lookup_q vs a host gather, to the bit"; + const RadKernelInfo* r = find(pl, "embed_lookup_q_bf16"); + if (!r) { ok(what, false, "row absent"); return; } + + struct Shape { int64_t ne; bool e4m3; bool host; }; + const Shape shapes[] = { { 160, true, false }, { 160, true, true }, { 13, true, false }, + { 160, false, true }, { 13, false, false } }; + const int64_t NV = 1031, M = 37; + const float scale = rad_bf16_to_f32(rad_f32_to_bf16(1.99317932e-4f)); + std::vector pinned; + std::string bad; + for (const Shape& sh : shapes) { + const int64_t es = sh.e4m3 ? 1 : 2; + const size_t tbytes = (size_t)(NV * sh.ne * es); + std::vector table(tbytes); + uint32_t rs = 0x9e3779b9u; + for (int64_t i = 0; i < NV * sh.ne; ++i) { + rs = rs * 1664525u + 1013904223u; + if (sh.e4m3) { + uint8_t c = (uint8_t)((i * 167 + (rs >> 24)) & 0xFF); + if ((c & 0x7F) == 0x7F) c ^= 0x01; /* 0x7F and 0xFF are NaN */ + table[(size_t)i] = c; + } else { + const uint16_t b = rad_f32_to_bf16((float)((int32_t)(rs >> 9) - (1 << 22)) * 1e-6f); + std::memcpy(&table[(size_t)(2 * i)], &b, 2); + } + } + std::vector ids((size_t)M); + for (int64_t m = 0; m < M; ++m) ids[(size_t)m] = (int32_t)((m * 131 + 7) % NV); + ids[3] = -1; + ids[7] = (int32_t)NV; + ids[11] = (int32_t)(NV - 1); + + void* d_tab = nullptr; + if (sh.host) { + void* h = nullptr; + if (hipHostMalloc(&h, tbytes, hipHostMallocMapped) != hipSuccess) { + ok(what, false, "pinned table allocation failed"); + return; + } + pinned.push_back(h); + std::memcpy(h, table.data(), tbytes); + if (hipHostGetDevicePointer(&d_tab, h, 0) != hipSuccess || !d_tab) { + ok(what, false, "no device address for the pinned table"); + return; + } + } else { + d_tab = dalloc(tbytes); + st_memcpy(d_tab, table.data(), tbytes, hipMemcpyHostToDevice); + } + const uint16_t sc_bits = rad_f32_to_bf16(scale); + void* d_sc = dalloc(2); + st_memcpy(d_sc, &sc_bits, 2, hipMemcpyHostToDevice); + void* d_tok = dalloc((size_t)M * 4); + st_memcpy(d_tok, ids.data(), (size_t)M * 4, hipMemcpyHostToDevice); + void* d_x = dalloc((size_t)(M * sh.ne * 2)); + st_memset(d_x, 0xFF, (size_t)(M * sh.ne * 2)); /* a zero row has to be written */ + + std::vector ts = { T(d_tok, RAD_I32, { M }), + T(d_tab, sh.e4m3 ? RAD_F8E4M3 : RAD_BF16, { NV, sh.ne }), + T(sh.e4m3 ? d_sc : nullptr, RAD_BF16, { 1 }), + T(d_x, RAD_BF16, { M, sh.ne }) }; + std::vector ps = { PI("M", M), PI("n_embd", sh.ne), PI("n_vocab", NV), + PS("dtype", "bf16") }; + 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 int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + std::vector got((size_t)(M * sh.ne), 0); + st_memcpy(got.data(), d_x, got.size() * 2, hipMemcpyDeviceToHost); + + int64_t wrong = 0; + for (int64_t m = 0; m < M; ++m) { + const int32_t id = ids[(size_t)m]; + for (int64_t i = 0; i < sh.ne; ++i) { + uint16_t want = 0; + if (id >= 0 && id < NV) { + const size_t at = (size_t)(id * sh.ne + i); + if (sh.e4m3) { + want = rad_f32_to_bf16(rad_fp8e4m3_to_f32(table[at]) * scale); + } else { + std::memcpy(&want, &table[2 * at], 2); + } + } + if (got[(size_t)(m * sh.ne + i)] != want) ++wrong; + } + } + if (rc != RAD_OK || wrong) + bad += fmt("%s n_embd=%lld %s: rc=%d, %lld of %lld entries differ; ", + sh.e4m3 ? "e4m3" : "bf16", (long long)sh.ne, + sh.host ? "pinned host table" : "vram table", rc, (long long)wrong, + (long long)(M * sh.ne)); + } + for (void* h : pinned) hip_ck(hipHostFree(h), "hipHostFree", __LINE__); + ok(what, bad.empty(), bad); +} + static void ngram_ahead_case(const Plugin& pl) { if (!sel("ngram_ids_i32")) return; const RadKernelInfo* r = find(pl, "ngram_ids_i32"); @@ -9194,6 +9307,7 @@ static void device_phase(const Plugin& pl) { if (!g_case) std::printf("\ndevice smoke tests (device %d)\n", devs[0]); ngram_ahead_case(pl); + embed_lookup_q_case(pl); /* --- the paged cache's write side --- */ kv_store_case(pl, "kv_store_bf16", "bf16"); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 4dcf2994..295057e9 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -296,6 +296,26 @@ extern "C" int r4d_shape_embed_lookup(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* The quantised gather: libref's description (ref_embed_lookup_q_shape), an E4M3 table and a + * one-element scale in the activation dtype. `ahead` is not passed: it is ids for a reader that + * fetches rows from a file, and the kernel does not read it. */ +extern "C" int r4d_shape_embed_lookup_q(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_embd"); + const int64_t nv = pi(p, n_p, "n_vocab"); + const int64_t vo = pi(p, n_p, "vocab_offset", 0); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { + opd_idx(M, 0, vo + nv), + opd((uint32_t)RAD_F8E4M3, nv, ne), + opd(D, 1), + opd(D, M, ne), + opd_none(), + }; + R4D_PICK(l); +} + extern "C" int r4d_shape_gather_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/tests/place_test.cpp b/tests/place_test.cpp index 1b88b4b9..5546d251 100644 --- a/tests/place_test.cpp +++ b/tests/place_test.cpp @@ -2237,7 +2237,7 @@ TEST(the_weight_footprint_splits_statics_from_the_elastic_expert_plane) { build_moe(f, /*n=*/4, /*each=*/2 * MiB, &experts); WeightFootprint fp; - weight_footprint(f.prog, &fp, TablePlacement::Vram); + weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk); /* One model-level weight and four experts: five units. */ CHECK_EQ(fp.n_units, 5ll); @@ -2267,7 +2267,7 @@ TEST(weights_in_one_layer_are_one_unit_and_are_aligned_once_each) { } WeightFootprint fp; - weight_footprint(f.prog, &fp, TablePlacement::Vram); + weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk); CHECK_EQ(fp.n_units, 2ll); /* the declared group is the unit, not the weight */ /* ONE align_up A UNIT AND ONE INSIDE IT, which is how Mover::init spends the slab. A budget @@ -2300,7 +2300,7 @@ TEST(a_weight_with_no_device_band_takes_its_whole_unit_to_the_mapped_tier) { f.prog.ops.push_back(host_only); WeightFootprint fp; - weight_footprint(f.prog, &fp, TablePlacement::Vram); + weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk); CHECK_EQ(fp.n_units, 1ll); CHECK_EQ(fp.statics, 0ll); CHECK_EQ(fp.mapped, 6 * MiB); /* both weights: the unit is what moves */ @@ -2347,7 +2347,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) { add_ngram_table(f, 8 * MiB); WeightFootprint fp; - weight_footprint(f.prog, &fp, TablePlacement::Vram); + weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk); CHECK_EQ(fp.embedding, 1 * MiB); CHECK_EQ(fp.ngram, 8 * MiB); CHECK(!fp.ngram_device); @@ -2355,7 +2355,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) { CHECK_EQ(fp.statics, 2 * 4 * MiB + 2 * MiB); CHECK_EQ(fp.mapped, 8 * MiB); - weight_footprint(f.prog, &fp, TablePlacement::Ram); + weight_footprint(f.prog, &fp, TablePlacement::Ram, TablePlacement::Disk); CHECK_EQ(fp.embedding, 1 * MiB); CHECK_EQ(fp.hosted, 1 * MiB); CHECK_EQ(fp.statics, 2 * 4 * MiB + 1 * MiB); @@ -2372,7 +2372,7 @@ TEST(the_placement_flags_find_their_tables_by_what_reads_them) { t.op("embed_lookup", {m}, false); t.op("logits_gemm", {m}, false); CHECK(!is_embedding_table(t.prog, m)); - weight_footprint(t.prog, &fp, TablePlacement::Ram); + weight_footprint(t.prog, &fp, TablePlacement::Ram, TablePlacement::Disk); CHECK_EQ(fp.embedding, 0ll); CHECK_EQ(fp.hosted, 0ll); } @@ -2490,16 +2490,84 @@ TEST(ngram_ram_stays_mapped_and_reports_the_copy) { CHECK(plan2.report(f.prog).find("n-gram copy") == std::string::npos); } +/* An n-gram table a device kernel reads as well as the host one: --ngram-placement says where it + * is, and so who gathers. vram counts it with the statics and places it with them; ram keeps it on + * the mapped tier at the zero-copy site, the pinned copy a card reads, and reports that copy; disk + * keeps it on the mapped tier at the host site, where the host gather reads the container. */ +TEST(an_ngram_table_a_device_kernel_reads_goes_where_the_placement_says) { + Fixture f; + build_dense_lookup(f, /*layers=*/1, /*per_layer=*/4 * MiB); + const rad_weight t = f.weight("ngram.weight", 8 * MiB, RAD_ACCESS_VOCAB, -1, -1); + f.op("embed_lookup_q", {t}, /*host_kernel=*/true); + + WeightFootprint fp; + weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Vram); + CHECK(fp.ngram_device); + CHECK(fp.ngram_host); + CHECK_EQ(fp.ngram, 8 * MiB); + CHECK_EQ(fp.mapped, 0ll); + CHECK_EQ(fp.statics, 4 * MiB + 2 * MiB + 8 * MiB); + for (TablePlacement off : { TablePlacement::Ram, TablePlacement::Disk }) { + weight_footprint(f.prog, &fp, TablePlacement::Vram, off); + CHECK_EQ(fp.ngram, 8 * MiB); + CHECK_EQ(fp.mapped, 8 * MiB); + CHECK_EQ(fp.statics, 4 * MiB + 2 * MiB); + } + + Config cfg = base_config(); + cfg.placement = "all_vram"; + PlannerInput in{&f.prog, &cfg, 0, 1, nullptr, 0}; + + cfg.ngram_resolved = TablePlacement::Vram; + Plan on_card; + CHECK_OK(Planner(in).plan(&on_card)); + CHECK(on_card.weight[t].tier == Tier::VRAM); + CHECK(on_card.weight[t].site == Site::Device); + CHECK_EQ(on_card.ngram_copy_bytes, 0ll); + + cfg.ngram_resolved = TablePlacement::Ram; + Plan in_ram; + CHECK_OK(Planner(in).plan(&in_ram)); + CHECK(in_ram.weight[t].tier == Tier::Mapped); + CHECK(in_ram.weight[t].site == Site::DeviceZeroCopy); + CHECK_EQ(in_ram.ngram_copy_bytes, 8 * MiB); + CHECK(in_ram.ngram_copy_card); + CHECK(std::string(in_ram.weight[t].reason).find("the card reads") != std::string::npos); + CHECK(in_ram.report(f.prog).find("pinned RAM the card reads") != std::string::npos); + + cfg.ngram_resolved = TablePlacement::Disk; + Plan on_disk; + CHECK_OK(Planner(in).plan(&on_disk)); + CHECK(on_disk.weight[t].tier == Tier::Mapped); + CHECK(on_disk.weight[t].site == Site::Host); + CHECK_EQ(on_disk.ngram_copy_bytes, 0ll); + CHECK(std::string(on_disk.weight[t].reason).find("--ngram-placement disk") != + std::string::npos); +} + +/* The host gather's own kernel is what makes disk possible at all: an n-gram table only a device + * kernel reads has no host site, and the footprint says so. */ +TEST(an_ngram_table_with_no_host_kernel_cannot_stay_on_disk) { + Fixture f; + const rad_weight t = f.weight("ngram.weight", 8 * MiB, RAD_ACCESS_VOCAB, -1, -1); + f.op("embed_lookup_q", {t}, /*host_kernel=*/false); + WeightFootprint fp; + weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk); + CHECK(fp.ngram_device); + CHECK(!fp.ngram_host); +} + TEST(an_empty_program_has_an_empty_footprint) { Fixture f; WeightFootprint fp; fp.statics = 1; /* and the out parameter is reset, not accumulated */ - weight_footprint(f.prog, &fp, TablePlacement::Vram); + weight_footprint(f.prog, &fp, TablePlacement::Vram, TablePlacement::Disk); CHECK_EQ(fp.statics, 0ll); CHECK_EQ(fp.experts, 0ll); CHECK_EQ(fp.mapped, 0ll); CHECK_EQ(fp.n_units, 0ll); - weight_footprint(f.prog, nullptr, TablePlacement::Vram); /* and a null one is not a crash */ + /* and a null one is not a crash */ + weight_footprint(f.prog, nullptr, TablePlacement::Vram, TablePlacement::Disk); } RAD_TEST_MAIN()