From 1d7c662b4bf2870d600da56452d53fbaff295a52 Mon Sep 17 00:00:00 2001 From: OreoFR <29048345+OreoFR@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:24:49 +0100 Subject: [PATCH 1/2] compile gate: `auto` default, calibrated at device creation With LEONIDA_COMPILE_GATE unset or `auto`, the device measures the driver once before the VulkanContext exists: a worker creates a synthetic compute pipeline (SPIR-V written in code, new specialization seed each run, no pipeline cache) while the queue gets empty submissions waited on a fence. Quick submissions with the create still in the driver give the adaptive gate; a held one, a create too fast to tell, an unexplained slow submission or any failure give classic. The verdict is cached per vendor/device/driver/pipelineCacheUUID in compile_gate_calibration.txt beside the pipeline cache; LEONIDA_COMPILE_GATE_RECALIBRATE=1 measures again. Only the title process calibrates; build hosts and tests keep classic. `classic`, `adaptive`, `1`, `0` still force a mode. Tests: compile_gate_policy_test (no GPU: settings, NVIDIA version decode, verdicts, cache file, SPIR-V shape) and vk_compile_gate_calibration_test (GPU: a verdict within 20 s, adaptive on NVIDIA 621.40). Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 38 +- runtime/CMakeLists.txt | 21 + runtime/README.md | 7 +- runtime/shims/d3d12_vulkan_device.cpp | 98 ++++ runtime/src/compile_gate_calibration.h | 234 ++++++++ runtime/src/compile_gate_policy.h | 524 ++++++++++++++++++ runtime/src/main.cpp | 4 + runtime/src/vulkan_device_fault.h | 144 +++-- runtime/test/compile_gate_policy_test.cpp | 235 ++++++++ .../test/vk_compile_gate_calibration_test.cpp | 71 +++ 10 files changed, 1320 insertions(+), 56 deletions(-) create mode 100644 runtime/src/compile_gate_calibration.h create mode 100644 runtime/src/compile_gate_policy.h create mode 100644 runtime/test/compile_gate_policy_test.cpp create mode 100644 runtime/test/vk_compile_gate_calibration_test.cpp diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index a368c77b48..bc32c505ad 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2899,10 +2899,12 @@ submitting thread; at the maintainers' decision it was replaced by this one when title submits (a submission in the last second, `src/pipeline_wait.h`); the pipeline is built at its first use instead. Opt-in: unset or 0, every warm-up runs, as on `main`, and `LargeModuleGate` (#1889) orders them behind a submission's compiles. Smaller warm-ups, and every warm-up before the first submission, run as before. -- **A bounded, adaptive compile gate, opt-in** (`SubmitMutex::enter_submit`, `src/vulkan_device_fault.h`, - `LEONIDA_COMPILE_GATE=adaptive`). Unset, the gate stays the classic one: compute creates only, each waited for - however long it takes, no probes, as before. The adaptive gate is opt-in because of what it costs on a driver that - does hold submissions behind a create (630.20, below): no run of it there has been reported yet. The gate keeps a +- **A bounded, adaptive compile gate, where the driver was measured for it** (`SubmitMutex::enter_submit`, + `src/vulkan_device_fault.h`; `LEONIDA_COMPILE_GATE=adaptive` forces it, `classic` forces the classic one). The + classic gate: compute creates only, each waited for however long it takes, no probes, as before. Unset or `auto`, + the device measures which one this driver gets before the title runs (the next item). The adaptive gate is not on + everywhere because of what it costs on a driver that does hold submissions behind a create (630.20, below): no run + of it there has been reported yet. The gate keeps a `vkQueueSubmit` out of the driver while a create is in it, since on NVIDIA 630.20 one that entered during a long `vkCreateComputePipelines` waited 10 s and lost the device. The waiting submission holds the submit lock, so all queues stop: on an RTX 4070 Laptop (NVIDIA 621.40) one compute create of a 2.3 MB module stayed in the driver for @@ -2966,6 +2968,34 @@ submitting thread; at the maintainers' decision it was replaced by this one when create in the driver (kind, program, SPIR-V size, thread, how long it had been there, whether submissions waited for it) and each kind's gate. Long graphics creates would leave the title's process only through the compile helper, which builds compute pipelines alone today. +- **`LEONIDA_COMPILE_GATE=auto`, the default: a calibration at device creation** (`src/compile_gate_policy.h`, + `src/compile_gate_calibration.h`, `decide_auto_compile_gate` in `shims/d3d12_vulkan_device.cpp`). Before the + `VulkanContext` (and its `SubmitMutex`) exists, so nothing is gated before the decision, a worker thread creates a + compute pipeline written in code (a chain of `fract(sin(...))` steps and branches over a storage buffer, its + constants from specialization constant 0 with a new seed each run, so neither a pipeline cache nor the driver's + shader cache answers it; no game data) while this thread submits an empty command buffer to the device's queue and + waits for its fence, over and over, until the create returns. At least 3 submissions back in 50 ms or less, before + the create left and some in its second half, with none slower: adaptive. One of 250 ms or more that came back + within 200 ms of the create leaving: the driver holds submissions, classic. A create under 300 ms is tried again + larger (up to 4 trials, none started after 6 s); a slow submission the create does not explain, too few samples + or any failed call: classic. The verdict is kept per vendor, device, driver version and pipeline cache UUID in + `compile_gate_calibration.txt` beside the pipeline cache (failures are not kept), so it runs once per driver; + `LEONIDA_COMPILE_GATE_RECALIBRATE=1` measures again. It is logged once, `[rt] compile-gate: auto: adaptive + (calibrated on NVIDIA 621.40 in 0.7 s: 115 submissions came back in <= 0.5 ms beside a 722 ms create; cached in + ...)` (`classic` and the reason otherwise). Only gta6rt's title process calibrates; `--precompile-pipelines`, + `--compile-server` and the tests keep the classic gate, and a forced value never waits for it. + Why a calibration can ask what an in-game probe cannot: the adaptive gate learns by letting a submission into the + driver beside a create of the title's, which can take 30-60 s, and on a driver that holds submissions such a probe + loses the device once it waits 10 s more. The calibration's create takes about a second and its submissions are + empty, so on such a driver one is held about a second and comes back with the create; that cannot reach the 10 s + the driver allows. What is known for the verdict to agree with, `MEASURED` but small (#2412, + [comment 7217585003](https://github.com/ubiquitarianism/leonida/pull/2412#issuecomment-7217585003)): on an RTX 4070 + Laptop with NVIDIA 621.40 a synthetic probe never held a submission past 80 ms beside 8-10 s graphics creates and + retail adaptive runs had no gate hang after #2418, and this calibration gives adaptive there (in 6 runs of + `vk_compile_gate_calibration_test`, 53-125 submissions each, none over 0.9 ms, beside creates of 354-783 ms); an RTX 4060 with 610.88 turned the adaptive gate off with no + regression reported; other 621.x users report fewer crashes with it; one freeze at about 231 s on an RTX 5070 + (621.x) was at a head without #2418 and is being rechecked. On 630.20 the calibration has not run yet: the + expected verdict there is classic, from the 10 s hold measured beside a long compute create. **Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. The trace will enumerate them. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 4cbe50acb2..7f3b79aaa1 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -914,6 +914,10 @@ if(BUILD_TESTING) target_link_libraries(big_compile_gate_test PRIVATE Threads::Threads) add_test(NAME big_compile_gate COMMAND big_compile_gate_test) set_tests_properties(big_compile_gate PROPERTIES TIMEOUT 120) + # LEONIDA_COMPILE_GATE=auto (src/compile_gate_policy.h): the setting, the calibration verdict, its cache file and the + # slow pipeline's SPIR-V: pure stdlib, no Vulkan device. + add_executable(compile_gate_policy_test test/compile_gate_policy_test.cpp) + add_test(NAME compile_gate_policy COMMAND compile_gate_policy_test) # vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. add_executable(large_module_gate_test test/large_module_gate_test.cpp) find_package(Threads REQUIRED) @@ -2006,6 +2010,23 @@ if(TARGET Vulkan::Headers) target_compile_definitions(${tool} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() endforeach() + # The LEONIDA_COMPILE_GATE=auto calibration (src/compile_gate_calibration.h) on this machine's GPU: a verdict within + # 20 s, adaptive on NVIDIA 621.40. 77 without a Vulkan device. + add_executable(vk_compile_gate_calibration_test test/vk_compile_gate_calibration_test.cpp) + target_link_libraries(vk_compile_gate_calibration_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) + if(WIN32) + target_compile_definitions(vk_compile_gate_calibration_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + else() + find_package(Threads REQUIRED) + target_link_libraries(vk_compile_gate_calibration_test PRIVATE Threads::Threads) + endif() + if(MSVC) + target_compile_options(vk_compile_gate_calibration_test PRIVATE /W4 /permissive- /utf-8) + endif() + if(BUILD_TESTING) + add_test(NAME vk_compile_gate_calibration COMMAND vk_compile_gate_calibration_test) + set_tests_properties(vk_compile_gate_calibration PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() # The ExecuteIndirect argument clamp's compute pass (runtime/src/vulkan_indirect_clamp.h): every argument kind and # the counted variants, with garbage records bounded and the batch budget saturating, read back from the scratch # the replay would use. 77 without a Vulkan device. diff --git a/runtime/README.md b/runtime/README.md index b885981fc3..18b0e65b88 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -421,10 +421,11 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TEXTURE_REFRESH_ASYNC` | unset | `1` moves the before-submission refresh of the title textures (`refresh_title_textures`) to a worker: a submission only wakes it, and fills by itself only the mapped textures that were never filled, so their first draw has their bytes. Persistent mappings are hashed whole on the worker every pass; the rest is swept 128 textures at a time. A texture changed since may be sampled a frame behind. | | `LEONIDA_SUBMIT_ASYNC` | `0` | ``: each queue's `ExecuteCommandLists`, `Signal`, `Wait` and markers run in call order on a worker of the queue's own (`src/vulkan_backend.h`), at most n batches queued; the caller of the next one waits for room. The replay, the before-submission refreshes and `vkQueueSubmit` then leave the title's thread. A batch that fails is reported as a held one is. `0`: on the caller's thread. | | `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` | unset | ``: a compute warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the last second); the pipeline is built at its first use instead (docs/d3d12_vulkan.md, "Pipelines still being built"). Unset or `0`: every warm-up runs, ordered behind a submission's compiles by the large-compile gate. | -| `LEONIDA_COMPILE_GATE` | on (classic) | The compile gate (`SubmitMutex::CompileTurn`, `src/vulkan_device_fault.h`): a queue submission (or a present or device wait) does not enter the driver while a pipeline create is in it, and waits in the runtime instead, since on NVIDIA 630.20 a `vkQueueSubmit` that entered during a long `vkCreateComputePipelines` waited 10 s in the driver and lost the device. Creates pass together; one that arrives while a submission waits queues behind it. Unset: the classic gate, as before the adaptive one: compute creates only, waited for however long they take (`LEONIDA_COMPILE_GATE_WAIT_MS` can bound it), no probes. `adaptive`: the adaptive gate, opt-in until it has run on a driver that holds submissions (630.20), where its first probe of a kind enters the driver after the probe budget and loses the device if that create stays 10 s more. The adaptive gate's wait is bounded by `LEONIDA_COMPILE_GATE_WAIT_MS`. Each submission that enters the driver next to a create the gate went past (at that limit, or earlier at the probe budget, `LEONIDA_COMPILE_GATE_PROBE_MS`) is a probe; two that come back in under 250 ms, at least 1 s apart, with the create still in the driver turn the gate off for the rest of the run (NVIDIA 621.40: 0-11 ms), and one that stays 2 s or more keeps it on; both are logged once. The verdict is kept per kind of create, compute and graphics (mesh included; graphics creates pass the gate since then, only compute ones did before): on NVIDIA 621.40 submissions came back in 0-12 ms beside compute creates, but one sat 54 s in the driver beside a 56 s mesh create and the device was lost. A kind that is off is still timed, and a submission that stays 2 s beside one of its creates turns it back on. A submission never goes ahead, at the limit or the budget, beside a create of a kind whose verdict is that it holds submissions: it waits for that create up to `LEONIDA_COMPILE_GATE_HELD_WAIT_MS`. On a device loss the log names the creates in the driver (kind, program, size, how long) and each kind's gate. `1`: always gate, graphics creates too, with no limit unless `LEONIDA_COMPILE_GATE_WAIT_MS` sets one, never probe or turn it off, and a compute pipeline build also holds the submit lock for its driver calls (`compute_driver_turn`, `shims/d3d12_vulkan_device.cpp`). `0`: no gate. | -| `LEONIDA_COMPILE_GATE_WAIT_MS` | 0 (15000 with `LEONIDA_COMPILE_GATE=adaptive`) | ``: how long a submission waits at the compile gate before it goes ahead anyway; the creates in the driver then hold no later submission back (creates that enter after it are waited for again), and the log says how long the submission then took in the driver. The waiter holds the submit lock, so every queue stops behind it, and the title's hang watchdog ends the process after 30 s (one create stayed in the driver for over 54 s on NVIDIA 621.40). 15 s keeps the 630.20 protection for creates of up to 25 s. The same with the watchdog kept kicked: nothing ends the run then, but the stops still cost the frames (an RTX 4060 run that way had 459 waits, 155 s in all, by t=202 s). `0`: no limit, and with `LEONIDA_COMPILE_GATE_PROBE_MS` unset no probes either: the gate waits however long the creates take and never adapts. | +| `LEONIDA_COMPILE_GATE` | `auto` (adaptive or classic, by calibration) | The compile gate (`SubmitMutex::CompileTurn`, `src/vulkan_device_fault.h`): a queue submission (or a present or device wait) does not enter the driver while a pipeline create is in it, and waits in the runtime instead, since on NVIDIA 630.20 a `vkQueueSubmit` that entered during a long `vkCreateComputePipelines` waited 10 s in the driver and lost the device. Creates pass together; one that arrives while a submission waits queues behind it. Unset or `auto`: the device measures the driver once, before the title has it (`src/compile_gate_calibration.h`, `docs/d3d12_vulkan.md`): a worker thread creates a synthetic compute pipeline that takes about a second to compile while the queue gets empty submissions, each waited for. Submissions back in under 50 ms with the create still in the driver give the adaptive gate; one held until the create leaves, a create too fast to tell, a submission slow for another reason or any failure give the classic gate. The verdict is kept per GPU and driver (vendor, device, driver version, pipeline cache UUID) in `compile_gate_calibration.txt` beside the pipeline cache, so the measurement runs once per driver, and is logged once: `[rt] compile-gate: auto: adaptive (calibrated on NVIDIA 621.40 in 0.7 s: 115 submissions came back in <= 0.5 ms beside a 722 ms create; cached in ...)`, or `auto: classic (...)`, or `(cached calibration of ...)`. Only gta6rt's title process calibrates: `--precompile-pipelines`, `--compile-server` and tests keep the classic gate. `classic`: compute creates only, waited for however long they take (`LEONIDA_COMPILE_GATE_WAIT_MS` can bound it), no probes, the default before `auto`. `adaptive`: the adaptive gate whatever the calibration says; on a driver that holds submissions (630.20) its first probe of a kind enters the driver after the probe budget and loses the device if that create stays 10 s more. The adaptive gate's wait is bounded by `LEONIDA_COMPILE_GATE_WAIT_MS`. Each submission that enters the driver next to a create the gate went past (at that limit, or earlier at the probe budget, `LEONIDA_COMPILE_GATE_PROBE_MS`) is a probe; two that come back in under 250 ms, at least 1 s apart, with the create still in the driver turn the gate off for the rest of the run (NVIDIA 621.40: 0-11 ms), and one that stays 2 s or more keeps it on; both are logged once. The verdict is kept per kind of create, compute and graphics (mesh included; graphics creates pass the gate since then, only compute ones did before): on NVIDIA 621.40 submissions came back in 0-12 ms beside compute creates, but one sat 54 s in the driver beside a 56 s mesh create and the device was lost. A kind that is off is still timed, and a submission that stays 2 s beside one of its creates turns it back on. A submission never goes ahead, at the limit or the budget, beside a create of a kind whose verdict is that it holds submissions: it waits for that create up to `LEONIDA_COMPILE_GATE_HELD_WAIT_MS`. On a device loss the log names the creates in the driver (kind, program, size, how long) and each kind's gate. `1`: always gate, graphics creates too, with no limit unless `LEONIDA_COMPILE_GATE_WAIT_MS` sets one, never probe or turn it off, and a compute pipeline build also holds the submit lock for its driver calls (`compute_driver_turn`, `shims/d3d12_vulkan_device.cpp`). `0`: no gate. | +| `LEONIDA_COMPILE_GATE_WAIT_MS` | 0 (15000 with the adaptive gate) | ``: how long a submission waits at the compile gate before it goes ahead anyway; the creates in the driver then hold no later submission back (creates that enter after it are waited for again), and the log says how long the submission then took in the driver. The waiter holds the submit lock, so every queue stops behind it, and the title's hang watchdog ends the process after 30 s (one create stayed in the driver for over 54 s on NVIDIA 621.40). 15 s keeps the 630.20 protection for creates of up to 25 s. The same with the watchdog kept kicked: nothing ends the run then, but the stops still cost the frames (an RTX 4060 run that way had 459 waits, 155 s in all, by t=202 s). `0`: no limit, and with `LEONIDA_COMPILE_GATE_PROBE_MS` unset no probes either: the gate waits however long the creates take and never adapts. | | `LEONIDA_COMPILE_GATE_HELD_WAIT_MS` | 60000 | ``: with the adaptive gate, how long a submission waits for creates of a kind the gate found to hold submissions (`docs/d3d12_vulkan.md`) before it goes ahead anyway; those creates are then not waited for again. `0`: until they leave. | -| `LEONIDA_COMPILE_GATE_PROBE_MS` | 2500 with `LEONIDA_COMPILE_GATE=adaptive` (0 with `LEONIDA_COMPILE_GATE_WAIT_MS=0`) | ``: the adaptive gate's probe budget. Until it knows whether the driver holds a submission behind a create, a submission also goes ahead once the submissions' waits at the gate in the last 10 s, its own included, add up to this; a single wait reaches it at 2.5 s. On NVIDIA 621.40 waits of 3-7 s, none near the 15 s limit, came back to back and kept the title's main loop from reporting for 30 s; on an RTX 4060 with the watchdog kept kicked, 459 waits of up to 2.9 s took 155 s by t=202 s. The cost on a driver that does hold submissions (630.20): the first probe enters the driver after 2.5 s of waiting and loses the device if the create stays 10 s more; the held verdict then stops the early probes. `0`: probes only at `LEONIDA_COMPILE_GATE_WAIT_MS`. Used only with `LEONIDA_COMPILE_GATE=adaptive`. | +| `LEONIDA_COMPILE_GATE_PROBE_MS` | 2500 with the adaptive gate (0 with `LEONIDA_COMPILE_GATE_WAIT_MS=0`) | ``: the adaptive gate's probe budget. Until it knows whether the driver holds a submission behind a create, a submission also goes ahead once the submissions' waits at the gate in the last 10 s, its own included, add up to this; a single wait reaches it at 2.5 s. On NVIDIA 621.40 waits of 3-7 s, none near the 15 s limit, came back to back and kept the title's main loop from reporting for 30 s; on an RTX 4060 with the watchdog kept kicked, 459 waits of up to 2.9 s took 155 s by t=202 s. The cost on a driver that does hold submissions (630.20): the first probe enters the driver after 2.5 s of waiting and loses the device if the create stays 10 s more; the held verdict then stops the early probes. `0`: probes only at `LEONIDA_COMPILE_GATE_WAIT_MS`. Used only by the adaptive gate. | +| `LEONIDA_COMPILE_GATE_RECALIBRATE` | unset | `1`: with `LEONIDA_COMPILE_GATE` unset or `auto`, the device measures the driver again instead of reading the verdict kept in `compile_gate_calibration.txt`, and writes the new one there (after a driver update the key changes and it measures anyway). | | `LEONIDA_FAST_PIPELINES` | unset | `graphics`, `compute` or `all` (`1` = all) creates those pipelines with `VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT` (`shims/d3d12_pipeline_compile.h`): slower shaders, much shorter builds. Part of the compute journal key, so optimized and fast builds keep separate files. | | `LEONIDA_GRAPHICS_COMPILE_WORKER` | on | A second compile worker that takes graphics pipeline builds only, so a long compute build does not hold them up (`shims/d3d12_pipeline_compile.h`). `0`: the one general worker builds everything. | | `LEONIDA_CONSOLE_HEAP_GPU` | unset | `1`: the V#s of the console descriptor heaps are rebased by a compute pass at the start of each submission (`src/console_heap_gpu.h`) instead of on the CPU. The CPU still finds the changed slots and registers the T#s; a V# the pass cannot answer is resolved after its submission and its slot queued again. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 6c8d9345c3..d1c43e0dd7 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -45,6 +45,7 @@ #include "../src/vulkan_mesh_limits.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" +#include "../src/compile_gate_calibration.h" #include "../src/pipeline_cache_file.h" #include "../src/pipeline_profile.h" #include "../src/submit_phases.h" @@ -1695,6 +1696,101 @@ std::filesystem::path pipeline_cache_heavy_path() { return path; } +// LEONIDA_COMPILE_GATE unset or `auto` (src/compile_gate_policy.h): decides the compile gate for this GPU and driver +// before the VulkanContext (and its SubmitMutex) exists. The verdict comes from compile_gate_calibration.txt beside +// the pipeline cache, or from a calibration on `info.queue` (src/compile_gate_calibration.h), written there once. +// Only in gta6rt's title process (compile_gate_policy::calibration_allowed): a build host, a test or anything else +// that creates a device keeps the classic gate and never calibrates. A forced setting returns at once. +void decide_auto_compile_gate(const VulkanDeviceInfo& info, PFN_vkGetDeviceProcAddr get_device, + const leonida::cached_pso::Identity& identity) { + namespace policy = leonida::compile_gate_policy; + using leonida::CompileGateMode; + using leonida::SubmitMutex; + if (SubmitMutex::compile_gate_setting() != policy::Setting::automatic) return; + if (!policy::calibration_allowed.load() || compile_helper::build_host.load()) return; // classic, as before `auto` + static std::once_flag once; + std::call_once(once, [&] { + const auto decide = [](CompileGateMode mode, const std::string& why) { + SubmitMutex::decide_auto_gate(mode); + std::fprintf(stderr, "[rt] compile-gate: auto: %s (%s; LEONIDA_COMPILE_GATE=classic|adaptive overrides)\n", + mode == CompileGateMode::adaptive ? "adaptive" : "classic", why.c_str()); + }; + const auto utf8 = [](const std::filesystem::path& path) { + const std::wstring& wide = path.native(); + const int n = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), int(wide.size()), nullptr, 0, nullptr, nullptr); + std::string out(std::size_t(n > 0 ? n : 0), '\0'); + if (n > 0) WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), int(wide.size()), out.data(), n, nullptr, nullptr); + return out; + }; + if (!identity.vendor || !info.device || !info.queue || !get_device) { + decide(CompileGateMode::classic, "the GPU or its queue is not known, so no calibration"); + return; + } + const std::string driver = policy::describe_driver(identity.vendor, identity.driver); + if (info.physical && info.get_instance_proc) { + if (const auto get_props = reinterpret_cast( + info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { + VkPhysicalDeviceProperties props{}; + get_props(info.physical, &props); + if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) { + decide(CompileGateMode::classic, driver + " is a CPU device, not calibrated"); + return; + } + } + } + policy::CacheKey key; + key.vendor = identity.vendor; + key.device = identity.device; + key.driver = identity.driver; + std::memcpy(key.uuid, identity.cache_uuid, sizeof key.uuid); + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"compile_gate_calibration.txt"); + std::string text; + if (!path.empty()) { + std::ifstream in(path, std::ios::binary); + if (in) text.assign(std::istreambuf_iterator(in), std::istreambuf_iterator()); + } + char value[4] = {}; + std::size_t length = 0; + const bool recalibrate = + getenv_s(&length, value, "LEONIDA_COMPILE_GATE_RECALIBRATE") == 0 && length > 1 && policy::recalibrate(value); + if (!recalibrate) { + if (const auto cached = policy::find_entry(text, key)) { + decide(policy::mode_for(cached->verdict.outcome), + "cached calibration of " + driver + ": " + policy::describe_verdict(cached->verdict) + "; in " + + utf8(path) + ", LEONIDA_COMPILE_GATE_RECALIBRATE=1 measures again"); + return; + } + } + const auto seed = static_cast(std::chrono::steady_clock::now().time_since_epoch().count()) | 1u; + const leonida::compile_gate_calibration::Result result = + leonida::compile_gate_calibration::calibrate(get_device, info.device, info.queue, info.queue_family, seed); + if (!result.ok) { + decide(CompileGateMode::classic, "calibration of " + driver + " failed: " + result.error + "; not cached"); + return; + } + std::string where = "not cached (no pipeline cache folder)"; + if (!path.empty()) { + const std::string updated = policy::replace_entry(text, {key, result.verdict}); + std::filesystem::path temp = path; + temp += L".tmp"; + bool written = false; + { + std::ofstream out(temp, std::ios::binary | std::ios::trunc); + out.write(updated.data(), std::streamsize(updated.size())); + written = bool(out); + } + std::error_code ec; + if (written) std::filesystem::rename(temp, path, ec); + where = written && !ec ? "cached in " + utf8(path) : "not cached (" + utf8(path) + " could not be written)"; + } + char took[64]; + std::snprintf(took, sizeof took, " in %.1f s", result.total_ms / 1000.0); + decide(policy::mode_for(result.verdict.outcome), "calibrated on " + driver + took + ": " + + policy::describe_verdict(result.verdict) + "; " + where); + }); +} + // 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() { @@ -14442,6 +14538,8 @@ class Device final .first_instance = info.draw_indirect_first_instance, .multiple = info.multi_draw_indirect, .count_buffer = info.draw_indirect_count_enabled, .max_count = info.max_draw_indirect_count, .robust_index_view = info.robust_index_view, .require_clamp = leonida::indirect_clamp_enabled()}; + // Before the context: its SubmitMutex takes the gate's mode and limits when it is made. + decide_auto_compile_gate(info, get_device, state_.pso_identity); state_.context = std::make_unique(get_device, info.device, info.separate_depth_stencil_layouts, info.conditional_rendering, info.ray_tracing, diff --git a/runtime/src/compile_gate_calibration.h b/runtime/src/compile_gate_calibration.h new file mode 100644 index 0000000000..2f0e73a4ef --- /dev/null +++ b/runtime/src/compile_gate_calibration.h @@ -0,0 +1,234 @@ +// The measurement behind LEONIDA_COMPILE_GATE=auto (compile_gate_policy.h): whether this driver holds a queue +// submission while a pipeline create is in it. Run once per driver at device creation, before the title has the +// device, on the device's own queue: a worker thread creates the slow compute pipeline of +// compile_gate_policy::slow_compute_spirv (no pipeline cache, a new seed each time), and this thread submits an empty +// command buffer and waits for its fence over and over until the create returns. A create too fast to tell is tried +// again larger, up to kMaxTrials. Every failure is a classic verdict; the caller does not cache those. +#pragma once + +#include + +#include "compile_gate_policy.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::compile_gate_calibration { + +inline constexpr std::uint32_t kFirstStatements = 1000; +inline constexpr std::uint32_t kMostStatements = 32000; +inline constexpr unsigned kMaxTrials = 4; +inline constexpr double kStartTrialsWithinMs = 6000; // no new trial after this long +inline constexpr std::uint64_t kFenceTimeoutNs = 10'000'000'000ull; +inline constexpr std::size_t kMostSamples = 4000; // per trial; the create may outlast them + +struct Result { + bool ok = false; // false: a Vulkan call failed (`error` says which); the verdict is then unclear + std::string error; + compile_gate_policy::Verdict verdict; + unsigned trials = 0; + std::uint32_t statements = 0; // of the last trial + double total_ms = 0; +}; + +namespace detail { + +struct Fns { + PFN_vkCreateDescriptorSetLayout create_set_layout = nullptr; + PFN_vkDestroyDescriptorSetLayout destroy_set_layout = nullptr; + PFN_vkCreatePipelineLayout create_layout = nullptr; + PFN_vkDestroyPipelineLayout destroy_layout = nullptr; + PFN_vkCreateShaderModule create_module = nullptr; + PFN_vkDestroyShaderModule destroy_module = nullptr; + PFN_vkCreateComputePipelines create_compute = nullptr; + PFN_vkDestroyPipeline destroy_pipeline = nullptr; + PFN_vkCreateCommandPool create_pool = nullptr; + PFN_vkDestroyCommandPool destroy_pool = nullptr; + PFN_vkAllocateCommandBuffers allocate_cbs = nullptr; + PFN_vkBeginCommandBuffer begin_cb = nullptr; + PFN_vkEndCommandBuffer end_cb = nullptr; + PFN_vkCreateFence create_fence = nullptr; + PFN_vkDestroyFence destroy_fence = nullptr; + PFN_vkResetFences reset_fences = nullptr; + PFN_vkWaitForFences wait_fences = nullptr; + PFN_vkQueueSubmit queue_submit = nullptr; + + bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { + const auto fn = [&](auto& out, const char* name) { + out = reinterpret_cast>(get(device, name)); + return out != nullptr; + }; + return fn(create_set_layout, "vkCreateDescriptorSetLayout") && + fn(destroy_set_layout, "vkDestroyDescriptorSetLayout") && + fn(create_layout, "vkCreatePipelineLayout") && fn(destroy_layout, "vkDestroyPipelineLayout") && + fn(create_module, "vkCreateShaderModule") && fn(destroy_module, "vkDestroyShaderModule") && + fn(create_compute, "vkCreateComputePipelines") && fn(destroy_pipeline, "vkDestroyPipeline") && + fn(create_pool, "vkCreateCommandPool") && fn(destroy_pool, "vkDestroyCommandPool") && + fn(allocate_cbs, "vkAllocateCommandBuffers") && fn(begin_cb, "vkBeginCommandBuffer") && + fn(end_cb, "vkEndCommandBuffer") && fn(create_fence, "vkCreateFence") && + fn(destroy_fence, "vkDestroyFence") && fn(reset_fences, "vkResetFences") && + fn(wait_fences, "vkWaitForFences") && fn(queue_submit, "vkQueueSubmit"); + } +}; + +using clock = std::chrono::steady_clock; +inline double ms_between(clock::time_point a, clock::time_point b) { + return std::chrono::duration(b - a).count(); +} + +} // namespace detail + +// Runs the calibration on `queue` (of `family`). Nothing else may use the queue meanwhile. `seed` varies the program +// (the caller passes something new each run, so the driver's own shader cache never answers). Progress goes to +// stderr with `tag` in front. +inline Result calibrate(PFN_vkGetDeviceProcAddr get, VkDevice device, VkQueue queue, std::uint32_t family, + std::uint32_t seed, const char* tag = "[rt] compile-gate:") { + namespace policy = compile_gate_policy; + Result result; + const auto began = detail::clock::now(); + detail::Fns vk; + if (!get || !device || !queue || !vk.load(get, device)) { + result.error = "the device's entry points are missing"; + return result; + } + VkDescriptorSetLayout set_layout = VK_NULL_HANDLE; + VkPipelineLayout layout = VK_NULL_HANDLE; + VkCommandPool pool = VK_NULL_HANDLE; + VkCommandBuffer cb = VK_NULL_HANDLE; + VkFence fence = VK_NULL_HANDLE; + const auto cleanup = [&] { + if (fence) vk.destroy_fence(device, fence, nullptr); + if (pool) vk.destroy_pool(device, pool, nullptr); + if (layout) vk.destroy_layout(device, layout, nullptr); + if (set_layout) vk.destroy_set_layout(device, set_layout, nullptr); + }; + const auto fail = [&](const char* what, VkResult r) { + char text[120]; + std::snprintf(text, sizeof text, "%s failed (VkResult %d)", what, int(r)); + result.error = text; + cleanup(); + result.total_ms = detail::ms_between(began, detail::clock::now()); + return result; + }; + + VkDescriptorSetLayoutBinding binding{}; + binding.binding = 0; + binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + binding.descriptorCount = 1; + binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + set_info.bindingCount = 1; + set_info.pBindings = &binding; + if (const VkResult r = vk.create_set_layout(device, &set_info, nullptr, &set_layout); r != VK_SUCCESS) + return fail("vkCreateDescriptorSetLayout", r); + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.setLayoutCount = 1; + layout_info.pSetLayouts = &set_layout; + if (const VkResult r = vk.create_layout(device, &layout_info, nullptr, &layout); r != VK_SUCCESS) + return fail("vkCreatePipelineLayout", r); + VkCommandPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + pool_info.queueFamilyIndex = family; + if (const VkResult r = vk.create_pool(device, &pool_info, nullptr, &pool); r != VK_SUCCESS) + return fail("vkCreateCommandPool", r); + VkCommandBufferAllocateInfo cb_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + cb_info.commandPool = pool; + cb_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + cb_info.commandBufferCount = 1; + if (const VkResult r = vk.allocate_cbs(device, &cb_info, &cb); r != VK_SUCCESS) + return fail("vkAllocateCommandBuffers", r); + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + if (const VkResult r = vk.begin_cb(cb, &begin); r != VK_SUCCESS) return fail("vkBeginCommandBuffer", r); + if (const VkResult r = vk.end_cb(cb); r != VK_SUCCESS) return fail("vkEndCommandBuffer", r); + VkFenceCreateInfo fence_info{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; + if (const VkResult r = vk.create_fence(device, &fence_info, nullptr, &fence); r != VK_SUCCESS) + return fail("vkCreateFence", r); + VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO}; + submit.commandBufferCount = 1; + submit.pCommandBuffers = &cb; + + std::uint32_t statements = kFirstStatements; + bool retried_unclear = false; + for (unsigned trial = 0; trial < kMaxTrials; ++trial) { + if (trial && detail::ms_between(began, detail::clock::now()) > kStartTrialsWithinMs) break; + const std::vector words = policy::slow_compute_spirv(statements); + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * sizeof(std::uint32_t); + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (const VkResult r = vk.create_module(device, &module_info, nullptr, &module); r != VK_SUCCESS) + return fail("vkCreateShaderModule", r); + const std::uint32_t trial_seed = seed + trial; + VkSpecializationMapEntry entry{0, 0, sizeof(std::uint32_t)}; + VkSpecializationInfo spec{1, &entry, sizeof trial_seed, &trial_seed}; + VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; + info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + info.stage.module = module; + info.stage.pName = "main"; + info.stage.pSpecializationInfo = &spec; + info.layout = layout; + + std::atomic entered{false}, left{false}; + detail::clock::time_point create_begin{}, create_end{}; + VkResult create_result = VK_SUCCESS; + VkPipeline pipeline = VK_NULL_HANDLE; + std::thread worker([&] { + create_begin = detail::clock::now(); + entered.store(true, std::memory_order_release); + create_result = vk.create_compute(device, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline); + create_end = detail::clock::now(); + left.store(true, std::memory_order_release); + }); + while (!entered.load(std::memory_order_acquire)) std::this_thread::yield(); + const detail::clock::time_point start_mark = create_begin; + policy::Trial t; + VkResult submit_result = VK_SUCCESS; + // Let the create get into the driver before the first submission. + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + while (!left.load(std::memory_order_acquire) && t.samples.size() < kMostSamples) { + const auto s0 = detail::clock::now(); + submit_result = vk.queue_submit(queue, 1, &submit, fence); + if (submit_result != VK_SUCCESS) break; + submit_result = vk.wait_fences(device, 1, &fence, VK_TRUE, kFenceTimeoutNs); + const auto s1 = detail::clock::now(); + if (submit_result != VK_SUCCESS) break; + submit_result = vk.reset_fences(device, 1, &fence); + if (submit_result != VK_SUCCESS) break; + t.samples.push_back({detail::ms_between(start_mark, s0), detail::ms_between(start_mark, s1)}); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + worker.join(); + if (pipeline) vk.destroy_pipeline(device, pipeline, nullptr); + vk.destroy_module(device, module, nullptr); + if (submit_result != VK_SUCCESS) return fail("an empty submission", submit_result); + if (create_result != VK_SUCCESS) return fail("vkCreateComputePipelines", create_result); + t.create_ms = detail::ms_between(create_begin, create_end); + result.verdict = policy::judge(t); + result.trials = trial + 1; + result.statements = statements; + std::fprintf(stderr, "%s calibration trial %u: %u statements, create %.0f ms, %zu submissions, %s\n", tag, + trial + 1, unsigned(statements), t.create_ms, t.samples.size(), + policy::outcome_name(result.verdict.outcome)); + if (result.verdict.outcome == policy::Outcome::adaptive || result.verdict.outcome == policy::Outcome::holds) + break; + if (result.verdict.outcome == policy::Outcome::too_fast) { + if (statements >= kMostStatements) break; + statements = policy::next_statements(statements, t.create_ms, kMostStatements); + } else { // unclear: once more at the same size (another process may have used the GPU), then give up + if (retried_unclear) break; + retried_unclear = true; + } + } + cleanup(); + result.ok = true; + result.total_ms = detail::ms_between(began, detail::clock::now()); + return result; +} + +} // namespace leonida::compile_gate_calibration diff --git a/runtime/src/compile_gate_policy.h b/runtime/src/compile_gate_policy.h new file mode 100644 index 0000000000..57ab30db4b --- /dev/null +++ b/runtime/src/compile_gate_policy.h @@ -0,0 +1,524 @@ +// Which compile gate (SubmitMutex, vulkan_device_fault.h) a run uses, and the pure half of the calibration that +// decides it when LEONIDA_COMPILE_GATE is unset or `auto`: the setting, the verdict over the timings, the cache file +// and the SPIR-V of the slow pipeline. No Vulkan calls and no environment here, so compile_gate_policy_test checks it +// without a GPU; compile_gate_calibration.h runs the measurement. +// +// `auto` measures the driver once, at device creation and before the title runs: a worker thread creates a compute +// pipeline that takes the driver about a second to compile, and meanwhile the device's queue gets empty submissions, +// each waited for on a fence. Submissions that come back in under kQuickMs while the create is still in the driver +// mean this driver does not hold a submission behind a create: the adaptive gate. One held until the create leaves +// means it does (NVIDIA 630.20 held one 10 s beside a long compute create and lost the device): the classic gate. A +// create too fast to tell, a submission slow for another reason, or any failure: classic, the gate as before `auto`. +// Holding an empty submission for a second beside a one-second create cannot lose the device; the probes the adaptive +// gate makes in the title, beside creates of 30-60 s, can (docs/d3d12_vulkan.md). The verdict is cached per GPU and +// driver (compile_gate_calibration.txt beside the pipeline cache), so the measurement runs once per driver. +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// The gate a run uses. off: no gate. classic: compute creates only, no limit, no probes. adaptive: bounded, probes, +// off once the driver is seen not to hold submissions. always: both kinds, no probes (LEONIDA_COMPILE_GATE=1). +enum class CompileGateMode { off, classic, adaptive, always }; + +namespace compile_gate_policy { + +// What LEONIDA_COMPILE_GATE asks for. automatic: unset, empty or `auto`. +enum class Setting { automatic, off, classic, adaptive, always }; + +struct ParsedSetting { + Setting setting = Setting::automatic; + bool unknown = false; // a value none of the below: classic, as before `auto` +}; + +// "0" off, "1" always, "adaptive", "classic", "auto"; unset or empty: auto. Anything else is classic, as it was +// before `auto`: an unknown value never turns the adaptive gate on. +inline ParsedSetting parse_setting(const char* value) { + if (!value || !*value || !std::strcmp(value, "auto")) return {Setting::automatic, false}; + if (!std::strcmp(value, "0")) return {Setting::off, false}; + if (!std::strcmp(value, "1")) return {Setting::always, false}; + if (!std::strcmp(value, "adaptive")) return {Setting::adaptive, false}; + if (!std::strcmp(value, "classic")) return {Setting::classic, false}; + return {Setting::classic, true}; +} + +// The mode a forced setting names; automatic is classic until the calibration decides. +inline CompileGateMode forced_mode(Setting setting) { + switch (setting) { + case Setting::off: return CompileGateMode::off; + case Setting::adaptive: return CompileGateMode::adaptive; + case Setting::always: return CompileGateMode::always; + case Setting::classic: + case Setting::automatic: break; + } + return CompileGateMode::classic; +} + +// Set by gta6rt's title path (main.cpp) only: the calibration never runs in a build host (--precompile-pipelines, +// --compile-server) or in a test process that creates a device, which keep the classic gate under `auto`. +inline std::atomic calibration_allowed{false}; + +inline constexpr std::uint32_t kNvidiaVendorId = 0x10DE; +inline constexpr std::uint32_t kAmdVendorId = 0x1002; +inline constexpr std::uint32_t kIntelVendorId = 0x8086; + +// NVIDIA's VkPhysicalDeviceProperties::driverVersion: 10 bits major, 8 bits minor, then 8 and 6 bits the driver does +// not show on Windows ("621.40" is major 621, minor 40). +struct NvidiaVersion { + std::uint32_t major = 0; + std::uint32_t minor = 0; +}; +constexpr NvidiaVersion decode_nvidia(std::uint32_t version) { + return {(version >> 22) & 0x3ffu, (version >> 14) & 0xffu}; +} +constexpr std::uint32_t encode_nvidia(std::uint32_t major, std::uint32_t minor) { + return ((major & 0x3ffu) << 22) | ((minor & 0xffu) << 14); +} + +// "NVIDIA 621.40", "AMD driver 0x...", "vendor 0x... driver 0x...", "an unknown GPU", for the log. +inline std::string describe_driver(std::uint32_t vendor_id, std::uint32_t driver_version) { + char text[96]; + if (vendor_id == kNvidiaVendorId) { + const NvidiaVersion v = decode_nvidia(driver_version); + std::snprintf(text, sizeof text, "NVIDIA %u.%02u", unsigned(v.major), unsigned(v.minor)); + } else if (vendor_id == kAmdVendorId) { + std::snprintf(text, sizeof text, "AMD driver 0x%08x", unsigned(driver_version)); + } else if (vendor_id == kIntelVendorId) { + std::snprintf(text, sizeof text, "Intel driver 0x%08x", unsigned(driver_version)); + } else if (vendor_id == 0) { + std::snprintf(text, sizeof text, "an unknown GPU"); + } else { + std::snprintf(text, sizeof text, "vendor 0x%04x driver 0x%08x", unsigned(vendor_id), unsigned(driver_version)); + } + return text; +} + +// ---- The verdict over one trial. + +inline constexpr double kQuickMs = 50; // a submission back within this did not wait for the create +inline constexpr double kMinCreateMs = 300; // a shorter create cannot tell: the next trial is bigger +inline constexpr unsigned kMinQuick = 3; // quick submissions needed for the adaptive verdict +inline constexpr double kEndMarginMs = 20; // a quick one counts only if it came back this long before the create +inline constexpr double kHeldMs = 250; // a submission this long ... +inline constexpr double kHeldReturnMs = 200; // ... that came back within this of the create leaving was held by it +inline constexpr double kTargetCreateMs = 800; + +// One submission, in ms from the moment the create entered the driver: entered the queue at start_ms, its fence +// signalled at end_ms. +struct Sample { + double start_ms = 0; + double end_ms = 0; +}; + +struct Trial { + double create_ms = 0; // how long vkCreateComputePipelines took + std::vector samples; +}; + +enum class Outcome { + adaptive, // submissions came back quickly with the create still in the driver + holds, // a submission was held until the create left + too_fast, // the create left before it could tell + unclear, // a submission was slow, but not held by the create; or too few samples +}; + +inline const char* outcome_name(Outcome outcome) { + switch (outcome) { + case Outcome::adaptive: return "adaptive"; + case Outcome::holds: return "holds"; + case Outcome::too_fast: return "too_fast"; + case Outcome::unclear: break; + } + return "unclear"; +} +inline std::optional parse_outcome(std::string_view name) { + for (const Outcome o : {Outcome::adaptive, Outcome::holds, Outcome::too_fast, Outcome::unclear}) + if (name == outcome_name(o)) return o; + return std::nullopt; +} +inline CompileGateMode mode_for(Outcome outcome) { + return outcome == Outcome::adaptive ? CompileGateMode::adaptive : CompileGateMode::classic; +} + +struct Verdict { + Outcome outcome = Outcome::unclear; + unsigned quick = 0; // submissions back within kQuickMs, before the create left + double max_quick_ms = 0; // the longest of those + double create_ms = 0; + double slow_ms = 0; // the longest submission over kQuickMs (held or not), 0 if none +}; + +inline Verdict judge(const Trial& trial) { + Verdict v; + v.create_ms = trial.create_ms; + bool held = false, slow = false, late_quick = false; + for (const Sample& s : trial.samples) { + if (s.start_ms < 0 || s.start_ms >= trial.create_ms) continue; // entered while the create was in the driver + const double ms = s.end_ms - s.start_ms; + if (ms > kQuickMs) { + v.slow_ms = (std::max)(v.slow_ms, ms); + if (ms >= kHeldMs && s.end_ms >= trial.create_ms - kEndMarginMs && + s.end_ms <= trial.create_ms + kHeldReturnMs) + held = true; + else + slow = true; + continue; + } + if (s.end_ms > trial.create_ms - kEndMarginMs) continue; // back as the create left: tells nothing + ++v.quick; + v.max_quick_ms = (std::max)(v.max_quick_ms, ms); + if (s.start_ms >= trial.create_ms * 0.5) late_quick = true; + } + if (held) v.outcome = Outcome::holds; // first: a hold outweighs any number of quick ones + else if (slow) v.outcome = Outcome::unclear; + else if (trial.create_ms < kMinCreateMs) v.outcome = Outcome::too_fast; + else if (v.quick >= kMinQuick && late_quick) v.outcome = Outcome::adaptive; + else v.outcome = Outcome::unclear; + return v; +} + +// How many statements the next trial gets after one of `statements` took `create_ms`: towards kTargetCreateMs, at +// least twice and at most eight times as many, and never more than `most`. +inline std::uint32_t next_statements(std::uint32_t statements, double create_ms, std::uint32_t most) { + const double scaled = double(statements) * kTargetCreateMs / (std::max)(create_ms, 1.0); + const double grown = std::clamp(scaled, double(statements) * 2, double(statements) * 8); + return std::uint32_t((std::min)(grown, double(most))); +} + +// "N submissions came back in <= X ms beside a Y ms create" and the other outcomes, for the log. +inline std::string describe_verdict(const Verdict& v) { + char text[200]; + switch (v.outcome) { + case Outcome::adaptive: + std::snprintf(text, sizeof text, "%u submissions came back in <= %.1f ms beside a %.0f ms create", v.quick, + v.max_quick_ms, v.create_ms); + break; + case Outcome::holds: + std::snprintf(text, sizeof text, "a submission was held %.0f ms, until a %.0f ms create left", v.slow_ms, + v.create_ms); + break; + case Outcome::too_fast: + std::snprintf(text, sizeof text, "inconclusive: the largest create took only %.0f ms", v.create_ms); + break; + case Outcome::unclear: + if (v.slow_ms > 0) + std::snprintf(text, sizeof text, "inconclusive: a submission took %.0f ms beside a %.0f ms create, " + "but did not come back with it", v.slow_ms, v.create_ms); + else + std::snprintf(text, sizeof text, "inconclusive: %u quick submissions beside a %.0f ms create", v.quick, + v.create_ms); + break; + } + return text; +} + +// ---- The cache: one line per GPU and driver. + +struct CacheKey { + std::uint32_t vendor = 0; + std::uint32_t device = 0; + std::uint32_t driver = 0; + std::uint8_t uuid[16] = {}; // pipelineCacheUUID +}; +inline bool same_key(const CacheKey& a, const CacheKey& b) { + return a.vendor == b.vendor && a.device == b.device && a.driver == b.driver && + !std::memcmp(a.uuid, b.uuid, sizeof a.uuid); +} + +struct CacheEntry { + CacheKey key; + Verdict verdict; +}; + +inline constexpr std::string_view kCacheTag = "compile-gate-calibration v1"; + +inline std::string format_entry(const CacheEntry& e) { + char uuid[33]; + for (int i = 0; i < 16; ++i) std::snprintf(uuid + 2 * i, 3, "%02x", unsigned(e.key.uuid[i])); + char text[320]; + // Whole tenths of a millisecond, not decimals: no locale reads a comma into them. + std::snprintf(text, sizeof text, + "%s vendor=%04x device=%04x driver=%08x uuid=%s outcome=%s quick=%u max_quick_ds=%lld " + "create_ds=%lld slow_ds=%lld", + std::string(kCacheTag).c_str(), unsigned(e.key.vendor), unsigned(e.key.device), + unsigned(e.key.driver), uuid, outcome_name(e.verdict.outcome), e.verdict.quick, + static_cast(e.verdict.max_quick_ms * 10 + 0.5), + static_cast(e.verdict.create_ms * 10 + 0.5), + static_cast(e.verdict.slow_ms * 10 + 0.5)); + return text; +} + +namespace detail { +inline bool hex_u32(std::string_view text, std::uint32_t& out) { + if (text.empty() || text.size() > 8) return false; + std::uint32_t v = 0; + for (const char c : text) { + int d; + if (c >= '0' && c <= '9') d = c - '0'; + else if (c >= 'a' && c <= 'f') d = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') d = c - 'A' + 10; + else return false; + v = (v << 4) | std::uint32_t(d); + } + out = v; + return true; +} +inline bool dec_ll(std::string_view text, long long& out) { + if (text.empty() || text.size() > 18) return false; + long long v = 0; + for (const char c : text) { + if (c < '0' || c > '9') return false; + v = v * 10 + (c - '0'); + } + out = v; + return true; +} +} // namespace detail + +// One cache line; nullopt for a line that is not one (another version, damaged). +inline std::optional parse_entry(std::string_view line) { + while (!line.empty() && (line.back() == '\r' || line.back() == '\n' || line.back() == ' ')) line.remove_suffix(1); + if (line.substr(0, kCacheTag.size()) != kCacheTag) return std::nullopt; + line.remove_prefix(kCacheTag.size()); + CacheEntry e; + unsigned seen = 0; + while (!line.empty()) { + if (line.front() != ' ') return std::nullopt; + line.remove_prefix(1); + const std::size_t end = (std::min)(line.find(' '), line.size()); + const std::string_view field = line.substr(0, end); + line.remove_prefix(end); + const std::size_t eq = field.find('='); + if (eq == std::string_view::npos) return std::nullopt; + const std::string_view name = field.substr(0, eq), value = field.substr(eq + 1); + long long n = 0; + if (name == "vendor") { if (!detail::hex_u32(value, e.key.vendor)) return std::nullopt; seen |= 1; } + else if (name == "device") { if (!detail::hex_u32(value, e.key.device)) return std::nullopt; seen |= 2; } + else if (name == "driver") { if (!detail::hex_u32(value, e.key.driver)) return std::nullopt; seen |= 4; } + else if (name == "uuid") { + if (value.size() != 32) return std::nullopt; + for (int i = 0; i < 16; ++i) { + std::uint32_t byte = 0; + if (!detail::hex_u32(value.substr(std::size_t(2 * i), 2), byte)) return std::nullopt; + e.key.uuid[i] = std::uint8_t(byte); + } + seen |= 8; + } else if (name == "outcome") { + const auto o = parse_outcome(value); + if (!o) return std::nullopt; + e.verdict.outcome = *o; + seen |= 16; + } else if (name == "quick") { + if (!detail::dec_ll(value, n) || n > 0xffffffffLL) return std::nullopt; + e.verdict.quick = unsigned(n); + } else if (name == "max_quick_ds") { if (!detail::dec_ll(value, n)) return std::nullopt; e.verdict.max_quick_ms = double(n) / 10; } + else if (name == "create_ds") { if (!detail::dec_ll(value, n)) return std::nullopt; e.verdict.create_ms = double(n) / 10; } + else if (name == "slow_ds") { if (!detail::dec_ll(value, n)) return std::nullopt; e.verdict.slow_ms = double(n) / 10; } + // An unknown field is skipped: a later version may add one. + } + if (seen != 31) return std::nullopt; + return e; +} + +// The entry for `key` in a cache file's text, if it has one. +inline std::optional find_entry(std::string_view text, const CacheKey& key) { + std::optional found; + while (!text.empty()) { + const std::size_t end = (std::min)(text.find('\n'), text.size()); + if (const auto e = parse_entry(text.substr(0, end)); e && same_key(e->key, key)) found = e; // the last wins + text.remove_prefix((std::min)(end + 1, text.size())); + } + return found; +} + +// The text with `entry` in place of any line for its key, every other valid line kept, damaged lines dropped. +inline std::string replace_entry(std::string_view text, const CacheEntry& entry) { + std::string out; + while (!text.empty()) { + const std::size_t end = (std::min)(text.find('\n'), text.size()); + if (const auto e = parse_entry(text.substr(0, end)); e && !same_key(e->key, entry.key)) + out += format_entry(*e) + "\n"; + text.remove_prefix((std::min)(end + 1, text.size())); + } + out += format_entry(entry) + "\n"; + return out; +} + +// LEONIDA_COMPILE_GATE_RECALIBRATE=1: measure again and write over the cached verdict. +inline bool recalibrate(const char* value) { return value && !std::strcmp(value, "1"); } + +// ---- The slow pipeline: a compute shader, SPIR-V 1.0, written here (no game data, no shader compiler). +// +// One storage buffer (set 0, binding 0) of floats: a = buf[0], b = buf[1] at run time, so nothing folds; then +// `statements` times +// a = fract(sin(a * k1 + b) * 43758.5453); +// if (a > k2) b = b * 0.97 + a * k1; else b = b - a * k2; +// with k1 and k2 made from the specialization constant 0 (the seed), and buf[2] = a + b. Each seed is a different +// program to the driver, so neither a pipeline cache nor the driver's own shader cache can answer the create. It is +// never dispatched. +class SpirvWriter { +public: + std::uint32_t id() { return next_++; } + void op(std::uint32_t opcode, std::initializer_list operands) { + words_.push_back(std::uint32_t(operands.size() + 1) << 16 | opcode); + words_.insert(words_.end(), operands.begin(), operands.end()); + } + void op_string(std::uint32_t opcode, std::initializer_list before, const char* text, + std::initializer_list after = {}) { + const std::size_t length = std::strlen(text); + const std::size_t string_words = length / 4 + 1; + words_.push_back(std::uint32_t(1 + before.size() + string_words + after.size()) << 16 | opcode); + words_.insert(words_.end(), before.begin(), before.end()); + for (std::size_t w = 0; w < string_words; ++w) { + std::uint32_t word = 0; + for (std::size_t b = 0; b < 4; ++b) { + const std::size_t i = w * 4 + b; + if (i < length) word |= std::uint32_t(std::uint8_t(text[i])) << (8 * b); + } + words_.push_back(word); + } + words_.insert(words_.end(), after.begin(), after.end()); + } + std::vector finish() { + std::vector out{0x07230203u, 0x00010000u, 0u, next_, 0u}; + out.insert(out.end(), words_.begin(), words_.end()); + return out; + } + +private: + std::vector words_; + std::uint32_t next_ = 1; +}; + +inline std::uint32_t float_bits(float f) { + std::uint32_t u; + std::memcpy(&u, &f, sizeof u); + return u; +} + +inline std::vector slow_compute_spirv(std::uint32_t statements) { + enum : std::uint32_t { + OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, + OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, + OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypePointer = 32, OpTypeFunction = 33, OpConstant = 43, + OpSpecConstant = 50, OpFunction = 54, OpFunctionEnd = 56, OpVariable = 59, OpLoad = 61, OpStore = 62, + OpAccessChain = 65, OpDecorate = 71, OpMemberDecorate = 72, OpConvertUToF = 112, OpFAdd = 129, + OpFSub = 131, OpFMul = 133, OpFOrdGreaterThan = 186, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, + OpBranchConditional = 250, OpReturn = 253, + }; + enum : std::uint32_t { Uniform = 2, Function = 7, GLSLSin = 13, GLSLFract = 10 }; + SpirvWriter w; + const std::uint32_t glsl = w.id(), main_fn = w.id(), void_t = w.id(), fn_t = w.id(), float_t = w.id(), + uint_t = w.id(), int_t = w.id(), bool_t = w.id(), seed = w.id(), array_t = w.id(), + block_t = w.id(), block_ptr = w.id(), buf = w.id(), ufloat_ptr = w.id(), ffloat_ptr = w.id(), + i0 = w.id(), i1 = w.id(), i2 = w.id(), c_big = w.id(), c_097 = w.id(); + constexpr std::uint32_t kConstants = 13; + std::uint32_t ka[kConstants], kb[kConstants]; + for (std::uint32_t i = 0; i < kConstants; ++i) ka[i] = w.id(), kb[i] = w.id(); + + w.op(OpCapability, {1}); // Shader + w.op_string(OpExtInstImport, {glsl}, "GLSL.std.450"); + w.op(OpMemoryModel, {0, 1}); + w.op_string(OpEntryPoint, {5, main_fn}, "main"); + w.op(OpExecutionMode, {main_fn, 17, 1, 1, 1}); // LocalSize 1 1 1 + w.op(OpDecorate, {seed, 1, 0}); // SpecId 0 + w.op(OpDecorate, {array_t, 6, 4}); // ArrayStride 4 + w.op(OpMemberDecorate, {block_t, 0, 35, 0}); // Offset 0 + w.op(OpDecorate, {block_t, 3}); // BufferBlock + w.op(OpDecorate, {buf, 34, 0}); // DescriptorSet 0 + w.op(OpDecorate, {buf, 33, 0}); // Binding 0 + w.op(OpTypeVoid, {void_t}); + w.op(OpTypeFunction, {fn_t, void_t}); + w.op(OpTypeFloat, {float_t, 32}); + w.op(OpTypeInt, {uint_t, 32, 0}); + w.op(OpTypeInt, {int_t, 32, 1}); + w.op(OpTypeBool, {bool_t}); + w.op(OpTypeRuntimeArray, {array_t, float_t}); + w.op(OpTypeStruct, {block_t, array_t}); + w.op(OpTypePointer, {block_ptr, Uniform, block_t}); + w.op(OpTypePointer, {ufloat_ptr, Uniform, float_t}); + w.op(OpTypePointer, {ffloat_ptr, Function, float_t}); + w.op(OpSpecConstant, {uint_t, seed, 0}); + w.op(OpConstant, {int_t, i0, 0}); + w.op(OpConstant, {int_t, i1, 1}); + w.op(OpConstant, {int_t, i2, 2}); + w.op(OpConstant, {float_t, c_big, float_bits(43758.5453f)}); + w.op(OpConstant, {float_t, c_097, float_bits(0.97f)}); + for (std::uint32_t i = 0; i < kConstants; ++i) { + w.op(OpConstant, {float_t, ka[i], float_bits(0.0013f * float(i + 1))}); + w.op(OpConstant, {float_t, kb[i], float_bits(0.5f + 0.11f * float(i))}); + } + w.op(OpVariable, {block_ptr, buf, Uniform}); + + w.op(OpFunction, {void_t, main_fn, 0, fn_t}); + w.op(OpLabel, {w.id()}); + const std::uint32_t va = w.id(), vb = w.id(); + w.op(OpVariable, {ffloat_ptr, va, Function}); + w.op(OpVariable, {ffloat_ptr, vb, Function}); + const std::uint32_t p0 = w.id(), x = w.id(), p1 = w.id(), y = w.id(), seedf = w.id(); + w.op(OpAccessChain, {ufloat_ptr, p0, buf, i0, i0}); + w.op(OpLoad, {float_t, x, p0}); + w.op(OpAccessChain, {ufloat_ptr, p1, buf, i0, i1}); + w.op(OpLoad, {float_t, y, p1}); + w.op(OpConvertUToF, {float_t, seedf, seed}); + w.op(OpStore, {va, x}); + w.op(OpStore, {vb, y}); + for (std::uint32_t i = 0; i < statements; ++i) { + const std::uint32_t c1 = i % kConstants, c2 = (i * 7 + 3) % kConstants; + const std::uint32_t k1m = w.id(), k1 = w.id(), k2m = w.id(), k2 = w.id(); + w.op(OpFMul, {float_t, k1m, seedf, ka[c1]}); + w.op(OpFAdd, {float_t, k1, k1m, kb[c1]}); + w.op(OpFMul, {float_t, k2m, seedf, ka[c2]}); + w.op(OpFAdd, {float_t, k2, k2m, kb[c2]}); + const std::uint32_t a = w.id(), b = w.id(), t1 = w.id(), t2 = w.id(), s = w.id(), m = w.id(), f = w.id(); + w.op(OpLoad, {float_t, a, va}); + w.op(OpLoad, {float_t, b, vb}); + w.op(OpFMul, {float_t, t1, a, k1}); + w.op(OpFAdd, {float_t, t2, t1, b}); + w.op(OpExtInst, {float_t, s, glsl, GLSLSin, t2}); + w.op(OpFMul, {float_t, m, s, c_big}); + w.op(OpExtInst, {float_t, f, glsl, GLSLFract, m}); + w.op(OpStore, {va, f}); + const std::uint32_t cond = w.id(), then_l = w.id(), else_l = w.id(), merge_l = w.id(); + w.op(OpFOrdGreaterThan, {bool_t, cond, f, k2}); + w.op(OpSelectionMerge, {merge_l, 0}); + w.op(OpBranchConditional, {cond, then_l, else_l}); + w.op(OpLabel, {then_l}); + const std::uint32_t tb = w.id(), tf = w.id(), tsum = w.id(); + w.op(OpFMul, {float_t, tb, b, c_097}); + w.op(OpFMul, {float_t, tf, f, k1}); + w.op(OpFAdd, {float_t, tsum, tb, tf}); + w.op(OpStore, {vb, tsum}); + w.op(OpBranch, {merge_l}); + w.op(OpLabel, {else_l}); + const std::uint32_t ef = w.id(), ediff = w.id(); + w.op(OpFMul, {float_t, ef, f, k2}); + w.op(OpFSub, {float_t, ediff, b, ef}); + w.op(OpStore, {vb, ediff}); + w.op(OpBranch, {merge_l}); + w.op(OpLabel, {merge_l}); + } + const std::uint32_t fa = w.id(), fb = w.id(), sum = w.id(), p2 = w.id(); + w.op(OpLoad, {float_t, fa, va}); + w.op(OpLoad, {float_t, fb, vb}); + w.op(OpFAdd, {float_t, sum, fa, fb}); + w.op(OpAccessChain, {ufloat_ptr, p2, buf, i0, i2}); + w.op(OpStore, {p2, sum}); + w.op(OpReturn, {}); + w.op(OpFunctionEnd, {}); + return w.finish(); +} + +} // namespace compile_gate_policy +} // namespace leonida diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 6f70390995..c8545f338e 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -177,6 +177,7 @@ void start_title_peek(std::uint8_t* base) { } // namespace #include "base_reservation.h" +#include "compile_gate_policy.h" #include "code_hooks.h" #include "cpu_emulation.h" #include "host_cpu.h" @@ -390,6 +391,9 @@ int wmain(int argc, wchar_t** argv) { if (argc > 1 && std::wstring(argv[1]) == L"--precompile-pipelines") return precompile_main(argc, argv); if (argc > 1 && std::wstring(argv[1]) == L"--compile-server") return compile_server_main(argc, argv); #endif + // The title's process (not a build host above): LEONIDA_COMPILE_GATE=auto may calibrate the driver when the device + // is made (src/compile_gate_policy.h). + leonida::compile_gate_policy::calibration_allowed = true; std::filesystem::path image, game_dir, overlay_dir, mods_dir; uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash int archetype_lookup_arg = 0; diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h index 17f4209344..3c49fce8d2 100644 --- a/runtime/src/vulkan_device_fault.h +++ b/runtime/src/vulkan_device_fault.h @@ -2,6 +2,7 @@ #include +#include "compile_gate_policy.h" #include "vulkan_device_markers.h" #include @@ -482,8 +483,10 @@ class SubmitMutex { // device was lost; waiting here starves the title as long, but keeps the device. Graphics creates pass the gate // since this split (adaptive and LEONIDA_COMPILE_GATE=1; the classic gate, as before, only compute ones). On a // device loss, report_creates_on_loss names the creates in the driver and the verdicts. - // classic (the default): the gate as on main before the adaptive one, compute creates only, no limit, no probes. - enum class GateMode { off, classic, adaptive, always }; + // classic: the gate as on main before the adaptive one, compute creates only, no limit, no probes. The default + // (`auto`) is adaptive where the calibration at device creation saw the driver not hold a submission behind a + // create, and classic elsewhere (compile_gate_policy.h). + using GateMode = CompileGateMode; enum class GateVerdict { pending, driver_does_not_hold, driver_holds }; static constexpr std::int64_t kProbeQuickMs = 250; static constexpr std::int64_t kProbeHeldMs = 2000; @@ -531,18 +534,37 @@ class SubmitMutex { }; // LEONIDA_COMPILE_GATE: 0 off, 1 always (both kinds, and compute builds hold the submit lock, compute_driver_turn - // in shims/d3d12_vulkan_device.cpp), `adaptive` the adaptive gate, anything else (unset) classic. Classic stays - // the default until the adaptive gate has run on a driver that holds submissions (630.20): there its first probe - // of a kind enters the driver after the probe budget and loses the device if the create stays 10 s more. - static GateMode compile_gate_mode() { - static const GateMode mode = [] { + // in shims/d3d12_vulkan_device.cpp), `adaptive` the adaptive gate, `classic` the classic one, anything else + // classic, and unset or `auto` what the calibration at device creation finds (compile_gate_policy.h): adaptive + // where submissions came back quickly beside a create, classic where one was held and wherever it could not tell. + // The adaptive gate is not forced on everywhere because of what it costs on a driver that holds submissions + // (630.20): there its first probe of a kind enters the driver after the probe budget and loses the device if the + // create stays 10 s more. Read once. + static compile_gate_policy::Setting compile_gate_setting() { + static const compile_gate_policy::Setting setting = [] { const char* value = std::getenv("LEONIDA_COMPILE_GATE"); - if (value && !std::strcmp(value, "0")) return GateMode::off; - if (value && !std::strcmp(value, "1")) return GateMode::always; - if (value && !std::strcmp(value, "adaptive")) return GateMode::adaptive; - return GateMode::classic; + const compile_gate_policy::ParsedSetting parsed = compile_gate_policy::parse_setting(value); + if (parsed.unknown) + std::fprintf(stderr, "[rt] compile-gate: LEONIDA_COMPILE_GATE=%s is none of auto, classic, adaptive, " + "0, 1; classic\n", value); + return parsed.setting; }(); - return mode; + return setting; + } + // The gate in use. With `auto`, classic until decide_auto_gate: the device calls it once, after the calibration + // and before it creates the VulkanContext (and its SubmitMutex), so nothing is gated before the decision, and + // anything that were would get the classic gate, as before `auto`. + static GateMode compile_gate_mode() { return gate_mode_slot().load(std::memory_order_acquire); } + // With `auto`: the gate the calibration chose (adaptive or classic), for the rest of the process; the first call + // decides. A forced setting keeps its mode. Returns the gate in use. + static GateMode decide_auto_gate(GateMode mode) { + if (compile_gate_setting() != compile_gate_policy::Setting::automatic) return compile_gate_mode(); + static std::once_flag once; + std::call_once(once, [mode] { + gate_mode_slot().store(mode == GateMode::adaptive ? GateMode::adaptive : GateMode::classic, + std::memory_order_release); + }); + return compile_gate_mode(); } static bool compile_gate_enabled() { return compile_gate_mode() != GateMode::off; } // Whether graphics (and mesh) creates pass the gate: not in the classic gate, where only compute ones did. @@ -559,45 +581,63 @@ class SubmitMutex { std::int64_t wait_ms; std::int64_t probe_ms; }; + // One set per mode, each read and logged once: with `auto` the mode is known only once the driver is. static GateDefaults gate_defaults() { - static const GateDefaults defaults = [] { - const auto read = [](const char* name, std::int64_t fallback) -> std::int64_t { - const char* value = std::getenv(name); - if (!value || !*value) return fallback; - char* end = nullptr; - const long long n = std::strtoll(value, &end, 10); - if (end && !*end && n >= 0) return n; - std::fprintf(stderr, "[rt] compile-gate: %s=%s is not a number of milliseconds; ignored\n", name, value); - return fallback; - }; - const GateMode mode = compile_gate_mode(); - const bool always = mode == GateMode::always; - const bool adaptive = mode == GateMode::adaptive; // classic and always: no limit by default - const std::int64_t wait_ms = read("LEONIDA_COMPILE_GATE_WAIT_MS", adaptive ? kDefaultGateWaitMs : 0); - const GateDefaults d{wait_ms, read("LEONIDA_COMPILE_GATE_PROBE_MS", wait_ms ? kDefaultProbeBudgetMs : 0)}; - if (mode == GateMode::classic && d.wait_ms) - std::fprintf(stderr, "[rt] compile-gate: classic (compute creates); a submission waits at most %lld ms " - "for them to leave the driver (LEONIDA_COMPILE_GATE_WAIT_MS; " - "LEONIDA_COMPILE_GATE=adaptive for the adaptive gate)\n", - static_cast(d.wait_ms)); - else if (always && d.wait_ms) - std::fprintf(stderr, "[rt] compile-gate: always (LEONIDA_COMPILE_GATE=1); a submission waits at most " - "%lld ms for pipeline creates to leave the driver (LEONIDA_COMPILE_GATE_WAIT_MS)\n", - static_cast(d.wait_ms)); - else if (always) - std::fprintf(stderr, "[rt] compile-gate: always (LEONIDA_COMPILE_GATE=1); a submission waits for " - "pipeline creates to leave the driver, however long they take\n"); - else if (adaptive) - std::fprintf(stderr, "[rt] compile-gate: adaptive (LEONIDA_COMPILE_GATE=adaptive), off once " - "submissions come back quickly with a create in the driver; a submission goes " - "ahead after %lld ms of waiting (0: no limit, LEONIDA_COMPILE_GATE_WAIT_MS) or, " - "until that is known, once the waits of the last " - "%lld s add up to %lld ms (0: never, LEONIDA_COMPILE_GATE_PROBE_MS)\n", - static_cast(d.wait_ms), static_cast(kProbeWindowMs / 1000), - static_cast(d.probe_ms)); + switch (compile_gate_mode()) { + case GateMode::off: { + static const GateDefaults d = make_gate_defaults(GateMode::off); return d; - }(); - return defaults; + } + case GateMode::adaptive: { + static const GateDefaults d = make_gate_defaults(GateMode::adaptive); + return d; + } + case GateMode::always: { + static const GateDefaults d = make_gate_defaults(GateMode::always); + return d; + } + case GateMode::classic: break; + } + static const GateDefaults d = make_gate_defaults(GateMode::classic); + return d; + } + static GateDefaults make_gate_defaults(GateMode mode) { + const auto read = [](const char* name, std::int64_t fallback) -> std::int64_t { + const char* value = std::getenv(name); + if (!value || !*value) return fallback; + char* end = nullptr; + const long long n = std::strtoll(value, &end, 10); + if (end && !*end && n >= 0) return n; + std::fprintf(stderr, "[rt] compile-gate: %s=%s is not a number of milliseconds; ignored\n", name, value); + return fallback; + }; + const bool always = mode == GateMode::always; + const bool adaptive = mode == GateMode::adaptive; // classic and always: no limit by default + const std::int64_t wait_ms = read("LEONIDA_COMPILE_GATE_WAIT_MS", adaptive ? kDefaultGateWaitMs : 0); + const GateDefaults d{wait_ms, read("LEONIDA_COMPILE_GATE_PROBE_MS", wait_ms ? kDefaultProbeBudgetMs : 0)}; + if (mode == GateMode::classic && d.wait_ms) + std::fprintf(stderr, "[rt] compile-gate: classic (compute creates); a submission waits at most %lld ms " + "for them to leave the driver (LEONIDA_COMPILE_GATE_WAIT_MS; " + "LEONIDA_COMPILE_GATE=adaptive for the adaptive gate)\n", + static_cast(d.wait_ms)); + else if (always && d.wait_ms) + std::fprintf(stderr, "[rt] compile-gate: always (LEONIDA_COMPILE_GATE=1); a submission waits at most " + "%lld ms for pipeline creates to leave the driver (LEONIDA_COMPILE_GATE_WAIT_MS)\n", + static_cast(d.wait_ms)); + else if (always) + std::fprintf(stderr, "[rt] compile-gate: always (LEONIDA_COMPILE_GATE=1); a submission waits for " + "pipeline creates to leave the driver, however long they take\n"); + else if (adaptive) + std::fprintf(stderr, "[rt] compile-gate: adaptive (%s), off once " + "submissions come back quickly with a create in the driver; a submission goes " + "ahead after %lld ms of waiting (0: no limit, LEONIDA_COMPILE_GATE_WAIT_MS) or, " + "until that is known, once the waits of the last " + "%lld s add up to %lld ms (0: never, LEONIDA_COMPILE_GATE_PROBE_MS)\n", + compile_gate_setting() == compile_gate_policy::Setting::automatic + ? "auto" : "LEONIDA_COMPILE_GATE=adaptive", + static_cast(d.wait_ms), static_cast(kProbeWindowMs / 1000), + static_cast(d.probe_ms)); + return d; } static std::int64_t default_gate_wait_limit_ms() { return gate_defaults().wait_ms; } static std::int64_t default_gate_probe_budget_ms() { return gate_defaults().probe_ms; } @@ -1042,6 +1082,12 @@ class SubmitMutex { static_cast(stats_.submit_max_ms)); } + // The gate in use: the forced setting's mode, or with `auto` classic until decide_auto_gate. + static std::atomic& gate_mode_slot() { + static std::atomic slot{compile_gate_policy::forced_mode(compile_gate_setting())}; + return slot; + } + std::mutex mutex_; std::atomic owner_{0}; std::atomic since_{0}; diff --git a/runtime/test/compile_gate_policy_test.cpp b/runtime/test/compile_gate_policy_test.cpp new file mode 100644 index 0000000000..bab8a3adfa --- /dev/null +++ b/runtime/test/compile_gate_policy_test.cpp @@ -0,0 +1,235 @@ +// LEONIDA_COMPILE_GATE=auto without a GPU (src/compile_gate_policy.h): the setting, NVIDIA's driver version, the +// verdict over a calibration's timings, the cache file and the slow pipeline's SPIR-V. +#include "../src/compile_gate_policy.h" + +#include +#include +#include + +namespace { + +int failures = 0; + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + ++failures; \ + } \ + } while (0) + +using namespace leonida::compile_gate_policy; +using leonida::CompileGateMode; + +void settings() { + CHECK(parse_setting(nullptr).setting == Setting::automatic); + CHECK(parse_setting("").setting == Setting::automatic); + CHECK(parse_setting("auto").setting == Setting::automatic); + CHECK(parse_setting("0").setting == Setting::off); + CHECK(parse_setting("1").setting == Setting::always); + CHECK(parse_setting("adaptive").setting == Setting::adaptive); + CHECK(parse_setting("classic").setting == Setting::classic); + CHECK(!parse_setting("classic").unknown); + // Unknown values are classic, as before `auto`: never the adaptive gate. + CHECK(parse_setting("2").setting == Setting::classic && parse_setting("2").unknown); + CHECK(parse_setting("Adaptive").setting == Setting::classic); + // Forced settings name their mode; auto is classic until the calibration decides. + CHECK(forced_mode(Setting::automatic) == CompileGateMode::classic); + CHECK(forced_mode(Setting::classic) == CompileGateMode::classic); + CHECK(forced_mode(Setting::adaptive) == CompileGateMode::adaptive); + CHECK(forced_mode(Setting::always) == CompileGateMode::always); + CHECK(forced_mode(Setting::off) == CompileGateMode::off); + CHECK(recalibrate("1") && !recalibrate("0") && !recalibrate(nullptr) && !recalibrate("")); +} + +void nvidia_versions() { + constexpr std::uint32_t v621_40 = encode_nvidia(621, 40); + static_assert(decode_nvidia(v621_40).major == 621 && decode_nvidia(v621_40).minor == 40); + CHECK(v621_40 == ((621u << 22) | (40u << 14))); + CHECK(decode_nvidia(encode_nvidia(610, 88)).major == 610 && decode_nvidia(encode_nvidia(610, 88)).minor == 88); + CHECK(decode_nvidia(encode_nvidia(630, 20) | 0x3fffu).minor == 20); // the low 14 bits are not the minor + CHECK(describe_driver(kNvidiaVendorId, encode_nvidia(621, 40)) == "NVIDIA 621.40"); + CHECK(describe_driver(kNvidiaVendorId, encode_nvidia(630, 2)) == "NVIDIA 630.02"); + CHECK(describe_driver(kAmdVendorId, 0x00802001u) == "AMD driver 0x00802001"); + CHECK(describe_driver(0, 0) == "an unknown GPU"); + CHECK(describe_driver(0x10005, 1) == "vendor 0x10005 driver 0x00000001"); +} + +Trial quick_trial(double create_ms, double every_ms, double each_ms) { + Trial t; + t.create_ms = create_ms; + for (double s = 20; s < create_ms; s += every_ms) t.samples.push_back({s, s + each_ms}); + return t; +} + +void verdicts() { + // 621.40-like: submissions come back in a couple of ms all through a 900 ms create. + { + const Verdict v = judge(quick_trial(900, 10, 2)); + CHECK(v.outcome == Outcome::adaptive); + CHECK(v.quick > 50); + CHECK(v.max_quick_ms == 2); + CHECK(mode_for(v.outcome) == CompileGateMode::adaptive); + } + // 630.20-like: the first submission is held until the create leaves. + { + Trial t; + t.create_ms = 1200; + t.samples = {{20, 1205}, {1210, 1212}}; + const Verdict v = judge(t); + CHECK(v.outcome == Outcome::holds); + CHECK(v.slow_ms == 1185); + CHECK(mode_for(v.outcome) == CompileGateMode::classic); + } + // A hold outweighs any number of quick submissions (the driver may lock for only part of the create). + { + Trial t = quick_trial(600, 10, 1); + t.create_ms = 1500; + t.samples.push_back({700, 1510}); + CHECK(judge(t).outcome == Outcome::holds); + } + // Too fast to tell: the next trial is larger. + { + const Verdict v = judge(quick_trial(120, 10, 1)); + CHECK(v.outcome == Outcome::too_fast); + CHECK(mode_for(v.outcome) == CompileGateMode::classic); + } + // A slow submission that did not come back with the create (something else on the GPU): unclear, classic. + { + Trial t = quick_trial(1000, 10, 1); + t.samples.push_back({300, 700}); + CHECK(judge(t).outcome == Outcome::unclear); + CHECK(mode_for(Outcome::unclear) == CompileGateMode::classic); + } + // Quick ones only at the start: not enough to say the create was still in the driver later. + { + Trial t; + t.create_ms = 1000; + t.samples = {{20, 21}, {30, 31}, {40, 41}, {50, 51}}; + CHECK(judge(t).outcome == Outcome::unclear); + } + // Submissions that came back as the create left, or that entered after it, tell nothing. + { + Trial t; + t.create_ms = 1000; + t.samples = {{600, 605}, {990, 995}, {1001, 1003}}; + const Verdict v = judge(t); + CHECK(v.quick == 1); + CHECK(v.outcome == Outcome::unclear); + } + // No samples at all: unclear (or too fast), never adaptive. + { + Trial t; + t.create_ms = 2000; + CHECK(judge(t).outcome == Outcome::unclear); + } + CHECK(next_statements(2000, 100, 32000) == 16000); // at most 8x + CHECK(next_statements(2000, 700, 32000) == 4000); // at least 2x + CHECK(next_statements(2000, 200, 32000) == 8000); // towards 800 ms + CHECK(next_statements(20000, 100, 32000) == 32000); // capped + CHECK(describe_verdict(judge(quick_trial(900, 10, 2))).find("submissions came back in <= 2.0 ms beside a 900 ms " + "create") != std::string::npos); +} + +CacheKey key_a() { + CacheKey k; + k.vendor = kNvidiaVendorId; + k.device = 0x2820; + k.driver = encode_nvidia(621, 40); + for (int i = 0; i < 16; ++i) k.uuid[i] = std::uint8_t(i * 17); + return k; +} + +void cache() { + CacheEntry e; + e.key = key_a(); + e.verdict.outcome = Outcome::adaptive; + e.verdict.quick = 42; + e.verdict.max_quick_ms = 3.14; + e.verdict.create_ms = 912.0; + const std::string line = format_entry(e); + CHECK(line.find("outcome=adaptive") != std::string::npos); + CHECK(line.find("driver=9b4a0000") != std::string::npos); + const auto back = parse_entry(line); + CHECK(back && same_key(back->key, e.key)); + CHECK(back && back->verdict.outcome == Outcome::adaptive && back->verdict.quick == 42); + CHECK(back && back->verdict.max_quick_ms == 3.1 && back->verdict.create_ms == 912.0); + CHECK(parse_entry(line + "\r\n").has_value()); + CHECK(parse_entry(line + " later_field=7").has_value()); // a later version's field is skipped + + // Damaged or foreign lines are not entries. + CHECK(!parse_entry("")); + CHECK(!parse_entry("compile-gate-calibration v2 vendor=10de")); + CHECK(!parse_entry(line.substr(0, line.size() / 2))); + std::string bad = line; + bad.replace(bad.find("outcome=adaptive"), 16, "outcome=maybe"); + CHECK(!parse_entry(bad)); + std::string bad_uuid = line; + bad_uuid.replace(bad_uuid.find("uuid=") + 5, 2, "zz"); + CHECK(!parse_entry(bad_uuid)); + + // Another driver (630.20 on the same GPU) is another key. + CacheEntry other = e; + other.key.driver = encode_nvidia(630, 20); + other.verdict = {}; + other.verdict.outcome = Outcome::holds; + other.verdict.slow_ms = 1185; + other.verdict.create_ms = 1200; + std::string text = replace_entry("", e); + text = replace_entry("garbage line\n" + text, other); + CHECK(text.find("garbage") == std::string::npos); + CHECK(find_entry(text, e.key) && find_entry(text, e.key)->verdict.outcome == Outcome::adaptive); + CHECK(find_entry(text, other.key) && find_entry(text, other.key)->verdict.outcome == Outcome::holds); + CacheKey unknown = key_a(); + unknown.uuid[3] ^= 1; + CHECK(!find_entry(text, unknown)); + // Recalibrating writes over the entry for the key, keeping the others. + CacheEntry again = e; + again.verdict.outcome = Outcome::unclear; + text = replace_entry(text, again); + CHECK(find_entry(text, e.key)->verdict.outcome == Outcome::unclear); + CHECK(find_entry(text, other.key).has_value()); + std::size_t lines = 0; + for (const char c : text) lines += c == '\n'; + CHECK(lines == 2); +} + +void spirv() { + const auto small = slow_compute_spirv(10); + const auto big = slow_compute_spirv(1000); + CHECK(small.size() > 5 && small[0] == 0x07230203u && small[1] == 0x00010000u); + CHECK(big.size() > small.size() * 50); + // Every instruction's word count walks exactly to the end, and no id reaches the bound. + for (const auto* words : {&small, &big}) { + std::size_t at = 5; + bool ok = true; + while (at < words->size()) { + const std::uint32_t count = (*words)[at] >> 16; + if (!count) { + ok = false; + break; + } + at += count; + } + CHECK(ok && at == words->size()); + CHECK((*words)[3] > 20); + } + // The same size gives the same program: the seed (specialization constant 0) is what varies it. + CHECK(slow_compute_spirv(10) == small); +} + +} // namespace + +int main() { + settings(); + nvidia_versions(); + verdicts(); + cache(); + spirv(); + if (failures) { + std::fprintf(stderr, "compile_gate_policy_test: %d failure(s)\n", failures); + return 1; + } + std::printf("compile_gate_policy_test: ok\n"); + return 0; +} diff --git a/runtime/test/vk_compile_gate_calibration_test.cpp b/runtime/test/vk_compile_gate_calibration_test.cpp new file mode 100644 index 0000000000..fc0c18cd7c --- /dev/null +++ b/runtime/test/vk_compile_gate_calibration_test.cpp @@ -0,0 +1,71 @@ +// The LEONIDA_COMPILE_GATE=auto calibration (src/compile_gate_calibration.h) on this machine's GPU: it must finish +// within kBoundMs and, on NVIDIA, reach a verdict (adaptive or holds) rather than give up. On NVIDIA 621.40 (an RTX +// 4070 Laptop) submissions were measured never to wait for a create, so there the verdict must be adaptive; +// LEONIDA_EXPECT_COMPILE_GATE=adaptive|classic states the expected gate on any other GPU. 77 without a device. +#include "vk_test_device.h" + +#include "../src/compile_gate_calibration.h" + +#include +#include +#include +#include + +namespace { +constexpr double kBoundMs = 20000; +} + +int main() { + namespace policy = leonida::compile_gate_policy; + vktest::Device device; + if (!device.create()) { + std::printf("vk_compile_gate_calibration_test: SKIP (no Vulkan device)\n"); + return 77; + } + VkPhysicalDeviceProperties props{}; + device.instance_fn("vkGetPhysicalDeviceProperties")(device.physical, &props); + const std::string driver = policy::describe_driver(props.vendorID, props.driverVersion); + std::printf("vk_compile_gate_calibration_test: %s, %s\n", props.deviceName, driver.c_str()); + if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) { + std::printf("vk_compile_gate_calibration_test: SKIP (a CPU device: the runtime does not calibrate those)\n"); + return 77; + } + const auto seed = static_cast(std::chrono::steady_clock::now().time_since_epoch().count()) | 1u; + const auto result = leonida::compile_gate_calibration::calibrate(device.device_proc, device.device, device.queue, + device.family, seed, "[test]"); + std::printf("vk_compile_gate_calibration_test: %s after %u trial(s), %u statements, %.0f ms: %s\n", + result.ok ? policy::outcome_name(result.verdict.outcome) : "failed", result.trials, + unsigned(result.statements), result.total_ms, + result.ok ? policy::describe_verdict(result.verdict).c_str() : result.error.c_str()); + int failures = 0; + if (!result.ok) { + std::fprintf(stderr, "FAIL: calibration failed: %s\n", result.error.c_str()); + ++failures; + } + if (result.total_ms > kBoundMs) { + std::fprintf(stderr, "FAIL: calibration took %.0f ms (bound %.0f ms)\n", result.total_ms, kBoundMs); + ++failures; + } + const bool decided = + result.verdict.outcome == policy::Outcome::adaptive || result.verdict.outcome == policy::Outcome::holds; + if (result.ok && props.vendorID == policy::kNvidiaVendorId && !decided) { + std::fprintf(stderr, "FAIL: no verdict on NVIDIA (%s)\n", policy::outcome_name(result.verdict.outcome)); + ++failures; + } + const char* expect = std::getenv("LEONIDA_EXPECT_COMPILE_GATE"); + const bool measured_621_40 = props.vendorID == policy::kNvidiaVendorId && + policy::decode_nvidia(props.driverVersion).major == 621 && + policy::decode_nvidia(props.driverVersion).minor == 40; + if (!expect && measured_621_40) expect = "adaptive"; + if (result.ok && expect) { + const char* got = policy::mode_for(result.verdict.outcome) == leonida::CompileGateMode::adaptive ? "adaptive" + : "classic"; + if (std::strcmp(expect, got)) { + std::fprintf(stderr, "FAIL: expected the %s gate, the calibration gives %s\n", expect, got); + ++failures; + } + } + if (failures) return 1; + std::printf("vk_compile_gate_calibration_test: ok\n"); + return 0; +} From e31f50bbcce7bce2fae5746aab1b23c721c92a5c Mon Sep 17 00:00:00 2001 From: OreoFR <29048345+OreoFR@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:49:07 +0100 Subject: [PATCH 2/2] compile gate calibration: keep no unclear verdict, drain a timed-out fence Review of #2462: - An unclear calibration (a slow submission the create does not explain) is no longer written to compile_gate_calibration.txt, and an unclear line an earlier build wrote is not read as a cached verdict: the next launch measures again instead of staying classic until the driver changes (compile_gate_policy::cache_verdict, tested in compile_gate_policy_test). - After a fence wait that fails, the fence and command pool are destroyed only once the pending submission's fence signals (up to 60 s); on a lost device or if it still has not, they are left alive. The verdict stays classic. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 5 ++++- runtime/README.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 4 +++- runtime/src/compile_gate_calibration.h | 21 ++++++++++++++++++--- runtime/src/compile_gate_policy.h | 13 +++++++++++-- runtime/test/compile_gate_policy_test.cpp | 14 ++++++++++++-- 6 files changed, 49 insertions(+), 10 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 2e0469590a..a004c798fd 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3003,7 +3003,10 @@ submitting thread; at the maintainers' decision it was replaced by this one when within 200 ms of the create leaving: the driver holds submissions, classic. A create under 300 ms is tried again larger (up to 4 trials, none started after 6 s); a slow submission the create does not explain, too few samples or any failed call: classic. The verdict is kept per vendor, device, driver version and pipeline cache UUID in - `compile_gate_calibration.txt` beside the pipeline cache (failures are not kept), so it runs once per driver; + `compile_gate_calibration.txt` beside the pipeline cache, so it runs once per driver; a failed call or an unclear + verdict (a slow submission the create does not explain) is not kept, and the next launch measures again, so one + busy moment on the GPU does not hold every later launch on the classic gate. After a wait that times out, the fence + and command pool are destroyed only once the submission's fence signals (left alive on a lost device). `LEONIDA_COMPILE_GATE_RECALIBRATE=1` measures again. It is logged once, `[rt] compile-gate: auto: adaptive (calibrated on NVIDIA 621.40 in 0.7 s: 115 submissions came back in <= 0.5 ms beside a 722 ms create; cached in ...)` (`classic` and the reason otherwise). Only gta6rt's title process calibrates; `--precompile-pipelines`, diff --git a/runtime/README.md b/runtime/README.md index 3e2c01683b..d7822f0e23 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -422,7 +422,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w | `LEONIDA_TEXTURE_REFRESH_ASYNC` | unset | `1` moves the before-submission refresh of the title textures (`refresh_title_textures`) to a worker: a submission only wakes it, and fills by itself only the mapped textures that were never filled, so their first draw has their bytes. Persistent mappings are hashed whole on the worker every pass; the rest is swept 128 textures at a time. A texture changed since may be sampled a frame behind. | | `LEONIDA_SUBMIT_ASYNC` | `0` | ``: each queue's `ExecuteCommandLists`, `Signal`, `Wait` and markers run in call order on a worker of the queue's own (`src/vulkan_backend.h`), at most n batches queued; the caller of the next one waits for room. The replay, the before-submission refreshes and `vkQueueSubmit` then leave the title's thread. A batch that fails is reported as a held one is. `0`: on the caller's thread. | | `LEONIDA_COMPUTE_WARMUP_LIVE_MAX_BYTES` | unset | ``: a compute warm-up of a module over n bytes of SPIR-V is not started while the title submits (a submission in the last second); the pipeline is built at its first use instead (docs/d3d12_vulkan.md, "Pipelines still being built"). Unset or `0`: every warm-up runs, ordered behind a submission's compiles by the large-compile gate. | -| `LEONIDA_COMPILE_GATE` | `auto` (adaptive or classic, by calibration) | The compile gate (`SubmitMutex::CompileTurn`, `src/vulkan_device_fault.h`): a queue submission (or a present or device wait) does not enter the driver while a pipeline create is in it, and waits in the runtime instead, since on NVIDIA 630.20 a `vkQueueSubmit` that entered during a long `vkCreateComputePipelines` waited 10 s in the driver and lost the device. Creates pass together; one that arrives while a submission waits queues behind it. Unset or `auto`: the device measures the driver once, before the title has it (`src/compile_gate_calibration.h`, `docs/d3d12_vulkan.md`): a worker thread creates a synthetic compute pipeline that takes about a second to compile while the queue gets empty submissions, each waited for. Submissions back in under 50 ms with the create still in the driver give the adaptive gate; one held until the create leaves, a create too fast to tell, a submission slow for another reason or any failure give the classic gate. The verdict is kept per GPU and driver (vendor, device, driver version, pipeline cache UUID) in `compile_gate_calibration.txt` beside the pipeline cache, so the measurement runs once per driver, and is logged once: `[rt] compile-gate: auto: adaptive (calibrated on NVIDIA 621.40 in 0.7 s: 115 submissions came back in <= 0.5 ms beside a 722 ms create; cached in ...)`, or `auto: classic (...)`, or `(cached calibration of ...)`. Only gta6rt's title process calibrates: `--precompile-pipelines`, `--compile-server` and tests keep the classic gate. `classic`: compute creates only, waited for however long they take (`LEONIDA_COMPILE_GATE_WAIT_MS` can bound it), no probes, the default before `auto`. `adaptive`: the adaptive gate whatever the calibration says; on a driver that holds submissions (630.20) its first probe of a kind enters the driver after the probe budget and loses the device if that create stays 10 s more. The adaptive gate's wait is bounded by `LEONIDA_COMPILE_GATE_WAIT_MS`. Each submission that enters the driver next to a create the gate went past (at that limit, or earlier at the probe budget, `LEONIDA_COMPILE_GATE_PROBE_MS`) is a probe; two that come back in under 250 ms, at least 1 s apart, with the create still in the driver turn the gate off for the rest of the run (NVIDIA 621.40: 0-11 ms), and one that stays 2 s or more keeps it on; both are logged once. The verdict is kept per kind of create, compute and graphics (mesh included; graphics creates pass the gate since then, only compute ones did before): on NVIDIA 621.40 submissions came back in 0-12 ms beside compute creates, but one sat 54 s in the driver beside a 56 s mesh create and the device was lost. A kind that is off is still timed, and a submission that stays 2 s beside one of its creates turns it back on. A submission never goes ahead, at the limit or the budget, beside a create of a kind whose verdict is that it holds submissions: it waits for that create up to `LEONIDA_COMPILE_GATE_HELD_WAIT_MS`. On a device loss the log names the creates in the driver (kind, program, size, how long) and each kind's gate. `1`: always gate, graphics creates too, with no limit unless `LEONIDA_COMPILE_GATE_WAIT_MS` sets one, never probe or turn it off, and a compute pipeline build also holds the submit lock for its driver calls (`compute_driver_turn`, `shims/d3d12_vulkan_device.cpp`). `0`: no gate. | +| `LEONIDA_COMPILE_GATE` | `auto` (adaptive or classic, by calibration) | The compile gate (`SubmitMutex::CompileTurn`, `src/vulkan_device_fault.h`): a queue submission (or a present or device wait) does not enter the driver while a pipeline create is in it, and waits in the runtime instead, since on NVIDIA 630.20 a `vkQueueSubmit` that entered during a long `vkCreateComputePipelines` waited 10 s in the driver and lost the device. Creates pass together; one that arrives while a submission waits queues behind it. Unset or `auto`: the device measures the driver once, before the title has it (`src/compile_gate_calibration.h`, `docs/d3d12_vulkan.md`): a worker thread creates a synthetic compute pipeline that takes about a second to compile while the queue gets empty submissions, each waited for. Submissions back in under 50 ms with the create still in the driver give the adaptive gate; one held until the create leaves, a create too fast to tell, a submission slow for another reason or any failure give the classic gate. The verdict is kept per GPU and driver (vendor, device, driver version, pipeline cache UUID) in `compile_gate_calibration.txt` beside the pipeline cache, so the measurement runs once per driver (a failed or unclear calibration is not kept: the next launch measures again), and is logged once: `[rt] compile-gate: auto: adaptive (calibrated on NVIDIA 621.40 in 0.7 s: 115 submissions came back in <= 0.5 ms beside a 722 ms create; cached in ...)`, or `auto: classic (...)`, or `(cached calibration of ...)`. Only gta6rt's title process calibrates: `--precompile-pipelines`, `--compile-server` and tests keep the classic gate. `classic`: compute creates only, waited for however long they take (`LEONIDA_COMPILE_GATE_WAIT_MS` can bound it), no probes, the default before `auto`. `adaptive`: the adaptive gate whatever the calibration says; on a driver that holds submissions (630.20) its first probe of a kind enters the driver after the probe budget and loses the device if that create stays 10 s more. The adaptive gate's wait is bounded by `LEONIDA_COMPILE_GATE_WAIT_MS`. Each submission that enters the driver next to a create the gate went past (at that limit, or earlier at the probe budget, `LEONIDA_COMPILE_GATE_PROBE_MS`) is a probe; two that come back in under 250 ms, at least 1 s apart, with the create still in the driver turn the gate off for the rest of the run (NVIDIA 621.40: 0-11 ms), and one that stays 2 s or more keeps it on; both are logged once. The verdict is kept per kind of create, compute and graphics (mesh included; graphics creates pass the gate since then, only compute ones did before): on NVIDIA 621.40 submissions came back in 0-12 ms beside compute creates, but one sat 54 s in the driver beside a 56 s mesh create and the device was lost. A kind that is off is still timed, and a submission that stays 2 s beside one of its creates turns it back on. A submission never goes ahead, at the limit or the budget, beside a create of a kind whose verdict is that it holds submissions: it waits for that create up to `LEONIDA_COMPILE_GATE_HELD_WAIT_MS`. On a device loss the log names the creates in the driver (kind, program, size, how long) and each kind's gate. `1`: always gate, graphics creates too, with no limit unless `LEONIDA_COMPILE_GATE_WAIT_MS` sets one, never probe or turn it off, and a compute pipeline build also holds the submit lock for its driver calls (`compute_driver_turn`, `shims/d3d12_vulkan_device.cpp`). `0`: no gate. | | `LEONIDA_COMPILE_GATE_WAIT_MS` | 0 (15000 with the adaptive gate) | ``: how long a submission waits at the compile gate before it goes ahead anyway; the creates in the driver then hold no later submission back (creates that enter after it are waited for again), and the log says how long the submission then took in the driver. The waiter holds the submit lock, so every queue stops behind it, and the title's hang watchdog ends the process after 30 s (one create stayed in the driver for over 54 s on NVIDIA 621.40). 15 s keeps the 630.20 protection for creates of up to 25 s. The same with the watchdog kept kicked: nothing ends the run then, but the stops still cost the frames (an RTX 4060 run that way had 459 waits, 155 s in all, by t=202 s). `0`: no limit, and with `LEONIDA_COMPILE_GATE_PROBE_MS` unset no probes either: the gate waits however long the creates take and never adapts. | | `LEONIDA_COMPILE_GATE_HELD_WAIT_MS` | 60000 | ``: with the adaptive gate, how long a submission waits for creates of a kind the gate found to hold submissions (`docs/d3d12_vulkan.md`) before it goes ahead anyway; those creates are then not waited for again. `0`: until they leave. | | `LEONIDA_COMPILE_GATE_PROBE_MS` | 2500 with the adaptive gate (0 with `LEONIDA_COMPILE_GATE_WAIT_MS=0`) | ``: the adaptive gate's probe budget. Until it knows whether the driver holds a submission behind a create, a submission also goes ahead once the submissions' waits at the gate in the last 10 s, its own included, add up to this; a single wait reaches it at 2.5 s. On NVIDIA 621.40 waits of 3-7 s, none near the 15 s limit, came back to back and kept the title's main loop from reporting for 30 s; on an RTX 4060 with the watchdog kept kicked, 459 waits of up to 2.9 s took 155 s by t=202 s. The cost on a driver that does hold submissions (630.20): the first probe enters the driver after 2.5 s of waiting and loses the device if the create stays 10 s more; the held verdict then stops the early probes. `0`: probes only at `LEONIDA_COMPILE_GATE_WAIT_MS`. Used only by the adaptive gate. | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 9bbe8d9a7d..d3dfdcdc2c 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -1771,7 +1771,9 @@ void decide_auto_compile_gate(const VulkanDeviceInfo& info, PFN_vkGetDeviceProcA return; } std::string where = "not cached (no pipeline cache folder)"; - if (!path.empty()) { + if (!policy::cache_verdict(result.verdict.outcome)) { + where = "not cached: the next launch measures again"; + } else if (!path.empty()) { const std::string updated = policy::replace_entry(text, {key, result.verdict}); std::filesystem::path temp = path; temp += L".tmp"; diff --git a/runtime/src/compile_gate_calibration.h b/runtime/src/compile_gate_calibration.h index 2f0e73a4ef..e1cd48dec6 100644 --- a/runtime/src/compile_gate_calibration.h +++ b/runtime/src/compile_gate_calibration.h @@ -26,6 +26,9 @@ inline constexpr std::uint32_t kMostStatements = 32000; inline constexpr unsigned kMaxTrials = 4; inline constexpr double kStartTrialsWithinMs = 6000; // no new trial after this long inline constexpr std::uint64_t kFenceTimeoutNs = 10'000'000'000ull; +// After a wait that failed, how long the fence gets before the fence and command pool are destroyed: they must not be +// destroyed while the submission is pending. Still not signalled after this, or the device lost: they are left alive. +inline constexpr std::uint64_t kDrainTimeoutNs = 60'000'000'000ull; inline constexpr std::size_t kMostSamples = 4000; // per trial; the create may outlast them struct Result { @@ -102,9 +105,10 @@ inline Result calibrate(PFN_vkGetDeviceProcAddr get, VkDevice device, VkQueue qu VkCommandPool pool = VK_NULL_HANDLE; VkCommandBuffer cb = VK_NULL_HANDLE; VkFence fence = VK_NULL_HANDLE; + bool keep_queue_objects = false; // a submission may still be pending: never destroy its fence or command pool const auto cleanup = [&] { - if (fence) vk.destroy_fence(device, fence, nullptr); - if (pool) vk.destroy_pool(device, pool, nullptr); + if (fence && !keep_queue_objects) vk.destroy_fence(device, fence, nullptr); + if (pool && !keep_queue_objects) vk.destroy_pool(device, pool, nullptr); if (layout) vk.destroy_layout(device, layout, nullptr); if (set_layout) vk.destroy_set_layout(device, set_layout, nullptr); }; @@ -189,15 +193,18 @@ inline Result calibrate(PFN_vkGetDeviceProcAddr get, VkDevice device, VkQueue qu const detail::clock::time_point start_mark = create_begin; policy::Trial t; VkResult submit_result = VK_SUCCESS; + bool in_flight = false; // submitted, its fence not yet seen signalled // Let the create get into the driver before the first submission. std::this_thread::sleep_for(std::chrono::milliseconds(20)); while (!left.load(std::memory_order_acquire) && t.samples.size() < kMostSamples) { const auto s0 = detail::clock::now(); submit_result = vk.queue_submit(queue, 1, &submit, fence); if (submit_result != VK_SUCCESS) break; + in_flight = true; submit_result = vk.wait_fences(device, 1, &fence, VK_TRUE, kFenceTimeoutNs); const auto s1 = detail::clock::now(); if (submit_result != VK_SUCCESS) break; + in_flight = false; submit_result = vk.reset_fences(device, 1, &fence); if (submit_result != VK_SUCCESS) break; t.samples.push_back({detail::ms_between(start_mark, s0), detail::ms_between(start_mark, s1)}); @@ -206,7 +213,15 @@ inline Result calibrate(PFN_vkGetDeviceProcAddr get, VkDevice device, VkQueue qu worker.join(); if (pipeline) vk.destroy_pipeline(device, pipeline, nullptr); vk.destroy_module(device, module, nullptr); - if (submit_result != VK_SUCCESS) return fail("an empty submission", submit_result); + if (submit_result != VK_SUCCESS) { + // A wait that timed out leaves the submission pending: the fence and the command buffer's pool are + // destroyed only once its fence signals. On a lost device, or if it still has not, they are left alive + // (a small leak, on a path that ends in the classic gate anyway). + if (submit_result == VK_ERROR_DEVICE_LOST) keep_queue_objects = true; + else if (in_flight && vk.wait_fences(device, 1, &fence, VK_TRUE, kDrainTimeoutNs) != VK_SUCCESS) + keep_queue_objects = true; + return fail("an empty submission", submit_result); + } if (create_result != VK_SUCCESS) return fail("vkCreateComputePipelines", create_result); t.create_ms = detail::ms_between(create_begin, create_end); result.verdict = policy::judge(t); diff --git a/runtime/src/compile_gate_policy.h b/runtime/src/compile_gate_policy.h index 57ab30db4b..2e8ea21b7d 100644 --- a/runtime/src/compile_gate_policy.h +++ b/runtime/src/compile_gate_policy.h @@ -331,12 +331,21 @@ inline std::optional parse_entry(std::string_view line) { return e; } -// The entry for `key` in a cache file's text, if it has one. +// Whether a calibration's verdict is written to the cache. Not an unclear one: a submission slowed by something else +// on the GPU (another process, a driver background task) says nothing about this driver, and kept, it would hold +// every later launch on the classic gate until the driver changes; the next launch measures again instead. A create +// still too fast at kMostStatements is kept: that does not change from one launch to the next. +inline bool cache_verdict(Outcome outcome) { return outcome != Outcome::unclear; } + +// The entry for `key` in a cache file's text, if it has one the cache keeps (an unclear one, written by an earlier +// build, is not one: the next launch measures again). inline std::optional find_entry(std::string_view text, const CacheKey& key) { std::optional found; while (!text.empty()) { const std::size_t end = (std::min)(text.find('\n'), text.size()); - if (const auto e = parse_entry(text.substr(0, end)); e && same_key(e->key, key)) found = e; // the last wins + if (const auto e = parse_entry(text.substr(0, end)); + e && same_key(e->key, key) && cache_verdict(e->verdict.outcome)) + found = e; // the last wins text.remove_prefix((std::min)(end + 1, text.size())); } return found; diff --git a/runtime/test/compile_gate_policy_test.cpp b/runtime/test/compile_gate_policy_test.cpp index bab8a3adfa..3257279526 100644 --- a/runtime/test/compile_gate_policy_test.cpp +++ b/runtime/test/compile_gate_policy_test.cpp @@ -183,12 +183,22 @@ void cache() { CacheKey unknown = key_a(); unknown.uuid[3] ^= 1; CHECK(!find_entry(text, unknown)); + // Only verdicts that say something about the driver are cached: an unclear one would hold every later launch + // on the classic gate. + CHECK(cache_verdict(Outcome::adaptive) && cache_verdict(Outcome::holds) && cache_verdict(Outcome::too_fast)); + CHECK(!cache_verdict(Outcome::unclear)); // Recalibrating writes over the entry for the key, keeping the others. CacheEntry again = e; - again.verdict.outcome = Outcome::unclear; + again.verdict.outcome = Outcome::holds; text = replace_entry(text, again); - CHECK(find_entry(text, e.key)->verdict.outcome == Outcome::unclear); + CHECK(find_entry(text, e.key)->verdict.outcome == Outcome::holds); CHECK(find_entry(text, other.key).has_value()); + // An unclear line (written by an earlier build) is not a cached verdict: the next launch measures again. + CacheEntry unclear = e; + unclear.verdict.outcome = Outcome::unclear; + CHECK(parse_entry(format_entry(unclear)).has_value()); + CHECK(!find_entry(replace_entry(text, unclear), e.key)); + CHECK(find_entry(replace_entry(text, unclear), other.key).has_value()); std::size_t lines = 0; for (const char c : text) lines += c == '\n'; CHECK(lines == 2);