• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

celerity / celerity-runtime / 12047884020

27 Nov 2024 09:58AM UTC coverage: 94.956% (-0.02%) from 94.972%
12047884020

push

github

fknorr
Do not disable CGF disagnostics in test_utils::add_*_task

This eliminates dead code from an earlier incomplete refactoring.

The CGF teardown / reinit was only required by a single test, which was
coincidentally also broken and didn't test the feature advertised. This
commit splits up the test between runtime_ and runtime_deprecation_tests
and also moves runtime-independent sibling tests to task_graph_tests.

3202 of 3633 branches covered (88.14%)

Branch coverage included in aggregate %.

7151 of 7270 relevant lines covered (98.36%)

1224689.38 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.66
/src/runtime.cc
1
#include "runtime.h"
2

3
#include "affinity.h"
4
#include "backend/sycl_backend.h"
5
#include "cgf.h"
6
#include "cgf_diagnostics.h"
7
#include "command_graph_generator.h"
8
#include "dry_run_executor.h"
9
#include "host_object.h"
10
#include "instruction_graph_generator.h"
11
#include "live_executor.h"
12
#include "log.h"
13
#include "named_threads.h"
14
#include "print_graph.h"
15
#include "print_utils.h"
16
#include "print_utils_internal.h"
17
#include "ranges.h"
18
#include "reduction.h"
19
#include "scheduler.h"
20
#include "select_devices.h"
21
#include "system_info.h"
22
#include "task.h"
23
#include "task_manager.h"
24
#include "testspy/runtime_testspy.h"
25
#include "tracy.h"
26
#include "types.h"
27
#include "utils.h"
28
#include "version.h"
29

30
#include <atomic>
31
#include <cassert>
32
#include <chrono>
33
#include <cmath>
34
#include <cstddef>
35
#include <cstdint>
36
#include <cstdlib>
37
#include <cstring>
38
#include <future>
39
#include <limits>
40
#include <memory>
41
#include <optional>
42
#include <stdexcept>
43
#include <string>
44
#include <thread>
45
#include <utility>
46
#include <variant>
47
#include <vector>
48

49
#include <fmt/format.h>
50
#include <spdlog/spdlog.h>
51
#include <sycl/sycl.hpp>
52

53

54
#ifdef _MSC_VER
55
#include <process.h>
56
#else
57
#include <unistd.h>
58
#endif
59

60
#if CELERITY_USE_MIMALLOC
61
// override default new/delete operators to use the mimalloc memory allocator
62
#include <mimalloc-new-delete.h>
63
#endif
64

65
#if CELERITY_ENABLE_MPI
66
#include "mpi_communicator.h"
67
#include <mpi.h>
68
#else
69
#include "local_communicator.h"
70
#endif
71

72

