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
7 changes: 7 additions & 0 deletions docs/experiments/native-startup-request-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ reported as `invalid compute pack size`. Each record contains either
DXIL IR with its binding layout or the exact typed frontend refusal. Other errors
are printed per request, omitted from the pack, and cause a nonzero command status.
If every input fails with an ordinary error, an existing pack is preserved.
The requests are prepared on every hardware thread (at most 64); `--jobs N` after the
entry offset sets the count, and `--jobs 1` prepares them one at a time. The records
follow the sorted request names, so the pack is the same for every count
(`native_compute_pack` builds 11 requests with 1, 4 and the default count and compares
the bytes); the threads only translate, and the records are split into parts afterwards
in that order. In a debug build the CRT debug heap takes one
lock for every allocation, so the threads mostly wait for each other there: use `--jobs 1`.

Set `X2W_NATIVE_COMPUTE_PACK` to the absolute path of part 0 before startup. The runtime
loads the index once when native compute requests are published. At first use it
Expand Down
77 changes: 51 additions & 26 deletions src/direct_compute_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <cstdio>
#include <cstring>
#include <fstream>
#include <future>
#include <charconv>
#include <sstream>
#include <set>
Expand Down Expand Up @@ -415,52 +416,76 @@ NativeComputeShader prepare_direct_compute(const fs::path &input, unsigned entry
}

