Skip to content
18 changes: 18 additions & 0 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -2816,6 +2816,24 @@ Pipeline creation:
A root signature the runtime does not know is hashed by its address, so the key of a pipeline made with one can
change from one run to the next. The file is local, like the cache files, and is not meant to be attached to a
report: quote the counts. It changes no build, order or cache.
`LEONIDA_PIPELINE_PREWARM_ORDER=<file>` reads such a log at boot and builds, ahead of their first draw, the graphics
and mesh pipelines an earlier run asked for first (RT-PIPELINE-PREWARM-ORDER, phase 2; `runtime/src/pipeline_prewarm.h`).
`1` names `pipeline_order.log` beside the session cache; it is read before this run's own record is appended, so
both variables can be on together. Of the runs recorded on this GPU (vendor and device id), the one with the most
records is read, the newest on a tie. When the title creates a PSO whose key is in it, each recorded variant is
queued on the compile workers as a warm-up at its recorded rank: after every demanded build, one warm-up at a time
and none while a demanded build runs (`PipelineCompiler`; the compile-gate finding in "Compile workers" below is
why), ahead of the compute warm-up's size order and before the cache checkpoint. A variant 0 built at create is
skipped. A console stream kept for its first bind (`LEONIDA_PIPELINE_COMPILE=on-demand`) is otherwise parsed only
there, which would leave the prewarm no lead: when its pipeline is in the plan, the parse is queued as its first
prewarm job instead (at the rank of its first recorded variant, on a compile worker), and its variants follow with
their ranks. A bind that comes first waits for that parse, which it would otherwise have done itself. Records are taken in order until their recorded build times add up to
`LEONIDA_PIPELINE_PREWARM_BUDGET_MS` (default 300000; a record with no build time counts 1000 ms), and at most
`LEONIDA_PIPELINE_PREWARM_MAX_ENTRIES` (default 4096). Compute records are left to the compute warm-up and to
`gta6rt --precompile-pipelines`. A missing or unreadable file, a file with no readable record and a file from
another GPU are ignored with one `[rt] pipeline-prewarm:` line; a damaged line is skipped, as are line types a v1
reader does not know (`E`). A queued prewarm holds no reference: a PSO released first drops it. One that is already
running when the title submits still holds the compile gate (`LEONIDA_COMPILE_GATE`), as any warm-up does.
A queued build holds no reference to its PSO or device (`PipelineCompiler`, `runtime/shims/d3d12_pipeline_compile.h`).
A PSO's last release drops its queued builds and returns at once; one already running is left to finish, and the
worker deletes the PSO after it (`PipelineState::last_release`). The PSO's device reference goes at the release, so
Expand Down
14 changes: 11 additions & 3 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -882,15 +882,15 @@ if(BUILD_TESTING)
add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp)
add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test)

add_executable(heavy_pipeline_cache_test test/heavy_pipeline_cache_test.cpp)
add_test(NAME heavy_pipeline_cache COMMAND heavy_pipeline_cache_test)

# RT-PIPELINE-PREWARM-ORDER phase 1: the file format and the recorder of src/pipeline_order.h (pure stdlib, no GPU).
add_executable(pipeline_order_test test/pipeline_order_test.cpp)
target_link_libraries(pipeline_order_test PRIVATE Threads::Threads)
add_test(NAME pipeline_order COMMAND pipeline_order_test)
set_tests_properties(pipeline_order PROPERTIES TIMEOUT 120)

add_executable(heavy_pipeline_cache_test test/heavy_pipeline_cache_test.cpp)
add_test(NAME heavy_pipeline_cache COMMAND heavy_pipeline_cache_test)

