Skip to content
Open
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
5 changes: 3 additions & 2 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -2363,8 +2363,9 @@ Pipeline creation:
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.
`LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` also schedules a snapshot after a successful pipeline build,
at most once per 120 seconds. It starts on the compile worker when queued builds have drained and the device
has no active builds. These snapshots have an additional 512 MiB ceiling. The driver fills a mapped staging
starting 30 seconds after device creation and at most once per 30 seconds after a save. It queues on the
compile worker at priority 1 (behind priority-0 awaited first-use builds and ahead of speculative warm-up),
yielding only when a priority-0 build is queued (retrying after 5 seconds). These snapshots have an additional 512 MiB ceiling. The driver fills a mapped staging
file directly. A successful snapshot atomically replaces the session. An interrupted write preserves the
previous cache; the next launch removes unheld staging files older than ten minutes.
`LEONIDA_TRACE_PIPELINE_COMPILE=1` records each graphics and compute build's trigger, thread, elapsed time,
Expand Down
15 changes: 13 additions & 2 deletions runtime/shims/d3d12_pipeline_checkpoint.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,19 @@
namespace rt::d3d12 {
struct CompileActivity {
std::atomic<unsigned>& count;
explicit CompileActivity(std::atomic<unsigned>& active) : count(active) { ++count; }
~CompileActivity() { --count; }
bool active = true;
explicit CompileActivity(std::atomic<unsigned>& c) : count(c) {
count.fetch_add(1, std::memory_order_acq_rel);
}
void finish() {
if (active) {
count.fetch_sub(1, std::memory_order_acq_rel);
active = false;
}
}
~CompileActivity() { finish(); }
CompileActivity(const CompileActivity&) = delete;
CompileActivity& operator=(const CompileActivity&) = delete;
};

inline bool direct_session_cache() {
Expand Down
4 changes: 3 additions & 1 deletion runtime/shims/d3d12_pipeline_compile.h
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,11 @@ class PipelineCompiler {
return closed_;
}

// Priority 0 is an awaited first-use draw/dispatch build; priority 1 is a cache checkpoint; higher priorities are
// speculative compute warm-up builds (keyed by SPIR-V byte size). Only priority-0 waiters preempt a checkpoint.
bool has_compile_waiter() {
std::lock_guard lock(mutex_);
return !jobs_.empty() && jobs_.begin()->first != SIZE_MAX;
return !jobs_.empty() && jobs_.begin()->first == 0;
}
// Returns when no job is queued or running. A job owns its pipeline state, and through it the device, until it
// finishes; a caller that counts references (rt::d3d12_xs::device_proxy_ref_count) waits here first.
Expand Down
64 changes: 38 additions & 26 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1420,30 +1420,32 @@ bool startup_cache_checkpoints_enabled() {
}

// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write.
void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache,
bool checkpoint = false) {
if (!cache || !vk.vkGetPipelineCacheData) return;
leonida::pipeline_cache_store::CheckpointOutcome save_session_pipeline_cache(
const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, bool checkpoint = false) {
using leonida::pipeline_cache_store::CheckpointOutcome;
if (!cache || !vk.vkGetPipelineCacheData) return CheckpointOutcome::skipped;
auto limit = pipeline_cache_save_limit();
// The output is an opaque Vulkan blob. A prefix is not an incremental cache.
if (checkpoint) limit = (std::min)(limit, std::size_t{512} << 20);
if (!limit) return;
if (!limit) return CheckpointOutcome::skipped;
const auto start = compile_us();
std::size_t size = 0;
if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS ||
size <= sizeof(VkPipelineCacheHeaderVersionOne)) return;
size <= sizeof(VkPipelineCacheHeaderVersionOne))
return CheckpointOutcome::skipped;
if (size > limit) {
std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes, over the %zu-byte write limit\n", size, limit);
return;
return CheckpointOutcome::skipped;
}
const auto queried = compile_us();
// A size query can itself serialize the driver cache. Let newly queued work run first.
if (checkpoint && PipelineCompiler::instance().has_compile_waiter()) return;
// Yield only if a priority-0 awaited draw/dispatch build arrived while querying cache size.
if (checkpoint && PipelineCompiler::instance().has_compile_waiter()) return CheckpointOutcome::deferred;
const auto path = pipeline_cache_session_path();
if (path.empty()) return;
if (path.empty()) return CheckpointOutcome::skipped;
CacheStagingFile staging(path, size);
if (!staging.data) {
std::fprintf(stderr, "[rt] d3d12: could not map staging file for %zu pipeline cache bytes\n", size);
return;
return CheckpointOutcome::skipped;
}
auto written = size;
const auto result = vk.vkGetPipelineCacheData(device, cache, &written, staging.data);
Expand All @@ -1456,6 +1458,7 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev
compile_us()-filled, int(ok), int(result));
if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written);
else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result));
return ok ? CheckpointOutcome::saved : CheckpointOutcome::skipped;
}

