Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

C-4: the prompt's embedding in one gather, and the n-gram table read by several threads

Niko1221dfe61b1ca071
diff --git a/include/strata/platform/direct_file.hpp b/include/strata/platform/direct_file.hpp
index 1d196d860..c59eb9100 100644
--- a/include/strata/platform/direct_file.hpp
+++ b/include/strata/platform/direct_file.hpp
@@ -2,7 +2,8 @@
//
// The n-gram table (26.8 GiB) stays on the SSD and must never occupy RAM, including the OS file cache. A memory
// map cannot promise that; an unbuffered read can. On Windows this is FILE_FLAG_NO_BUFFERING | OVERLAPPED with
-// an I/O completion port; on Linux, O_DIRECT (synchronous pread for now; io_uring is phase L).
+// an I/O completion port; on Linux, O_DIRECT preads. Both issue the reads from a small thread pool (submit only
+// queues), so many reads are in flight: STRATA_IO_THREADS sets its size (default 4 on Windows, 16 on Linux).
//
// Contract of every read: offset, length and buffer address are multiples of `alignment()` (4096 here).
// Reads past end of file return the bytes that exist; `Completion::bytes` says how many.
diff --git a/src/platform/direct_file.cpp b/src/platform/direct_file.cpp
index 0e4601744..cd4f6a71b 100644
--- a/src/platform/direct_file.cpp
+++ b/src/platform/direct_file.cpp
@@ -1,10 +1,14 @@
// src/platform/direct_file.cpp - see include/strata/platform/direct_file.hpp.
#include "strata/platform/direct_file.hpp"
+#include <algorithm>
#include <chrono>
+#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <deque>
+#include <mutex>
+#include <thread>
#include <vector>
#if defined(_WIN32)
@@ -42,6 +46,26 @@ void DirectFile::free_aligned(void* p) {
#endif
}
+namespace {
+/// A queued read: `submit` only queues it; the pool's threads issue it (perf-review C-4 / F-2). One thread
+/// issuing every read was the limit of the n-gram table's prompt reads: ~12 us of kernel time per read, ~80K
+/// reads/s, while an NVMe drive serves several times that at depth.
+struct Pending {
+ uint64_t offset;
+ void* buffer;
+ uint32_t length;
+ uint64_t tag;
+};
+
+/// The number of issuing threads: STRATA_IO_THREADS, else 4 (Windows: overlapped submits) / 16 (Linux: each
+/// thread does one blocking pread, so the thread count is the queue depth).
+int io_threads(int dflt) {
+ const char* v = std::getenv("STRATA_IO_THREADS");
+ const int n = v ? std::atoi(v) : dflt;
+ return std::clamp(n, 1, 64);
+}
+} // namespace
+
#if defined(_WIN32)
// ------------------------------------------------------------------------------------------------ Windows
namespace {
@@ -57,9 +81,14 @@ struct DirectFile::Impl {
HANDLE file = INVALID_HANDLE_VALUE;
HANDLE port = nullptr;
uint64_t size = 0;
+ std::mutex mu; // everything below
std::deque<Req*> free_reqs;
std::vector<Req*> all_reqs;
- std::deque<Completion> immediate; // requests that failed after being counted as queued
+ std::deque<Completion> immediate; // requests that completed without a port packet (EOF) or failed
+ std::deque<Pending> queue; // submitted, not yet issued
+ std::condition_variable cv;
+ bool stop = false;
+ std::vector<std::thread> pool;
Req* take() {
if (free_reqs.empty()) {
@@ -71,6 +100,52 @@ struct DirectFile::Impl {
free_reqs.pop_front();
return r;
}
+
+ void issue(const Pending& p) {
+ Req* r;
+ {
+ std::lock_guard<std::mutex> lk(mu);
+ r = take();
+ }
+ std::memset(&r->ov, 0, sizeof r->ov);
+ r->ov.Offset = (DWORD) (p.offset & 0xFFFFFFFFull);
+ r->ov.OffsetHigh = (DWORD) (p.offset >> 32);
+ r->tag = p.tag;
+ if (!ReadFile(file, p.buffer, p.length, nullptr, &r->ov)) {
+ const DWORD e = GetLastError();
+ if (e != ERROR_IO_PENDING) {
+ std::lock_guard<std::mutex> lk(mu);
+ free_reqs.push_back(r);
+ // at or past end of file: a zero-byte completion; anything else: a failed one
+ immediate.push_back(Completion{p.tag, 0, e == ERROR_HANDLE_EOF});
+ PostQueuedCompletionStatus(port, 0, 0, nullptr); // wake a waiter to collect it
+ }
+ }
+ }
+
+ void worker() {
+ std::unique_lock<std::mutex> lk(mu);
+ for (;;) {
+ cv.wait(lk, [&] { return stop || !queue.empty(); });
+ if (stop && queue.empty()) return;
+ const Pending p = queue.front();
+ queue.pop_front();
+ lk.unlock();
+ issue(p);
+ lk.lock();
+ }
+ }
+
+ void stop_pool() {
+ {
+ std::lock_guard<std::mutex> lk(mu);
+ stop = true;
+ }
+ cv.notify_all();
+ for (std::thread& t : pool) t.join();
+ pool.clear();
+ stop = false;
+ }
};
DirectFile::DirectFile() : impl_(new Impl) {}
@@ -106,18 +181,22 @@ bool DirectFile::open(const std::string& path, std::string& err) {
close();
return false;
}
- // Completions of reads that finish synchronously must still be queued to the port, so every submit
- // produces exactly one packet and `wait` is the only completion path.
+ // Completions of reads that finish synchronously are still queued to the port, so every issued read
+ // produces exactly one packet; `wait` is the only completion path.
+ const int n = io_threads(4);
+ for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); });
return true;
}
void DirectFile::close() {
+ impl_->stop_pool();
if (impl_->port != nullptr) CloseHandle(impl_->port);
if (impl_->file != INVALID_HANDLE_VALUE) CloseHandle(impl_->file);
impl_->port = nullptr;
impl_->file = INVALID_HANDLE_VALUE;
impl_->size = 0;
impl_->immediate.clear();
+ impl_->queue.clear();
}
bool DirectFile::is_open() const { return impl_->file != INVALID_HANDLE_VALUE; }
@@ -129,31 +208,22 @@ bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t
err = "DirectFile: unaligned request";
return false;
}
- Req* r = impl_->take();
- std::memset(&r->ov, 0, sizeof r->ov);
- r->ov.Offset = (DWORD) (offset & 0xFFFFFFFFull);
- r->ov.OffsetHigh = (DWORD) (offset >> 32);
- r->tag = tag;
- if (!ReadFile(impl_->file, buffer, length, nullptr, &r->ov)) {
- const DWORD e = GetLastError();
- if (e != ERROR_IO_PENDING) {
- impl_->free_reqs.push_back(r);
- if (e == ERROR_HANDLE_EOF) { // at or past end of file: a zero-byte completion
- impl_->immediate.push_back(Completion{tag, 0, true});
- return true;
- }
- err = "DirectFile: ReadFile failed (error " + std::to_string(e) + ")";
- return false;
- }
+ {
+ std::lock_guard<std::mutex> lk(impl_->mu);
+ impl_->queue.push_back(Pending{offset, buffer, length, tag});
}
+ impl_->cv.notify_one();
return true;
}
int DirectFile::wait(Completion* out, int max, int timeout_ms) {
int n = 0;
- while (n < max && !impl_->immediate.empty()) {
- out[n++] = impl_->immediate.front();
- impl_->immediate.pop_front();
+ {
+ std::lock_guard<std::mutex> lk(impl_->mu);
+ while (n < max && !impl_->immediate.empty()) {
+ out[n++] = impl_->immediate.front();
+ impl_->immediate.pop_front();
+ }
}
if (n == max || !is_open()) return n;
OVERLAPPED_ENTRY entries[64];
@@ -161,9 +231,14 @@ int DirectFile::wait(Completion* out, int max, int timeout_ms) {
ULONG got = 0;
const DWORD t = timeout_ms < 0 ? INFINITE : (DWORD) timeout_ms;
if (!GetQueuedCompletionStatusEx(impl_->port, entries, want, &got, n > 0 ? 0 : t, FALSE)) return n;
+ std::lock_guard<std::mutex> lk(impl_->mu);
for (ULONG i = 0; i < got; ++i) {
- if (entries[i].lpOverlapped == nullptr) { // a wake() packet, not a read
- out[n++] = Completion{WAKE_TAG, 0, true};
+ if (entries[i].lpOverlapped == nullptr) { // a wake() packet (or an immediate completion's nudge)
+ while (n < max && !impl_->immediate.empty()) {
+ out[n++] = impl_->immediate.front();
+ impl_->immediate.pop_front();
+ }
+ if (n < max) out[n++] = Completion{WAKE_TAG, 0, true};
continue;
}
Req* r = (Req*) entries[i].lpOverlapped;
@@ -185,12 +260,44 @@ void DirectFile::wake() {
#else
// ------------------------------------------------------------------------------------------------ POSIX
-// Phase L replaces this with io_uring. Until then a read completes inside `submit`, which is correct and
-// keeps the tree compiling on Linux (plan v0.3 section 5.1 rule 4).
+// perf-review F-2: a pool of threads, each doing blocking O_DIRECT preads, so reads run in parallel (the thread
+// count is the queue depth). It replaced one synchronous pread inside `submit`, which read the n-gram table's
+// rows one at a time.
struct DirectFile::Impl {
int fd = -1;
uint64_t size = 0;
+ std::mutex mu;
+ std::condition_variable cv_work, cv_done;
+ std::deque<Pending> queue;
std::deque<Completion> done;
+ bool stop = false;
+ std::vector<std::thread> pool;
+
+ void worker() {
+ std::unique_lock<std::mutex> lk(mu);
+ for (;;) {
+ cv_work.wait(lk, [&] { return stop || !queue.empty(); });
+ if (stop && queue.empty()) return;
+ const Pending p = queue.front();
+ queue.pop_front();
+ lk.unlock();
+ const ssize_t got = pread(fd, p.buffer, p.length, (off_t) p.offset);
+ lk.lock();
+ done.push_back(Completion{p.tag, got < 0 ? 0u : (uint32_t) got, got >= 0});
+ cv_done.notify_all();
+ }
+ }
+
+ void stop_pool() {
+ {
+ std::lock_guard<std::mutex> lk(mu);
+ stop = true;
+ }
+ cv_work.notify_all();
+ for (std::thread& t : pool) t.join();
+ pool.clear();
+ stop = false;
+ }
};
DirectFile::DirectFile() : impl_(new Impl) {}
@@ -203,14 +310,18 @@ bool DirectFile::open(const std::string& path, std::string& err) {
struct stat st;
if (fstat(impl_->fd, &st) != 0) { err = "DirectFile: cannot size " + path; close(); return false; }
impl_->size = (uint64_t) st.st_size;
+ const int n = io_threads(16);
+ for (int i = 0; i < n; ++i) impl_->pool.emplace_back([this] { impl_->worker(); });
return true;
}
void DirectFile::close() {
+ impl_->stop_pool();
if (impl_->fd >= 0) ::close(impl_->fd);
impl_->fd = -1;
impl_->size = 0;
impl_->done.clear();
+ impl_->queue.clear();
}
bool DirectFile::is_open() const { return impl_->fd >= 0; }
@@ -221,14 +332,27 @@ bool DirectFile::submit(uint64_t offset, void* buffer, uint32_t length, uint64_t
err = "DirectFile: unaligned request";
return false;
}
- const ssize_t got = pread(impl_->fd, buffer, length, (off_t) offset);
- impl_->done.push_back(Completion{tag, got < 0 ? 0u : (uint32_t) got, got >= 0});
+ {
+ std::lock_guard<std::mutex> lk(impl_->mu);
+ impl_->queue.push_back(Pending{offset, buffer, length, tag});
+ }
+ impl_->cv_work.notify_one();
return true;
}
-void DirectFile::wake() {} // reads complete inside submit; nothing ever blocks in wait
+void DirectFile::wake() {
+ std::lock_guard<std::mutex> lk(impl_->mu);
+ impl_->done.push_back(Completion{WAKE_TAG, 0, true});
+ impl_->cv_done.notify_all();
+}
-int DirectFile::wait(Completion* out, int max, int) {
+int DirectFile::wait(Completion* out, int max, int timeout_ms) {
+ std::unique_lock<std::mutex> lk(impl_->mu);
+ if (impl_->done.empty() && timeout_ms != 0) {
+ auto ready = [&] { return !impl_->done.empty(); };
+ if (timeout_ms < 0) impl_->cv_done.wait(lk, ready);
+ else impl_->cv_done.wait_for(lk, std::chrono::milliseconds(timeout_ms), ready);
+ }
int n = 0;
while (n < max && !impl_->done.empty()) {
out[n++] = impl_->done.front();
diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp
index 73c43ee80..83ac0b8c3 100644
--- a/src/prefill/prefill.cpp
+++ b/src/prefill/prefill.cpp
@@ -16,6 +16,8 @@
#include "strata/kernels/cvec.hpp"
#include "strata/kernels/kv_q4.hpp"
#include "strata/core/layer.hpp"
+#include "strata/core/native_head.hpp"
+#include "strata/kernels/verify_kernels.hpp"
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/qsa_select.hpp"
#include "strata/prefill/gemm.hpp"
@@ -297,6 +299,9 @@ struct Prefill::Impl {
// layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn)
int device = -1;
float* hand[2] = {};
+ // C-4: the chunk's token ids on the device, for one batched embedding gather
+ int32_t* tok_dev = nullptr;
+ std::vector<int32_t> tok_host;
};
namespace {
@@ -451,6 +456,14 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co
err = "prefill: the layer split's hand-off buffers";
return false;
}
+ if (m.tok_dev == nullptr) {
+ if (cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)) != cudaSuccess) {
+ err = "prefill: the token id buffer";
+ return false;
+ }
+ m.owned.push_back(m.tok_dev);
+ m.tok_host.resize((size_t) chunk);
+ }
if (cudaStreamCreateWithFlags(&m.copy, cudaStreamNonBlocking) != cudaSuccess) { err = "prefill: copy stream"; return false; }
const size_t T = (size_t) chunk;
m.T_max = chunk;
@@ -730,6 +743,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
std::string next_err;
std::future<bool> next_run;
int hand_buf = 0;
+ double host_sync_ms = 0, host_chunk_ms = 0, host_setup_ms = 0; // STRATA_PREFILL_TIMING: the host's share
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
@@ -778,6 +792,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
const int64_t T = std::min(m.T, n - c0), p0 = pos0 + c0;
++stats_.chunks;
pt.mark(kPfStart, cs);
+ const auto tsetup = Clock::now();
// ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the
// previous stage handed on
if (hand_in_ != nullptr) {
@@ -787,7 +802,40 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
return false;
}
}
- for (int64_t t = 0; hand_in_ == nullptr && t < T; ++t) {
+ // C-4: the whole chunk's rows in one gather (the same per-element arithmetic as the per-token path, so the
+ // same bits); a chunk with picture rows, or a token outside the table, takes the per-token path
+ bool batched = hand_in_ == nullptr && m.tok_dev != nullptr;
+ const core::NativeEmbed* nemb = core::native_embed();
+ const core::WeightRef* wemb = nemb ? nullptr : m.wt->find("token_embd.weight");
+ if (batched && nemb == nullptr &&
+ (wemb == nullptr || wemb->codebook_iq4nl || wemb->ne0 != g.n_embd || wemb->group_elems <= 0 ||
+ (wemb->code_bits != 2 && wemb->code_bits != 4 && wemb->code_bits != 8)))
+ batched = false;
+ for (int64_t t = 0; batched && t < T; ++t) {
+ const int64_t tok = tokens[c0 + t];
+ if ((embd_rows && embd_rows[p0 + t]) || tok < 0 || (wemb && tok >= wemb->ne1)) batched = false;
+ else m.tok_host[(size_t) t] = (int32_t) tok;
+ }
+ if (batched) {
+ if (cudaMemcpyAsync(m.tok_dev, m.tok_host.data(), (size_t) T * sizeof(int32_t), cudaMemcpyHostToDevice,
+ m.cs) != cudaSuccess) {
+ err = "prefill: the token id upload failed";
+ return false;
+ }
+ if (nemb) {
+ nemb->gather_dev(m.tok_dev, T, m.emb, m.cs);
+ } else {
+ const auto* codes = (const uint8_t*) wemb->data;
+ const auto* scales = (const float*) (codes + wemb->codes_bytes);
+ const auto* offsets = wemb->has_offset ? (const float*) (codes + wemb->codes_bytes + wemb->scales_bytes)
+ : nullptr;
+ strata::kernels::embedding_gather_dev(codes, scales, offsets, m.tok_dev, (int) T, wemb->ne0,
+ wemb->code_bits, wemb->code_bias, wemb->group_elems,
+ (uint64_t) (wemb->ne0 / (8 / wemb->code_bits)),
+ (uint64_t) (wemb->ne0 / wemb->group_elems), m.emb, m.cs);
+ }
+ }
+ for (int64_t t = 0; hand_in_ == nullptr && !batched && t < T; ++t) {
const float* row = embd_rows ? embd_rows[p0 + t] : nullptr;
if (row) {
if (cudaMemcpyAsync(m.emb + t * N, row, (size_t) N * 4, cudaMemcpyHostToDevice, m.cs) != cudaSuccess) {
@@ -884,6 +932,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
}
};
if (stream_all) issue_until((size_t) m.ring); // layer 0's first experts, behind the embedding and the PLE
+ host_setup_ms += ms_since(tsetup);
for (int64_t l = LB; l < LE; ++l) {
core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still moving
const core::LayerView v(*m.wt, l);
@@ -1403,11 +1452,15 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
}
}
if (on_chunk) {
+ const auto toc = Clock::now();
if (cudaStreamSynchronize(m.cs) != cudaSuccess) {
err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
+ const auto toc2 = Clock::now();
if (!on_chunk(m.R, T, p0, err)) return false;
+ host_sync_ms += std::chrono::duration<double, std::milli>(toc2 - toc).count();
+ host_chunk_ms += ms_since(toc2);
}
}
if (next_run.valid() && !next_run.get()) { err = next_err; return false; }
@@ -1449,6 +1502,9 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
}
std::fprintf(stderr, "strata prefill timing: %lld tokens, GPU timeline %.0f ms, wall %.0f ms, host staging %.0f ms:%s\n",
(long long) n, total, ms_since(t_start), stats_.ms_experts_host, line.c_str());
+ std::fprintf(stderr, "strata prefill timing: host: chunk setup (PLE rows, the expert stream plan) %.0f ms, "
+ "waiting for each chunk %.0f ms, after each chunk (the draft layer, progress) %.0f ms, "
+ "PLE %.0f ms\n", host_setup_ms, host_sync_ms, host_chunk_ms, stats_.ms_ple);
}
if (std::getenv("STRATA_STATE_HASH_GDN") != nullptr) { // debug: the GDN states as the prompt path leaves them
cudaStreamSynchronize(m.cs);