diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2fe3697c4f..ecdcbdeeb5 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2414,6 +2414,25 @@ Pipeline creation: The files must match the Vulkan vendor, device and pipeline-cache UUID. Vulkan supplies an opaque snapshot. Replacing part of the previous file would corrupt it. `LEONIDA_PIPELINE_CACHE_BYTES` caps session writes (256 MiB by default, zero disables the session file). + The session file can't keep a crashed run's compiles. It is written at teardown only, and a cache seeded from + the corpus returns the whole corpus, so it's over that cap. The heavy pipeline cache (RT-HEAVY-PIPELINE-CACHE, + `runtime/src/heavy_pipeline_cache.h`) keeps the graphics ones; compute pipelines go to the per-pipeline journal + described below. Every graphics build first asks the corpus cache with + `VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT`. A pipeline the corpus doesn't have is built against a + second cache, seeded from `pipeline_cache.heavy.bin` next to `pipeline_cache.bin`, so that cache holds only the + corpus's misses. + A build that takes at least `LEONIDA_HEAVY_PIPELINE_CACHE_MS` (500 by default) marks the heavy cache for writing. + A thread of its own writes it whole: 3 s after the newest slow build, and no later than 20 s after the first unwritten + one, through the same staging file and rename as the session cache. A crash therefore loses at most the last 20 s + of slow builds, and the next launch starts with the rest. A write that fails, or whose + `vkGetPipelineCacheData` returns anything but `VK_SUCCESS` (`VK_INCOMPLETE` means the cache grew after the size + query, so the blob is truncated), leaves the previous file in place and the cache dirty: it is tried again 5 s + later, the delay doubling with each failure in a row up to 2 min, so the cache is not left unsaved until teardown + and a write that keeps failing does not spin. At device teardown the thread stops, and the cache is + written if any build went into it. Fast builds are kept that way: without an offline seed every build is a miss, + so they no longer reach `pipeline_cache.session.bin`. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the + `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create + (`cache-only`) is left as it is. `LEONIDA_SKIP_COMPUTE=[,...]` (`all`: every compute program) never builds the matching compute programs and drops their dispatches, direct and indirect; the first dropped dispatch of each is logged. It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index b8d284d6e2..78c862106d 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -814,6 +814,9 @@ if(BUILD_TESTING) add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) + add_executable(heavy_pipeline_cache_test test/heavy_pipeline_cache_test.cpp) + add_test(NAME heavy_pipeline_cache COMMAND heavy_pipeline_cache_test) + # The per-pipeline journal files compute pipelines are kept in: naming, header check, atomic replacement. add_executable(pipeline_cache_journal_test test/pipeline_cache_journal_test.cpp) add_test(NAME pipeline_cache_journal COMMAND pipeline_cache_journal_test) @@ -4161,6 +4164,11 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) + # The same draws through the heavy pipeline cache (src/heavy_pipeline_cache.h): every build first asks the + # offline cache without compiling, and a miss is built against the heavy cache in a folder of its own. + add_test(NAME d3d12_mesh_heavy_cache COMMAND d3d12_mesh_test) + set_tests_properties(d3d12_mesh_heavy_cache PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT + "LEONIDA_HEAVY_PIPELINE_CACHE_MS=1;LEONIDA_PIPELINE_CACHE_DIR=${CMAKE_CURRENT_BINARY_DIR}/heavy_cache_test") else() message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") endif() diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index bb8efa815b..e26afc1918 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -168,6 +168,9 @@ struct VulkanDeviceInfo { bool occlusion_query_precise = false; bool prepare_on_bind = false; bool cold_graphics_compile = false; // Driver supports a cache-only create and reports when compilation is pending. + // pipelineCreationCacheControl is on for the heavy pipeline cache (src/heavy_pipeline_cache.h): a pipeline the + // offline cache does not have is created against the cache of pipeline_cache.heavy.bin, written back as it grows. + bool heavy_pipeline_cache = false; bool pipeline_statistics_query = false; bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e8676b32c7..7511d2617d 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -47,6 +47,7 @@ #include "../src/pipeline_cache_file.h" #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" +#include "../src/heavy_pipeline_cache.h" #include "../src/pipeline_cache_store.h" #include "../src/pipeline_cache_journal.h" #include "../src/large_module_gate.h" @@ -1387,6 +1388,30 @@ std::filesystem::path pipeline_cache_session_path() { return path; } +// The pipelines the offline seed does not have, kept next to it and written while the game runs +// (src/heavy_pipeline_cache.h). +std::filesystem::path pipeline_cache_heavy_path() { + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"pipeline_cache.heavy.bin"); + return path; +} + +// LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write of the heavy cache; 0 turns the +// heavy cache off. One line for a value that is not a number. +std::uint32_t heavy_pipeline_cache_ms() { + static const std::uint32_t ms = [] { + char text[32] = {}; + size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_HEAVY_PIPELINE_CACHE_MS") == 0 && length > 1; + const auto threshold = leonida::heavy_pipeline_cache::parse_threshold(present ? text : ""); + if (!threshold.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_HEAVY_PIPELINE_CACHE_MS=%s is not a number of milliseconds; " + "using %u\n", text, threshold.ms); + return threshold.ms; + }(); + return ms; +} + std::size_t pipeline_cache_save_limit(); // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): where each compute pipeline's own cache file goes, beside @@ -1664,6 +1689,66 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result)); } +// The heavy cache, seeded from pipeline_cache.heavy.bin when it is there and made for this device; empty otherwise. +VkPipelineCache create_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, + const leonida::cached_pso::Identity& identity) { + const auto path = pipeline_cache_heavy_path(); + clean_stale_cache_files(path); + VkPipelineCache cache = VK_NULL_HANDLE; + { + const PipelineCacheSeed seed(path); + if (seed.data() && seed.compatible(identity)) { + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, + seed.size(), seed.data()}; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) == VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: loaded %zu bytes from pipeline_cache.heavy.bin\n", seed.size()); + return cache; + } + std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.heavy.bin; starting it empty\n"); + } else if (seed.data()) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin does not match this Vulkan device; starting " + "it empty\n"); + } + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &cache) != VK_SUCCESS) return VK_NULL_HANDLE; + return cache; +} + +// Writes the heavy cache whole: a staging file renamed over pipeline_cache.heavy.bin, so the file on disk is always +// a complete blob. It only holds what the offline seed missed, so it has no size limit of its own. +bool save_heavy_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, + std::uint64_t compiles, std::uint64_t hits) { + if (!cache || !vk.vkGetPipelineCacheData) return false; + const auto path = pipeline_cache_heavy_path(); + if (path.empty()) return false; + const auto start = compile_us(); + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || + size <= sizeof(VkPipelineCacheHeaderVersionOne)) + return false; + CacheStagingFile staging(path, size); + if (!staging.data) { + std::fprintf(stderr, "[rt] d3d12: could not map a staging file for %zu heavy pipeline cache bytes\n", size); + return false; + } + auto written = size; + const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data); + // VK_INCOMPLETE means the cache grew after the size query and the blob is a truncated snapshot; it must not + // replace a complete file. The writer tries again later with a fresh size. + const bool ok = result == VK_SUCCESS && written > sizeof(VkPipelineCacheHeaderVersionOne) && written <= size && + staging.publish(path, written); + if (ok) + std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.heavy.bin in %.1f s (%llu slow builds " + "and %llu other builds past the offline cache so far)\n", + written, double(compile_us() - start) / 1e6, static_cast(compiles), + static_cast(hits)); + else + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.heavy.bin not written (%d); the previous file is kept\n", + int(result)); + return ok; +} + // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own), unless the translator's // partition-invariance tier says otherwise. Logged once per stage with the first shader's name, then again at 10, 100, @@ -2299,6 +2384,105 @@ struct DeviceState { return pipeline_cache_handle; } + // The heavy pipeline cache (src/heavy_pipeline_cache.h) and the thread that writes it. + std::once_flag heavy_cache_once; + VkPipelineCache heavy_cache_handle = VK_NULL_HANDLE; + std::mutex heavy_mutex; + std::condition_variable heavy_wake; + leonida::heavy_pipeline_cache::WriteSchedule heavy_schedule; // under heavy_mutex + bool heavy_stop = false; // under heavy_mutex + std::thread heavy_writer; // started at the first slow build + std::atomic heavy_compiles{0}, heavy_hits{0}; + std::atomic heavy_changed{false}; // a build went into the heavy cache since it was loaded + + VkPipelineCache heavy_cache() { + std::call_once(heavy_cache_once, [this] { + if (context->vk.vkCreatePipelineCache) + heavy_cache_handle = create_heavy_pipeline_cache(context->vk, info.device, pso_identity); + }); + return heavy_cache_handle; + } + + // A build past the offline cache took `took_ms`: a slow one schedules a write. + void note_heavy_build(ULONGLONG took_ms) { + heavy_changed = true; + if (took_ms < heavy_pipeline_cache_ms()) { + ++heavy_hits; + return; + } + ++heavy_compiles; + std::lock_guard lock(heavy_mutex); + if (heavy_stop) return; + heavy_schedule.note_heavy(GetTickCount64()); + if (!heavy_writer.joinable()) { + try { + heavy_writer = std::thread([this] { write_heavy_cache_loop(); }); + } catch (const std::exception&) { + return; // no thread: the cache is still written at teardown + } + } + heavy_wake.notify_one(); + } + + void write_heavy_cache_loop() { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + std::unique_lock lock(heavy_mutex); + while (!heavy_stop) { + if (!heavy_schedule.dirty()) { + heavy_wake.wait(lock); + continue; + } + const std::uint64_t now = GetTickCount64(); + if (!heavy_schedule.due(now)) { + heavy_wake.wait_for(lock, std::chrono::milliseconds(heavy_schedule.due_ms() - now)); + continue; + } + const std::uint64_t generation = heavy_schedule.generation(); + lock.unlock(); + const bool saved = save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, + heavy_compiles.load(), heavy_hits.load()); + lock.lock(); + // A failed write leaves the cache dirty: it is tried again after a growing delay, not only at teardown. + if (saved) heavy_schedule.written(generation, now); + else heavy_schedule.failed(now); + } + } + + // At device teardown, with no build running: stop the writer and write the cache if any build went into it. + // Fast builds never schedule a write, so this is where they are kept: without an offline seed every build is + // a miss, and these are the builds pipeline_cache.session.bin used to keep. + void finish_heavy_cache() { + { + std::lock_guard lock(heavy_mutex); + heavy_stop = true; + } + heavy_wake.notify_all(); + if (heavy_writer.joinable()) heavy_writer.join(); + if (!heavy_cache_handle) return; + if (heavy_changed.load() && !active_compiles.load()) + save_heavy_pipeline_cache(context->vk, info.device, heavy_cache_handle, heavy_compiles.load(), + heavy_hits.load()); + context->vk.vkDestroyPipelineCache(info.device, heavy_cache_handle, nullptr); + heavy_cache_handle = VK_NULL_HANDLE; + } + + // vkCreateGraphicsPipelines through `create(cache, flags)` (compute pipelines have their journal). With the heavy + // cache, the offline cache is asked first without compiling; a pipeline it does not have is built against the heavy + // cache, which a slow build then writes back to disk. A caller that already asked for a cache-only create keeps it. + template + VkResult create_pipeline(VkPipelineCreateFlags flags, Create&& create) { + constexpr VkPipelineCreateFlags cache_only = VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT; + const VkPipelineCache corpus = pipeline_cache(); + if (!info.heavy_pipeline_cache || (flags & cache_only)) return create(corpus, flags); + const VkResult cached = create(corpus, flags | cache_only); + if (cached != VK_PIPELINE_COMPILE_REQUIRED) return cached; + const VkPipelineCache heavy = heavy_cache(); + const ULONGLONG started = GetTickCount64(); + const VkResult built = create(heavy ? heavy : corpus, flags); + if (built == VK_SUCCESS && heavy) note_heavy_build(GetTickCount64() - started); + return built; + } + QueueClock clock; // device-wide calibration entry points std::vector timestamp_bits; @@ -12002,7 +12186,11 @@ class PipelineState final const leonida::dev_status::Build dev_build(r.mesh ? "mesh pipeline" : "graphics pipeline"); const leonida::pipeline_profile::DriverCall profile(r.mesh ? "ms" : "vs", lazy_ ? "lazy" : "eager", program, fragment, unbound); - const auto result = device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, cache, 1, &info, nullptr, &pipeline); + const auto result = device_.create_pipeline(flags, [&](VkPipelineCache with, VkPipelineCreateFlags f) { + info.flags = f; + pipeline = VK_NULL_HANDLE; + return device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, with, 1, &info, nullptr, &pipeline); + }); if (status) *status = result; profile.finish(int(result)); trace.end(trigger, profile_shaders_.c_str(), unbound, bytes, result); @@ -14310,6 +14498,7 @@ class Device final vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } + state_.finish_heavy_cache(); if (state_.pipeline_cache_handle) { // Nothing should be building into the cache now (the compiler's jobs for this device are gone, and so // is every PSO). If something is, its pipelines are half in the cache: keep the previous session file. @@ -20794,8 +20983,12 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin v13.compute_full_subgroups, info.subgroup); const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); const auto mode = compile_mode ? std::string_view(compile_mode) : std::string_view{}; - v13.enable_pipeline_cache_control = mode == "cache-only" && v13.core && v13.pipeline_cache_control; - info.cold_graphics_compile = v13.enable_pipeline_cache_control; + // pipelineCreationCacheControl: for LEONIDA_PIPELINE_COMPILE=cache-only, and for the heavy pipeline cache unless + // LEONIDA_HEAVY_PIPELINE_CACHE_MS=0 turns it off. + v13.enable_pipeline_cache_control = + (mode == "cache-only" || heavy_pipeline_cache_ms()) && v13.core && v13.pipeline_cache_control; + info.cold_graphics_compile = mode == "cache-only" && v13.enable_pipeline_cache_control; + info.heavy_pipeline_cache = heavy_pipeline_cache_ms() && v13.enable_pipeline_cache_control; info.prepare_on_bind = mode == "on-demand"; void* v13_chain = v13.enable(ext_chain); // D3D-78 uses the core robustness and format-feature flags. Leave the Vulkan 1.2 extension path unchanged. diff --git a/runtime/src/heavy_pipeline_cache.h b/runtime/src/heavy_pipeline_cache.h new file mode 100644 index 0000000000..8cad10e660 --- /dev/null +++ b/runtime/src/heavy_pipeline_cache.h @@ -0,0 +1,94 @@ +// A pipeline cache that survives a crash, for the pipelines the offline corpus does not have (RT-HEAVY-PIPELINE-CACHE). +// +// The offline seed (pipeline_cache.bin, several GiB) covers what the `pipelines` build stage creates. A pipeline it +// misses is compiled on the spot, and some of those take the driver seconds each. pipeline_cache.session.bin cannot +// keep them across a crash: it is written at device teardown only, and a cache seeded from the corpus returns the +// whole corpus, over its write limit, so it is not written at all. +// +// So a pipeline is first created against the corpus cache with VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED. +// When the driver would have to compile, it is created again against a cache of its own, seeded from +// pipeline_cache.heavy.bin. That cache holds only the corpus's misses, so it stays small. After a compile that took +// at least LEONIDA_HEAVY_PIPELINE_CACHE_MS (default 500 ms), it is written back to disk on a thread of its own: a +// staging file renamed over the old one, so a crash at any point leaves the last complete file. +// +// This header holds the pure decisions (the threshold and when to write). Vulkan and the file live in the device. +#pragma once + +#include +#include + +namespace leonida::heavy_pipeline_cache { + +inline constexpr std::uint32_t default_threshold_ms = 500; + +struct Threshold { + std::uint32_t ms = default_threshold_ms; // 0: off + bool valid = true; // false: the text was not a number; ms stays the default +}; + +// LEONIDA_HEAVY_PIPELINE_CACHE_MS: a compile at least this long schedules a write; 0 turns the heavy cache off. +inline Threshold parse_threshold(const char* text) { + if (!text || !*text) return {}; + std::uint64_t value = 0; + for (const char* p = text; *p; ++p) { + if (*p < '0' || *p > '9') return {default_threshold_ms, false}; + value = value * 10 + std::uint64_t(*p - '0'); + if (value > 3'600'000) return {default_threshold_ms, false}; // an hour: past it the text is a mistake + } + return {std::uint32_t(value), true}; +} + +// When the writer thread writes. A heavy compile marks the cache dirty; the write waits `settle_ms` after the +// newest one (heavy compiles come in bursts at a load, and each write copies the whole heavy cache) but never more +// than `max_delay_ms` after the first unwritten one, so a long burst is still saved as it goes. A write that fails +// keeps the cache dirty and is tried again `retry_ms` later, the delay doubling with each failure in a row up to +// `max_retry_ms`, so a disk that stays full or a driver that keeps failing does not make the writer spin. +class WriteSchedule { +public: + static constexpr std::uint64_t settle_ms = 3000; + static constexpr std::uint64_t max_delay_ms = 20000; + static constexpr std::uint64_t retry_ms = 5000; + static constexpr std::uint64_t max_retry_ms = 120000; + + void note_heavy(std::uint64_t now_ms) { + if (!dirty_) first_ = now_ms; + dirty_ = true; + last_ = now_ms; + ++generation_; + } + bool dirty() const { return dirty_; } + // The time to write at; only meaningful while dirty. + std::uint64_t due_ms() const { + const std::uint64_t settled = last_ + settle_ms, latest = first_ + max_delay_ms; + const std::uint64_t at = settled < latest ? settled : latest; + return at > retry_at_ ? at : retry_at_; + } + bool due(std::uint64_t now_ms) const { return dirty_ && now_ms >= due_ms(); } + // Taken when a write starts; the write covers every heavy compile noted up to then. + std::uint64_t generation() const { return generation_; } + // A write that started at `generation` and `started_ms` is done. A heavy compile noted after it started, even in + // the same millisecond tick, keeps the cache dirty for the next write, due as if it were first noted then. + void written(std::uint64_t generation, std::uint64_t started_ms) { + failures_ = 0; + retry_at_ = 0; + if (generation_ == generation) dirty_ = false; + else first_ = started_ms; + } + // A write that started at `started_ms` failed: the cache stays dirty and the next try waits out the backoff. + void failed(std::uint64_t started_ms) { + std::uint64_t delay = retry_ms; + for (std::uint32_t i = 0; i < failures_ && delay < max_retry_ms; ++i) delay *= 2; + if (delay > max_retry_ms) delay = max_retry_ms; + if (failures_ < 64) ++failures_; + retry_at_ = started_ms + delay; + } + std::uint32_t failures() const { return failures_; } + +private: + bool dirty_ = false; + std::uint64_t first_ = 0, last_ = 0, generation_ = 0; + std::uint32_t failures_ = 0; // failed writes in a row + std::uint64_t retry_at_ = 0; // no write before this time after a failure +}; + +} // namespace leonida::heavy_pipeline_cache diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index 775cfeb581..14f30d3a60 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -150,6 +150,7 @@ int main(int argc, char** argv) { rt::d3d12::VulkanDeviceInfo info{}; info.prepare_on_bind=d.prepare_on_bind; info.cold_graphics_compile=d.cold_graphics_compile; + info.heavy_pipeline_cache=d.heavy_pipeline_cache; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 5601102409..b45cc2c841 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -193,6 +193,7 @@ int main(int argc, char** argv) { rt::d3d12::VulkanDeviceInfo info{}; info.prepare_on_bind=d.prepare_on_bind; info.cold_graphics_compile=d.cold_graphics_compile; + info.heavy_pipeline_cache=d.heavy_pipeline_cache; info.get_instance_proc = d.instance_proc; info.instance = d.instance; info.physical = d.physical; diff --git a/runtime/test/heavy_pipeline_cache_test.cpp b/runtime/test/heavy_pipeline_cache_test.cpp new file mode 100644 index 0000000000..8181a047cd --- /dev/null +++ b/runtime/test/heavy_pipeline_cache_test.cpp @@ -0,0 +1,109 @@ +// src/heavy_pipeline_cache.h: the LEONIDA_HEAVY_PIPELINE_CACHE_MS threshold and when the heavy cache is written. +// No Vulkan, no GPU, no files. +#include "../src/heavy_pipeline_cache.h" + +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace heavy = leonida::heavy_pipeline_cache; + +static int test_threshold() { + CHECK(heavy::parse_threshold(nullptr).ms == heavy::default_threshold_ms); + CHECK(heavy::parse_threshold("").ms == heavy::default_threshold_ms); + CHECK(heavy::parse_threshold("0").ms == 0 && heavy::parse_threshold("0").valid); // off + CHECK(heavy::parse_threshold("2000").ms == 2000); + CHECK(heavy::parse_threshold("0750").ms == 750); + // Not a number, a sign, a unit or an absurd value: the default, reported as invalid. + for (const char* bad : {"-1", "+5", "1s", "1.5", "abc", "3600001", "99999999999999999999"}) { + const auto t = heavy::parse_threshold(bad); + CHECK(!t.valid && t.ms == heavy::default_threshold_ms); + } + CHECK(heavy::parse_threshold("3600000").valid); + return 0; +} + +static int test_schedule() { + using S = heavy::WriteSchedule; + S s; + CHECK(!s.dirty() && !s.due(1'000'000)); + // One heavy compile: written once it has settled. + s.note_heavy(1000); + CHECK(s.dirty() && !s.due(1000 + S::settle_ms - 1) && s.due(1000 + S::settle_ms)); + s.written(s.generation(), 1000 + S::settle_ms); + CHECK(!s.dirty()); + // A burst, one compile a second for a minute: the write does not wait for the burst to end. + S burst; + for (std::uint64_t t = 10'000; t <= 70'000; t += 1000) { + burst.note_heavy(t); + if (burst.due(t)) { + CHECK(t - 10'000 >= S::max_delay_ms); // first write no later than max_delay after the first compile + burst.written(burst.generation(), t); + break; + } + } + CHECK(!burst.dirty()); + // A compile that finishes while a write is running is not lost: the cache stays dirty for the next write. + S racing; + racing.note_heavy(5000); + const std::uint64_t start = 5000 + S::settle_ms; + const std::uint64_t taken = racing.generation(); + racing.note_heavy(start + 10); // during the write + racing.written(taken, start); + CHECK(racing.dirty()); + CHECK(racing.due(start + 10 + S::settle_ms)); + // The same, inside one tick of a coarse clock: the compile noted at the write's own start time is still kept. + S tick; + tick.note_heavy(9000); + const std::uint64_t at = 9000 + S::settle_ms; + const std::uint64_t before = tick.generation(); + tick.note_heavy(at); + tick.written(before, at); + CHECK(tick.dirty()); + return 0; +} + +static int test_failed_write() { + using S = heavy::WriteSchedule; + S s; + s.note_heavy(1000); + std::uint64_t now = 1000 + S::settle_ms; + CHECK(s.due(now)); + // A failed write keeps the cache dirty and waits out the backoff before the next try. + s.failed(now); + CHECK(s.dirty() && s.failures() == 1); + CHECK(!s.due(now) && !s.due(now + S::retry_ms - 1) && s.due(now + S::retry_ms)); + // Failures in a row double the delay up to the cap, so a write that keeps failing does not spin. + std::uint64_t expect = S::retry_ms; + for (int i = 0; i < 12; ++i) { + now = s.due_ms(); + s.failed(now); + expect = expect * 2 > S::max_retry_ms ? S::max_retry_ms : expect * 2; + CHECK(s.due_ms() == now + expect); + } + CHECK(s.due_ms() - now == S::max_retry_ms); + // A heavy compile during the backoff does not bring the retry forward. + s.note_heavy(now + 1); + CHECK(!s.due(now + S::settle_ms + 1) && s.due(now + S::max_retry_ms)); + // A successful write clears the dirty flag and the backoff. + now = s.due_ms(); + s.written(s.generation(), now); + CHECK(!s.dirty() && s.failures() == 0); + s.note_heavy(now + 10); + CHECK(s.due(now + 10 + S::settle_ms)); + return 0; +} + +int main() { + if (const int r = test_threshold()) return r; + if (const int r = test_schedule()) return r; + if (const int r = test_failed_write()) return r; + std::printf("heavy_pipeline_cache: threshold parsing, the write schedule and retries after a failed write\n"); + return 0; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index e561f72889..d6fa80dedc 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -123,6 +123,7 @@ class Device { bool occlusion_query_precise = false; // occlusionQueryPrecise enabled bool prepare_on_bind=false; bool cold_graphics_compile = false; + bool heavy_pipeline_cache = false; // LEONIDA_HEAVY_PIPELINE_CACHE_MS set and pipelineCreationCacheControl on bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled bool request_multi_draw_indirect = false, request_draw_indirect_count = false; bool draw_indirect_count_enabled = false; @@ -410,8 +411,13 @@ class Device { // (zero-based VS ids) is in; harmless before. const char* compile_mode = std::getenv("LEONIDA_PIPELINE_COMPILE"); const bool cache_only = compile_mode && std::strcmp(compile_mode, "cache-only") == 0; - v13_.enable_pipeline_cache_control = cache_only && v13_.core && v13_.pipeline_cache_control; - cold_graphics_compile = v13_.enable_pipeline_cache_control; + // LEONIDA_HEAVY_PIPELINE_CACHE_MS other than 0: the heavy pipeline cache path, as the runtime takes it by default + // (src/heavy_pipeline_cache.h). Tests leave it off unless asked. + const char* heavy_ms = std::getenv("LEONIDA_HEAVY_PIPELINE_CACHE_MS"); + const bool heavy = heavy_ms && *heavy_ms && std::strcmp(heavy_ms, "0") != 0; + v13_.enable_pipeline_cache_control = (cache_only || heavy) && v13_.core && v13_.pipeline_cache_control; + cold_graphics_compile = cache_only && v13_.enable_pipeline_cache_control; + heavy_pipeline_cache = heavy && v13_.enable_pipeline_cache_control; prepare_on_bind = compile_mode && std::strcmp(compile_mode, "on-demand") == 0; VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, v13_.enable(conditional_rendering ? &enable_conditional : nullptr)};