From a5a2eb570fc3b38267c52dc1cbfddcc3fe41ec09 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 22:58:25 +0100 Subject: [PATCH] startup: use cached native compute frontend results before translating live Refs #2935 --- .../native-startup-request-cache.md | 15 +++- src/direct_compute_cache.cpp | 78 ++++++++++++------- src/direct_compute_cache.h | 3 + src/startup_stubs/d3d12_compute_dispatch.inl | 48 +++++++++--- src/startup_stubs/d3d12_draw.inl | 2 + src/startup_stubs/d3d12_xs_device.cpp | 7 ++ tests/cmake/native_compute_csir.cmake | 7 ++ tests/native_compute_csir_check.py | 75 ++++++++++++++++++ 8 files changed, 195 insertions(+), 40 deletions(-) create mode 100644 tests/cmake/native_compute_csir.cmake create mode 100644 tests/native_compute_csir_check.py diff --git a/docs/experiments/native-startup-request-cache.md b/docs/experiments/native-startup-request-cache.md index 9d07ed87b8..f774762c8e 100644 --- a/docs/experiments/native-startup-request-cache.md +++ b/docs/experiments/native-startup-request-cache.md @@ -34,14 +34,23 @@ If every input fails with an ordinary error, an existing pack is preserved. Set `X2W_NATIVE_COMPUTE_PACK` to the absolute pack path before startup. The runtime loads the index once when native compute requests are published. At first use it checks the frontend revision, entry offset and SHA-256 of all six frozen parts. -A miss takes the ordinary translation path. A matched refusal proceeds to the -existing published-translation loader. Successful hits run the usual binding +A matched refusal proceeds to the existing published-translation loader. +Successful hits run the usual binding checks, device capability checks, bytecode compilation/cache lookup and PSO creation. The heartbeat reports prepared hits, matched refusals and pack misses. +After a pack miss or when no pack is loaded, the runtime checks for an offline +`.csir` result in `X2W_SHADER_CACHE\native`. Pass that subdirectory as +`CACHE_DIRECTORY` to `compile_dxil --watch` or to the `gfx1013-direct-cs@0` +profile to share its slot-67 frontend cache. The lookup uses the pack's +revision, entry offset and six-part digest. It verifies the file header and +payload before using the cached IR and binding data. A missing or rejected +entry goes through live translation. The heartbeat counts hits, misses, +identity mismatches and invalid entries. + ```powershell cmake --build --preset release --target compile_dxil native_compute_pack_check startup_stream_consumer d3d12_xs_shim -ctest --preset release --no-tests=error -R '^native_compute_pack(_hardware)?$' +ctest --preset release --no-tests=error -R '^(native_compute_pack(_hardware)?|native_compute_csir_hardware)$' ``` ## Alignment between `compile_dxil --requests` and the startup cache diff --git a/src/direct_compute_cache.cpp b/src/direct_compute_cache.cpp index ab7ff78833..ef6cd2ea5e 100644 --- a/src/direct_compute_cache.cpp +++ b/src/direct_compute_cache.cpp @@ -197,25 +197,32 @@ NativeComputeShader decode(std::string_view bytes) { shader.dxil_ir = in.remaining; return shader; } -bool lookup(const fs::path &path, const Bytes &key, Bytes &payload) { - HANDLE handle = CreateFileW(path.c_str(), GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - if (handle == INVALID_HANDLE_VALUE) - return false; - LARGE_INTEGER size{}; - bool ok = false; - if (GetFileSizeEx(handle, &size) && size.QuadPart > 128 && size.QuadPart <= 256ll * 1024 * 1024) { - Bytes id(64, 0), checksum(64, 0); - payload.resize(static_cast(size.QuadPart) - 128); - DWORD got_id = 0, got_sum = 0, got_body = 0; - ok = ReadFile(handle, id.data(), 64, &got_id, nullptr) && got_id == 64 && id == key && - ReadFile(handle, checksum.data(), 64, &got_sum, nullptr) && got_sum == 64 && - ReadFile(handle, payload.data(), static_cast(payload.size()), &got_body, nullptr) && - got_body == payload.size() && shader_digest(payload) == checksum; +ComputeFrontendCacheResult lookup_frontend_payload(const fs::path &path, const Bytes &key, Bytes &payload) { + using Result = ComputeFrontendCacheResult; + HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) { + const DWORD error = GetLastError(); + return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? Result::missing : Result::invalid; } - CloseHandle(handle); - return ok; + const std::unique_ptr handle(file, CloseHandle); + LARGE_INTEGER size{}; + if (!GetFileSizeEx(file, &size) || size.QuadPart <= 128 || size.QuadPart > 256ll * 1024 * 1024) + return Result::invalid; + const auto read = [file](char *data, DWORD count) { + DWORD got = 0; + return ReadFile(file, data, count, &got, nullptr) && got == count; + }; + Bytes id(64, 0), checksum(64, 0); + if (!read(id.data(), 64)) return Result::invalid; + if (id != key) return Result::identity_mismatch; + payload.resize(static_cast(size.QuadPart) - 128); + if (!read(checksum.data(), 64) || !read(payload.data(), static_cast(payload.size()))) + return Result::invalid; + return shader_digest(payload) == checksum ? Result::hit : Result::invalid; +} +bool lookup(const fs::path &path, const Bytes &key, Bytes &payload) { + return lookup_frontend_payload(path, key, payload) == ComputeFrontendCacheResult::hit; } void publish(const fs::path &path, const Bytes &key, const Bytes &payload) { fs::create_directories(path.parent_path()); @@ -340,16 +347,25 @@ Bytes slot67_digest(const ComputeRequest &request, unsigned entry) { identity += shader_digest(*part); return shader_digest(identity); } +fs::path compute_ir_path(const fs::path &cache, const Bytes &key) { + return cache / (key + ".csir"); +} +ComputeFrontendCacheResult lookup_compute_ir(const fs::path &path, const Bytes &key, NativeComputeShader &program) { + using Result = ComputeFrontendCacheResult; + Bytes payload; + const auto result = lookup_frontend_payload(path, key, payload); + if (result != Result::hit) return result; + try { program = decode(payload); } + catch (const std::runtime_error &) { return Result::invalid; } + return Result::hit; +} template NativeComputeShader cached_compute_ir(const fs::path &cache, const Bytes &key, bool &hit, Translate translate) { - const auto path = cache / (key + ".csir"); - Bytes payload; - hit = lookup(path, key, payload); - if (hit) { - try { return decode(payload); } - catch (const std::runtime_error &) { hit = false; } - } - auto program = translate(); + const auto path = compute_ir_path(cache, key); + NativeComputeShader program; + hit = lookup_compute_ir(path, key, program) == ComputeFrontendCacheResult::hit; + if (hit) return program; + program = translate(); publish(path, key, encode(program)); return program; } @@ -359,6 +375,16 @@ Bytes pack_version(unsigned entry) { return shader_digest(version); } } +ComputeFrontendCacheResult lookup_compute_frontend(const ComputeRequest &request, unsigned entry, + const fs::path &cache, NativeComputeShader &program) { + try { + const auto key = slot67_digest(request, entry); + return lookup_compute_ir(compute_ir_path(cache, key), key, program); + } catch (const std::runtime_error &) { + return ComputeFrontendCacheResult::invalid; + } +} + NativeComputeShader prepare_direct_compute(const fs::path &input, unsigned entry, bool container, const fs::path &cache, bool &cache_hit, HeapViewContract heap_view) { if (!container) { diff --git a/src/direct_compute_cache.h b/src/direct_compute_cache.h index ec388dc541..5cfa003c75 100644 --- a/src/direct_compute_cache.h +++ b/src/direct_compute_cache.h @@ -6,6 +6,7 @@ // The result includes the emitted DXIL module and its exact desktop/guest binding layout. namespace x2w { enum class ComputePackResult { miss, prepared, unsupported }; +enum class ComputeFrontendCacheResult { hit, missing, identity_mismatch, invalid }; struct ComputePackCounts { size_t prepared{}, unsupported{}; std::vector errors; }; class ComputeFrontendPack { struct Record { std::string digest, payload; bool unsupported; }; @@ -26,6 +27,8 @@ GuestShaderStage reviewed_graphics_stage(std::string_view raw, GpuStage kind, const std::filesystem::path &cache, bool &exact); // Signature component (f32/u32/i32) for supported typed IA and RTV formats. unsigned dxil_io_component(unsigned dxgi_format); +ComputeFrontendCacheResult lookup_compute_frontend(const ComputeRequest &request, unsigned entry, + const std::filesystem::path &cache, NativeComputeShader &program); NativeComputeShader prepare_direct_compute(const std::filesystem::path &input, unsigned entry, bool container, const std::filesystem::path &cache, bool &cache_hit, HeapViewContract heap_view = HeapViewContract::none); diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 9356b70f3f..9893d8c0ef 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -464,9 +464,9 @@ const char* load_compute_translation(ComputeTranslation& tr) return nullptr; } -// X2W_NATIVE_SHADERS=: the first Dispatch of a slot 67 request translates -// it in this process with the C++ compiler (src/gfx1013_compute_native.cpp), before a published .txt is read -// and with no offline translator running. The dispatch path below binds root constants and supported table views. +// X2W_NATIVE_SHADERS=: the first Dispatch of a slot 67 request uses a +// prepared frontend result or translates it in this process, before a published .txt is read. +// The dispatch path below binds root constants and supported table views. // The constant sampler words the compiler resolved become static samplers. // A refusal is logged and leaves the key to the published translations. draw_lock held. Returns whether tr is ready. bool translate_compute_natively(ComputeTranslation& tr) @@ -491,6 +491,8 @@ bool translate_compute_natively(ComputeTranslation& tr) try { // The request as this runtime published it. The reader checks the six parts against the key in the name. // Entry 0: a source-built program starts there, and the frontend reads a capture's v_nop prefix as code. + constexpr unsigned entry = 0; + const auto cache = std::filesystem::path(path).parent_path() / L"native"; auto frozen = frozen_compute_requests().take(tr.key); if (frozen) x2w::validate_compute_request_shape(*frozen); else frozen.emplace(x2w::read_compute_request(path)); @@ -498,15 +500,41 @@ bool translate_compute_natively(ComputeTranslation& tr) auto result = x2w::ComputePackResult::miss; if (const auto* pack = runtime_compute_pack()) { std::string diagnostic; - result = pack->lookup(*frozen, 0, program, diagnostic); + result = pack->lookup(*frozen, entry, program, diagnostic); if (result == x2w::ComputePackResult::unsupported) { InterlockedIncrement(&compute_pack_refused); return refuse_native(diagnostic.c_str()); } InterlockedIncrement(result == x2w::ComputePackResult::prepared ? &compute_pack_prepared : &compute_pack_misses); } - if (result == x2w::ComputePackResult::miss) - program = x2w::translate_compute(*frozen, 0, true); + const char* frontend = "prepared"; + const char* cache_detail = ""; + if (result == x2w::ComputePackResult::miss) { + using Result = x2w::ComputeFrontendCacheResult; + const auto cached = x2w::lookup_compute_frontend(*frozen, entry, cache, program); + switch (cached) { + case Result::hit: + InterlockedIncrement(&compute_frontend_cache_hits); + frontend = "cached"; + break; + case Result::missing: + InterlockedIncrement(&compute_frontend_cache_misses); + cache_detail = " (frontend cache miss)"; + break; + case Result::identity_mismatch: + InterlockedIncrement(&compute_frontend_cache_mismatches); + cache_detail = " (frontend cache identity mismatch)"; + break; + case Result::invalid: + InterlockedIncrement(&compute_frontend_cache_invalid); + cache_detail = " (invalid frontend cache entry)"; + break; + } + if (cached != Result::hit) { + program = x2w::translate_compute(*frozen, entry, true); + frontend = "live"; + } + } for (const auto& block : program.constants) for (unsigned word = 0; word < block.count; ++word) tr.uds.push_back({static_cast(block.root_parameter), static_cast(word)}); @@ -583,13 +611,11 @@ bool translate_compute_natively(ComputeTranslation& tr) // Never released: a static destructor would release DXC after its module may have detached. static x2w::ShaderDxilCompiler* const compiler = new x2w::ShaderDxilCompiler(x2w::ShaderDxilCompiler::runtime_worker(sdk)); - const auto shader = compiler->compile(program.dxil_ir, L"cs_6_6", std::filesystem::path(path).parent_path() / L"native", - x2w::ShaderSourceFormat::dxil_ir); + const auto shader = compiler->compile(program.dxil_ir, L"cs_6_6", cache, x2w::ShaderSourceFormat::dxil_ir); if (const char* failure = create_compute_pipeline(tr, shader.dxil.data(), shader.dxil.size())) throw std::runtime_error(failure); - log("x2w-draw compute pipeline %016llx translated natively: %zu entry values, %zu inputs, %zu outputs (frontend %s)", tr.key, - tr.uds.size(), tr.srvs.size(), tr.uavs.size(), - result == x2w::ComputePackResult::prepared ? "prepared" : "live"); + log("x2w-draw compute pipeline %016llx translated natively: %zu entry values, %zu inputs, %zu outputs (frontend %s)%s", + tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size(), frontend, cache_detail); return true; } catch (const std::exception& error) { return refuse_native(error.what()); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f6e88d4e4f..578c4e0ec1 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -763,6 +763,8 @@ SRWLOCK compute_request_lock = SRWLOCK_INIT; std::unordered_set& compute_keys_seen() { static std::unordered_set s; return s; } #ifdef X2W_NATIVE_SHADERS LONG compute_pack_prepared, compute_pack_refused, compute_pack_misses; +LONG compute_frontend_cache_hits, compute_frontend_cache_misses, compute_frontend_cache_mismatches, + compute_frontend_cache_invalid; const x2w::ComputeFrontendPack* runtime_compute_pack() { static const auto pack = []() -> std::optional { wchar_t path[32768]; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index cc1f9abc54..98046097b3 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -7998,6 +7998,13 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (compute_pack_prepared || compute_pack_refused || compute_pack_misses) log("x2w-render compute frontend pack: prepared %ld, unsupported %ld, misses %ld", compute_pack_prepared, compute_pack_refused, compute_pack_misses); + const LONG hits = InterlockedCompareExchange(&compute_frontend_cache_hits, 0, 0); + const LONG misses = InterlockedCompareExchange(&compute_frontend_cache_misses, 0, 0); + const LONG mismatches = InterlockedCompareExchange(&compute_frontend_cache_mismatches, 0, 0); + const LONG invalid = InterlockedCompareExchange(&compute_frontend_cache_invalid, 0, 0); + if (hits || misses || mismatches || invalid) + log("x2w-render compute frontend cache: hits %ld, misses %ld, identity mismatches %ld, invalid %ld", + hits, misses, mismatches, invalid); log("x2w-render compute request snapshots: hits %llu, misses %llu, evicted %llu, retained %zu bytes in %zu entries", stats.hits, stats.misses, stats.evicted, stats.bytes, stats.entries); } diff --git a/tests/cmake/native_compute_csir.cmake b/tests/cmake/native_compute_csir.cmake new file mode 100644 index 0000000000..0b810e3dc5 --- /dev/null +++ b/tests/cmake/native_compute_csir.cmake @@ -0,0 +1,7 @@ +if(TARGET compile_dxil AND TARGET startup_stream_consumer AND EXISTS "${INTAKE_PYTHON}" + AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + add_test(NAME native_compute_csir_hardware COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/native_compute_csir_check.py" "$" + "$" "${DXC_BIN_DIR}") + set_tests_properties(native_compute_csir_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) +endif() diff --git a/tests/native_compute_csir_check.py b/tests/native_compute_csir_check.py new file mode 100644 index 0000000000..4c66e3f7b6 --- /dev/null +++ b/tests/native_compute_csir_check.py @@ -0,0 +1,75 @@ +"""Replay a compile_dxil slot-67 frontend result through the first native Dispatch.""" +from hashlib import sha256 +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines, prepare_case +from startup_compute_dispatch_native_check import CAPABILITY_REFUSALS, LOAD_X8, LOADS_X4, mismatch + + +def run(cli, consumer, sdk): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + cache, env = prepare_case(work, "hardware") + env.pop("X2W_NATIVE_COMPUTE_PACK", None) + env.update(X2W_NATIVE_SHADERS=str(sdk), X2W_NATIVE_SHADERS_ONLY="1") + + code = work / "program" + original_code = code.read_bytes() + assert original_code.count(LOAD_X8) == 1 + code.write_bytes(original_code.replace(LOAD_X8, LOADS_X4)) + mode = "dispatch-records32" + live_words, result = dispatch(work, str(consumer), env, mode, probe=True) + if any(lines(result, reason) for reason in CAPABILITY_REFUSALS): + assert live_words == [C.SENTINEL] * C.WORDS, result.stderr + print("SKIP: native compute requires shader model 6.6 and wave32") + return 77 + + def check(words, result, route): + assert len(lines(result, "outputs " + route)) == 1, result.stderr + assert len(lines(result, "Dispatch(3, 2, 2) translated")) == 1, result.stderr + expected = C.expected("A") + assert words == expected, mismatch(words, expected, result) + assert words == live_words + errors = [line for line in lines(result, "x2w-d3d12-debug ") if " sev=0 " in line or " sev=1 " in line] + assert not errors, errors + + check(live_words, result, "(frontend live) (frontend cache miss)") + frontend = cache / "native" + assert not list(frontend.glob("*.csir")), "the live run must leave the frontend cache cold" + marker, = cache.glob("req_*.c67") + built = subprocess.run([cli, sdk, frontend, "gfx1013-direct-cs@0", marker, work / "offline.cso"], + capture_output=True, text=True) + assert built.returncode == 0 and "frontend_cache_hit=0" in built.stdout, (built.stdout, built.stderr) + entry, = frontend.glob("*.csir") + original = entry.read_bytes() + assert len(original) > 128 and original[:64] == entry.stem.encode("ascii") + + for bytecode in frontend.glob("*.bin"): + bytecode.unlink() + words, result = dispatch(work, str(consumer), env, mode) + check(words, result, "(frontend cached)") + # Keep the entry at the expected path with its payload intact. Change the stored identity + # and then the checksum independently so each header check has a negative control. + for offset, reason in ((0, "frontend cache identity mismatch"), (64, "invalid frontend cache entry")): + replacement = b"1" if original[offset:offset + 1] == b"0" else b"0" + damaged = original[:offset] + replacement + original[offset + 1:] + entry.write_bytes(damaged) + words, result = dispatch(work, str(consumer), env, mode) + check(words, result, f"(frontend live) ({reason})") + assert entry.read_bytes() == damaged, "runtime unexpectedly modified the offline cache" + + # A checksummed payload still needs to decode as a frontend result. + payload = b"\xff" * 4 + original[132:] # instruction count exceeds the decoder's limit + entry.write_bytes(original[:64] + sha256(payload).hexdigest().encode("ascii") + payload) + words, result = dispatch(work, str(consumer), env, mode) + check(words, result, "(frontend live) (invalid frontend cache entry)") + print(f"Offline .csir, live translation and invalid-entry fallbacks matched all {C.WORDS} words.") + return 0 + + +if __name__ == "__main__": + sys.exit(run(*(Path(arg).resolve() for arg in sys.argv[1:])))