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
12 changes: 7 additions & 5 deletions docs/experiments/native-sdwa-f16.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
# SDWA binary16 arithmetic in direct compute

Issue #2963 adds SDWA to `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16`.
Each source must be a VGPR. WORD_0 and DWORD read the low half, and WORD_1 reads the
high half. Source abs clears the binary16 sign bit before neg toggles it. The compiler
Each source can be a VGPR, SGPR, or inline constant. WORD_0 and DWORD read the low
half, and WORD_1 reads the high half. Inline floats use a low-half binary16 encoding
with a zero high half. Source abs clears the binary16 sign bit before neg toggles it. The compiler
widens the halves to binary32, performs the operation, and rounds once to binary16
using the integer nearest-even path from the [plain forms](f16-alu-direct.md).
The binary16 rounding and denormal mode requirements apply to both forms.

WORD_0 and WORD_1 destinations accept UNUSED_PAD, which zeroes the other half,
and UNUSED_PRESERVE, which copies it from the old destination. DWORD and byte
destinations, UNUSED_SEXT, byte sources, source sext, scalar and constant sources,
destinations, UNUSED_SEXT, byte sources, source sext, literals,
clamp, and output modifiers are refused. SDWA min and max remain refused.

Direct wave32 compute SDWA VOPC compares can write a 32-bit mask to `vcc_hi` and read it as a scalar source.
Expand All @@ -35,8 +36,9 @@ The product of `7bff` and `4000` overflows to `7c000000` with high-half pad.
The add of `7e01` and `3c00` expects a NaN in the low half and exactly `a55a`
in the preserved high half. The NaN payload and sign may vary.

Compile-only controls cover DWORD destination, BYTE_1 source, SGPR source,
inline constant source, source sext, UNUSED_SEXT, clamp, omod, min and max.
Compile-only controls cover DWORD destination, BYTE_1 source, source sext,
UNUSED_SEXT, clamp, omod, min and max. The scalar-source fixture separately
covers SGPR and inline source selection, literal refusal, and scalar source sext.
Swapping WORD_0 and WORD_1 on either source and forcing UNUSED_PRESERVE to pad
are manual lowering mutations that must fail the readback comparison.

