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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -2326,6 +2326,26 @@ Pipeline creation:
serialized size and bytes are each device's own (the host's empty library is 900 bytes, the layer's 16).
- Not compared: the calls the host runtime faults on (`Serialize(nullptr, n)`, `StorePipeline` with a null PSO,
`Load*` with a null name or description); the layer answers `E_INVALIDARG` for each.
- Compiles at draw time: the first draw of a graphics pipeline, the first dispatch of a compute pipeline the warm-up
has not built, and each variant are compiled for the submission that needs them. `prepare()` leaves each one that is
not built yet to `PipelineCompiles`, once per pipeline and variant; `VulkanQueue::execute_now` then compiles them
side by side on the device's workers (`runtime/src/pipeline_workers.h`), the submitting thread among them, and writes
the command buffer when all are built. Every draw and dispatch has its own pipeline: none is left to a later frame. A
pipeline the driver refuses has the result it had when `prepare()` built it: a draw or an indirect dispatch fails the
submission, a dispatch is dropped (strict replay: fails it too). The resource lock is held while they compile, as it
is when each is compiled alone, so a PSO released meanwhile waits for the submission. The workers have ended before
the session cache is read at device teardown. `LEONIDA_PIPELINE_THREADS=<n>` sets the workers: unset, half the
logical processors and at most 8; `0` compiles each pipeline on the submitting thread where `prepare()` meets it.
Graphics pipelines of 1 MiB of SPIR-V or more, and compute pipelines over 128 KiB (`LEONIDA_SERIAL_BIG_COMPILES`),
are compiled one after another beside the smaller ones, because a compile takes the driver some hundred bytes of
memory for each byte of SPIR-V ([pipeline_check.md](pipeline_check.md)); so are the variants of one PSO.
`LEONIDA_ASYNC_PIPELINES=1` is not changed: its builds stay on the compile worker. Measured with synthetic programs
never compiled before and the warm-up off (RTX 3080, NVIDIA 621.24, Windows 11, 16 logical processors, 8 workers,
three runs each): the first submission of 192 graphics pipelines takes 126 to 143 ms instead of 861 to 882, of 192
variants 124 to 130 instead of 856 to 863, of 96 compute pipelines 74 to 81 instead of 486 to 519, and the process
holds about 50 MiB more (the driver keeps memory for each thread that compiles). One `VkPipelineCache` is enough: one
cache per thread, merged, was about as fast. Tested by `pipeline_workers`, `replay_pipeline_compiles` and
`d3d12_pipeline_workers`.

**Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear.
The trace will enumerate them.
Expand Down
27 changes: 27 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,12 @@ if(BUILD_TESTING)

add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp)
add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test)
# The pool that compiles a submission's pipelines (runtime/src/pipeline_workers.h): pure stdlib.
add_executable(pipeline_workers_test test/pipeline_workers_test.cpp)
find_package(Threads REQUIRED)
target_link_libraries(pipeline_workers_test PRIVATE Threads::Threads)
add_test(NAME pipeline_workers COMMAND pipeline_workers_test)
set_tests_properties(pipeline_workers PROPERTIES TIMEOUT 120)

