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++
cuda: add opt-in batched expert upload submission (PR #807 by midhatn)
midhatnc8a73fbf9882
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 9728d8f9e..8bb7c8824 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -711,6 +711,16 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)# the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU,# synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906)if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906)+ # Independent pinned expert uploads: byte parity and stream/event ordering.+ add_executable(dma_batch_parity tests/core/dma_batch_parity.cu)+ target_include_directories(dma_batch_parity PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)+ target_link_libraries(dma_batch_parity PRIVATE ${_strata_gpu_runtime_target})+ add_test(NAME dma_batch_parity COMMAND dma_batch_parity)+ set_tests_properties(dma_batch_parity PROPERTIES TIMEOUT 120)+ if(WIN32)+ add_test(NAME dma_batch_registered_parity COMMAND dma_batch_parity --registered)+ set_tests_properties(dma_batch_registered_parity PROPERTIES TIMEOUT 120)+ endif()add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu)target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target})add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity)diff --git a/docs/BATCHED_DMA.md b/docs/BATCHED_DMA.mdnew file mode 100644index 000000000..188049ca8--- /dev/null+++ b/docs/BATCHED_DMA.md@@ -0,0 +1,114 @@+# Batched DMA submission (experimental)++With `--pcie-mode dma`, `STRATA_DMA_BATCH=1` submits a verifier group's independent+expert uploads through `cudaMemcpyBatchAsync` on CUDA 13.0 or later. The default+is `0`, retaining the existing per-expert copies. The normal kernel-copy mode+is unchanged. This is an experiment to reduce host submission overhead, not a+demonstrated increase in model tokens per second.++`STRATA_DMA_BATCH=2` also sets CUDA 13.4's+`cudaMemcpyFlagPreferOverlapWithCompute`. It is a scheduling hint, not a+guarantee of overlap. On CUDA 13.0–13.3 this mode behaves like `1`. Older CUDA+builds and HIP retain individual copies. A single upload or a group larger than+128 also uses individual copies.++The sources must be immutable pinned host blobs, and destinations must be+disjoint. `expert_source.cpp` already restricts the DMA group to pinned experts.+The helper resolves device-visible aliases for registered host allocations;+Windows registered host pointers need not equal their GPU aliases. No extra+VRAM or weight conversion is introduced. All copies remain on the existing+stream, before the callback that signals flag B. A submission error fails the+engine rather than signalling readiness for stale weights.++## Tests++With the normal CUDA build and `STRATA_BUILD_TESTS=ON`:++```sh+cmake --build build --target dma_batch_parity+ctest --test-dir build -R dma_batch --output-on-failure+```++The test checks bytes and cross-stream event ordering for 0, 1, 4, 17, 64, 128,+and 129 uploads, at 37 bytes, 4 KiB and 2 MiB per upload, in all three modes.+Windows also runs the same cases with `VirtualAlloc` plus `cudaHostRegister`.+It prints interleaved diagnostic timings separately for submission and total+transfer time. These times overlap; they must not be added. On Windows it also+reports submitting-thread cycles using `QueryThreadCycleTime`. Cycle counts+are neither whole-process CPU utilization nor an energy measurement.++The 63-case matrix passed with both host allocation methods on CUDA 13.4 and+13.0, and with the individual-copy fallback on CUDA 12.6, all using the same+RTX 4070 Laptop and driver 616.56. This checks the older-toolkit fallback;+it is not a HIP runtime test.++## Initial measurement++RTX 4070 Laptop 8 GB, Ryzen 9 7940HS, 64 GB DDR5-5600, Windows, CUDA 13.4:+16 independent registered-host uploads of 2 MiB each, five measured repetitions+after warmup, alternating mode order:++| Path | Median host submission | Median total transfer |+| --- | ---: | ---: |+| Individual copies | 0.0936 ms | 2.5589 ms |+| Batch | 0.0162 ms | 2.5248 ms |+| Batch with overlap hint | 0.0155 ms | 2.5206 ms |++Batch submission latency fell 82.7%; total transfer latency fell only 1.3%.+Submission latency is measured wall time around the API calls, not whole-process+CPU utilization or energy consumption. The initial full-model screen on Swift+1.5 IQ3_XXS at 64K allocated context did not establish a generation-speed gain:+one coding request measured 30.3 tokens/s with individual DMA and 30.0 with+batching. Its generated lengths differed, so total task times cannot isolate+the transfer change. This evidence does not justify changing the default.++A separate CUDA 13.4 repetition with submitting-thread cycle measurements gave+449,824 cycles for individual copies and 67,939 for the batch, about 84.9% fewer.+Submission wall time was 0.1127 vs 0.0170 ms, while total transfer time was+2.5584 vs 2.5309 ms (about 1.1% lower). These are separate runs from the initial+table, not measurements to combine into a larger speedup.++## Model comparison on the isolated patch++An A-B-B-A comparison used only this patch on v0.1.39, with `--pcie-mode dma`.+Each fresh engine ran the same nine requests, including tool use, prompt reuse+and an independently checked interval-merging implementation. The coding request+used high reasoning, seed 4242, temperature 1, top-p 0.95, top-k 20 and a+3,072-token output limit. Context allocation was 65,536, INT8 KV with 20,480+resident cells, 1,040 cached experts, 7 workers plus the caller, PCIe fraction+0.35, and MTP 5 with English drafting and min-p 0.5.++| Run | Batch mode | Code decode tok/s | Output tokens including reasoning | Request wall time |+| --- | ---: | ---: | ---: | ---: |+| A1 | 0 | 29.7 | 928 | 32.98 s |+| B1 | 1 | 31.4 | 1,478 | 48.86 s |+| B2 | 1 | 30.3 | 1,314 | 45.12 s |+| A2 | 0 | 30.2 | 1,078 | 37.45 s |++All 36 requests passed. All four implementations passed 155 independent cases+and generator, invalid-input and non-mutation checks. Outputs differed even+between the two controls, and draft acceptance also differed. These runs do+not isolate a model speedup or show better time to a verified answer. The+byte-parity tests establish transfer correctness, not deterministic generated+text or general agent reliability.++A fifth run with batching enabled passed the same nine requests plus a+57,750-token prompt, auxiliary-call restoration, and three 1,024-square image+color checks including image-state restoration. An OpenAI-compatible HTTP+smoke request also passed. The long prompt read took 78.414 seconds; restoring+57,745 tokens after the side call reduced prompt processing to 0.301 seconds.+This validates the existing state cache with the patch, not a new cache speedup.+The five clean-patch runs passed 53 recorded requests plus the HTTP check.+Observed free physical VRAM stayed at least 347 MiB via NVML, and available+system RAM stayed above 4.30 GiB. The engine's separate CUDA free-memory warning+reported zero, so the NVML figure must not be read as a verified WDDM budget.+Linux and HIP runtime validation remains untested.++## Design reference++The batching idea follows NVIDIA NCCL's+[copy-engine implementation](https://github.com/NVIDIA/nccl/blob/12df1a11afad322be5a204a2db890161cbf8131d/src/ce_coll.cc)+and the [CUDA `cudaMemcpyBatchAsync` contract](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html).+The helper and tests here are new;+no NCCL source was transplanted. NCCL's multi-GPU performance claims are not+used as predictions for this single-GPU path.diff --git a/include/strata/core/dma_batch.hpp b/include/strata/core/dma_batch.hppnew file mode 100644index 000000000..d75cc35d1--- /dev/null+++ b/include/strata/core/dma_batch.hpp@@ -0,0 +1,53 @@+#pragma once++#include <cuda_runtime.h>+#include <array>+#include <cstddef>+#include <cstdint>++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;+#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<void*, cap> dsts{};+ std::array<const void*, cap> srcs{};+ std::array<size_t, cap> 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;+#if CUDART_VERSION >= 13040+ 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);+ }+#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);+ if (e != cudaSuccess) return e;+ }+ return cudaSuccess;+}++} // namespace strata::corediff --git a/src/core/verify.cpp b/src/core/verify.cppindex 5439d2a7c..fcd5c36cf 100644--- a/src/core/verify.cpp+++ b/src/core/verify.cpp@@ -1,6 +1,7 @@// src/core/verify.cpp - see include/strata/core/verify.hpp.#include "strata/core/verify.hpp"#include "strata/core/remote_expert_opt.hpp"+#include "strata/core/dma_batch.hpp"#if defined(_WIN32)#include <intrin.h>#endif@@ -1850,7 +1851,22 @@ void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytif (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- for (int i = 0; i < n; ++i) cudaMemcpyAsync(stage + (size_t) i * bytes, src[i], bytes, cudaMemcpyHostToDevice, v->copy_);+ // 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();+ }FlagSet& fs = v->flag_sets_[v->cur_layer_ % (sizeof v->flag_sets_ / sizeof v->flag_sets_[0])];fs.flag = v->h_flagB_;fs.value = want;diff --git a/tests/core/dma_batch_parity.cu b/tests/core/dma_batch_parity.cunew file mode 100644index 000000000..489ba5a80--- /dev/null+++ b/tests/core/dma_batch_parity.cu@@ -0,0 +1,107 @@+// Byte parity and event ordering for independent pinned-host expert uploads.+#include "strata/core/dma_batch.hpp"+#include <algorithm>+#include <chrono>+#include <cstdio>+#include <cstring>+#include <vector>+#if defined(_WIN32)+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#endif+#define CK(call) do { auto e=(call); if(e!=cudaSuccess) { \+ std::fprintf(stderr,"%s: %s\n",#call,cudaGetErrorString(e)); return 1; } } while(0)+int main(int argc, char** argv) {+ const bool registered = argc > 1 && !std::strcmp(argv[1], "--registered");+ int runtime=0, driver=0;+ CK(cudaRuntimeGetVersion(&runtime)); CK(cudaDriverGetVersion(&driver));+ std::printf("headers=%d runtime=%d driver=%d registered=%d\n", CUDART_VERSION, runtime, driver, registered);+ constexpr size_t capacity=129u*2u*1024u*1024u;+ uint8_t *host=nullptr,*out=nullptr,*device=nullptr;+#if defined(_WIN32)+ if (registered) {+ host=(uint8_t*)VirtualAlloc(nullptr,capacity,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);+ if (!host) return 3;+ CK(cudaHostRegister(host,capacity,cudaHostRegisterPortable));+ } else+#endif+ CK(cudaMallocHost(&host,capacity));+ CK(cudaMallocHost(&out,capacity));+ CK(cudaMalloc(&device,capacity));+ for(size_t i=0;i<capacity;++i) host[i]=(uint8_t)((i*17+(i>>8)*31+(i>>17))&255);+ cudaStream_t copy,consume; cudaEvent_t ready;+ CK(cudaStreamCreateWithFlags(©,cudaStreamNonBlocking));+ CK(cudaStreamCreateWithFlags(&consume,cudaStreamNonBlocking));+ CK(cudaEventCreateWithFlags(&ready,cudaEventDisableTiming));+ int cases=0;+ for(size_t bytes:{size_t(37),size_t(4096),size_t(2*1024*1024)}) {+ for(int n:{0,1,4,17,64,128,129}) for(int mode:{0,1,2}) {+ std::vector<const uint8_t*> src(n);+ for(int i=0;i<n;++i) src[i]=host+(size_t)((i*37)%129)*bytes;+ std::printf("case mode=%d n=%d bytes=%zu\n",mode,n,bytes); std::fflush(stdout);+ CK(cudaMemsetAsync(device,0xa5,std::max<size_t>(bytes*n,1),copy));+ CK(strata::core::copy_expert_blobs(device,src.data(),n,bytes,copy,mode));+ CK(cudaEventRecord(ready,copy));+ CK(cudaStreamWaitEvent(consume,ready,0));+ CK(cudaMemcpyAsync(out,device,std::max<size_t>(bytes*n,1),cudaMemcpyDeviceToHost,consume));+ CK(cudaStreamSynchronize(consume));+ if(!n && out[0]!=0xa5) return 2;+ for(int i=0;i<n;++i) if(std::memcmp(out+(size_t)i*bytes,src[i],bytes)) {+ std::fprintf(stderr,"mismatch mode=%d n=%d bytes=%zu i=%d\n",mode,n,bytes,i);return 2;+ }+ ++cases;+ }+ }+ std::printf("PASS: %d byte-parity/event-order cases, CUDA %d\n",cases,CUDART_VERSION);+ // Interleaved copy-only diagnostic at representative expert sizes/counts.+ // Host enqueue cost and total wall time are separate, not additive.+ for(int n:{4,16,48}) {+ const size_t bytes=2*1024*1024;+ std::vector<const uint8_t*> src(n);+ for(int i=0;i<n;++i) src[i]=host+(size_t)((i*37)%129)*bytes;+ std::vector<double> wall[3],enqueue[3];+#if defined(_WIN32)+ std::vector<double> cycles[3];+#endif+ for(int rep=0;rep<6;++rep) for(int j=0;j<3;++j) {+ int mode=(rep%2)?2-j:j;+ CK(cudaStreamSynchronize(copy));+#if defined(_WIN32)+ ULONG64 cycle_start=0,cycle_end=0;+ if (!QueryThreadCycleTime(GetCurrentThread(), &cycle_start)) return 3;+#endif+ auto start=std::chrono::steady_clock::now();+ for(int k=0;k<16;++k) CK(strata::core::copy_expert_blobs(device,src.data(),n,bytes,copy,mode));+ auto submitted=std::chrono::steady_clock::now();+#if defined(_WIN32)+ if (!QueryThreadCycleTime(GetCurrentThread(), &cycle_end)) return 3;+#endif+ CK(cudaStreamSynchronize(copy));+ auto end=std::chrono::steady_clock::now();+ if(rep) {+ enqueue[mode].push_back(std::chrono::duration<double,std::milli>(submitted-start).count()/16);+ wall[mode].push_back(std::chrono::duration<double,std::milli>(end-start).count()/16);+#if defined(_WIN32)+ cycles[mode].push_back(double(cycle_end-cycle_start)/16);+#endif+ }+ }+ for(int mode=0;mode<3;++mode) {+ std::sort(wall[mode].begin(),wall[mode].end());std::sort(enqueue[mode].begin(),enqueue[mode].end());+ std::printf("n=%d bytes=%zu mode=%d median_submit_ms=%.4f median_total_ms=%.4f",n,bytes,mode,enqueue[mode][2],wall[mode][2]);+#if defined(_WIN32)+ std::sort(cycles[mode].begin(),cycles[mode].end());+ std::printf(" median_thread_cycles=%.0f",cycles[mode][2]);+#endif+ std::printf("\n");+ }+ }+ CK(cudaEventDestroy(ready)); CK(cudaStreamDestroy(copy)); CK(cudaStreamDestroy(consume));+ CK(cudaFree(device));+#if defined(_WIN32)+ if (registered) { CK(cudaHostUnregister(host)); VirtualFree(host,0,MEM_RELEASE); } else+#endif+ CK(cudaFreeHost(host));+ CK(cudaFreeHost(out));+ return 0;+}