73
namespace celerity {
74
namespace detail {
75

76
        class epoch_promise final : public task_promise {
77
          public:
78
                std::future<void> get_future() { return m_promise.get_future(); }
573✔
79

80
                void fulfill() override { m_promise.set_value(); }
573✔
81

82
                allocation_id get_user_allocation_id() override { utils::panic("epoch_promise::get_user_allocation_id"); }
×
83

84
          private:
85
                std::promise<void> m_promise;
86
        };
87

88
        class runtime::impl final : public runtime, private task_manager::delegate, private scheduler::delegate, private executor::delegate {
89
          public:
90
                impl(int* argc, char** argv[], const devices_or_selector& user_devices_or_selector);
91

92
                impl(const runtime::impl&) = delete;
93
                impl(runtime::impl&&) = delete;
94
                impl& operator=(const runtime::impl&) = delete;
95
                impl& operator=(runtime::impl&&) = delete;
96

97
                ~impl();
98

99
                task_id submit(raw_command_group&& cg);
100

101
                task_id fence(buffer_access access, std::unique_ptr<task_promise> fence_promise);
102

103
                task_id fence(host_object_effect effect, std::unique_ptr<task_promise> fence_promise);
104

105
                task_id sync(detail::epoch_action action);
106

107
                void create_queue();
108

109
                void destroy_queue();
110

111
                allocation_id create_user_allocation(void* ptr);
112

113
                buffer_id create_buffer(const range<3>& range, size_t elem_size, size_t elem_align, allocation_id user_aid);
114

115
                void set_buffer_debug_name(buffer_id bid, const std::string& debug_name);
116

117
                void destroy_buffer(buffer_id bid);
118

119
                host_object_id create_host_object(std::unique_ptr<host_object_instance> instance /* optional */);
120

121
                void destroy_host_object(host_object_id hoid);
122

123
                reduction_id create_reduction(std::unique_ptr<reducer> reducer);
124

125
                bool is_dry_run() const;
126

127
                void set_scheduler_lookahead(experimental::lookahead lookahead);
128

129
                void flush_scheduler();
130

131
          private:
132
                friend struct runtime_testspy;
133

134
                // `runtime` is not thread safe except for its delegate implementations, so we store the id of the thread where it was instantiated (the application
135
                // thread) in order to throw if the user attempts to issue a runtime operation from any other thread. One case where this may happen unintentionally
136
                // is capturing a buffer into a host-task by value, where this capture is the last reference to the buffer: The runtime would attempt to destroy itself
137
                // from a thread that it also needs to await, which would at least cause a deadlock. This variable is immutable, so reading it from a different thread
138
                // for the purpose of the check is safe.
139
                std::thread::id m_application_thread;
140

141
                std::unique_ptr<config> m_cfg;
142
                size_t m_num_nodes = 0;
143
                node_id m_local_nid = 0;
144
                size_t m_num_local_devices = 0;
145

146
                // track all instances of celerity::queue, celerity::buffer and celerity::host_object to sanity-check runtime destruction
147
                size_t m_num_live_queues = 0;
148
                std::unordered_set<buffer_id> m_live_buffers;
149
                std::unordered_set<host_object_id> m_live_host_objects;
150

151
                buffer_id m_next_buffer_id = 0;
152
                raw_allocation_id m_next_user_allocation_id = 1;
153
                host_object_id m_next_host_object_id = 0;
154
                reduction_id m_next_reduction_id = no_reduction_id + 1;
155

156
                task_graph m_tdag;
157
                std::unique_ptr<task_manager> m_task_mngr;
158
                std::unique_ptr<scheduler> m_schdlr;
159
                std::unique_ptr<executor> m_exec;
160

161
                std::optional<task_id> m_latest_horizon_reached; // only accessed by executor thread
162
                std::atomic<size_t> m_latest_epoch_reached;      // task_id, but cast to size_t to work with std::atomic
163
                task_id m_last_epoch_pruned_before = 0;
164

165
                std::unique_ptr<detail::task_recorder> m_task_recorder;               // accessed by task manager (application thread)
166
                std::unique_ptr<detail::command_recorder> m_command_recorder;         // accessed only by scheduler thread (until shutdown)
167
                std::unique_ptr<detail::instruction_recorder> m_instruction_recorder; // accessed only by scheduler thread (until shutdown)
168

169
                std::unique_ptr<detail::thread_pinning::thread_pinner> m_thread_pinner; // thread safe, manages lifetime of thread pinning machinery
170

171
                /// Panic when not called from m_application_thread (see that variable for more info on the matter). Since there are thread-safe and non thread-safe
172
                /// member functions, we call this check at the beginning of all the non-safe ones.
173
                void require_call_from_application_thread() const;
174

175
                void maybe_prune_task_graph();
176

177
                // task_manager::delegate
178
                void task_created(const task* tsk) override;
179

180
                // scheduler::delegate
181
                void flush(std::vector<const instruction*> instructions, std::vector<outbound_pilot> pilot) override;
182

183
                // executor::delegate
184
                void horizon_reached(task_id horizon_tid) override;
185
                void epoch_reached(task_id epoch_tid) override;
186

187
                /// True when no buffers, host objects or queues are live that keep the runtime alive.
188
                bool is_unreferenced() const;
189
        };
190

191
        static auto get_pid() {
231✔
192
#ifdef _MSC_VER
193
                return _getpid();
194
#else
195
                return getpid();
231✔
196
#endif
197
        }
198

199
        static std::string get_version_string() {
231✔
200
                using namespace celerity::version;
201
                return fmt::format("{}.{}.{} {}{}", major, minor, patch, git_revision, git_dirty ? "-dirty" : "");
462!
202
        }
203

204
        static const char* get_build_type() {
231✔
205
#if CELERITY_DETAIL_ENABLE_DEBUG
206
                return "debug";
231✔
207
#else
208
                return "release";
209
#endif
210
        }
211

212
        static const char* get_mimalloc_string() {
231✔
213
#if CELERITY_USE_MIMALLOC
214
                return "using mimalloc";
215
#else
216
                return "using the default allocator";
231✔
217
#endif
218
        }
219

220
        static std::string get_sycl_version() {
231✔
221
#if CELERITY_SYCL_IS_ACPP
222
                return fmt::format("AdaptiveCpp {}.{}.{}", HIPSYCL_VERSION_MAJOR, HIPSYCL_VERSION_MINOR, HIPSYCL_VERSION_PATCH);
223
#elif CELERITY_SYCL_IS_DPCPP
224
                return "DPC++ / Clang " __clang_version__;
225
#elif CELERITY_SYCL_IS_SIMSYCL
226
                return "SimSYCL " SIMSYCL_VERSION;
693✔
227
#else
228
#error "unknown SYCL implementation"
229
#endif
230
        }
231

232
        static std::string get_mpi_version() {
231✔
233
#if CELERITY_ENABLE_MPI
234
                char version[MPI_MAX_LIBRARY_VERSION_STRING];
231✔
235
                int len = -1;
231✔
236
                MPI_Get_library_version(version, &len);
231✔
237
                // try shortening the human-readable version string (so far tested on OpenMPI)
238
                if(const auto brk = /* find last of */ strpbrk(version, ",;")) { len = static_cast<int>(brk - version); }
231!
239
                return std::string(version, static_cast<size_t>(len));
924✔
240
#else
241
                return "single node";
242
#endif
243
        }
244

245
        static host_config get_mpi_host_config() {
225✔
246
#if CELERITY_ENABLE_MPI
247
                // Determine the "host config", i.e., how many nodes are spawned on this host,
248
                // and what this node's local rank is. We do this by finding all world-ranks
249
                // that can use a shared-memory transport (if running on OpenMPI, use the
250
                // per-host split instead).
251
#ifdef OPEN_MPI
252
#define SPLIT_TYPE OMPI_COMM_TYPE_HOST
253
#else
254
                // TODO: Assert that shared memory is available (i.e. not explicitly disabled)
255
#define SPLIT_TYPE MPI_COMM_TYPE_SHARED
256
#endif
257
                MPI_Comm host_comm = nullptr;
225✔
258
                MPI_Comm_split_type(MPI_COMM_WORLD, SPLIT_TYPE, 0, MPI_INFO_NULL, &host_comm);
225✔
259

260
                int local_rank = 0;
225✔
261
                MPI_Comm_rank(host_comm, &local_rank);
225✔
262

263
                int node_count = 0;
225✔
264
                MPI_Comm_size(host_comm, &node_count);
225✔
265

266
                host_config host_cfg;
225✔
267
                host_cfg.local_rank = local_rank;
225✔
268
                host_cfg.node_count = node_count;
225✔
269

270
                MPI_Comm_free(&host_comm);
225✔
271

272
                return host_cfg;
450✔
273
#else  // CELERITY_ENABLE_MPI
274
                return host_config{1, 0};
275
#endif // CELERITY_ENABLE_MPI
276
        }
277

278
        runtime::impl::impl(int* argc, char** argv[], const devices_or_selector& user_devices_or_selector) {
231✔
279
                m_application_thread = std::this_thread::get_id();
231✔
280

281
                m_cfg = std::make_unique<config>(argc, argv);
231✔
282

283
                CELERITY_DETAIL_IF_TRACY_SUPPORTED(tracy_detail::g_tracy_mode = m_cfg->get_tracy_mode());
284
                CELERITY_DETAIL_TRACY_ZONE_SCOPED("runtime::startup", DarkGray);
285

286
                if(s_test_mode) {
231✔
287
                        assert(s_test_active && "initializing the runtime from a test without a runtime_fixture");
188✔
288
                        s_test_runtime_was_instantiated = true;
188✔
289
                } else {
290
                        mpi_initialize_once(argc, argv);
43✔
291
                }
292

293
                int world_size = 1;
231✔
294
                int world_rank = 0;
231✔
295
#if CELERITY_ENABLE_MPI
296
                MPI_Comm_size(MPI_COMM_WORLD, &world_size);
231✔
297
                MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
231✔
298
#endif
299

300
                host_config host_cfg;
231✔
301
                if(m_cfg->is_dry_run()) {
231✔
302
                        if(world_size != 1) throw std::runtime_error("In order to run with CELERITY_DRY_RUN_NODES a single MPI process/rank must be used.");
6!
303
                        m_num_nodes = static_cast<size_t>(m_cfg->get_dry_run_nodes());
6✔
304
                        m_local_nid = 0;
6✔
305
                        host_cfg.node_count = 1;
6✔
306
                        host_cfg.local_rank = 0;
6✔
307
                } else {
308
                        m_num_nodes = static_cast<size_t>(world_size);
225✔
309
                        m_local_nid = static_cast<node_id>(world_rank);
225✔
310
                        host_cfg = get_mpi_host_config();
225✔
311
                }
312

313
                // Do not touch logger settings in tests, where the full (trace) logs are captured
314
                if(!s_test_mode) {
231✔
315
                        spdlog::set_level(m_cfg->get_log_level());
43✔
316
                        spdlog::set_pattern(fmt::format("[%Y-%m-%d %H:%M:%S.%e] [{:0{}}] [%^%l%$] %v", m_local_nid, int(ceil(log10(double(m_num_nodes))))));
43✔
317
                }
318

319
                CELERITY_INFO("Celerity runtime version {} running on {} / {}. PID = {}, build type = {}, {}", get_version_string(), get_sycl_version(),
231✔
320
                    get_mpi_version(), get_pid(), get_build_type(), get_mimalloc_string());
321

322
                if(!s_test_mode && m_cfg->get_tracy_mode() != tracy_mode::off) {
231!
323
                        if constexpr(CELERITY_TRACY_SUPPORT) {
324
                                CELERITY_WARN("Profiling with Tracy is enabled. Performance may be negatively impacted.");
325
                        } else {
326
                                CELERITY_WARN("CELERITY_TRACY is set, but Celerity was compiled without Tracy support. Ignoring.");
×
327
                        }
328
                }
329

330
                cgf_diagnostics::make_available();
231✔
331

332
                std::vector<sycl::device> devices;
231✔
333
                {
334
                        CELERITY_DETAIL_TRACY_ZONE_SCOPED("runtime::select_devices", PaleVioletRed);
335
                        devices = std::visit([&](const auto& value) { return select_devices(host_cfg, value, sycl::platform::get_platforms()); }, user_devices_or_selector);
462✔
336
                        assert(!devices.empty()); // postcondition of select_devices
231✔
337
                }
338

339
                {
340
                        const auto& pin_cfg = m_cfg->get_thread_pinning_config();
231✔
341
                        const thread_pinning::runtime_configuration thread_pinning_cfg{
231✔
342
                            .enabled = pin_cfg.enabled,
231✔
343
                            .num_devices = static_cast<uint32_t>(devices.size()),
231✔
344
                            .use_backend_device_submission_threads = m_cfg->should_use_backend_device_submission_threads(),
231✔
345
                            .num_legacy_processes = static_cast<uint32_t>(host_cfg.node_count),
231✔
346
                            .legacy_process_index = static_cast<uint32_t>(host_cfg.local_rank),
231✔
347
                            .standard_core_start_id = pin_cfg.starting_from_core,
231✔
348
                            .hardcoded_core_ids = pin_cfg.hardcoded_core_ids,
231✔
349
                        };
462✔
350
                        m_thread_pinner = std::make_unique<thread_pinning::thread_pinner>(thread_pinning_cfg);
231✔
351
                        name_and_pin_and_order_this_thread(named_threads::thread_type::application);
231✔
352
                }
231✔
353

354
                const sycl_backend::configuration backend_config = {
231✔
355
                    .per_device_submission_threads = m_cfg->should_use_backend_device_submission_threads(), .profiling = m_cfg->should_enable_device_profiling()};
231✔
356
                auto backend = make_sycl_backend(select_backend(sycl_backend_enumerator{}, devices), devices, backend_config);
231✔
357
                const auto system = backend->get_system_info(); // backend is about to be moved
231✔
358

359
                if(m_cfg->is_dry_run()) {
231✔
360
                        m_exec = std::make_unique<dry_run_executor>(static_cast<executor::delegate*>(this));
6✔
361
                } else {
362
#if CELERITY_ENABLE_MPI
363
                        auto comm = std::make_unique<mpi_communicator>(collective_clone_from, MPI_COMM_WORLD);
225✔
364
#else
365
                        auto comm = std::make_unique<local_communicator>();
366
#endif
367
                        m_exec = std::make_unique<live_executor>(std::move(backend), std::move(comm), static_cast<executor::delegate*>(this));
225✔
368
                }
225✔
369

370
                if(m_cfg->should_record()) {
231✔
371
                        m_task_recorder = std::make_unique<task_recorder>();
16✔
372
                        m_command_recorder = std::make_unique<command_recorder>();
16✔
373
                        m_instruction_recorder = std::make_unique<instruction_recorder>();
16✔
374
                }
375

376
                task_manager::policy_set task_mngr_policy;
231✔
377
                // Merely _declaring_ an uninitialized read is legitimate as long as the kernel does not actually perform the read at runtime - this might happen in the
378
                // first iteration of a submit-loop. We could get rid of this case by making access-modes a runtime property of accessors (cf
379
                // https://github.com/celerity/meta/issues/74).
380
                task_mngr_policy.uninitialized_read_error = CELERITY_ACCESS_PATTERN_DIAGNOSTICS ? error_policy::log_warning : error_policy::ignore;
231✔
381

382
                m_task_mngr = std::make_unique<task_manager>(m_num_nodes, m_tdag, m_task_recorder.get(), static_cast<task_manager::delegate*>(this), task_mngr_policy);
231✔
383
                if(m_cfg->get_horizon_step()) m_task_mngr->set_horizon_step(m_cfg->get_horizon_step().value());
231!
384
                if(m_cfg->get_horizon_max_parallelism()) m_task_mngr->set_horizon_max_parallelism(m_cfg->get_horizon_max_parallelism().value());
231!
385

386
                scheduler::policy_set schdlr_policy;
231✔
387
                // Any uninitialized read that is observed on CDAG generation was already logged on task generation, unless we have a bug.
388
                schdlr_policy.command_graph_generator.uninitialized_read_error = error_policy::ignore;
231✔
389
                schdlr_policy.instruction_graph_generator.uninitialized_read_error = error_policy::ignore;
231✔
390
                schdlr_policy.command_graph_generator.overlapping_write_error = CELERITY_ACCESS_PATTERN_DIAGNOSTICS ? error_policy::log_error : error_policy::ignore;
231✔
391
                schdlr_policy.instruction_graph_generator.overlapping_write_error =
231✔
392
                    CELERITY_ACCESS_PATTERN_DIAGNOSTICS ? error_policy::log_error : error_policy::ignore;
393
                schdlr_policy.instruction_graph_generator.unsafe_oversubscription_error = error_policy::log_warning;
231✔
394

395
                // The scheduler references tasks by pointer, so we make sure its lifetime is shorter than the task_manager's.
396
                m_schdlr = std::make_unique<scheduler>(
693✔
397
                    m_num_nodes, m_local_nid, system, static_cast<scheduler::delegate*>(this), m_command_recorder.get(), m_instruction_recorder.get(), schdlr_policy);
462✔
398
                if(m_cfg->get_lookahead() != experimental::lookahead::automatic) { m_schdlr->set_lookahead(m_cfg->get_lookahead()); }
231✔
399

400
                // task_manager will pass generated tasks through its delegate, so generate the init epoch only after the scheduler has been initialized
401
                m_task_mngr->generate_epoch_task(epoch_action::init);
231✔
402

403
                m_num_local_devices = system.devices.size();
231✔
404
        }
462✔
405

406
        void runtime::impl::require_call_from_application_thread() const {
7,682✔
407
                if(std::this_thread::get_id() != m_application_thread) {
7,682✔
408
                        utils::panic("Celerity runtime, queue, handler, buffer and host_object types must only be constructed, used, and destroyed from the "
40✔
409
                                     "application thread. Make sure that you did not accidentally capture one of these types in a host_task.");
410
                }
411
        }
7,672✔
412

413
        runtime::impl::~impl() {
231✔
414
                // LCOV_EXCL_START
415
                if(m_num_live_queues != 0 || !m_live_buffers.empty() || !m_live_host_objects.empty()) {
416
                        // this call might originate from static destruction - we cannot assume spdlog to still be around
417
                        utils::panic("Detected an attempt to destroy runtime while at least one queue, buffer or host_object was still alive. This likely means "
418
                                     "that one of these objects was leaked, or at least its lifetime extended beyond the scope of main(). This is undefined.");
419
                }
420
                // LCOV_EXCL_STOP
421

422
                require_call_from_application_thread();
231✔
423

424
                CELERITY_DETAIL_TRACY_ZONE_SCOPED("runtime::shutdown", DimGray);
425

426
                // Create and await the shutdown epoch
427
                sync(epoch_action::shutdown);
231✔
428

429
                // The shutdown epoch is, by definition, the last task (and command / instruction) issued. Since it has now completed, no more scheduler -> executor
430
                // traffic will occur, and `runtime` can stop functioning as a scheduler_delegate (which would require m_exec to be live).
431
                m_exec.reset();
231✔
432

433
                // task_manager references the scheduler as its delegate, so we destroy it first.
434
                m_task_mngr.reset();
231✔
435

436
                // ~executor() joins its thread after notifying the scheduler that the shutdown epoch has been reached, which means that this notification is
437
                // sequenced-before the destructor return, and `runtime` can now stop functioning as an executor_delegate (which would require m_schdlr to be live).
438
                m_schdlr.reset();
231✔
439

440
                // With scheduler and executor threads gone, all recorders can be safely accessed from the runtime / application thread
441
                if(spdlog::should_log(log_level::info) && m_cfg->should_print_graphs()) {
231!
442
                        if(m_local_nid == 0) { // It's the same across all nodes
16✔
443
                                assert(m_task_recorder.get() != nullptr);
8✔
444
                                const auto tdag_str = detail::print_task_graph(*m_task_recorder);
24✔
445
                                CELERITY_INFO("Task graph:\n\n{}\n", tdag_str);
8!
446
                        }
8✔
447

448
                        assert(m_command_recorder.get() != nullptr);
16✔
449
                        auto cdag_str = print_command_graph(m_local_nid, *m_command_recorder);
48✔
450
                        if(!is_dry_run()) { cdag_str = gather_command_graph(cdag_str, m_num_nodes, m_local_nid); } // must be called on all nodes
16!
451

452
                        if(m_local_nid == 0) {
16✔
453
                                // Avoid racing on stdout with other nodes (funneled through mpirun)
454
                                if(!is_dry_run()) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); }
8!
455
                                CELERITY_INFO("Command graph:\n\n{}\n", cdag_str);
8!
456
                        }
457

458
                        // IDAGs become unreadable when all nodes print them at the same time - TODO attempt gathering them as well?
459
                        if(m_local_nid == 0) {
16✔
460
                                // we are allowed to deref m_instruction_recorder / m_command_recorder because the scheduler thread has exited at this point
461
                                const auto idag_str = detail::print_instruction_graph(*m_instruction_recorder, *m_command_recorder, *m_task_recorder);
24✔
462
                                CELERITY_INFO("Instruction graph on node 0:\n\n{}\n", idag_str);
8!
463
                        }
8✔
464
                }
16✔
465

466
                m_instruction_recorder.reset();
231✔
467
                m_command_recorder.reset();
231✔
468
                m_task_recorder.reset();
231✔
469

470
                cgf_diagnostics::teardown();
231✔
471

472
                if(!s_test_mode) { mpi_finalize_once(); }
231✔
473
        }