# D3D-704's session-cache limit and header check: pure stdlib, no Vulkan headers.
add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp)
Expand Down Expand Up @@ -2193,6 +2199,18 @@ if(TARGET Vulkan::Headers)
add_test(NAME d3d12_texture_memory COMMAND d3d12_texture_memory_test)
set_tests_properties(d3d12_texture_memory PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120
FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
# The pipelines a submission needs, compiled on the device's workers: the same image as without them. The second
# time with the pipelines compiled when they are created, which leaves the variants.
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)
target_compile_options(d3d12_pipeline_workers_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME d3d12_pipeline_workers COMMAND d3d12_pipeline_workers_test)
add_test(NAME d3d12_pipeline_workers_eager COMMAND d3d12_pipeline_workers_test)
set_tests_properties(d3d12_pipeline_workers d3d12_pipeline_workers_eager PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180
FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
set_tests_properties(d3d12_pipeline_workers_eager PROPERTIES
ENVIRONMENT "LEONIDA_LAZY_PIPELINES=0;LEONIDA_LAZY_COMPUTE=0")
# ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836).
add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp)
target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com)
Expand Down Expand Up @@ -3984,6 +4002,15 @@ if(TARGET Vulkan::Headers)
target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
endif()
add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test)
# Pipelines not built yet, left to the pool of pipeline_workers.h: what prepare() alone would give (no GPU).
add_executable(replay_pipeline_compiles_test test/replay_pipeline_compiles_test.cpp)
target_link_libraries(replay_pipeline_compiles_test PRIVATE Vulkan::Headers Threads::Threads)
if(WIN32)
target_compile_definitions(replay_pipeline_compiles_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
endif()
add_test(NAME replay_pipeline_compiles COMMAND replay_pipeline_compiles_test)
add_test(NAME replay_pipeline_compiles_strict COMMAND replay_pipeline_compiles_test)
set_tests_properties(replay_pipeline_compiles_strict PROPERTIES ENVIRONMENT "LEONIDA_STRICT_REPLAY=1")
add_executable(replay_quad_list_test test/replay_quad_list_test.cpp)
target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers)
if(WIN32)
Expand Down
2 changes: 2 additions & 0 deletions runtime/shims/d3d12_com.h
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,8 @@ leonida::ResourceId uav_image_resource(ID3D12Resource* resource, std::uint64_t a
VkBuffer vulkan_buffer(ID3D12Resource* resource);
// What a device from create_vulkan_device* was created with (enabled features included), or null. For tests.
const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device);
// The device's pipeline workers (src/pipeline_workers.h) and what they have compiled; zeros without any. For tests.
leonida::PipelineWorkers::Stats pipeline_worker_stats(ID3D12Device* device);
// True when a slot-133 buffer is a shadow copied from the title's pages, false when they were imported. For tests.
bool title_shadow_buffer(ID3D12Resource* resource);
// VirtualQuery calls made by the title-buffer shadows in their latest refresh. For tests.
Expand Down
52 changes: 45 additions & 7 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1309,6 +1309,16 @@ bool console_format_stand_ins() {
return on;
}

// A driver's compiler needs hundreds of MiB for a very large module; several at once exhausted host memory. Compute modules
// over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for).
bool serial_big_compile(std::size_t spirv_bytes) {
static const bool serial = [] {
wchar_t v[2]{};
return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0');
}();
return serial && spirv_bytes > 128 * 1024;
}

bool startup_cache_checkpoints_enabled() {
static const bool enabled = [] {
wchar_t value[2]{};
Expand Down Expand Up @@ -7394,6 +7404,7 @@ class PipelineState final
if (!mesh && topology_bits != leonida::topology_type_rect_list)
graphics_.rectangle_variant_topology = leonida::topology_rect_list;

std::uint64_t spirv_bytes = 0;
for (Stage& stage : stages) {
if (!stage.entry) continue;
// After the f16 link above, which can also edit the pixel shader's words.
Expand All @@ -7408,6 +7419,7 @@ class PipelineState final
stage.words = std::move(patched);
}
}
spirv_bytes += stage.words.size() * sizeof(std::uint32_t);
if (trace_pipeline_compile()) {
if (!profile_shaders_.empty()) profile_shaders_ += ',';
profile_shaders_ += stage.entry->name;
Expand Down Expand Up @@ -7793,6 +7805,13 @@ class PipelineState final
return graphics_.async_build ? queue_build(false, unbound) : variant(unbound, "draw");
});
};
graphics_.built = [this](std::uint32_t unbound) {
std::unique_lock lock(variants_mutex_, std::try_to_lock); // held: another thread is compiling one
if (!lock.owns_lock()) return VkPipeline(VK_NULL_HANDLE);
const auto it = variants_.find(unbound);
return it == variants_.end() ? VkPipeline(VK_NULL_HANDLE) : it->second;
};
graphics_.large = spirv_bytes >= leonida::PipelineCompiles::large_spirv_bytes;

