Skip to content

pso_state_decode: read the pipeline library's graphics state blobs as GPU registers (slot 57) - #8507

Closed
FIocker wants to merge 1 commit into
ProjectLeonida:mainfrom
FIocker:feat/pso-state-decode
Closed

FIocker wants to merge 1 commit into
ProjectLeonida:mainfrom
FIocker:feat/pso-state-decode

Conversation

@FIocker

@FIocker FIocker commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Claimed in #8344 (comment). For device slot 57: @ruvenesh's #8273 measured its description and lists "the 380 to 404 B state blob decoded into a PC graphics pipeline description" as one of the two things a handler needs. This PR is that decoding. The handler stays with ruvenesh.

What the state blob is

Slot 57's six (pointer, size) pairs line up with the pipeline library's graphics records (docs/shader_library.md §2):

pair contents measured size
0 state blob 380–404 B
1 input-layout blob 80–224 B
2 PS program
3 PS stage blob
4 VS program
5 VS stage blob

The state blob is a block of GPU context register values in two fixed layouts:

word 1 pipelines size
4 every VS (+ PS) pipeline 380–420 B
6 every MS (+ PS) pipeline 464–520 B; the same registers sit 0x54 bytes later

I identified the registers from the values alone, by their RDNA2 field layouts:

  • SPI_SHADER_COL_FORMAT, CB_SHADER_MASK, CB_TARGET_MASK
  • CB_BLEND0..7_CONTROL
  • SX_PS_DOWNCONVERT, SX_BLEND_OPT_EPSILON / _CONTROL, SX_MRT0..7_BLEND_OPT
  • DB_DEPTH_CONTROL, DB_STENCIL_CONTROL, DB_STENCILREFMASK(_BF)

Checks over all 5,680 distinct state blobs of 1.0.2.1 (counts only):

  • Blend: blending is on for render target n exactly when SX_MRTn_BLEND_OPT is not the "blend disabled" word 0x06000600. That holds in all 45,440 (blob, target) pairs. Every enabled word decodes to an ordinary D3D12 blend: SRC_ALPHA/INV_SRC_ALPHA, premultiplied, dual-source SRC1_*, MAX, DEST_COLOR multiply.
  • Masks: the four per-target masks are non-zero from target 0 upwards in 97–100% of the blobs. 230 blobs have no colour target.
  • Depth: no blob writes depth with the depth test off. Mesh pipelines mostly test GREATER_EQUAL (reversed Z).
  • Matching a description: within the records built from the same shaders, these are the words that differ. The blend block differs in about 4,770 of 8,786 VS pairs, then depth and stencil. So a title's description can be matched to one record through them.

Not decoded: the rasterizer state, the topology and the other words. Nothing here is measured on a console; it is a reading of the data, to be checked against a handler's results.

Changes

  • tools/pso_state_decode.py (new): <library or shaders.rpf> --out <file.json> [--summary]. For each graphics record it writes the D3D12-level reading: render targets, export formats, format class, write masks, blend, depth and stencil. The output is game data.
  • tests/test_pso_state_decode.py (new): decodes hand-built blobs of both layouts. It also covers an inconsistent blend-optimisation word, refused layouts, and the CLI on a library built with test_shader_library.py's helpers. 5 passed.
  • docs/shader_library.md §7: the register table and the checks.