231✔
474

475
        task_id runtime::impl::submit(raw_command_group&& cg) {
1,876✔
476
                require_call_from_application_thread();
1,876✔
477
                maybe_prune_task_graph();
1,875✔
478
                return m_task_mngr->generate_command_group_task(std::move(cg));
1,875✔
479
        }
480

481
        task_id runtime::impl::fence(buffer_access access, std::unique_ptr<task_promise> fence_promise) {
51✔
482
                require_call_from_application_thread();
51✔
483
                maybe_prune_task_graph();
51✔
484
                return m_task_mngr->generate_fence_task(std::move(access), std::move(fence_promise));
51✔
485
        }
486

487
        task_id runtime::impl::fence(host_object_effect effect, std::unique_ptr<task_promise> fence_promise) {
18✔
488
                require_call_from_application_thread();
18✔
489
                maybe_prune_task_graph();
17✔
490
                return m_task_mngr->generate_fence_task(effect, std::move(fence_promise));
17✔
491
        }
492

493
        task_id runtime::impl::sync(epoch_action action) {
574✔
494
                require_call_from_application_thread();
574✔
495

496
                maybe_prune_task_graph();
573✔
497
                auto promise = std::make_unique<epoch_promise>();
573✔
498
                const auto future = promise->get_future();
573✔
499
                const auto epoch = m_task_mngr->generate_epoch_task(action, std::move(promise));
573✔
500
                future.wait();
573✔
501
                return epoch;
573✔
502
        }
