okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
6.4 KiB146 linesraw
1// src/core/graph.cpp - P2.S5: the GraphRegistry implementation.
2#include "strata/core/graph.hpp"
3
4#include "strata/platform/cpu_relax.hpp"
5
6#include <chrono>
7#include <cstdio>
8
9namespace strata::core {
10namespace {
11
12/// Fills `err` from the CUDA runtime, naming the call that failed.  A bare "invalid argument" with no call
13/// site is the least useful error this API can produce and the easiest to avoid.
14bool fail(std::string& err, const char* what, cudaError_t e) {
15    err = std::string(what) + ": " + cudaGetErrorString(e);
16    return false;
17}
18
19}  // namespace
20
21CapturedGraph& CapturedGraph::operator=(CapturedGraph&& o) noexcept {
22    if (this != &o) {
23        reset();
24        graph_ = o.graph_;
25        exec_ = o.exec_;
26        done_ = o.done_;
27        nodes_ = o.nodes_;
28        o.graph_ = nullptr;
29        o.exec_ = nullptr;
30        o.done_ = nullptr;
31        o.nodes_ = 0;
32    }
33    return *this;
34}
35
36void CapturedGraph::reset() {
37    // ORDER MATTERS: destroying a graph exec BLOCKS until the launch it is destroying has completed, so
38    // destroying it before the event is harmless but destroying it after a spin that was supposed to observe
39    // completion would silently become the thing that caused it.  `bench/micro/graph_capture.cu` was fooled by
40    // exactly this once - it looked like captured graphs made a doorbell visible and direct launches did not.
41    if (exec_) { cudaGraphExecDestroy(exec_); exec_ = nullptr; }
42    if (graph_) { cudaGraphDestroy(graph_); graph_ = nullptr; }
43    if (done_) { cudaEventDestroy(done_); done_ = nullptr; }
44    nodes_ = 0;
45}
46
47bool CapturedGraph::begin(void* stream, std::string& err) {
48    if (graph_ || exec_) { err = "begin: this CapturedGraph is already recorded"; return false; }
49    const cudaError_t e = cudaStreamBeginCapture((cudaStream_t) stream, cudaStreamCaptureModeThreadLocal);
50    if (e != cudaSuccess) return fail(err, "cudaStreamBeginCapture", e);
51    return true;
52}
53
54bool CapturedGraph::end(void* stream, std::string& err) {
55    cudaError_t e = cudaStreamEndCapture((cudaStream_t) stream, &graph_);
56    if (e != cudaSuccess) { graph_ = nullptr; return fail(err, "cudaStreamEndCapture", e); }
57
58    nodes_ = 0;
59    e = cudaGraphGetNodes(graph_, nullptr, &nodes_);
60    if (e != cudaSuccess) return fail(err, "cudaGraphGetNodes", e);
61    // A capture that recorded NOTHING is a wiring mistake, and a graph that replays nothing produces no error
62    // and no output - the silent kind of failure this project keeps paying for.
63    if (nodes_ == 0) { err = "end: the capture recorded ZERO nodes - the body launched nothing"; reset(); return false; }
64
65    e = cudaGraphInstantiate(&exec_, graph_, nullptr, nullptr, 0);
66    if (e != cudaSuccess) return fail(err, "cudaGraphInstantiate", e);
67
68    // The completion event is recorded ONCE and reused: `launch` records it again after each replay, which is
69    // what makes `wait_ms` a query rather than a sync.
70    e = cudaEventCreateWithFlags(&done_, cudaEventDisableTiming);
71    if (e != cudaSuccess) return fail(err, "cudaEventCreateWithFlags", e);
72    return true;
73}
74
75bool CapturedGraph::launch(void* stream, std::string& err) const {
76    if (!exec_) { err = "launch: not recorded"; return false; }
77    cudaError_t e = cudaGraphLaunch(exec_, (cudaStream_t) stream);
78    if (e != cudaSuccess) return fail(err, "cudaGraphLaunch", e);
79    e = cudaEventRecord(done_, (cudaStream_t) stream);
80    if (e != cudaSuccess) return fail(err, "cudaEventRecord", e);
81    return true;
82}
83
84bool CapturedGraph::wait_ms(int timeout_ms) const {
85    if (!done_) return false;
86    // A BOUNDED wait, and the bound is the point: an unbounded spin turns a protocol bug into a hung run, and
87    // a hung run says nothing about which side is stuck.  `cudaEventQuery` is a QUERY - it does not block and
88    // it does not synchronise - so this satisfies P2.X3 while still giving the driver the call it needs to
89    // flush the submission.  See NOTE 1 in the header: without a driver call here the work never starts.
90    //
91    // The deadline is a REAL CLOCK, not a count of pause instructions: `_mm_pause` is a few cycles, so
92    // counting pauses as microseconds would make the timeout tens of times longer than the caller asked for -
93    // a timeout that does not time out is worse than none, because it reports a hang as a pass.
94    const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
95    for (;;) {
96        const cudaError_t q = cudaEventQuery(done_);
97        if (q == cudaSuccess) return true;
98        if (q != cudaErrorNotReady) return false;   // a real error, not "not finished"
99        if (std::chrono::steady_clock::now() >= deadline) return false;
100        for (int i = 0; i < 64; ++i) strata_cpu_pause();
101    }
102}
103
104bool GraphRegistry::record(LayerType type, int n_tokens, const std::function<void()>& body, std::string& err) {
105    const Key k{(int) type, n_tokens};
106    if (graphs_.count(k)) return true;              // already recorded: the point of a registry
107
108    CapturedGraph g;
109    if (!g.begin(stream_, err)) return false;
110    body();                                        // the caller launches into the captured stream
111    // The body must not have failed silently.  An error state left on the stream would make EndCapture
112    // succeed with a broken graph, so it is checked and cleared first.
113    const cudaError_t body_err = cudaGetLastError();
114    if (body_err != cudaSuccess) {
115        // Abandon the capture without instantiating anything.
116        cudaGraph_t junk = nullptr;
117        cudaStreamEndCapture((cudaStream_t) stream_, &junk);
118        if (junk) cudaGraphDestroy(junk);
119        return fail(err, "the capture body left a CUDA error", body_err);
120    }
121    if (!g.end(stream_, err)) return false;
122
123    graphs_.emplace(k, std::move(g));
124    ++captures_;
125    return true;
126}
127
128const CapturedGraph* GraphRegistry::find(LayerType type, int n_tokens) const {
129    const auto it = graphs_.find(Key{(int) type, n_tokens});
130    return it == graphs_.end() ? nullptr : &it->second;
131}
132
133bool GraphRegistry::launch(LayerType type, int n_tokens, int timeout_ms, std::string& err) const {
134    const CapturedGraph* g = find(type, n_tokens);
135    if (!g) {
136        char buf[128];
137        std::snprintf(buf, sizeof buf, "launch: no graph recorded for %s n=%d", to_string(type), n_tokens);
138        err = buf;
139        return false;
140    }
141    if (!g->launch(stream_, err)) return false;
142    if (!g->wait_ms(timeout_ms)) { err = "launch: timed out waiting for the graph to complete"; return false; }
143    return true;
144}
145
146}  // namespace strata::core