Tests

  • tests/test_pso_state_decode.py, tests/test_shader_library.py: pass.
  • tests/test_docs_*.py, tests/test_ci_registration.py: pass, except four failures that come from other pages (embedded_shaders.md flags, strand_grooms.md links, …). test_docs_cli_flags and test_docs_links fail the same way on current main (also noted in docs/fspx: device slot 57's description, measured over 10,000 calls (RT-5) #8273). The other two (test_docs_design_rows on README.md, test_docs_repo_paths) are in files this PR doesn't touch.
  • scripts/check_no_game_data.py: exit 0.

AI-assisted (Claude Code). Windows 11, Python 3.12, no GPU used.

🤖 Generated with Claude Code

… GPU registers

Device slot 57 passes a graphics pipeline description whose first (pointer, size) pair is the
380-404-byte state blob of the library's graphics records (ItsNotRexed#8273). A slot-57 handler needs it
decoded into a PC pipeline description. The blob is a block of GPU context register values in
two fixed layouts: word 1 == 4 for every VS(+PS) pipeline, 6 for every MS(+PS) pipeline, whose
colour and depth registers sit 0x54 bytes later. Identified from the values by their RDNA2 field
layouts and checked over all 5,680 distinct 1.0.2.1 blobs: SPI_SHADER_COL_FORMAT, CB_SHADER_MASK,
CB_TARGET_MASK, CB_BLEND0..7_CONTROL, SX_PS_DOWNCONVERT, SX_BLEND_OPT_EPSILON/CONTROL,
SX_MRT0..7_BLEND_OPT, DB_DEPTH_CONTROL, DB_STENCIL_CONTROL, DB_STENCILREFMASK(_BF).
* Blending is on for render target n exactly when SX_MRTn_BLEND_OPT is not the "disabled" word,
  in all 45,440 (blob, target) pairs, and every enabled word decodes to a D3D12 blend.
* No blob writes depth with the depth test off; mesh pipelines mostly test GREATER_EQUAL.

tools/pso_state_decode.py writes, per graphics record, the D3D12-level reading: render targets,
export formats, format class, write masks, blend, depth and stencil. docs/shader_library.md §7
gives the register table and the checks. tests/test_pso_state_decode.py decodes hand-built blobs
of both layouts, an inconsistent blend-optimisation word, refused layouts and the CLI on a
built library. The rasterizer words and the topology are not decoded; nothing is measured on a
console.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@Altorru Altorru left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Data-loss finding: --out is not checked against --src, so the report can overwrite the archive it decodes.

At head, main() reads a.src (line 124) and then opens a.out for writing (line 141). Nothing refuses --out naming the input, and shaders.rpf is the file this tool is documented to be run on — so the natural mistake of reusing the path destroys a game archive that took a full unpack to produce.

Measured at 1d1cfd8 with a library built from the test helpers (1,389 bytes):

psd.main([src, "--out", src])
-> rc: 0 | size before: 1389 | size after: 956
   after head: b'[\n {\n  "record": 0,\n  "state": 0,\n ...'

Exit 0, no warning, input gone. This is the collision tools/report_paths.py exists for — its own docstring: "One answer for the tools that refuse an output that would overwrite an input or another output" — and the sibling tools you can see merging right now (#8418, #8486, #8413, #8468) all guard it with same_report_path, which also catches a symlink or hard link to the input that a plain string compare would miss.

Ready-to-merge fix:

 import shader_library as sl  # noqa: E402
+from report_paths import same_report_path  # noqa: E402
@@
     a = ap.parse_args(argv)
+    # Writing the report over the archive it came from is a one-way loss: refuse before the read.
+    if same_report_path(a.src, a.out):
+        print(f"ERROR: --out {a.out} would overwrite the input; pass another path", file=sys.stderr)
+        return 2
     with open(a.src, "rb") as f:

and a test beside test_cli_on_a_library:

def test_out_that_is_the_input_is_refused(self):
    lib = LIB_TESTS["build"]([(0, 1, {0: (0, 2), 1: (1, 3)})], [],
                             [state(psd.VS_LAYOUT, 388, FIELDS), b"POSITION\0",
                              LIB_TESTS["layout_blob"](2, LIB_TESTS["D_PS"]),
                              LIB_TESTS["layout_blob"](2, LIB_TESTS["D_VS"], 2)],
                             [LIB_TESTS["prog"](1), LIB_TESTS["prog"](2, 5)])
    with tempfile.TemporaryDirectory() as tmp:
        src = os.path.join(tmp, "lib.bin")
        with open(src, "wb") as f:
            f.write(lib)
        self.assertEqual(psd.main([src, "--out", src]), 2)
        with open(src, "rb") as f:
            self.assertEqual(f.read(), lib)

Exit 2 matches the other refusals in this tool family. I did not run the patched tree (macOS arm64, CPython 3.14.8, no game data); the clobber above is a real run of the head, and the new tests/test_pso_state_decode.py passes 6/6 at that head. AI-assisted (Codebuff).

@Atomic258

Copy link
Copy Markdown
Contributor

Tested e5658e4f on Windows Server 2022, CPython 3.13.12: pass

  • python -I tests/test_pso_state_decode.py -> OK (1 graphics record decoded cleanly)

git diff --check clean; python -m compileall -q exit 0. No game files, no GPU. AI-assisted (Devin).

@hah346

hah346 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Independent Windows check of e5658e4. All five decoder tests passed. The offline decoder walked 25,471 graphics records and decoded all 5,680 distinct state blobs in my local 1.0.2.1 copy.

I also measured candidate ambiguity for #8273's slot-57 lookup. Restricting the library to the 13,407 VS-only or VS+PS records gives:

Lookup inputs from the library Distinct keys Keys with multiple distinct state blobs
Stage program IDs 3,148 1,002
Stage-program, stage-blob and input-layout byte sizes 1,528 440
Exact stage-program, stage-blob and input-layout content 13,394 0

For all graphics stages, 25,229 exact-content keys also map to a single distinct state blob each. For the VS subset there are 13 duplicate records by the content key, but their state bytes agree. This suggests using the payloads as a lookup key if their runtime bytes match the library representation. This was an offline catalog check. I did not compare actual slot-57 arguments or validate a Vulkan draw. Counts only, no game payloads, hashes or addresses. AI-assisted.

Comment thread tools/pso_state_decode.py
"func_back": COMPARE[(depth >> 20) & 7] if (depth >> 7) & 1 else COMPARE[(depth >> 8) & 7],
"front": ops(sc, 0), "back": ops(sc, 12),
"ref": ref & 0xFF, "read_mask": (ref >> 8) & 0xFF, "write_mask": (ref >> 16) & 0xFF,
"read_mask_back": (ref_bf >> 8) & 0xFF, "write_mask_back": (ref_bf >> 16) & 0xFF},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please preserve the back-face stencil test reference alongside ref. The existing fixture already enables two-sided stencil with EQUAL on both faces. Its front reference is 5 and its back reference is 0. The decoder reads ref_bf, but only emits its two mask bytes. Changing the fixture’s back word from 0x01FF0F00 to 0x01FF0F05 therefore leaves the whole decoded stencil object identical. With a stored stencil value of 0 and the fixture’s read mask of 0x0F, the first back-face comparison passes and the second fails. GFX10.3 defines bits 0–7 of DB_STENCILREFMASK_BF as STENCILTESTVAL_BF. Register definition

Adding "ref_back": ref_bf & 0xFF and asserting (ref, ref_back) == (5, 0) in the shared fixture check would preserve the distinction in both layouts. This is an offline report discrepancy. I checked the pinned source and evaluated the two public fixture words on an Intel Core Ultra 7 265K. No GPU or title run. Review claim

AI-assisted by GPT-6.2 Astra.

@Hiiva

Hiiva commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Synthetic finding at e5658e4f4167c173e60b03f31641a17cfb64f6df: sparse color-export slots lose later per-target state in tools/pso_state_decode.py:88-105.

The loop stops at the first zero nibble of SPI_SHADER_COL_FORMAT. For the hand-built value 0x404, slots 0 and 2 have FP16 exports, but the report contains only slot 0. Slot 2's export format, downconvert, write/shader masks and blend fields are omitted. Changing its write mask from 15 to 7 and source blend from SRC_ALPHA to ONE leaves the entire decoded state identical.

Reproducer using this PR's existing synthetic fixture helpers, from the repository root:

import runpy
t = runpy.run_path("tests/test_pso_state_decode.py")
p = t["psd"]
a = {**t["FIELDS"], p.COL_FORMAT: 0x404,
     p.SHADER_MASK: 0xF0F, p.TARGET_MASK: 0xF0F,
     p.DOWNCONVERT: 0x505,
     p.BLEND + 8: t["ALPHA_BLEND"],
     p.MRT_BLEND_OPT + 8: 0x01510154}
b = {**a, p.TARGET_MASK: 0x70F,
     p.BLEND + 8: (t["ALPHA_BLEND"] & ~0x1F) | 1}
for layout, size in ((p.VS_LAYOUT, 388), (p.MS_LAYOUT, 464)):
    before = p.decode(t["state"](layout, size, a))
    after = p.decode(t["state"](layout, size, b))
    assert before == after
    assert before["render_targets"] == 1
    assert before["blend_opt_consistent"]

Confirmed on Windows using only authored CPU fixtures. All 15 existing decoder/library tests pass. Across all 256 synthetic active-slot masks in each layout, 247 sparse patterns omit later active slots. Two hand-built two-record libraries reproduce the loss through the CLI as well; both source files remain unchanged.

Please retain slot positions and the per-target fields through the last nonzero export, including zero-valued gaps, instead of truncating at the first gap. A regression using the two records above should distinguish their slot-2 write mask and blend state in both layouts. This finding concerns the offline report only; no game inputs, title execution or GPU were used.

@akimfomin

Copy link
Copy Markdown

Independent Windows CPU check at e5658e4f with CPython 3.12.14. All five stock tests passed. I ran the actual CLI on a raw synthetic library and the same library stored in two valid zlib blocks. A VS state straddled the 64 KiB boundary. Two nonadjacent graphics records shared it, and the middle record used the MS layout. Both paths decoded 3 records / 2 distinct states / 0 failures, with byte-identical JSON and matching summaries. The export, mask and depth fields checked matched the fixture values. Synthetic files only. AI-assisted (Codex).

@Envyre

Envyre commented Nov 23, 2026

Copy link
Copy Markdown

Checked the field layouts in tools/pso_state_decode.py against the RDNA2 register definitions (CB_BLENDn_CONTROL, DB_DEPTH_CONTROL, DB_STENCIL_CONTROL, DB_STENCILREFMASK, SPI_SHADER_COL_FORMAT, SX_PS_DOWNCONVERT incl. 9_9_9_E5) and the enum tables. Bit positions and values all match. The size check at :84 covers the furthest MS-layout read (0x174). tests/test_pso_state_decode.py passes (5/5).

Two small gaps in the "D3D12-level reading":

  1. blend() :70: when SEPARATE_ALPHA_BLEND (bit 29) is clear, the alpha factors are copied from colour unchanged. A DEST_COLOR/ZERO multiply blend then gives src_alpha: "DEST_COLOR", and D3D12 rejects *_COLOR factors in SrcBlendAlpha/DestBlendAlpha. Mapping X_COLOR to X_ALPHA on the alpha side would keep the output valid.
  2. Stencil back face :111-114: func_back checks BACKFACE_ENABLE (DEPTH_CONTROL bit 7), but back ops and read_mask_back/write_mask_back always read the _BF fields. With bit 7 clear, the hardware uses the front state, but the JSON reports the raw BF ops and masks (for example front pass REPLACE_TEST, back pass INVERT, back masks 0).

AI-assisted (Claude Code).

@hah346

hah346 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Follow-up on whether the library programs can be paired in the driver. On Windows / RTX 2060 (616.64), I selected 16 VS+PS records with distinct VS and PS programs from the small-module tail of the local library. All 32 original programs translated and passed spirv-val. A local variant of vk_pipeline_check supplied each actual library PS as the partner for its VS in place of the normal synthetic stub. vkCreateGraphicsPipelines succeeded for all 16 pairs (wave32), zero failures or skips.

This is a driver pipeline-creation smoke test with generic target formats and vertex bindings. I did not execute a draw, validate the original PSO state, or measure startup coverage. #8754 implements the vertex input layout parser needed to replace the synthetic bindings in a proper slot-57 path. AI-assisted. Only aggregate results shared.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants