Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions docs/experiments/native-direct-cvt-pk-u8.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# v_cvt_pk_u8_f32 in the direct C++ compute path (#2997)

The direct compute frontend (`src/gfx1013_direct_compute.inl`) now lowers `v_cvt_pk_u8_f32`, which it refused with
`direct DXIL lowering for v_cvt_pk_u8_f32`. It computes
D = (S2 & ~(0xff << 8 * S1[1:0])) | (flt32_to_uint8(S0) << 8 * S1[1:0]).

The conversion is the one `gfx2hlsl.py` (`op_v_cvt_pk_u8_f32`) uses, measured on RDNA 2 hardware
(`docs/experiments.md`, `tools/rdna_cvt_pk_u8.py`): round to nearest even, saturate to [0, 255]. NaN, both zeros and
every negative value give 0; +inf gives 255.

The lowering follows that expression:
- The positive test is the integer comparison (bits - 1) < 0x7f800000, which fast-math cannot fold.
- The value then goes through DXIL `FMin` with 255.0 and `Round_ne`, and `fptoui`.
- The resulting byte is merged into S2.

Source and output modifiers stay refused (`direct ALU operand modifiers`), as `gfx2hlsl.py` refuses them.

## Fixture

`tests/native_cvt_pk_u8_check.py controls|hardware`
(`ctest --preset dev --no-tests=error -R '^native_cvt_pk_u8_' -V`).

Sixteen cases set S0 and S1 by `v_mov` literals over S2 = 0xa5a5a5a5, and every lane of two groups stores the
results. The cases cover:
- the ties 0.5, 1.5, 2.5 and 254.5;
- the bound 255.5, 1e30 and +inf;
- -0.0, -1.0 and -inf;
- a quiet NaN;
- the smallest subnormal;
- 127.4999, 0.0 and 255.0;
- all four byte selects, plus a select of 6 that must use only its low two bits.

The VOP3 word (opcode 0x15e) was assembled with LLVM 15.0.7 (`clang -cc1as -triple amdgcn -target-cpu gfx1013
-filetype asm -show-encoding`).

The controls:
- compile the program and check its module with `dxc -dumpbin`: one `FMin` (DXIL opcode 36) and one `Round_ne`
(opcode 26) per case, and no `FMax`;
- refuse it with a negated S0;
- check that three references differ from the expected words: rounding half up, truncating, and letting negatives
through.

The reference agrees with `model_rne_sat` of `tools/rdna_cvt_pk_u8.py` for all sixteen inputs (checked once while
writing the fixture). Fourteen of the sixteen inputs are also rows of the measured table
`tests/data/rdna_cvt_pk_u8_measured.tsv`; 1e30 and 127.4999 rely on the model only.