if (code_stage) {
VkDeviceSize offset = 0;
Expand Down Expand Up @@ -7952,6 +7971,12 @@ class PipelineState final
});
};
pipeline_.build_context = this;
pipeline_.built = [](void* self) {
auto* pso = static_cast<PipelineState*>(self);
std::unique_lock lock(pso->variants_mutex_, std::try_to_lock); // held: another thread is compiling it
return lock.owns_lock() ? pso->pipeline_.pipeline : VkPipeline(VK_NULL_HANDLE);
};
pipeline_.large = serial_big_compile(spirv_bytes);
} else if (!build_compute("compute-create")) {
return E_FAIL;
}
Expand Down Expand Up @@ -7985,15 +8010,9 @@ class PipelineState final
const leonida::ShaderLibrary* library = device_.library();
const leonida::ShaderEntry* entry = compute_entry_;
if (!library || !entry) return VK_NULL_HANDLE;
// The driver's compiler needs hundreds of MiB per very large module; several at once exhausted host memory.
// Modules over 128 KiB compile one at a time (LEONIDA_SERIAL_BIG_COMPILES=0: as many as are asked for).
static const bool serial_big = [] {
wchar_t v[2]{};
return !(GetEnvironmentVariableW(L"LEONIDA_SERIAL_BIG_COMPILES", v, 2) == 1 && v[0] == L'0');
}();
static std::mutex big_compile;
std::unique_lock<std::mutex> big_lock(big_compile, std::defer_lock);
if (serial_big && stage_bytes_ > 128 * 1024) big_lock.lock();
if (serial_big_compile(stage_bytes_)) big_lock.lock();
auto words = library->spirv(*entry);
if (words.empty()) {
std::fprintf(stderr, "[rt] d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str());
Expand Down Expand Up @@ -9696,6 +9715,17 @@ class Device final
leonida::title_va_aliases().set_buffer_maker(this, [](void* device, std::uint64_t va, std::uint64_t bytes) {
static_cast<std::remove_reference_t<decltype(*this)>*>(device)->make_title_buffer(va, bytes);
});
{
char text[32] = {};
size_t length = 0;
const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_THREADS") == 0 && length > 1;
const auto threads = leonida::pipeline_threads(present ? text : "", std::thread::hardware_concurrency());
if (!threads.valid)
std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_THREADS=%s is not a number; using %u\n", text,
threads.count);
if (threads.count)
state_.context->set_pipeline_workers(std::make_unique<leonida::PipelineWorkers>(threads.count));
}
leonida::title_va_aliases().set_hooks(
&state_,
[](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) {
Expand Down Expand Up @@ -10274,6 +10304,7 @@ class Device final
"vkDeviceWaitIdle");
}
state_.context->drain_deleted_resources(UINT64_MAX);
state_.context->set_pipeline_workers(nullptr); // before the pipeline cache is written and destroyed
state_.context->set_bindless_release(nullptr, nullptr);
state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below
}
Expand Down Expand Up @@ -15354,6 +15385,13 @@ VkBuffer vulkan_buffer(ID3D12Resource* resource) {
return r ? r->buffer() : VK_NULL_HANDLE;
}

leonida::PipelineWorkers::Stats pipeline_worker_stats(ID3D12Device* device) {
if (!device) return {};
ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device);
if (auto* d = Device::from<Device>(real ? real : device)) return d->context().pipeline_worker_stats();
return {};
}

const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) {
if (!device) return nullptr;
ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device);
Expand Down
173 changes: 173 additions & 0 deletions runtime/src/pipeline_workers.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// A bounded pool that compiles the pipelines of one submission side by side (docs/d3d12_vulkan.md, "Pipeline creation").
//
// run() is a blocking parallel loop: the calling thread works on its own batch beside the workers, so a batch completes
// even with no worker left (no thread could be started, or stop() was called), and nothing outlives the call. Several
// threads may call run() at once; they share the workers. The workers are started by the first batch that can use them,
// so a device that never compiles at draw time has none. They are plain std::threads: a driver's compiler needs the 8 MB
// of stack the loader's header gives those (docs/pipeline_check.md, "Stack reserve").
#pragma once

#include <algorithm>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <exception>
#include <functional>
#include <mutex>
#include <system_error>
#include <thread>
#include <utility>
#include <vector>

