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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -2465,6 +2465,19 @@ Pipeline creation:
4 threads: modules of 3.6-5.8 MB took 46-145 s each, 12 in 312 s, about 3.5 GB of host memory each while in the
driver (14.5 GB peak for four). Graphics pipelines are not covered: they are built at a title's draw from its PSO
description and the bound formats, and take milliseconds.
After precompiling, run `gta6rt --precompile-pipelines --verify` in a fresh process with the same environment
and selection flags. It reads each selected compute pipeline's local journal file into a separate Vulkan cache
and asks the driver to create that pipeline with `FAIL_ON_PIPELINE_COMPILE_REQUIRED`. A verified entry requires a
successful creation and valid, pipeline-level `APPLICATION_PIPELINE_CACHE_HIT` feedback for that cache. A driver
may return a pipeline without confirming a hit. That entry counts as unverified, as does a response that
compilation is required. [Vulkan pipeline creation feedback](https://docs.vulkan.org/refpages/latest/refpages/source/VkPipelineCreationFeedbackFlagBits.html)
The verifier makes one probe per selected entry with a usable local file, bypassing the shared and external seed
caches, helpers, journal writes, LRU touches and eviction. It exits 0 for a nonempty selection of verified
entries, 2 for an empty selection or any missing, unusable, unverified or failed entry, and 1 when setup fails
(including disabled journaling or unavailable cache control). A name-matching entry with a missing or empty
module counts as an input error before size filters and leaves the `--limit` slots available for buildable
entries. The summary includes the filtered and unbuildable counts. To test on generated inputs, run
`python -I scripts/check_precompile_verify.py <path-to-gta6rt.exe> --require-hit`.
`LEONIDA_COMPILE_HELPER=1` (`shims/d3d12_compile_helper.h`) keeps first-ever compiles out of the title's process:
the driver's locks, which a long `vkCreateComputePipelines` holds and a `vkQueueSubmit` of the same process waits
for, are per process. A compute build of `LEONIDA_COMPILE_HELPER_MIN_BYTES` or more (128 KiB) with no journal file
Expand Down
5 changes: 5 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4290,6 +4290,11 @@ if(TARGET Vulkan::Headers)
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$<CONFIG>"
)
if(Python3_FOUND)
if(CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING)
add_test(NAME precompile_verify COMMAND "${Python3_EXECUTABLE}" -I
"${CMAKE_CURRENT_SOURCE_DIR}/../scripts/check_precompile_verify.py" "$<TARGET_FILE:gta6rt>")
set_tests_properties(precompile_verify PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 240)
endif()
add_test(NAME run_tiny_frame COMMAND "${Python3_EXECUTABLE}" -I
"${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$<TARGET_FILE:gta6rt>"
"$<TARGET_FILE:tiny_frame>" "--probe=$<TARGET_FILE:d3d12_com_test>" ${_trace_runner})
Expand Down
3 changes: 2 additions & 1 deletion runtime/shims/d3d12_precompile.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ struct PrecompileOptions {
std::size_t min_bytes = 0, max_bytes = 0; // SPIR-V size bounds (0: none)
std::vector<std::string> filters; // only entries whose name contains one of these
bool dry_run = false; // --list: print the plan, build nothing
bool verify = false; // --verify: require a driver-reported hit from each local journal file
bool via_helper = false; // --via-helper: as a title does with LEONIDA_COMPILE_HELPER=1 (a test)
};

