Merge f-143-prefetch: adapt overlap default-on CUDA

This commit is contained in:
Niko1221 committed 2026-10-11 01:49:13 +02:00
commit b5e040da40
7 files changed
+266 -2

No files matched your search

+8
View File
@@ -1669,6 +1669,14 @@ the pairs in which the switched arm won). They are here so you can try them on y
-0.1% (5/6). Boxes that hold all experts in RAM never use the stage buffers.
- **`STRATA_ADAPT_LAG=2`: the adaptive tier's copies are waited for one window later** (#764). Decode, 6 pairs: Tesla P100
(PCIe 3.0 x16) +3.5% (6/6 pairs faster), RTX 5070 +0.2% (4/6), RTX 3060 -1.3% (0/6), so it stays opt-in.
- **`STRATA_ADAPT_OVERLAP` (CUDA: on, `=0` turns it off; HIP: `=1` turns it on): the adaptive tier's copies land while the next
window runs, with the same tokens.** The window takes the swaps at the same moment as with #463's wait (so the same experts run
on the GPU and the CPU in every window), but the copies go in layer order and the verify window holds a layer's plan back
until that layer's copies have landed, instead of the whole window waiting for the round (about 10 ms every fourth window on
an A4000, PCIe 3.0 x16). One GPU, the whole arena in RAM, no `--adapt-async`, `--pipeline-windows`, `STRATA_ADAPT_LAG`,
`STRATA_ADAPT_NOWAIT` or `STRATA_DMA_BATCH`; otherwise the log says why it is off. RTX A4000, 6 interleaved pairs each,
decode median tok/s: Q2_0 16 GB 62.5 -> 66.2 (+5.9%), Q2_0 as a 12 GB card 51.3 -> 54.2 (+5.7%), IQ3_XXS 16 GB 48.6 -> 52.6 (+8.3%),
IQ3_XXS as 12 GB 39.3 -> 41.5 (+5.5%), 6/6 pairs faster every time.
## Thread placement: `--aux-cpus` (Linux, off by default)
+8
View File
@@ -613,6 +613,12 @@ public:
void prepare_overrides() { if (override_.empty()) override_.assign((size_t) blobs_, nullptr); }
/// After the GPU copies of every staged swap have landed. Returns how many exchanges were applied.
int64_t commit_exchanges();
/// 0.1.43 (STRATA_ADAPT_OVERLAP): BEFORE the GPU copies of the staged swaps have landed, make each staged `out` look to the
/// planner as it will after `commit_exchanges` (pinned, with a device alias into its exchange buffer, so the PCIe share
/// treats it exactly as a committed one) without touching `in`'s place, which the copy still reads. `commit_exchanges`
/// (after the copies have landed) ends it. False: not possible here (rotation, exchange buffers not page-locked): the
/// caller waits for the copies instead.
bool soft_commit_exchanges();
/// `commit_exchanges` in two halves, for the asynchronous adaptive tier (--adapt-async): `commit_copies` moves
/// every staged evicted blob into its `in`'s place in the copy (on another thread: safe once nothing computes `in`
/// from RAM - it is resident on the GPU - while `out` is still read from its exchange buffer), then `commit_flip`
@@ -865,6 +871,8 @@ private:
std::vector<const uint8_t*> override_; ///< staged exchanges: an evicted expert read from its exchange buffer
struct Exchange { size_t in, out; int64_t q; uint64_t bytes; };
std::vector<Exchange> staged_;
std::vector<size_t> soft_in_; ///< soft_commit_exchanges: per `out` index, the `in` whose place it will take (SIZE_MAX: none)
const uint8_t* xstage_dev_ = nullptr; ///< the exchange buffers' device alias (soft_commit_exchanges)
uint8_t* xstage_ = nullptr; ///< exchange buffers, `xstage_cap_ x xstage_blob_`
bool xstage_pinned_ = false;
int64_t xstage_cap_ = 0;
+22
View File
@@ -39,6 +39,18 @@
namespace strata::core {
/// 0.1.43 (STRATA_ADAPT_OVERLAP): the adaptive tier's copies still landing while a decode window runs. The window's
/// residency tables are the baseline's (the swapped-in experts are resident from the window's first layer), but their
/// bytes arrive layer by layer: `run` holds a layer's plan (the first thing that lets the GPU read the layer's expert
/// slots) back until `landed >= layer` for a layer with a swap (`has[layer]`). Set `active` only around one window.
struct AdaptGate {
struct Tick { AdaptGate* gate; int32_t layer; };
std::atomic<int32_t> landed{-1}; ///< the highest layer whose swap copies have landed (n_layers: all of them)
std::atomic<bool> active{false};
std::vector<uint8_t> has; ///< per layer: a swap copies into this layer's slots
std::vector<Tick> ticks; ///< host-function contexts, one per layer and the final one (stable storage)
};
class NativeHead;
class RemoteExpertOpt;
@@ -216,6 +228,14 @@ public:
/// expert evicted on the host (the pool then computes it on the CPU) before the device table follows. Also turns
/// the device-planned layers (E-6) off. Before `init`.
void set_always_publish(bool on) { always_publish_ = on; }
/// 0.1.43: the adaptive tier's overlap gate (see AdaptGate). Refused (false) with the device-planned layers (E-6),
/// which never ask the host. The pointer must outlive the verifier's windows.
bool set_adapt_gate(AdaptGate* g) {
if (g != nullptr && device_plan_) return false;
adapt_gate_ = g;
return true;
}
double ms_gate = 0; ///< host time spent holding a layer's plan for the adaptive copies (decode timing prints it)
cudaStream_t stream() const { return cs_; }
int device() const { return device_; }
/// Capture every window size and the commit graph now (a capture syncs the stream: never with a window in flight).
@@ -321,6 +341,8 @@ private:
// pipelined windows (pl_launch ...)
cudaStream_t ext_stream_ = nullptr; ///< set_stream: the stage's shared stream (not destroyed here)
bool always_publish_ = false;
bool adapt_gate_wait(int32_t layer, std::string& err);
AdaptGate* adapt_gate_ = nullptr; ///< 0.1.43: STRATA_ADAPT_OVERLAP's gate (null: off)
void pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]);
cudaEvent_t ev_done_ = nullptr, ev_commit_ = nullptr;
unsigned long long* prof_pin_ = nullptr; ///< pinned host copy of the stamps (pipelined windows)
+23 -2
View File
@@ -3303,8 +3303,24 @@ bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, in
return true;
}
bool FileExpertSource::soft_commit_exchanges() {
if (staged_.empty()) return true;
if (exchange_storage_.active() || !xstage_pinned_ || xstage_ == nullptr || !complement_pinned_ || complement_device_ == nullptr)
return false;
if (xstage_dev_ == nullptr) {
void* d = nullptr;
if (cudaHostGetDevicePointer(&d, xstage_, 0) != cudaSuccess || d == nullptr) { (void) cudaGetLastError(); return false; }
xstage_dev_ = (const uint8_t*) d;
}
if (soft_in_.empty()) soft_in_.assign((size_t) blobs_, SIZE_MAX);
for (const Exchange& x : staged_) soft_in_[x.out] = x.in;
return true;
}
int64_t FileExpertSource::commit_exchanges() {
int64_t n = 0;
for (const Exchange& x : staged_)
if (!soft_in_.empty()) soft_in_[x.out] = SIZE_MAX;
for (const Exchange& x : staged_) {
const uint8_t* src = override_[x.out];
if (exchange_storage_.active()) {
@@ -3432,16 +3448,21 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {
layer >= n_layers_ || expert >= n_expert_) return false;
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
if (exchange_storage_.active()) return exchange_storage_.resident(index).host != nullptr;
if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false;
// soft_commit_exchanges: a staged `out` is judged by the place it will take (`in`'s), as after the commit
const size_t at_index = !soft_in_.empty() && soft_in_[index] != SIZE_MAX ? soft_in_[index] : index;
if (at_index >= complement_offsets_.size() || complement_offsets_[at_index] == kNoComplement) return false;
// a partial pin (CS-T): only the registered prefix
return !complement_partial_ ||
complement_offsets_[index] + layer_blob_bytes_[(size_t) layer] <= complement_pin_limit_;
complement_offsets_[at_index] + layer_blob_bytes_[(size_t) layer] <= complement_pin_limit_;
}
const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const {
if (!pinned(layer, expert) || complement_device_ == nullptr) return nullptr;
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
if (exchange_storage_.active()) return exchange_storage_.resident(index).device;
if (!soft_in_.empty() && soft_in_[index] != SIZE_MAX) // soft_commit_exchanges: out is read from its exchange buffer
return override_.empty() || override_[index] == nullptr || xstage_dev_ == nullptr
? nullptr : xstage_dev_ + (size_t) (override_[index] - xstage_);
return complement_device_ + (size_t) complement_offsets_[index];
}
+24
View File
@@ -1969,6 +1969,24 @@ void Verifier::accumulate_profile(const unsigned long long* stamps) {
++prof_windows_;
}
// 0.1.43 (STRATA_ADAPT_OVERLAP): hold the host until the adaptive tier's copies up to `layer` have landed. The wait
// is a spin on an atomic the copy stream's host functions raise (no driver call here); 20 s is the window's own limit.
bool Verifier::adapt_gate_wait(int32_t layer, std::string& err) {
const Clock::time_point t0 = Clock::now();
uint32_t spins = 0;
while (adapt_gate_->landed.load(std::memory_order_acquire) < layer) {
_mm_pause();
if ((++spins & 1023u) != 0) continue;
if (Clock::now() - t0 > std::chrono::seconds(20)) {
err = "verify: the adaptive tier's copies for layer " + std::to_string(layer) + " never landed" +
released_note(release_gpu_waits(5000));
return false;
}
}
ms_gate += ms_since(t0);
return true;
}
bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, void* user, int32_t* out,
std::string& err) {
using namespace strata::kernels;
@@ -2002,6 +2020,9 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
ms_host += ms_since(t0);
VDBG("staged; launching\n");
if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0;
// 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first
if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() &&
!adapt_gate_wait((int32_t) g.n_layers, err)) return false;
const cudaError_t le = cudaGraphLaunch(ar_off_ ? exec_nr_[T] : exec_[T], cs_);
trace_ev("LAUNCHED", -1, -1, (int64_t) le);
if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; }
@@ -2065,6 +2086,9 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
const Clock::time_point b = Clock::now();
if (g_trace) trace_ev("RANG", k, l, (int64_t) std::chrono::duration_cast<std::chrono::microseconds>(b - a).count());
VDBG("layer %lld rang\n", (long long) l);
if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && l >= 0 &&
(size_t) l < adapt_gate_->has.size() && adapt_gate_->has[(size_t) l] != 0 &&
!adapt_gate_wait((int32_t) l, err)) return false;
cur_layer_ = want - 1;
set_plan_slot(grp);
const int tb = gtb[grp], n = gte[grp] - gtb[grp];
+99
View File
@@ -1320,6 +1320,23 @@ int adapt_lag() {
return v;
}
/// 0.1.43 STRATA_ADAPT_OVERLAP=1: the adaptive tier's copies land while the next decode window already runs. The window
/// sees the swapped-in experts as resident from its first layer, exactly as after #463's wait (so the tokens are the same
/// ones); what changes is only when the bytes arrive: the copies go in layer order and the verify window holds a layer's
/// plan back until that layer's copies have landed (AdaptGate in strata/core/verify.hpp). The ~10 ms a 96-swap round
/// took at the next window's start (PCIe 3.0 x16, Q2_0) is then hidden behind the window. On for CUDA (=0 turns it off), opt-in on HIP.
bool adapt_overlap() {
static const bool v = [] {
const char* e = std::getenv("STRATA_ADAPT_OVERLAP");
#if defined(STRATA_USE_HIP)
return e && e[0] == '1'; // HIP: not measured yet, opt-in
#else
return !(e && e[0] == '0'); // CUDA: on since 0.1.43 (same tokens, +5.5..8.3% decode on an A4000); =0 turns it off
#endif
}();
return v;
}
/// --adapt-async: one background job at a time (the asynchronous adaptive tier's copies and memcpys). `post` hands
/// it over, `idle` says whether it has finished; the owner never posts while a job runs.
class JobThread {
@@ -2925,6 +2942,7 @@ int main(int argc, char** argv) {
(unsigned long long) (total_b >> 20));
return 1;
}
mem_mark("the CUDA context and the weight arena");
auto load_t0 = std::chrono::steady_clock::now();
auto load_s = [&] {
const auto t = std::chrono::steady_clock::now();
@@ -2940,6 +2958,7 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: %llu MiB of weights loaded from %s in %.1f s (%zu canonical tensors "
"skipped: served natively)\n",
(unsigned long long) (pool_bytes >> 20), o.pack.c_str(), load_s(), skip.size());
mem_mark("the pack weights");
strata::core::NativeDense native_dense;
if (!o.native_dense_gguf.empty()) {
@@ -4162,6 +4181,7 @@ int main(int argc, char** argv) {
(unsigned long long) ple_table.rows(), o.ple_gguf.c_str());
}
}
mem_mark("the session (KV, GDN state, PLE history)");
for (size_t i = 0; i < stages.size(); ++i) {
GpuStage& st = *stages[i];
const strata::core::OnDevice on(st.dev);
@@ -4392,6 +4412,7 @@ int main(int argc, char** argv) {
std::chrono::duration<double>(std::chrono::steady_clock::now() - head_t0).count());
}
std::vector<float> logits((size_t) n_vocab);
mem_mark("the native head");
float* d_logits = nullptr;
if (cudaMalloc(&d_logits, (size_t) n_vocab * 4) != cudaSuccess) {
(void) cudaGetLastError();
@@ -8137,6 +8158,40 @@ int main(int argc, char** argv) {
std::vector<void*> pin_live; // the swaps' locked arena pages (pin_blob), unlocked once they have landed
cudaEvent_t adapt_ev = nullptr;
cudaEventCreateWithFlags(&adapt_ev, cudaEventDisableTiming);
// 0.1.43 STRATA_ADAPT_OVERLAP=1 (adapt_overlap above): the single-GPU, plain-RAM-arena decode loop only
strata::core::AdaptGate agate;
bool aflipped = false; // the pending swaps are in the tables and their copies may still be landing
bool aov = false;
int64_t aov_flips = 0;
if (adapt_overlap()) {
const char* why = multi_gpu || !stages.empty() ? "not on a layer split"
: peer.valid() ? "not with --peer-device"
: remote_opt ? "not with --remote-expert-opt"
: o.adapt_async ? "not with --adapt-async"
: o.pipeline_windows > 0 ? "not with --pipeline-windows"
: pin_blobs_on() ? "not with page-locked swap sources"
: strata::core::dma_batch_mode() != 0 ? "not with STRATA_DMA_BATCH"
: adapt_lag() != 1 || adapt_nowait() ? "not with STRATA_ADAPT_LAG / STRATA_ADAPT_NOWAIT"
// the resident RAM mode is exact too (soft_commit_exchanges) but not a win everywhere: RTX A4000 +7.0%
// (5/5 pairs), RTX 3060 on a 46 GB box -2.6% (0/5; the CPU experts and the copies share the RAM bandwidth)
: src.complement_ready() && !(std::getenv("STRATA_ADAPT_OVERLAP_RESIDENT") &&
std::getenv("STRATA_ADAPT_OVERLAP_RESIDENT")[0] == '1')
? "not in the resident RAM mode unless STRATA_ADAPT_OVERLAP_RESIDENT=1"
: drive.d.usage.empty() ? "the adaptive tier is off"
: nullptr;
if (why == nullptr) {
agate.ticks.resize((size_t) g.n_layers + 1);
for (int64_t l = 0; l <= g.n_layers; ++l) agate.ticks[(size_t) l] = {&agate, (int32_t) l};
agate.has.assign((size_t) g.n_layers, 0);
if (!ver.set_adapt_gate(&agate)) why = "the device-planned layers (STRATA_VERIFY_DEVICE_PLAN) are on";
}
aov = why == nullptr;
if (aov)
std::fprintf(stderr, "strata serve: adaptive overlap (STRATA_ADAPT_OVERLAP=0 turns it off): the adaptive tier's copies land while the next window runs "
"(same tokens, a layer waits for its own copies)\n");
else if (std::getenv("STRATA_ADAPT_OVERLAP") != nullptr) // quiet when it was only the default
std::fprintf(stderr, "strata serve: STRATA_ADAPT_OVERLAP=1 is off: %s\n", why);
}
// a layer split's later stages keep a copy of the residency table on their devices, and swap on their own
auto res_upload = [&]() {
if (d_res != nullptr)
@@ -8165,6 +8220,8 @@ int main(int argc, char** argv) {
}
pending.clear();
pending_age = 0;
agate.active.store(false, std::memory_order_release); // 0.1.43: the copies have landed (STRATA_ADAPT_OVERLAP)
aflipped = false;
res_upload();
};
// --pipeline-windows: set while the tier adapts beside windows in flight (see its use in adapt)
@@ -8197,6 +8254,12 @@ int main(int argc, char** argv) {
}
std::sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.gain > b.gain; });
if ((int) swaps.size() > o.adapt_swaps) swaps.resize((size_t) o.adapt_swaps);
if (aov) { // 0.1.43: the copies go in layer order and each layer's landing is told to the verify window
std::stable_sort(swaps.begin(), swaps.end(), [](const Swap& a, const Swap& b) { return a.layer < b.layer; });
agate.landed.store(-1, std::memory_order_release);
agate.has.assign((size_t) g.n_layers, 0);
for (const Swap& s : swaps) agate.has[(size_t) s.layer] = 1;
}
// the copies back read the cache of the card that owns each layer (see resident_stage_swaps)
auto home_of = [&](int64_t layer) -> SwapHome {
const int stn = multi_gpu ? stage_of(layer) : 0;
@@ -8237,6 +8300,13 @@ int main(int argc, char** argv) {
std::vector<size_t> cp_bytes;
for (size_t si = 0; si < swaps.size(); ++si) {
const Swap& s = swaps[si];
if (aov && (si == 0 || swaps[si - 1].layer != s.layer)) {
// test hook (STRATA_ADAPT_OVERLAP_SLOW_US=N): a slow link, to make the windows wait for the copies
static const int slow_us = [] { const char* e = std::getenv("STRATA_ADAPT_OVERLAP_SLOW_US"); return e ? std::atoi(e) : 0; }();
static int slow_arg = slow_us;
if (slow_us > 0)
cudaLaunchHostFunc(adapt_stream, [](void* p) { std::this_thread::sleep_for(std::chrono::microseconds(*(int*) p)); }, &slow_arg);
}
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 = fenced_slots.empty() ? host_res[out] : fenced_slots[si];
const uint8_t* b = srcp->blob_stable(s.layer, s.in);
@@ -8266,6 +8336,16 @@ int main(int argc, char** argv) {
host_res[out] = strata::core::kNotResident; // evicted now: the CPU computes it meanwhile
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 (aov && (si + 1 == swaps.size() || swaps[si + 1].layer != s.layer) &&
cudaLaunchHostFunc(adapt_stream, [](void* p) {
auto* t = (strata::core::AdaptGate::Tick*) p;
int32_t cur = t->gate->landed.load(std::memory_order_relaxed);
while (cur < t->layer && !t->gate->landed.compare_exchange_weak(cur, t->layer, std::memory_order_release)) {}
}, &agate.ticks[(size_t) s.layer]) != cudaSuccess) {
(void) cudaGetLastError();
cudaStreamSynchronize(adapt_stream); // no callback: wait here, the gate opens at once
agate.landed.store((int32_t) g.n_layers, std::memory_order_release);
}
}
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) {
@@ -11591,6 +11671,21 @@ int main(int argc, char** argv) {
// expert ran on the GPU or the CPU (they round differently) depended on the copy's timing
// (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B)
if (adapt_nowait()) apply_pending(false);
else if (aov && !pending.empty() && !aflipped) {
// 0.1.43 STRATA_ADAPT_OVERLAP: the tables take the swaps now, exactly where the wait would have ended;
// the copies still landing are waited for per layer inside the window (AdaptGate)
// (resident RAM mode: the staged evicted experts look committed to the planner at once, the RAM
// copy's places stay as they are until the copies have landed; see soft_commit_exchanges)
if (src.complement_ready() && !src.soft_commit_exchanges()) {
apply_pending(true); // not possible here: the plain wait
} else {
for (const auto& [i, slot] : pending) host_res[(size_t) i] = slot;
res_upload();
aflipped = true;
++aov_flips;
agate.active.store(true, std::memory_order_release);
}
}
else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true);
if (!adapt_tick(false)) { // --adapt-async: the round in flight moves on a step when it can
std::printf("ERR an adaptive refill failed\n");
@@ -11622,6 +11717,7 @@ int main(int argc, char** argv) {
std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str());
return 1;
}
if (aflipped) apply_pending(true); // 0.1.43: every layer's copies were waited for in the window; the bookkeeping now
// Diagnostics (as in generate): STRATA_DUMP_FIRST_LOGITS=<path> writes the logits of each request's first
// window to <path>.<n>, so the prompt paths (a peer card's share, a split) can be compared by KL
if (first_window) {
@@ -11740,6 +11836,9 @@ int main(int argc, char** argv) {
(d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w,
(d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L),
(d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L));
if (aov)
std::fprintf(stderr, "strata decode adapt overlap: %lld windows took swaps still landing, a layer waited %.2f ms in all so far\n",
(long long) aov_flips, ver.ms_gate);
for (int st = 0; st < n_stages; ++st) { // every stage's GPU profile, not only the first card's
const std::string pr = stage_ver(st).profile_report();
if (pr.empty()) continue;
+82
View File
@@ -0,0 +1,82 @@
// 0.1.43 5.2: do two streams move host->device data faster than one (both copy engines)? And what does one layer's
// worth of expert-sized copies cost end to end (issue, copy, host function, sync)?
// nvcc -O2 -o h2d_bench tools/h2d_bench.cu && ./h2d_bench [device]
#include <cuda_runtime.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <vector>
#define CK(x) do { cudaError_t e = (x); if (e != cudaSuccess) { std::printf("%s:%d %s\n", __FILE__, __LINE__, cudaGetErrorString(e)); std::exit(1); } } while (0)
using Clock = std::chrono::steady_clock;
static double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
int main(int argc, char** argv) {
int dev = argc > 1 ? std::atoi(argv[1]) : 0;
CK(cudaSetDevice(dev));
cudaDeviceProp p;
CK(cudaGetDeviceProperties(&p, dev));
std::printf("%s asyncEngineCount=%d\n", p.name, p.asyncEngineCount);
const size_t blob = 1382400; // a Q2_0 expert
const size_t nb = 256; // blobs in the arena
const size_t arena_bytes = nb * blob;
uint8_t* host = nullptr;
// like the engine's arena: plain pages registered with cudaHostRegister (PORTABLE)
host = (uint8_t*) aligned_alloc(2 << 20, (arena_bytes + (2 << 20) - 1) / (2 << 20) * (2 << 20));
for (size_t i = 0; i < arena_bytes; i += 4096) host[i] = (uint8_t) i;
CK(cudaHostRegister(host, arena_bytes, cudaHostRegisterPortable));
uint8_t* dbuf;
CK(cudaMalloc(&dbuf, 2 * 64 * blob));
cudaStream_t s[2];
for (int i = 0; i < 2; ++i) CK(cudaStreamCreateWithFlags(&s[i], cudaStreamNonBlocking));
// 1. throughput: N blobs, one stream vs two streams (alternate blobs)
for (int nstreams = 1; nstreams <= 2; ++nstreams) {
double best = 1e9;
for (int rep = 0; rep < 7; ++rep) {
auto t0 = Clock::now();
for (size_t i = 0; i < nb; ++i) CK(cudaMemcpyAsync(dbuf + (i % 64) * blob, host + i * blob, blob, cudaMemcpyHostToDevice, s[i % nstreams]));
for (int i = 0; i < nstreams; ++i) CK(cudaStreamSynchronize(s[i]));
best = std::min(best, ms_since(t0));
}
std::printf("throughput %d stream(s): %.3f ms for %zu blobs = %.2f GB/s\n", nstreams, best, nb, arena_bytes / best / 1e6);
}
// 1b. the same with each stream copying one big contiguous range
for (int nstreams = 1; nstreams <= 2; ++nstreams) {
double best = 1e9;
for (int rep = 0; rep < 7; ++rep) {
auto t0 = Clock::now();
size_t half = 64 * blob / nstreams;
for (int i = 0; i < nstreams; ++i) CK(cudaMemcpyAsync(dbuf + i * half, host + i * half, half, cudaMemcpyHostToDevice, s[i]));
for (int i = 0; i < nstreams; ++i) CK(cudaStreamSynchronize(s[i]));
best = std::min(best, ms_since(t0));
}
std::printf("big range %d stream(s): %.3f ms for %zu bytes = %.2f GB/s\n", nstreams, best, 64 * blob, 64 * blob / best / 1e6);
}
// 2. per-layer latency: k blobs, then a host function, then wait for it (the engine's flag B)
for (int k : {1, 2, 4, 8, 16}) {
for (int nstreams = 1; nstreams <= 2; ++nstreams) {
std::vector<double> v;
for (int rep = 0; rep < 200; ++rep) {
static volatile int flag;
flag = 0;
auto t0 = Clock::now();
for (int i = 0; i < k; ++i) CK(cudaMemcpyAsync(dbuf + i * blob, host + ((rep * 13 + i * 7) % nb) * blob, blob, cudaMemcpyHostToDevice, s[i % nstreams]));
if (nstreams == 2) {
cudaEvent_t ev;
CK(cudaEventCreateWithFlags(&ev, cudaEventDisableTiming));
CK(cudaEventRecord(ev, s[1]));
CK(cudaStreamWaitEvent(s[0], ev, 0));
CK(cudaEventDestroy(ev));
}
CK(cudaLaunchHostFunc(s[0], [](void*) { flag = 1; }, nullptr));
while (!flag) {}
v.push_back(ms_since(t0));
}
std::sort(v.begin(), v.end());
std::printf("layer of %2d blobs, %d stream(s): median %.3f ms min %.3f p90 %.3f (ideal at 11 GB/s %.3f)\n", k, nstreams, v[v.size() / 2], v[0], v[v.size() * 9 / 10], k * blob / 11e6);
}
}
return 0;
}