// A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or,
Expand Down Expand Up @@ -1961,7 +1964,8 @@ struct DeviceState {
leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against
std::once_flag pipeline_cache_once;
VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE;
std::atomic<ULONGLONG> next_checkpoint{GetTickCount64() + 120000};
leonida::pipeline_cache_store::CheckpointSchedule checkpoint_schedule{
GetTickCount64() + leonida::pipeline_cache_store::default_checkpoint_interval_ms};
std::atomic<unsigned> active_compiles{0};

VkPipelineCache pipeline_cache() {
Expand Down Expand Up @@ -9079,7 +9083,7 @@ class PipelineState final
// failure is logged and not retried.
VkPipeline build_compute(const char* trigger) {
CompileActivity activity(device_.active_compiles);
std::lock_guard lock(variants_mutex_);
std::unique_lock lock(variants_mutex_);
if (pipeline_.pipeline || compute_failed_) return pipeline_.pipeline;
compute_failed_ = true; // until the pipeline exists
auto& vk = device_.context->vk;
Expand Down Expand Up @@ -9134,9 +9138,11 @@ class PipelineState final
if (took >= 2000)
std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n",
entry->name.c_str(), double(took) / 1000.0, bytes);
maybe_checkpoint(cache);
pipeline_.pipeline = built;
compute_failed_ = false;
lock.unlock();
activity.finish();
maybe_checkpoint(cache);
return built;
}

Expand All @@ -9147,24 +9153,29 @@ class PipelineState final
// The startup cache checkpoint is the device's job, not this PSO's: ~Device cancels it before the cache goes.
void maybe_checkpoint(VkPipelineCache cache) {
if (!cache || !startup_cache_checkpoints_enabled()) return;
auto now = GetTickCount64();
auto next = device_.next_checkpoint.load();
if (now < next || !device_.next_checkpoint.compare_exchange_strong(next, ULLONG_MAX)) return;
using leonida::pipeline_cache_store::CheckpointOutcome;
const auto now = GetTickCount64();
if (!device_.checkpoint_schedule.try_claim(now)) return;
DeviceState* const state = &device_;
bool queued = false;
try {
queued = PipelineCompiler::instance().submit(state, state, SIZE_MAX, [state, cache] {
try {
if (!state->active_compiles.load() && !PipelineCompiler::instance().has_compile_waiter())
save_session_pipeline_cache(state->context->vk, state->info.device, cache, true);
} catch (const std::exception& e) {
std::fprintf(stderr, "[rt] pipeline cache checkpoint failed: %s\n", e.what());
}
state->next_checkpoint.store(GetTickCount64() + 120000);
});
queued = PipelineCompiler::instance().submit(
state, state, leonida::pipeline_cache_store::checkpoint_priority, [state, cache] {
CheckpointOutcome outcome = CheckpointOutcome::deferred;
try {
if (!PipelineCompiler::instance().has_compile_waiter()) {
outcome = save_session_pipeline_cache(state->context->vk, state->info.device, cache, true);
}
} catch (const std::exception& e) {
outcome = CheckpointOutcome::skipped;
std::fprintf(stderr, "[rt] pipeline cache checkpoint failed: %s\n", e.what());
}
state->checkpoint_schedule.complete(GetTickCount64(), outcome);
});
} catch (...) {
}
if (!queued) device_.next_checkpoint.store(now + 120000); // refused after an exit stop, or out of memory
// Refused after an exit stop, or out of memory.
if (!queued) device_.checkpoint_schedule.complete(now, CheckpointOutcome::skipped);
}

VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0) {
Expand Down Expand Up @@ -9439,6 +9450,7 @@ class PipelineState final
pipeline = VK_NULL_HANDLE;
}
drop_modules();
activity.finish();
if (pipeline) maybe_checkpoint(cache);
return pipeline;
}
Expand Down
57 changes: 57 additions & 0 deletions runtime/src/pipeline_cache_store.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// part of Vulkan's ABI, not something a driver chooses.
#pragma once

#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstring>
Expand Down Expand Up @@ -66,4 +67,60 @@ inline bool header_matches(const void* data, std::size_t size, const cached_pso:
std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0;
}

inline constexpr std::uint64_t default_checkpoint_interval_ms = 30000;
inline constexpr std::uint64_t default_checkpoint_retry_ms = 5000;
inline constexpr std::size_t checkpoint_priority = 1; // behind priority-0 awaited builds, ahead of warm-up (SPIR-V bytes)

enum class CheckpointOutcome : std::uint8_t {
saved, // snapshot written; wait interval_ms before the next checkpoint
deferred, // yielded to a priority-0 awaited build; retry after retry_ms
skipped, // empty cache, over size cap, or I/O failure; wait interval_ms before retrying
};

