diff --git a/README.md b/README.md index 0860ff63f..3b9a6b61b 100644 --- a/README.md +++ b/README.md @@ -225,11 +225,13 @@ that stage has finished rebuilding `vk_pipeline_check`, so it can overlap the re translated shader on your GPU driver, reports any it has to skip, and saves a pipeline cache to `pipeline_cache.bin` in `--out`, which also holds `gta6rt.exe` after the `runtime` stage. The runtime seeds its Vulkan pipeline cache from the file beside the executable when its header matches the device and pipeline cache UUID. It falls back to -an empty cache if the file is missing, incompatible, or rejected by the driver. Shader translation is the longest -CPU step. It runs on `--jobs` processes (half the CPU threads by default). When shaders and assets share the machine, -that budget is split between them and passed to `rpf9dump` as `--jobs`. A solo assets run still lets `rpf9dump` use -every core. Progress lines include percent and a rough ETA for translation shards, asset steps, and overall stage -completion. +an empty cache if the file is missing, incompatible, or rejected by the driver. `pipeline_done.json` beside the cache +lists the shaders already built for this GPU, driver and checker, so a later run only builds the ones whose SPIR-V +changed ([docs/pipeline_check.md](docs/pipeline_check.md#shard-caches-and-the-done-list)). Shader translation is the +longest CPU step. It runs on `--jobs` processes (half the CPU threads by default). When shaders and assets share the +machine, that budget is split between them and passed to `rpf9dump` as `--jobs`. A solo assets run still lets +`rpf9dump` use every core. Progress lines include percent and a rough ETA for translation shards, asset steps, and +overall stage completion. On an interactive terminal, a LEONIDA setup screen lets you set jobs and whether stages overlap, then a key-switchable per-stage log view (`1`–`4` / `Tab`) keeps parallel output demuxed; full stage logs go under `work/logs/`. Use diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 4d5be5e35..5fb1c50b0 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -44,6 +44,15 @@ Build with `make_game.py --stages shaders --compact-spirv` to run SPIRV-Tools lo | `--isolate` | POSIX only: check in child processes, `--isolate-batch N` modules at a time (default 256), so a crashing module is recorded as `MODULE CRASH` and the pass continues. Not compatible with `--stats`. | | `--inflight-file F` | Keep the modules currently in the driver in F as `namephase` lines. It is rewritten by the watchdog and when a large module enters or leaves, and emptied at the end; `make_game.py`'s pipelines stage reads it. | | `--skip-file F` | Do not compile modules named one per line in F; each is reported as `MODULE CRASH` and counted as a failed pipeline. `make_game.py` writes F after a crash so the next run checks the rest. | +| `--names-file F` | Check only the index entries named one per line in F (applied before `--start`/`--count`); a name the index lacks is a usage error. | +| `--done-file F` | At the end, write the modules that passed to F, one per line and sorted: module created, and pipeline created or skipped for a missing feature or stub, with the cache saved. Not with `--isolate`. | + +Two other modes take no spirv dir: + +| Command | Meaning | +|---|---| +| `vk_pipeline_check --device-info` | Print `device-info vendor=… device=… driver=… api=… uuid= name=…` for the device a check would use (`LEONIDA_VK_DEVICE` applies). | +| `vk_pipeline_check --merge ...` | Load `` if it exists, add each input with `vkMergePipelineCaches` and save `` atomically. An input whose header names another vendor, device or `pipelineCacheUUID` (`runtime/test/pipeline_cache_header.h`), or that cannot be read, fails the merge with exit 1 and leaves `` as it was; an `` of another device is replaced. | `--isolate-child` is internal to the parent/child protocol and is not meant to be passed directly. A module with a missing partner stub is skipped; without `--isolate`, a driver crash ends the run. @@ -347,8 +356,10 @@ that size. Which threads the game creates pipelines on is not known without its ## Build-stage batches (BUILD-1030) `make_game.py` runs the pipelines stage in fresh checker processes over at most **500 index entries** each, on -Windows and POSIX. The ranges partition the same name-sorted index as `--start` / `--count`, including the final -short range. Each finished process saves to the same `pipeline_cache.bin`, and the next loads that checkpoint. +Windows and POSIX. The ranges partition the name-sorted list of modules still to check (with a checker before +`--merge`, the whole index, selected by `--start` / `--count`), including the final short range. Each process writes +its own shard cache, merged into `pipeline_cache.bin` at the end (next section); with a checker before `--merge`, +each finished process saves to the same `pipeline_cache.bin`, and the next loads that checkpoint. This bounds each invocation to a range that can be split further if concurrent heavy compiles exceed available memory. A work folder with at most 500 entries keeps the single invocation. An older checker without the range options keeps the older invocation; rebuild the runtime to get batching. @@ -378,6 +389,60 @@ bounded coverage and cache checkpoints, collective memory-crash recovery, a genu failures, interruptions, setup failures, inconclusive probes and compatibility with older checkers. It needs no game files or GPU. +## Shard caches and the done-list + +With one shared `pipeline_cache.bin`, every one of the 53 processes of a full run loaded the whole cache and saved it +back: on an RTX 4070 SUPER (NVIDIA 621.01) the full set's cache is 9.6 GB, and that load and save took 1-2 minutes per +process. A run after a translator change also checked all 26,503 modules again, even the unchanged ones (they compile +from the cache, but each process still pays the load and save). With a checker that has `--merge`, the stage instead: + +- gives each process (and each single-module crash probe and each pass over an extra set) its own empty cache, + `pipeline_shards/NNNNN.bin` in `--out`, and its batch through `--names-file`; +- merges the shards into `pipeline_cache.bin` once at the end (`--merge`), then removes them. A run that was stopped + (Ctrl+C, a setup error, the crash retries running out) keeps its shards, and the next run merges them. A run with a + validation failure still merges what was built, as each process's own cache save did before; +- records each module its `--done-file` names in `pipeline_done.json` in `--out`, with the SHA-256 of its `.spv` and + of its index entry and the shard it went to. A later run skips the modules recorded with the same hashes, so after + a translator change only the modules whose SPIR-V (or index entry) changed are built; +- after the main set, checks the extra sets the runtime seed needs, each whole in one process: `bvh/` + (XboxBvhBuilder), `fspx/` (the FidelityFX DLL's compute programs) and `exe/` (the executable's own programs). Each + is recorded under `extras` by a hash of its `index.json` and `.spv` files, so an unchanged corpus starts no process + and needs no merge. `library/` and `fspx_gfx/` are not checked: on NVIDIA the seed does not hit for them ([#1608](https://github.com/ubiquitarianism/leonida/issues/1608)). A + set that fails is not recorded and fails the stage, but the other sets and the merge still run. + +The whole list is tied to one identity: vendor and device ID, driver version and `pipelineCacheUUID` +(`--device-info`), the checker, the partner stubs in `stubs/` and the list's format. A change of any of them checks +every module again. A new GPU or driver also drops leftover shards and starts from empty caches (the old cache is of +no use to it). A new checker or new stubs on the same driver instead checkpoint into the existing `pipeline_cache.bin` +for that one run, as the first run does, so the pipelines it holds compile from it; leftover shards are merged. The checker is named by the SHA-256 of its sources when it is the +current build in this checkout's `runtime/build` (the `cl.exe` fallback of `scripts/build_runtime.ps1` relinks it on +every runtime stage), otherwise by the SHA-256 of the executable. Entries already merged into `pipeline_cache.bin` +are kept when something else writes to it (a checker run straight into it only adds pipelines), and dropped, with a +line saying why, only when the cache is gone or empty, is smaller than the last merge left it, or its header names +another vendor, device or `pipelineCacheUUID`; deleting the cache builds everything again. A module that failed, crashed the driver or was not checked is not on the list, so it is checked on every run +as before. The first run over a `pipeline_cache.bin` from before the done-list keeps the old per-process load and save, +so what that cache holds still compiles from it; later runs use shards. + +The cache holds the same pipelines as before: each module's pipeline is created by the same checker with the same +device setup, only into a smaller cache that is merged afterwards. `runtime/test/check_vk_pipeline_merge.py` (CTest +`vk_pipeline_check_merge`) checks this on the GPU: two caches of three synthetic compute shaders each, merged, seed a +run over all six with six application-cache hits, and the first cache alone with three. `pipeline_cache_header` tests +the header check without a device, and `tests/test_make_game_pipeline_batches.py` runs the stage's crash recovery with +both checker generations plus the done-list cases (resume, changed module, changed driver or checker, failed merge). + +Measured on an RTX 4070 SUPER (NVIDIA 621.01, Windows 11), `--jobs 2`, `__GL_SHADER_DISK_CACHE=0`, 400 synthetic compute +shaders in batches of 50 (8 processes), seconds, two runs each: + +| | Full run | Rerun, nothing changed | Rerun, 20 modules changed | +|---|---:|---:|---:| +| one shared cache | 2.9 / 3.0 | 2.3 / 2.4 | 2.2 / 2.5 | +| shards + done-list | 3.2 / 3.5 | 0.22 / 0.25 | 0.76 / 0.86 | + +That cache is 2.8 MB, so this measures the per-process and per-module work, not the cache I/O, which is what dominates +the real corpus: the stage no longer loads or saves the cache per process, and merges once. The checker also reads +its seed cache in one call now; loading a 2 GiB cache file took 21.6 s before (a character-by-character copy) and +1.7 s after, on the same machine. + ## Crash isolation (`--isolate`) A driver that dies while compiling one module (for example the RADV `SIGFPE` in diff --git a/make_game.py b/make_game.py index f1af5a172..80c590629 100644 --- a/make_game.py +++ b/make_game.py @@ -74,7 +74,7 @@ import leonida_tui # noqa: E402 from shader_stage_manifest import shader_stems # noqa: E402 from replace_retry import replace as replace_retry # noqa: E402 -from stale_build import newer_sources # noqa: E402 +from stale_build import newer_sources, program_sources # noqa: E402 VERSIONS = os.path.join(ROOT, "game") STAGES = ["check", "shaders", "assets", "runtime", "pipelines"] @@ -2775,13 +2775,35 @@ def pipelines(work: str, out: str, jobs: "int | None" = None, *, runtime_build: # --jobs: make_game.py's own; without it vk_pipeline_check uses half the hardware threads whatever was asked jobs_args = ["--jobs", str(jobs)] if jobs else [] base = [exe, spirv, cache, *jobs_args] - - def seed_bvh() -> None: - bvh = os.path.join(spirv, "bvh") - if not os.path.isfile(os.path.join(bvh, "index.json")): - return - log("pipelines: creating XboxBvhBuilder compute pipelines") - run([exe, bvh, cache, *jobs_args]) + book: "PipelineDoneList | None" = None + + def seed_extras() -> int: + """The shader sets beside the main index that the runtime seed needs (PIPELINE_EXTRA_SETS), each in one + checker process. Returns the first failing exit code with the done-list (the rest of the sets still run + unless it was a setup error or a stop); without it a failure stops the stage, as before.""" + first = 0 + for name, label in PIPELINE_EXTRA_SETS: + directory = os.path.join(spirv, name) + if not os.path.isfile(os.path.join(directory, "index.json")): + continue + if not book: + log(f"pipelines: creating {label} pipelines") + run([exe, directory, cache, *jobs_args]) + continue + digest = book.directory_digest(directory) + if book.extra_done(name, digest): # unchanged: no shard, so an unchanged corpus needs no merge either + continue + log(f"pipelines: creating {label} pipelines") + shard = book.new_shard() + code = run([exe, directory, shard, *jobs_args], check=False) + if code == 0: + book.record_extra(name, digest, shard) + continue + log(f"pipelines: the {label} pass ({name}/) exited with {exit_label(code)}") + first = first or code + if code == 2 or interrupted(code): + return code + return first if not checker_supports(exe, "--inflight-file", "--skip-file"): # An older build takes any argument it doesn't know as the cache path, so it would write the cache into @@ -2789,21 +2811,61 @@ def seed_bvh() -> None: log("pipelines: this vk_pipeline_check has no --inflight-file; rebuild the runtime stage so a module that " "crashes the driver is skipped instead of stopping the stage") run(base) - seed_bvh() + seed_extras() log("pipelines: done") return base += ["--inflight-file", inflight] + # A checker with --merge and --done-file gets shard caches and the done-list (PIPELINES-STAGE-SHARDS-AND-DONE-LIST): + # each process writes its own small cache instead of loading and rewriting pipeline_cache.bin, the shards are + # merged into it once at the end, and a module already built for this GPU, driver and checker is not built again. + book = PipelineDoneList(out, spirv, cache, exe) if checker_supports(exe, *PIPELINE_SHARD_OPTIONS) else None + batch_names = os.path.join(out, "pipeline_batch.txt") + batch_done = os.path.join(out, "pipeline_batch_done.txt") # Bound each checker invocation to a range that recovery can split further when concurrent heavy compiles # exceed available memory, without starting the entire corpus again (BUILD-1030). - names = pipeline_names(spirv) if checker_supports(exe, "--start", "--count") else [] + if book: + names = book.todo + log(f"pipelines: {book.total - len(names)} of {book.total} modules are already built for this GPU, driver " + f"and checker; {len(names)} to check" + (" (checkpointing into the existing pipeline_cache.bin, as " + "before, while the done-list is first made)" if book.migrating + else "")) + else: + names = pipeline_names(spirv) if checker_supports(exe, "--start", "--count") else [] crashed: "list[str]" = [] + def launch(start: int, count: "int | None") -> int: + """One checker process over names[start:start + count] (all of the index when count is None).""" + skip_args = ["--skip-file", skip] if crashed else [] + if not book: + selection = ["--start", str(start), "--count", str(count)] if count is not None else [] + return run(base + selection + skip_args, check=False) + batch = names[start:start + count] + with open(batch_names, "w", encoding="utf-8", newline="\n") as f: + f.write("".join(n + "\n" for n in batch)) + drop(batch_done) + shard = book.new_shard() + try: + return run([exe, spirv, shard, *jobs_args, "--inflight-file", inflight, "--names-file", batch_names, + "--done-file", batch_done, *skip_args], check=False) + finally: + book.harvest(batch_done, shard, batch) + + def probe(name: str) -> bool: + """crashes_alone, into its own shard with the done-list when there is one.""" + if not book: + return crashes_alone(exe, spirv, cache, name, inflight) + drop(batch_done) + shard = book.new_shard() + try: + return crashes_alone(exe, spirv, shard, name, inflight, names_file=batch_names, done_file=batch_done) + finally: + book.harvest(batch_done, shard, [name]) + def check_range(start: int = 0, count: "int | None" = None) -> int: - selection = ["--start", str(start), "--count", str(count)] if count is not None else [] allowed = set(names[start:start + count]) if count is not None else None for _ in range(PIPELINE_CRASH_RETRIES + 1): drop(inflight) # a crash during setup must not inherit another process's in-flight module names - code = run(base + selection + (["--skip-file", skip] if crashed else []), check=False) + code = launch(start, count) # Native setup failures also return 1. A finished pass writes/clears this report even when shaders # fail validation; setup failures return before writing it. Do not repeat setup for every batch. if code == 1 and not os.path.isfile(inflight): @@ -2815,7 +2877,7 @@ def check_range(start: int = 0, count: "int | None" = None) -> int: if n not in crashed and (allowed is None or n in allowed))) # Even the last in-flight module can be innocent after other heavy compiles in the batch. if count is not None or len(suspects) > 1: - suspects = [n for n in suspects if crashes_alone(exe, spirv, cache, n, inflight)] + suspects = [n for n in suspects if probe(n)] if not suspects: if count is not None and count > 1: # All suspects survived in fresh processes: do not blacklist them. Re-check the entire failed @@ -2847,7 +2909,7 @@ def check_range(start: int = 0, count: "int | None" = None) -> int: code = 0 ranges = [(s, min(PIPELINE_BATCH_SIZE, len(names) - s)) - for s in range(0, len(names), PIPELINE_BATCH_SIZE)] if names else [(0, None)] + for s in range(0, len(names), PIPELINE_BATCH_SIZE)] if names or book else [(0, None)] for start, count in ranges: if count is not None: log(f"pipelines: checking shaders {start + 1}-{start + count} of {len(names)} in a fresh process") @@ -2860,12 +2922,20 @@ def check_range(start: int = 0, count: "int | None" = None) -> int: code = 1 if crashed: record_crashes(out, spirv, crashed) - drop(inflight) + drop(inflight, batch_names, batch_done) + if book and code != 2 and not interrupted(code): + # A validation failure still keeps what was built, as each batch's own cache save did before. A stopped + # run keeps its shards instead, and the next run merges them. + if code == 0: + code = seed_extras() + if code != 2 and not interrupted(code): + book.merge(exe) if code != 0: why = f"; {len(crashed)} module(s) took the driver down and were counted as failed (with their SPIR-V " \ f"hashes in pipeline_crashes.json): " + ", ".join(crashed) if crashed else "" fail(f"vk_pipeline_check exited with {exit_label(code)}{why}") - seed_bvh() + if not book: + seed_extras() log("pipelines: done") @@ -2941,12 +3011,22 @@ def pipeline_names(spirv: str) -> "list[str]": return sorted(index, key=lambda n: n.encode("utf-8")) -def crashes_alone(exe: str, spirv: str, cache: str, name: str, inflight: str | None = None) -> bool: - """Confirm a crash only when this probe's fresh report names the selected module as in flight.""" +def crashes_alone(exe: str, spirv: str, cache: str, name: str, inflight: str | None = None, *, + names_file: str | None = None, done_file: str | None = None) -> bool: + """Confirm a crash only when this probe's fresh report names the selected module as in flight. With names_file + (a checker with --names-file), the module is selected by name through that file, and done_file gets the + checker's --done-file.""" names = pipeline_names(spirv) if name not in names: return False - args = [exe, spirv, cache, "--jobs", "1", "--start", str(names.index(name)), "--count", "1"] + if names_file: + with open(names_file, "w", encoding="utf-8", newline="\n") as f: + f.write(name + "\n") + args = [exe, spirv, cache, "--jobs", "1", "--names-file", names_file] + if done_file: + args += ["--done-file", done_file] + else: + args = [exe, spirv, cache, "--jobs", "1", "--start", str(names.index(name)), "--count", "1"] if inflight: drop(inflight) args += ["--inflight-file", inflight] @@ -2968,6 +3048,338 @@ def crashes_alone(exe: str, spirv: str, cache: str, name: str, inflight: str | N return True +# Shard caches and the done-list (docs/pipeline_check.md, "Shard caches and the done-list"). +PIPELINE_SHARD_OPTIONS = ("--names-file", "--done-file", "--merge", "--device-info") +PIPELINE_DONE_FILE = "pipeline_done.json" +PIPELINE_SHARD_DIR = "pipeline_shards" +PIPELINE_DONE_FORMAT = 1 +PIPELINE_MERGE_COMMAND_CHARS = 24000 # inputs per --merge call: well under Windows' 32,767-character command line +_SHARD_NAME = re.compile(r"^(\d+)\.bin$") +# Shader sets beside the main index that the runtime seed needs, each checked whole in one process after the main set: +# (folder under shaders/spirv, what the log calls it). Not library/ or fspx_gfx/: on NVIDIA the seed does not hit for +# those (#1608). +PIPELINE_EXTRA_SETS = (("bvh", "XboxBvhBuilder compute"), ("fspx", "FidelityFX (FSPX) compute"), + ("exe", f"{EXE_IMAGE} graphics")) + + +def checker_device_info(exe: str) -> dict: + """`vk_pipeline_check --device-info` as a dict: vendor, device, driver, api, uuid (pipelineCacheUUID) and name.""" + try: + r = subprocess.run([exe, "--device-info"], capture_output=True, text=True, errors="replace", timeout=300) + except (OSError, subprocess.SubprocessError) as e: + fail(f"pipelines: cannot run {exe} --device-info: {e}") + line = next((x for x in (r.stdout or "").splitlines() if x.startswith("device-info ")), None) + if r.returncode or not line: + fail(f"pipelines: vk_pipeline_check --device-info exited with {exit_label(r.returncode)}: " + f"{(r.stderr or r.stdout or '').strip()[-400:]}") + fields, _, name = line[len("device-info "):].partition(" name=") + info = dict(f.split("=", 1) for f in fields.split() if "=" in f) + info["name"] = name.strip() + return info + + +def checker_fingerprint(exe: str) -> str: + """What identifies the checker's behaviour. The checker in this checkout's runtime/build, when it is not older + than its sources, is named by those sources, so relinking the same code keeps the done-list (the cl.exe fallback + of scripts/build_runtime.ps1 rebuilds it on every runtime stage). Any other checker is named by its bytes.""" + build = os.path.abspath(os.path.join(ROOT, "runtime", "build")) + h = hashlib.sha256() + if path_is_within(os.path.abspath(exe), build) and not newer_sources(exe, ROOT, "vk_pipeline_check"): + sources = sorted(program_sources(ROOT, "vk_pipeline_check"), + key=lambda p: os.path.relpath(p, ROOT).replace(os.sep, "/")) + for path in sources: + with open(path, "rb") as f: + text = f.read().replace(b"\r\n", b"\n") # the same sources with either checkout line ending + h.update(os.path.relpath(path, ROOT).replace(os.sep, "/").encode() + b"\0") + h.update(len(text).to_bytes(8, "little") + text) + return "sources:" + h.hexdigest() + try: + with open(exe, "rb") as f: + return "exe:" + hashlib.file_digest(f, "sha256").hexdigest() + except OSError as e: + fail(f"pipelines: cannot read {exe}: {e.strerror or e}") + + +def pipeline_cache_device(path: str) -> "tuple[int, int, str] | None": + """Vendor ID, device ID and pipelineCacheUUID (hex) from a VkPipelineCacheHeaderVersionOne, or None when the + file is missing, short or not a version-one header (runtime/test/pipeline_cache_header.h).""" + try: + with open(path, "rb") as f: + head = f.read(32) + except OSError: + return None + if len(head) < 32: + return None + size, version, vendor, device = struct.unpack_from("<4I", head) + if version != 1 or size < 32: + return None + return vendor, device, head[16:32].hex() + + +def _file_stamp(path: str) -> "dict | None": + try: + st = os.stat(path) + except OSError: + return None + return {"size": st.st_size, "mtime_ns": st.st_mtime_ns} + + +class PipelineDoneList: + """pipeline_done.json and pipeline_shards/ in the output folder. + + The list records each module of the shader index that a checker process built without a failure, keyed by the + SHA-256 of its .spv and of its index entry, together with the shard (or pipeline_cache.bin) its pipeline was saved + to. The whole list holds only for one identity: the GPU and driver (vendor and device ID, driver version, + pipelineCacheUUID), the checker (checker_fingerprint), the partner stubs and this format; any change of these + checks every module again. Entries saved to pipeline_cache.bin hold while that file is still this driver's and no + smaller than the last merge left it (_cache_doubt): a write from outside (a checker run straight into it) only + adds pipelines. An entry whose shard is gone is dropped. The PIPELINE_EXTRA_SETS passes are recorded + the same way, by a digest of their folder.""" + + def __init__(self, out: str, spirv: str, cache: str, exe: str): + self.path = os.path.join(out, PIPELINE_DONE_FILE) + self.shards = os.path.join(out, PIPELINE_SHARD_DIR) + self.cache = cache + index_path = os.path.join(spirv, "index.json") + try: + with open(index_path, encoding="utf-8-sig") as f: + index = json.load(f) + except (OSError, ValueError) as e: + fail(f"pipelines: cannot read {index_path}: {getattr(e, 'strerror', None) or e}") + if not isinstance(index, dict): + fail(f"pipelines: {index_path} must contain a JSON object") + device = checker_device_info(exe) + self.identity = { + "format": PIPELINE_DONE_FORMAT, + "device": {k: device.get(k) for k in ("vendor", "device", "driver", "uuid", "name")}, + "checker": checker_fingerprint(exe), + "stubs": self._stubs_digest(os.path.join(spirv, "stubs")), + } + previous = self._load() + self.migrating = False + records: dict = {} + self.cache_stamp = None + # PIPELINE_EXTRA_SETS passes: folder -> {"digest", "shard"}, checked like a module record + self.extras: "dict[str, dict]" = {} + if previous is None: + # No list yet: the first run checkpoints into an existing pipeline_cache.bin as before (each process loads + # and saves it), so what it already holds compiles from the cache instead of again from scratch. + self.migrating = bool((_file_stamp(cache) or {}).get("size")) + elif previous.get("identity") != self.identity: + old_device = (previous.get("identity") or {}).get("device") + if old_device == self.identity["device"]: + # Same GPU and driver, another checker or stubs: every module is checked again, but the pipelines + # pipeline_cache.bin already holds are still this driver's, so this run checkpoints into it as the + # first run does and they compile from it. Leftover shards are this driver's too: merged at the end. + log("pipelines: the checker or partner stubs changed since the done-list was written; checking every " + "module again, from the existing pipeline_cache.bin") + self.migrating = bool((_file_stamp(cache) or {}).get("size")) + else: + log("pipelines: the GPU or driver changed since the done-list was written; building every module again") + shutil.rmtree(self.shards, ignore_errors=True) + else: + records = dict(previous.get("modules") or {}) + extras = dict(previous.get("extras") or {}) + if isinstance(previous.get("bvh"), dict): # the list before fspx/ and exe/ had only this pass + extras.setdefault("bvh", previous["bvh"]) + # checked like the modules just below, under keys no module name can have + records.update({(None, n): r for n, r in extras.items() if isinstance(r, dict)}) + stamp = _file_stamp(cache) + if previous.get("cache") != stamp: + doubt = self._cache_doubt(previous.get("cache"), stamp) + merged = sum(1 for n, r in records.items() if not r.get("shard") and isinstance(n, str)) + if doubt: + if merged: + log(f"pipelines: {doubt}, so the {merged} module(s) the done-list has in it are checked again") + records = {n: r for n, r in records.items() if r.get("shard")} + elif merged: + # Something else wrote to it (a checker run straight into it, a copy back): that only adds + # pipelines, so what the last merge put there is still in it. + log("pipelines: pipeline_cache.bin changed since the last merge but is no smaller and is this " + "driver's; keeping the done-list") + self.cache_stamp = stamp + records = {n: r for n, r in records.items() + if not r.get("shard") or os.path.isfile(os.path.join(self.shards, r["shard"]))} + self.extras = {n[1]: records.pop(n) for n in [k for k in records if isinstance(k, tuple)]} + # A first run that was stopped goes on checkpointing into the cache. + self.migrating = bool(previous.get("migrating")) and bool((_file_stamp(cache) or {}).get("size")) + self.names = sorted(index, key=lambda n: n.encode("utf-8")) + self.total = len(self.names) + self.current = self._module_keys(spirv, index, records) + self.records = {n: r for n, r in records.items() + if self.current.get(n) and r.get("spv") == self.current[n]["spv"] + and r.get("meta") == self.current[n]["meta"]} + self.todo = [n for n in self.names if n not in self.records] + numbers = [int(m.group(1)) for m in map(_SHARD_NAME.match, self._listdir()) if m] + self.next_shard = max(numbers, default=0) + 1 + self.save() + + def _cache_doubt(self, old: "dict | None", stamp: "dict | None") -> str: + """Why pipeline_cache.bin may no longer hold what the last merge put in it, or "" when nothing says so. + Another write to it (a checker run straight into it) only adds pipelines, so a change of size or time alone + is no reason; a cache that is gone, shrank or names another GPU or driver in its header is.""" + name = os.path.basename(self.cache) + if not stamp or not stamp["size"]: + return f"{name} is gone or empty" + if old and isinstance(old.get("size"), int) and stamp["size"] < old["size"]: + return f"{name} shrank from {old['size']} to {stamp['size']} bytes since the last merge" + device = self.identity["device"] + try: + mine = (int(device["vendor"], 16), int(device["device"], 16), str(device["uuid"]).lower()) + except (KeyError, TypeError, ValueError): + return "" + found = pipeline_cache_device(self.cache) + if found != mine: + what = ("has no pipeline cache header" if found is None else + f"was written by vendor 0x{found[0]:04x} device 0x{found[1]:04x} pipelineCacheUUID {found[2]}") + return f"{name} {what}, not by this GPU and driver" + return "" + + @staticmethod + def _stubs_digest(stubs: str) -> str: + h = hashlib.sha256() + try: + names = sorted(os.listdir(stubs)) + except OSError: + return "" + for name in names: + path = os.path.join(stubs, name) + if os.path.isfile(path): + with open(path, "rb") as f: + data = f.read() + h.update(name.encode() + b"\0" + len(data).to_bytes(8, "little") + data) + return h.hexdigest() + + def _load(self) -> "dict | None": + try: + with open(self.path, encoding="utf-8") as f: + doc = json.load(f) + except FileNotFoundError: + return None + except (OSError, ValueError) as e: + log(f"pipelines: {self.path} is unreadable ({getattr(e, 'strerror', None) or e}); starting a new one") + return {} + return doc if isinstance(doc, dict) else {} + + def _listdir(self) -> "list[str]": + try: + return os.listdir(self.shards) + except OSError: + return [] + + @staticmethod + def _module_keys(spirv: str, index: dict, records: dict) -> dict: + """name -> {spv, meta, size, mtime_ns}, or None for a module without its .spv. A .spv with the size and + modification time of its record keeps the recorded hash instead of being read again.""" + def key(name: str) -> "dict | None": + path = os.path.join(spirv, name + ".spv") + stamp = _file_stamp(path) + if stamp is None: + return None + old = records.get(name) or {} + if old.get("size") == stamp["size"] and old.get("mtime_ns") == stamp["mtime_ns"] and old.get("spv"): + spv = old["spv"] + else: + try: + with open(path, "rb") as f: + spv = hashlib.file_digest(f, "sha256").hexdigest() + except OSError: + return None + meta = hashlib.sha256(json.dumps(index[name], sort_keys=True, separators=(",", ":")).encode()).hexdigest() + return {"spv": spv, "meta": meta, **stamp} + with ThreadPoolExecutor(max_workers=min(8, os.cpu_count() or 1)) as pool: + return dict(zip(index, pool.map(key, index))) + + def new_shard(self) -> str: + """The cache path for the next checker process: a new shard, or pipeline_cache.bin itself while migrating.""" + if self.migrating: + return self.cache + os.makedirs(self.shards, exist_ok=True) + path = os.path.join(self.shards, f"{self.next_shard:05d}.bin") + self.next_shard += 1 + return path + + def harvest(self, done_file: str, shard: str, batch: "list[str]") -> None: + """Record the modules of `batch` that the checker's --done-file lists; absent when the process died.""" + try: + with open(done_file, encoding="utf-8") as f: + passed = {line.strip() for line in f if line.strip()} + except OSError: + passed = set() + where = None if self.migrating else os.path.basename(shard) + for name in batch: + if name in passed and self.current.get(name): + self.records[name] = {**self.current[name], "shard": where} + if self.migrating: + self.cache_stamp = _file_stamp(self.cache) + self.save() + + @staticmethod + def directory_digest(directory: str) -> str: + """SHA-256 over the names and bytes of what the checker reads in `directory`: index.json and the .spv files.""" + h = hashlib.sha256() + for name in sorted(os.listdir(directory)): + path = os.path.join(directory, name) + if os.path.isfile(path) and (name == "index.json" or name.endswith(".spv")): + with open(path, "rb") as f: + h.update(name.encode() + b"\0" + hashlib.file_digest(f, "sha256").digest()) + return h.hexdigest() + + def extra_done(self, name: str, digest: str) -> bool: + return (self.extras.get(name) or {}).get("digest") == digest + + def record_extra(self, name: str, digest: str, shard: str) -> None: + self.extras[name] = {"digest": digest, "shard": None if self.migrating else os.path.basename(shard)} + self.save() + + def save(self) -> None: + doc = {"format": PIPELINE_DONE_FORMAT, "identity": self.identity, "cache": self.cache_stamp, + "migrating": self.migrating, "extras": dict(sorted(self.extras.items())), + "modules": dict(sorted(self.records.items()))} + staged = self.path + ".tmp" + with open(staged, "w", encoding="utf-8", newline="\n") as f: + json.dump(doc, f, separators=(",", ":")) + f.write("\n") + replace_retry(staged, self.path) + + def merge(self, exe: str) -> None: + """Merge every shard into pipeline_cache.bin (vk_pipeline_check --merge), then remove them. A failed merge + leaves the cache and the shards as they were, so the next run merges them again.""" + if self.migrating: # the first pass is over (the BVH pipelines went into the cache too): shards from now on + self.migrating = False + self.cache_stamp = _file_stamp(self.cache) + self.save() + shards = sorted((n for n in self._listdir() if _SHARD_NAME.match(n)), key=lambda n: int(n.split(".")[0])) + if not shards: + return + log(f"pipelines: merging {len(shards)} shard cache(s) into {os.path.basename(self.cache)}") + while shards: + chunk, length = [], len(exe) + len(self.cache) + 16 + for name in shards: + path = os.path.join(self.shards, name) + if chunk and length + len(path) + 3 > PIPELINE_MERGE_COMMAND_CHARS: + break + chunk.append(name) + length += len(path) + 3 + shards = shards[len(chunk):] + code = run([exe, "--merge", self.cache, *(os.path.join(self.shards, n) for n in chunk)], check=False) + if code: + fail(f"pipelines: merging the shard caches into {self.cache} exited with {exit_label(code)}; the " + f"shards stay in {self.shards} and the next run of this stage merges them again") + merged = set(chunk) + for record in [*self.records.values(), *self.extras.values()]: + if record.get("shard") in merged: + record["shard"] = None + self.cache_stamp = _file_stamp(self.cache) + self.save() + for name in chunk: + drop(os.path.join(self.shards, name)) + try: + os.rmdir(self.shards) + except OSError: + pass + + def path_is_within(path: str, directory: str) -> bool: try: return os.path.commonpath([path, directory]) == directory diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 4cbe50acb..63a72e8d8 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -922,6 +922,9 @@ if(BUILD_TESTING) # vk_pipeline_check's isolate summary stage set: pure stdlib, no Vulkan device. add_executable(pipeline_summary_test test/pipeline_summary_test.cpp) add_test(NAME pipeline_summary COMMAND pipeline_summary_test) + # vk_pipeline_check --merge's pipeline cache header check: pure stdlib, no Vulkan device. + add_executable(pipeline_cache_header_test test/pipeline_cache_header_test.cpp) + add_test(NAME pipeline_cache_header COMMAND pipeline_cache_header_test) # XDXR build descriptions (docs/xdxr.md); compared with d3d12.h where the Windows SDK provides it. add_executable(xdxr_descs_test test/xdxr_descs_test.cpp) add_test(NAME xdxr_descs COMMAND xdxr_descs_test) @@ -2074,6 +2077,15 @@ if(TARGET Vulkan::Headers) "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/vk_pipeline_check_cli_input" "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_vk_pipeline_cli.cmake") + # --merge, --names-file and --done-file on six synthetic compute shaders (make_game.py's shard caches): needs a + # Vulkan device whose driver reports application-cache hits, else it exits 77. + find_package(Python3 COMPONENTS Interpreter QUIET) + if(Python3_FOUND AND NOT CMAKE_CROSSCOMPILING) + add_test(NAME vk_pipeline_check_merge COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/test/check_vk_pipeline_merge.py" "$" + "${CMAKE_CURRENT_BINARY_DIR}/vk_pipeline_check_merge") + set_tests_properties(vk_pipeline_check_merge PROPERTIES SKIP_RETURN_CODE 77) + endif() add_test(NAME vk_texture_cube_alpha COMMAND vk_texture_test --self-test-cube-alpha) if(WIN32) # Reads SizeOfStackReserve from the built file; the program is not run, so it needs no emulator. diff --git a/runtime/test/check_vk_pipeline_merge.py b/runtime/test/check_vk_pipeline_merge.py new file mode 100644 index 000000000..6997a53fb --- /dev/null +++ b/runtime/test/check_vk_pipeline_merge.py @@ -0,0 +1,170 @@ +"""vk_pipeline_check --merge, --names-file and --done-file (PIPELINES-STAGE-SHARDS-AND-DONE-LIST). + +make_game.py's pipelines stage gives each checker process its own small cache (a shard) and merges the shards into +pipeline_cache.bin once at the end. This builds two caches from six tiny synthetic compute shaders (three each, no +game data), merges them, and checks that the result is a cache of this device that holds all six: a run over the +six seeded with the merged cache reports six application-cache hits, one seeded with only the first shard three. +It also checks that a cache written for another device is refused and leaves the output as it was, and that +--names-file selects and --done-file lists the right modules. + + python -I check_vk_pipeline_merge.py + +Exit 0 on success, 1 on a failure, 77 (skip) with no Vulkan device or a driver that reports no application-cache +hits even for a cache it wrote itself (llvmpipe). Standard library only, plus tools/spirv_asm.py from this checkout. +""" +import json +import os +import re +import shutil +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, os.path.join(ROOT, "tools")) +from spirv_asm import assemble # noqa: E402 + +SKIP = 77 +ASM = """OpCapability Shader +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main "main" +OpExecutionMode %main LocalSize {size} 1 1 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%main = OpFunction %void None %fn +%entry = OpLabel +OpReturn +OpFunctionEnd +""" +FIRST = ["m_alpha", "m_bravo", "m_charlie"] +SECOND = ["m_delta", "m_echo", "m_foxtrot"] + + +def write_corpus(directory, names): + os.makedirs(directory, exist_ok=True) + index = {} + for name in names: + size = 1 << (FIRST + SECOND).index(name) # a different module (and pipeline) per name + with open(os.path.join(directory, name + ".spv"), "wb") as f: + f.write(assemble(ASM.format(size=size), target_env="vulkan1.1")) + index[name] = {"stage": "cs", "subgroup_size": None, "features": []} + with open(os.path.join(directory, "index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump(index, f) + + +def run(cmd): + p = subprocess.run([str(c) for c in cmd], capture_output=True, text=True, errors="replace", timeout=300) + return p.returncode, p.stdout, p.stderr + + +def hits(stdout): + m = re.search(r"cs cache feedback: (\d+) hits", stdout) + return int(m.group(1)) if m else None + + +def main(argv): + if len(argv) != 3: + print(__doc__, file=sys.stderr) + return 2 + tool, work = os.path.abspath(argv[1]), argv[2] + shutil.rmtree(work, ignore_errors=True) + os.makedirs(work) + failures = [] + + def expect(condition, what, *output): + if not condition: + failures.append(what + ("\n" + "\n".join(o for o in output if o) if output else "")) + + code, out, err = run([tool, "--device-info"]) + if code != 0: + print(f"SKIP: no Vulkan device (--device-info exited {code}): {err.strip()[-300:]}") + return SKIP + info = dict(re.findall(r"(\w+)=(\S+)", out.split(" name=")[0])) + expect(out.startswith("device-info ") and len(info.get("uuid", "")) == 32, "--device-info line", out) + + first, second, both = (os.path.join(work, d) for d in ("first", "second", "both")) + write_corpus(first, FIRST) + write_corpus(second, SECOND) + write_corpus(both, FIRST + SECOND) + cache_a, cache_b = os.path.join(work, "a.bin"), os.path.join(work, "b.bin") + done_a = os.path.join(work, "a.done") + code, out, err = run([tool, first, cache_a, "--jobs", "2", "--done-file", done_a]) + expect(code == 0 and "cs pipelines: 3 ok" in out, "first shard", out, err) + with open(done_a, encoding="utf-8") as f: + expect(f.read() == "".join(n + "\n" for n in FIRST), "--done-file lists the three passed modules") + code, out, err = run([tool, second, cache_b, "--jobs", "2"]) + expect(code == 0 and "cs pipelines: 3 ok" in out, "second shard", out, err) + + # A driver that reports no hit for a cache it wrote itself can't show what a merge holds. + code, out, err = run([tool, first, cache_a, "--jobs", "2", "--cache-feedback"]) + if hits(out) != 3: + print(f"SKIP: this driver reports {hits(out)} application-cache hits for its own cache, not 3") + return SKIP + + merged = os.path.join(work, "merged.bin") + code, out, err = run([tool, "--merge", merged, cache_a, cache_b]) + expect(code == 0 and "merged 2 cache(s)" in out, "--merge", out, err) + with open(merged, "rb") as f: + header = f.read(32) + expect(len(header) == 32 and int.from_bytes(header[4:8], "little") == 1, "merged cache header version") + expect(int.from_bytes(header[8:12], "little") == int(info.get("vendor", "0"), 16), "merged cache vendor") + expect(header[16:32].hex() == info.get("uuid"), "merged cache pipelineCacheUUID") + + # Seeded with the merge, all six pipelines hit; with the first shard alone only its three. + for seed, want in ((merged, 6), (cache_a, 3)): + probe = os.path.join(work, "probe.bin") + shutil.copyfile(seed, probe) + code, out, err = run([tool, both, probe, "--jobs", "2", "--cache-feedback"]) + expect(code == 0 and hits(out) == want, f"{os.path.basename(seed)} seeds {want} hits, got {hits(out)}", + out, err) + + # Merging into an existing output keeps what it held. + grown = os.path.join(work, "grown.bin") + shutil.copyfile(cache_a, grown) + code, out, err = run([tool, "--merge", grown, cache_b]) + expect(code == 0, "--merge into an existing cache", out, err) + code, out, err = run([tool, both, grown, "--jobs", "2", "--cache-feedback"]) + expect(hits(out) == 6, f"existing output plus one input holds six, got {hits(out)}", out, err) + + # Another device's cache is refused, and the output stays as it was. + foreign = os.path.join(work, "foreign.bin") + with open(cache_b, "rb") as f: + data = bytearray(f.read()) + data[8] ^= 0xFF # vendorID + with open(foreign, "wb") as f: + f.write(data) + with open(merged, "rb") as f: + before = f.read() + code, out, err = run([tool, "--merge", merged, foreign]) + expect(code == 1 and "not this device's cache" in err, "a foreign input fails the merge", out, err) + with open(merged, "rb") as f: + expect(f.read() == before, "a failed merge leaves the output as it was") + code, out, err = run([tool, "--merge", merged, merged]) + expect(code == 2, "the output can't be an input", out, err) + code, out, err = run([tool, "--merge", merged, os.path.join(work, "missing.bin")]) + expect(code == 1, "an unreadable input fails the merge", out, err) + + # --names-file picks entries of the index; a name it doesn't have is a usage error. + names = os.path.join(work, "names.txt") + done = os.path.join(work, "both.done") + with open(names, "w", encoding="utf-8", newline="\n") as f: + f.write("m_echo\nm_alpha\n") + code, out, err = run([tool, both, "--jobs", "2", "--names-file", names, "--done-file", done]) + expect(code == 0 and "cs pipelines: 2 ok" in out, "--names-file selects two", out, err) + with open(done, encoding="utf-8") as f: + expect(f.read() == "m_alpha\nm_echo\n", "--done-file of a --names-file run") + with open(names, "w", encoding="utf-8", newline="\n") as f: + f.write("m_missing\n") + code, out, err = run([tool, both, "--names-file", names]) + expect(code == 2 and "not in" in err, "--names-file with a name the index lacks", out, err) + code, out, err = run([tool, both, "--isolate", "--done-file", done]) + expect(code == 2, "--done-file is refused with --isolate", out, err) + + for failure in failures: + print("FAIL:", failure) + if not failures: + print("vk_pipeline_check merge: ok") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/runtime/test/pipeline_cache_header.h b/runtime/test/pipeline_cache_header.h new file mode 100644 index 000000000..618827b14 --- /dev/null +++ b/runtime/test/pipeline_cache_header.h @@ -0,0 +1,74 @@ +// The VkPipelineCacheHeaderVersionOne at the start of a saved pipeline cache, read without a Vulkan device. +// +// vk_pipeline_check --merge refuses an input written by another GPU or driver before it reaches +// vkMergePipelineCaches: a driver may accept such data and quietly drop it, and then the merged cache would miss +// pipelines that make_game.py's done-list (docs/pipeline_check.md, "Shard caches and the done-list") counts as built. +#pragma once + +#include +#include +#include +#include + +namespace leonida::vk_test { + +struct PipelineCacheHeader { + uint32_t header_size = 0; + uint32_t version = 0; + uint32_t vendor = 0; + uint32_t device = 0; + uint8_t uuid[16] = {}; +}; + +// The header fields, little-endian as the Vulkan spec writes them. False when fewer than 32 bytes are there. +inline bool read_pipeline_cache_header(const void* data, size_t size, PipelineCacheHeader& header) { + if (!data || size < 32) return false; + const auto* bytes = static_cast(data); + auto word = [&](size_t at) { + return uint32_t(bytes[at]) | uint32_t(bytes[at + 1]) << 8 | uint32_t(bytes[at + 2]) << 16 | + uint32_t(bytes[at + 3]) << 24; + }; + header.header_size = word(0); + header.version = word(4); + header.vendor = word(8); + header.device = word(12); + for (size_t i = 0; i < 16; ++i) header.uuid[i] = bytes[16 + i]; + return true; +} + +inline std::string uuid_hex(const uint8_t (&uuid)[16]) { + std::string text; + char digits[3]; + for (const uint8_t byte : uuid) { + std::snprintf(digits, sizeof digits, "%02x", byte); + text += digits; + } + return text; +} + +// Empty when the data is a version-one cache of this device (vendor, device and pipelineCacheUUID); otherwise why not. +inline std::string pipeline_cache_mismatch(const void* data, size_t size, uint32_t vendor, uint32_t device, + const uint8_t (&uuid)[16]) { + PipelineCacheHeader header; + if (!read_pipeline_cache_header(data, size, header)) return "shorter than a pipeline cache header"; + char why[96]; + if (header.version != 1) { + std::snprintf(why, sizeof why, "header version %u, not 1", header.version); + return why; + } + if (header.header_size < 32 || header.header_size > size) { + std::snprintf(why, sizeof why, "header size %u in %zu bytes", header.header_size, size); + return why; + } + if (header.vendor != vendor || header.device != device) { + std::snprintf(why, sizeof why, "written by vendor 0x%04x device 0x%04x, this is 0x%04x 0x%04x", header.vendor, + header.device, vendor, device); + return why; + } + for (size_t i = 0; i < 16; ++i) + if (header.uuid[i] != uuid[i]) return "pipelineCacheUUID " + uuid_hex(header.uuid) + ", this driver's is " + + uuid_hex(uuid); + return {}; +} + +} // namespace leonida::vk_test diff --git a/runtime/test/pipeline_cache_header_test.cpp b/runtime/test/pipeline_cache_header_test.cpp new file mode 100644 index 000000000..340bc9779 --- /dev/null +++ b/runtime/test/pipeline_cache_header_test.cpp @@ -0,0 +1,66 @@ +// vk_pipeline_check --merge's check of a saved cache's header (pipeline_cache_header.h), without a Vulkan device. +#include "pipeline_cache_header.h" + +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace { + +void put(std::vector& data, size_t at, uint32_t value) { + for (int i = 0; i < 4; ++i) data[at + i] = uint8_t(value >> (8 * i)); +} + +std::vector cache(uint32_t version, uint32_t vendor, uint32_t device, const uint8_t (&uuid)[16]) { + std::vector data(48, 0xAB); // a header and some opaque driver data + put(data, 0, 32); + put(data, 4, version); + put(data, 8, vendor); + put(data, 12, device); + for (int i = 0; i < 16; ++i) data[16 + i] = uuid[i]; + return data; +} + +} // namespace + +int main() { + using leonida::vk_test::pipeline_cache_mismatch; + const uint8_t uuid[16] = {0x64, 0x4b, 0x88, 0x65, 0x79, 0x26, 0x38, 0x47, + 0xcb, 0x65, 0x75, 0xcc, 0x2a, 0x9e, 0xc8, 0x71}; + uint8_t other[16]; + for (int i = 0; i < 16; ++i) other[i] = uuid[i]; + other[15] ^= 1; + CHECK(leonida::vk_test::uuid_hex(uuid) == "644b886579263847cb6575cc2a9ec871"); + + const auto good = cache(1, 0x10de, 0x2783, uuid); + CHECK(pipeline_cache_mismatch(good.data(), good.size(), 0x10de, 0x2783, uuid).empty()); + CHECK(pipeline_cache_mismatch(good.data(), 31, 0x10de, 0x2783, uuid) == "shorter than a pipeline cache header"); + CHECK(pipeline_cache_mismatch(nullptr, 0, 0x10de, 0x2783, uuid) == "shorter than a pipeline cache header"); + + // Another vendor, another GPU of the same vendor, another driver build (UUID) and another header version. + CHECK(pipeline_cache_mismatch(good.data(), good.size(), 0x1002, 0x2783, uuid) == + "written by vendor 0x10de device 0x2783, this is 0x1002 0x2783"); + CHECK(!pipeline_cache_mismatch(good.data(), good.size(), 0x10de, 0x2704, uuid).empty()); + CHECK(pipeline_cache_mismatch(good.data(), good.size(), 0x10de, 0x2783, other).find("pipelineCacheUUID 644b") == 0); + const auto v2 = cache(2, 0x10de, 0x2783, uuid); + CHECK(pipeline_cache_mismatch(v2.data(), v2.size(), 0x10de, 0x2783, uuid) == "header version 2, not 1"); + + // A header size field that can't be right: below the version-one size or beyond the data. + auto small = good; + put(small, 0, 16); + CHECK(!pipeline_cache_mismatch(small.data(), small.size(), 0x10de, 0x2783, uuid).empty()); + auto big = good; + put(big, 0, 4096); + CHECK(!pipeline_cache_mismatch(big.data(), big.size(), 0x10de, 0x2783, uuid).empty()); + + std::puts("pipeline_cache_header: ok"); + return 0; +} diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 3ff89524f..90c6215cd 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -47,13 +47,27 @@ // --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted // as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F // after a crash, so the next run checks everything else instead of dying on the same module. +// --names-file F check only the index entries named in F (one per line), before --start/--count; a name that +// is not in the index is a usage error. make_game.py gives each process its batch this way. +// --done-file F at the end of the pass, F lists (one per line, sorted) the modules that passed: module created and +// pipeline created or skipped for a missing feature or stub, and the cache saved. Failed, crashed +// (--skip-file) and BIG SKIP modules are left out. Not with --isolate. // test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=[:SIGNAL] simulates a process crash // just before the pipeline of a matching module is created. For testing --isolate and the // pipelines stage's retry. +// +// Two other modes, without a spirv dir: +// vk_pipeline_check --device-info print "device-info vendor=0x.. device=0x.. driver=0x.. api=0x.. uuid=<32 hex> +// name=" for the device a check would use (LEONIDA_VK_DEVICE applies), then exit 0. +// vk_pipeline_check --merge ... load if it exists, add every input with +// vkMergePipelineCaches and save atomically. An input written by another device or driver +// (pipeline_cache_header.h) or that cannot be read fails the merge (exit 1) and is left +// as it was. make_game.py's pipelines stage merges its shard caches this way. #include "vulkan_loader.h" #include "vk_device_pick.h" #include "../src/pipeline_cache_file.h" #include "pipeline_cache_snapshot.h" +#include "pipeline_cache_header.h" #include "large_module_gate.h" #include "pipeline_summary.h" #include "../src/spirv_words.h" @@ -797,11 +811,36 @@ int main(int argc, char** argv) { "usage: vk_pipeline_check [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " "[--max-bytes N] [--large-module-bytes N] [--large-parallel N] [--stage all|cs|graphics | --compute-only | --graphics-only] " "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] " - "[--skip-file F]\n"); + "[--skip-file F] [--names-file F] [--done-file F]\n" + " vk_pipeline_check --device-info\n" + " vk_pipeline_check --merge ...\n"); return 2; } std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen - std::string dir = argv[1], cache_path, stats_path, inflight_path, skip_path; + enum class Mode { check, device_info, merge }; + const std::string_view first = argv[1]; + const Mode mode = first == "--device-info" ? Mode::device_info : first == "--merge" ? Mode::merge : Mode::check; + std::string dir = argv[1], cache_path, stats_path, inflight_path, skip_path, names_path, done_path; + std::vector merge_inputs; + if (mode == Mode::device_info && argc != 2) { + std::fprintf(stderr, "--device-info takes no other arguments\n"); + return 2; + } + if (mode == Mode::merge) { + if (argc < 4) { + std::fprintf(stderr, "--merge needs an output cache and at least one input cache\n"); + return 2; + } + cache_path = argv[2]; + merge_inputs.assign(argv + 3, argv + argc); + for (const auto& input : merge_inputs) { + std::error_code error; + if (input == cache_path || std::filesystem::equivalent(input, cache_path, error)) { + std::fprintf(stderr, "error: --merge output %s is also an input\n", cache_path.c_str()); + return 2; + } + } + } bool cache_given = false; // an empty cache_path alone can't tell "not given" from an empty argument uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2); size_t start = 0, count = 0, max_bytes = 0; @@ -811,7 +850,7 @@ int main(int argc, char** argv) { std::string stage_filter = "all"; bool cache_feedback = false, isolate = false, iso_child = false, nv_diagnostics = false; size_t isolate_batch = 256; - for (int i = 2; i < argc; i++) { + for (int i = 2; mode == Mode::check && i < argc; i++) { std::string a = argv[i]; auto value = [&]() -> std::string_view { if (i + 1 == argc || std::string_view(argv[i + 1]).starts_with("--")) return {}; @@ -852,6 +891,8 @@ int main(int argc, char** argv) { else if (a == "--stats") valid = !(stats_path = value()).empty(); else if (a == "--inflight-file") valid = !(inflight_path = value()).empty(); else if (a == "--skip-file") valid = !(skip_path = value()).empty(); + else if (a == "--names-file") valid = !(names_path = value()).empty(); + else if (a == "--done-file") valid = !(done_path = value()).empty(); else if (a == "--cache-feedback") cache_feedback = true; else if (a == "--isolate") isolate = true; else if (a == "--nv-diagnostics") nv_diagnostics = true; @@ -885,6 +926,10 @@ int main(int argc, char** argv) { std::fprintf(stderr, "--isolate cannot be combined with --stats\n"); return 2; } + if (isolate && !done_path.empty()) { // each child would overwrite the list of the one before + std::fprintf(stderr, "--isolate cannot be combined with --done-file\n"); + return 2; + } #ifdef _WIN32 if (iso_child) SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); #endif @@ -897,11 +942,13 @@ int main(int argc, char** argv) { // These inputs already exist on a valid invocation. Compare file identity so aliases are also protected. for (const auto& [option, output] : {std::pair{"cache path", &cache_path}, std::pair{"--stats", &stats_path}, - std::pair{"--inflight-file", &inflight_path}}) { + std::pair{"--inflight-file", &inflight_path}, + std::pair{"--done-file", &done_path}}) { if (output->empty()) continue; const char* input = nullptr; if (same_file(*output, index_path)) input = "index.json"; else if (!skip_path.empty() && same_file(*output, skip_path)) input = "--skip-file"; + else if (!names_path.empty() && same_file(*output, names_path)) input = "--names-file"; if (input) { std::fprintf(stderr, "error: %s must not overwrite %s\n", option, input); return 2; @@ -921,20 +968,43 @@ int main(int argc, char** argv) { } } + std::set only_names; // --names-file: the batch make_game.py gave this process + if (!names_path.empty()) { + std::ifstream nf(names_path); + if (!nf) { + std::fprintf(stderr, "error: cannot read --names-file %s\n", names_path.c_str()); + return 2; + } + for (std::string line; std::getline(nf, line);) { + while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) line.pop_back(); + if (!line.empty()) only_names.insert(line); + } + } + std::string index_err; bool index_unreadable = false; - auto index = read_index(index_path, index_err, index_unreadable); + // --device-info and --merge read no index: the work list stays empty and only the device is set up. + auto index = mode == Mode::check ? read_index(index_path, index_err, index_unreadable) + : decltype(read_index(index_path, index_err, index_unreadable)){}; if (!index_err.empty()) { std::fprintf(stderr, index_unreadable ? "error: cannot read %s/index.json: %s\n" : "error: malformed JSON in %s/index.json: %s\n", dir.c_str(), index_err.c_str()); return 2; } - std::fprintf(stderr, "%zu shaders in index\n", index.size()); + if (mode == Mode::check) std::fprintf(stderr, "%zu shaders in index\n", index.size()); + for (const auto& name : only_names) { + if (!index.count(name)) { + std::fprintf(stderr, "error: --names-file names %s, which is not in %s\n", name.c_str(), index_path.c_str()); + return 2; + } + } - // Build work list: index order (sorted by name), optionally filtered by stage, then [start, start + count). + // Build work list: index order (sorted by name), optionally filtered by --names-file and stage, then + // [start, start + count). using Item = std::pair; std::vector all; for (auto& [name, meta] : index) { + if (!names_path.empty() && !only_names.count(name)) continue; if (stage_filter == "cs" && meta.stage != "cs") continue; if (stage_filter == "graphics" && !is_graphics_stage(meta.stage)) continue; all.push_back({&name, &meta}); @@ -958,6 +1028,8 @@ int main(int argc, char** argv) { if (cache_feedback) pass.push_back("--cache-feedback"); if (!inflight_path.empty()) pass.insert(pass.end(), {"--inflight-file", inflight_path}); if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path}); + // The children's --start/--count index the same filtered list, so they need the same filter. + if (!names_path.empty()) pass.insert(pass.end(), {"--names-file", names_path}); struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; }; std::map agg; std::vector crashes; @@ -1106,6 +1178,13 @@ int main(int argc, char** argv) { return 1; } VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); + if (mode == Mode::device_info) { + // What a saved cache is tied to (its header) plus the driver version: make_game.py's done-list key. + std::printf("device-info vendor=0x%04x device=0x%04x driver=0x%08x api=0x%08x uuid=%s name=%s\n", + props.vendorID, props.deviceID, props.driverVersion, props.apiVersion, + leonida::vk_test::uuid_hex(props.pipelineCacheUUID).c_str(), props.deviceName); + return 0; + } VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; VkPhysicalDeviceVulkan11Properties indexing_limits{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES}; // Vulkan12Properties already includes the float controls (do not chain both promoted structs). @@ -1435,10 +1514,26 @@ int main(int argc, char** argv) { VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; std::vector seed; if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly - std::ifstream cf(cache_path, std::ios::binary); - seed.assign(std::istreambuf_iterator(cf), {}); + // One read of the whole file: a character-by-character copy took 21 s for 2 GiB (Windows 11, NVMe). + std::ifstream cf(cache_path, std::ios::binary | std::ios::ate); + const std::streamoff size = cf ? std::streamoff(cf.tellg()) : std::streamoff(0); + if (size > 0) { + seed.resize(size_t(size)); + cf.seekg(0); + if (!cf.read(seed.data(), size)) seed.clear(); // unreadable: start empty, as a missing file does + } if (!seed.empty()) std::fprintf(stderr, "seeded the pipeline cache with %zu bytes from %s\n", seed.size(), cache_path.c_str()); } + if (mode == Mode::merge && !seed.empty()) { + // An output from another GPU or driver holds nothing this device can use: start the merge empty instead. + const std::string why = leonida::vk_test::pipeline_cache_mismatch(seed.data(), seed.size(), props.vendorID, + props.deviceID, props.pipelineCacheUUID); + if (!why.empty()) { + std::fprintf(stderr, "note: %s is not this device's cache (%s); it is replaced\n", cache_path.c_str(), + why.c_str()); + std::vector().swap(seed); + } + } pci.initialDataSize = seed.size(); pci.pInitialData = seed.empty() ? nullptr : seed.data(); VkPipelineCache cache = VK_NULL_HANDLE; if (vkCreatePipelineCache(dev, &pci, nullptr, &cache)) { // data from another driver: start empty @@ -1466,6 +1561,56 @@ int main(int argc, char** argv) { } }; + if (mode == Mode::merge) { + // One input in memory at a time: a shard is read, handed to the driver, merged and freed before the next. + LOADD(vkMergePipelineCaches); LOADD(vkDestroyPipelineCache); + size_t merged = 0, skipped_empty = 0; + uint64_t merged_bytes = 0; + for (const auto& input : merge_inputs) { + std::ifstream in(input, std::ios::binary | std::ios::ate); + const std::streamoff size = in ? std::streamoff(in.tellg()) : std::streamoff(-1); + std::vector data(size > 0 ? size_t(size) : 0); + if (size > 0) { + in.seekg(0); + in.read(data.data(), size); + } + if (size < 0 || !in) { + std::fprintf(stderr, "error: cannot read %s; %s is left as it was\n", input.c_str(), cache_path.c_str()); + return 1; + } + if (data.empty()) { // a process that saved nothing (no pipeline was created) + ++skipped_empty; + continue; + } + const std::string why = leonida::vk_test::pipeline_cache_mismatch(data.data(), data.size(), props.vendorID, + props.deviceID, props.pipelineCacheUUID); + if (!why.empty()) { + std::fprintf(stderr, "error: %s is not this device's cache (%s); %s is left as it was\n", + input.c_str(), why.c_str(), cache_path.c_str()); + return 1; + } + VkPipelineCacheCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + info.initialDataSize = data.size(); + info.pInitialData = data.data(); + VkPipelineCache source = VK_NULL_HANDLE; + if (VkResult r = vkCreatePipelineCache(dev, &info, nullptr, &source)) { + std::fprintf(stderr, "error: vkCreatePipelineCache for %s failed: %d\n", input.c_str(), r); + return 1; + } + const VkResult r = vkMergePipelineCaches(dev, cache, 1, &source); + vkDestroyPipelineCache(dev, source, nullptr); + if (r) { + std::fprintf(stderr, "error: vkMergePipelineCaches with %s failed: %d\n", input.c_str(), r); + return 1; + } + ++merged; + merged_bytes += data.size(); + } + std::printf("merged %zu cache(s), %llu bytes%s\n", merged, static_cast(merged_bytes), + skipped_empty ? (", " + std::to_string(skipped_empty) + " empty input(s) skipped").c_str() : ""); + return save_cache(true) ? 0 : 1; + } + const auto worker_count = static_cast(std::min(jobs, work.size())); std::fprintf(stderr, "checking %zu shaders [%zu, %zu) (stage=%s) on %u threads\n", work.size(), lo, hi, stage_filter.c_str(), worker_count); @@ -1492,6 +1637,12 @@ int main(int argc, char** argv) { large_gate.max_inflight()); } std::map modules_ok, modules_bad, big_skipped; + std::set passed_names; // --done-file: modules with no failure (guarded by mu) + auto record_passed = [&](const std::string& name) { + if (done_path.empty()) return; + std::lock_guard g(mu); + passed_names.insert(name); + }; std::map stats; std::map stub_cache; std::atomic next{0}, done{0}; @@ -1547,6 +1698,8 @@ int main(int argc, char** argv) { auto& st = stats[stage]; st.pipes_skipped++; st.skip_reasons[reason]++; + // --done-file: this device skips it the same way every time, so there is nothing to build again + if (!done_path.empty()) passed_names.insert(name); std::printf("SKIPPED %s (%s)\n", name.c_str(), reason.c_str()); }; @@ -1702,6 +1855,7 @@ int main(int argc, char** argv) { if (mod_ok) modules_ok[stage]++; else { modules_bad[stage]++; std::printf("MODULE FAIL %s\n", name.c_str()); } } + bool passed = mod_ok; // --done-file: cleared below when the pipeline fails if (mod_ok && stage == "cs") { const std::string miss = check_missing_feature(meta); if (!miss.empty()) { @@ -1739,6 +1893,7 @@ int main(int argc, char** argv) { VkPipeline p = VK_NULL_HANDLE; maybe_simulate_crash(name); VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p); + passed = r == VK_SUCCESS; const double sec = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p); if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr); @@ -1913,6 +2068,7 @@ int main(int argc, char** argv) { VkPipeline p = VK_NULL_HANDLE; maybe_simulate_crash(name); VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p); + passed = r == VK_SUCCESS; const double sec = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p); if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr); @@ -1923,6 +2079,7 @@ int main(int argc, char** argv) { record_skip(name, stage, "unsupported stage " + stage); } if (sm) vkDestroyShaderModule(dev, sm, nullptr); + if (passed) record_passed(name); { // out of the driver on every path (a pipeline, a skip, a failed module) std::lock_guard g(mu); if (inflight.erase(std::this_thread::get_id()) && inflight.empty()) write_inflight(); @@ -2038,6 +2195,16 @@ int main(int argc, char** argv) { large_module_bytes); std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count); const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed + if (!done_path.empty()) { + // Only what reached the saved cache is done: without a cache save, the list is written empty. + std::string list; // sorted and each name once: a std::set + if (cache_saved) + for (const auto& name : passed_names) list += name + '\n'; + if (const auto error = write_pipeline_cache_file(done_path, list.data(), list.size())) { + std::fprintf(stderr, "cannot write --done-file %s: %s\n", done_path.c_str(), error.message().c_str()); + check_failed = true; + } + } if (stats_out) { const bool write_failed = std::ferror(stats_out) != 0; const bool close_failed = std::fclose(stats_out) != 0; diff --git a/tests/test_make_game_pipeline_batches.py b/tests/test_make_game_pipeline_batches.py index 49e3ad272..8d24dd6ec 100644 --- a/tests/test_make_game_pipeline_batches.py +++ b/tests/test_make_game_pipeline_batches.py @@ -26,12 +26,31 @@ import signal import sys +if sys.argv[1] == "--merge": + # The stand-in cache is a JSON list of completed names, so a merge is the output's list plus each input's. + out, *inputs = map(Path, sys.argv[2:]) + control = json.loads(Path(os.environ["SYNTHETIC_MERGE_CONTROL"]).read_text(encoding="utf-8")) + with Path(os.environ["SYNTHETIC_MERGE_CONTROL"]).with_name("merges.jsonl").open("a", encoding="utf-8", + newline="\n") as f: + f.write(json.dumps([str(p) for p in inputs]) + "\n") + if control.get("merge_exit"): + sys.exit(control["merge_exit"]) + # like the real merge, an output seed of another GPU or driver is replaced + seed = out.read_text(encoding="utf-8") if out.exists() else "[]" + merged = [] if seed.startswith("foreign") else json.loads(seed) + for p in inputs: + merged += json.loads(p.read_text(encoding="utf-8")) + out.write_text(json.dumps(merged), encoding="utf-8", newline="\n") + sys.exit(0) spirv, cache, *args = sys.argv[1:] spirv, cache = Path(spirv), Path(cache) config = json.loads((spirv / "control.json").read_text(encoding="utf-8")) names = sorted(json.loads((spirv / "index.json").read_text(encoding="utf-8")), key=lambda n: n.encode("utf-8")) def option(flag, default=None): return args[args.index(flag) + 1] if flag in args else default +names_file = option("--names-file") +if names_file: + names = [n for n in names if n in Path(names_file).read_text(encoding="utf-8").splitlines()] start = int(option("--start", 0)) count = int(option("--count", len(names))) selected = names[start:start + count] @@ -46,7 +65,8 @@ def record(event): if config.get("setup_error") or config.get("probe_setup_error") and count == 1 and option("--jobs") == "1": print("no Vulkan physical devices found", file=sys.stderr) sys.exit(config.get("setup_exit", 2)) -if config.get("interrupt") or config.get("interrupt_probe") and count == 1 and option("--jobs") == "1": +if (config.get("interrupt") or config.get("interrupt_probe") and count == 1 and option("--jobs") == "1" + or config.get("interrupt_at") in active): if os.name == "nt": import ctypes ctypes.windll.kernel32.ExitProcess(0xC000013A) @@ -72,11 +92,19 @@ def record(event): record("completed") if inflight: Path(inflight).write_text("", encoding="utf-8", newline="\n") +if option("--done-file"): + passed = sorted(n for n in active if n != config.get("invalid")) + Path(option("--done-file")).write_text("".join(n + "\n" for n in passed), encoding="utf-8", newline="\n") sys.exit(1 if skipped and set(selected).intersection(skipped) or config.get("invalid") in active else 0) ''' class PipelineBatchesTest(unittest.TestCase): + """A checker before --merge: every process loads and saves pipeline_cache.bin (BUILD-1030).""" + SHARDED = False + DEVICE = {"vendor": "0x10de", "device": "0x2783", "driver": "0x9b404000", "api": "0x00404165", + "uuid": "00" * 16, "name": "Synthetic GPU"} + def setUp(self): tmp = tempfile.TemporaryDirectory(prefix="pipeline batches ") self.addCleanup(tmp.cleanup) @@ -90,27 +118,39 @@ def setUp(self): self.child = self.root / "checker.py" self.child.write_text(CHECKER, encoding="utf-8", newline="\n") self.commands = [] + self.device = dict(self.DEVICE) + self.fingerprint = "sources:synthetic" - def write_index(self, names): - (self.spirv / "index.json").write_text(json.dumps({n: {} for n in reversed(names)}), + def write_index(self, names, meta=None): + (self.spirv / "index.json").write_text(json.dumps({n: (meta or {}).get(n, {}) for n in reversed(names)}), encoding="utf-8", newline="\n") + for n in names: # the done-list keys a module by its .spv; these bytes only stand for one + if not (self.spirv / (n + ".spv")).exists(): + (self.spirv / (n + ".spv")).write_bytes(n.encode()) def invoke(self, control=None, range_support=True): (self.spirv / "control.json").write_text(json.dumps(control or {}), encoding="utf-8", newline="\n") + merge_control = self.root / "merge_control.json" + merge_control.write_text(json.dumps(control or {}), encoding="utf-8", newline="\n") def run(args, hint="", check=True, **kwargs): args = [str(a) for a in args] self.commands.append(args) done = subprocess.run([sys.executable, "-I", str(self.child), *args[1:]], - capture_output=True, text=True, timeout=15) + capture_output=True, text=True, timeout=15, + env=dict(os.environ, SYNTHETIC_MERGE_CONTROL=str(merge_control))) if check and done.returncode: raise SystemExit(1) return done.returncode def supports(exe, *options): + if "--merge" in options: + return self.SHARDED return range_support or "--start" not in options logs, err = [], io.StringIO() # create=True keeps the regression runnable on the old implementation, which lacks this constant. with mock.patch.object(make_game, "pipeline_check_exe", return_value="synthetic-checker"), \ mock.patch.object(make_game, "checker_supports", side_effect=supports), \ + mock.patch.object(make_game, "checker_device_info", side_effect=lambda exe: dict(self.device)), \ + mock.patch.object(make_game, "checker_fingerprint", side_effect=lambda exe: self.fingerprint), mock.patch.object(make_game, "pipeline_cache_device", side_effect=self.cache_device), \ mock.patch.object(make_game, "PIPELINE_BATCH_SIZE", 3, create=True), \ mock.patch.object(make_game, "run", side_effect=run), \ mock.patch.object(make_game, "log", side_effect=logs.append), contextlib.redirect_stderr(err): @@ -120,6 +160,25 @@ def supports(exe, *options): return exc.code, logs, err.getvalue() return 0, logs, err.getvalue() + def cache_device(self, path): + """The stand-in cache has no Vulkan header: it is this device's unless a test marks it foreign.""" + try: + text = Path(path).read_text(encoding="utf-8") + except OSError: + return None + if text.startswith("foreign"): + return 0x1002, 0x73BF, "22" * 16 + return int(self.device["vendor"], 16), int(self.device["device"], 16), self.device["uuid"] + + def extra_set(self, name, modules=("x_0",), control=None): + folder = self.spirv / name + folder.mkdir(exist_ok=True) + (folder / "index.json").write_text(json.dumps({m: {} for m in modules}), encoding="utf-8", newline="\n") + (folder / "control.json").write_text(json.dumps(control or {}), encoding="utf-8", newline="\n") + for m in modules: + (folder / (m + ".spv")).write_bytes(f"{name}/{m}".encode()) + return folder + def calls(self, event=None): path = self.spirv / "calls.jsonl" rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] if path.exists() else [] @@ -146,6 +205,18 @@ def test_bvh_pipelines_are_added_to_the_runtime_seed(self): rows = [json.loads(line) for line in (bvh / "calls.jsonl").read_text(encoding="utf-8").splitlines()] self.assertEqual([row["selected"] for row in rows if row["event"] == "completed"], [["b_0"]]) + def test_fspx_and_exe_pipelines_are_added_to_the_runtime_seed_but_not_library(self): + self.extra_set("fspx", ["f_0", "f_1"]) + self.extra_set("exe", ["e_0"]) + self.extra_set("library", ["l_0"]) + self.extra_set("fspx_gfx", ["g_0"]) + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(sorted(json.loads((self.out / "pipeline_cache.bin").read_text(encoding="utf-8"))), + sorted(self.names + ["f_0", "f_1", "e_0"])) + self.assertFalse(any(c[1] in (str(self.spirv / "library"), str(self.spirv / "fspx_gfx")) + for c in self.commands)) + def test_collective_memory_crash_splits_without_skipping_healthy_modules(self): code, logs, err = self.invoke({"max_batch": 2}) self.assertEqual(code, 0, err) @@ -243,5 +314,271 @@ def test_small_indices_keep_the_single_run(self): self.assertEqual(len(self.commands), 1) +class ShardedPipelineBatchesTest(PipelineBatchesTest): + """The same recovery with a checker that has --merge (PIPELINES-STAGE-SHARDS-AND-DONE-LIST): each process writes + its own shard cache, the shards are merged into pipeline_cache.bin once, and a module already built for the + same GPU, driver and checker is not checked again.""" + SHARDED = True + + def shard_dir(self): + return self.out / "pipeline_shards" + + def done_list(self): + return json.loads((self.out / "pipeline_done.json").read_text(encoding="utf-8")) + + def merges(self): + path = self.root / "merges.jsonl" + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] if path.exists() else [] + + def checked(self, since=0): + return [n for row in self.calls("completed")[since:] for n in row["active"]] + + def cache(self): + return json.loads((self.out / "pipeline_cache.bin").read_text(encoding="utf-8")) + + def test_an_older_checker_gets_no_unsupported_range_arguments(self): + self.skipTest("a checker with --merge also has --names-file") + + def test_small_indices_keep_the_single_run(self): + self.write_index(self.names[:2]) + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual([c[1] for c in self.commands], [str(self.spirv), "--merge"]) # one check, one merge + + def test_each_process_writes_its_own_shard_and_one_merge_makes_the_cache(self): + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + checks = [c for c in self.commands if c[1] != "--merge"] + shards = [c[2] for c in checks] + self.assertEqual([os.path.basename(s) for s in shards], ["00001.bin", "00002.bin", "00003.bin"]) + self.assertTrue(all(os.path.dirname(s) == str(self.shard_dir()) for s in shards), shards) + self.assertFalse(any(str(self.out / "pipeline_cache.bin") in c for c in checks)) # never loaded per batch + self.assertEqual(len(self.merges()), 1) + self.assertEqual(self.merges()[0], shards) + self.assertEqual(self.cache(), self.names) + self.assertFalse(self.shard_dir().exists(), "the shards are removed after a good merge") + self.assertEqual(sorted(self.done_list()["modules"]), self.names) + self.assertTrue(all(r["shard"] is None for r in self.done_list()["modules"].values())) + + def test_the_done_list_is_written_with_lf_line_endings(self): + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertNotIn(b"\r\n", (self.out / "pipeline_done.json").read_bytes()) + + def test_a_rerun_skips_every_module_already_built(self): + self.assertEqual(self.invoke()[0], 0) + before, commands = len(self.calls("started")), len(self.commands) + code, logs, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(len(self.calls("started")), before, "no checker process for an unchanged corpus") + self.assertEqual(len(self.commands), commands) + self.assertEqual(self.cache(), self.names) + self.assertTrue(any("7 of 7 modules are already built" in line for line in logs), logs) + + def test_only_a_module_whose_spirv_changed_is_built_again(self): + self.assertEqual(self.invoke()[0], 0) + since = len(self.calls("completed")) + (self.spirv / "m_04.spv").write_bytes(b"retranslated") + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(self.checked(since), ["m_04"]) + self.assertEqual(self.cache(), self.names + ["m_04"]) # merged onto what the cache already held + self.assertEqual(len(self.merges()), 2) + + def test_a_changed_index_entry_is_built_again(self): + self.assertEqual(self.invoke()[0], 0) + since = len(self.calls("completed")) + self.write_index(self.names, meta={"m_02": {"stage": "cs", "push_constant_bytes": 128}}) + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(self.checked(since), ["m_02"]) + + def test_a_new_driver_or_checker_or_stub_builds_everything_again(self): + changes = { + "driver": lambda: self.device.update(driver="0x9b408000"), + "pipelineCacheUUID": lambda: self.device.update(uuid="11" * 16), + "GPU": lambda: self.device.update(device="0x2704"), + "checker": lambda: setattr(self, "fingerprint", "sources:other"), + "stubs": lambda: ((self.spirv / "stubs").mkdir(exist_ok=True), + (self.spirv / "stubs" / "vs_0.spv").write_bytes(b"stub")), + } + self.assertEqual(self.invoke()[0], 0) + cache = str(self.out / "pipeline_cache.bin") + for what, change in changes.items(): + with self.subTest(what=what): + since, commands = len(self.calls("completed")), len(self.commands) + change() + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(sorted(self.checked(since)), self.names) + targets = {c[2] for c in self.commands[commands:] if c[1] != "--merge"} + if what in ("checker", "stubs"): + # Same driver: what the cache holds is still valid, so the checks load it instead of starting + # empty shards, and the next change goes to shards again. + self.assertEqual(targets, {cache}) + self.assertFalse(self.done_list()["migrating"]) + else: + self.assertNotIn(cache, targets) + + def test_a_new_checker_keeps_leftover_shards_of_the_same_driver(self): + code, _, _ = self.invoke({"interrupt_at": "m_03"}) + self.assertNotEqual(code, 0) + self.assertTrue((self.shard_dir() / "00001.bin").exists()) + self.fingerprint = "sources:other" + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + # No pipeline_cache.bin yet, so the new checker's checks go to new shards; the old one is merged with them. + self.assertEqual([os.path.basename(p) for p in self.merges()[-1]][0], "00001.bin") + self.assertFalse(self.shard_dir().exists()) + self.assertEqual(sorted(set(self.cache())), self.names) + + def test_an_interrupted_run_keeps_its_shards_and_the_next_run_finishes_the_rest(self): + code, _, _ = self.invoke({"interrupt_at": "m_03"}) + self.assertNotEqual(code, 0) + self.assertEqual(self.merges(), [], "a stopped run does not merge") + self.assertEqual([p.name for p in self.shard_dir().iterdir()], ["00001.bin"]) + self.assertFalse((self.out / "pipeline_cache.bin").exists()) + self.assertEqual(sorted(self.done_list()["modules"]), self.names[:3]) + since = len(self.calls("completed")) + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(self.checked(since), self.names[3:]) + self.assertEqual(sorted(self.cache()), self.names) + self.assertEqual([os.path.basename(p) for p in self.merges()[0]], ["00001.bin", "00002.bin", "00003.bin"]) + self.assertFalse(self.shard_dir().exists()) + + def test_a_failed_merge_keeps_the_shards_for_the_next_run(self): + code, _, err = self.invoke({"merge_exit": 1}) + self.assertNotEqual(code, 0) + self.assertIn("merges them again", err) + self.assertEqual(len(list(self.shard_dir().iterdir())), 3) + self.assertFalse((self.out / "pipeline_cache.bin").exists()) + before = len(self.calls("started")) + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(len(self.calls("started")), before, "nothing is checked again, the shards are merged") + self.assertEqual(self.cache(), self.names) + + def test_the_bvh_pass_runs_again_only_when_its_shaders_change(self): + bvh = self.spirv / "bvh" + bvh.mkdir() + (bvh / "index.json").write_text('{"b_0": {}}', encoding="utf-8") + (bvh / "control.json").write_text("{}", encoding="utf-8") + (bvh / "b_0.spv").write_bytes(b"bvh") + bvh_runs = lambda: sum(1 for c in self.commands if c[1] == str(bvh)) # noqa: E731 + self.assertEqual(self.invoke()[0], 0) + self.assertEqual((bvh_runs(), len(self.merges())), (1, 1)) + self.assertEqual(self.invoke()[0], 0) + self.assertEqual((bvh_runs(), len(self.merges())), (1, 1), "an unchanged corpus needs no process or merge") + (bvh / "b_0.spv").write_bytes(b"bvh, rebuilt") + self.assertEqual(self.invoke()[0], 0) + self.assertEqual((bvh_runs(), len(self.merges())), (2, 2)) + self.assertEqual(self.cache(), self.names + ["b_0", "b_0"]) + + def test_fspx_and_exe_run_again_only_when_their_shaders_change(self): + fspx = self.extra_set("fspx", ["f_0", "f_1"]) + exe = self.extra_set("exe", ["e_0"]) + runs = lambda folder: sum(1 for c in self.commands if c[1] == str(folder)) # noqa: E731 + self.assertEqual(self.invoke()[0], 0) + self.assertEqual((runs(fspx), runs(exe), len(self.merges())), (1, 1, 1)) + self.assertEqual(sorted(self.done_list()["extras"]), ["exe", "fspx"]) + self.assertTrue(all(r["shard"] is None for r in self.done_list()["extras"].values())) + self.assertEqual(self.invoke()[0], 0) + self.assertEqual((runs(fspx), runs(exe), len(self.merges())), (1, 1, 1)) + (fspx / "f_1.spv").write_bytes(b"fspx, retranslated") + self.assertEqual(self.invoke()[0], 0) + self.assertEqual((runs(fspx), runs(exe), len(self.merges())), (2, 1, 2)) + + def test_a_failing_extra_set_is_not_recorded_but_the_rest_is_merged(self): + self.extra_set("fspx", ["f_0"], control={"invalid": "f_0"}) + exe = self.extra_set("exe", ["e_0"]) + code, _, _ = self.invoke() + self.assertNotEqual(code, 0) + self.assertEqual(len(self.merges()), 1) + self.assertEqual(sorted(self.done_list()["extras"]), ["exe"]) + self.assertIn("e_0", self.cache()) + self.assertEqual(sum(1 for c in self.commands if c[1] == str(exe)), 1, "the next set still runs") + + def test_a_done_list_from_before_the_extra_sets_keeps_its_bvh_record(self): + bvh = self.extra_set("bvh", ["b_0"]) + self.assertEqual(self.invoke()[0], 0) + doc = self.done_list() + doc["bvh"] = doc.pop("extras")["bvh"] + (self.out / "pipeline_done.json").write_text(json.dumps(doc), encoding="utf-8", newline="\n") + before = len(self.calls("started")) + self.assertEqual(self.invoke()[0], 0) + self.assertEqual(len(self.calls("started")), before) + self.assertEqual(sum(1 for c in self.commands if c[1] == str(bvh)), 1) + self.assertNotIn("bvh", self.done_list()) + self.assertEqual(sorted(self.done_list()["extras"]), ["bvh"]) + + def test_an_outside_write_to_the_cache_keeps_the_done_list(self): + self.assertEqual(self.invoke()[0], 0) + # e.g. the checker run straight into pipeline_cache.bin for another shader set: larger and newer + cache = self.out / "pipeline_cache.bin" + cache.write_text(json.dumps(self.cache() + ["outside_0", "outside_1"]), encoding="utf-8", newline="\n") + before = len(self.calls("started")) + code, logs, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(len(self.calls("started")), before, "nothing is checked again") + self.assertTrue(any("keeping the done-list" in line for line in logs), logs) + self.assertEqual(sorted(self.done_list()["modules"]), self.names) + self.assertEqual(self.done_list()["cache"]["size"], cache.stat().st_size) + code, logs, err = self.invoke() # the new stamp is recorded, so it is not reported again + self.assertEqual(code, 0, err) + self.assertFalse(any("keeping the done-list" in line for line in logs), logs) + + def test_a_shrunken_or_foreign_cache_checks_its_modules_again_and_says_why(self): + for what, text, reason in (("shrank", "[]", "shrank from"), + ("foreign", "foreign" + " " * 4096, "not by this GPU and driver")): + with self.subTest(what=what): + self.assertEqual(self.invoke()[0], 0) + (self.out / "pipeline_cache.bin").write_text(text, encoding="utf-8", newline="\n") + since = len(self.calls("completed")) + code, logs, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(sorted(self.checked(since)), self.names) + self.assertTrue(any(reason in line and "7 module(s)" in line for line in logs), logs) + (self.out / "pipeline_cache.bin").unlink() + (self.out / "pipeline_done.json").unlink() + + def test_a_removed_cache_builds_everything_again(self): + self.assertEqual(self.invoke()[0], 0) + (self.out / "pipeline_cache.bin").unlink() + since = len(self.calls("completed")) + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(self.checked(since), self.names) + + def test_a_crasher_and_a_failed_module_are_not_done(self): + code, _, _ = self.invoke({"crasher": "m_01", "invalid": "m_05"}) + self.assertNotEqual(code, 0) + self.assertEqual(sorted(self.done_list()["modules"]), sorted(set(self.names) - {"m_01", "m_05"})) + self.assertEqual(len(self.merges()), 1, "what was built is still merged after a failure") + since = len(self.calls("completed")) + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(sorted(self.checked(since)), ["m_01", "m_05"]) + + def test_the_first_run_over_an_existing_cache_checkpoints_into_it(self): + # A cache from before the done-list: its pipelines must still compile from it, so the first run keeps + # the old per-process load and save instead of starting empty shards. + (self.out).mkdir() + (self.out / "pipeline_cache.bin").write_text(json.dumps(["old"]), encoding="utf-8", newline="\n") + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + checks = [c for c in self.commands if c[1] != "--merge"] + self.assertTrue(all(c[2] == str(self.out / "pipeline_cache.bin") for c in checks), checks) + self.assertEqual(self.merges(), []) + self.assertEqual(self.cache(), ["old"] + self.names) + self.assertFalse(self.done_list()["migrating"]) + since = len(self.calls("completed")) + (self.spirv / "m_06.spv").write_bytes(b"changed") + code, _, err = self.invoke() + self.assertEqual(code, 0, err) + self.assertEqual(self.checked(since), ["m_06"]) + self.assertEqual(len(self.merges()), 1, "after the first run, shards") + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_make_game_pipelines.py b/tests/test_make_game_pipelines.py index e0f15ba6f..9b12717bf 100644 --- a/tests/test_make_game_pipelines.py +++ b/tests/test_make_game_pipelines.py @@ -135,8 +135,13 @@ def fake_run(args, hint="", check=True, **kw): raise SystemExit(1) return code logs = [] + + def legacy(exe, *options): + # A checker before --merge: shard caches and the done-list are tested in + # test_make_game_pipeline_batches.py; these tests pin the --start/--count protocol it still gets. + return supports and "--merge" not in options with mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"), \ - mock.patch.object(make_game, "checker_supports", return_value=supports), \ + mock.patch.object(make_game, "checker_supports", side_effect=legacy), \ mock.patch.object(make_game, "run", side_effect=fake_run), \ mock.patch.object(make_game, "log", logs.append): try: