okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

main
9.5 KiB249 linesraw
1// src/core/graph.cpp - P2.S5: the GraphRegistry implementation.
2#include <sycl/sycl.hpp>
3#include <dpct/dpct.hpp>
4#include "strata/sycl_queue.hpp"
5#include "strata/core/graph.hpp"
6
7#include <immintrin.h>
8
9#include <chrono>
10#include <cstdio>
11#include <chrono>
12
13namespace strata::core {
14namespace {
15
16/// Fills `err` from the CUDA runtime, naming the call that failed.  A bare "invalid argument" with no call
17/// site is the least useful error this API can produce and the easiest to avoid.
18bool fail(std::string &err, const char *what, dpct::err0 e) {
19    /*
20    DPCT1009: SYCL reports errors using exceptions and does not use error
21    codes. Please replace the "get_error_string_dummy(...)" with a real
22    error-handling function.
23    */
24    err = std::string(what) + ": " + dpct::get_error_string_dummy(e);
25    return false;
26}
27
28}  // namespace
29
30CapturedGraph& CapturedGraph::operator=(CapturedGraph&& o) noexcept {
31    if (this != &o) {
32        reset();
33        graph_ = o.graph_;
34        exec_ = o.exec_;
35        done_ = o.done_;
36        nodes_ = o.nodes_;
37        o.graph_ = nullptr;
38        o.exec_ = nullptr;
39        o.done_ = nullptr;
40        o.nodes_ = 0;
41    }
42    return *this;
43}
44
45void CapturedGraph::reset() {
46    // ORDER MATTERS: destroying a graph exec BLOCKS until the launch it is destroying has completed, so
47    // destroying it before the event is harmless but destroying it after a spin that was supposed to observe
48    // completion would silently become the thing that caused it.  `bench/micro/graph_capture.cu` was fooled by
49    // exactly this once - it looked like captured graphs made a doorbell visible and direct launches did not.
50    if (exec_) { delete (exec_); exec_ = nullptr; }
51    if (graph_) { delete (graph_); graph_ = nullptr; }
52    if (done_) { dpct::destroy_event(done_); done_ = nullptr; }
53    nodes_ = 0;
54}
55
56bool CapturedGraph::begin(void *stream, std::string &err) try {
57    if (graph_ || exec_) { err = "begin: this CapturedGraph is already recorded"; return false; }
58    const dpct::err0 e = DPCT_CHECK_ERROR(
59        dpct::experimental::begin_recording(strata::q_of(stream)));
60    /*
61    DPCT1001: The statement could not be removed.
62    */
63    /*
64    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
65    */
66    if (e != 0) return fail(err, "cudaStreamBeginCapture", e);
67    return true;
68}
69catch (sycl::exception const &exc) {
70  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
71            << ", line:" << __LINE__ << std::endl;
72  std::exit(1);
73}
74
75bool CapturedGraph::end(void *stream, std::string &err) try {
76    dpct::err0 e = DPCT_CHECK_ERROR(
77        dpct::experimental::end_recording(strata::q_of(stream), &graph_));
78    /*
79    DPCT1001: The statement could not be removed.
80    */
81    /*
82    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
83    */
84    if (e != 0) {
85        graph_ = nullptr; return fail(err, "cudaStreamEndCapture", e);
86    }
87
88    nodes_ = 0;
89    e = DPCT_CHECK_ERROR(
90        dpct::experimental::get_nodes(graph_, nullptr, &nodes_));
91    /*
92    DPCT1001: The statement could not be removed.
93    */
94    /*
95    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
96    */
97    if (e != 0) return fail(err, "cudaGraphGetNodes", e);
98    // A capture that recorded NOTHING is a wiring mistake, and a graph that replays nothing produces no error
99    // and no output - the silent kind of failure this project keeps paying for.
100    if (nodes_ == 0) { err = "end: the capture recorded ZERO nodes - the body launched nothing"; reset(); return false; }
101
102    e = DPCT_CHECK_ERROR(
103        exec_ = new sycl::ext::oneapi::experimental::command_graph<
104            sycl::ext::oneapi::experimental::graph_state::executable>(
105            (graph_)->finalize()));
106    /*
107    DPCT1001: The statement could not be removed.
108    */
109    /*
110    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
111    */
112    if (e != 0) return fail(err, "cudaGraphInstantiate", e);
113
114    // The completion event is recorded ONCE and reused: `launch` records it again after each replay, which is
115    // what makes `wait_ms` a query rather than a sync.
116    e = DPCT_CHECK_ERROR(done_ = new sycl::event());
117    /*
118    DPCT1001: The statement could not be removed.
119    */
120    /*
121    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
122    */
123    if (e != 0) return fail(err, "cudaEventCreateWithFlags", e);
124    return true;
125}
126catch (sycl::exception const &exc) {
127  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
128            << ", line:" << __LINE__ << std::endl;
129  std::exit(1);
130}
131
132bool CapturedGraph::launch(void *stream, std::string &err) const try {
133    if (!exec_) { err = "launch: not recorded"; return false; }
134    dpct::err0 e =
135        DPCT_CHECK_ERROR(strata::q_of(stream)->ext_oneapi_graph(*exec_));
136    /*
137    DPCT1001: The statement could not be removed.
138    */
139    /*
140    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
141    */
142    if (e != 0) return fail(err, "cudaGraphLaunch", e);
143    /*
144    DPCT1012: Detected kernel execution time measurement pattern and
145    generated an initial code for time measurements in SYCL. You can change the
146    way time is measured depending on your goals.
147    */
148    /*
149    DPCT1024: The original code returned the error code that was further
150    consumed by the program logic. This original code was replaced with 0. You
151    may need to rewrite the program logic consuming the error code.
152    */
153    done__ct1 = std::chrono::steady_clock::now();
154    e = DPCT_CHECK_ERROR(*done_ = strata::q_of(stream)
155                                      ->ext_oneapi_submit_barrier());
156    /*
157    DPCT1001: The statement could not be removed.
158    */
159    /*
160    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
161    */
162    if (e != 0) return fail(err, "cudaEventRecord", e);
163    return true;
164}
165catch (sycl::exception const &exc) {
166  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
167            << ", line:" << __LINE__ << std::endl;
168  std::exit(1);
169}
170
171bool CapturedGraph::wait_ms(int timeout_ms) const try {
172    if (!done_) return false;
173    // A BOUNDED wait, and the bound is the point: an unbounded spin turns a protocol bug into a hung run, and
174    // a hung run says nothing about which side is stuck.  `cudaEventQuery` is a QUERY - it does not block and
175    // it does not synchronise - so this satisfies P2.X3 while still giving the driver the call it needs to
176    // flush the submission.  See NOTE 1 in the header: without a driver call here the work never starts.
177    //
178    // The deadline is a REAL CLOCK, not a count of pause instructions: `_mm_pause` is a few cycles, so
179    // counting pauses as microseconds would make the timeout tens of times longer than the caller asked for -
180    // a timeout that does not time out is worse than none, because it reports a hang as a pass.
181    const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
182    for (;;) {
183        const dpct::err0 q = dpct::sycl_event_query(done_);
184        if (q == 0) return true;
185        if (q != 1) return false; // a real error, not "not finished"
186        if (std::chrono::steady_clock::now() >= deadline) return false;
187        for (int i = 0; i < 64; ++i) _mm_pause();
188    }
189}
190catch (sycl::exception const &exc) {
191  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
192            << ", line:" << __LINE__ << std::endl;
193  std::exit(1);
194}
195
196bool GraphRegistry::record(LayerType type, int n_tokens, const std::function<void()>& body, std::string& err) {
197    const Key k{(int) type, n_tokens};
198    if (graphs_.count(k)) return true;              // already recorded: the point of a registry
199
200    CapturedGraph g;
201    if (!g.begin(stream_, err)) return false;
202    body();                                        // the caller launches into the captured stream
203    // The body must not have failed silently.  An error state left on the stream would make EndCapture
204    // succeed with a broken graph, so it is checked and cleared first.
205    /*
206    DPCT1010: SYCL uses exceptions to report errors and does not use the
207    error codes. The cudaGetLastError function call was replaced with 0. You
208    need to rewrite this code.
209    */
210    const dpct::err0 body_err = 0;
211    /*
212    DPCT1000: Error handling if-stmt was detected but could not be rewritten.
213    */
214    if (body_err != 0) {
215        // Abandon the capture without instantiating anything.
216        dpct::experimental::command_graph_ptr junk = nullptr;
217        /*
218        DPCT1001: The statement could not be removed.
219        */
220        dpct::experimental::end_recording(strata::q_of(stream_), &junk);
221        if (junk) delete (junk);
222        return fail(err, "the capture body left a CUDA error", body_err);
223    }
224    if (!g.end(stream_, err)) return false;
225
226    graphs_.emplace(k, std::move(g));
227    ++captures_;
228    return true;
229}
230
231const CapturedGraph* GraphRegistry::find(LayerType type, int n_tokens) const {
232    const auto it = graphs_.find(Key{(int) type, n_tokens});
233    return it == graphs_.end() ? nullptr : &it->second;
234}
235
236bool GraphRegistry::launch(LayerType type, int n_tokens, int timeout_ms, std::string& err) const {
237    const CapturedGraph* g = find(type, n_tokens);
238    if (!g) {
239        char buf[128];
240        std::snprintf(buf, sizeof buf, "launch: no graph recorded for %s n=%d", to_string(type), n_tokens);
241        err = buf;
242        return false;
243    }
244    if (!g->launch(stream_, err)) return false;
245    if (!g->wait_ms(timeout_ms)) { err = "launch: timed out waiting for the graph to complete"; return false; }
246    return true;
247}
248
249}  // namespace strata::core