Expand All @@ -39,7 +40,7 @@ struct CompileServerOptions {
int compile_server(const CompileServerOptions& options);

// Returns 0 when every selected entry was built or already journaled, 2 when some could not be built, 1 when the
// device or the library could not be had.
// device or the library could not be had. Verification returns 0 only for a nonempty selection of confirmed hits.
int precompile_compute_pipelines(const PrecompileOptions& options);

} // namespace rt::d3d12
134 changes: 115 additions & 19 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1362,14 +1362,16 @@ std::uint32_t max_queues_per_family(rt::d3d12::QueueTestSettings settings) {

// The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory.
// LEONIDA_PIPELINE_CACHE_DIR=<folder> keeps it there instead, so several builds of gta6rt share one warmed cache.
std::filesystem::path pipeline_cache_path() {
std::filesystem::path pipeline_cache_path(bool create_directory = true) {
{
std::wstring dir(32768, L'\0');
const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_CACHE_DIR", dir.data(), static_cast<DWORD>(dir.size()));
if (n > 0 && n < dir.size()) {
dir.resize(n);
std::error_code ec;
std::filesystem::create_directories(dir, ec);
if (create_directory) {
std::error_code ec;
std::filesystem::create_directories(dir, ec);
}
return std::filesystem::path(dir) / L"pipeline_cache.bin";
}
}
Expand Down Expand Up @@ -1398,7 +1400,7 @@ const leonida::pipeline_journal::Roots& pipeline_journal_roots() {
if (GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL", value, 2) == 1 && value[0] == L'0')
return {};
if (!pipeline_cache_save_limit()) return {};
std::filesystem::path path = pipeline_cache_path();
std::filesystem::path path = pipeline_cache_path(false); // naming a journal file needs no writes
if (!path.empty()) path.replace_filename(L"pipeline_cache.d");
std::wstring seed(32768, L'\0');
const DWORD n = GetEnvironmentVariableW(L"LEONIDA_PIPELINE_JOURNAL_SEED_DIR", seed.data(),
Expand Down Expand Up @@ -1433,14 +1435,15 @@ std::size_t pipeline_cache_save_limit() {
// and deny writers while the view is in use.
class PipelineCacheSeed {
public:
explicit PipelineCacheSeed(const std::filesystem::path& path) {
explicit PipelineCacheSeed(const std::filesystem::path& path, std::size_t limit = SIZE_MAX) {
if (path.empty()) return;
file_ = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file_ == INVALID_HANDLE_VALUE) return;
LARGE_INTEGER length{};
constexpr auto header_size = static_cast<LONGLONG>(sizeof(VkPipelineCacheHeaderVersionOne));
if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size)
if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size ||
static_cast<ULONGLONG>(length.QuadPart) > limit)
return;
const HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (!mapping) return;
Expand Down Expand Up @@ -10272,6 +10275,8 @@ class JournalCache {
VkResult result_ = VK_SUCCESS;
};

enum class JournalProbe { error, missing_or_unusable, unverified, verified };

// What one compute pipeline build did (build_compute_pipeline).
struct ComputeBuild {
VkPipeline pipeline = VK_NULL_HANDLE; // the caller's from here on
Expand All @@ -10285,6 +10290,7 @@ struct ComputeBuild {
bool journal_hit = false; // found in its journal file
bool journaled = false; // compiled and written to its journal file
bool from_shared = false; // found in the shared cache
JournalProbe probe = JournalProbe::error; // --verify only; early failures never count as hits
};

struct ComputeBuildOptions {
Expand All @@ -10297,8 +10303,46 @@ struct ComputeBuildOptions {
std::uint64_t helper_priority = 0; // the request's urgency: 0 a dispatch, else the warm-up's module size
bool mark_building = false; // precompile, helper: claim the entry, skip it when another process has it
bool key_only = false; // only name the journal file (journal_path), build nothing
bool verify = false; // probe this file alone, without upkeep, publishing or fallback
};

// Probe exactly one local application cache. Only a successful creation with valid application-hit feedback
// identifies the supplied cache as useful. A driver can succeed using its internal cache without setting that bit.
void probe_compute_journal(DeviceState& device, const std::vector<std::uint32_t>& words,
VkComputePipelineCreateInfo pipeline_info, ComputeBuild& out) {
// Take size, header and payload from one handle, even if a concurrent writer replaces this entry.
const PipelineCacheSeed file(out.journal_path, leonida::pipeline_journal::entry_read_limit);
if (file.size() <= leonida::pipeline_cache_store::header_bytes || !file.compatible(device.pso_identity)) {
out.probe = JournalProbe::missing_or_unusable;
return;
}
auto& vk = device.context->vk;
const VkDevice dev = device.info.device;
VkPipelineCache cache = VK_NULL_HANDLE;
const VkPipelineCacheCreateInfo seed{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0,
file.size(), file.data()};
out.result = vk.vkCreatePipelineCache(dev, &seed, nullptr, &cache);
if (out.result != VK_SUCCESS) return;
VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};
module_info.codeSize = words.size() * sizeof(words[0]);
module_info.pCode = words.data();
out.result = vk.vkCreateShaderModule(dev, &module_info, nullptr, &pipeline_info.stage.module);
if (out.result == VK_SUCCESS) {
CompileTrace feedback;
feedback.request_feedback(pipeline_info);
pipeline_info.flags |= VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT;
VkPipeline pipeline = VK_NULL_HANDLE;
out.result = vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline);
if (out.result == VK_SUCCESS && pipeline)
out.probe = feedback.hit() == 1 ? JournalProbe::verified : JournalProbe::unverified;
else if (out.result == VK_PIPELINE_COMPILE_REQUIRED)
out.probe = JournalProbe::unverified;
if (pipeline) vk.vkDestroyPipeline(dev, pipeline, nullptr);
vk.vkDestroyShaderModule(dev, pipeline_info.stage.module, nullptr);
}
vk.vkDestroyPipelineCache(dev, cache, nullptr);
}

// A compute pipeline from a library entry: what a PSO's first dispatch, the warm-up worker and gta6rt
// --precompile-pipelines all build, so their journal names and the driver's keys are the same. `layout` is the push
// range of leonida::ShaderUserData, with the device's bindless set 0 when the entry declares bindings; `subgroup` is
Expand Down Expand Up @@ -10342,7 +10386,8 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn
leonida::apply_subgroup_request(subgroup, required_size, pipeline_info.stage);
pipeline_info.layout = layout;
pipeline_info.flags |= fast_pipeline_flags(true); // before the journal key, which hashes the flags
const VkPipelineCache shared = device.pipeline_cache();
// pipeline_cache() also runs upkeep and may start a helper. The verifier uses only the named file.
const VkPipelineCache shared = options.verify ? VK_NULL_HANDLE : device.pipeline_cache();
auto& submits = device.context->submit_mutex();

// LOCAL FIX (pipeline journal, pipeline_cache_journal.h): the pipeline is created against its own cache, made
Expand All @@ -10369,9 +10414,15 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn
key.value(std::uint32_t(leonida::aftermath::extra_config_flags()));
}
if (entry->binding_count) hash_bindless_layout(key, device.bindless->features());
const auto path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest());
out.journal_path = path;
if (options.key_only) return out;
out.journal_path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest());
}
if (options.verify) {
if (!out.journal_path.empty()) probe_compute_journal(device, words, pipeline_info, out);
return out;
}
if (options.key_only) return out;
if (!out.journal_path.empty()) {
const auto& path = out.journal_path;
// Precompile: a usable file is there already, so the pipeline is not built (only its header is read).
if (options.skip_journaled && leonida::pipeline_journal::entry_usable(path, device.pso_identity)) {
out.skipped = true;
Expand Down Expand Up @@ -21509,7 +21560,7 @@ class BuildHost {
d3d_->Release();
}

bool open() {
bool open(bool verify = false) {
// The GPU address arena holds nothing here and does not change a pipeline: 64 MB, not a title's 2 GB.
_putenv_s("LEONIDA_ARENA_MB", "64");
compile_helper::build_host = true;
Expand All @@ -21528,13 +21579,25 @@ class BuildHost {
std::fprintf(stderr, "%s no translated shader library (LEONIDA_SHADERS)\n", tag_);
return false;
}
if (pipeline_journal_dir().empty())
std::fprintf(stderr, "%s the pipeline journal is off (LEONIDA_PIPELINE_JOURNAL=0 or "
"LEONIDA_PIPELINE_CACHE_BYTES=0): only the driver's own cache is filled\n", tag_);
state.pipeline_cache(); // the shared cache and the journal's upkeep, as at a title's first pipeline
// Every pipeline goes into a journal file: one found in the shared cache would not be.
state.journal_ask_shared = false;
auto& vk = state.context->vk;
if (verify) {
if (pipeline_journal_dir().empty()) {
std::fprintf(stderr, "%s verification requires an enabled local pipeline journal\n", tag_);
return false;
}
if (!state.info.pipeline_cache_control || !state.info.pipeline_creation_feedback ||
!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) {
std::fprintf(stderr, "%s verification requires enabled pipelineCreationCacheControl and "
"pipeline creation feedback\n", tag_);
return false;
}
} else {
if (pipeline_journal_dir().empty())
std::fprintf(stderr, "%s the pipeline journal is off (LEONIDA_PIPELINE_JOURNAL=0 or "
"LEONIDA_PIPELINE_CACHE_BYTES=0): only the driver's own cache is filled\n", tag_);
state.pipeline_cache(); // the shared cache and the journal's upkeep, as at a title's first pipeline
state.journal_ask_shared = false; // every pipeline goes into its own journal file
}
const VkDevice dev = state.info.device;
if (state.info.max_push_constants_size && state.info.max_push_constants_size < sizeof(leonida::ShaderUserData)) {
std::fprintf(stderr, "%s maxPushConstantsSize %u is under the shaders' %zu bytes: the runtime builds no "
Expand Down Expand Up @@ -21600,7 +21663,7 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
using Clock = std::chrono::steady_clock;
const auto began = Clock::now();
BuildHost host("[precompile]");
if (!host.open()) return 1;
if (!host.open(options.verify)) return 1;
const leonida::ShaderLibrary* library = host.library();

// What to build: every compute entry the runtime could create a pipeline for.
Expand All @@ -21609,7 +21672,7 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
std::size_t bytes;
};
std::vector<Job> jobs;
std::size_t not_buildable = 0, filtered = 0;
std::size_t not_buildable = 0, filtered = 0, input_errors = 0;
for (const leonida::ShaderEntry* entry : library->stage_entries("cs")) {
if (!options.filters.empty() &&
std::none_of(options.filters.begin(), options.filters.end(),
Expand All @@ -21618,6 +21681,12 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
continue;
}
const std::size_t bytes = library->spirv_bytes(*entry);
if (options.verify && !bytes) {
// A missing or empty module has no usable size. Report it without displacing a buildable job at --limit.
++input_errors;
std::fprintf(stderr, "[precompile] %s: missing, unreadable or empty SPIR-V file\n", entry->name.c_str());
continue;
}
if ((options.min_bytes && bytes < options.min_bytes) || (options.max_bytes && bytes > options.max_bytes)) {
++filtered;
continue;
Expand All @@ -21633,6 +21702,33 @@ int precompile_compute_pipelines(const PrecompileOptions& options) {
return options.smallest_first ? a.bytes < b.bytes : a.bytes > b.bytes;
});
if (options.limit && jobs.size() > options.limit) jobs.resize(options.limit);
if (options.verify) {
ComputeBuildOptions probe_options;
probe_options.verify = true;
std::size_t verified = 0, missing = 0, unverified = 0, errors = input_errors;
for (const Job& job : jobs) {
ComputeBuild build;
try {
build = host.build(*job.entry, probe_options);
} catch (const std::exception& e) {
std::fprintf(stderr, "[precompile] %s: %s\n", job.entry->name.c_str(), e.what());
}
switch (build.probe) {
case JournalProbe::verified: ++verified; break;
case JournalProbe::missing_or_unusable: ++missing; break;
case JournalProbe::unverified: ++unverified; break;
case JournalProbe::error: ++errors; break;
}
if (build.probe == JournalProbe::error || build.probe == JournalProbe::unverified)
std::fprintf(stderr, "[precompile] %s: %s (VkResult %d)\n", job.entry->name.c_str(),
build.probe == JournalProbe::error ? "probe failed" : "no confirmed application-cache hit",
int(build.result));
}
std::fprintf(stderr, "[precompile] verify selected=%zu verified=%zu missing_or_unusable=%zu unverified=%zu "
"errors=%zu filtered=%zu not_buildable=%zu\n",
jobs.size(), verified, missing, unverified, errors, filtered, not_buildable);
return !jobs.empty() && verified == jobs.size() && !errors ? 0 : 2;
}
std::uint64_t total_bytes = 0;
for (const Job& job : jobs) total_bytes += job.bytes;
const unsigned threads = (std::max)(1u, options.threads);
Expand Down
Loading
Loading