| | | 1 | | // Copyright 2025 Digital Holography Foundation |
| | | 2 | | // |
| | | 3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
| | | 4 | | // you may not use this file except in compliance with the License. |
| | | 5 | | // You may obtain a copy of the License at |
| | | 6 | | // |
| | | 7 | | // http://www.apache.org/licenses/LICENSE-2.0 |
| | | 8 | | // |
| | | 9 | | // Unless required by applicable law or agreed to in writing, software |
| | | 10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
| | | 11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| | | 12 | | // See the License for the specific language governing permissions and |
| | | 13 | | // limitations under the License. |
| | | 14 | | |
| | | 15 | | #include "holoflow/runtime/compiler.hh" |
| | | 16 | | |
| | | 17 | | #include <boost/graph/adjacency_list.hpp> |
| | | 18 | | #include <boost/graph/breadth_first_search.hpp> |
| | | 19 | | #include <boost/graph/topological_sort.hpp> |
| | | 20 | | #include <chrono> |
| | | 21 | | #include <format> |
| | | 22 | | #include <fstream> |
| | | 23 | | #include <iostream> |
| | | 24 | | #include <mutex> |
| | | 25 | | #include <numeric> |
| | | 26 | | #include <nvtx3/nvtx3.hpp> |
| | | 27 | | #include <queue> |
| | | 28 | | #include <ranges> |
| | | 29 | | #include <set> |
| | | 30 | | #include <stack> |
| | | 31 | | #include <thread> |
| | | 32 | | #include <type_traits> |
| | | 33 | | #include <unordered_map> |
| | | 34 | | #include <unordered_set> |
| | | 35 | | #include <variant> |
| | | 36 | | |
| | | 37 | | #include "curaii/cuda.hh" |
| | | 38 | | #include "holoflow/core/graph_spec.hh" |
| | | 39 | | #include "holoflow/core/registry.hh" |
| | | 40 | | #include "holoflow/core/tasks.hh" |
| | | 41 | | #include "holoflow/core/tensor.hh" |
| | | 42 | | #include "holoflow/runtime/graph_display.hh" |
| | | 43 | | #include "holoflow/runtime/graph_exec.hh" |
| | | 44 | | #include "spdlog/sinks/basic_file_sink.h" |
| | | 45 | | #include "spdlog/sinks/stdout_color_sinks.h" |
| | | 46 | | #include "spdlog/spdlog.h" |
| | | 47 | | |
| | | 48 | | namespace holoflow::runtime { |
| | | 49 | | |
| | | 50 | | // ------------------------------------------------------------------------------------------------- |
| | | 51 | | // Internal Types & Error Handling |
| | | 52 | | // ------------------------------------------------------------------------------------------------- |
| | | 53 | | |
| | | 54 | | class CompilerException : public std::runtime_error { |
| | | 55 | | public: |
| | | 56 | | using std::runtime_error::runtime_error; |
| | | 57 | | }; |
| | | 58 | | |
| | | 59 | | // ------------------------------------------------------------------------------------------------- |
| | | 60 | | // Profiling Data Structures |
| | | 61 | | // ------------------------------------------------------------------------------------------------- |
| | | 62 | | |
| | | 63 | | struct TraceEvent { |
| | | 64 | | std::string name; |
| | | 65 | | std::string category; |
| | | 66 | | long long start_us; |
| | | 67 | | long long dur_us; |
| | | 68 | | uint32_t tid; |
| | | 69 | | }; |
| | | 70 | | |
| | | 71 | | class CompilationProfiler { |
| | | 72 | | public: |
| | 1 | 73 | | void add_event(std::string name, std::string category, long long start_us, long long dur_us) { |
| | 1 | 74 | | std::lock_guard<std::mutex> lock(mutex_); |
| | 1 | 75 | | uint32_t tid = static_cast<uint32_t>(std::hash<std::thread::id>{}(std::this_thread::get_id())); |
| | 1 | 76 | | events_.push_back({std::move(name), std::move(category), start_us, dur_us, tid}); |
| | 1 | 77 | | } |
| | | 78 | | |
| | 1 | 79 | | void log_summary(std::shared_ptr<spdlog::logger> &logger) const { |
| | 1 | 80 | | if (!logger || events_.empty()) |
| | 0 | 81 | | return; |
| | | 82 | | |
| | 1 | 83 | | double total_time_ms = 0.0; |
| | 1 | 84 | | for (const auto &ev : events_) { |
| | 1 | 85 | | if (ev.name == "Total Compilation") { |
| | 1 | 86 | | total_time_ms = ev.dur_us / 1000.0; |
| | 1 | 87 | | break; |
| | | 88 | | } |
| | 0 | 89 | | } |
| | | 90 | | |
| | 1 | 91 | | logger->info("{:=^60}", " Compilation Passes Summary "); |
| | 1 | 92 | | logger->info("{:<30} | {:>12} | {:>10}", "Pass Name", "Time (ms)", "% Total"); |
| | 1 | 93 | | logger->info("{:-^60}", ""); |
| | | 94 | | |
| | 1 | 95 | | for (const auto &ev : events_) { |
| | 1 | 96 | | if (ev.category != "pass" && ev.name != "Total Compilation") |
| | 1 | 97 | | continue; |
| | | 98 | | |
| | 1 | 99 | | double dur_ms = ev.dur_us / 1000.0; |
| | 1 | 100 | | double percent = (total_time_ms > 0) ? (dur_ms / total_time_ms) * 100.0 : 0.0; |
| | | 101 | | |
| | 1 | 102 | | if (ev.name == "Total Compilation") { |
| | 1 | 103 | | logger->info("{:-^60}", ""); |
| | | 104 | | } |
| | 1 | 105 | | logger->info("{:<30} | {:>12.3f} | {:>9.2f}%", ev.name, dur_ms, percent); |
| | 1 | 106 | | } |
| | 1 | 107 | | logger->info("{:=^60}", ""); |
| | 1 | 108 | | } |
| | | 109 | | |
| | 1 | 110 | | void dump_chrome_tracing(const std::filesystem::path &filepath) const { |
| | 1 | 111 | | std::ofstream out(filepath); |
| | 1 | 112 | | if (!out.is_open()) |
| | 0 | 113 | | return; |
| | | 114 | | |
| | 1 | 115 | | out << "[\n"; |
| | 1 | 116 | | for (size_t i = 0; i < events_.size(); ++i) { |
| | 1 | 117 | | const auto &ev = events_[i]; |
| | 1 | 118 | | out << " {" |
| | | 119 | | << "\"name\": \"" << ev.name << "\", " |
| | | 120 | | << "\"cat\": \"" << ev.category << "\", " |
| | | 121 | | << "\"ph\": \"X\", " |
| | | 122 | | << "\"ts\": " << ev.start_us << ", " |
| | | 123 | | << "\"dur\": " << ev.dur_us << ", " |
| | | 124 | | << "\"pid\": 1, " |
| | | 125 | | << "\"tid\": " << ev.tid << "}"; |
| | 1 | 126 | | if (i < events_.size() - 1) |
| | 1 | 127 | | out << ","; |
| | 1 | 128 | | out << "\n"; |
| | 1 | 129 | | } |
| | 1 | 130 | | out << "]\n"; |
| | 1 | 131 | | } |
| | | 132 | | |
| | | 133 | | private: |
| | | 134 | | std::vector<TraceEvent> events_; |
| | | 135 | | std::mutex mutex_; |
| | | 136 | | }; |
| | | 137 | | |
| | | 138 | | // ------------------------------------------------------------------------------------------------- |
| | | 139 | | // Observability & Scoped Tracer |
| | | 140 | | // ------------------------------------------------------------------------------------------------- |
| | | 141 | | |
| | | 142 | | class ScopedTrace { |
| | | 143 | | public: |
| | | 144 | | using Clock = std::chrono::steady_clock; |
| | | 145 | | using SystemClock = std::chrono::system_clock; |
| | | 146 | | |
| | | 147 | | ScopedTrace(std::string name, std::string category, std::shared_ptr<spdlog::logger> logger, |
| | | 148 | | CompilationProfiler *profiler) |
| | 1 | 149 | | : name_(std::move(name)), category_(std::move(category)), logger_(std::move(logger)), |
| | 1 | 150 | | profiler_(profiler) { |
| | | 151 | | |
| | 1 | 152 | | start_time_ = Clock::now(); |
| | 1 | 153 | | start_us_ = std::chrono::time_point_cast<std::chrono::microseconds>(SystemClock::now()) |
| | | 154 | | .time_since_epoch() |
| | | 155 | | .count(); |
| | | 156 | | |
| | 1 | 157 | | if (logger_ && category_ == "pass") { |
| | 1 | 158 | | logger_->trace(">> Begin Pass: {}", name_); |
| | | 159 | | } |
| | | 160 | | |
| | 1 | 161 | | nvtxRangePush(name_.c_str()); |
| | 1 | 162 | | } |
| | | 163 | | |
| | 1 | 164 | | ~ScopedTrace() { |
| | 1 | 165 | | auto end_time = Clock::now(); |
| | 1 | 166 | | auto dur_us = |
| | | 167 | | std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time_).count(); |
| | | 168 | | |
| | 1 | 169 | | if (logger_ && category_ == "pass") { |
| | 1 | 170 | | logger_->info("<< End Pass: {} ({:.3f} ms)", name_, dur_us / 1000.0); |
| | | 171 | | } |
| | | 172 | | |
| | 1 | 173 | | if (profiler_) { |
| | 1 | 174 | | profiler_->add_event(name_, category_, start_us_, dur_us); |
| | | 175 | | } |
| | | 176 | | |
| | 1 | 177 | | nvtxRangePop(); |
| | 1 | 178 | | } |
| | | 179 | | |
| | | 180 | | private: |
| | | 181 | | std::string name_; |
| | | 182 | | std::string category_; |
| | | 183 | | std::shared_ptr<spdlog::logger> logger_; |
| | | 184 | | CompilationProfiler *profiler_; |
| | | 185 | | Clock::time_point start_time_; |
| | | 186 | | long long start_us_; |
| | | 187 | | }; |
| | | 188 | | |
| | | 189 | | // ------------------------------------------------------------------------------------------------- |
| | | 190 | | // Storage Adapter for owning tasks |
| | | 191 | | // ------------------------------------------------------------------------------------------------- |
| | | 192 | | class TaskStorageAdapter : public core::IOStorageAccess { |
| | | 193 | | public: |
| | | 194 | | TaskStorageAdapter(std::vector<int> in_tids, std::vector<int> out_tids, ExecResouces &resources); |
| | | 195 | | [[nodiscard]] core::Storage &owned_input_storage(size_t index) override; |
| | | 196 | | [[nodiscard]] core::Storage &owned_output_storage(size_t index) override; |
| | | 197 | | |
| | | 198 | | private: |
| | | 199 | | std::vector<int> in_tids_; |
| | | 200 | | std::vector<int> out_tids_; |
| | | 201 | | ExecResouces &res_; |
| | | 202 | | }; |
| | | 203 | | |
| | | 204 | | TaskStorageAdapter::TaskStorageAdapter(std::vector<int> in_tids, std::vector<int> out_tids, |
| | | 205 | | ExecResouces &resources) |
| | 1 | 206 | | : in_tids_(std::move(in_tids)), out_tids_(std::move(out_tids)), res_(resources) {} |
| | | 207 | | |
| | 1 | 208 | | core::Storage &TaskStorageAdapter::owned_input_storage(size_t index) { |
| | 1 | 209 | | if (index >= in_tids_.size()) { |
| | 1 | 210 | | throw std::out_of_range("Input index out of range in TaskStorageAdapter"); |
| | | 211 | | } |
| | 1 | 212 | | size_t tid = in_tids_[index]; |
| | 1 | 213 | | size_t sid = res_.tid_to_sid.at(tid); |
| | 1 | 214 | | return *res_.storages.at(sid); |
| | 1 | 215 | | } |
| | | 216 | | |
| | 1 | 217 | | core::Storage &TaskStorageAdapter::owned_output_storage(size_t index) { |
| | 1 | 218 | | if (index >= out_tids_.size()) { |
| | 1 | 219 | | throw std::out_of_range("Output index out of range in TaskStorageAdapter"); |
| | | 220 | | } |
| | 1 | 221 | | size_t tid = out_tids_[index]; |
| | 1 | 222 | | size_t sid = res_.tid_to_sid.at(tid); |
| | 1 | 223 | | return *res_.storages.at(sid); |
| | 1 | 224 | | } |
| | | 225 | | |
| | | 226 | | // ------------------------------------------------------------------------------------------------- |
| | | 227 | | // Compiler Declaration (PIMPL) |
| | | 228 | | // ------------------------------------------------------------------------------------------------- |
| | | 229 | | |
| | | 230 | | class Compiler::Impl { |
| | | 231 | | public: |
| | | 232 | | Impl(core::Registry ®istry, Compiler::Config config); |
| | | 233 | | |
| | | 234 | | std::unique_ptr<CompilerOutput> run(const core::GraphSpec &gspec, |
| | | 235 | | std::unique_ptr<CompilerOutput> prev); |
| | | 236 | | |
| | | 237 | | private: |
| | | 238 | | // --- State --- |
| | | 239 | | core::Registry ®istry_; |
| | | 240 | | Compiler::Config config_; |
| | | 241 | | std::shared_ptr<spdlog::logger> logger_; |
| | | 242 | | CompilationProfiler profiler_; |
| | | 243 | | |
| | 1 | 244 | | const core::GraphSpec *gspec_ = nullptr; |
| | | 245 | | std::unique_ptr<CompilerOutput> prev_; |
| | | 246 | | std::unique_ptr<CompilerOutput> out_; |
| | | 247 | | |
| | | 248 | | // Auxiliary Map: Node Name -> Section ID |
| | | 249 | | std::unordered_map<std::string, size_t> node_to_section_map_; |
| | | 250 | | |
| | | 251 | | // --- Helpers --- |
| | | 252 | | void setup_logging(); |
| | | 253 | | ScopedTrace trace_scope(std::string name, std::string category = "pass"); |
| | | 254 | | void dump_graphviz(const std::string &filename); |
| | | 255 | | template <class TaskInterface, class Factory, class Ctx> |
| | | 256 | | std::unique_ptr<core::ITask> create_or_update_task(Factory &factory, const NodePlan &np, |
| | | 257 | | const Ctx &ctx); |
| | | 258 | | |
| | | 259 | | // --- Pass Declarations --- |
| | | 260 | | void validate_spec(); |
| | | 261 | | void build_graph_structure(); |
| | | 262 | | void run_type_inference(); |
| | | 263 | | void assign_tensor_ids(); |
| | | 264 | | void assign_storage_ids(); |
| | | 265 | | void verify_buffer_consistency(); |
| | | 266 | | void allocate_buffers(); |
| | | 267 | | void create_storage_adapters(); |
| | | 268 | | void partition_sections(); |
| | | 269 | | void assign_streams(); |
| | | 270 | | void instantiate_tasks(); |
| | | 271 | | void bind_tasks(); |
| | | 272 | | |
| | | 273 | | // Generic Pass Runner |
| | | 274 | | template <typename Func> void run_pass(const char *name, Func &&fn) { |
| | | 275 | | auto scope = trace_scope(name, "pass"); |
| | | 276 | | fn(); |
| | | 277 | | } |
| | | 278 | | }; |
| | | 279 | | |
| | | 280 | | // ------------------------------------------------------------------------------------------------- |
| | | 281 | | // Compiler Implementation (PIMPL) |
| | | 282 | | // ------------------------------------------------------------------------------------------------- |
| | | 283 | | |
| | | 284 | | Compiler::Impl::Impl(core::Registry ®istry, Compiler::Config config) |
| | 1 | 285 | | : registry_(registry), config_(std::move(config)) { |
| | 1 | 286 | | setup_logging(); |
| | 1 | 287 | | } |
| | | 288 | | |
| | | 289 | | std::unique_ptr<CompilerOutput> Compiler::Impl::run(const core::GraphSpec &gspec, |
| | | 290 | | std::unique_ptr<CompilerOutput> prev) { |
| | | 291 | | gspec_ = &gspec; |
| | | 292 | | prev_ = std::move(prev); |
| | | 293 | | out_ = std::make_unique<CompilerOutput>(); |
| | | 294 | | |
| | | 295 | | // Use optional to control exactly when the trace ends without double-destruction |
| | | 296 | | std::optional<ScopedTrace> total_trace; |
| | | 297 | | total_trace.emplace(trace_scope("Total Compilation", "lifecycle")); |
| | | 298 | | |
| | | 299 | | try { |
| | | 300 | | run_pass("Validate Spec", [&] { validate_spec(); }); |
| | | 301 | | run_pass("Build Graph Plan", [&] { build_graph_structure(); }); |
| | | 302 | | run_pass("Type Inference", [&] { run_type_inference(); }); |
| | | 303 | | |
| | | 304 | | run_pass("Tensor IDs", [&] { assign_tensor_ids(); }); |
| | | 305 | | run_pass("Storage Mapping", [&] { assign_storage_ids(); }); |
| | | 306 | | run_pass("Buffer Consistency", [&] { verify_buffer_consistency(); }); |
| | | 307 | | run_pass("Buffer Allocation", [&] { allocate_buffers(); }); |
| | | 308 | | |
| | | 309 | | run_pass("Storage Adapters", [&] { create_storage_adapters(); }); |
| | | 310 | | |
| | | 311 | | run_pass("Section Partitioning", [&] { partition_sections(); }); |
| | | 312 | | run_pass("Stream Assignment", [&] { assign_streams(); }); |
| | | 313 | | run_pass("Task Instantiation", [&] { instantiate_tasks(); }); |
| | | 314 | | run_pass("Task Binding", [&] { bind_tasks(); }); |
| | | 315 | | |
| | | 316 | | if (config_.dump_dot_on_failure) { |
| | | 317 | | run_pass("Dump Graphviz", [&] { dump_graphviz("compilation_success.dot"); }); |
| | | 318 | | } |
| | | 319 | | } catch (const std::exception &e) { |
| | | 320 | | logger_->error("Compilation Failed: {}", e.what()); |
| | | 321 | | if (config_.dump_dot_on_failure) { |
| | | 322 | | run_pass("Dump Graphviz", [&] { dump_graphviz("compilation_failure.dot"); }); |
| | | 323 | | } |
| | | 324 | | |
| | | 325 | | total_trace.reset(); // Stop timer before throwing |
| | | 326 | | |
| | | 327 | | try { |
| | | 328 | | CUDA_CHECK(cudaDeviceSynchronize()); |
| | | 329 | | } catch (const std::exception &cuda_e) { |
| | | 330 | | logger_->error("CUDA error during cleanup: {}", cuda_e.what()); |
| | | 331 | | } |
| | | 332 | | |
| | | 333 | | try { |
| | | 334 | | CUDA_CHECK(cudaGetLastError()); |
| | | 335 | | } catch (const std::exception &cuda_e) { |
| | | 336 | | logger_->error("CUDA error during cleanup: {}", cuda_e.what()); |
| | | 337 | | } |
| | | 338 | | |
| | | 339 | | logger_->flush(); |
| | | 340 | | throw; |
| | | 341 | | } |
| | | 342 | | |
| | | 343 | | // Stop the total compilation timer safely |
| | | 344 | | total_trace.reset(); |
| | | 345 | | |
| | | 346 | | if (config_.enable_profiling) { |
| | | 347 | | // profiler_.log_summary(logger_); |
| | | 348 | | run_pass("Dump log summary", [&] { profiler_.log_summary(logger_); }); |
| | | 349 | | if (!config_.log_dir.empty()) { |
| | | 350 | | // profiler_.dump_chrome_tracing(config_.log_dir / config_.trace_filename); |
| | | 351 | | run_pass("Dump Chrome Tracing", |
| | | 352 | | [&] { profiler_.dump_chrome_tracing(config_.log_dir / config_.trace_filename); }); |
| | | 353 | | } |
| | | 354 | | } |
| | | 355 | | |
| | | 356 | | return std::move(out_); |
| | | 357 | | } |
| | | 358 | | |
| | 1 | 359 | | void Compiler::Impl::setup_logging() { |
| | 1 | 360 | | if (spdlog::get("compiler")) { |
| | 0 | 361 | | spdlog::drop("compiler"); |
| | | 362 | | } |
| | | 363 | | |
| | 1 | 364 | | if (!config_.log_dir.empty()) { |
| | 1 | 365 | | std::filesystem::create_directories(config_.log_dir); |
| | 1 | 366 | | auto path = config_.log_dir / "compiler.log"; |
| | 1 | 367 | | logger_ = spdlog::basic_logger_mt("compiler", path.string(), true); |
| | 1 | 368 | | } else { |
| | 1 | 369 | | logger_ = spdlog::stdout_color_mt("compiler"); |
| | | 370 | | } |
| | 1 | 371 | | logger_->set_level(config_.verbose_tracing ? spdlog::level::trace : spdlog::level::info); |
| | 1 | 372 | | } |
| | | 373 | | |
| | 1 | 374 | | ScopedTrace Compiler::Impl::trace_scope(std::string name, std::string category) { |
| | 1 | 375 | | return ScopedTrace(std::move(name), std::move(category), logger_, |
| | | 376 | | config_.enable_profiling ? &profiler_ : nullptr); |
| | 1 | 377 | | } |
| | | 378 | | |
| | 1 | 379 | | void Compiler::Impl::dump_graphviz(const std::string &filename) { |
| | 1 | 380 | | if (config_.log_dir.empty()) { |
| | 0 | 381 | | return; |
| | | 382 | | } |
| | | 383 | | |
| | 1 | 384 | | std::ofstream file(config_.log_dir / filename); |
| | 1 | 385 | | if (!file.is_open()) { |
| | 0 | 386 | | return; |
| | | 387 | | } |
| | | 388 | | |
| | 1 | 389 | | const auto graph_name = std::filesystem::path(filename).stem().string(); |
| | 1 | 390 | | file << to_dot(*out_, GraphCompiledDumpPreferences{}, graph_name); |
| | 1 | 391 | | } |
| | | 392 | | |
| | | 393 | | // ------------------------------------------------------------------------------------------------- |
| | | 394 | | // Pass: Validate Spec |
| | | 395 | | // ------------------------------------------------------------------------------------------------- |
| | 1 | 396 | | void Compiler::Impl::validate_spec() { |
| | 1 | 397 | | std::unordered_set<std::string> names; |
| | 1 | 398 | | std::unordered_set<std::string> edge_dsts; |
| | | 399 | | |
| | 1 | 400 | | auto vertices = boost::make_iterator_range(boost::vertices(*gspec_)); |
| | 1 | 401 | | for (const auto &v : vertices) { |
| | 1 | 402 | | const auto &ns = (*gspec_)[v]; |
| | 1 | 403 | | if (!names.insert(ns.name).second) { |
| | 1 | 404 | | throw CompilerException(std::format("Duplicate node name: '{}'", ns.name)); |
| | | 405 | | } |
| | 1 | 406 | | if (!registry_.is_registered(ns.kind)) { |
| | 1 | 407 | | throw CompilerException(std::format("Unknown node kind '{}'", ns.kind)); |
| | | 408 | | } |
| | 1 | 409 | | } |
| | | 410 | | |
| | 1 | 411 | | auto edges = boost::make_iterator_range(boost::edges(*gspec_)); |
| | 1 | 412 | | for (const auto &e : edges) { |
| | 1 | 413 | | const auto &es = (*gspec_)[e]; |
| | 1 | 414 | | const auto dst = (*gspec_)[boost::target(e, *gspec_)]; |
| | 1 | 415 | | std::string label = std::format("{}:{}", dst.name, es.in_idx); |
| | | 416 | | |
| | 1 | 417 | | if (!edge_dsts.insert(label).second) { |
| | 1 | 418 | | throw CompilerException(std::format("Multiple edges targeting: {}", label)); |
| | | 419 | | } |
| | 1 | 420 | | } |
| | 1 | 421 | | } |
| | | 422 | | |
| | | 423 | | // ------------------------------------------------------------------------------------------------- |
| | | 424 | | // Pass: Build Graph Structure |
| | | 425 | | // ------------------------------------------------------------------------------------------------- |
| | 1 | 426 | | void Compiler::Impl::build_graph_structure() { |
| | | 427 | | using VSpec = core::GraphSpec::vertex_descriptor; |
| | | 428 | | using VPlan = GraphPlan::vertex_descriptor; |
| | 1 | 429 | | std::map<VSpec, VPlan> v_map; |
| | 1 | 430 | | auto &g = out_->graph; |
| | | 431 | | |
| | 1 | 432 | | for (auto v : boost::make_iterator_range(boost::vertices(*gspec_))) { |
| | 1 | 433 | | NodePlan np; |
| | 1 | 434 | | np.spec = (*gspec_)[v]; |
| | 1 | 435 | | v_map[v] = boost::add_vertex(np, g); |
| | 1 | 436 | | } |
| | | 437 | | |
| | 1 | 438 | | for (auto e : boost::make_iterator_range(boost::edges(*gspec_))) { |
| | 1 | 439 | | const auto &es = (*gspec_)[e]; |
| | 1 | 440 | | const auto src = v_map.at(boost::source(e, *gspec_)); |
| | 1 | 441 | | const auto dst = v_map.at(boost::target(e, *gspec_)); |
| | 1 | 442 | | EdgePlan ep; |
| | 1 | 443 | | ep.spec = es; |
| | 1 | 444 | | boost::add_edge(src, dst, ep, g); |
| | 1 | 445 | | } |
| | 1 | 446 | | } |
| | | 447 | | |
| | | 448 | | // ------------------------------------------------------------------------------------------------- |
| | | 449 | | // Pass: Type Inference |
| | | 450 | | // ------------------------------------------------------------------------------------------------- |
| | 1 | 451 | | void Compiler::Impl::run_type_inference() { |
| | 1 | 452 | | auto &g = out_->graph; |
| | 1 | 453 | | std::vector<GraphPlan::vertex_descriptor> topo_order; |
| | | 454 | | |
| | | 455 | | try { |
| | 1 | 456 | | boost::topological_sort(g, std::back_inserter(topo_order)); |
| | 1 | 457 | | } catch (const boost::not_a_dag &) { |
| | 1 | 458 | | throw CompilerException("Graph contains a cycle (loop), which is not allowed."); |
| | 0 | 459 | | } |
| | | 460 | | |
| | 1 | 461 | | for (auto v : std::views::reverse(topo_order)) { |
| | 1 | 462 | | auto &node = g[v]; |
| | 1 | 463 | | auto node_trace = trace_scope(std::format("Infer: {}", node.spec.name), "detail"); |
| | | 464 | | |
| | 1 | 465 | | auto in_degree = boost::in_degree(v, g); |
| | 1 | 466 | | std::vector<core::TDesc> input_descs(in_degree); |
| | | 467 | | |
| | 1 | 468 | | for (auto e : boost::make_iterator_range(boost::in_edges(v, g))) { |
| | 1 | 469 | | const auto &edge_plan = g[e]; |
| | 1 | 470 | | if (edge_plan.spec.in_idx >= input_descs.size()) { |
| | 0 | 471 | | throw CompilerException("Input index out of bounds"); |
| | | 472 | | } |
| | 1 | 473 | | input_descs[edge_plan.spec.in_idx] = edge_plan.desc; |
| | 1 | 474 | | } |
| | | 475 | | |
| | 1 | 476 | | const auto &factory = registry_.get(node.spec.kind); |
| | 1 | 477 | | node.infer = factory.infer(input_descs, node.spec.settings); |
| | | 478 | | |
| | 1 | 479 | | for (auto e : boost::make_iterator_range(boost::out_edges(v, g))) { |
| | 1 | 480 | | auto &edge_plan = g[e]; |
| | 1 | 481 | | if (edge_plan.spec.out_idx >= node.infer.output_descs.size()) { |
| | 1 | 482 | | throw CompilerException("Output index out of bounds"); |
| | | 483 | | } |
| | 1 | 484 | | edge_plan.desc = node.infer.output_descs[edge_plan.spec.out_idx]; |
| | 1 | 485 | | } |
| | 1 | 486 | | } |
| | 1 | 487 | | } |
| | | 488 | | |
| | | 489 | | // ------------------------------------------------------------------------------------------------- |
| | | 490 | | // Pass: Assign Tensor IDs |
| | | 491 | | // ------------------------------------------------------------------------------------------------- |
| | 1 | 492 | | void Compiler::Impl::assign_tensor_ids() { |
| | 1 | 493 | | auto &g = out_->graph; |
| | 1 | 494 | | auto &res = out_->resources; |
| | 1 | 495 | | int next_tid = 0; |
| | | 496 | | |
| | 1 | 497 | | std::vector<GraphPlan::vertex_descriptor> topo; |
| | 1 | 498 | | boost::topological_sort(g, std::back_inserter(topo)); |
| | | 499 | | |
| | 1 | 500 | | for (auto v : std::views::reverse(topo)) { |
| | 1 | 501 | | auto &node = g[v]; |
| | | 502 | | |
| | 1 | 503 | | node.in_tids.resize(node.infer.input_descs.size()); |
| | 1 | 504 | | for (auto e : boost::make_iterator_range(boost::in_edges(v, g))) { |
| | 1 | 505 | | const auto &ep = g[e]; |
| | 1 | 506 | | node.in_tids[ep.spec.in_idx] = ep.tid; |
| | 1 | 507 | | res.tensor_descs[ep.tid] = ep.desc; |
| | 1 | 508 | | } |
| | | 509 | | |
| | 1 | 510 | | node.out_tids.resize(node.infer.output_descs.size()); |
| | 1 | 511 | | auto out_edges = boost::out_edges(v, g); |
| | | 512 | | |
| | 1 | 513 | | for (size_t i = 0; i < node.out_tids.size(); ++i) { |
| | 1 | 514 | | int tid = next_tid++; |
| | 1 | 515 | | node.out_tids[i] = tid; |
| | 1 | 516 | | res.tensor_descs[tid] = node.infer.output_descs[i]; |
| | | 517 | | |
| | 1 | 518 | | for (auto e : boost::make_iterator_range(out_edges)) { |
| | 1 | 519 | | if (g[e].spec.out_idx == static_cast<int>(i)) { |
| | 1 | 520 | | g[e].tid = tid; |
| | | 521 | | } |
| | 1 | 522 | | } |
| | 1 | 523 | | } |
| | 1 | 524 | | } |
| | 1 | 525 | | } |
| | | 526 | | |
| | | 527 | | // ------------------------------------------------------------------------------------------------- |
| | | 528 | | // Pass: Assign Storage IDs |
| | | 529 | | // ------------------------------------------------------------------------------------------------- |
| | 1 | 530 | | void Compiler::Impl::assign_storage_ids() { |
| | 1 | 531 | | auto &g = out_->graph; |
| | 1 | 532 | | auto &res = out_->resources; |
| | | 533 | | |
| | 1 | 534 | | res.tid_to_sid.clear(); |
| | 1 | 535 | | int next_sid = 0; |
| | | 536 | | |
| | 1 | 537 | | std::vector<GraphPlan::vertex_descriptor> topo; |
| | 1 | 538 | | boost::topological_sort(g, std::back_inserter(topo)); |
| | | 539 | | |
| | 1 | 540 | | for (auto v : std::views::reverse(topo)) { |
| | 1 | 541 | | auto &node = g[v]; |
| | | 542 | | |
| | 1 | 543 | | for (size_t out_idx = 0; out_idx < node.out_tids.size(); ++out_idx) { |
| | 1 | 544 | | int out_tid = node.out_tids[out_idx]; |
| | 1 | 545 | | int sid = -1; |
| | | 546 | | |
| | 1 | 547 | | for (const auto &ip : node.infer.in_place) { |
| | 0 | 548 | | if (ip.out_idx == static_cast<int>(out_idx)) { |
| | 0 | 549 | | int in_tid = node.in_tids[ip.in_idx]; |
| | | 550 | | |
| | 0 | 551 | | if (res.tid_to_sid.contains(in_tid)) { |
| | 0 | 552 | | sid = (int)res.tid_to_sid.at(in_tid); |
| | 0 | 553 | | } else { |
| | 0 | 554 | | throw CompilerException( |
| | | 555 | | std::format("Node '{}': In-place input TID {} has no Storage ID assigned.", |
| | | 556 | | node.spec.name, in_tid)); |
| | | 557 | | } |
| | 0 | 558 | | break; |
| | | 559 | | } |
| | 0 | 560 | | } |
| | | 561 | | |
| | 1 | 562 | | if (sid == -1) { |
| | 1 | 563 | | sid = next_sid++; |
| | | 564 | | } |
| | 1 | 565 | | res.tid_to_sid[out_tid] = sid; |
| | 1 | 566 | | } |
| | 1 | 567 | | } |
| | 1 | 568 | | } |
| | | 569 | | |
| | 1 | 570 | | void Compiler::Impl::verify_buffer_consistency() { |
| | 1 | 571 | | std::map<size_t, std::vector<std::string>> owners; |
| | 1 | 572 | | auto &g = out_->graph; |
| | 1 | 573 | | auto &res = out_->resources; |
| | | 574 | | |
| | 1 | 575 | | for (auto v : boost::make_iterator_range(boost::vertices(g))) { |
| | 1 | 576 | | const auto &node = g[v]; |
| | 1 | 577 | | for (size_t i = 0; i < node.infer.owned_inputs.size(); ++i) { |
| | 1 | 578 | | if (node.infer.owned_inputs[i]) { |
| | 1 | 579 | | owners[res.tid_to_sid.at(node.in_tids[i])].push_back(node.spec.name + ":in"); |
| | | 580 | | } |
| | 1 | 581 | | } |
| | 1 | 582 | | for (size_t i = 0; i < node.infer.owned_outputs.size(); ++i) { |
| | 1 | 583 | | if (node.infer.owned_outputs[i]) { |
| | 1 | 584 | | owners[res.tid_to_sid.at(node.out_tids[i])].push_back(node.spec.name + ":out"); |
| | | 585 | | } |
| | 1 | 586 | | } |
| | 1 | 587 | | } |
| | | 588 | | |
| | 1 | 589 | | for (const auto &[sid, nodeList] : owners) { |
| | 1 | 590 | | if (nodeList.size() > 1) { |
| | 1 | 591 | | throw CompilerException(std::format("Storage ID {} has multiple owners", sid)); |
| | | 592 | | } |
| | 1 | 593 | | } |
| | 1 | 594 | | } |
| | | 595 | | |
| | | 596 | | // void Compiler::Impl::allocate_buffers() { |
| | | 597 | | // auto &g = out_->graph; |
| | | 598 | | // auto &res = out_->resources; |
| | | 599 | | |
| | | 600 | | // res.memory_blocks.clear(); |
| | | 601 | | // res.storages.clear(); |
| | | 602 | | |
| | | 603 | | // std::unordered_set<size_t> user_managed_sids; |
| | | 604 | | // for (auto v : boost::make_iterator_range(boost::vertices(g))) { |
| | | 605 | | // const auto &node = g[v]; |
| | | 606 | | // for (size_t i = 0; i < node.out_tids.size(); ++i) { |
| | | 607 | | // if (node.infer.owned_outputs[i]) { |
| | | 608 | | // int tid = node.out_tids[i]; |
| | | 609 | | // size_t sid = res.tid_to_sid.at(tid); |
| | | 610 | | // user_managed_sids.insert(sid); |
| | | 611 | | // } |
| | | 612 | | // } |
| | | 613 | | // for (size_t i = 0; i < node.in_tids.size(); ++i) { |
| | | 614 | | // if (node.infer.owned_inputs[i]) { |
| | | 615 | | // int tid = node.in_tids[i]; |
| | | 616 | | // size_t sid = res.tid_to_sid.at(tid); |
| | | 617 | | // user_managed_sids.insert(sid); |
| | | 618 | | // } |
| | | 619 | | // } |
| | | 620 | | // } |
| | | 621 | | |
| | | 622 | | // std::map<size_t, size_t> sid_to_rep_tid; |
| | | 623 | | // for (const auto &[tid, sid] : res.tid_to_sid) { |
| | | 624 | | // if (!sid_to_rep_tid.count(sid)) |
| | | 625 | | // sid_to_rep_tid[sid] = tid; |
| | | 626 | | // } |
| | | 627 | | |
| | | 628 | | // for (const auto &[sid, tid] : sid_to_rep_tid) { |
| | | 629 | | // auto alloc_scope = trace_scope(std::format("Alloc SID {}", sid), "detail"); |
| | | 630 | | // const auto &desc = res.tensor_descs.at(tid); |
| | | 631 | | |
| | | 632 | | // auto storage = std::make_unique<core::Storage>(); |
| | | 633 | | // storage->mem_loc = desc.mem_loc; |
| | | 634 | | // storage->bytes = desc.num_bytes(); |
| | | 635 | | // storage->ptr = nullptr; |
| | | 636 | | |
| | | 637 | | // if (!user_managed_sids.contains(sid)) { |
| | | 638 | | // MemoryBlock block; |
| | | 639 | | // block.mem_loc = desc.mem_loc; |
| | | 640 | | // block.size_bytes = desc.num_bytes(); |
| | | 641 | | |
| | | 642 | | // logger_->info("Allocating {} bytes for SID {} at {:?} memory", block.size_bytes, sid, |
| | | 643 | | // to_string(desc.mem_loc)); |
| | | 644 | | |
| | | 645 | | // // Use a standard scope block to control the RAII timer |
| | | 646 | | // { |
| | | 647 | | // auto sys_scope = trace_scope( |
| | | 648 | | // desc.mem_loc == core::MemLoc::Host ? "Host Malloc" : "Device Malloc", "syscall"); |
| | | 649 | | // if (desc.mem_loc == core::MemLoc::Host) { |
| | | 650 | | // block.h_data = curaii::make_unique_host_ptr<std::byte>(block.size_bytes); |
| | | 651 | | // } else { |
| | | 652 | | // block.d_data = curaii::make_unique_device_ptr<std::byte>(block.size_bytes); |
| | | 653 | | // } |
| | | 654 | | // } // sys_scope naturally destructs here! |
| | | 655 | | |
| | | 656 | | // storage->ptr = static_cast<std::byte *>(block.get()); |
| | | 657 | | // res.memory_blocks.emplace(sid, std::move(block)); |
| | | 658 | | // } else { |
| | | 659 | | // logger_->info("SID {} is user-managed; skipping allocation.", sid); |
| | | 660 | | // } |
| | | 661 | | |
| | | 662 | | // res.storages.emplace(sid, std::move(storage)); |
| | | 663 | | // } |
| | | 664 | | |
| | | 665 | | // // Temp test, trigger a 1b cuda memcopy to see how it shows up in the profiler |
| | | 666 | | // CUDA_CHECK(cudaDeviceSynchronize()); |
| | | 667 | | // if (res.memory_blocks.size() >= 2) { |
| | | 668 | | // auto &block1 = res.memory_blocks.begin()->second; |
| | | 669 | | // auto &block2 = std::next(res.memory_blocks.begin())->second; |
| | | 670 | | // if (block1.mem_loc == core::MemLoc::Device && block2.mem_loc == core::MemLoc::Device) { |
| | | 671 | | // auto sys_scope = trace_scope("Test Memcpy", "syscall"); |
| | | 672 | | // CUDA_CHECK(cudaMemcpy(block2.get(), block1.get(), 1, cudaMemcpyDeviceToDevice)); |
| | | 673 | | // CUDA_CHECK(cudaDeviceSynchronize()); |
| | | 674 | | // } |
| | | 675 | | // } |
| | | 676 | | // } |
| | | 677 | | |
| | 1 | 678 | | void Compiler::Impl::allocate_buffers() { |
| | 1 | 679 | | auto &g = out_->graph; |
| | 1 | 680 | | auto &res = out_->resources; |
| | | 681 | | |
| | 1 | 682 | | res.memory_blocks.clear(); |
| | 1 | 683 | | res.storages.clear(); |
| | | 684 | | |
| | | 685 | | // 1. Identify user-managed SIDs |
| | 1 | 686 | | std::unordered_set<size_t> user_managed_sids; |
| | 1 | 687 | | for (auto v : boost::make_iterator_range(boost::vertices(g))) { |
| | 1 | 688 | | const auto &node = g[v]; |
| | 1 | 689 | | for (size_t i = 0; i < node.out_tids.size(); ++i) { |
| | 1 | 690 | | if (node.infer.owned_outputs[i]) { |
| | 1 | 691 | | user_managed_sids.insert(res.tid_to_sid.at(node.out_tids[i])); |
| | | 692 | | } |
| | 1 | 693 | | } |
| | 1 | 694 | | for (size_t i = 0; i < node.in_tids.size(); ++i) { |
| | 1 | 695 | | if (node.infer.owned_inputs[i]) { |
| | 1 | 696 | | user_managed_sids.insert(res.tid_to_sid.at(node.in_tids[i])); |
| | | 697 | | } |
| | 1 | 698 | | } |
| | 1 | 699 | | } |
| | | 700 | | |
| | | 701 | | // 2. Map SID to representative TID |
| | 1 | 702 | | std::map<size_t, size_t> sid_to_rep_tid; |
| | 1 | 703 | | for (const auto &[tid, sid] : res.tid_to_sid) { |
| | 1 | 704 | | if (!sid_to_rep_tid.count(sid)) { |
| | 1 | 705 | | sid_to_rep_tid[sid] = tid; |
| | | 706 | | } |
| | 1 | 707 | | } |
| | | 708 | | |
| | | 709 | | // 3. Build a pool of scavengable blocks from prev_ |
| | | 710 | | // Key: {MemLoc, size_in_bytes} |
| | 1 | 711 | | std::multimap<std::pair<core::MemLoc, size_t>, MemoryBlock> free_blocks; |
| | 1 | 712 | | if (prev_) { |
| | 1 | 713 | | for (auto &[prev_sid, block] : prev_->resources.memory_blocks) { |
| | 1 | 714 | | free_blocks.emplace(std::make_pair(block.mem_loc, block.size_bytes), std::move(block)); |
| | 1 | 715 | | } |
| | | 716 | | } |
| | | 717 | | |
| | | 718 | | // 4. Allocate or Scavenge |
| | 1 | 719 | | for (const auto &[sid, tid] : sid_to_rep_tid) { |
| | 1 | 720 | | auto alloc_scope = trace_scope(std::format("Alloc SID {}", sid), "detail"); |
| | 1 | 721 | | const auto &desc = res.tensor_descs.at(tid); |
| | | 722 | | |
| | 1 | 723 | | auto storage = std::make_unique<core::Storage>(); |
| | 1 | 724 | | storage->mem_loc = desc.mem_loc; |
| | 1 | 725 | | storage->bytes = desc.num_bytes(); |
| | 1 | 726 | | storage->ptr = nullptr; |
| | | 727 | | |
| | 1 | 728 | | if (!user_managed_sids.contains(sid)) { |
| | 1 | 729 | | MemoryBlock block; |
| | 1 | 730 | | auto pool_key = std::make_pair(desc.mem_loc, desc.num_bytes()); |
| | 1 | 731 | | auto it = free_blocks.find(pool_key); |
| | | 732 | | |
| | 1 | 733 | | if (it != free_blocks.end()) { |
| | | 734 | | // We found an exact match! Scavenge it. |
| | 1 | 735 | | logger_->info("Reusing {} bytes for SID {} at {:?} memory", desc.num_bytes(), sid, |
| | | 736 | | to_string(desc.mem_loc)); |
| | 1 | 737 | | block = std::move(it->second); |
| | 1 | 738 | | free_blocks.erase(it); |
| | 1 | 739 | | } else { |
| | | 740 | | // No match found, allocate fresh memory. |
| | 1 | 741 | | block.mem_loc = desc.mem_loc; |
| | 1 | 742 | | block.size_bytes = desc.num_bytes(); |
| | | 743 | | |
| | 1 | 744 | | logger_->info("Allocating {} bytes for SID {} at {:?} memory", block.size_bytes, sid, |
| | | 745 | | to_string(desc.mem_loc)); |
| | | 746 | | |
| | | 747 | | { |
| | 1 | 748 | | auto sys_scope = trace_scope( |
| | | 749 | | desc.mem_loc == core::MemLoc::Host ? "Host Malloc" : "Device Malloc", "syscall"); |
| | 1 | 750 | | if (desc.mem_loc == core::MemLoc::Host) { |
| | 1 | 751 | | block.h_data = curaii::make_unique_host_ptr<std::byte>(block.size_bytes); |
| | 1 | 752 | | } else { |
| | 1 | 753 | | block.d_data = curaii::make_unique_device_ptr<std::byte>(block.size_bytes); |
| | | 754 | | } |
| | 1 | 755 | | } |
| | | 756 | | } |
| | | 757 | | |
| | 1 | 758 | | storage->ptr = static_cast<std::byte *>(block.get()); |
| | 1 | 759 | | res.memory_blocks.emplace(sid, std::move(block)); |
| | 1 | 760 | | } else { |
| | 1 | 761 | | logger_->info("SID {} is user-managed; skipping allocation.", sid); |
| | | 762 | | } |
| | | 763 | | |
| | 1 | 764 | | res.storages.emplace(sid, std::move(storage)); |
| | 1 | 765 | | } |
| | | 766 | | |
| | | 767 | | // Temp test, trigger a 1b cuda memcopy to see how it shows up in the profiler |
| | 1 | 768 | | CUDA_CHECK(cudaDeviceSynchronize()); |
| | 1 | 769 | | if (res.memory_blocks.size() >= 2) { |
| | 1 | 770 | | auto &block1 = res.memory_blocks.begin()->second; |
| | 1 | 771 | | auto &block2 = std::next(res.memory_blocks.begin())->second; |
| | 1 | 772 | | if (block1.mem_loc == core::MemLoc::Device && block2.mem_loc == core::MemLoc::Device) { |
| | 1 | 773 | | auto sys_scope = trace_scope("Test Memcpy", "syscall"); |
| | 1 | 774 | | CUDA_CHECK(cudaMemcpy(block2.get(), block1.get(), 1, cudaMemcpyDeviceToDevice)); |
| | 1 | 775 | | CUDA_CHECK(cudaDeviceSynchronize()); |
| | 1 | 776 | | } |
| | | 777 | | } |
| | | 778 | | |
| | | 779 | | // Any blocks left inside `free_blocks` will naturally go out of scope here and |
| | | 780 | | // safely deallocate, meaning memory for removed nodes is properly cleaned up. |
| | 1 | 781 | | } |
| | | 782 | | |
| | | 783 | | // ------------------------------------------------------------------------------------------------- |
| | | 784 | | // Pass: Section Partitioning |
| | | 785 | | // ------------------------------------------------------------------------------------------------- |
| | 1 | 786 | | void Compiler::Impl::partition_sections() { |
| | 1 | 787 | | auto &g = out_->graph; |
| | 1 | 788 | | auto num_verts = boost::num_vertices(g); |
| | | 789 | | |
| | 1 | 790 | | for (auto e : boost::make_iterator_range(boost::edges(g))) { |
| | 1 | 791 | | const auto source = boost::source(e, g); |
| | 1 | 792 | | const auto target = boost::target(e, g); |
| | 1 | 793 | | if (g[source].infer.kind == core::TaskKind::Async && |
| | | 794 | | g[target].infer.kind == core::TaskKind::Async) { |
| | 1 | 795 | | throw CompilerException( |
| | | 796 | | std::format("Consecutive asynchronous nodes '{}' and '{}' are not supported", |
| | | 797 | | g[source].spec.name, g[target].spec.name)); |
| | | 798 | | } |
| | 1 | 799 | | } |
| | | 800 | | |
| | 1 | 801 | | std::vector<size_t> parent(num_verts); |
| | 1 | 802 | | std::iota(parent.begin(), parent.end(), 0); |
| | | 803 | | |
| | | 804 | | auto find = [&](size_t i) { |
| | | 805 | | while (i != parent[i]) { |
| | | 806 | | parent[i] = parent[parent[i]]; |
| | | 807 | | i = parent[i]; |
| | | 808 | | } |
| | | 809 | | return i; |
| | 1 | 810 | | }; |
| | | 811 | | |
| | | 812 | | auto unite = [&](size_t i, size_t j) { |
| | | 813 | | size_t root_i = find(i); |
| | | 814 | | size_t root_j = find(j); |
| | | 815 | | if (root_i != root_j) |
| | | 816 | | parent[root_i] = root_j; |
| | 1 | 817 | | }; |
| | | 818 | | |
| | 1 | 819 | | for (auto e : boost::make_iterator_range(boost::edges(g))) { |
| | 1 | 820 | | auto u = boost::source(e, g); |
| | 1 | 821 | | auto v = boost::target(e, g); |
| | 1 | 822 | | if (g[u].infer.kind == core::TaskKind::Sync && g[v].infer.kind == core::TaskKind::Sync) { |
| | 1 | 823 | | unite(u, v); |
| | | 824 | | } |
| | 1 | 825 | | } |
| | | 826 | | |
| | 1 | 827 | | for (auto v : boost::make_iterator_range(boost::vertices(g))) { |
| | 1 | 828 | | if (g[v].infer.kind == core::TaskKind::Async) { |
| | 1 | 829 | | std::vector<size_t> sync_preds; |
| | 1 | 830 | | for (auto e : boost::make_iterator_range(boost::in_edges(v, g))) { |
| | 1 | 831 | | auto p = boost::source(e, g); |
| | 1 | 832 | | if (g[p].infer.kind == core::TaskKind::Sync) |
| | 1 | 833 | | sync_preds.push_back(p); |
| | 1 | 834 | | } |
| | 1 | 835 | | if (!sync_preds.empty()) { |
| | 1 | 836 | | for (size_t i = 1; i < sync_preds.size(); ++i) |
| | 0 | 837 | | unite(sync_preds[0], sync_preds[i]); |
| | | 838 | | } |
| | | 839 | | |
| | 1 | 840 | | std::vector<size_t> sync_succs; |
| | 1 | 841 | | for (auto e : boost::make_iterator_range(boost::out_edges(v, g))) { |
| | 1 | 842 | | auto s = boost::target(e, g); |
| | 1 | 843 | | if (g[s].infer.kind == core::TaskKind::Sync) |
| | 1 | 844 | | sync_succs.push_back(s); |
| | 1 | 845 | | } |
| | 1 | 846 | | if (!sync_succs.empty()) { |
| | 1 | 847 | | for (size_t i = 1; i < sync_succs.size(); ++i) |
| | 0 | 848 | | unite(sync_succs[0], sync_succs[i]); |
| | | 849 | | } |
| | 1 | 850 | | } |
| | 1 | 851 | | } |
| | | 852 | | |
| | 1 | 853 | | std::map<size_t, size_t> root_to_section_id; |
| | 1 | 854 | | out_->sections.clear(); |
| | 1 | 855 | | int next_sec_id = 0; |
| | 1 | 856 | | node_to_section_map_.clear(); |
| | | 857 | | |
| | | 858 | | auto get_section_id = [&](size_t v_idx) { |
| | | 859 | | size_t root = find(v_idx); |
| | | 860 | | if (root_to_section_id.find(root) == root_to_section_id.end()) { |
| | | 861 | | Section s; |
| | | 862 | | s.id = next_sec_id; |
| | | 863 | | s.name = std::format("section-{}", next_sec_id); |
| | | 864 | | out_->sections.push_back(s); |
| | | 865 | | root_to_section_id[root] = next_sec_id++; |
| | | 866 | | } |
| | | 867 | | return root_to_section_id[root]; |
| | 1 | 868 | | }; |
| | | 869 | | |
| | 1 | 870 | | std::vector<GraphPlan::vertex_descriptor> topo; |
| | 1 | 871 | | boost::topological_sort(g, std::back_inserter(topo)); |
| | | 872 | | |
| | 1 | 873 | | for (auto v : std::views::reverse(topo)) { |
| | 1 | 874 | | auto &np = g[v]; |
| | 1 | 875 | | if (np.infer.kind == core::TaskKind::Sync) { |
| | 1 | 876 | | size_t sec_id = get_section_id(v); |
| | 1 | 877 | | out_->sections[sec_id].sync_topo.push_back(v); |
| | 1 | 878 | | node_to_section_map_[np.spec.name] = sec_id; |
| | | 879 | | } |
| | 1 | 880 | | } |
| | | 881 | | |
| | 1 | 882 | | for (auto v : boost::make_iterator_range(boost::vertices(g))) { |
| | 1 | 883 | | if (g[v].infer.kind != core::TaskKind::Async) |
| | 1 | 884 | | continue; |
| | | 885 | | |
| | 1 | 886 | | std::set<size_t> unique_cons_sections; |
| | 1 | 887 | | for (auto e : boost::make_iterator_range(boost::out_edges(v, g))) { |
| | 1 | 888 | | auto s = boost::target(e, g); |
| | 1 | 889 | | if (g[s].infer.kind == core::TaskKind::Sync) { |
| | 1 | 890 | | unique_cons_sections.insert(get_section_id(s)); |
| | | 891 | | } |
| | 1 | 892 | | } |
| | 1 | 893 | | for (size_t sec_id : unique_cons_sections) { |
| | 1 | 894 | | out_->sections[sec_id].async_cons.push_back(v); |
| | 1 | 895 | | } |
| | | 896 | | |
| | 1 | 897 | | std::set<size_t> unique_prod_sections; |
| | 1 | 898 | | for (auto e : boost::make_iterator_range(boost::in_edges(v, g))) { |
| | 1 | 899 | | auto p = boost::source(e, g); |
| | 1 | 900 | | if (g[p].infer.kind == core::TaskKind::Sync) { |
| | 1 | 901 | | unique_prod_sections.insert(get_section_id(p)); |
| | | 902 | | } |
| | 1 | 903 | | } |
| | 1 | 904 | | for (size_t sec_id : unique_prod_sections) { |
| | 1 | 905 | | out_->sections[sec_id].async_prod.push_back(v); |
| | 1 | 906 | | } |
| | 1 | 907 | | } |
| | | 908 | | |
| | 1 | 909 | | for (auto §ion : out_->sections) { |
| | | 910 | | // A synchronizing producer must run before ordinary producers: its barrier covers all preceding |
| | | 911 | | // sync-node work before an ordinary queue is allowed to publish its GPU-backed input. |
| | | 912 | | const auto ordinary_begin = |
| | 1 | 913 | | std::stable_partition(section.async_prod.begin(), section.async_prod.end(), |
| | | 914 | | [&](auto v) { return g[v].infer.synchronizes_producer_stream; }); |
| | 1 | 915 | | section.has_synchronizing_async_producer = ordinary_begin != section.async_prod.begin(); |
| | 1 | 916 | | } |
| | 1 | 917 | | } |
| | | 918 | | |
| | | 919 | | // void Compiler::Impl::assign_streams() { |
| | | 920 | | // out_->resources.streams.clear(); |
| | | 921 | | // for (auto &sec : out_->sections) { |
| | | 922 | | // curaii::CudaStream stream; |
| | | 923 | | // sec.stream = stream.get(); |
| | | 924 | | // out_->resources.streams.emplace(sec.id, std::move(stream)); |
| | | 925 | | // } |
| | | 926 | | // } |
| | | 927 | | |
| | 1 | 928 | | void Compiler::Impl::assign_streams() { |
| | 1 | 929 | | out_->resources.streams.clear(); |
| | | 930 | | |
| | | 931 | | // 1. Only set up the iterators if prev_ actually exists |
| | 1 | 932 | | if (prev_) { |
| | 1 | 933 | | auto prev_it = prev_->resources.streams.begin(); |
| | 1 | 934 | | auto prev_end = prev_->resources.streams.end(); |
| | | 935 | | |
| | 1 | 936 | | for (auto &sec : out_->sections) { |
| | 1 | 937 | | if (prev_it != prev_end) { |
| | | 938 | | // Scavenge an existing stream |
| | 1 | 939 | | auto &old_stream = prev_it->second; |
| | 1 | 940 | | sec.stream = old_stream.get(); |
| | | 941 | | |
| | 1 | 942 | | out_->resources.streams.emplace(sec.id, std::move(old_stream)); |
| | 1 | 943 | | ++prev_it; |
| | 1 | 944 | | } else { |
| | | 945 | | // Fallback: Create a new stream (ran out of old ones) |
| | 0 | 946 | | curaii::CudaStream stream; |
| | 0 | 947 | | sec.stream = stream.get(); |
| | 0 | 948 | | out_->resources.streams.emplace(sec.id, std::move(stream)); |
| | 0 | 949 | | } |
| | 1 | 950 | | } |
| | 1 | 951 | | } else { |
| | | 952 | | // 2. No previous graph at all, just create fresh streams for everything |
| | 1 | 953 | | for (auto &sec : out_->sections) { |
| | 1 | 954 | | curaii::CudaStream stream; |
| | 1 | 955 | | sec.stream = stream.get(); |
| | 1 | 956 | | out_->resources.streams.emplace(sec.id, std::move(stream)); |
| | 1 | 957 | | } |
| | | 958 | | } |
| | 1 | 959 | | } |
| | | 960 | | |
| | 1 | 961 | | void Compiler::Impl::create_storage_adapters() { |
| | 1 | 962 | | auto &g = out_->graph; |
| | 1 | 963 | | auto &res = out_->resources; |
| | | 964 | | |
| | 1 | 965 | | res.node_storage_adapters.clear(); |
| | | 966 | | |
| | 1 | 967 | | for (auto v : boost::make_iterator_range(boost::vertices(g))) { |
| | 1 | 968 | | const auto &np = g[v]; |
| | 1 | 969 | | auto adapter = std::make_unique<TaskStorageAdapter>(np.in_tids, np.out_tids, res); |
| | 1 | 970 | | res.node_storage_adapters.emplace(np.spec.name, std::move(adapter)); |
| | 1 | 971 | | } |
| | 1 | 972 | | } |
| | | 973 | | |
| | | 974 | | template <class To, class From> |
| | 1 | 975 | | std::unique_ptr<To> dynamic_unique_ptr_cast(std::unique_ptr<From> &&ptr) noexcept { |
| | 1 | 976 | | if (auto casted = dynamic_cast<To *>(ptr.get())) { |
| | 1 | 977 | | ptr.release(); |
| | 1 | 978 | | return std::unique_ptr<To>(casted); |
| | | 979 | | } |
| | 0 | 980 | | return nullptr; |
| | 1 | 981 | | } |
| | | 982 | | |
| | | 983 | | template <class TaskInterface, class Factory, class Ctx> |
| | | 984 | | std::unique_ptr<core::ITask> |
| | 1 | 985 | | Compiler::Impl::create_or_update_task(Factory &factory, const NodePlan &np, const Ctx &ctx) { |
| | | 986 | | |
| | | 987 | | // 1. Helper to synchronize the correct streams based on Ctx type |
| | | 988 | | auto sync_streams = [&]() { |
| | | 989 | | if constexpr (std::is_same_v<Ctx, core::SyncCreateCtx>) { |
| | | 990 | | if (ctx.stream) { |
| | | 991 | | CUDA_CHECK(cudaStreamSynchronize(ctx.stream)); |
| | | 992 | | } else { |
| | | 993 | | logger_->warn("SyncCreateCtx has null stream; skipping synchronization."); |
| | | 994 | | } |
| | | 995 | | } else if constexpr (std::is_same_v<Ctx, core::AsyncCreateCtx>) { |
| | | 996 | | if (ctx.producer_stream) { |
| | | 997 | | CUDA_CHECK(cudaStreamSynchronize(ctx.producer_stream)); |
| | | 998 | | } else { |
| | | 999 | | logger_->warn("AsyncCreateCtx has null producer_stream; skipping synchronization."); |
| | | 1000 | | } |
| | | 1001 | | if (ctx.consumer_stream) { |
| | | 1002 | | CUDA_CHECK(cudaStreamSynchronize(ctx.consumer_stream)); |
| | | 1003 | | } else { |
| | | 1004 | | logger_->warn("AsyncCreateCtx has null consumer_stream; skipping synchronization."); |
| | | 1005 | | } |
| | | 1006 | | } |
| | 1 | 1007 | | }; |
| | | 1008 | | |
| | | 1009 | | // 2. Helper to accurately profile Task Creation |
| | | 1010 | | auto do_create = [&]() { |
| | | 1011 | | auto scope = trace_scope(std::format("Create Task: {}", np.spec.name), "detail"); |
| | | 1012 | | auto task = factory.create(np.infer.input_descs, np.spec.settings, ctx); |
| | | 1013 | | sync_streams(); |
| | | 1014 | | return task; |
| | 1 | 1015 | | }; // scope naturally destructs here, capturing the fully synced time |
| | | 1016 | | |
| | | 1017 | | // 3. Helper to accurately profile Task Updating |
| | | 1018 | | auto do_update = [&](std::unique_ptr<TaskInterface> prev_task) { |
| | | 1019 | | auto scope = trace_scope(std::format("Update Task: {}", np.spec.name), "detail"); |
| | | 1020 | | auto task = factory.update(std::move(prev_task), np.infer.input_descs, np.spec.settings, ctx); |
| | | 1021 | | sync_streams(); |
| | | 1022 | | return task; |
| | 1 | 1023 | | }; |
| | | 1024 | | |
| | | 1025 | | // --- Main Logic --- |
| | | 1026 | | |
| | 1 | 1027 | | std::unique_ptr<core::ITask> *prev_ptr_ref = nullptr; |
| | 1 | 1028 | | if (prev_ && !prev_->resources.tasks.empty()) { |
| | 1 | 1029 | | auto &prev_tasks = prev_->resources.tasks; |
| | 1 | 1030 | | if (auto it = prev_tasks.find(np.spec.name); it != prev_tasks.end()) { |
| | 1 | 1031 | | prev_ptr_ref = &it->second; |
| | | 1032 | | } |
| | | 1033 | | } |
| | | 1034 | | |
| | 1 | 1035 | | if (!prev_ptr_ref) { |
| | 1 | 1036 | | return do_create(); |
| | | 1037 | | } |
| | | 1038 | | |
| | 1 | 1039 | | bool kind_mismatch = false; |
| | 1 | 1040 | | bool found_in_prev_graph = false; |
| | | 1041 | | |
| | 1 | 1042 | | auto [vi, vi_end] = boost::vertices(prev_->graph); |
| | 1 | 1043 | | for (; vi != vi_end; ++vi) { |
| | 1 | 1044 | | const NodePlan &prev_node = prev_->graph[*vi]; |
| | 1 | 1045 | | if (prev_node.spec.name == np.spec.name) { |
| | 1 | 1046 | | found_in_prev_graph = true; |
| | 1 | 1047 | | if (prev_node.spec.kind != np.spec.kind) { |
| | 0 | 1048 | | kind_mismatch = true; |
| | | 1049 | | } |
| | 1 | 1050 | | break; |
| | | 1051 | | } |
| | 1 | 1052 | | } |
| | | 1053 | | |
| | 1 | 1054 | | if (!found_in_prev_graph || kind_mismatch) { |
| | 0 | 1055 | | return do_create(); |
| | | 1056 | | } |
| | | 1057 | | |
| | 1 | 1058 | | auto prev_task_typed = dynamic_unique_ptr_cast<TaskInterface>(std::move(*prev_ptr_ref)); |
| | | 1059 | | |
| | 1 | 1060 | | if (!prev_task_typed) { |
| | 0 | 1061 | | return do_create(); |
| | | 1062 | | } |
| | | 1063 | | |
| | 1 | 1064 | | return do_update(std::move(prev_task_typed)); |
| | 1 | 1065 | | } |
| | | 1066 | | |
| | 1 | 1067 | | void Compiler::Impl::instantiate_tasks() { |
| | 1 | 1068 | | auto &g = out_->graph; |
| | 1 | 1069 | | auto &tasks = out_->resources.tasks; |
| | | 1070 | | |
| | 1 | 1071 | | tasks.clear(); |
| | | 1072 | | |
| | 1 | 1073 | | for (auto v : boost::make_iterator_range(boost::vertices(g))) { |
| | 1 | 1074 | | const auto &np = g[v]; |
| | | 1075 | | |
| | 1 | 1076 | | if (np.infer.kind == core::TaskKind::Sync) { |
| | 1 | 1077 | | size_t sid = node_to_section_map_.at(np.spec.name); |
| | 1 | 1078 | | auto stream = out_->resources.streams.at(sid).get(); |
| | | 1079 | | |
| | 1 | 1080 | | core::SyncCreateCtx ctx{.stream = stream}; |
| | 1 | 1081 | | auto &factory = registry_.get_sync(np.spec.kind); |
| | | 1082 | | |
| | 1 | 1083 | | auto task = create_or_update_task<core::ISyncTask>(factory, np, ctx); |
| | 1 | 1084 | | tasks.emplace(np.spec.name, std::move(task)); |
| | | 1085 | | |
| | 1 | 1086 | | } else if (np.infer.kind == core::TaskKind::Async) { |
| | 1 | 1087 | | void *prod_stream = nullptr; |
| | 1 | 1088 | | for (auto e : boost::make_iterator_range(boost::in_edges(v, g))) { |
| | 1 | 1089 | | auto p = boost::source(e, g); |
| | 1 | 1090 | | if (g[p].infer.kind == core::TaskKind::Sync) { |
| | 1 | 1091 | | size_t sid = node_to_section_map_.at(g[p].spec.name); |
| | 1 | 1092 | | prod_stream = out_->resources.streams.at(sid).get(); |
| | 1 | 1093 | | break; |
| | | 1094 | | } |
| | 0 | 1095 | | } |
| | | 1096 | | |
| | 1 | 1097 | | void *cons_stream = nullptr; |
| | 1 | 1098 | | for (auto e : boost::make_iterator_range(boost::out_edges(v, g))) { |
| | 1 | 1099 | | auto s = boost::target(e, g); |
| | 1 | 1100 | | if (g[s].infer.kind == core::TaskKind::Sync) { |
| | 1 | 1101 | | size_t sid = node_to_section_map_.at(g[s].spec.name); |
| | 1 | 1102 | | cons_stream = out_->resources.streams.at(sid).get(); |
| | 1 | 1103 | | break; |
| | | 1104 | | } |
| | 0 | 1105 | | } |
| | | 1106 | | |
| | 1 | 1107 | | core::AsyncCreateCtx ctx{.producer_stream = static_cast<cudaStream_t>(prod_stream), |
| | 1 | 1108 | | .consumer_stream = static_cast<cudaStream_t>(cons_stream)}; |
| | | 1109 | | |
| | 1 | 1110 | | auto &factory = registry_.get_async(np.spec.kind); |
| | | 1111 | | |
| | 1 | 1112 | | auto task = create_or_update_task<core::IAsyncTask>(factory, np, ctx); |
| | 1 | 1113 | | tasks.emplace(np.spec.name, std::move(task)); |
| | 1 | 1114 | | } |
| | 1 | 1115 | | } |
| | 1 | 1116 | | } |
| | | 1117 | | |
| | | 1118 | | std::shared_ptr<spdlog::logger> create_task_logger(const std::string &node_name, |
| | 1 | 1119 | | const std::string &node_kind) { |
| | 1 | 1120 | | auto sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); |
| | 1 | 1121 | | sink->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%n] [thread %t] [%^%l%$] %v"); |
| | 1 | 1122 | | auto logger_name = fmt::format("TaskLogger-{}-{}", node_kind, node_name); |
| | 1 | 1123 | | auto logger = std::make_shared<spdlog::logger>(logger_name, sink); |
| | 1 | 1124 | | logger->set_level(spdlog::default_logger()->level()); |
| | 1 | 1125 | | return logger; |
| | 1 | 1126 | | } |
| | | 1127 | | |
| | 1 | 1128 | | void Compiler::Impl::bind_tasks() { |
| | 1 | 1129 | | auto &g = out_->graph; |
| | 1 | 1130 | | auto &res = out_->resources; |
| | | 1131 | | |
| | 1 | 1132 | | for (auto v : boost::make_iterator_range(boost::vertices(g))) { |
| | 1 | 1133 | | const auto &np = g[v]; |
| | | 1134 | | |
| | 1 | 1135 | | auto it_task = res.tasks.find(np.spec.name); |
| | 1 | 1136 | | if (it_task == res.tasks.end()) |
| | 0 | 1137 | | continue; |
| | 1 | 1138 | | core::ITask *task = it_task->second.get(); |
| | | 1139 | | |
| | 1 | 1140 | | if (auto it_adapter = res.node_storage_adapters.find(np.spec.name); |
| | 1 | 1141 | | it_adapter != res.node_storage_adapters.end()) { |
| | 1 | 1142 | | task->bind_storage_access(it_adapter->second.get()); |
| | | 1143 | | } |
| | | 1144 | | |
| | 1 | 1145 | | auto logger = create_task_logger(np.spec.name, np.spec.kind); |
| | 1 | 1146 | | task->bind_logger(std::move(logger)); |
| | 1 | 1147 | | } |
| | 1 | 1148 | | } |
| | | 1149 | | |
| | | 1150 | | // ------------------------------------------------------------------------------------------------- |
| | | 1151 | | // Public API PIMPL forwarding |
| | | 1152 | | // ------------------------------------------------------------------------------------------------- |
| | | 1153 | | |
| | | 1154 | | Compiler::Compiler(core::Registry ®istry, Config config) |
| | 1 | 1155 | | : impl_(std::make_unique<Impl>(registry, std::move(config))) {} |
| | | 1156 | | |
| | 1 | 1157 | | Compiler::~Compiler() = default; |
| | | 1158 | | |
| | | 1159 | | std::unique_ptr<CompilerOutput> Compiler::compile(const core::GraphSpec &gspec, |
| | 1 | 1160 | | std::unique_ptr<CompilerOutput> prev) { |
| | 1 | 1161 | | return impl_->run(gspec, std::move(prev)); |
| | 1 | 1162 | | } |
| | | 1163 | | |
| | | 1164 | | } // namespace holoflow::runtime |