From a3642eb4be7c66d4fe6fb3230797c41114ea37f8 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Mon, 5 Oct 2026 10:28:24 +0200 Subject: [PATCH] F12: one copy_blobs helper for the expert uploads: the PCIe share's and the adaptive refills' copies as one batch. Builds on midhatn's #807 (cudaMemcpyBatchAsync for the verifier's DMA group). dma_batch.hpp now holds one helper, copy_blobs, for independent host-to-device copies on a stream, which the verifier's PCIe share (copy_expert_blobs) and the adaptive tier's refills (both loops of generate.cpp: --serve's main device, the CLI's) use. Changes against the pull request, from the review: mode 0 is the old loop untouched (it never stops the engine: the PR aborted on any copy error, which 0.1.39 ignored); the Windows host alias (cudaHostGetDevicePointer) is looked up once per blob; a batch the runtime refuses is redone as the loop with one warning; HIP, CUDA before 13 and groups over 128 keep the loop; the batch order is the stream's. eddoursul's fork batches the same copies (F12: under WDDM each copy raises an interrupt where it lands, on the processor the GPU's interrupts go to). STRATA_DMA_BATCH is 0 (off) unless set; 1 batches, 2 adds CUDA 13.4's overlap hint. Co-authored-by: midhatn <35053211+midhatn@users.noreply.github.com> Co-authored-by: Eddoursul --- include/strata/core/dma_batch.hpp | 136 +++++++++++++++++++++++------- src/core/verify.cpp | 30 +++---- src/program/generate.cpp | 45 +++++++++- 3 files changed, 161 insertions(+), 50 deletions(-) diff --git a/include/strata/core/dma_batch.hpp b/include/strata/core/dma_batch.hpp index d75cc35d..1a1b47da 100644 --- a/include/strata/core/dma_batch.hpp +++ b/include/strata/core/dma_batch.hpp @@ -1,53 +1,125 @@ #pragma once - +// dma_batch.hpp - independent host-to-device blob copies as one submission: copy_blobs. +// +// The batched path is midhatn's (PR #807, MIT-compatible contribution): cudaMemcpyBatchAsync for independent +// pinned expert uploads on CUDA 13+, with the Windows alias lookup it found necessary. eddoursul's fork (F12) uses +// the same call for the adaptive tier's and the prefetch's copies: under WDDM a copy submitted alone raises an +// interrupt when it lands, on the processor its GPU's interrupts go to; a batch raises one. +// +// Modes (STRATA_DMA_BATCH, read once; `dma_batch_mode()`): +// 0 one cudaMemcpyAsync per blob: exactly the loop the engine always ran +// 1 cudaMemcpyBatchAsync (CUDA 13+, groups of 2..128), the copies in any order, the batch in the stream's +// 2 as 1, plus CUDA 13.4's cudaMemcpyFlagPreferOverlapWithCompute (a hint) +// Every other build (HIP, CUDA before 13) and every single copy or group over 128 takes the loop. A batch the +// runtime refuses is redone as the loop (with one warning), never dropped: readiness is signalled only for +// uploads that were submitted. #include + #include #include #include +#include +#include +#include +#include namespace strata::core { -// Independent immutable host blobs, disjoint device destinations. The caller keeps -// both alive until the stream completes. Ordering with earlier/later stream work -// (including the verifier's completion callback) is unchanged. No extra VRAM. -inline cudaError_t copy_expert_blobs(uint8_t* dst, const uint8_t* const* src, - int n, size_t bytes, cudaStream_t stream, - int batch_mode) { - if (n <= 0) return cudaSuccess; +/// The mode: STRATA_DMA_BATCH (0, 1, 2); unset = the engine's default (`default_mode`, set at the call site's first +/// use; 0 until a measured win makes it 1). +inline int dma_batch_mode(int default_mode = 0) { + static const int mode = [default_mode] { + const char* e = std::getenv("STRATA_DMA_BATCH"); + return e != nullptr && e[0] != '\0' ? std::atoi(e) : default_mode; + }(); + return mode; +} + +namespace detail { + +// A registered Windows host pointer may differ from its device-visible alias; the batch API needs the alias +// (cudaMemcpyAsync(kind=HostToDevice) resolves it itself). The experts' blobs are fixed, so each is looked up once. +inline cudaError_t host_alias(const void* p, const void** out) { + static std::mutex mu; + static std::unordered_map cache; + { + std::lock_guard lk(mu); + const auto it = cache.find(p); + if (it != cache.end()) { *out = it->second; return cudaSuccess; } + } + void* alias = nullptr; + const cudaError_t e = cudaHostGetDevicePointer(&alias, const_cast(p), 0); + if (e != cudaSuccess) return e; + std::lock_guard lk(mu); + cache.emplace(p, alias); + *out = alias; + return cudaSuccess; +} + +} // namespace detail + +/// `n` independent copies, dst[i] <- src[i] (bytes[i] each), on `stream`. The sources are immutable pinned host +/// blobs and the destinations disjoint; the caller keeps them alive until the stream completes. Ordering with +/// earlier and later work on the stream is that of the copies one by one. Returns the first error (the loop +/// continues past none: the first failing copy ends it). +inline cudaError_t copy_blobs(void* const* dst, const void* const* src, const size_t* bytes, size_t n, + cudaStream_t stream, int batch_mode) { + if (n == 0) return cudaSuccess; #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && defined(CUDART_VERSION) && CUDART_VERSION >= 13000 - constexpr int cap = 128; - if (batch_mode && n > 1 && n <= cap) { - std::array dsts{}; + constexpr size_t cap = 128; + if (batch_mode != 0 && n > 1 && n <= cap) { std::array srcs{}; - std::array sizes{}; - for (int i = 0; i < n; ++i) { - dsts[i] = dst + (size_t) i * bytes; - // Registered host VAs may not be device-visible on Windows. Unlike - // cudaMemcpyAsync(kind=HostToDevice), the batch API needs the alias. - void* alias = nullptr; - const auto mapped = cudaHostGetDevicePointer(&alias, (void*) src[i], 0); - if (mapped != cudaSuccess) return mapped; - srcs[i] = alias; - sizes[i] = bytes; - } - cudaMemcpyAttributes attr{}; - attr.srcAccessOrder = cudaMemcpySrcAccessOrderStream; + bool aliased = true; + for (size_t i = 0; i < n; ++i) + if (detail::host_alias(src[i], &srcs[i]) != cudaSuccess) { aliased = false; break; } + if (aliased) { + cudaMemcpyAttributes attr{}; + attr.srcAccessOrder = cudaMemcpySrcAccessOrderStream; #if CUDART_VERSION >= 13040 - if (batch_mode == 2) attr.flags = cudaMemcpyFlagPreferOverlapWithCompute; + if (batch_mode == 2) attr.flags = cudaMemcpyFlagPreferOverlapWithCompute; #endif - size_t first = 0; - return cudaMemcpyBatchAsync(dsts.data(), srcs.data(), sizes.data(), - (size_t) n, &attr, &first, 1, stream); + size_t first = 0; + std::array dsts{}; + std::array sizes{}; + for (size_t i = 0; i < n; ++i) { dsts[i] = dst[i]; sizes[i] = bytes[i]; } + const cudaError_t e = cudaMemcpyBatchAsync(dsts.data(), srcs.data(), sizes.data(), n, &attr, &first, 1, stream); + if (e == cudaSuccess) return cudaSuccess; + static bool warned = false; + if (!warned) { + warned = true; + std::fprintf(stderr, "strata: cudaMemcpyBatchAsync failed (%s); the uploads go one copy at a time\n", + cudaGetErrorString(e)); + } + (void) cudaGetLastError(); + } } #else (void) batch_mode; #endif - for (int i = 0; i < n; ++i) { - const auto e = cudaMemcpyAsync(dst + (size_t) i * bytes, src[i], bytes, - cudaMemcpyHostToDevice, stream); + for (size_t i = 0; i < n; ++i) { + const cudaError_t e = cudaMemcpyAsync(dst[i], src[i], bytes[i], cudaMemcpyHostToDevice, stream); if (e != cudaSuccess) return e; } return cudaSuccess; } -} // namespace strata::core +/// The verifier's form: `n` blobs of `bytes` each into consecutive slots of `dst`. +inline cudaError_t copy_expert_blobs(uint8_t* dst, const uint8_t* const* src, int n, size_t bytes, + cudaStream_t stream, int batch_mode) { + if (n <= 0) return cudaSuccess; + constexpr int cap = 128; + if (batch_mode == 0 || n > cap) { // the old loop, with no staging of its own + for (int i = 0; i < n; ++i) { + const cudaError_t e = cudaMemcpyAsync(dst + (size_t) i * bytes, src[i], bytes, cudaMemcpyHostToDevice, stream); + if (e != cudaSuccess) return e; + } + return cudaSuccess; + } + std::array d{}; + std::array s{}; + std::array b{}; + for (int i = 0; i < n; ++i) { d[i] = dst + (size_t) i * bytes; s[i] = src[i]; b[i] = bytes; } + return copy_blobs(d.data(), s.data(), b.data(), (size_t) n, stream, batch_mode); +} + +} // namespace strata::core diff --git a/src/core/verify.cpp b/src/core/verify.cpp index fcd5c36c..f3365acd 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -1851,21 +1851,21 @@ void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t byt if (n <= 0) { raise_flag(v->h_flagB_, want); return; } v->copy_used_ = true; uint8_t* stage = (uint8_t*) v->sink_.staging; // this group's half in a split window - // Opt-in: combine independent uploads to reduce host API submission overhead. - // The existing stream/callback handshake remains unchanged. Mode 2 also asks - // CUDA 13.4+ to prefer overlap with compute (a driver hint, not a guarantee). - static const int batch_mode = [] { - const char* e = std::getenv("STRATA_DMA_BATCH"); - return e ? std::atoi(e) : 0; - }(); - const auto copied = copy_expert_blobs(stage, src, n, bytes, v->copy_, batch_mode); - if (copied != cudaSuccess) { - // Do not signal readiness for partially submitted uploads. Termination is - // safer than returning an answer with stale expert weights. - std::fprintf(stderr, "strata DMA: expert upload failed: %s\n", cudaGetErrorString(copied)); - std::fflush(stderr); - v->release_gpu_waits(5000); - std::abort(); + // STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync. Mode 0 is + // the loop the engine always ran, errors unchecked (it never stops the engine). A batch mode whose uploads + // cannot be submitted stops the engine: flag B must not release the consumers to expert weights that were never + // copied. + const int batch_mode = strata::core::dma_batch_mode(); + if (batch_mode == 0) { + for (int i = 0; i < n; ++i) cudaMemcpyAsync(stage + (size_t) i * bytes, src[i], bytes, cudaMemcpyHostToDevice, v->copy_); + } else { + const auto copied = strata::core::copy_expert_blobs(stage, src, n, bytes, v->copy_, batch_mode); + if (copied != cudaSuccess) { + std::fprintf(stderr, "strata DMA: expert upload failed: %s\n", cudaGetErrorString(copied)); + std::fflush(stderr); + v->release_gpu_waits(5000); + std::abort(); + } } FlagSet& fs = v->flag_sets_[v->cur_layer_ % (sizeof v->flag_sets_ / sizeof v->flag_sets_[0])]; fs.flag = v->h_flagB_; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index f9296204..d077d639 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -15,6 +15,7 @@ // (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump. #include "strata/core/arch_defaults.hpp" +#include "strata/core/dma_batch.hpp" #include "strata/core/device.hpp" #include "strata/core/remote_expert_opt.hpp" #include "strata/core/expert_cache.hpp" @@ -6752,6 +6753,11 @@ int main(int argc, char** argv) { adapt_fence(); } bool main_live = false; + // STRATA_DMA_BATCH (F12): the main device's copies as one cudaMemcpyBatchAsync (mode 0: one each) + const int dma_mode = multi_gpu ? 0 : strata::core::dma_batch_mode(); + std::vector cp_dst; + std::vector cp_src; + std::vector cp_bytes; for (size_t si = 0; si < swaps.size(); ++si) { const Swap& s = swaps[si]; const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; @@ -6760,6 +6766,16 @@ int main(int argc, char** argv) { const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cache GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr; const strata::core::OnDevice on(gs ? gs->dev : -1); + if (dma_mode != 0 && slot >= 0 && b != nullptr) { + cp_dst.push_back(xcache.device_slot(slot)); + cp_src.push_back(b); + cp_bytes.push_back((size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); + main_live = true; + host_res[out] = strata::core::kNotResident; + srcp->prefetch(s.layer, s.out); + pending.emplace_back((int32_t) in, slot); + continue; + } if (slot < 0 || b == nullptr || adapt_copy_h2d(gs ? gs->cache.device_slot(slot) : xcache.device_slot(slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), @@ -6774,6 +6790,12 @@ int main(int argc, char** argv) { srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead pending.emplace_back((int32_t) in, slot); // resident once the copy has landed } + if (!cp_dst.empty() && strata::core::copy_blobs(cp_dst.data(), cp_src.data(), cp_bytes.data(), cp_dst.size(), + adapt_stream, dma_mode) != cudaSuccess) { + std::fprintf(stderr, "strata serve: adaptive swap copy failed (batched): %s\n", + cudaGetErrorString(cudaGetLastError())); + return false; + } if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); (void) main_live; for (auto& st : stages) @@ -10550,14 +10572,26 @@ int main(int argc, char** argv) { (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); pin_blobs(std::move(spans), pin_live); } + // STRATA_DMA_BATCH (F12): the round's copies as one cudaMemcpyBatchAsync; mode 0 is the loop of one copy each + const int dma_mode = strata::core::dma_batch_mode(); + std::vector cp_dst; + std::vector cp_src; + std::vector cp_bytes; for (const Swap& s : swaps) { const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; const int32_t slot = host_res[out]; const uint8_t* b = srcp->blob(s.layer, s.in); + const size_t blob_n = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer); // asynchronous: the copies run while the MTP drafts; the next window waits for them - if (slot < 0 || b == nullptr || - adapt_copy_h2d(xcache.device_slot(slot), b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), - adapt_stream) != cudaSuccess) { + if (slot < 0 || b == nullptr) { + std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); + return false; + } + if (dma_mode != 0) { + cp_dst.push_back(xcache.device_slot(slot)); + cp_src.push_back(b); + cp_bytes.push_back(blob_n); + } else if (adapt_copy_h2d(xcache.device_slot(slot), b, blob_n, adapt_stream) != cudaSuccess) { std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); return false; } @@ -10565,6 +10599,11 @@ int main(int argc, char** argv) { srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead pending.emplace_back((int32_t) in, slot); // resident once the copy has landed } + if (!cp_dst.empty() && strata::core::copy_blobs(cp_dst.data(), cp_src.data(), cp_bytes.data(), cp_dst.size(), + adapt_stream, dma_mode) != cudaSuccess) { + std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); + return false; + } if (!swaps.empty()) cudaEventRecord(adapt_ev, adapt_stream); if (trace_adapt) std::fprintf(stderr, "strata: ADAPT round=%lld swapped %zu of %d slots, usage decayed\n",