573✔
503

504
        void runtime::impl::maybe_prune_task_graph() {
2,516✔
505
                require_call_from_application_thread();
2,516✔
506

507
                const auto current_epoch = m_latest_epoch_reached.load(std::memory_order_relaxed);
2,516✔
508
                if(current_epoch > m_last_epoch_pruned_before) {
2,516✔
509
                        m_tdag.erase_before_epoch(current_epoch);
841✔
510
                        m_last_epoch_pruned_before = current_epoch;
841✔
511
                }
512
        }
2,516✔
513

514
        std::string gather_command_graph(const std::string& graph_str, const size_t num_nodes, const node_id local_nid) {
18✔
515
#if CELERITY_ENABLE_MPI
516
                const auto comm = MPI_COMM_WORLD;
18✔
517
                const int tag = 0xCDA6; // aka 'CDAG' - Celerity does not perform any other peer-to-peer communication over MPI_COMM_WORLD
18✔
518

519
                // Send local graph to rank 0 on all other nodes
520
                if(local_nid != 0) {
18✔
521
                        const uint64_t usize = graph_str.size();
9✔
522
                        assert(usize < std::numeric_limits<int32_t>::max());
9✔
523
                        const int32_t size = static_cast<int32_t>(usize);
9✔
524
                        MPI_Send(&size, 1, MPI_INT32_T, 0, tag, comm);
9✔
525
                        if(size > 0) MPI_Send(graph_str.data(), static_cast<int32_t>(size), MPI_BYTE, 0, tag, comm);
9!
526
                        return "";
27✔
527
                }
528
                // On node 0, receive and combine
529
                std::vector<std::string> graphs;
9✔
530
                graphs.push_back(graph_str);
9✔
531
                for(node_id peer = 1; peer < num_nodes; ++peer) {
18✔
532
                        int32_t size = 0;
9✔
533
                        MPI_Recv(&size, 1, MPI_INT32_T, static_cast<int>(peer), tag, comm, MPI_STATUS_IGNORE);
9✔
534
                        if(size > 0) {
9!
535
                                std::string graph;
9✔
536
                                graph.resize(size);
9✔
537
                                MPI_Recv(graph.data(), size, MPI_BYTE, static_cast<int>(peer), tag, comm, MPI_STATUS_IGNORE);
9✔
538
                                graphs.push_back(std::move(graph));
9✔
539
                        }
9✔
540
                }
541
                return combine_command_graphs(graphs);
27✔
542
#else  // CELERITY_ENABLE_MPI
543
                assert(num_nodes == 1 && local_nid == 0);
544
                return graph_str;
545
#endif // CELERITY_ENABLE_MPI
546
        }