Expand Down
2 changes: 0 additions & 2 deletions src/gfx1013_compute_native.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,6 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa
const unsigned control = (ext >> (16 + 8*j)) & 255;
i.src_select[j] = control & 7;
i.src_sext[j] = (control & 8) != 0;
if (half_alu && (control & 128))
refuse(pc, "SDWA binary16 source must be a VGPR");
if (half_alu && i.src_select[j] < 4)
refuse(pc, "invalid SDWA source modifier");
if (i.src_select[j] == 7 || (control & 64) || (fp_input && i.src_sext[j]) || (!fp_input && (control & 0x30)))
Expand Down
10 changes: 8 additions & 2 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1599,9 +1599,15 @@ struct DirectCompute {
if (!j && permuted) {
bits = ir.binary("and", *permuted, "65535");
} else if (i.subword) {
// A DWORD selection reads the low half for binary16 arithmetic.
auto inline_word = packed_f16_inline_constant(r);
auto word = inline_word ? to_string(*inline_word) : operand32(i, r);
// Select from the full operand word. DWORD reads the low half.
const unsigned sel = i.src_select[j];
bits = subword(operand32(i, r), sel == 6 ? 4 : sel, false);
// Only the binary16 value of an inline constant is modelled; its other
// half under SDWA is not documented here, so a high-half pick stays refused.
if (inline_word && sel != 4 && sel != 6)
refuse(i.pc, "unsupported SDWA binary16 inline constant selection");
bits = subword(word, sel == 6 ? 4 : sel, false);
} else if (r >= 240 && r <= 248) {
// Inline floats are f32 patterns. The f16 operation consumes the
// binary16 rounding of that value.
Expand Down
12 changes: 12 additions & 0 deletions tests/cmake/native_sdwa_f16_scalar.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Scalar sources in direct C++ binary16 SDWA arithmetic.
if(TARGET native_compute_ir_dump)
add_test(NAME native_sdwa_f16_scalar_ir COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_scalar_check.py"
ir "$<TARGET_FILE:native_compute_ir_dump>")
endif()
if(TARGET native_store_replay)
add_test(NAME native_sdwa_f16_scalar_hardware COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/native_sdwa_f16_scalar_check.py"
gpu "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}")
set_tests_properties(native_sdwa_f16_scalar_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
endif()
3 changes: 0 additions & 3 deletions tests/native_sdwa_f16_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,9 @@ def refusals():
add = fixture.OP_CODE['add']
dest_error = 'unsupported SDWA destination modifier'
src_error = 'invalid SDWA source modifier'
vgpr_error = 'SDWA binary16 source must be a VGPR'
return [
(sdwa(add, DWORD, PAD, WORD_0, WORD_0), dest_error),
(sdwa(add, WORD_0, PAD, BYTE_1, WORD_0), src_error),
(sdwa(add, WORD_0, PAD, WORD_0 | SCALAR, WORD_0), vgpr_error),
(sdwa(add, WORD_0, PAD, WORD_0, WORD_0 | SCALAR, reg1=242), vgpr_error),
(sdwa(add, WORD_0, PAD, WORD_0, WORD_0 | 8), src_error),
(sdwa(add, WORD_0, SEXT, WORD_0, WORD_0), dest_error),
(sdwa(add, WORD_0, PAD, WORD_0, WORD_0, dst_mod=1 << 13), dest_error),
Expand Down
113 changes: 113 additions & 0 deletions tests/native_sdwa_f16_scalar_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""Direct compute binary16 SDWA scalar sources. Use ir DUMPER or gpu STORE_REPLAY SDK."""
import struct
import subprocess
import sys
import tempfile
from pathlib import Path

import f16_packed_model as model
import native_f16_alu_check as fixture
from native_compute_clear_check import write_request
from native_sdwa_f16_check import DWORD, OLD, PAD, PRESERVE, SCALAR, WORD_0, WORD_1, sdwa

SGPR = 9
WORDS = {SGPR: 0x44004000, 256 + 1: 0x48003c00, 256 + 2: 0x45004200}
SOURCE_WORDS = {**WORDS, **fixture.INLINE_F16, 128: 0}


def instruction(op, unused, left, left_sel, right, right_sel):
def control(source, selector):
return selector | (SCALAR if source < 256 else 0)

return sdwa(op, WORD_0, unused, control(left, left_sel), control(right, right_sel),
reg0=left & 255, reg1=right & 255)


class Case:
dest = 3

def __init__(self, op, unused, left, left_sel, right, right_sel):
self.instruction = instruction(fixture.OP_CODE[op], unused, left, left_sel, right, right_sel)

def half(source, selector):
return model.pick(SOURCE_WORDS[source], selector == WORD_1)

result = fixture.binary16(op, half(left, left_sel), half(right, right_sel))
self.want = (OLD & 0xffff0000 if unused == PRESERVE else 0) | result

def emit(self):
return (fixture.smov(SGPR, WORDS[SGPR]) +
fixture.mov(1, WORDS[257]) + fixture.mov(2, WORDS[258]) +
fixture.mov(self.dest, OLD) + self.instruction)


def cases():
return [
Case('add', PAD, SGPR, DWORD, 258, WORD_0),
Case('add', PRESERVE, 242, WORD_0, 128, DWORD),
Case('mul', PRESERVE, 257, WORD_0, SGPR, WORD_1),
Case('sub', PAD, 257, WORD_1, SGPR, DWORD),
Case('subrev', PAD, 257, WORD_1, SGPR, WORD_0),
]


def refusals():
add = fixture.OP_CODE['add']
return [
(instruction(add, PAD, 255, WORD_0, 258, WORD_0), 'literal is unavailable in SDWA'),
(instruction(add, PAD, 257, WORD_0, SGPR, WORD_1 | 8), 'invalid SDWA source modifier'),
(instruction(add, PAD, 258, WORD_0, 242, WORD_1), 'unsupported SDWA binary16 inline constant selection'),
# These captured min/max forms also need an arithmetic lowering.
(instruction(0x39, PRESERVE, SGPR, DWORD, 258, WORD_1), 'unimplemented direct SDWA operand profile'),
(instruction(0x3a, PAD, 257, WORD_0, 258, WORD_0), 'unimplemented direct SDWA operand profile'),
]


def run_ir(dumper, items):
with tempfile.TemporaryDirectory() as tmp:
work = Path(tmp)
# Isolate each shape so one decode refusal cannot hide another.
for index, case in enumerate(items):
code, _ = fixture.program([case])
run = fixture.dump(dumper, work, code, f'case-{index}')
assert run.returncode == 0, (index, run.stderr)
stores = fixture.interpret(run.stdout)
assert stores == [(0, case.want)], (index, stores, hex(case.want))
for index, (words, why) in enumerate(refusals()):
run = fixture.dump(dumper, work, words + [0xbf810000], f'refused-{index}')
assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr)
print(f'native_sdwa_f16_scalar IR: {len(items)} results and {len(refusals())} refusals')


def run_gpu(gpu, sdk, items):
code, expected = fixture.program(items)
with tempfile.TemporaryDirectory() as tmp:
work = Path(tmp)
src, root = work / 'root.hlsl', work / 'root.bin'
src.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"')
subprocess.run([str(Path(sdk) / 'dxc.exe'), '-T', 'rootsig_1_1', '-E', 'SIG', '-Fo', root, src], check=True)
sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x80 | (5 << 1))
marker = write_request(work, code, root.read_bytes(), sa)
dest = work / 'sdwa-f16-scalar-readback.bin'
run = subprocess.run([gpu, sdk, str(marker), str(work / 'cache'), '0', str(dest), '--direct'])
if run.returncode == 77:
sys.exit(77)
run.check_returncode()
# The preamble sets EXEC_LO=1. Group IDs 0 and 1 in s5 select
# wave32 records at DWORDs 8 and 136, with contiguous lane-0 results.
stores = {slot: want for offsets in fixture.group_offsets(len(items))
for slot, want in zip(offsets, expected)}
actual = struct.unpack(f'<{fixture.WORDS}I', dest.read_bytes())
for index, got in enumerate(actual):
want = stores.get(index, fixture.SENTINEL)
assert got == want, (index, hex(got), hex(want))
print(f'native_sdwa_f16_scalar GPU: {len(stores)} results and {fixture.WORDS - len(stores)} guards')


if __name__ == '__main__':
if len(sys.argv) == 3 and sys.argv[1] == 'ir':
run_ir(sys.argv[2], cases())
elif len(sys.argv) == 4 and sys.argv[1] == 'gpu':
run_gpu(sys.argv[2], sys.argv[3], cases())
else:
sys.exit(__doc__)
Loading