# The per-pipeline journal files compute pipelines are kept in: naming, header check, atomic replacement.
add_executable(pipeline_cache_journal_test test/pipeline_cache_journal_test.cpp)
add_test(NAME pipeline_cache_journal COMMAND pipeline_cache_journal_test)
Expand Down Expand Up @@ -2625,6 +2625,14 @@ if(TARGET Vulkan::Headers)
target_compile_options(d3d12_compile_pool_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME d3d12_compile_pool COMMAND d3d12_compile_pool_test)
set_tests_properties(d3d12_compile_pool PROPERTIES TIMEOUT 120)
# RT-PIPELINE-PREWARM-ORDER phase 2: the plan read from an order log (src/pipeline_prewarm.h) and its warm-ups on the
# compile workers, with jobs that wait at gates; no device.
add_executable(pipeline_prewarm_test test/pipeline_prewarm_test.cpp)
target_link_libraries(pipeline_prewarm_test PRIVATE gta6rt_d3d12_com)
target_compile_definitions(pipeline_prewarm_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(pipeline_prewarm_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME pipeline_prewarm COMMAND pipeline_prewarm_test)
set_tests_properties(pipeline_prewarm PROPERTIES TIMEOUT 120)
add_executable(d3d12_pipeline_workers_test test/d3d12_pipeline_workers_test.cpp)
target_link_libraries(d3d12_pipeline_workers_test PRIVATE gta6rt_d3d12_com)
target_compile_definitions(d3d12_pipeline_workers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
Expand Down
3 changes: 3 additions & 0 deletions runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,9 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
| `LEONIDA_ASYNC_MIN_BYTES` | unset | `<n>`, with `LEONIDA_ASYNC_PIPELINES=1`: only a pipeline of n bytes of SPIR-V or more (compute: its module; graphics: all its stages) is built asynchronously, its draws or dispatches skipped until the compile worker has it; a smaller one is built where it is needed, as with asynchronous builds off, so small lighting and post programs are not skipped while the large ray-tracing ones compile. Unset or `0`: every pipeline is asynchronous. Text that is not a decimal number is ignored, with a log line. ([docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md), "Only the large ones asynchronous") |
| `LEONIDA_COMPUTE_WARMUP_MAX_BYTES` | `1048576` | The largest SPIR-V module, in bytes, the background warm-up thread (`LEONIDA_COMPUTE_WARMUP`) builds ahead of its first dispatch. Larger modules wait for that dispatch. |
| `LEONIDA_PIPELINE_ORDER_LOG` | unset (off) | `1` appends, for each pipeline and variant (the unbound-slot mask of a graphics pipeline) that a dispatch or draw names for the first time, one line to `pipeline_order.log` beside `pipeline_cache.session.bin`: the PSO's description key, the variant, when the title created the PSO and when it first used it (milliseconds since the process started), the build time and whether the handle was ready already. A line of counts is printed at exit (`[rt] pipeline-order: requested N, already ready M, median lead X ms`). The hook never blocks and allocates nothing; it takes only a non-blocking `try_lock`, on the first request of a pipeline and of a variant. Record only: nothing builds, orders or skips differently, and no cache file is touched. At most 8192 lines per run; a file past 8 MiB is set aside as `pipeline_order.log.prev`. The file holds hashes and numbers, no shader or game data, and stays local. See `docs/d3d12_vulkan.md`. |
| `LEONIDA_PIPELINE_PREWARM_ORDER` | unset (off) | `<file>`: an order log written with `LEONIDA_PIPELINE_ORDER_LOG=1` in an earlier run; `1`: `pipeline_order.log` beside the session cache. The graphics and mesh pipelines that run asked for first are queued, when the title creates them, as warm-ups on the compile workers in the recorded order: after every demanded build, one at a time and none while a demanded build runs. The run read is this GPU's with the most records. With `LEONIDA_PIPELINE_COMPILE=on-demand`, a console stream in the plan is parsed by its first prewarm job rather than at its first bind. A missing, garbled or other-GPU file is ignored with one `[rt] pipeline-prewarm:` line. See `docs/d3d12_vulkan.md`. |
| `LEONIDA_PIPELINE_PREWARM_BUDGET_MS` | `300000` | With `LEONIDA_PIPELINE_PREWARM_ORDER`: records are prewarmed in order until their recorded build times add up to this many milliseconds (a record with no build time counts 1000). |
| `LEONIDA_PIPELINE_PREWARM_MAX_ENTRIES` | `4096` | With `LEONIDA_PIPELINE_PREWARM_ORDER`: at most this many pipeline variants are prewarmed. |
| `LEONIDA_SERIAL_BIG_COMPILES` | unset | Large pipelines (compute modules over 128 KiB of SPIR-V, graphics pipelines of 1 MiB or more) compile side by side while their estimates, 512 bytes of memory for each byte of SPIR-V, fit a budget (`LEONIDA_BIG_COMPILE_BUDGET_MB`): one always does, what a submission waits for goes before the warm-up, and the warm-up takes a quarter of the budget at most. `1` compiles the compute ones one at a time, and the graphics ones of a submission one after another, as before there was a budget. `0` lets all of them compile side by side, within the compile workers' heavy count (`LEONIDA_COMPILE_HEAVY_MAX`) for the asynchronous builds and the warm-up. |
| `LEONIDA_BIG_COMPILE_BUDGET_MB` | unset | The budget, in MiB: a fixed number (`0`: one large pipeline at a time) instead of three quarters of the memory that is free at the moment, which is the smaller of the free RAM and the room under the commit limit, read again for each pipeline. Text that is not a number is ignored. |
| `LEONIDA_CONSOLE_FORMATS` | on | Texture descriptions the console accepts and a PC GPU may not (an R9G9B9E5 render target, an sRGB RGBA8 or BGRA8 texture with unordered access) get a host format that can do the job. `0` refuses them, as a PC D3D12 runtime does. |
Expand Down
84 changes: 80 additions & 4 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
#include "../src/pipeline_cache_store.h"
#include "../src/pipeline_cache_journal.h"
#include "../src/pipeline_order.h"
#include "../src/pipeline_prewarm.h"
#include "../src/large_module_gate.h"
#include "../src/dev_status.h"
#include "../src/conservative_raster.h"
Expand Down Expand Up @@ -2726,6 +2727,41 @@ struct DeviceState {
// LEONIDA_PIPELINE_ORDER_LOG=1: which pipelines the title asks for first, appended to pipeline_order.log beside the
// session cache (pipeline_order.h). Null when off: the pipelines then carry no hook at all.
std::unique_ptr<leonida::pipeline_order::Recorder> order_log;
// LEONIDA_PIPELINE_PREWARM_ORDER=<file> ("1": pipeline_order.log beside the session cache): the graphics pipelines an
// earlier run asked for first, queued as warm-ups in that order when the title creates them (pipeline_prewarm.h).
// Null when off. Read before start_order_log, which appends this run to the same file when both are on.
std::unique_ptr<const leonida::pipeline_prewarm::Plan> prewarm_plan;
void load_prewarm_plan() {
namespace prewarm = leonida::pipeline_prewarm;
wchar_t value[1024]{};
const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_PREWARM_ORDER", value, DWORD(std::size(value)));
if (n == 0 || n >= std::size(value) || (n == 1 && value[0] == L'0')) return;
try {
std::filesystem::path path = value;
if (n == 1 && value[0] == L'1') {
path = pipeline_cache_session_path();
if (path.empty()) {
std::fprintf(stderr, "[rt] pipeline-prewarm: no session cache folder; nothing is prewarmed\n");
return;
}
path.replace_filename(L"pipeline_order.log");
}
const auto count = [](const char* name, std::uint64_t fallback) {
char text[32]{};
const DWORD m = GetEnvironmentVariableA(name, text, sizeof(text));
return prewarm::parse_count(m > 0 && m < sizeof(text) ? text : nullptr, fallback);
};
prewarm::Options options;
options.budget_ms = count("LEONIDA_PIPELINE_PREWARM_BUDGET_MS", prewarm::default_budget_ms);
options.max_entries = std::size_t(count("LEONIDA_PIPELINE_PREWARM_MAX_ENTRIES", prewarm::default_max_entries));
auto plan = prewarm::load_plan(path, pso_identity.vendor, pso_identity.device, options);
std::fprintf(stderr, "%s\n", plan.message.c_str());
if (plan) prewarm_plan = std::make_unique<const prewarm::Plan>(std::move(plan));
} catch (const std::exception& e) {
std::fprintf(stderr, "[rt] pipeline-prewarm: the order log could not be read (%s); nothing is prewarmed\n",
e.what());
}
}
void start_order_log() {
char text[8]{};
const DWORD n = GetEnvironmentVariableA("LEONIDA_PIPELINE_ORDER_LOG", text, sizeof(text));
Expand Down Expand Up @@ -12513,6 +12549,7 @@ class PipelineState final
}
registered_ = true;
is_graphics_ = true;
prewarm_queue(std::size_t((std::max)(spirv_bytes, std::uint64_t{1})));
return S_OK;
}

Expand Down Expand Up @@ -12778,7 +12815,9 @@ class PipelineState final
// handle once built; otherwise a compile-worker job is queued (once) and null answered, so the draw or dispatch is
// skipped and a later submission uses the pipeline. `warm_bytes`: a warm-up, queued by module size. `count_skip`:
// false for a request made at record time (request_early), which skips nothing.
VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0, bool count_skip = true) {
// `priority`: where a warm-up goes among the others (PipelineCompiler); 0: by `warm_bytes`, the module size.
VkPipeline queue_build(bool compute, std::uint32_t unbound, std::size_t warm_bytes = 0, bool count_skip = true,
std::size_t priority = 0) {
static std::mutex publication; // ready handles only; no compiler call holds this lock
const bool warm = warm_bytes != 0;
// After an exit stop (stop_pipeline_compiles) nothing is queued: a warm-up or an early request is skipped,
Expand All @@ -12797,7 +12836,7 @@ class PipelineState final
}
bool queued = false;
try {
queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm_bytes,
queued = PipelineCompiler::instance().submit(compile_owner(), &device_, warm && priority ? priority : warm_bytes,
[this, compute, warm, unbound, warm_bytes] {
// A big warm-up while the title submits is left to the pipeline's first use (warmup_waits_for_quiet).
if (warm && warmup_waits_for_quiet(warm_bytes)) return;
Expand Down Expand Up @@ -12839,7 +12878,42 @@ class PipelineState final
return VK_NULL_HANDLE;
}

// LEONIDA_PIPELINE_PREWARM_ORDER: the variants an earlier run asked this graphics pipeline for, queued as warm-ups at
// their recorded rank (pipeline_prewarm.h): after every demanded build, one warm-up at a time and none while a
// demanded build runs (PipelineCompiler). A queued one holds no reference: a release first drops it (last_release).
void prewarm_queue(std::size_t bytes) {
const auto* plan = device_.prewarm_plan.get();
if (!plan) return;
const auto& key = order_key_.empty() ? cache_key_ : order_key_;
const auto* entries = key.empty() ? nullptr : plan->find(key);
if (!entries) return;
for (const auto& entry : *entries) {
if (entry.variant == 0 && graphics_.pipeline) continue; // built at create
queue_build(false, entry.variant, bytes, true, leonida::pipeline_prewarm::priority(entry.rank));
}
}

public:
// A console stream kept for its first bind (LEONIDA_PIPELINE_COMPILE=on-demand, set_pending_stream) is parsed only
// when it is first resolved, and create_graphics queues the prewarm from there: no lead at all. When the plan has
// the stream's pipeline, the parse is queued here as its first prewarm job instead, at the rank of its first
// recorded variant, on a compile worker rather than the title's thread; create_graphics then queues the variants
// with their ranks as for any other PSO. A bind meanwhile waits for that parse (resolve_type's call_once), which it
// would otherwise have done itself. Like any queued build it holds no reference (last_release drops it).
void prewarm_pending_stream() {
const auto* plan = device_.prewarm_plan.get();
if (!plan || pending_stream_kind_ != 1) return;
const auto& key = order_key_.empty() ? cache_key_ : order_key_;
const auto* entries = key.empty() ? nullptr : plan->find(key);
if (!entries || entries->empty()) return;
try {
PipelineCompiler::instance().submit(compile_owner(), &device_,
leonida::pipeline_prewarm::priority(entries->front().rank),
[this] { resolve_type(true); }, true);
} catch (...) {
}
}

// Record time (SetPipelineState for compute, a draw for graphics, with the render-target slots it binds and
// whether it binds a depth buffer): asynchronous builds start on the compile worker before the list is submitted.
// Never waits; nothing to do when the variant is the last one asked for here.
Expand Down Expand Up @@ -14611,6 +14685,7 @@ class Device final
state_.pso_identity.device = props.deviceID;
state_.pso_identity.driver = props.driverVersion;
std::memcpy(state_.pso_identity.cache_uuid, props.pipelineCacheUUID, VK_UUID_SIZE);
state_.load_prewarm_plan(); // first: the order log may append this run to the same file
state_.start_order_log();
if (state_.info.max_push_constants_size == 0) {
state_.info.max_push_constants_size = props.limits.maxPushConstantsSize;
Expand Down Expand Up @@ -15615,9 +15690,10 @@ class Device final
auto* pipeline=new PipelineState(state_);
pipeline->attach_device(identity());
pipeline->set_cache_key(stream.has_cs?pipeline_key(stream.compute):pipeline_key(stream.graphics));
if(state_.order_log) pipeline->set_order_key(order_key(stream));
if(state_.order_log||state_.prewarm_plan) pipeline->set_order_key(order_key(stream));
if(!rt::d3d12_xs::attach_pso_record(pipeline,std::move(record))){pipeline->Release();return E_OUTOFMEMORY;}
pipeline->set_pending_stream(stream.has_cs);
pipeline->prewarm_pending_stream();
return hand_out(pipeline,iid,out);
}
HRESULT shared_native_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& pc, D3D12_SHADER_BYTECODE mesh,
Expand Down Expand Up @@ -17853,7 +17929,7 @@ class Device final
if (FAILED(parsed)) return finish(parsed);
auto* pipeline = new PipelineState(state_);
pipeline->attach_device(identity());
if (state_.order_log) pipeline->set_order_key(order_key(stream));
if (state_.order_log || state_.prewarm_plan) pipeline->set_order_key(order_key(stream));
const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute)
: pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as,
stream.back_masks ? &stream.back_stencil : nullptr, stream.depth_bounds);
Expand Down
Loading
Loading