9✔
547

548
        // task_manager::delegate
549

550
        void runtime::impl::task_created(const task* tsk) {
3,327✔
551
                assert(m_schdlr != nullptr);
3,327✔
552
                m_schdlr->notify_task_created(tsk);
3,327✔
553
        }
3,327✔
554

555
        // scheduler::delegate
556

557
        void runtime::impl::flush(std::vector<const instruction*> instructions, std::vector<outbound_pilot> pilots) {
3,962✔
558
                // thread-safe
559
                assert(m_exec != nullptr);
3,962✔
560
                m_exec->submit(std::move(instructions), std::move(pilots));
3,962✔
561
        }
3,962✔
562

563
        // executor::delegate
564

565
        void runtime::impl::horizon_reached(const task_id horizon_tid) {
582✔
566
                assert(!m_latest_horizon_reached || *m_latest_horizon_reached < horizon_tid);
582✔
567
                assert(m_latest_epoch_reached.load(std::memory_order::relaxed) < horizon_tid); // relaxed: written only by this thread
1,164✔
568

569
                if(m_latest_horizon_reached.has_value()) {
582✔
570
                        m_latest_epoch_reached.store(*m_latest_horizon_reached, std::memory_order_relaxed);
553✔
571
                        m_schdlr->notify_epoch_reached(*m_latest_horizon_reached);
553✔
572
                }
573
                m_latest_horizon_reached = horizon_tid;
582✔
574
        }
