diff --git a/CMakeLists.txt b/CMakeLists.txt index 0edf2b02eb..3595219ff0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -415,6 +415,11 @@ if(STRATA_BUILD_TESTS) target_include_directories(timer_marks_test PRIVATE include) add_test(NAME timer_marks_test COMMAND timer_marks_test) + # PR #4844: the adaptive tier's copy-in range across serial, pipelined and drained rounds (header-only, no GPU) + add_executable(adaptive_range_test tests/program/adaptive_range_test.cpp) + target_include_directories(adaptive_range_test PRIVATE include) + add_test(NAME adaptive_range_test COMMAND adaptive_range_test) + # the Windows HIP auto prefill chunk cap (#1630) and the commit-limit verdict (#1607): header-only, no GPU add_executable(host_limits_test tests/platform/host_limits_test.cpp) target_include_directories(host_limits_test PRIVATE include) @@ -1377,6 +1382,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) 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) + # PR #5096: flag B stays behind queued copies (delayed host-function copy, a consumer kernel, graph replay, every device) + add_executable(flag_order_test tests/core/flag_order_test.cu) + target_include_directories(flag_order_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(flag_order_test PRIVATE ${_strata_gpu_runtime_target} Threads::Threads) + add_test(NAME flag_order_test COMMAND flag_order_test) + set_tests_properties(flag_order_test PROPERTIES TIMEOUT 60) if(WIN32) add_test(NAME dma_batch_registered_parity COMMAND dma_batch_parity --registered) set_tests_properties(dma_batch_registered_parity PROPERTIES TIMEOUT 120) diff --git a/include/strata/core/flag_order.hpp b/include/strata/core/flag_order.hpp new file mode 100644 index 0000000000..93c28f1290 --- /dev/null +++ b/include/strata/core/flag_order.hpp @@ -0,0 +1,59 @@ +// include/strata/core/flag_order.hpp - flag B is raised behind the copies queued before it (PR #5096, @AlanJager). +// +// Flag B tells the graph that a layer's PCIe experts have landed in staging. It is one counter that only rises, and the +// graph waits for "flag B >= layer + 1". A non-empty plan raises it from a host function on the copy stream, so it +// rises after that plan's copies. An empty plan used to raise it on the spot, even when the copy stream still held an +// earlier layer's (or the other token group's) uploads: the counter jumped past a layer whose bytes had not landed, and +// the graph read a half-written staging slot. raise_flag_b_ordered() keeps the counter behind every copy queued on the +// stream, and raises it directly only when nothing was queued in this window. The plain raise is shared with Verifier. +#pragma once + +#include + +#include +#if defined(_WIN32) +#include +#endif + +namespace strata::core { + +/// Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly. +inline void flag_raise_max(uint32_t* flag, uint32_t value) { +#if defined(_WIN32) + volatile long* f = (volatile long*) flag; + long cur = *f; + while ((uint32_t) cur < value) { + const long prev = _InterlockedCompareExchange(f, (long) value, cur); + if (prev == cur) break; + cur = prev; + } +#else + uint32_t cur = __atomic_load_n(flag, __ATOMIC_SEQ_CST); + while (cur < value && !__atomic_compare_exchange_n(flag, &cur, value, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {} +#endif +} + +/// The argument of the host function (it must outlive the call: it lives in the Verifier's table). +struct FlagRaise { + uint32_t* flag; + uint32_t value; +}; + +/// Raise `flag` to `value` once every copy queued so far on `copy` has landed. `copies_queued` is false when nothing was +/// queued on the stream since it was last drained: then there is nothing to wait for and the flag rises at once. +/// Returns the launch status (cudaSuccess when the flag was raised directly). On a failure the flag has NOT been raised: +/// the caller must not release the consumers (Verifier::fetch_dma stops the engine). +inline cudaError_t raise_flag_b_ordered(bool copies_queued, cudaStream_t copy, FlagRaise* slot, uint32_t* flag, uint32_t value) { + if (!copies_queued || copy == nullptr) { + flag_raise_max(flag, value); + return cudaSuccess; + } + slot->flag = flag; + slot->value = value; + return cudaLaunchHostFunc(copy, [](void* p) { + FlagRaise* s = (FlagRaise*) p; + flag_raise_max(s->flag, s->value); + }, slot); +} + +} // namespace strata::core diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 258ba76e34..d8d4be66b2 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -24,6 +24,7 @@ #include #include "strata/core/expert_source.hpp" +#include "strata/core/flag_order.hpp" #include "strata/core/layer.hpp" #include "strata/core/session.hpp" #include "strata/kernels/sampler.hpp" @@ -701,10 +702,12 @@ private: cudaEvent_t commit_done_ = nullptr; // recorded after an async commit (set_commit_async); see wait_commit bool commit_pending_ = false; cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts) - struct FlagSet { uint32_t* flag; uint32_t value; }; + using FlagSet = strata::core::FlagRaise; FlagSet flag_sets_[2 * 64 * 2] = {}; // host-function arguments, one per (layer, group) static void fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes); static void raise_flag(uint32_t* flag, uint32_t value); + /// Flag B for `want`, behind every copy queued on copy_ (an empty plan must not overtake an earlier layer's DMA). + void raise_flag_b_ordered(uint32_t want); int32_t* h_plan_ = nullptr; int32_t* m_plan_ = nullptr; // counts | start | dst | tok | ptr (as int32 pairs) int64_t plan_i32_ = 0; // int32 words in the plan block GpuPlanSink sink_; diff --git a/include/strata/program/adaptive_range.hpp b/include/strata/program/adaptive_range.hpp new file mode 100644 index 0000000000..1bc0b4b264 --- /dev/null +++ b/include/strata/program/adaptive_range.hpp @@ -0,0 +1,47 @@ +// include/strata/program/adaptive_range.hpp - which swaps of an adaptive-tier round have had their copy in (PR #4844, @uvlad23). +// +// A round of the adaptive tier moves a list of swaps (aswaps) into the GPU expert caches. Step 2 copies them in, step 3 +// marks the ones that landed as resident. On the serial loop the copies go in batches (the arena may cap one), and step 3 +// marks the batch that just landed, [lo, hi). On the pipelined loop every swap is copied at its card's next gap and +// step 3 marks the whole list. Which loop runs is decided per tick: the pipelined loop can drain after step 2 has been +// planned, and the next tick then takes step 3 on the serial rule. lo/hi/bi then still named the last batch of an earlier +// round, so step 3 marked only that range and every other swap of the round was lost (its slot held the new expert, the +// table still said the old one). The pipelined plan therefore sets the range to the whole round. Plain arithmetic, so a +// host test can walk the rounds without a GPU. +#pragma once + +#include +#include + +namespace strata::program { + +struct AdaptiveCopyRange { + size_t lo = 0, hi = 0; ///< the batch being copied in / just landed + size_t bi = 0; ///< where the next batch starts + + void clear() { lo = hi = bi = 0; } + + /// Serial loop, step 2: the next batch is [bi, bi + batch) of `total` swaps (all the rest when batch == 0, the arena's + /// cap otherwise). Never past `total`, and an overflowing sum is the end. + void next_batch(size_t total, size_t batch) { + lo = std::min(bi, total); + hi = total; + if (batch > 0 && batch < total - lo) hi = lo + batch; + bi = hi; + } + + /// Pipelined loop, step 2: the whole round is one batch, whatever an earlier round left here. + void whole_round(size_t total) { + lo = 0; + hi = bi = total; + } + + /// Step 3 on the serial rule: more batches of the round still to copy in. + bool more(size_t total) const { return bi < total; } + + /// Step 3: the swaps that landed. `pipelined` is this tick's rule; the range is the whole round on that one. + size_t landed_begin(bool pipelined) const { return pipelined ? 0 : lo; } + size_t landed_end(bool pipelined, size_t total) const { return pipelined ? total : hi; } +}; + +} // namespace strata::program diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 47977c15b5..93cbe403d7 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -3506,7 +3506,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, sink_.start2[0] = 0; std::atomic_thread_fence(std::memory_order_seq_cst); *(volatile uint32_t*) h_flagA_ = want; - raise_flag(h_flagB_, want); + raise_flag_b_ordered(want); // behind any copy still queued from an earlier layer } // Layer 1's pre(1, 0) copies h_ple_ -> ple_ after Layer 0's wait_flag_ge(m_flag_, 1). // By collecting PLE here at k == 0 (after publishing flagA/flagB for Layer 0 so the GPU can run @@ -3724,19 +3724,21 @@ void Verifier::set_plan_slot(int grp) { } // Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly. -void Verifier::raise_flag(uint32_t* flag, uint32_t value) { - volatile long* f = (volatile long*) flag; -#if defined(_WIN32) - long cur = *f; - while ((uint32_t) cur < value) { - const long prev = _InterlockedCompareExchange(f, (long) value, cur); - if (prev == cur) break; - cur = prev; +void Verifier::raise_flag(uint32_t* flag, uint32_t value) { strata::core::flag_raise_max(flag, value); } + +// Flag B for layer `want - 1`, behind every copy queued on the copy stream (PR #5096, @AlanJager). The counter only +// rises and the graph waits for "flag B >= layer + 1", so raising it on the spot for a layer with nothing to copy +// releases an earlier layer (or the other token group of a split window) whose uploads are still in flight. +void Verifier::raise_flag_b_ordered(uint32_t want) { + FlagSet& fs = flag_sets_[(want - 1) % (sizeof flag_sets_ / sizeof flag_sets_[0])]; + const cudaError_t e = strata::core::raise_flag_b_ordered(copy_used_, copy_, &fs, h_flagB_, want); + if (e != cudaSuccess) { + // The flag was not raised: the consumers must not be released to staging that is still being written. + std::fprintf(stderr, "strata DMA: ordered flag B completion failed: %s\n", cudaGetErrorString(e)); + std::fflush(stderr); + release_gpu_waits(5000); + std::abort(); } -#else - uint32_t cur = __atomic_load_n((uint32_t*) flag, __ATOMIC_SEQ_CST); - while (cur < value && !__atomic_compare_exchange_n((uint32_t*) flag, &cur, value, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {} -#endif } // Plan v0.3 P6: the PCIe share by DMA. The copy engine moves the blobs while the CPU computes its own share and the @@ -3745,7 +3747,7 @@ void Verifier::raise_flag(uint32_t* flag, uint32_t value) { void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes) { Verifier* v = (Verifier*) ctx; const uint32_t want = v->cur_layer_ + 1; - if (n <= 0) { raise_flag(v->h_flagB_, want); return; } + if (n <= 0) { v->raise_flag_b_ordered(want); return; } // an empty plan stays behind the copies already queued v->copy_used_ = true; uint8_t* stage = (uint8_t*) v->sink_.staging; // this group's half in a split window // STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync. Mode 0 is @@ -3764,10 +3766,7 @@ void Verifier::fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t byt 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; - cudaLaunchHostFunc(v->copy_, [](void* p) { FlagSet* s = (FlagSet*) p; raise_flag(s->flag, s->value); }, &fs); + v->raise_flag_b_ordered(want); // copy_used_ is set: the host function runs after this group's uploads } void Verifier::publish_plan(void* ctx) { @@ -4761,7 +4760,7 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons sink_.start2[0] = 0; std::atomic_thread_fence(std::memory_order_seq_cst); *(volatile uint32_t*) h_flagA_ = want; - raise_flag(h_flagB_, want); + raise_flag_b_ordered(want); // behind any copy still queued from an earlier layer } *flag = want; ms_wait += std::chrono::duration(b - a).count(); @@ -4976,7 +4975,7 @@ int Verifier::batch_serve(PoolMultiFn pool, void* user) { sink_.start2[0] = 0; std::atomic_thread_fence(std::memory_order_seq_cst); *(volatile uint32_t*) h_flagA_ = want; - raise_flag(h_flagB_, want); + raise_flag_b_ordered(want); // behind any copy still queued from an earlier layer } *(volatile uint32_t*) h_flag_ = want; ms_pool += ms_since(b); @@ -5330,7 +5329,7 @@ int Verifier::service(PoolMultiFn pool, void* user, std::string& err) { sink_.start2[0] = 0; std::atomic_thread_fence(std::memory_order_seq_cst); *(volatile uint32_t*) h_flagA_ = want; - raise_flag(h_flagB_, want); + raise_flag_b_ordered(want); // behind any copy still queued from an earlier layer } if (fl_k_ == 0 && !gather_ple()) return -1; *(volatile uint32_t*) h_flag_ = want; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index bfe8374ba9..aa17f5d14f 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -25,6 +25,7 @@ #include "strata/kernels/gfx_arch.hpp" #include "strata/core/batch_telemetry.hpp" #include "strata/core/dma_batch.hpp" +#include "strata/program/adaptive_range.hpp" #include "strata/core/device.hpp" #include "strata/core/remote_expert_opt.hpp" #include "strata/core/expert_cache.hpp" @@ -13104,7 +13105,7 @@ int main(int argc, char** argv) { Clock::time_point a_t0; std::atomic a_err{false}; double a_pick_ms = 0; // the arena's inline choice, summed (the stats line) - size_t a_lo = 0, a_hi = 0, a_bi = 0; // the batch being copied in (a_copy_in), and where the next one starts + strata::program::AdaptiveCopyRange a_rng; // the batch being copied in (a_copy_in), and where the next one starts std::vector ahomes; // [0] = CUDA0's cache, [k] = layer split stage k's std::unique_ptr ajob; // the arena mode (srcp == &arena_src): every expert is in the arena already, so a round is a copy in only - no @@ -13252,7 +13253,7 @@ int main(int argc, char** argv) { }; auto a_copy_in = [&]() { // step 2 on the job thread (the serial loop): each source read, then copied in std::vector used(ahomes.size(), 0); - for (size_t i = a_lo; i < a_hi; ++i) { // (the batch; all the round's swaps unless the arena caps it) + for (size_t i = a_rng.lo; i < a_rng.hi; ++i) { // (the batch; all the round's swaps unless the arena caps it) const ASwap& w = aswaps[i]; if (const uint8_t* b = a_from(w)) { a_in_one(w, b); @@ -13263,9 +13264,7 @@ int main(int argc, char** argv) { if (used[hi]) a_mark(ahomes[hi]); }; auto a_post_batch = [&]() { // step 2: the next batch of copies in goes to the job thread (all of them but for the arena's cap) - a_lo = a_bi; - a_hi = a_batch > 0 ? std::min(aswaps.size(), a_bi + a_batch) : aswaps.size(); - a_bi = a_hi; + a_rng.next_batch(aswaps.size(), a_batch); ajob->post(a_copy_in); }; auto a_stage_in = [&]() { // step 2's host part on the job thread (the pipelined loop: a_in queues the copies) @@ -13385,10 +13384,13 @@ int main(int argc, char** argv) { if (pl) { // the copies in at each card's next gap: after this step, so fenced (see above) a_res_dirty = true; for (const ASwap& w : aswaps) a_in_due[(size_t) w.home] = 1; + // the whole round is one batch: when the pipelined loop drains before step 3, the next tick + // takes step 3 on the serial rule and marks [lo, hi), which an earlier round left otherwise + a_rng.whole_round(aswaps.size()); ajob->post(a_stage_in); } else { res_upload(); - a_lo = a_hi = a_bi = 0; + a_rng.clear(); a_post_batch(); } astate = AState::SwapIn; @@ -13399,15 +13401,15 @@ int main(int argc, char** argv) { if (a_due(a_in_due)) return true; // (pipelined) a card not seen idle since step 2 if (!a_ready(drain || a_wait)) return true; if (a_err.load()) return false; - for (size_t i = pl ? 0 : a_lo; i < (pl ? aswaps.size() : a_hi); ++i) { // (the batch just landed) + for (size_t i = a_rng.landed_begin(pl); i < a_rng.landed_end(pl, aswaps.size()); ++i) { // (the batch just landed) const ASwap& w = aswaps[i]; host_res[(size_t) w.layer * g.n_expert + w.in] = w.slot; srcp->release(w.layer, w.in); } if (pl) a_res_dirty = true; else res_upload(); - a_swapped += pl ? (int64_t) aswaps.size() : (int64_t) (a_hi - a_lo); - if (!pl && a_bi < aswaps.size()) { // the arena's cap: the next batch goes now + a_swapped += (int64_t) (a_rng.landed_end(pl, aswaps.size()) - a_rng.landed_begin(pl)); + if (!pl && a_rng.more(aswaps.size())) { // the arena's cap: the next batch goes now for (AHome& h : ahomes) h.used = false; a_post_batch(); if (!drain) return true; diff --git a/tests/core/flag_order_test.cu b/tests/core/flag_order_test.cu new file mode 100644 index 0000000000..7c2df6a797 --- /dev/null +++ b/tests/core/flag_order_test.cu @@ -0,0 +1,125 @@ +// Flag B behind queued copies (PR #5096): an empty plan must not release a layer whose uploads are still in flight. +// A delayed host function stands in for a slow DMA on the copy stream (it writes the "staging" word a while after it was +// queued); a kernel plays the graph (waits for flag B >= value, then reads staging). Run on every device found. +#include "strata/core/flag_order.hpp" + +#include +#include +#include +#include + +using strata::core::FlagRaise; +using strata::core::flag_raise_max; +using strata::core::raise_flag_b_ordered; + +static int failed = 0; +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #x); ++failed; } } while (0) +#define CK(call) do { const cudaError_t e_ = (call); if (e_ != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", #call, cudaGetErrorString(e_)); return 1; } } while (0) + +struct SlowCopy { volatile uint32_t* staging; uint32_t word; int ms; }; +static void slow_copy(void* p) { + SlowCopy* c = (SlowCopy*) p; + std::this_thread::sleep_for(std::chrono::milliseconds(c->ms)); + *c->staging = c->word; // the final writer of the buffer +} + +__global__ void consumer(volatile uint32_t* flag, uint32_t want, volatile uint32_t* staging, volatile uint32_t* seen) { + while (*flag < want) {} + *seen = *staging; // what the graph's PCIe group would read +} + +static uint32_t rd(volatile uint32_t* p) { return __atomic_load_n((uint32_t*) p, __ATOMIC_SEQ_CST); } + +static int run_device(int dev) { + CK(cudaSetDevice(dev)); + cudaStream_t copy, cs; + CK(cudaStreamCreateWithFlags(©, cudaStreamNonBlocking)); + CK(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking)); + volatile uint32_t *flag_h, *staging_h, *seen_h; + CK(cudaHostAlloc((void**) &flag_h, 64, cudaHostAllocMapped)); + CK(cudaHostAlloc((void**) &staging_h, 64, cudaHostAllocMapped)); + CK(cudaHostAlloc((void**) &seen_h, 64, cudaHostAllocMapped)); + volatile uint32_t *flag_d, *staging_d, *seen_d; + CK(cudaHostGetDevicePointer((void**) &flag_d, (void*) flag_h, 0)); + CK(cudaHostGetDevicePointer((void**) &staging_d, (void*) staging_h, 0)); + CK(cudaHostGetDevicePointer((void**) &seen_d, (void*) seen_h, 0)); + FlagRaise slots[4] = {}; + SlowCopy c0{staging_h, 0xAAu, 150}; + + // 1. nonempty plan (layer 0) followed by an empty plan (layer 1) while the copy is delayed + *flag_h = 0; *staging_h = 0; *seen_h = 0; + CK(cudaLaunchHostFunc(copy, slow_copy, &c0)); // layer 0's upload, in flight + CK(raise_flag_b_ordered(true, copy, &slots[0], (uint32_t*) flag_h, 1)); // its completion flag (non-empty plan) + CK(raise_flag_b_ordered(true, copy, &slots[1], (uint32_t*) flag_h, 2)); // layer 1: empty plan, same copy stream + CHECK(rd(flag_h) == 0); // neither flag may rise before the delayed copy + consumer<<<1, 1, 0, cs>>>(flag_d, 1, staging_d, seen_d); // the graph's layer-0 group + CK(cudaStreamSynchronize(cs)); + CHECK(rd(seen_h) == 0xAAu); // the consumer saw the final writer's bytes + CK(cudaStreamSynchronize(copy)); + CHECK(rd(flag_h) == 2); + + // 2. the negative control: a direct raise (the old empty-plan path) does release the consumer early + *flag_h = 0; *staging_h = 0; *seen_h = 0; + CK(cudaLaunchHostFunc(copy, slow_copy, &c0)); + flag_raise_max((uint32_t*) flag_h, 2); // what an unordered empty plan did + consumer<<<1, 1, 0, cs>>>(flag_d, 1, staging_d, seen_d); + CK(cudaStreamSynchronize(cs)); + CHECK(rd(seen_h) == 0); // read before the copy landed: the bug the ordered raise removes + CK(cudaStreamSynchronize(copy)); + + // 3. nothing queued in this window: the flag rises at once + *flag_h = 0; + CK(raise_flag_b_ordered(false, copy, &slots[2], (uint32_t*) flag_h, 3)); + CHECK(rd(flag_h) == 3); + + // 4. the flag only rises: a late host function of an earlier layer does not lower it + *flag_h = 5; + CK(raise_flag_b_ordered(true, copy, &slots[3], (uint32_t*) flag_h, 4)); + CK(cudaStreamSynchronize(copy)); + CHECK(rd(flag_h) == 5); + + // 5. an idle copy stream with copies_queued still set (the window's earlier copies finished): raised through the stream + *flag_h = 0; + CK(raise_flag_b_ordered(true, copy, &slots[0], (uint32_t*) flag_h, 6)); + CK(cudaStreamSynchronize(copy)); + CHECK(rd(flag_h) == 6); + + // 6. through a graph: the consumer is captured and replayed twice, a fresh delayed copy each time + { + cudaGraph_t graph; cudaGraphExec_t exec; + CK(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal)); + consumer<<<1, 1, 0, cs>>>(flag_d, 7, staging_d, seen_d); + CK(cudaStreamEndCapture(cs, &graph)); + CK(cudaGraphInstantiate(&exec, graph, nullptr, nullptr, 0)); + for (int rep = 0; rep < 2; ++rep) { + *flag_h = 0; *staging_h = 0; *seen_h = 0; + SlowCopy c{staging_h, 0x55u + (uint32_t) rep, 60}; + CK(cudaLaunchHostFunc(copy, slow_copy, &c)); + CK(raise_flag_b_ordered(true, copy, &slots[1], (uint32_t*) flag_h, 7)); + CK(cudaGraphLaunch(exec, cs)); + CK(cudaStreamSynchronize(cs)); + CHECK(rd(seen_h) == 0x55u + (uint32_t) rep); + CK(cudaStreamSynchronize(copy)); + } + CK(cudaGraphExecDestroy(exec)); + CK(cudaGraphDestroy(graph)); + } + CK(cudaStreamDestroy(copy)); + CK(cudaStreamDestroy(cs)); + CK(cudaFreeHost((void*) flag_h)); CK(cudaFreeHost((void*) staging_h)); CK(cudaFreeHost((void*) seen_h)); + return 0; +} + +int main() { + int n = 0; + CK(cudaGetDeviceCount(&n)); + if (n == 0) { std::puts("flag_order_test: no device, skipped"); return 0; } + for (int d = 0; d < n; ++d) { + const int rc = run_device(d); + if (rc != 0) return rc; + std::printf("flag_order_test: device %d ok\n", d); + } + if (failed) { std::fprintf(stderr, "%d check(s) failed\n", failed); return 1; } + std::puts("flag_order_test: ok"); + return 0; +} diff --git a/tests/program/adaptive_range_test.cpp b/tests/program/adaptive_range_test.cpp new file mode 100644 index 0000000000..67e39ea4a4 --- /dev/null +++ b/tests/program/adaptive_range_test.cpp @@ -0,0 +1,102 @@ +// The adaptive tier's copy-in range (PR #4844): which swaps of a round step 3 marks resident. No GPU: the rounds are +// walked as generate.cpp walks them, and each swap is a counter that says whether it was copied in and whether it was marked. +#include +#include + +#include "strata/program/adaptive_range.hpp" + +using strata::program::AdaptiveCopyRange; + +static int failed = 0; +#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #x); ++failed; } } while (0) + +struct Round { + size_t total; + std::vector copied, marked; + explicit Round(size_t n) : total(n), copied(n, 0), marked(n, 0) {} + static bool all(const std::vector& v) { for (int x : v) if (x != 1) return false; return true; } +}; + +// the serial loop: plan (clear + next_batch), copy the batch, step 3 marks it, repeat while more() (the arena's cap) +static void serial_round(AdaptiveCopyRange& r, Round& rd, size_t batch) { + r.clear(); + r.next_batch(rd.total, batch); + for (;;) { + for (size_t i = r.lo; i < r.hi; ++i) ++rd.copied[i]; + for (size_t i = r.landed_begin(false); i < r.landed_end(false, rd.total); ++i) ++rd.marked[i]; + if (!r.more(rd.total)) break; + r.next_batch(rd.total, batch); + } +} + +int main() { + // the serial loop covers every swap once, whatever the cap, including zero swaps and one swap + for (size_t total : {(size_t) 0, (size_t) 1, (size_t) 2, (size_t) 5, (size_t) 8, (size_t) 64}) + for (size_t batch : {(size_t) 0, (size_t) 1, (size_t) 2, (size_t) 3, (size_t) 7, (size_t) 8, (size_t) 100}) { + AdaptiveCopyRange r; + Round rd(total); + serial_round(r, rd, batch); + CHECK(Round::all(rd.copied) && Round::all(rd.marked)); + CHECK(r.bi == total && r.hi == total); + } + + // a batch never runs past the list, even for a cap near the size_t limit + { + AdaptiveCopyRange r; + r.next_batch(5, (size_t) -1); + CHECK(r.lo == 0 && r.hi == 5 && r.bi == 5); + r.next_batch(5, 2); // asked again after the end: an empty batch at the end + CHECK(r.lo == 5 && r.hi == 5 && !r.more(5)); + } + + // the lost experts of #4844: a round planned on the pipelined loop whose loop drained before step 3 is marked on the + // serial rule. An earlier serial round left [lo, hi) at its last batch. + { + AdaptiveCopyRange r; + Round first(5); + serial_round(r, first, 2); // leaves lo = 4, hi = 5, bi = 5 + CHECK(r.lo == 4 && r.hi == 5); + + // the old plan (nothing set for a pipelined round): step 3 on the serial rule marks only the stale range + { + AdaptiveCopyRange stale = r; + Round pl(7); + for (size_t i = 0; i < pl.total; ++i) ++pl.copied[i]; // a_in copied all of them at the gaps + for (size_t i = stale.landed_begin(false); i < stale.landed_end(false, pl.total); ++i) ++pl.marked[i]; + CHECK(!Round::all(pl.marked)); // the bug this test pins + } + + // the fix: the pipelined plan names the whole round + Round pl(7); + r.whole_round(pl.total); + for (size_t i = 0; i < pl.total; ++i) ++pl.copied[i]; + for (size_t i = r.landed_begin(false); i < r.landed_end(false, pl.total); ++i) ++pl.marked[i]; // the drained tick: serial rule + CHECK(Round::all(pl.marked)); + CHECK(!r.more(pl.total)); // and no second batch is posted + // the same round finished on the pipelined rule marks the same range + CHECK(r.landed_begin(true) == r.landed_begin(false) && r.landed_end(true, pl.total) == r.landed_end(false, pl.total)); + } + + // one swap, and an empty round, on the pipelined plan + { + AdaptiveCopyRange r; + r.next_batch(9, 4); + r.whole_round(1); + CHECK(r.landed_begin(false) == 0 && r.landed_end(false, 1) == 1 && !r.more(1)); + r.whole_round(0); + CHECK(r.landed_begin(false) == 0 && r.landed_end(false, 0) == 0 && !r.more(0)); + } + + // a serial round that follows a pipelined one starts clean + { + AdaptiveCopyRange r; + r.whole_round(6); + Round rd(3); + serial_round(r, rd, 2); + CHECK(Round::all(rd.copied) && Round::all(rd.marked)); + } + + if (failed) { std::fprintf(stderr, "%d check(s) failed\n", failed); return 1; } + std::puts("adaptive_range_test: ok"); + return 0; +}