namespace leonida {

class PipelineWorkers {
public:
static constexpr unsigned kMaxThreads = 64;

// What the pool has done: batches handed to the workers, the jobs in them, and the jobs running now.
struct Stats {
unsigned threads = 0; // the most workers the pool starts
std::size_t started = 0; // the workers it has started
std::uint64_t batches = 0;
std::uint64_t jobs = 0;
std::size_t running = 0;
};

explicit PipelineWorkers(unsigned threads) : limit_(std::min(threads, kMaxThreads)) {}
~PipelineWorkers() { stop(); }
PipelineWorkers(const PipelineWorkers&) = delete;
PipelineWorkers& operator=(const PipelineWorkers&) = delete;

unsigned threads() const { return limit_; }

// Calls job(0) .. job(count - 1) and returns when every call has returned. When calls threw, rethrows what the
// lowest of them threw, after the last has returned. With no workers or a single job the calls are made in order on
// this thread, and the first exception ends them.
void run(std::size_t count, const std::function<void(std::size_t)>& job) {
if (!limit_ || count < 2) {
for (std::size_t i = 0; i < count; ++i) job(i);
return;
}
Batch batch{&job, count};
std::unique_lock lock(mutex_);
queue_.push_back(&batch);
++batches_;
jobs_ += count;
start(count - 1);
work_.notify_all();
while (batch.next < batch.count) step(batch, lock);
batch.done.wait(lock, [&] { return !batch.running; });
lock.unlock();
if (batch.error) std::rethrow_exception(batch.error);
}

// Ends the workers once each has finished the job it is in. A run() in progress on another thread finishes its
// remaining jobs itself, and so does every later one.
void stop() {
std::vector<std::thread> threads;
{
std::lock_guard lock(mutex_);
stopping_ = true;
threads.swap(threads_);
}
work_.notify_all();
for (std::thread& thread : threads) thread.join();
}

Stats stats() {
std::lock_guard lock(mutex_);
return {limit_, started_, batches_, jobs_, running_};
}

private:
struct Batch { // on the stack of the run() that made it; guarded by mutex_
const std::function<void(std::size_t)>* job;
std::size_t count;
std::size_t next = 0;
std::size_t running = 0;
std::exception_ptr error{};
std::size_t error_index = 0;
std::condition_variable done{};
};

// With mutex_ held: enough workers for `wanted` more jobs, within the limit.
void start(std::size_t wanted) {
wanted = std::min<std::size_t>(wanted, limit_);
while (!stopping_ && !exhausted_ && threads_.size() < wanted) {
try {
threads_.emplace_back([this] { work(); });
++started_;
} catch (const std::system_error&) {
exhausted_ = true; // the workers there are, and the callers, do it all
}
}
}

void work() {
std::unique_lock lock(mutex_);
for (;;) {
work_.wait(lock, [this] { return stopping_ || !queue_.empty(); });
if (stopping_) return;
step(*queue_.front(), lock);
}
}

// Takes the next job of `batch` (there is one), runs it unlocked, and returns locked. The batch leaves the queue
// with its last job, so no worker can reach it once run() has seen nothing left and nothing running.
void step(Batch& batch, std::unique_lock<std::mutex>& lock) {
const std::size_t index = batch.next++;
if (batch.next == batch.count) std::erase(queue_, &batch);
++batch.running;
++running_;
lock.unlock();
std::exception_ptr error;
try {
(*batch.job)(index);
} catch (...) {
error = std::current_exception();
}
lock.lock();
--running_;
if (error && (!batch.error || index < batch.error_index)) {
batch.error = std::move(error);
batch.error_index = index;
}
// Notified with the mutex held: run() cannot return, and end the batch, before this has.
if (!--batch.running && batch.next == batch.count) batch.done.notify_all();
}

const unsigned limit_;
std::mutex mutex_;
std::condition_variable work_;
std::deque<Batch*> queue_; // batches with jobs nobody has taken yet
std::vector<std::thread> threads_;
bool stopping_ = false;
bool exhausted_ = false;
std::size_t started_ = 0;
std::uint64_t batches_ = 0;
std::uint64_t jobs_ = 0;
std::size_t running_ = 0;
};

// LEONIDA_PIPELINE_THREADS: how many workers, 0 for none (pipelines compile on the thread that submits, as before).
// Unset or empty: half the logical processors and at most 8, past which the compiles of one submission gained little
// (docs/d3d12_vulkan.md). `valid` is false for text that is not a number, which counts as unset.
struct PipelineThreads {
unsigned count = 0;
bool valid = true;
};

inline PipelineThreads pipeline_threads(const char* text, unsigned logical_processors) {
const unsigned automatic = std::min(8u, logical_processors / 2);
if (!text || !*text) return {automatic, true};
unsigned value = 0;
for (const char* c = text; *c; ++c) {
if (*c < '0' || *c > '9') return {automatic, false};
value = std::min(PipelineWorkers::kMaxThreads, value * 10 + unsigned(*c - '0'));
}
return {value, true};
}

} // namespace leonida
Loading
Loading