Measured on 27.11.2026, `cpp-migration` `4ff5e36d` plus this change, Windows 10.0.26100.9711. The controls printed
`compiled with one FMin and one Round_ne per case; a negated source refused; the half-up, truncating and
negative-passing references differ`. The readback
reported a skip (77) on the NVIDIA Quadro M1000M (driver 32.0.15.7371, debug layer unavailable), because
`native_store_replay` needs shader model 6.6 with wave32. The readback is not measured.
13 changes: 13 additions & 0 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1948,6 +1948,19 @@ struct DirectCompute {
auto pad = ir.binary("sub", "32", width);
auto field = shift("ashr", a, b);
z = select(cmp("eq", width, "0"), "0", shift("ashr", shift("shl", field, pad), pad));
} else if (n == "v_cvt_pk_u8_f32") {
// (S2 & ~(0xff << 8 * S1[1:0])) | (flt32_to_uint8(S0) << 8 * S1[1:0]) (#2997), with the conversion
// gfx2hlsl.py measured on RDNA 2: round to nearest even, saturate to [0, 255], zero for NaN, both zeros
// and negatives. (bits - 1) < 0x7f800000 holds exactly from the smallest subnormal to +inf, as an integer
// test that fast-math cannot fold.
auto amount = ir.binary("shl", ir.binary("and", b, "3"), "3");
auto positive = cmp("ult", ir.binary("sub", a, "1"), "2139095040");
auto bounded = ir.invoke("float", "binary.f32", 36, {{"float", ir.value("bitcast i32 " + a + " to float")},
{"float", "2.550000e+02"}}, "nounwind readnone");
auto rounded = ir.invoke("float", "unary.f32", 26, {{"float", bounded}}, "nounwind readnone");
auto byte = select(positive, ir.binary("and", ir.value("fptoui float " + rounded + " to i32"), "255"), "0");
auto keep = ir.binary("xor", ir.binary("shl", "255", amount), "4294967295");
z = ir.binary("or", ir.binary("and", val(2), keep), ir.binary("shl", byte, amount));
} else if (n == "s_orn2_b32")
z = ir.binary("or", a, ir.binary("xor", b, "4294967295"));
else if (n == "s_nand_b32" || n == "s_xnor_b32")
Expand Down
13 changes: 13 additions & 0 deletions tests/cmake/native_cvt_pk_u8.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Direct C++ compute: v_cvt_pk_u8_f32 (#2997). The controls compile and check the
# reference's mutants; the readback needs shader model 6.6 with wave32 and otherwise reports a skip (77).
if(TARGET compile_dxil AND TARGET native_store_replay AND
EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll")
add_test(NAME native_cvt_pk_u8_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/native_cvt_pk_u8_check.py" controls
"$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
set_tests_properties(native_cvt_pk_u8_controls PROPERTIES TIMEOUT 60)
add_test(NAME native_cvt_pk_u8_hardware COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/native_cvt_pk_u8_check.py" hardware
"$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}")
set_tests_properties(native_cvt_pk_u8_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
endif()
120 changes: 120 additions & 0 deletions tests/native_cvt_pk_u8_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""v_cvt_pk_u8_f32 in the direct compute path (#2997).

native_cvt_pk_u8_check.py controls <compile_dxil> <sdk bin dir>
native_cvt_pk_u8_check.py hardware <native_store_replay> <sdk bin dir>

D = (S2 & ~(0xff << 8 * S1[1:0])) | (flt32_to_uint8(S0) << 8 * S1[1:0]). The conversion is the one gfx2hlsl.py
measured on RDNA 2 hardware (see docs/experiments.md): round to nearest even, saturated to [0, 255], with NaN, both
zeros and every negative value giving 0 and +inf giving 255. The VOP3 word (opcode 0x15e) was assembled with LLVM
15.0.7 (clang -cc1as, gfx1013); the other words were checked with tools/disasm_rdna2.py --hex.

Each case below sets S0 and S1 with v_mov literals over S2 = 0xa5a5a5a5 and stores the result; every lane of two
groups of 32 stores all of them. References that round half up, truncate, or let NaN or negative inputs through
must each differ from the expected words.
"""
from pathlib import Path
import math
import struct
import subprocess
import sys
import tempfile

from native_dpp_quad_check import request

REST = 0xA5A5A5A5
F = lambda value: struct.unpack('<I', struct.pack('<f', value))[0] # noqa: E731
CASES = [(F(0.5), 0), (F(1.5), 1), (F(2.5), 2), (F(254.5), 3), (F(255.5), 0), (F(1e30), 1), (0x7F800000, 2),
(0x80000000, 3), (F(-1.0), 0), (0x7FC00000, 1), (0x00000001, 2), (F(127.4999), 3), (F(3.0), 6),
(0xFF800000, 0), (F(0.0), 1), (F(255.0), 2)]
PROLOGUE = [0xBE940304, 0xBE950380, 0xF408080A, 0xFA000020, 0x8F078B05, 0x34100086, 0x4A101007, 0xBF8CC07F]
CVT = (0xD55E0004, 0x040E0501) # v_cvt_pk_u8_f32 v4, v1, v2, v3
SENTINEL = 0x69696969
GUARD_WORDS = 8
OUTPUT_WORDS = 2064


def program(modifier=0):
code = PROLOGUE + [0x7E0602FF, REST] # v_mov_b32 v3, 0xa5a5a5a5
for index, (value, select) in enumerate(CASES):
code += [0x7E0202FF, value, 0x7E0402FF, select, CVT[0], CVT[1] | modifier,
0xE0701000 | 4 * index, 0x80080408] # buffer_store_dword v4, v8, s[32:35], 0 offen
return code + [0xBF810000]


def to_u8(bits, half_up=False, truncate=False, lax=False):
value = struct.unpack('<f', struct.pack('<I', bits))[0]
if math.isnan(value) or value <= 0:
if not lax or math.isnan(value):
return 0
return int(max(-128, value)) & 0xFF # a lowering that forgets the zero test
value = min(value, 255.0)
if truncate:
return int(value)
if half_up:
return int(math.floor(value + 0.5))
return round(value) # Python rounds half to even


def reference(**mutation):
expected = [SENTINEL] * OUTPUT_WORDS
for lane in range(64):
base = GUARD_WORDS + lane * 16
for index, (value, select) in enumerate(CASES):
shift = 8 * (select & 3)
expected[base + index] = (REST & ~(0xFF << shift) & 0xFFFFFFFF) | (to_u8(value, **mutation) << shift)
return expected


def compile_program(cli, sdk, work, root, code):
marker = request(work, root, code)
return marker, subprocess.run([cli, sdk, work / 'cache', 'gfx1013-direct-cs@0', marker,
marker.with_suffix('.cso')], capture_output=True, text=True)


def controls(cli, sdk, work, root):
marker, result = compile_program(cli, sdk, work, root, program())
assert result.returncode == 0 and marker.with_suffix('.cso').is_file(), (result.stdout, result.stderr)
# The module, before any GPU run: one FMin (DXIL binary opcode 36, not FMax 35) with 255.0 and one Round_ne
# (unary opcode 26) per case, and no FMax.
dump = subprocess.run([Path(sdk) / 'dxc.exe', '-dumpbin', marker.with_suffix('.cso')], capture_output=True,
text=True, check=True).stdout
assert dump.count('@dx.op.binary.f32(i32 36,') == len(CASES), dump
assert dump.count('@dx.op.unary.f32(i32 26,') == len(CASES), dump
assert '@dx.op.binary.f32(i32 35,' not in dump, dump
_, result = compile_program(cli, sdk, work, root, program(modifier=1 << 29)) # neg on S0
assert result.returncode and 'direct ALU operand modifiers' in result.stderr, (result.stdout, result.stderr)
expected = reference()
for label, mutation in (('half up', {'half_up': True}), ('truncated', {'truncate': True}),
('negatives let through', {'lax': True})):
assert reference(**mutation) != expected, label
print('compiled with one FMin and one Round_ne per case; a negated source refused; the half-up, truncating and '
'negative-passing references differ')
return 0


def hardware(replay, sdk, work, root):
marker = request(work, root, program())
output = work / 'out.bin'
result = subprocess.run([replay, sdk, marker, work / 'cache', '0', output, '--direct'])
if result.returncode == 77:
return 77
result.check_returncode()
actual = list(struct.unpack(f'<{OUTPUT_WORDS}I', output.read_bytes()))
diff = [(i, hex(x), hex(y)) for i, (x, y) in enumerate(zip(actual, reference())) if x != y]
assert not diff, diff[:10]
print('v_cvt_pk_u8_f32: all 2064 words matched (1024 results, guards and sentinels)')
return 0


def main(mode, tool, sdk):
with tempfile.TemporaryDirectory() as temp:
work = Path(temp)
shader = work / 'root.hlsl'
shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"')
root = work / 'root.bin'
subprocess.run([Path(sdk) / 'dxc.exe', '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, shader], check=True)
return {'controls': controls, 'hardware': hardware}[mode](tool, sdk, work, root.read_bytes())


if __name__ == '__main__':
sys.exit(main(*sys.argv[1:]))
Loading