From 35ce606dfb0c16ffca67424319928e206b992d7f Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sat, 28 Nov 2026 02:50:36 +0100 Subject: [PATCH 1/2] compute: allow implicit-derivative image sampling in direct compute image_sample, image_sample_b, image_sample_c, image_gather4 and image_get_lod no longer refuse in direct compute when the guest group has a multiple of four threads. The guest model treats a compute quad as four consecutive lanes (ddx from lane ^ 1, ddy from lane ^ 2), so a module that uses implicit derivatives declares numthreads(X*Y*Z, 1, 1), where SM 6.6 forms quads from four consecutive threads; the guest x/y/z IDs are still rebuilt from the logical lane index (wave rank * 32 + host lane) with the original shape. Such a module also declares DXIL validator 1.8, which accepts derivative operations in compute; every other module keeps 1.6. Groups that are not a multiple of four stay refused. New test native_compute_implicit_lod (controls, WARP, hardware): (32,1,1), (8,4,1), (64,1,1) and (8,4,2) groups sample a three-mip texture with implicit LOD and with image_sample_l, and compare against the mip the guest quad selects. native_direct_container keeps its refusal check on a six-thread group. --- src/dxil_module.h | 5 +- src/gfx1013_direct_compute.inl | 18 ++- tests/cmake/native_compute_implicit_lod.cmake | 15 ++ tests/native_compute_implicit_lod_check.py | 146 ++++++++++++++++++ tests/native_direct_container_check.py | 8 +- 5 files changed, 185 insertions(+), 7 deletions(-) create mode 100644 tests/cmake/native_compute_implicit_lod.cmake create mode 100644 tests/native_compute_implicit_lod_check.py diff --git a/src/dxil_module.h b/src/dxil_module.h index 21f344e793..31106bf01d 100644 --- a/src/dxil_module.h +++ b/src/dxil_module.h @@ -165,6 +165,9 @@ class DxilModule { << "b, %dx.types.ResourceProperties { i32 14, i32 0 })\n"; return h; } + // DXIL validator 1.8 accepts implicit-derivative operations in compute; every other + // module keeps validator 1.6. + unsigned validator_minor = 6; Text finish_compute(unsigned x, unsigned y, unsigned z, const Text &stage = "cs") { std::ostringstream out; out << "target datalayout = " @@ -293,7 +296,7 @@ class DxilModule { "readnone\n" "declare %dx.types.Handle " "@dx.op.annotateHandle(i32,%dx.types.Handle,%dx.types.ResourceProperties) nounwind readnone\n"; - out << "!llvm.ident = !{" << ident << "}\n!dx.version = !{" << version << "}\n!dx.valver = !{" << version + out << "!llvm.ident = !{" << ident << "}\n!dx.version = !{" << version << "}\n!dx.valver = !{" << node("i32 1, i32 " + std::to_string(validator_minor)) << "}\n!dx.shaderModel = !{" << model << "}\n"; if (res != "null") out << "!dx.resources = !{" << res << "}\n"; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 473dcb443f..06ff987bc5 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -35,6 +35,8 @@ struct DirectCompute { std::map,string> descriptor_strides; unsigned label_number = 0; bool pixel_stage = false; + bool complete_compute_quads = false; + bool compute_derivatives = false; // Straight-line graphics stages keep exact SSA definitions; a missing // entry value is resolved through the container's stage signature. std::function graphics_input; @@ -201,6 +203,7 @@ struct DirectCompute { } void initialize(unsigned user, unsigned flags, unsigned x, unsigned y, unsigned z) { unsigned threads = x * y * z; + complete_compute_quads = threads % 4 == 0; lane = ir.invoke("i32", "waveGetLaneIndex", 111, {}, "nounwind readnone"); lane_bit = ir.binary("shl", "1", lane); write(126, ballot("true")); @@ -828,8 +831,11 @@ struct DirectCompute { const bool compare_gather = i.op == 79; const bool compare = i.op == 40 || i.op == 47 || compare_gather; const bool implicit = i.op == 32 || i.op == 40 || bias || query || i.op == 64; - if (implicit && !pixel_stage) - refuse(i.pc, "implicit derivatives require a pixel stage"); + if (implicit && !pixel_stage) { + if (!complete_compute_quads) + refuse(i.pc, "implicit derivatives require a pixel stage"); + compute_derivatives = true; + } const bool gather = i.op == 64 || i.op == 71 || compare_gather; const bool gather_lod = i.op == 68; const bool sample = (!gather && implicit) || (compare && !gather) || gradient || i.op == 39 || i.op == 36, @@ -3883,7 +3889,13 @@ struct DirectCompute { const unsigned rank_words = x * y * z > 64 ? x * y * z : 0; if ((uses_lds ? lds_words : 0) + rank_words + (uses_exchange ? exchange_words : 0) > 8192) refuse(entry, "combined shared storage exceeds 32 KiB"); - r.dxil_ir = ir.finish_compute(x, y, z); + // SM 6.6 forms consecutive linear quads for 1D groups. In 2D it forms + // spatial 2x2 quads, which can cross the guest's consecutive lane quads. + // initialize() still reconstructs guest IDs using the original dimensions. + // The wave64 split occurs at lane 32, a quad boundary. + if (compute_derivatives) + ir.validator_minor = 8; + r.dxil_ir = compute_derivatives ? ir.finish_compute(x * y * z, 1, 1) : ir.finish_compute(x, y, z); return std::move(r); } }; diff --git a/tests/cmake/native_compute_implicit_lod.cmake b/tests/cmake/native_compute_implicit_lod.cmake new file mode 100644 index 0000000000..2baf329e27 --- /dev/null +++ b/tests/cmake/native_compute_implicit_lod.cmake @@ -0,0 +1,15 @@ +if(TARGET compile_dxil AND EXISTS "${INTAKE_PYTHON}" AND + EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll") + set(implicit_lod_check "${CMAKE_SOURCE_DIR}/tests/native_compute_implicit_lod_check.py") + add_test(NAME native_compute_implicit_lod_controls COMMAND "${INTAKE_PYTHON}" -B + "${implicit_lod_check}" "$" "${DXC_BIN_DIR}") + set_tests_properties(native_compute_implicit_lod_controls PROPERTIES TIMEOUT 330) + if(TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME native_compute_implicit_lod_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${implicit_lod_check}" "$" "${DXC_BIN_DIR}" + "$" ${adapter}) + set_tests_properties(native_compute_implicit_lod_${adapter} PROPERTIES TIMEOUT 540 SKIP_RETURN_CODE 77) + endforeach() + endif() +endif() diff --git a/tests/native_compute_implicit_lod_check.py b/tests/native_compute_implicit_lod_check.py new file mode 100644 index 0000000000..92029217b0 --- /dev/null +++ b/tests/native_compute_implicit_lod_check.py @@ -0,0 +1,146 @@ +"""Check that direct DXIL sampling uses the guest's consecutive-lane quads.""" + +import math +from pathlib import Path +import subprocess +import sys +import tempfile + +from compute_gather4_l_check import FLOAT_TEXTURE_FLAG, HEIGHT, SENTINEL, WIDTH, bits +from native_direct_container_check import compute, words +from native_gather_lod_check import render + + +CASES = ( + ((32, 1, 1), True), + ((64, 1, 1), False), + ((8, 4, 1), True), + ((8, 4, 2), False), +) +MIP_COLORS = tuple(bits(value) for value in (1.0, 2.0, 4.0)) + + +def vop2(op, dst, src0, src1): + return (op << 25) | (dst << 17) | (src1 << 9) | src0 + + +def program(group, wave32, implicit): + # One group at ID (0,0,0), with guest local IDs in v0/v1/v2. + # The texture descriptor is at table + 0 and output at table + 0x20. + code = [ + 0xBEFE03C1 if wave32 else 0xBEFE04C1, # s_mov_b32 exec_lo, -1 / s_mov_b64 exec, -1 + 0xBE810380, 0xF40C0200, 0xFA000000, + 0xF4080800, 0xFA000020, + ] + for reg, value in enumerate((0x12, 0xFFF000, 0x04500000, 0), start=4): + code += [0xBE8003FF | reg << 16, value] + + _, y, z = group + if z > 1: + code += [ + vop2(26, 2, 133, 2), # v2 = z << 5 + vop2(28, 0, 258, 0), # v0 |= v2 + ] + if y > 1: + code += [ + vop2(26, 1, 131, 1), # v1 = y << 3 + vop2(28, 0, 257, 0), # v0 |= v1, completing the linear index + ] + code += [ + vop2(26, 5, 130, 0), # v5 = linear index * 4, the output byte offset + ] + if y > 1: + # V ramps within each pair of guest rows. Consecutive quads step two lanes + # in ddy, covering one texel (mip 0). Without flattening, the 2D spatial + # quad steps eight lanes in ddy, covering four texels (mip 2). + code += [ + 0x7E0202F0, # v_mov_b32 v1, 0.5 (U) + vop2(27, 2, 143, 0), # v2 = linear index & 15 + 0x7E040D02, # v_cvt_f32_u32 v2, v2 + vop2(8, 2, 255, 2), bits(1 / (2 * HEIGHT)), # V + 0x7E060280, # v_mov_b32 v3, 0 (explicit LOD) + ] + else: + code += [ + vop2(22, 3, 130, 0), # v3 = linear index >> 2 + vop2(27, 3, 131, 3), # v3 &= 3 + vop2(19, 3, 130, 3), # v3 = min(v3, 2), the expected mip + vop2(26, 4, 151, 3), # v4 = mip << 23 + vop2(37, 4, 255, 4), bits(1 / WIDTH), # v4 = bits for (1 / WIDTH) * 2**mip + vop2(27, 1, 129, 0), # v1 = linear index & 1 + 0x7E020D01, # v_cvt_f32_u32 v1, v1 + vop2(8, 1, 260, 1), # v1 = U, giving each quad ddx(U) = 2**mip / WIDTH + vop2(27, 4, 136, 0), # v4 = linear index & 8 + 0x7E080D04, # v_cvt_f32_u32 v4, v4 + vop2(8, 4, 255, 4), bits(0.0625), # v4 = 0.5 when bit 3 of the index is set + vop2(3, 1, 260, 1), # Add an offset constant within each quad. + 0x7E0402F0, # v_mov_b32 v2, 0.5 (V) + 0x7E060D03, # v_cvt_f32_u32 v3, v3 (explicit LOD) + ] + code += [ + 0xBF8CC07F, # s_waitcnt lgkmcnt(0) + 0xF0000108 | ((32 if implicit else 36) << 18), 0x00220401, + 0xBF8C3F70, # s_waitcnt vmcnt(0) + 0xE0701000, 0x80080405, # buffer_store_dword v4, v5, s[32:35], 0 offen + 0xBF810000, + ] + return compute(words(*code), table=True, wave32=wave32, group=group) + + +def compile_shader(cli, sdk, work, group, wave32, implicit): + source = work / ('-'.join(map(str, (*group, int(wave32), int(implicit)))) + '.c67') + source.write_bytes(program(group, wave32, implicit)) + shader = source.with_suffix('.cso') + run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], + capture_output=True, text=True, timeout=30) + return shader, run + + +def compile_pair(cli, sdk, work, group, wave32): + for implicit in (True, False): + shader, run = compile_shader(cli, sdk, work, group, wave32, implicit) + assert run.returncode == 0 and shader.is_file(), (group, wave32, implicit, run.stdout, run.stderr) + yield shader + + +def write_reference(path, group): + threads = math.prod(group) + if group[1] > 1: + expected = [MIP_COLORS[0]] * threads + else: + expected = [MIP_COLORS[min((lane // 4) % 4, 2)] for lane in range(threads)] + expected += [SENTINEL] * (320 - threads) + texels = [color for mip, color in enumerate(MIP_COLORS) + for _ in range((WIDTH >> mip) * (HEIGHT >> mip) * 4)] + path.write_bytes(words(FLOAT_TEXTURE_FLAG | 1, *expected, *texels)) + + +def main(cli, sdk, *render_args): + with tempfile.TemporaryDirectory() as tmp: + work = Path(tmp) + if not render_args: + for group, wave32 in CASES: + tuple(compile_pair(cli, sdk, work, group, wave32)) + group = (6, 1, 1) + _, run = compile_shader(cli, sdk, work, group, True, True) + assert run.returncode != 0 and 'implicit derivatives require a pixel stage' in run.stderr, ( + run.stdout, run.stderr) + shader, run = compile_shader(cli, sdk, work, group, True, False) + assert run.returncode == 0 and shader.is_file(), run.stdout + run.stderr + return + + renderer, adapter = render_args + wave = render(renderer, adapter, '--shader-wave32') + assert wave.returncode == 0, wave.stdout + wave.stderr + reference = work / 'expected.bin' + for group, wave32 in CASES: + write_reference(reference, group) + for shader in compile_pair(cli, sdk, work, group, wave32): + result = render(renderer, adapter, '--compute-texture-case', shader, reference) + assert result.returncode == 0 and 'compared_words=320 mismatches=0' in result.stdout, ( + shader.name, result.stdout, result.stderr) + print(f'{group} wave{32 if wave32 else 64}: implicit and explicit LOD matched guest readback') + + +if __name__ == '__main__': + main(*sys.argv[1:]) diff --git a/tests/native_direct_container_check.py b/tests/native_direct_container_check.py index b6c54d4255..97af8e7f33 100644 --- a/tests/native_direct_container_check.py +++ b/tests/native_direct_container_check.py @@ -13,7 +13,7 @@ def words(*values): return struct.pack(f"<{len(values)}I", *values) -def compute(code, threads=32, table=False, root_descriptor=False, wave32=True, uses=()): +def compute(code, threads=32, table=False, root_descriptor=False, wave32=True, uses=(), *, group=None): body = bytearray(256) struct.pack_into(" Date: Sat, 28 Nov 2026 03:49:42 +0100 Subject: [PATCH 2/2] compute: pin implicit-derivative group shapes and read back each operation Document the accepted group shapes and the lane-mapping assumption in docs/experiments/native-compute-implicit-derivatives.md. native_compute_implicit_lod adds (4,1,1) and (12,1,1) sub-wave groups and (96,1,1) wave32 and (128,1,1) wave64 multi-wave groups, and keeps the 36-thread "partial final wave in multi-wave group" refusal distinct from the 6-thread incomplete-quad refusal. It now reads back image_sample_b (bias +1 selects the next mip, matching image_sample_l at that LOD), image_sample_c (LESS against a depth mip chain at the implicit LOD), image_get_lod (clamped and unclamped LOD) and image_gather4 with a sampler fixed to mip zero (matching image_gather4_l at LOD 0), and keeps the refusal for implicit gather with a sampler that is not fixed to mip zero. compute_check gains a scalar R32_FLOAT comparison case and a mip-zero static sampler for those cases. --- docs/experiments.md | 4 + .../native-compute-implicit-derivatives.md | 34 +++++ tests/compute_check.cpp | 41 +++++- tests/native_compute_implicit_lod_check.py | 125 +++++++++++++++--- 4 files changed, 184 insertions(+), 20 deletions(-) create mode 100644 docs/experiments/native-compute-implicit-derivatives.md diff --git a/docs/experiments.md b/docs/experiments.md index 9af28be5e1..b15306833d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15,6 +15,10 @@ cmake --build --preset dev --target startup_stream_consumer d3d12_xs_shim compil ctest --preset dev --no-tests=error -V -R '^startup_native_graphics_draw_(hardware|warp)$' ``` +## Implicit derivatives in direct compute + +[Group shapes, lane mapping and readback fixtures](experiments/native-compute-implicit-derivatives.md) + ## Slot 67 wave size in direct compute State block A bit 20 of dword 4 selects the guest wave size. diff --git a/docs/experiments/native-compute-implicit-derivatives.md b/docs/experiments/native-compute-implicit-derivatives.md new file mode 100644 index 0000000000..2cca01ca8c --- /dev/null +++ b/docs/experiments/native-compute-implicit-derivatives.md @@ -0,0 +1,34 @@ +# Implicit derivatives in direct compute + +Groups with a multiple of four threads can use implicit derivatives when +they pass the existing wave guards: a group of more than 32 threads must be +a multiple of 32, and a wave64 group a multiple of 64. The DXIL module uses +`numthreads(X*Y*Z,1,1)` and validator version 1.8 only when it emits +compute derivatives. Guest local X, Y and Z are reconstructed from the +linear guest index. + +A guest quad is four consecutive guest lanes. The emitter reconstructs +the linear guest index as host wave rank * 32 + host lane index. The +SM 6.6 derivatives spec section "1D quads" guarantees the matching position +within each quad. The full reconstruction also assumes that host lane +order follows thread order within a wave, including across quads. + +A 6-thread wave32 group has an incomplete quad and refuses with +"implicit derivatives require a pixel stage". A 36-thread wave32 group +has complete quads and fails the earlier wave guard with "partial final +wave in multi-wave group". Implicit Gather with a constant sampler requires +that sampler to be fixed to mip zero (LOD range word zero). + +```powershell +cmake --build --preset dev --target compile_dxil offscreen_check +ctest --preset dev --no-tests=error -j 1 -R '^native_compute_implicit_lod_' -V +``` + +On an NVIDIA GeForce RTX 5080 (Windows 11, Release), the hardware fixture +matches its CPU reference for 4-, 12-, 32- and 96-thread wave32 groups, +64- and 128-thread wave64 groups, and the multidimensional (8,4,1) and +(8,4,2) groups. Its other readbacks cover bias selecting mip 2, point depth +comparison at mip 1, both LOD query outputs, and the four taps of mip-zero +Gather. Bias and Gather each use the same CPU reference for their implicit +and explicit-LOD shaders. Inbox WARP reports the capability skip +"requires SM 6.6, WaveOps, and a 32-lane wave". diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index ee4fb50d1b..5a23d036a0 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -25,6 +25,9 @@ constexpr UINT uavs = 13, srvs = 21; // The image case header packs the dispatch count and a format/capability selector. The payload // carries raw texels, one word each for RGBA8 and scalar R32, or four for RGBA32. constexpr UINT texture_rgba8_flag = 1u << 24; +// Read-only image case selectors. The dispatch dimensions each fit in three bits. +constexpr UINT texture_mip_zero_sampler_flag = 1u << 22; +constexpr UINT texture_comparison_flag = 1u << 23; constexpr UINT texture_atomic_uint_flag = 1u << 25; constexpr UINT texture_atomic_sint_minmax_flag = 1u << 26; constexpr UINT texture_atomic_uint_minmax_flag = 1u << 27; @@ -460,8 +463,13 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch const bool rgba8 = (store.groups & texture_rgba8_flag) != 0; const bool rgba32_float = (store.groups & texture_rgba32_float_flag) != 0; const bool view_mip1 = (store.groups & texture_view_mip1_flag) != 0; - store.groups &= ~(texture_rgba8_flag | texture_rgba32_float_flag | texture_view_mip1_flag); - const UINT base_words = texture_width * texture_height * (rgba8 ? 1 : texture_channels); + const bool mip_zero = (store.groups & texture_mip_zero_sampler_flag) != 0; + const bool comparison = (store.groups & texture_comparison_flag) != 0; + store.groups &= ~(texture_rgba8_flag | texture_rgba32_float_flag | texture_view_mip1_flag | + texture_mip_zero_sampler_flag | texture_comparison_flag); + const auto format = comparison ? DXGI_FORMAT_R32_FLOAT : rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT + : rgba32_float ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32A32_UINT; + const UINT base_words = texture_width * texture_height * texture_words_per_texel(format); std::vector texels(base_words); source.read(reinterpret_cast(texels.data()), static_cast(texels.size() * sizeof(UINT))); // Older cases stop after the base image. A mip case appends levels one and two. @@ -472,11 +480,34 @@ void check_compute_texture_file(ID3D12Device* device, const char* path, const ch } if (!source || source.peek() != std::char_traits::eof() || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || store.axis(2) > 5 || (rgba8 && rgba32_float) || + (comparison && (rgba8 || rgba32_float || mip_zero)) || (view_mip1 && texels.size() == base_words)) throw std::runtime_error("Invalid compute image load reference"); - const auto format = rgba8 ? DXGI_FORMAT_R8G8B8A8_UINT - : rgba32_float ? DXGI_FORMAT_R32G32B32A32_FLOAT : DXGI_FORMAT_R32G32B32A32_UINT; - const auto program = create_compute_program(device, shader, {compute_tables, sizeof(compute_tables)}); + D3D12_SHADER_BYTECODE root{compute_tables, sizeof(compute_tables)}; + ComPtr case_root; + if (comparison || mip_zero) { + ComPtr embedded; + check(D3D12CreateVersionedRootSignatureDeserializer(root.pShaderBytecode, root.BytecodeLength, + IID_PPV_ARGS(&embedded)), "Read embedded compute table signature"); + const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* original = nullptr; + check(embedded->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &original), + "Get v1.1 compute table signature"); + auto desc = *original; + if (desc.Desc_1_1.NumStaticSamplers != 1) + throw std::runtime_error("Expected one static sampler in the compute table signature"); + auto sampler = desc.Desc_1_1.pStaticSamplers[0]; + if (comparison) { + sampler.Filter = D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT; + sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_LESS; + } else { + sampler.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; + sampler.MaxLOD = 0; + } + desc.Desc_1_1.pStaticSamplers = &sampler; + check(D3D12SerializeVersionedRootSignature(&desc, &case_root, nullptr), "Serialize compute case signature"); + root = {case_root->GetBufferPointer(), case_root->GetBufferSize()}; + } + const auto program = create_compute_program(device, shader, root); run_compute(device, true, program, false, &store, &texels, format, nullptr, false, false, view_mip1 ? 1 : 0); } diff --git a/tests/native_compute_implicit_lod_check.py b/tests/native_compute_implicit_lod_check.py index 92029217b0..752eb78aec 100644 --- a/tests/native_compute_implicit_lod_check.py +++ b/tests/native_compute_implicit_lod_check.py @@ -6,25 +6,34 @@ import sys import tempfile -from compute_gather4_l_check import FLOAT_TEXTURE_FLAG, HEIGHT, SENTINEL, WIDTH, bits +from compute_gather4_l_check import FLOAT_TEXTURE_FLAG, HEIGHT, SENTINEL, WIDTH, bits, texels from native_direct_container_check import compute, words from native_gather_lod_check import render +from startup_compute_gather_l_check import reference as gather_reference +from startup_image_sample_c_check import LESS, POINT CASES = ( + ((4, 1, 1), True), + ((12, 1, 1), True), ((32, 1, 1), True), ((64, 1, 1), False), + ((96, 1, 1), True), + ((128, 1, 1), False), ((8, 4, 1), True), ((8, 4, 2), False), ) MIP_COLORS = tuple(bits(value) for value in (1.0, 2.0, 4.0)) +MIP_ZERO_FLAG = 1 << 22 # tests/compute_check.cpp texture_mip_zero_sampler_flag +DEPTH_FLAG = 1 << 23 # tests/compute_check.cpp texture_comparison_flag +POINT_MIP_SAMPLER = (0x12, 0xFFF000, 0x04500000, 0) def vop2(op, dst, src0, src1): return (op << 25) | (dst << 17) | (src1 << 9) | src0 -def program(group, wave32, implicit): +def setup(wave32, sampler): # One group at ID (0,0,0), with guest local IDs in v0/v1/v2. # The texture descriptor is at table + 0 and output at table + 0x20. code = [ @@ -32,9 +41,13 @@ def program(group, wave32, implicit): 0xBE810380, 0xF40C0200, 0xFA000000, 0xF4080800, 0xFA000020, ] - for reg, value in enumerate((0x12, 0xFFF000, 0x04500000, 0), start=4): + for reg, value in enumerate(sampler, start=4): code += [0xBE8003FF | reg << 16, value] + return code + +def program(group, wave32, implicit): + code = setup(wave32, POINT_MIP_SAMPLER) _, y, z = group if z > 1: code += [ @@ -88,8 +101,13 @@ def program(group, wave32, implicit): def compile_shader(cli, sdk, work, group, wave32, implicit): - source = work / ('-'.join(map(str, (*group, int(wave32), int(implicit)))) + '.c67') - source.write_bytes(program(group, wave32, implicit)) + name = '-'.join(map(str, (*group, int(wave32), int(implicit)))) + return compile_program(cli, sdk, work, name, program(group, wave32, implicit)) + + +def compile_program(cli, sdk, work, name, binary): + source = work / f'{name}.c67' + source.write_bytes(binary) shader = source.with_suffix('.cso') run = subprocess.run([cli, sdk, work / 'cache', 'gfx1013-container-cs', source, shader], capture_output=True, text=True, timeout=30) @@ -103,16 +121,79 @@ def compile_pair(cli, sdk, work, group, wave32): yield shader +def mip_payload(colors, channels=4): + return [color for mip, color in enumerate(colors) + for _ in range((WIDTH >> mip) * (HEIGHT >> mip) * channels)] + + +def write_case(path, expected, payload, flags=FLOAT_TEXTURE_FLAG): + expected = [*expected, *([SENTINEL] * (320 - len(expected)))] + path.write_bytes(words(flags | 1, *expected, *payload)) + + def write_reference(path, group): threads = math.prod(group) if group[1] > 1: expected = [MIP_COLORS[0]] * threads else: expected = [MIP_COLORS[min((lane // 4) % 4, 2)] for lane in range(threads)] - expected += [SENTINEL] * (320 - threads) - texels = [color for mip, color in enumerate(MIP_COLORS) - for _ in range((WIDTH >> mip) * (HEIGHT >> mip) * 4)] - path.write_bytes(words(FLOAT_TEXTURE_FLAG | 1, *expected, *texels)) + write_case(path, expected, mip_payload(MIP_COLORS)) + + +def operation_program(op, *, step=2 / WIDTH, operand=0.0, mask=1, components=1, + sampler=POINT_MIP_SAMPLER): + code = setup(True, sampler) + code += [ + vop2(26, 8, {1: 130, 2: 131, 4: 132}[components], 0), # byte offset + vop2(27, 7, 129, 0), # lane & 1 + 0x7E0E0D07, # convert v7 to float + vop2(8, 1, 255, 7), bits(step), + vop2(3, 1, 240, 1), # U = 0.5 + step * (lane & 1) + 0x7E0402F0, # V = 0.5 + 0x7E0002FF, bits(operand), + ] + address = 0 if op in (37, 40) else 1 + if op == 40: + # Comparison reference before U and V, as in startup_image_sample_c_check. + code += [vop2(8, 0, 255, 7), bits(0.25), vop2(3, 0, 240, 0)] + if op in (36, 68): + code += [0x7E060300] # v_mov_b32 v3, v0: explicit LOD after U and V + code += [ + 0xBF8CC07F, + 0xF0000008 | op << 18 | mask << 8, 0x00220400 | address, + 0xBF8C3F70, + {1: 0xE0701000, 2: 0xE0741000, 4: 0xE0781000}[components], 0x80080408, + 0xBF810000, + ] + return compute(words(*code), wave32=True, group=(4, 1, 1), table=True) + + +def operation_cases(): + colors = mip_payload(MIP_COLORS) + yield 'bias-base', operation_program(32), [MIP_COLORS[1]] * 4, colors, FLOAT_TEXTURE_FLAG + yield 'bias-plus-one', operation_program(37, operand=1.0), [MIP_COLORS[2]] * 4, colors, FLOAT_TEXTURE_FLAG + yield 'bias-explicit', operation_program(36, operand=2.0), [MIP_COLORS[2]] * 4, colors, FLOAT_TEXTURE_FLAG + + comparison = (POINT | LESS, 0xFFF000, 0x04000000, 0) + depth = mip_payload(tuple(map(bits, (0.25, 0.625, 1.0))), channels=1) + yield 'compare', operation_program(40, sampler=comparison), [bits(1.0), bits(0.0)] * 2, depth, DEPTH_FLAG + + mip_zero = (0x12, 0, 0x04500000, 0) + query = operation_program(96, step=4 / WIDTH, mask=3, components=2, sampler=mip_zero) + yield 'get-lod', query, [bits(0.0), bits(2.0)] * 4, colors, FLOAT_TEXTURE_FLAG | MIP_ZERO_FLAG + + step = 1 / (4 * WIDTH) + taps = gather_reference(0, 0, (0.5, 0.5))[:4] + assert taps == gather_reference(0, 0, (0.5 + step, 0.5))[:4] + for name, op in (('gather', 64), ('gather-explicit', 68)): + binary = operation_program(op, step=step, components=4, sampler=mip_zero) + yield name, binary, taps * 4, texels(), FLOAT_TEXTURE_FLAG | MIP_ZERO_FLAG + + +def check_readback(renderer, adapter, shader, reference): + result = render(renderer, adapter, '--compute-texture-case', shader, reference) + assert result.returncode == 0 and 'compared_words=320 mismatches=0' in result.stdout, ( + shader.name, result.stdout, result.stderr) def main(cli, sdk, *render_args): @@ -121,12 +202,22 @@ def main(cli, sdk, *render_args): if not render_args: for group, wave32 in CASES: tuple(compile_pair(cli, sdk, work, group, wave32)) - group = (6, 1, 1) - _, run = compile_shader(cli, sdk, work, group, True, True) - assert run.returncode != 0 and 'implicit derivatives require a pixel stage' in run.stderr, ( + for group, reason in ( + ((36, 1, 1), 'partial final wave in multi-wave group'), + ((6, 1, 1), 'implicit derivatives require a pixel stage'), + ): + _, run = compile_shader(cli, sdk, work, group, True, True) + assert run.returncode != 0 and reason in run.stderr, (group, run.stdout, run.stderr) + _, run = compile_program(cli, sdk, work, 'gather-unsupported-sampler', + operation_program(64, components=4)) + assert run.returncode != 0 and 'implicit gather requires a sampler fixed to mip zero' in run.stderr, ( run.stdout, run.stderr) + group = (6, 1, 1) shader, run = compile_shader(cli, sdk, work, group, True, False) assert run.returncode == 0 and shader.is_file(), run.stdout + run.stderr + for name, binary, _, _, _ in operation_cases(): + shader, run = compile_program(cli, sdk, work, name, binary) + assert run.returncode == 0 and shader.is_file(), (name, run.stdout, run.stderr) return renderer, adapter = render_args @@ -136,10 +227,14 @@ def main(cli, sdk, *render_args): for group, wave32 in CASES: write_reference(reference, group) for shader in compile_pair(cli, sdk, work, group, wave32): - result = render(renderer, adapter, '--compute-texture-case', shader, reference) - assert result.returncode == 0 and 'compared_words=320 mismatches=0' in result.stdout, ( - shader.name, result.stdout, result.stderr) + check_readback(renderer, adapter, shader, reference) print(f'{group} wave{32 if wave32 else 64}: implicit and explicit LOD matched guest readback') + for name, binary, expected, payload, flags in operation_cases(): + shader, run = compile_program(cli, sdk, work, name, binary) + assert run.returncode == 0 and shader.is_file(), (name, run.stdout, run.stderr) + write_case(reference, expected, payload, flags) + check_readback(renderer, adapter, shader, reference) + print(f'{name}: exact readback') if __name__ == '__main__':