Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<part of a name>[,<part>...]` (`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.
Expand Down
8 changes: 8 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
3 changes: 3 additions & 0 deletions runtime/shims/d3d12_com.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
199 changes: 196 additions & 3 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<unsigned long long>(compiles),
static_cast<unsigned long long>(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,
Expand Down Expand Up @@ -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<std::uint64_t> heavy_compiles{0}, heavy_hits{0};
std::atomic<bool> 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 <class Create>
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<std::uint32_t> timestamp_bits;

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading