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
3 changes: 2 additions & 1 deletion docs/experiments/f16-alu-direct.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Lowers VOP2 and VOP3 `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16` in
- The operation is an f32 add, sub or mul. An f32 value has a 24-bit significand, which covers a correctly rounded binary16 add, sub or mul.
- The result is rounded with the same integer round-to-nearest-even conversion `v_cvt_f16_f32` uses. The low 16 bits are written and the high half is zero.
- `v_subrev_f16` subtracts the first source from the second.
- DPP16 VOP2 permutes the full src0 VGPR word before selecting its low half and honors FI, BOUND_CTRL, and row and bank write masks.

The bit-exact reference is `half_op` in [`tests/f16_packed_model.py`](../../tests/f16_packed_model.py). NaN results match by class. The check is [`tests/native_f16_alu_check.py`](../../tests/native_f16_alu_check.py).

Expand All @@ -18,7 +19,7 @@ The SDWA operand profile is covered by the [SDWA experiment](native-sdwa-f16.md)

Each of these is a named diagnostic:

- DPP
- DPP8
- clamp or omod
- a high-half `op_sel` (instruction bits 11 through 14)
- a binary16 rounding mode other than round-to-nearest-even, an f16 denormal mode other than keep on input and output, or `FP16_OVFL`
Expand Down
7 changes: 4 additions & 3 deletions src/gfx1013_compute_native.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ struct Inst {
bool clamp = false, wide = false, subword = false;
// 0..255 selects within a quad. Row operations and mirrors cross quads.
std::optional<unsigned> dpp_control;
unsigned dpp_row_mask = 15, dpp_bank_mask = 15;
bool dpp_fetch_inactive = false;
bool dpp_bound_zero = false;
unsigned mirror_mask() const { return dpp_control == 0x141 ? 7 : dpp_control == 0x140 ? 15 : 0; }
Expand Down Expand Up @@ -265,8 +266,6 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa
refuse(pc, "unsupported instruction " + string(encoded.name) + " " + hexword(a));
if (!i.wide && (i.enc == Encoding::Vop1 || i.enc == Encoding::Vop2 || i.enc == Encoding::Vopc)) {
const bool half_alu = !graphics && i.enc == Encoding::Vop2 && binary16_alu(encoded.name);
if (direct && half_alu && i.src[0] == 250)
refuse(pc, "unsupported " + string(encoded.name) + " DPP form");
const bool sdwa_logic = i.enc == Encoding::Vop2 && i.op == 0x1d;
const bool sdwa_class = i.enc == Encoding::Vopc && i.op == 0x88;
const bool sdwa_compare = i.enc == Encoding::Vopc && !sdwa_class;
Expand Down Expand Up @@ -365,10 +364,12 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa
auto control=take();
// DPP_CTRL[8] selects patterns outside a quad; bit 17 is
// reserved. FI and BOUND_CTRL are independent of the pattern.
if ((control >> 24) != 0xff) refuse(pc,"DPP requires a full-row, full-bank mask");
if (!half_alu && (control >> 24) != 0xff) refuse(pc,"DPP requires a full-row, full-bank mask");
if (control & (1u << 17)) refuse(pc,"reserved DPP16 control bit");
const auto pattern = (control >> 8) & 0x1ff;
i.dpp_control = pattern;
i.dpp_row_mask = control >> 28;
i.dpp_bank_mask = (control >> 24) & 15;
if (pattern > 255 && !i.mirror_mask() && i.dpp_row().op == Inst::DppRowOp::None)
refuse(pc,"unsupported DPP lane selection");
i.dpp_fetch_inactive = (control & (1u << 18)) != 0;
Expand Down
28 changes: 21 additions & 7 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1353,8 +1353,6 @@ struct DirectCompute {
// existing refusal; this lowering is the direct compute path.
if (graphics_input)
return false;
if (i.dpp_control || permuted)
refuse(i.pc, "unsupported " + string(n) + " DPP form");
if (i.clamp || i.scale)
refuse(i.pc, "unsupported " + string(n) + " clamp or omod");
// op_sel bits 11..14 select a high half. Bit 15 is clamp, already refused.
Expand All @@ -1365,7 +1363,9 @@ struct DirectCompute {
auto half_bits = [&](unsigned j) {
const unsigned r = i.src[j];
string bits;
if (i.subword) {
if (!j && permuted) {
bits = ir.binary("and", *permuted, "65535");
} else if (i.subword) {
// A DWORD selection reads the low half for binary16 arithmetic.
const unsigned sel = i.src_select[j];
bits = subword(operand32(i, r), sel == 6 ? 4 : sel, false);
Expand Down Expand Up @@ -3044,7 +3044,7 @@ struct DirectCompute {
: mask ? "DPP mirror needs complete source lane groups"
: "DPP quad_perm needs a thread count divisible by four");
const auto rule = alu_rules.find(i.name);
if (rule == alu_rules.end() || rule->second.arity > 2)
if (!binary16_alu(i.name) && (rule == alu_rules.end() || rule->second.arity > 2))
refuse(i.pc, "unsupported DPP arithmetic");
if (i.enc == Encoding::Vop1 && ((i.neg | i.abs) & 2))
refuse(i.pc, "unexpected second DPP source modifier");
Expand All @@ -3070,20 +3070,34 @@ struct DirectCompute {
}
auto src = operand32(i, i.src[0]);
auto word = ir.invoke("i32", "waveReadLaneAt.i32", 117, {{"i32",src},{"i32",source_lane}}, "nounwind");
string previous;
if (!i.dpp_fetch_inactive) {
auto exec = wave64 ? select(upper_half, read(127), read(126)) : read(126);
auto source_enabled = cmp("ne", ir.binary("and", exec, ir.binary("shl", "1", source_lane)), "0");
source_usable = source_usable.empty() ? source_enabled
: ir.value("and i1 " + source_usable + ", " + source_enabled);
}
string write_enabled;
if (!source_usable.empty()) {
if (i.dpp_bound_zero) word = select(source_usable, word, "0");
else previous = read(i.dst);
else write_enabled = source_usable;
}
// Row and bank masks gate destination writes independently of the source and BOUND_CTRL.
auto apply_mask = [&](unsigned mask, const string &index) {
auto enabled = cmp("ne", ir.binary("and", to_string(mask), ir.binary("shl", "1", index)), "0");
write_enabled = write_enabled.empty() ? enabled : ir.value("and i1 " + write_enabled + ", " + enabled);
};
if (i.dpp_row_mask != 15) {
auto row_index = ir.binary("lshr", lane, "4");
if (wave64) row_index = ir.binary("or", row_index, select(upper_half, "2", "0"));
apply_mask(i.dpp_row_mask, row_index);
}
if (i.dpp_bank_mask != 15)
apply_mask(i.dpp_bank_mask, ir.binary("and", ir.binary("lshr", lane, "2"), "3"));
string previous;
if (!write_enabled.empty()) previous = read(i.dst);
arithmetic(i, state, &word);
if (!previous.empty())
write(i.dst, select(source_usable, read(i.dst), previous));
write(i.dst, select(write_enabled, read(i.dst), previous));
}
// Returns true when the instruction is a MODE write this path has accepted
// (including a no-op that leaves the implemented contract in place).
Expand Down
106 changes: 74 additions & 32 deletions tests/native_f16_alu_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
native_f16_alu_check.py ir DUMPER
build one compute container, dump its DXIL text, evaluate it, and require the named refusals
native_f16_alu_check.py gpu STORE_REPLAY SDK
compute readback of the same words (exit 77 when the adapter cannot run a wave32 shader)
compute readback of the same words and the DPP16 cases (exit 77 without wave32)
"""
import re
import struct
Expand Down Expand Up @@ -48,6 +48,15 @@
]
HI_A = 0xABCD0000
HI_B = 0x789A0000
DPP_EXEC = 0xFFFFFEFD # Lanes 1 and 8 are inactive during the DPP instructions.
DPP_OLD = HI_A | 0x3555
DPP_CASES = (
# op, DPP_CTRL, FI, BOUND_CTRL, row mask, bank mask, src1 low half
('add', 0xB1, True, False, 0xF, 0xF, 0x1000), # quad_perm:[1,0,3,2], ties to even
('mul', 0x111, False, False, 0xF, 0xF, 0x3C01), # row_shr:1, preserve at row edges
('sub', 0xB1, True, False, 0x5, 0xF, 0x3C01),
('subrev', 0xB1, False, True, 0xF, 0x5, 0x3C01),
)


def binary16(op, a, b):
Expand Down Expand Up @@ -208,11 +217,15 @@ def all_cases():
return items


def program(items):
"""Preamble plus one store per case. s4 is the descriptor table and s5 is the group id."""
code = [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020,
def preamble():
"""s4 is the descriptor table and s5 is the group id."""
return [sop1(3, 20, 4), sop1(3, 21, 128), 0xf408080a, 0xfa000020,
scalar(0x1e, 7, 5, 128 + SHIFT), vmove(8, 7), sop1(3, 126, 129),
0xbfa40000, 0xbfa40010, 0xbfa5000f, 0xba800881, 0]


def program(items):
code = preamble()
want = []
for case in items:
code += case.emit()
Expand All @@ -222,6 +235,37 @@ def program(items):
return code, want


def dpp_program():
assert STRIDE == 32 * len(DPP_CASES)
code = preamble()
code += [sop1(3, 126, 193)] # the preamble leaves EXEC at lane 0; set up every lane
code += vop2(0x1A, 8, 132, 0) + vop2(0x25, 8, 7, 8) # 16 * lane + group byte base
code += mov(1, HI_B | 0x3c00) + vop2(0x1C, 1, 256, 1) # lane-distinct src0
for slot, (op, pattern, fi, bound_zero, rows, banks, src1) in enumerate(DPP_CASES):
control = 1 | pattern << 8 | fi << 18 | bound_zero << 19 | banks << 24 | rows << 28
code += mov(2, HI_B | src1) + mov(3, DPP_OLD)
code += [sop1(3, 126, 255), DPP_EXEC, *vop2(OP_CODE[op], 3, 250, 2), control]
# Store under full EXEC to observe both lane masks and preserved destinations.
code += [sop1(3, 126, 193), *store(4 * slot, 3)]
return code + [0xbf810000]


def dpp_reference():
results = []
for lane in range(32):
for op, _, fi, bound_zero, rows, banks, src1 in DPP_CASES:
peer = lane - 1 if op == 'mul' else lane ^ 1
in_row = peer // 16 == lane // 16
usable = in_row and (fi or DPP_EXEC & (1 << peer))
row, bank = lane // 16, lane // 4 % 4
enabled = DPP_EXEC & (1 << lane) and rows & (1 << row) and banks & (1 << bank)
if enabled and (usable or bound_zero):
results.append(HI_A | binary16(op, 0x3c00 + peer if usable else 0, src1))
else:
results.append(DPP_OLD)
return results


def swapped_want(case):
op = {'sub': 'subrev', 'subrev': 'sub'}.get(case.op, case.op)
return binary16(op, modified(case.a, case.abs_mask, case.neg, 0), modified(case.b, case.abs_mask, case.neg, 1))
Expand Down Expand Up @@ -262,8 +306,9 @@ def check_model(items):
def refusal_programs():
add = vop2(0x32, 3, 257, 2)
programs = []
for name, op in OP_CODE.items():
programs.append((vop2(op, 3, 250, 2) + [0, 0xbf810000], 'unsupported v_%s_f16 DPP form' % name))
programs.append((vop2(0x32, 3, 233, 2) + [0xfac68801, 0xbf810000], 'SDWA or DPP vector operands'))
# Clamp needs a wide encoding. A VOP3 with clamp and the DPP16 source selector is invalid.
programs.append((vop3(0x32, 3, 250, 258, clamp=1) + [0xbf810000], 'unsupported v_add_f16 clamp or omod'))
programs.append((vop3(0x35, 3, 257, 258, clamp=1) + [0xbf810000], 'unsupported v_mul_f16 clamp or omod'))
programs.append((vop3(0x33, 3, 257, 258, omod=1) + [0xbf810000], 'unsupported v_sub_f16 clamp or omod'))
programs.append((vop3(0x34, 3, 257, 258, opsel=1) + [0xbf810000], 'unsupported v_subrev_f16 high-half op_sel'))
Expand Down Expand Up @@ -535,6 +580,8 @@ def run_ir(dumper):
bad = [(i, hex(got), hex(expected)) for i, ((_, got), expected) in enumerate(zip(stores, want))
if not same_half(got, expected)]
assert not bad, bad[:8]
run = dump(dumper, work, dpp_program(), 'dpp')
assert run.returncode == 0 and 'waveReadLaneAt.i32' in run.stdout, (run.stdout, run.stderr)
for refused, why in refusal_programs():
run = dump(dumper, work, refused, 'refused')
assert run.returncode != 0 and why in run.stderr, (why, run.returncode, run.stderr)
Expand All @@ -551,37 +598,32 @@ def group_offsets(count):


def run_gpu(gpu, sdk):
items = all_cases()
code, want = program(items)
code, want = program(all_cases())
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, 0, 0x80 | (5 << 1))
marker = write_request(work, code, root.read_bytes(), sa)
dest = work / 'f16-alu-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()
offsets = group_offsets(len(want))
expected = [SENTINEL] * WORDS
results = {}
for group in range(GROUPS):
for slot, value in zip(offsets[group], want):
expected[slot] = value
results[slot] = value
actual = struct.unpack('<2064I', dest.read_bytes())
bad = []
for index, (got, model) in enumerate(zip(actual, expected)):
# NaN payloads are not portable. Finite values and infinities match bit for bit,
# and every result keeps HI_A in its upper half. Words outside the stores stay at the fill.
ok = same_half(got, results[index]) if index in results else got == model
if not ok:
bad.append((index, hex(got), hex(model)))
assert not bad[:10], bad[:10]
print('native_f16_alu GPU: %d words matched the model, high half kept' % (GROUPS * len(want)))
sa = struct.pack('<7I', 0, 0, 0, 32 | (1 << 16), 1 | (1 << 20), 0, 0x80 | (5 << 1))
for name, instructions, reference in (('alu', code, want), ('dpp', dpp_program(), dpp_reference())):
marker = write_request(work, instructions, root.read_bytes(), sa)
dest = work / (name + '-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()
results = {slot: value for offsets in group_offsets(len(reference))
for slot, value in zip(offsets, reference)}
actual = struct.unpack('<2064I', dest.read_bytes())
bad = []
for index, got in enumerate(actual):
model = results.get(index, SENTINEL)
# Compare NaNs by class, keep the destination high half, and check the guard words.
ok = same_half(got, model) if index in results else got == model
if not ok:
bad.append((index, hex(got), hex(model)))
assert not bad, (name, bad[:10])
print('native_f16_alu GPU %s: %d words matched the model, high half kept' % (name, len(results)))


if __name__ == '__main__':
Expand Down
Loading