582✔
575

576
        void runtime::impl::epoch_reached(const task_id epoch_tid) {
804✔
577
                // m_latest_horizon_reached does not need synchronization (see definition), all other accesses are implicitly synchronized.
578
                assert(!m_latest_horizon_reached || *m_latest_horizon_reached < epoch_tid);
804✔
579
                assert(epoch_tid == 0 || m_latest_epoch_reached.load(std::memory_order_relaxed) < epoch_tid);
1,377✔
580

581
                m_latest_epoch_reached.store(epoch_tid, std::memory_order_relaxed);
804✔
582
                m_schdlr->notify_epoch_reached(epoch_tid);
804✔
583
                m_latest_horizon_reached = std::nullopt; // Any non-applied horizon is now behind the epoch and will therefore never become an epoch itself
804✔
584
        }
804✔
585

586
        void runtime::impl::create_queue() {
224✔
587
                require_call_from_application_thread();
224✔
588
                ++m_num_live_queues;
223✔
589
        }
223✔
590

591
        void runtime::impl::destroy_queue() {
224✔
592
                require_call_from_application_thread();
224✔
593

594
                assert(m_num_live_queues > 0);
223✔
595
                --m_num_live_queues;
223✔
596
        }
223✔
597

598
        bool runtime::impl::is_dry_run() const { return m_cfg->is_dry_run(); }