// Coalesces startup pipeline-cache checkpoint scheduling across compiling threads.
// At most one checkpoint runs at a time; a deferred checkpoint backs off briefly (retry_ms) instead of burning the
// full cooldown interval.
class CheckpointSchedule {
public:
explicit CheckpointSchedule(std::uint64_t initial_due_ms,
std::uint64_t interval_ms = default_checkpoint_interval_ms,
std::uint64_t retry_ms = default_checkpoint_retry_ms)
: next_due_ms_(clamp_due(initial_due_ms)), interval_ms_(interval_ms), retry_ms_(retry_ms) {}

bool try_claim(std::uint64_t now_ms) {
std::uint64_t expected = next_due_ms_.load(std::memory_order_acquire);
while (expected != in_flight && now_ms >= expected) {
if (next_due_ms_.compare_exchange_weak(expected, in_flight, std::memory_order_acq_rel,
std::memory_order_acquire)) {
return true;
}
}
return false;
}

void complete(std::uint64_t now_ms, CheckpointOutcome outcome) {
const std::uint64_t wait = outcome == CheckpointOutcome::deferred ? retry_ms_ : interval_ms_;
next_due_ms_.store(saturate_add(now_ms, wait), std::memory_order_release);
}

void abort_claim(std::uint64_t now_ms) {
next_due_ms_.store(saturate_add(now_ms, retry_ms_), std::memory_order_release);
}

std::uint64_t next_due_ms() const { return next_due_ms_.load(std::memory_order_acquire); }
bool in_progress() const { return next_due_ms_.load(std::memory_order_acquire) == in_flight; }

private:
static constexpr std::uint64_t in_flight = (std::numeric_limits<std::uint64_t>::max)();
static constexpr std::uint64_t max_due = in_flight - 1;
static std::uint64_t clamp_due(std::uint64_t t) { return t > max_due ? max_due : t; }
static std::uint64_t saturate_add(std::uint64_t a, std::uint64_t b) {
return a > max_due - b ? max_due : a + b;
}

std::atomic<std::uint64_t> next_due_ms_;
std::uint64_t interval_ms_;
std::uint64_t retry_ms_;
};

} // namespace leonida::pipeline_cache_store
59 changes: 58 additions & 1 deletion runtime/test/pipeline_cache_store_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,64 @@ static int test_header() {
return 0;
}

static int test_checkpoint_schedule() {
using store::CheckpointOutcome;
using store::CheckpointSchedule;

CHECK(store::default_checkpoint_interval_ms == 30000);
CHECK(store::default_checkpoint_retry_ms == 5000);
CHECK(store::checkpoint_priority == 1);

CheckpointSchedule schedule(30000);
CHECK(!schedule.in_progress());
CHECK(!schedule.try_claim(0));
CHECK(!schedule.try_claim(29999));

// At the due time, one caller claims the slot; concurrent callers see in_progress and are coalesced.
CHECK(schedule.try_claim(30000));
CHECK(schedule.in_progress());
CHECK(!schedule.try_claim(30000));
CHECK(!schedule.try_claim(90000));

// A deferred checkpoint (priority-0 awaited build queued) retries after retry_ms (5 s) rather than burning the
// full 30 s cooldown.
schedule.complete(30050, CheckpointOutcome::deferred);
CHECK(!schedule.in_progress());
CHECK(schedule.next_due_ms() == 35050);
CHECK(!schedule.try_claim(35049));
CHECK(schedule.try_claim(35050));

// Queue failure (abort_claim) also retries after retry_ms.
schedule.abort_claim(35060);
CHECK(!schedule.in_progress());
CHECK(schedule.next_due_ms() == 40060);
CHECK(!schedule.try_claim(40059));
CHECK(schedule.try_claim(40060));

// A saved snapshot advances the deadline by interval_ms (30 s).
schedule.complete(41000, CheckpointOutcome::saved);
CHECK(!schedule.in_progress());
CHECK(schedule.next_due_ms() == 71000);
CHECK(!schedule.try_claim(70999));
CHECK(schedule.try_claim(71000));

// A skipped snapshot (empty cache, over limit, or I/O error) backs off by interval_ms so disk is not hammered.
schedule.complete(71010, CheckpointOutcome::skipped);
CHECK(schedule.next_due_ms() == 101010);
CHECK(!schedule.try_claim(101009));

// Near-UINT64_MAX timestamps saturate below the in_flight sentinel rather than wrapping or sticking in_flight.
const std::uint64_t near_max = (std::numeric_limits<std::uint64_t>::max)() - 10;
CheckpointSchedule hi(near_max);
CHECK(hi.try_claim(near_max));
hi.complete(near_max, CheckpointOutcome::saved);
CHECK(!hi.in_progress());
CHECK(hi.next_due_ms() == (std::numeric_limits<std::uint64_t>::max)() - 1);
return 0;
}

int main() {
if (const int failed = test_limit()) return failed;
return test_header();
if (const int failed = test_header()) return failed;
return test_checkpoint_schedule();
}
Loading