src/jit/kernel_disk_cache.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include "kernel_disk_cache.h" | ||
| 2 | |||
| 3 | #include <cstdlib> | ||
| 4 | #include <cstring> | ||
| 5 | #include <exception> | ||
| 6 | #include <mutex> | ||
| 7 | #include <span> | ||
| 8 | #include <system_error> | ||
| 9 | #include <unordered_map> | ||
| 10 | #include <utility> | ||
| 11 | |||
| 12 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 13 | #include <brass/cache/artifact_cache.hpp> | ||
| 14 | #include <brass/cache/native_module_cache.hpp> | ||
| 15 | #include <brass/codegen/kernel_jit.hpp> | ||
| 16 | #include <brass/mir/function.hpp> | ||
| 17 | #include <brass/target/msl_target.hpp> | ||
| 18 | #include <brass/target/spirv_target.hpp> | ||
| 19 | #endif | ||
| 20 | |||
| 21 | namespace brotensor::jit { | ||
| 22 | |||
| 23 | namespace { | ||
| 24 | |||
| 25 | 5711 | [[maybe_unused]] bool env_flag(const char* name) { | |
| 26 | 5711 | const char* v = std::getenv(name); | |
| 27 | 5711 | return v && (std::strcmp(v, "1") == 0 || std::strcmp(v, "true") == 0); | |
| 28 | } | ||
| 29 | |||
| 30 | 3537 | std::filesystem::path env_cache_dir() { | |
| 31 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 32 | 3537 | return brass::cache::default_cache_dir("brotensor", "kernels", "BRO_ML_CACHE_DIR"); | |
| 33 | #else | ||
| 34 | if (const char* env_dir = std::getenv("BRO_ML_CACHE_DIR")) { | ||
| 35 | if (env_dir[0] != '\0') return std::filesystem::path(env_dir); | ||
| 36 | } | ||
| 37 | if (const char* xdg = std::getenv("XDG_CACHE_HOME")) { | ||
| 38 | if (xdg[0] != '\0') return std::filesystem::path(xdg) / "brotensor" / "kernels"; | ||
| 39 | } | ||
| 40 | if (const char* home = std::getenv("HOME")) { | ||
| 41 | if (home[0] != '\0') return std::filesystem::path(home) / ".cache" / "brotensor" / "kernels"; | ||
| 42 | } | ||
| 43 | std::error_code ec; | ||
| 44 | auto tmp = std::filesystem::temp_directory_path(ec); | ||
| 45 | if (ec || tmp.empty()) tmp = "/tmp"; | ||
| 46 | return tmp / "brotensor_kernel_cache"; | ||
| 47 | #endif | ||
| 48 | } | ||
| 49 | |||
| 50 | 3478 | uint64_t env_max_bytes() { | |
| 51 | 3478 | if (const char* mb = std::getenv("BRO_ML_CACHE_MAX_MB")) { | |
| 52 | ✗ | char* end = nullptr; | |
| 53 | ✗ | const unsigned long long v = std::strtoull(mb, &end, 10); | |
| 54 | ✗ | if (end != mb && *end == '\0' && v > 0) return static_cast<uint64_t>(v) << 20; | |
| 55 | ✗ | } | |
| 56 | 3478 | return KernelDiskCache::kDefaultMaxBytes; | |
| 57 | 3478 | } | |
| 58 | |||
| 59 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 60 | |||
| 61 | // The previous cache's files: "<32 hex>.btkc", its temporaries | ||
| 62 | // "<...>.btkc.tmp.<pid>...", and its load copies under ".rt/". Nothing reads | ||
| 63 | // them; they only take space. | ||
| 64 | 141 | void remove_old_format(const std::filesystem::path& dir) { | |
| 65 | 141 | std::error_code ec; | |
| 66 | 141 | std::filesystem::directory_iterator it(dir, ec), end; | |
| 67 | 92585 | for (; !ec && it != end; it.increment(ec)) { | |
| 68 | 92444 | const std::string name = it->path().filename().string(); | |
| 69 | 92444 | const bool old = (name.size() > 5 && name.compare(name.size() - 5, 5, ".btkc") == 0) || | |
| 70 | 92443 | name.find(".btkc.tmp.") != std::string::npos; | |
| 71 | 92444 | std::error_code rec; | |
| 72 | 92444 | if (old && it->is_regular_file(rec)) std::filesystem::remove(it->path(), rec); | |
| 73 | 92444 | } | |
| 74 | 141 | std::filesystem::remove_all(dir / ".rt", ec); | |
| 75 | 141 | } | |
| 76 | |||
| 77 | 2199 | bool is_damage(brass::cache::Miss why) { | |
| 78 | using brass::cache::Miss; | ||
| 79 | 4397 | return why == Miss::Unreadable || why == Miss::Foreign || why == Miss::KeyMismatch || | |
| 80 | 2198 | why == Miss::Truncated || why == Miss::Corrupt; | |
| 81 | } | ||
| 82 | |||
| 83 | 196 | brass::codegen::KernelOptions to_kernel_options(const KernelDiskCache::CpuCompileOptions& opts, | |
| 84 | bool enable_optimizations) { | ||
| 85 | 196 | brass::codegen::KernelOptions k; | |
| 86 | 196 | k.opt_level = 2; | |
| 87 | 196 | k.enable_optimizations = enable_optimizations; | |
| 88 | 196 | k.enable_sroa = true; | |
| 89 | 196 | k.enable_bce = true; | |
| 90 | 196 | k.enable_smt_guard_elim = opts.enable_smt_guard_elim; | |
| 91 | 196 | k.enable_superopt = opts.enable_mir_superopt; | |
| 92 | 196 | k.enable_avx2 = opts.enable_avx2; | |
| 93 | 196 | k.enable_fma = opts.enable_fma; | |
| 94 | 196 | k.enable_vectorize = opts.enable_vectorize; | |
| 95 | 196 | k.enable_slp = true; | |
| 96 | 196 | k.enable_unroll = opts.enable_unroll; | |
| 97 | 196 | k.unroll_factor = opts.unroll_factor; | |
| 98 | 196 | k.enable_fp_reassociation = opts.enable_fp_reassociation; | |
| 99 | 196 | k.enable_trace_layout = opts.enable_trace_layout; | |
| 100 | 196 | k.enable_post_ra_schedule = opts.enable_post_ra_schedule; | |
| 101 | 196 | k.enable_software_pipelining = opts.enable_software_pipelining; | |
| 102 | 196 | return k; | |
| 103 | } | ||
| 104 | |||
| 105 | ✗ | brass::codegen::KernelFunction jit_compile(brass::Module& mod, std::string_view entry, | |
| 106 | const KernelDiskCache::CpuCompileOptions& opts) { | ||
| 107 | ✗ | brass::codegen::KernelJit jit(to_kernel_options(opts, opts.enable_loop_opt)); | |
| 108 | ✗ | return jit.compile(mod, entry); | |
| 109 | ✗ | } | |
| 110 | |||
| 111 | // build_fn, then Brass's KernelJit optimization & verification pipeline. | ||
| 112 | 98 | void build_kernel_module(brass::Module& mod, const std::function<void(brass::Module&)>& build_fn, | |
| 113 | const KernelDiskCache::CpuCompileOptions& opts) { | ||
| 114 | 98 | build_fn(mod); | |
| 115 | 98 | brass::codegen::KernelJit::prepare_module(mod, to_kernel_options(opts, opts.enable_loop_opt)); | |
| 116 | 98 | } | |
| 117 | |||
| 118 | #endif // BROTENSOR_HAS_BRASS_JIT | ||
| 119 | |||
| 120 | } // namespace | ||
| 121 | |||
| 122 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 123 | struct KernelDiskCache::Stores { | ||
| 124 | 282 | Stores(const std::filesystem::path& dir, uint64_t max_bytes) : store(dir, max_bytes), natives(store) {} | |
| 125 | brass::cache::ArtifactCache store; | ||
| 126 | brass::cache::NativeModuleCache natives; | ||
| 127 | }; | ||
| 128 | #else | ||
| 129 | struct KernelDiskCache::Stores {}; | ||
| 130 | #endif | ||
| 131 | |||
| 132 | 5735 | KernelDiskCache& KernelDiskCache::instance() { | |
| 133 | 5735 | static KernelDiskCache cache; | |
| 134 | 5735 | return cache; | |
| 135 | } | ||
| 136 | |||
| 137 | 5711 | bool KernelDiskCache::is_enabled() const noexcept { | |
| 138 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 139 | 5711 | return !env_flag("BRO_ML_CACHE_DISABLE"); | |
| 140 | #else | ||
| 141 | return false; | ||
| 142 | #endif | ||
| 143 | } | ||
| 144 | |||
| 145 | 3662 | std::filesystem::path KernelDiskCache::cache_dir() const { | |
| 146 | { | ||
| 147 | 3662 | std::lock_guard<std::mutex> lk(mutex_); | |
| 148 | 3662 | if (!override_dir_.empty()) return override_dir_; | |
| 149 | 3662 | } | |
| 150 | 3537 | return env_cache_dir(); | |
| 151 | 3662 | } | |
| 152 | |||
| 153 | 7 | void KernelDiskCache::set_cache_dir(std::filesystem::path dir) { | |
| 154 | 7 | std::lock_guard<std::mutex> lk(mutex_); | |
| 155 | 7 | override_dir_ = std::move(dir); | |
| 156 | 7 | } | |
| 157 | |||
| 158 | 2 | void KernelDiskCache::clear_cache_dir_override() { | |
| 159 | 2 | std::lock_guard<std::mutex> lk(mutex_); | |
| 160 | 2 | override_dir_.clear(); | |
| 161 | 2 | } | |
| 162 | |||
| 163 | 3519 | uint64_t KernelDiskCache::max_bytes() const { | |
| 164 | { | ||
| 165 | 3519 | std::lock_guard<std::mutex> lk(mutex_); | |
| 166 | 3519 | if (override_max_bytes_ != 0) return override_max_bytes_; | |
| 167 | 3519 | } | |
| 168 | 3478 | return env_max_bytes(); | |
| 169 | 3519 | } | |
| 170 | |||
| 171 | 3 | void KernelDiskCache::set_max_bytes(uint64_t bytes) { | |
| 172 | 3 | std::lock_guard<std::mutex> lk(mutex_); | |
| 173 | 3 | override_max_bytes_ = bytes; | |
| 174 | 3 | } | |
| 175 | |||
| 176 | 3519 | std::shared_ptr<KernelDiskCache::Stores> KernelDiskCache::stores() const { | |
| 177 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 178 | 3519 | if (!is_enabled()) return nullptr; | |
| 179 | 3519 | const std::filesystem::path dir = cache_dir(); | |
| 180 | 3519 | const uint64_t budget = max_bytes(); | |
| 181 | 3519 | std::lock_guard<std::mutex> lk(mutex_); | |
| 182 | 3519 | if (stores_ && stores_->store.dir() == dir && stores_->store.max_bytes() == budget) return stores_; | |
| 183 | 141 | remove_old_format(dir); | |
| 184 | 141 | stores_ = std::make_shared<Stores>(dir, budget); | |
| 185 | 141 | return stores_; | |
| 186 | #else | ||
| 187 | return nullptr; | ||
| 188 | #endif | ||
| 189 | 3519 | } | |
| 190 | |||
| 191 | 42 | bool KernelDiskCache::store_ptx(std::string_view signature, std::string_view ptx) { | |
| 192 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 193 | 42 | if (ptx.empty()) return false; | |
| 194 | 42 | auto st = stores(); | |
| 195 | 42 | if (!st || !st->store.put(blob_key("ptx", signature), {brass::cache::BlobRef("ptx", ptx)})) return false; | |
| 196 | 42 | std::lock_guard<std::mutex> lk(mutex_); | |
| 197 | 42 | ++stats_.writes; | |
| 198 | 42 | return true; | |
| 199 | #else | ||
| 200 | (void)signature; | ||
| 201 | (void)ptx; | ||
| 202 | return false; | ||
| 203 | #endif | ||
| 204 | 42 | } | |
| 205 | |||
| 206 | 4 | bool KernelDiskCache::load_ptx(std::string_view signature, std::string& out_ptx) { | |
| 207 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 208 | 4 | brass::cache::Miss why = brass::cache::Miss::None; | |
| 209 | 4 | std::optional<brass::cache::Artifact> art; | |
| 210 | 4 | if (auto st = stores()) art = st->store.get(blob_key("ptx", signature), &why); | |
| 211 | 4 | bool damaged = is_damage(why); | |
| 212 | 4 | if (art) { | |
| 213 | 2 | const std::string_view text = art->text("ptx"); | |
| 214 | 2 | if (text.find(".version") != std::string_view::npos || text.find(".entry") != std::string_view::npos) { | |
| 215 | 2 | out_ptx.assign(text); | |
| 216 | 2 | std::lock_guard<std::mutex> lk(mutex_); | |
| 217 | 2 | ++stats_.hits; | |
| 218 | 2 | return true; | |
| 219 | 2 | } | |
| 220 | ✗ | damaged = true; | |
| 221 | ✗ | } | |
| 222 | 2 | std::lock_guard<std::mutex> lk(mutex_); | |
| 223 | 2 | ++stats_.misses; | |
| 224 | 2 | if (damaged) ++stats_.corruptions; | |
| 225 | 2 | return false; | |
| 226 | #else | ||
| 227 | (void)signature; | ||
| 228 | (void)out_ptx; | ||
| 229 | return false; | ||
| 230 | #endif | ||
| 231 | 4 | } | |
| 232 | |||
| 233 | 2 | bool KernelDiskCache::store_blob(std::string_view kind, std::string_view signature, | |
| 234 | const void* data, std::size_t size) { | ||
| 235 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 236 | 2 | if (kind.empty() || !data || size == 0) return false; | |
| 237 | 2 | auto st = stores(); | |
| 238 | 2 | if (!st) return false; | |
| 239 | 2 | const auto* bytes = static_cast<const uint8_t*>(data); | |
| 240 | 4 | if (!st->store.put(blob_key(kind, signature), | |
| 241 | 2 | {brass::cache::BlobRef("blob", std::span<const uint8_t>(bytes, size))})) { | |
| 242 | ✗ | return false; | |
| 243 | } | ||
| 244 | 2 | std::lock_guard<std::mutex> lk(mutex_); | |
| 245 | 2 | ++stats_.writes; | |
| 246 | 2 | return true; | |
| 247 | #else | ||
| 248 | (void)kind; | ||
| 249 | (void)signature; | ||
| 250 | (void)data; | ||
| 251 | (void)size; | ||
| 252 | return false; | ||
| 253 | #endif | ||
| 254 | 2 | } | |
| 255 | |||
| 256 | 2 | bool KernelDiskCache::load_blob(std::string_view kind, std::string_view signature, | |
| 257 | std::vector<uint8_t>& out) { | ||
| 258 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 259 | 2 | if (kind.empty()) return false; | |
| 260 | 2 | brass::cache::Miss why = brass::cache::Miss::None; | |
| 261 | 2 | std::optional<brass::cache::Artifact> art; | |
| 262 | 2 | if (auto st = stores()) art = st->store.get(blob_key(kind, signature), &why); | |
| 263 | 2 | const bool damaged = is_damage(why); | |
| 264 | 2 | if (art) { | |
| 265 | 2 | const auto bytes = art->bytes("blob"); | |
| 266 | 2 | out.assign(bytes.begin(), bytes.end()); | |
| 267 | 2 | std::lock_guard<std::mutex> lk(mutex_); | |
| 268 | 2 | ++stats_.hits; | |
| 269 | 2 | return true; | |
| 270 | 2 | } | |
| 271 | ✗ | std::lock_guard<std::mutex> lk(mutex_); | |
| 272 | ✗ | ++stats_.misses; | |
| 273 | ✗ | if (damaged) ++stats_.corruptions; | |
| 274 | ✗ | return false; | |
| 275 | #else | ||
| 276 | (void)kind; | ||
| 277 | (void)signature; | ||
| 278 | (void)out; | ||
| 279 | return false; | ||
| 280 | #endif | ||
| 281 | 2 | } | |
| 282 | |||
| 283 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 284 | |||
| 285 | 3379 | brass::cache::CacheKey KernelDiskCache::blob_key(std::string_view kind, std::string_view signature) { | |
| 286 | 6758 | return brass::cache::KeyBuilder(kKeyDomain) | |
| 287 | 3379 | .add_brass_codegen() | |
| 288 | 3379 | .add("brotensor.kernels", kernel_source_fingerprint()) | |
| 289 | 3379 | .add("kind", kind) | |
| 290 | 3379 | .add("signature", signature) | |
| 291 | 3379 | .finish(); | |
| 292 | } | ||
| 293 | |||
| 294 | 141 | brass::cache::CacheKey KernelDiskCache::cpu_key(std::string_view signature, std::string_view entry_name, | |
| 295 | const CpuCompileOptions& o) { | ||
| 296 | 282 | return brass::cache::KeyBuilder(kKeyDomain) | |
| 297 | 141 | .add_brass_build() | |
| 298 | 141 | .add("brotensor.kernels", kernel_source_fingerprint()) | |
| 299 | 141 | .add("kind", "cpu") | |
| 300 | 141 | .add("signature", signature) | |
| 301 | 141 | .add("entry", entry_name) | |
| 302 | 141 | .add_bool("opt.loop_opt", o.enable_loop_opt) | |
| 303 | 141 | .add_bool("opt.avx2", o.enable_avx2) | |
| 304 | 141 | .add_bool("opt.fma", o.enable_fma) | |
| 305 | 141 | .add_bool("opt.vectorize", o.enable_vectorize) | |
| 306 | 141 | .add_bool("opt.unroll", o.enable_unroll) | |
| 307 | 141 | .add_u64("opt.unroll_factor", o.unroll_factor) | |
| 308 | 141 | .add_bool("opt.fp_reassociation", o.enable_fp_reassociation) | |
| 309 | 141 | .add_bool("opt.smt_guard_elim", o.enable_smt_guard_elim) | |
| 310 | 141 | .add_bool("opt.mir_superopt", o.enable_mir_superopt) | |
| 311 | 141 | .add_bool("opt.trace_layout", o.enable_trace_layout) | |
| 312 | 141 | .add_bool("opt.post_ra_schedule", o.enable_post_ra_schedule) | |
| 313 | 141 | .add_bool("opt.software_pipelining", o.enable_software_pipelining) | |
| 314 | 141 | .finish(); | |
| 315 | } | ||
| 316 | |||
| 317 | 2 | std::filesystem::path KernelDiskCache::blob_entry_path(std::string_view kind, std::string_view signature) const { | |
| 318 | 2 | auto st = stores(); | |
| 319 | 2 | return st ? st->store.path_for(blob_key(kind, signature)) : std::filesystem::path(); | |
| 320 | 2 | } | |
| 321 | |||
| 322 | 3 | std::filesystem::path KernelDiskCache::cpu_entry_path(std::string_view signature, std::string_view entry_name, | |
| 323 | const CpuCompileOptions& opts) const { | ||
| 324 | 3 | auto st = stores(); | |
| 325 | 3 | if (!st) return {}; | |
| 326 | 3 | return st->store.path_for(st->natives.storage_key(cpu_key(signature, entry_name, opts), {})); | |
| 327 | 3 | } | |
| 328 | |||
| 329 | 1 | uint64_t KernelDiskCache::trim() { | |
| 330 | 1 | auto st = stores(); | |
| 331 | 1 | return st ? st->store.trim() : 0; | |
| 332 | 1 | } | |
| 333 | |||
| 334 | 1 | bool KernelDiskCache::store_spirv_kernel(std::string_view signature, const brass::target::SpirvKernel& k) { | |
| 335 | 1 | if (k.words.empty()) return false; | |
| 336 | 1 | auto st = stores(); | |
| 337 | 1 | if (!st) return false; | |
| 338 | 1 | const std::vector<uint8_t> encoded = brass::target::serialize_spirv_kernel(k); | |
| 339 | 2 | const bool ok = st->store.put(blob_key("spirv", signature), | |
| 340 | 1 | {brass::cache::BlobRef("spirv_kernel", encoded)}); | |
| 341 | 1 | if (!ok) return false; | |
| 342 | 1 | std::lock_guard<std::mutex> lk(mutex_); | |
| 343 | 1 | ++stats_.writes; | |
| 344 | 1 | return true; | |
| 345 | 1 | } | |
| 346 | |||
| 347 | 2 | bool KernelDiskCache::load_spirv_kernel(std::string_view signature, brass::target::SpirvKernel& out) { | |
| 348 | 2 | brass::cache::Miss why = brass::cache::Miss::None; | |
| 349 | 2 | std::optional<brass::cache::Artifact> art; | |
| 350 | 2 | if (auto st = stores()) art = st->store.get(blob_key("spirv", signature), &why); | |
| 351 | 2 | bool damaged = is_damage(why); | |
| 352 | 2 | if (art) { | |
| 353 | 1 | brass::target::SpirvKernel k; | |
| 354 | 2 | if (brass::target::deserialize_spirv_kernel(art->bytes("spirv_kernel"), k) && | |
| 355 | 1 | k.words.size() >= 5 && k.words[0] == 0x07230203u) { | |
| 356 | 1 | out = std::move(k); | |
| 357 | 1 | std::lock_guard<std::mutex> lk(mutex_); | |
| 358 | 1 | ++stats_.hits; | |
| 359 | 1 | return true; | |
| 360 | 1 | } | |
| 361 | ✗ | damaged = true; | |
| 362 | 1 | } | |
| 363 | 1 | std::lock_guard<std::mutex> lk(mutex_); | |
| 364 | 1 | ++stats_.misses; | |
| 365 | 1 | if (damaged) ++stats_.corruptions; | |
| 366 | 1 | return false; | |
| 367 | 2 | } | |
| 368 | |||
| 369 | namespace { | ||
| 370 | |||
| 371 | 20989 | void append_u32(std::vector<uint8_t>& buf, uint32_t v) { | |
| 372 | 104945 | for (int i = 0; i < 4; ++i) buf.push_back(static_cast<uint8_t>((v >> (i * 8)) & 0xFFu)); | |
| 373 | 20989 | } | |
| 374 | |||
| 375 | 2262 | void append_str(std::vector<uint8_t>& buf, const std::string& s) { | |
| 376 | 2262 | append_u32(buf, static_cast<uint32_t>(s.size())); | |
| 377 | 4524 | buf.insert(buf.end(), reinterpret_cast<const uint8_t*>(s.data()), | |
| 378 | 2262 | reinterpret_cast<const uint8_t*>(s.data()) + s.size()); | |
| 379 | 2262 | } | |
| 380 | |||
| 381 | 20028 | bool read_u32(std::span<const uint8_t> bytes, size_t& pos, uint32_t& out) { | |
| 382 | 20028 | if (pos + 4 > bytes.size()) return false; | |
| 383 | 20028 | uint32_t v = 0; | |
| 384 | 100140 | for (int i = 0; i < 4; ++i) v |= static_cast<uint32_t>(bytes[pos + static_cast<size_t>(i)]) << (i * 8); | |
| 385 | 20028 | pos += 4; | |
| 386 | 20028 | out = v; | |
| 387 | 20028 | return true; | |
| 388 | 20028 | } | |
| 389 | |||
| 390 | 2134 | bool read_str(std::span<const uint8_t> bytes, size_t& pos, std::string& out) { | |
| 391 | 2134 | uint32_t n = 0; | |
| 392 | 2134 | if (!read_u32(bytes, pos, n) || pos + n > bytes.size()) return false; | |
| 393 | 2134 | out.assign(reinterpret_cast<const char*>(bytes.data() + pos), n); | |
| 394 | 2134 | pos += n; | |
| 395 | 2134 | return true; | |
| 396 | 2134 | } | |
| 397 | |||
| 398 | constexpr uint32_t kMslBlobMagic = 0x314C534Du; // "MSL1" | ||
| 399 | |||
| 400 | } // namespace | ||
| 401 | |||
| 402 | 1131 | bool KernelDiskCache::store_msl_kernel(std::string_view signature, const brass::target::MslKernel& k) { | |
| 403 | 1131 | if (k.source.empty()) return false; | |
| 404 | 1131 | auto st = stores(); | |
| 405 | 1131 | if (!st) return false; | |
| 406 | 1131 | std::vector<uint8_t> encoded; | |
| 407 | 1131 | encoded.reserve(64 + k.entry_name.size() + k.source.size() + k.scalar_param_offsets.size() * 4); | |
| 408 | 1131 | append_u32(encoded, kMslBlobMagic); | |
| 409 | 1131 | append_str(encoded, k.entry_name); | |
| 410 | 1131 | append_str(encoded, k.source); | |
| 411 | 1131 | append_u32(encoded, k.num_buffers); | |
| 412 | 1131 | append_u32(encoded, k.scalar_params_bytes); | |
| 413 | 1131 | append_u32(encoded, k.workgroup_x); | |
| 414 | 1131 | append_u32(encoded, k.workgroup_y); | |
| 415 | 1131 | append_u32(encoded, k.workgroup_z); | |
| 416 | 1131 | append_u32(encoded, k.uses_shared_memory ? 1u : 0u); | |
| 417 | 1131 | append_u32(encoded, k.shared_memory_bytes); | |
| 418 | 1131 | append_u32(encoded, static_cast<uint32_t>(k.scalar_param_offsets.size())); | |
| 419 | 9679 | for (uint32_t off : k.scalar_param_offsets) append_u32(encoded, off); | |
| 420 | |||
| 421 | 2262 | const bool ok = st->store.put(blob_key("msl", signature), | |
| 422 | 1131 | {brass::cache::BlobRef("msl_kernel", encoded)}); | |
| 423 | 1131 | if (!ok) return false; | |
| 424 | 1131 | std::lock_guard<std::mutex> lk(mutex_); | |
| 425 | 1131 | ++stats_.writes; | |
| 426 | 1131 | return true; | |
| 427 | 1131 | } | |
| 428 | |||
| 429 | 2191 | bool KernelDiskCache::load_msl_kernel(std::string_view signature, brass::target::MslKernel& out) { | |
| 430 | 2191 | brass::cache::Miss why = brass::cache::Miss::None; | |
| 431 | 2191 | std::optional<brass::cache::Artifact> art; | |
| 432 | 2191 | if (auto st = stores()) art = st->store.get(blob_key("msl", signature), &why); | |
| 433 | 2191 | bool damaged = is_damage(why); | |
| 434 | 2191 | if (art) { | |
| 435 | 1067 | auto raw = art->bytes("msl_kernel"); | |
| 436 | 1067 | size_t pos = 0; | |
| 437 | 1067 | uint32_t magic = 0, used_smem = 0, noff = 0; | |
| 438 | 1067 | brass::target::MslKernel k; | |
| 439 | 2134 | if (read_u32(raw, pos, magic) && magic == kMslBlobMagic && | |
| 440 | 1067 | read_str(raw, pos, k.entry_name) && | |
| 441 | 1067 | read_str(raw, pos, k.source) && !k.source.empty() && | |
| 442 | 1067 | read_u32(raw, pos, k.num_buffers) && | |
| 443 | 1067 | read_u32(raw, pos, k.scalar_params_bytes) && | |
| 444 | 1067 | read_u32(raw, pos, k.workgroup_x) && | |
| 445 | 1067 | read_u32(raw, pos, k.workgroup_y) && | |
| 446 | 1067 | read_u32(raw, pos, k.workgroup_z) && | |
| 447 | 1067 | read_u32(raw, pos, used_smem) && | |
| 448 | 1067 | read_u32(raw, pos, k.shared_memory_bytes) && | |
| 449 | 1067 | read_u32(raw, pos, noff) && pos + static_cast<size_t>(noff) * 4 == raw.size()) { | |
| 450 | 1067 | k.uses_shared_memory = (used_smem != 0); | |
| 451 | 1067 | k.scalar_param_offsets.resize(noff); | |
| 452 | 9358 | for (uint32_t i = 0; i < noff; ++i) read_u32(raw, pos, k.scalar_param_offsets[i]); | |
| 453 | 1067 | out = std::move(k); | |
| 454 | 1067 | std::lock_guard<std::mutex> lk(mutex_); | |
| 455 | 1067 | ++stats_.hits; | |
| 456 | 1067 | return true; | |
| 457 | 1067 | } | |
| 458 | ✗ | damaged = true; | |
| 459 | 1067 | } | |
| 460 | 1124 | std::lock_guard<std::mutex> lk(mutex_); | |
| 461 | 1124 | ++stats_.misses; | |
| 462 | 1124 | if (damaged) ++stats_.corruptions; | |
| 463 | 1124 | return false; | |
| 464 | 2191 | } | |
| 465 | |||
| 466 | 125 | void* KernelDiskCache::compile_or_load_cpu_kernel( | |
| 467 | std::string_view signature, | ||
| 468 | std::string_view entry_name, | ||
| 469 | const std::function<void(brass::Module&)>& build_fn, | ||
| 470 | const CpuCompileOptions& opts) { | ||
| 471 | |||
| 472 | 125 | brass::codegen::KernelFunction jitted; | |
| 473 | 250 | if (auto st = stores()) { | |
| 474 | 125 | std::exception_ptr thrown; | |
| 475 | 223 | const auto build_obj = [&](brass::object::ObjectFile& obj, std::string& error) { | |
| 476 | 98 | brass::Module mod("brotensor_" + std::string(entry_name)); | |
| 477 | try { | ||
| 478 | 98 | build_kernel_module(mod, build_fn, opts); | |
| 479 | 98 | } catch (...) { | |
| 480 | ✗ | thrown = std::current_exception(); | |
| 481 | ✗ | error = "the kernel's build threw"; | |
| 482 | ✗ | return false; | |
| 483 | ✗ | } | |
| 484 | // A cached image cannot point into this process: a module that | ||
| 485 | // calls functions it does not define is compiled in memory. | ||
| 486 | 98 | if (!mod.external_symbols().empty()) { | |
| 487 | ✗ | jitted = jit_compile(mod, entry_name, opts); | |
| 488 | ✗ | error = "the kernel calls functions it does not define"; | |
| 489 | ✗ | return false; | |
| 490 | } | ||
| 491 | try { | ||
| 492 | 98 | brass::codegen::KernelJit jit(to_kernel_options(opts, opts.enable_loop_opt)); | |
| 493 | 98 | obj = jit.compile_object(mod); | |
| 494 | 98 | } catch (const std::exception& e) { | |
| 495 | ✗ | error = e.what(); | |
| 496 | ✗ | return false; | |
| 497 | ✗ | } catch (...) { | |
| 498 | ✗ | error = "KernelJit::compile_object threw"; | |
| 499 | ✗ | return false; | |
| 500 | ✗ | } | |
| 501 | 98 | return true; | |
| 502 | 98 | }; | |
| 503 | 125 | std::string error; | |
| 504 | std::shared_ptr<const brass::cache::NativeModule> m = | ||
| 505 | 125 | st->natives.get_or_build_object(cpu_key(signature, entry_name, opts), build_obj, {}, &error); | |
| 506 | 125 | if (thrown) std::rethrow_exception(thrown); | |
| 507 | 125 | if (m) { | |
| 508 | 125 | if (void* sym = m->symbol(entry_name)) { | |
| 509 | 125 | std::lock_guard<std::mutex> lk(mutex_); | |
| 510 | 125 | if (m->from_cache()) { | |
| 511 | 27 | ++stats_.hits; | |
| 512 | 27 | } else { | |
| 513 | 98 | ++stats_.misses; | |
| 514 | 98 | ++stats_.writes; | |
| 515 | } | ||
| 516 | 125 | loaded_.push_back(std::move(m)); | |
| 517 | 125 | return sym; | |
| 518 | 125 | } | |
| 519 | ✗ | } | |
| 520 | 125 | } | |
| 521 | |||
| 522 | // Disabled, uncacheable, or the image would not link or load: in memory. | ||
| 523 | ✗ | if (!jitted.is_valid()) { | |
| 524 | ✗ | brass::Module mod("brotensor_" + std::string(entry_name)); | |
| 525 | ✗ | build_kernel_module(mod, build_fn, opts); | |
| 526 | ✗ | jitted = jit_compile(mod, entry_name, opts); | |
| 527 | ✗ | if (!jitted.is_valid()) return nullptr; | |
| 528 | ✗ | } | |
| 529 | ✗ | std::lock_guard<std::mutex> lk(mutex_); | |
| 530 | ✗ | ++stats_.misses; | |
| 531 | ✗ | loaded_.push_back(jitted.engine()); | |
| 532 | ✗ | return jitted.entry_point(); | |
| 533 | 125 | } | |
| 534 | |||
| 535 | #endif // BROTENSOR_HAS_BRASS_JIT | ||
| 536 | |||
| 537 | 18 | KernelDiskCache::Stats KernelDiskCache::stats() const noexcept { | |
| 538 | 18 | std::lock_guard<std::mutex> lk(mutex_); | |
| 539 | 18 | return stats_; | |
| 540 | 18 | } | |
| 541 | |||
| 542 | 10 | void KernelDiskCache::reset_stats() noexcept { | |
| 543 | 10 | std::lock_guard<std::mutex> lk(mutex_); | |
| 544 | 10 | stats_ = Stats{}; | |
| 545 | } | ||
| 546 | |||
| 547 | 8 | void KernelDiskCache::clear_loaded_libraries() { | |
| 548 | 8 | std::vector<std::shared_ptr<const void>> dropped; | |
| 549 | { | ||
| 550 | 8 | std::lock_guard<std::mutex> lk(mutex_); | |
| 551 | 8 | dropped.swap(loaded_); | |
| 552 | 8 | } | |
| 553 | 8 | } | |
| 554 | |||
| 555 | 6 | std::size_t KernelDiskCache::entry_count() const { | |
| 556 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 557 | 6 | if (auto st = stores()) return st->store.list_keys().size(); | |
| 558 | #endif | ||
| 559 | ✗ | return 0; | |
| 560 | 6 | } | |
| 561 | |||
| 562 | 3 | bool KernelDiskCache::export_bundle(const std::filesystem::path& out_path, | |
| 563 | std::string_view metadata, | ||
| 564 | std::size_t* entries_written, | ||
| 565 | std::size_t* bytes_out, | ||
| 566 | std::string* error) const { | ||
| 567 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 568 | 3 | auto st = stores(); | |
| 569 | 3 | if (!st) { | |
| 570 | ✗ | if (error) *error = "kernel disk cache is disabled"; | |
| 571 | ✗ | return false; | |
| 572 | } | ||
| 573 | 3 | brass::cache::BundleStats bs; | |
| 574 | 3 | const bool ok = st->store.export_bundle(out_path, metadata, &bs, error); | |
| 575 | 3 | if (entries_written) *entries_written = bs.entries_written; | |
| 576 | 3 | if (bytes_out) *bytes_out = bs.bytes; | |
| 577 | 3 | return ok; | |
| 578 | #else | ||
| 579 | (void)out_path; (void)metadata; (void)entries_written; (void)bytes_out; | ||
| 580 | if (error) *error = "Brass JIT is disabled"; | ||
| 581 | return false; | ||
| 582 | #endif | ||
| 583 | 3 | } | |
| 584 | |||
| 585 | 4 | bool KernelDiskCache::import_bundle(const std::filesystem::path& in_path, | |
| 586 | std::string* metadata_out, | ||
| 587 | std::size_t* entries_imported, | ||
| 588 | std::size_t* entries_skipped, | ||
| 589 | std::size_t* bytes_out, | ||
| 590 | std::string* error) { | ||
| 591 | #if BROTENSOR_HAS_BRASS_JIT | ||
| 592 | 4 | auto st = stores(); | |
| 593 | 4 | if (!st) { | |
| 594 | ✗ | if (error) *error = "kernel disk cache is disabled"; | |
| 595 | ✗ | return false; | |
| 596 | } | ||
| 597 | 4 | brass::cache::BundleStats bs; | |
| 598 | 4 | const bool ok = st->store.import_bundle(in_path, metadata_out, &bs, error); | |
| 599 | 4 | if (entries_imported) *entries_imported = bs.entries_imported; | |
| 600 | 4 | if (entries_skipped) *entries_skipped = bs.entries_skipped; | |
| 601 | 4 | if (bytes_out) *bytes_out = bs.bytes; | |
| 602 | 4 | return ok; | |
| 603 | #else | ||
| 604 | (void)in_path; (void)metadata_out; (void)entries_imported; (void)entries_skipped; (void)bytes_out; | ||
| 605 | if (error) *error = "Brass JIT is disabled"; | ||
| 606 | return false; | ||
| 607 | #endif | ||
| 608 | 4 | } | |
| 609 | |||
| 610 | namespace { | ||
| 611 | struct FlushHookRegistry { | ||
| 612 | std::mutex mu; | ||
| 613 | std::unordered_map<int, PipelineCacheFlushFn> hooks; | ||
| 614 | }; | ||
| 615 | 178 | FlushHookRegistry& flush_hooks() { | |
| 616 | 178 | static auto* r = new FlushHookRegistry(); | |
| 617 | 178 | return *r; | |
| 618 | ✗ | } | |
| 619 | } // namespace | ||
| 620 | |||
| 621 | 172 | void register_pipeline_flush_hook(DeviceType type, PipelineCacheFlushFn fn) { | |
| 622 | 172 | if (!fn) return; | |
| 623 | 172 | auto& r = flush_hooks(); | |
| 624 | 172 | std::lock_guard<std::mutex> lk(r.mu); | |
| 625 | 172 | r.hooks[static_cast<int>(type)] = fn; | |
| 626 | 172 | } | |
| 627 | |||
| 628 | 6 | void flush_pipeline_caches_for(Device dev) { | |
| 629 | 6 | PipelineCacheFlushFn fn = nullptr; | |
| 630 | { | ||
| 631 | 6 | auto& r = flush_hooks(); | |
| 632 | 6 | std::lock_guard<std::mutex> lk(r.mu); | |
| 633 | 6 | auto it = r.hooks.find(static_cast<int>(dev.type)); | |
| 634 | 6 | if (it != r.hooks.end()) fn = it->second; | |
| 635 | 6 | } | |
| 636 | 6 | if (fn) fn(dev.index); | |
| 637 | 6 | } | |
| 638 | |||
| 639 | } // namespace brotensor::jit | ||
| 640 |