30✔
599

600
        allocation_id runtime::impl::create_user_allocation(void* const ptr) {
114✔
601
                require_call_from_application_thread();
114✔
602
                const auto aid = allocation_id(user_memory_id, m_next_user_allocation_id++);
113✔
603
                m_exec->track_user_allocation(aid, ptr);
113✔
604
                return aid;
113✔
605
        }
606

607
        buffer_id runtime::impl::create_buffer(const range<3>& range, const size_t elem_size, const size_t elem_align, const allocation_id user_aid) {
347✔
608
                require_call_from_application_thread();
347✔
609

610
                const auto bid = m_next_buffer_id++;
346✔
611
                m_live_buffers.emplace(bid);
346✔
612
                m_task_mngr->notify_buffer_created(bid, range, user_aid != null_allocation_id);
346✔
613
                m_schdlr->notify_buffer_created(bid, range, elem_size, elem_align, user_aid);
346✔
614
                return bid;
692✔
615
        }
616

617
        void runtime::impl::set_buffer_debug_name(const buffer_id bid, const std::string& debug_name) {
23✔
618
                require_call_from_application_thread();
23✔
619

620
                assert(utils::contains(m_live_buffers, bid));
23✔
621
                m_task_mngr->notify_buffer_debug_name_changed(bid, debug_name);
23✔
622
                m_schdlr->notify_buffer_debug_name_changed(bid, debug_name);
23✔
623
        }
23✔
624

625
        void runtime::impl::destroy_buffer(const buffer_id bid) {
347✔
626
                require_call_from_application_thread();
347✔
627

628
                assert(utils::contains(m_live_buffers, bid));
346✔
629
                m_schdlr->notify_buffer_destroyed(bid);
346✔
630
                m_task_mngr->notify_buffer_destroyed(bid);
346✔
631
                m_live_buffers.erase(bid);
346✔
632
        }
346✔
633

634
        host_object_id runtime::impl::create_host_object(std::unique_ptr<host_object_instance> instance) {
34✔
635
                require_call_from_application_thread();
34✔
636

637
                const auto hoid = m_next_host_object_id++;
33✔
638
                m_live_host_objects.emplace(hoid);
33✔
639
                const bool owns_instance = instance != nullptr;
33✔
640
                if(owns_instance) { m_exec->track_host_object_instance(hoid, std::move(instance)); }
33✔
641
                m_task_mngr->notify_host_object_created(hoid);
33✔
642
                m_schdlr->notify_host_object_created(hoid, owns_instance);
33✔
643
                return hoid;
66✔
644
        }
645

646
        void runtime::impl::destroy_host_object(const host_object_id hoid) {
34✔
647
                require_call_from_application_thread();
34✔
648

649
                assert(utils::contains(m_live_host_objects, hoid));
33✔
650
                m_schdlr->notify_host_object_destroyed(hoid);
33✔
651
                m_task_mngr->notify_host_object_destroyed(hoid);
33✔
652
                m_live_host_objects.erase(hoid);
33✔
653
        }
33✔
654

655
        reduction_id runtime::impl::create_reduction(std::unique_ptr<reducer> reducer) {
65✔
656
                require_call_from_application_thread();
65✔
657

658
                const auto rid = m_next_reduction_id++;
65✔
659
                m_exec->track_reducer(rid, std::move(reducer));
65✔
660
                return rid;
130✔
661
        }
662

663
        void runtime::impl::set_scheduler_lookahead(const experimental::lookahead lookahead) {
4✔
664
                require_call_from_application_thread();
4✔
665
                m_schdlr->set_lookahead(lookahead);
4✔
666
        }
4✔
667

