diff --git a/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h index a09f2f78..446504fa 100644 --- a/arch/common/rad_block_ple.h +++ b/arch/common/rad_block_ple.h @@ -106,10 +106,18 @@ struct PleLayer { rad_op op_gate = 0, op_conv = 0, op_add = 0; int64_t hn() const { return c.hc * g.n_embd; } + /* The read-ahead queue's depth, in steps: the scheduler stages this many steps of the + * following prompt per step (batch.cpp, k_ahead_chunks) and the gather hands them to the + * reader thread, which prefetches their rows off the step path while the current chunk runs. + * Clamped to what `b_ids` was declared to hold, so a scheduler that offers more degrades the + * queue's depth, never an overflow. */ + static constexpr int64_t kAheadChunks = 8; /* The prompt that follows the step, bounded by what `b_ids` holds after the step's rows. */ int64_t ahead_rows(const RadBatch* batch) const { const int64_t a = batch->n_ahead; - return a <= 0 ? 0 : (a < g.max_tok ? a : g.max_tok); + if (a <= 0) return 0; + const int64_t cap = kAheadChunks * g.max_tok; + return a < cap ? a : cap; } int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& cfg, int layer, @@ -275,10 +283,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C * follows declared order, where the two ops are adjacent, so a transient could be overwritten * in between. */ { - /* Twice the step's rows: the step's ids, then those of the prompt that follows - * (RadBatch::n_ahead), which the gather's reader prefetches while the step runs. */ + /* The step's rows, then the read-ahead queue's: up to kAheadChunks further steps of the + * following prompt (RadBatch::n_ahead), which the gather's reader prefetches while the + * step runs, so a prefill's table rows are read at disk speed off the step path. */ RadBufDecl d{}; - d.dtype = RAD_I32; d.rank = 2; d.shape[0] = 2 * g.max_tok; d.shape[1] = c.heads; + d.dtype = RAD_I32; d.rank = 2; + d.shape[0] = (1 + kAheadChunks) * g.max_tok; d.shape[1] = c.heads; d.kind = RAD_BUF_PERSIST; d.domain = RAD_DOMAIN_HOST; b_ids = rad_decl_buffer(b, nm.f("ple_ids"), &d); diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 92becbe9..d21ab81a 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -12,6 +12,13 @@ namespace rad { +/* How many steps of the following prompt the PLE read-ahead queue stages (RadBatch::n_ahead): + * the arch's reader thread drains the queue at disk speed, off the step path, so a prefill + * chunk's table rows are already cached when its gather runs. Keep in step with rad_block_ple.h + * (kAheadChunks), which clamps to the buffer it declared; a mismatch degrades to a smaller queue, + * never an overflow. */ +static constexpr int64_t k_ahead_chunks = 8; + /* Alignment of each staging array carved from a set's slab. One slab per set means a couple of * allocations at init instead of two dozen, with every array sharing one mapping. */ static const int64_t k_carve_align = 256; @@ -97,9 +104,10 @@ void BatchBuilder::carve(Set& s, char* h) { *ph = ::rad::carve(h, oh, n); *pd = ::rad::carve(d, od, n); }; - /* Twice the step: its own tokens, then up to a step of the following prompt - * (RadBatch::n_ahead). */ - pair(&s.h_tok, &s.d_tok, 2 * T); + /* The step's tokens, then the PLE read-ahead queue -- k_ahead_chunks steps of the following + * prompt (RadBatch::n_ahead), which the arch's reader thread prefetches off the step path + * (rad_block_ple.h, which clamps to the same count). */ + pair(&s.h_tok, &s.d_tok, (1 + k_ahead_chunks) * T); pair(&s.h_pos, &s.d_pos, T); pair(&s.h_parent, &s.d_parent, T); pair(&s.h_cu, &s.d_cu, S + 1); @@ -1044,17 +1052,18 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, } } - /* Up to a step of the last sequence's following tokens, after this step's own - * (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, bounded by - * the tokens the request has; like token_at, a re-prefill after preemption continues into its - * own output. */ + /* Up to the read-ahead queue's worth of the last sequence's following tokens, after this + * step's own (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, + * bounded by the tokens the request has; like token_at, a re-prefill after preemption + * continues into its own output. The arch clamps to the rows it declared. */ int64_t n_ahead = 0; if (n_seq > 0 && plan.draft_pass == 0 && plan.tok_shift == 0) { const StepEntry& e = plan.e[(size_t)(n_seq - 1)]; if (e.req && e.is_prefill) { const int64_t next = (int64_t)e.ctx_len + e.n_tokens; const int64_t have = (int64_t)e.req->prompt.size() + (int64_t)e.req->output.size(); - n_ahead = std::min(std::max(have - next, 0), max_tok_); + n_ahead = std::min(std::max(have - next, 0), + k_ahead_chunks * max_tok_); for (int64_t j = 0; j < n_ahead; ++j) s.h_tok[n_tok + j] = token_at(e, next + j); } } diff --git a/libavx/avx_ngram.cpp b/libavx/avx_ngram.cpp index ccb735d4..ae32f4ef 100644 --- a/libavx/avx_ngram.cpp +++ b/libavx/avx_ngram.cpp @@ -40,6 +40,7 @@ #include #include +#include #include #include #include @@ -60,6 +61,16 @@ namespace { +/* Phase timers for one rank's gather, when RAD_PLE_TIMING is set: accumulated on the issuing + * thread and printed by avx::row_gather. The ahead-reader thread accumulates and never prints. */ +struct PleTiming { + bool on = std::getenv("RAD_PLE_TIMING") != nullptr; + double find_ms = 0, pub_ms = 0, read_ms = 0, wait_ms = 0, dec_ms = 0, again_ms = 0; + uint64_t enters = 0, bytes = 0; + size_t spans = 0, hits = 0, claimed = 0, none = 0, theirs = 0; +}; +thread_local PleTiming t_ple; + /* Prefetch distance, in rows, for cache lookups and decodes. Rows are scattered over an 80 MiB * cache and the set words over 4 MiB, so each is an L3 or DRAM miss. */ constexpr long long kPrefetchRows = 8; @@ -281,7 +292,12 @@ const TableFile* table_file(const uint8_t* p, long long n, int* err) { * committed only as slots fill. */ struct RowCache { static constexpr int kWays = 8; - static constexpr uint64_t kRows = 1ull << 19; + /* Slot count, overridable with RAD_PLE_CACHE_ROWS (rows, clamped to [2^16, 2^25]). Data cost + * is `rows` * row bytes (160 at E4M3), so the shipped 2^19 rows is 80 MiB. The table's row + * popularity is Zipfian: a larger cache holds a longer hot head of the distribution and + * trades RAM directly for a lower miss rate on repeated traffic. Size it from measurement, + * not the model -- RAD_PLE_TIMING prints the per-call hit counts the sweep reads. */ + static const uint64_t kRows; enum : uint64_t { EMPTY = 0, LOADING = 1, READY = 2 }; const TableFile* tf = nullptr; @@ -361,6 +377,21 @@ T* anon_array(size_t count) { } /* The cache for `n`-byte rows of `tf`, created on first use and kept for the process lifetime. */ +/* Defined out of line so the environment is read once, at first use. */ +const uint64_t RowCache::kRows = [] { + unsigned long long v = 1ull << 19; + if (const char* s = std::getenv("RAD_PLE_CACHE_ROWS")) { + char* end = nullptr; + const long long n = std::strtoll(s, &end, 10); + if (end != s && n > 0) v = (uint64_t)n; + } + if (v < 1ull << 16) v = 1ull << 16; + if (v > 1ull << 25) v = 1ull << 25; + /* Whole sets: the set index is `mix(key) & set_mask` over kWays-way sets. */ + v -= v % kWays; + return v; +}(); + RowCache* row_cache(const TableFile* tf, long long n) { static std::mutex mu; static std::vector> caches; @@ -470,6 +501,16 @@ struct ReadRing { * one span per `stride` bytes, submitting and waiting in one call. Short reads fail. */ int read_spans(const TableFile& tf, const SpanRead* r, unsigned count, long long n, long long stride, uint8_t* bounce) { + if (!t_ple.on) return read_spans_now(tf, r, count, n, stride, bounce); + const auto t0 = std::chrono::steady_clock::now(); + const int s = read_spans_now(tf, r, count, n, stride, bounce); + t_ple.read_ms += + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + t_ple.spans += count; + return s; + } + int read_spans_now(const TableFile& tf, const SpanRead* r, unsigned count, long long n, + long long stride, uint8_t* bounce) { const long long A = tf.align; unsigned tail = __atomic_load_n(sq_tail, __ATOMIC_RELAXED); for (unsigned i = 0; i < count; ++i) { @@ -486,6 +527,7 @@ struct ReadRing { s->user_data = (uint64_t)(e - a); sq_array[idx] = idx; ++tail; + t_ple.bytes += (uint64_t)(e - a); } __atomic_store_n(sq_tail, tail, __ATOMIC_RELEASE); int status = RAD_OK; @@ -493,6 +535,7 @@ struct ReadRing { while (got < count) { const long rc = syscall(__NR_io_uring_enter, fd, to_submit, count - got, IORING_ENTER_GETEVENTS, nullptr, (size_t)0); + ++t_ple.enters; if (rc < 0 && errno != EINTR && errno != EAGAIN && errno != EBUSY) return RAD_E_IO; if (rc > 0) to_submit -= (unsigned)rc < to_submit ? (unsigned)rc : to_submit; unsigned h = __atomic_load_n(cq_head, __ATOMIC_RELAXED); @@ -620,6 +663,7 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG g.waits.clear(); g.again.clear(); + const auto tf0 = std::chrono::steady_clock::now(); for (long long j = 0; j < M; ++j) { if (j + kPrefetchRows < M) { const long long mp = at(j + kPrefetchRows); @@ -632,17 +676,27 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG const RowCache::Found f = rc.find_or_claim(key, me, &s); g.slot[m] = s; g.kind[m] = (uint8_t)f; + if (f == RowCache::HIT) ++t_ple.hits; + else if (f == RowCache::CLAIMED) ++t_ple.claimed; + else if (f == RowCache::NONE) ++t_ple.none; + else if (f == RowCache::THEIRS) ++t_ple.theirs; if (f == RowCache::CLAIMED) g.reads.push_back({m, key, s}); else if (f == RowCache::NONE) { g.reads.push_back({m, key, -1}); g.kind[m] = Gather::DONE; } else if (f == RowCache::THEIRS) g.waits.push_back(m); } + t_ple.find_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tf0).count(); + const auto tp0 = std::chrono::steady_clock::now(); int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.pub_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tp0).count(); if (rs != RAD_OK) return rs; /* Wait for rows other threads claimed to turn READY. `published` is read before the words, so * a batch landing after the scan makes the wait return at once. Released claims (failed reads) * and reused slots are read by this thread instead. */ + const auto tw0 = std::chrono::steady_clock::now(); while (!g.waits.empty()) { const uint32_t e = rc.published.load(std::memory_order_acquire); size_t keep = 0; @@ -657,9 +711,12 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG g.waits.resize(keep); if (keep) rc.published.wait(e, std::memory_order_acquire); } + t_ple.wait_ms += + std::chrono::duration(std::chrono::steady_clock::now() - tw0).count(); /* Decode all READY rows in one batch: each word is read before the bytes and again after the * batch (the seqlock), and rows whose word changed are read again. */ + const auto td0 = std::chrono::steady_clock::now(); g.src.clear(); g.dst.clear(); g.dm.clear(); @@ -682,22 +739,35 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG for (size_t i = 0; i < g.dm.size(); ++i) if (rc.word[g.slot[g.dm[i]]].load(std::memory_order_relaxed) != g.dw[i]) g.again.push_back(g.dm[i]); + t_ple.dec_ms += + std::chrono::duration(std::chrono::steady_clock::now() - td0).count(); if (g.again.empty()) return RAD_OK; + const auto ta0 = std::chrono::steady_clock::now(); g.reads.clear(); for (long long m : g.again) g.reads.push_back({m, key_of(m), -1}); - return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + const int ra = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld); + t_ple.again_ms += + std::chrono::duration(std::chrono::steady_clock::now() - ta0).count(); + return ra; } /* ============================== the reader that runs a step ahead ============================== * * A prefill chunk gathers `heads` rows per token (32,768 for a 2048-token chunk); on unseen text * most are file reads (~30 ms per chunk on NVMe), during which the issuing thread waits and the card - * idles. The next chunk's ids are known a step early (RadBatch::n_ahead, ngram_ids' `ahead_ids`), so + * idles. The next chunks' ids are known a step early (RadBatch::n_ahead, ngram_ids' `ahead_ids`), so * the call hands them to one process-wide reader thread, which claims, reads and publishes the * missing rows while the chunk runs. The next call waits for LOADING rows as it would for the other * rank's. * + * The queue is handed over sliced: each job carries at most `kJobRows` keys, claimed and published + * one job at a time, in order. Claims are promises the consumer waits on (a slot LOADING for a row + * it needs blocks the gather on the reader's progress), so a job must stay small: bounded claims + * keep the promise horizon near, and a consumer that outruns the reader finds unclaimed rows it + * can read itself instead of waiting behind the whole queue. Jobs keep the list's order, so the + * nearest chunk's rows are always the reader's first work. + * * Both ranks hand over the same ids; a repeated list is dropped. A failed read releases its claims * and the next call reads those rows itself. The reader is detached and never destroyed. */ struct AheadJob { @@ -707,6 +777,10 @@ struct AheadJob { std::vector keys; }; +/* One producer job's claim-read-publish sweep: ~2 ring batches, so the promise a job makes to a + * consuming gather is paid in well under a second on any disk that can stream the table. */ +constexpr size_t kJobRows = 8192; + struct AheadReader { std::mutex mu; std::condition_variable cv; @@ -726,6 +800,8 @@ struct AheadReader { q.pop_front(); } if (!rr || !me) continue; + const auto t0 = t_ple.on ? std::chrono::steady_clock::now() + : std::chrono::steady_clock::time_point(); g.reads.clear(); for (size_t i = 0; i < j.keys.size(); ++i) { if (i + kPrefetchRows < j.keys.size()) @@ -737,6 +813,12 @@ struct AheadReader { /* Every read has a slot, so nothing is decoded and there is no output. */ (void)read_and_publish(*j.tf, *j.rc, *rr, g, g.reads, j.n, 0, nullptr, nullptr, nullptr, 0); + if (t_ple.on) { + const double ms = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + std::fprintf(stderr, "ple[reader] keys %zu reads %zu %.1fms\n", j.keys.size(), + g.reads.size(), ms); + } } } }; @@ -750,7 +832,9 @@ AheadReader* ahead_reader() { return r; } -/* Hands the rows of `q.ahead` (to be gathered by a later call) to the reader. */ +/* Hands the rows of `q.ahead` (to be gathered by later calls) to the reader, sliced into + * `kJobRows`-key jobs in list order: the reader claims, reads and publishes one job at a time, so + * the nearest chunk's rows are its first work and a claim's promise horizon stays short. */ void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) { uint64_t h = 1469598103934665603ull ^ (uint64_t)(uintptr_t)&rc; for (long long m = 0; m < q.n_ahead; ++m) { h ^= (uint32_t)q.ahead[m]; h *= 1099511628211ull; } @@ -760,17 +844,26 @@ void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) { if (h == r->last) return; r->last = h; } + const long long base = tf.off + (long long)(q.tab - tf.lo); AheadJob j; j.tf = &tf; j.rc = &rc; j.n = q.row_bytes; - const long long base = tf.off + (long long)(q.tab - tf.lo); - j.keys.reserve((size_t)q.n_ahead); + j.keys.reserve(kJobRows); for (long long m = 0; m < q.n_ahead; ++m) { const long long id = (long long)q.ahead[m] - q.voff; - if (id >= 0 && id < q.n_vocab) j.keys.push_back((uint64_t)(base + id * q.row_bytes)); + if (id < 0 || id >= q.n_vocab) continue; + j.keys.push_back((uint64_t)(base + id * q.row_bytes)); + if (j.keys.size() == kJobRows) { + { + std::lock_guard lk(r->mu); + r->q.push_back(j); + } + r->cv.notify_one(); + j.keys.clear(); + } } - { + if (!j.keys.empty()) { std::lock_guard lk(r->mu); r->q.push_back(std::move(j)); } @@ -806,6 +899,7 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { if (!tfile) return ferr; #if defined(__linux__) if (tfile->fd >= 0) { + const auto t0 = std::chrono::steady_clock::now(); int why = 0; ReadRing* rr = read_ring(&why); if (!rr) { @@ -819,6 +913,18 @@ int avx::row_gather(const RowGather& q, RowDecode decode) { const long long first = q.rank > 0 && q.rank < ws ? q.M * q.rank / ws : 0; const int rs = gather_rows(*tfile, *rc, *rr, q, first, decode, lut); if (rs != RAD_OK) return rs; + const double wall = + std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + if (t_ple.on) + std::fprintf(stderr, + "ple[rank %lld] rows %lld: find %.1fms (hit %zu claimed %zu none %zu " + "theirs %zu) pub %.1fms (ring %.1fms, %llu enters, %zu spans, " + "%.1f MiB) wait %.1fms dec %.1fms again %.1fms | wall %.1fms\n", + (long long)q.rank, (long long)q.M, t_ple.find_ms, t_ple.hits, + t_ple.claimed, t_ple.none, t_ple.theirs, t_ple.pub_ms, t_ple.read_ms, + (unsigned long long)t_ple.enters, t_ple.spans, t_ple.bytes / 1048576.0, + t_ple.wait_ms, t_ple.dec_ms, t_ple.again_ms, wall); + t_ple = {}; /* Queue the rows a later call will gather, after this call's own rows. */ if (q.ahead && q.n_ahead > 0) read_ahead(*tfile, *rc, q); return RAD_OK; diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 223ba77e..1d87c15b 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -8644,14 +8644,14 @@ struct ArchCases { qwen35moe_fp8::step, 3, {}, 0x1bd3b53543cd06eeull); add("qwen4exp_fp8", [this](RadBuilder* b) { auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); }, - qwen4exp_fp8::step, 3, {}, 0xbe74d476c7fd04b8ull); + qwen4exp_fp8::step, 3, {}, 0x43048d3448778280ull); add("qwen4exp_fp8, two ranks", [this](RadBuilder* b) { auto c = q4_ctx(0, 2); return qwen4exp_fp8::declare(b, &q4, &c); }, - nullptr, 3, { "ar_hc_write" }, 0x9d7df7914590d6d8ull); + nullptr, 3, { "ar_hc_write" }, 0x43d3be2b6d76e470ull); add("qwen4exp_fp8, four-bit experts", [this](RadBuilder* b) { b->encs = { { "ffn_gate_up_exps", w4 }, { "ffn_down_exps", w4 } }; auto c = q4_ctx(0, 1); return qwen4exp_fp8::declare(b, &q4, &c); }, - qwen4exp_fp8::step, 3, {}, 0xb308d06b168a61f1ull); + qwen4exp_fp8::step, 3, {}, 0x08d082fcbef37889ull); add("llama_fp8 + DSpark", [this](RadBuilder* b) { auto c = dspark_ctx(0, 1); return llama_fp8::declare(b, lla.meta(), &c); }, llama_fp8::step, 7, {}, 0xdcf36a1d31aba73cull); @@ -9333,11 +9333,11 @@ TEST(a_4096_budget_without_a_span_is_the_pinned_graph_and_steps) { uint64_t graph, steps; }; const Case cases[] = { - { "qwen4exp_fp8", 1, 0, 0x14b9cab0bea2591full, 0x26a9e2c23cf85696ull }, - { "qwen4exp_fp8", 2, 0, 0xc9bcbf1b538b597full, 0x889c6b36c014609full }, - { "qwen4exp_fp8", 2, 1, 0x8b2f1786a4ac12b8ull, 0x959ef6b7c6f57d8bull }, - { "qwen4exp_fp8", 4, 0, 0x1e97a26b759d29dfull, 0xfbe74f2b9d7020bfull }, - { "qwen4exp_fp8", 4, 3, 0x6669aa0573931943ull, 0x36df57cac613c6cfull }, + { "qwen4exp_fp8", 1, 0, 0x23ec76c443e2cb6full, 0x26a9e2c23cf85696ull }, + { "qwen4exp_fp8", 2, 0, 0x88290524cfd7714full, 0x889c6b36c014609full }, + { "qwen4exp_fp8", 2, 1, 0xa4268bda72739be8ull, 0x959ef6b7c6f57d8bull }, + { "qwen4exp_fp8", 4, 0, 0xaa5abead708b106full, 0xfbe74f2b9d7020bfull }, + { "qwen4exp_fp8", 4, 3, 0x9ffc4cf1b074a153ull, 0x36df57cac613c6cfull }, { "qwen35_fp8", 1, 0, 0xcfc82ca915ec549dull, 0x4d6fca823d1e97efull }, { "qwen35_fp8", 2, 1, 0xcaf28466af9e917dull, 0x0bcf5833fce11a86ull }, { "qwen35moe_fp8", 1, 0, 0x7fa7b015e1bc8873ull, 0x3fcf71676e558d79ull },