ComputePackCounts build_compute_frontend_pack(const fs::path &requests, const fs::path &cache, unsigned entry,
size_t part_limit) {
size_t part_limit, unsigned jobs) {
std::vector<fs::path> markers;
for (const auto &file : fs::directory_iterator(requests))
if (file.is_regular_file() && file.path().extension() == ".c67" && file.path().stem().wstring().rfind(L"req_",0) == 0)
markers.push_back(file.path());
if (markers.empty() || markers.size() > 100000)
throw std::runtime_error("invalid compute pack request count");
std::sort(markers.begin(), markers.end());
std::vector<Bytes> parts;
std::vector<uint32_t> part_counts;
ComputePackCounts counts;
for (const auto &marker : markers) {
// The requests are translated independently (the frontend keeps no state between them and the IR cache
// publishes through unique temporary files), on up to `jobs` threads. Their records are placed in parts in
// the sorted order afterwards, so the pack does not depend on the thread count.
struct Record { Bytes bytes; bool unsupported = false; std::string error; };
std::vector<Record> records(markers.size());
auto prepare = [&](size_t i) {
Record &record = records[i];
try {
const auto request = read_compute_request(marker);
const auto request = read_compute_request(markers[i]);
const auto digest = slot67_digest(request, entry);
Bytes payload;
bool unsupported = false, hit = false;
bool hit = false;
try {
auto program = cached_compute_ir(cache, digest, hit, [&] { return translate_compute(request, entry, true); });
payload = encode(program);

} catch (const UnsupportedComputeShader &error) {
payload = error.what();
unsupported = true;

record.unsupported = true;
}
if (payload.empty() || part_limit < pack_header + 80 || payload.size() > part_limit - pack_header - 80)
throw std::runtime_error("invalid compute pack size");
// A record that would cross the limit starts the next part; the records stay in sorted order.
if (parts.empty() || parts.back().size() + 80 + payload.size() > part_limit) {
parts.emplace_back(pack_header, '\0');
part_counts.push_back(0);
}
auto &pack = parts.back();
word(pack, static_cast<uint32_t>(request.key));
word(pack, static_cast<uint32_t>(request.key >> 32));
pack += digest;
word(pack, unsupported);
word(pack, static_cast<uint32_t>(payload.size()));
pack += payload;
++part_counts.back();
if (unsupported) ++counts.unsupported;
else ++counts.prepared;
word(record.bytes, static_cast<uint32_t>(request.key));
word(record.bytes, static_cast<uint32_t>(request.key >> 32));
record.bytes += digest;
word(record.bytes, record.unsupported);
word(record.bytes, static_cast<uint32_t>(payload.size()));
record.bytes += payload;
} catch (const std::runtime_error &e) {
counts.errors.push_back(marker.filename().string() + ": " + e.what());
record.error = markers[i].filename().string() + ": " + e.what();
}
};
const size_t threads = (std::min<size_t>)((std::max)(1u, jobs), markers.size());
if (threads == 1) {
for (size_t i = 0; i < markers.size(); ++i) prepare(i);
} else {
std::atomic<size_t> next{};
std::vector<std::future<void>> workers;
workers.reserve(threads);
for (size_t t = 0; t < threads; ++t)
workers.emplace_back(std::async(std::launch::async, [&] {
for (size_t i = next++; i < markers.size(); i = next++) prepare(i);
}));
for (auto &worker : workers) worker.get();
}
std::vector<Bytes> parts;
std::vector<uint32_t> part_counts;
ComputePackCounts counts;
for (auto &record : records) {
if (!record.error.empty()) {
counts.errors.push_back(std::move(record.error));
continue;
}
// A record that would cross the limit starts the next part; the records stay in sorted order.
if (parts.empty() || parts.back().size() + record.bytes.size() > part_limit) {
parts.emplace_back(pack_header, '\0');
part_counts.push_back(0);
}
parts.back() += record.bytes;
Bytes().swap(record.bytes); // the part holds it now
++part_counts.back();
if (record.unsupported) ++counts.unsupported;
else ++counts.prepared;
}
if (parts.empty()) throw std::runtime_error(counts.errors.at(0));
// Publish the last part first and part 0 last, so a reader never finds a new part 0 naming parts not yet written.
Expand Down
6 changes: 4 additions & 2 deletions src/direct_compute_cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ class ComputeFrontendPack {
// Every published file of a pack holds at most this many payload bytes (the cache lookup limit).
constexpr size_t compute_pack_part_limit = (256u << 20) - 128;
// Part 0 is CACHE/compute-<entry>.pack; a record that would cross part_limit starts compute-<entry>.<n>.pack.
// part_limit is lowered only by tests.
// part_limit is lowered only by tests. Translates the requests on up to `jobs` threads; the pack is the same for
// every thread count.
ComputePackCounts build_compute_frontend_pack(const std::filesystem::path &requests, const std::filesystem::path &cache,
unsigned entry, size_t part_limit = compute_pack_part_limit);
unsigned entry, size_t part_limit = compute_pack_part_limit,
unsigned jobs = 1);
// Part n of the pack whose part 0 is file: compute-0.pack -> compute-0.<n>.pack.
std::filesystem::path compute_pack_part(const std::filesystem::path &file, unsigned n);
// jobs: worker threads (1 = in this thread). The catalog does not depend on it.
Expand Down
40 changes: 40 additions & 0 deletions tests/native_compute_pack_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@
put_compute_request, state_a, COMPUTE_GROUP, COMPUTE_RSRC2)


def pack_keys(data):
"""Record keys of a one-part pack, in file order: 64-byte id, 64-byte checksum, then the 72-byte part header
[part count][record count][next part id] and [key lo][key hi][64-byte digest][unsupported][size][payload]."""
at = 128
total, count = struct.unpack_from("<II", data, at)
assert total == 1, "expected a single part"
at += 72
keys = []
for _ in range(count):
lo, hi = struct.unpack_from("<II", data, at)
(size,) = struct.unpack_from("<I", data, at + 76)
keys.append(lo | hi << 32)
at += 80 + size
assert at == len(data), "trailing pack data"
return keys


def run(cli, checker, sdk):
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
Expand All @@ -35,6 +52,29 @@ def run(cli, checker, sdk):
rejected = subprocess.run([checker, inputs, pack], capture_output=True, text=True)
assert rejected.returncode and "damaged compute pack" in rejected.stderr, rejected
pack.write_bytes(original)
# Parallel preparation: with more requests than threads, each thread count gives the same pack (records
# follow the sorted request names, not the order the threads finish in). Each build starts from an empty cache.
many = base / "many"
many.mkdir()
keys = [put_compute_request(many, code, root, state)]
# The refused program above (ds_append v0; s_endpgm) with destinations v1..v10: ten more keys, all refused.
for i in range(10):
keys.append(put_compute_request(many, bytes.fromhex(f"0000f8d8 {i + 1:08x} 000081bf"), root, state))
packs = {}
for jobs in ("1", "4", None):
out = base / f"cache-jobs-{jobs or 'default'}"
command = [cli, "--prepare-compute-pack", many, out, "0"] + (["--jobs", jobs] if jobs else [])
built = subprocess.run(command, capture_output=True, text=True)
assert built.returncode == 0 and "prepared=1 unsupported=10 errors=0" in built.stdout, built
packs[jobs] = (out / "compute-0.pack").read_bytes()
assert packs["1"] == packs["4"] == packs[None], "the pack depends on the thread count"
# Deterministic order check (the comparison above catches a completion-order append only by timing):
# records follow the sorted request names, and req_<key:016x> names sort as the keys do.
assert pack_keys(packs["4"]) == sorted(keys), "records do not follow the sorted request names"
subprocess.run([checker, many, base / "cache-jobs-4" / "compute-0.pack"], check=True)
bad = subprocess.run([cli, "--prepare-compute-pack", many, base / "cache-bad", "0", "--jobs", "0"],
capture_output=True, text=True)
assert bad.returncode == 1 and "--jobs must be between 1 and 64" in bad.stderr, bad
# Invalid source remains retryable. Other valid records still publish.
(inputs / "req_0000000000000000.c67").write_bytes(code)
result = subprocess.run(build, capture_output=True, text=True)
Expand Down
11 changes: 8 additions & 3 deletions tools/startup/compile_dxil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1542,13 +1542,18 @@ int wmain(int argc, wchar_t** argv) {
return run_watch(argc, argv);
if (argc >= 2 && std::wstring_view(argv[1]) == L"--refusals")
return run_refusals(argc, argv);
if (argc == 5 && std::wstring_view(argv[1]) == L"--prepare-compute-pack") {
if ((argc == 5 || (argc == 7 && std::wstring_view(argv[5]) == L"--jobs")) &&
std::wstring_view(argv[1]) == L"--prepare-compute-pack") {
try {
std::wstring number(argv[4]);
if (number.empty() || number.size() > 7 || number.find_first_not_of(L"0123456789") != number.npos)
throw std::runtime_error("invalid compute entry byte offset");
// Each request is translated on its own; by default on every hardware thread, as --rekey does.
const unsigned jobs = argc == 7 ? static_cast<unsigned>(parse_jobs_count(argv[6]))
: (std::min)(64u, (std::max)(1u, std::thread::hardware_concurrency()));
auto start = Clock::now();
auto counts = x2w::build_compute_frontend_pack(argv[2], argv[3], static_cast<unsigned>(std::stoul(number)));
auto counts = x2w::build_compute_frontend_pack(argv[2], argv[3], static_cast<unsigned>(std::stoul(number)),
x2w::compute_pack_part_limit, jobs);
for (const auto &error : counts.errors) std::cerr << "unprepared " << error << "\n";
std::cout << "prepared=" << counts.prepared << " unsupported=" << counts.unsupported
<< " errors=" << counts.errors.size() << " elapsed_ms=" << std::chrono::duration<double,std::milli>(Clock::now()-start).count() << "\n";
Expand Down Expand Up @@ -1596,7 +1601,7 @@ int wmain(int argc, wchar_t** argv) {
"Set X2W_DUMP_SHADER_IR=FILE to write the HLSL or DXIL text handed to the compiler.\n"
"Use --rekey OLD_CACHE_DIR NEW_REQUEST_DIR [--jobs N] to copy requests under the current cache revision keys.\n"
"Use --index-graphics-interfaces REVIEWED_DIRECTORY CACHE_DIRECTORY [--jobs N] to index native graphics interfaces.\n"
"Use --prepare-compute-pack REQUEST_DIRECTORY CACHE_DIRECTORY ENTRY_BYTE_OFFSET for captured compute.\n";
"Use --prepare-compute-pack REQUEST_DIRECTORY CACHE_DIRECTORY ENTRY_BYTE_OFFSET [--jobs N] for captured compute.\n";
return 2;
}
try {
Expand Down
Loading