668
        void runtime::impl::flush_scheduler() {
1,000✔
669
                require_call_from_application_thread();
1,000✔
670
                m_schdlr->flush_commands();
1,000✔
671
        }
1,000✔
672

673
        bool runtime::s_mpi_initialized = false;
674
        bool runtime::s_mpi_finalized = false;
675

676
        runtime runtime::s_instance; // definition of static member
677

678
        void runtime::mpi_initialize_once(int* argc, char*** argv) {
56✔
679
#if CELERITY_ENABLE_MPI
680
                CELERITY_DETAIL_TRACY_ZONE_SCOPED_V("mpi::init", LightSkyBlue, "MPI_Init");
681
                assert(!s_mpi_initialized);
56✔
682
                int provided = -1;
56✔
683
                MPI_Init_thread(argc, argv, MPI_THREAD_MULTIPLE, &provided);
56✔
684
                assert(provided == MPI_THREAD_MULTIPLE);
56✔
685
#endif // CELERITY_ENABLE_MPI
686
                s_mpi_initialized = true;
56✔
687
        }
56✔
688

689
        void runtime::mpi_finalize_once() {
56✔
690
#if CELERITY_ENABLE_MPI
691
                CELERITY_DETAIL_TRACY_ZONE_SCOPED_V("mpi::finalize", LightSkyBlue, "MPI_Finalize");
692
                assert(s_mpi_initialized && !s_mpi_finalized && (!s_test_mode || !has_instance()));
56✔
693
                MPI_Finalize();
56✔
694
#endif // CELERITY_ENABLE_MPI
695
                s_mpi_finalized = true;
56✔
696
        }
56✔
697

698
        void runtime::init(int* argc, char** argv[], const devices_or_selector& user_devices_or_selector) {
231✔
699
                assert(!has_instance());
231✔
700
                s_instance.m_impl = std::make_unique<runtime::impl>(argc, argv, user_devices_or_selector);
231✔
701
                if(!s_test_mode) { atexit(shutdown); }
231✔
702
        }
231✔
703

704
        runtime& runtime::get_instance() {
4,788✔
705
                if(!has_instance()) { throw std::runtime_error("Runtime has not been initialized"); }
4,788!
706
                return s_instance;
4,788✔
707
        }
708

709
        void runtime::shutdown() { s_instance.m_impl.reset(); }
241✔
710

711
        task_id runtime::submit(raw_command_group&& cg) { return m_impl->submit(std::move(cg)); }
1,876✔
712

713
        task_id runtime::fence(buffer_access access, std::unique_ptr<task_promise> fence_promise) {
51✔
714
                return m_impl->fence(std::move(access), std::move(fence_promise));
51✔
715
        }
716

717
        task_id runtime::fence(host_object_effect effect, std::unique_ptr<task_promise> fence_promise) { return m_impl->fence(effect, std::move(fence_promise)); }
19✔
718

719
        task_id runtime::sync(detail::epoch_action action) { return m_impl->sync(action); }
343✔
720

721
        void runtime::create_queue() { m_impl->create_queue(); }
224✔
722

723
        void runtime::destroy_queue() { m_impl->destroy_queue(); }
224✔
724

725
        allocation_id runtime::create_user_allocation(void* const ptr) { return m_impl->create_user_allocation(ptr); }
114✔
726

727
        buffer_id runtime::create_buffer(const range<3>& range, const size_t elem_size, const size_t elem_align, const allocation_id user_aid) {
347✔
728
                return m_impl->create_buffer(range, elem_size, elem_align, user_aid);
347✔
729
        }
730

731
        void runtime::set_buffer_debug_name(const buffer_id bid, const std::string& debug_name) { m_impl->set_buffer_debug_name(bid, debug_name); }
23✔
732

733
        void runtime::destroy_buffer(const buffer_id bid) { m_impl->destroy_buffer(bid); }
347✔
734

735
        host_object_id runtime::create_host_object(std::unique_ptr<host_object_instance> instance) { return m_impl->create_host_object(std::move(instance)); }
35✔
736

737
        void runtime::destroy_host_object(const host_object_id hoid) { m_impl->destroy_host_object(hoid); }
34✔
738

739
        reduction_id runtime::create_reduction(std::unique_ptr<reducer> reducer) { return m_impl->create_reduction(std::move(reducer)); }
65✔
740

741
        bool runtime::is_dry_run() const { return m_impl->is_dry_run(); }
6✔
742

743
        void runtime::set_scheduler_lookahead(const experimental::lookahead lookahead) { m_impl->set_scheduler_lookahead(lookahead); }
4✔
744

745
        void runtime::flush_scheduler() { m_impl->flush_scheduler(); }
1,000✔
746

747
        bool runtime::s_test_mode = false;
748
        bool runtime::s_test_active = false;
749
        bool runtime::s_test_runtime_was_instantiated = false;
750

751
} // namespace detail
752
} // namespace celerity
753

754

755
#define CELERITY_DETAIL_TAIL_INCLUDE
756
#include "testspy/runtime_testspy.inl"
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc