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
2 changes: 1 addition & 1 deletion docs/experiments/f16-alu-direct.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Each of these is a named diagnostic:

`s_round_mode` and `s_denorm_mode` that leave the f16 fields at that contract, and that leave the f32 fields unchanged, are accepted. A write that changes an f32 rounding or denormal field keeps the previous control-instruction refusal. A guest branch together with a MODE write makes the contract unprovable and is refused with the rounding diagnostic.

fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup, VOP1 and the `v_pk` forms stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16` and `v_min_f16`.
For the plain scalar-half forms, fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup and VOP1 stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16` and `v_min_f16`. VOP3P arithmetic has a [separate experiment](native-packed-f16.md).

## Linux

Expand Down
60 changes: 60 additions & 0 deletions docs/experiments/native-packed-f16.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Packed binary16 arithmetic in direct Pixel and Compute DXIL

The direct compiler lowers the VOP3P `v_pk_add_f16`, `v_pk_mul_f16`, and
`v_pk_fma_f16` instructions. Each result half has independent source-half
selectors and input negation. The packed word uses the normal EXEC-masked
destination write. The lowering accepts numeric registers, literal words, and
inline zero.

ADD and MUL widen the inputs, use binary32 arithmetic, then round to binary16
with the existing integer nearest-even conversion. FMA forms the exact 22-bit
product and aligns the addend in integer arithmetic. Alignment keeps a sticky
bit for distant operands, where cancellation cannot reach the discarded bits.
The intermediate keeps 24 significant bits, with its last bit set to one when
discarded bits are nonzero. This round-to-odd step preserves which side of a
binary16 midpoint the exact sum fell on. The final nearest-even conversion
therefore agrees with a single binary16 rounding.

The supported MODE preserves subnormals, rounds to nearest even, and leaves
`FP16_OVFL` clear. Clamp, unsupported source encodings, and undetermined or
unsupported MODE keep explicit refusals. NaN results use the canonical
`0x7e00` half from the project's arithmetic reference. NaN payload behavior
has not been measured on an RDNA2 device.

## Reproduction

Run from an x64 Visual Studio Developer PowerShell with DXC and Python configured.

```powershell
$env:XBOX2WINDOWS_ADAPTER = 'RTX 4070'
cmake --preset dev
cmake --build --preset dev --target compile_dxil native_store_replay offscreen_check
ctest --preset dev --no-tests=error -j 1 -R '^native_packed_f16_' -V
```

The [source-built fixture](../../tests/native_packed_f16_check.py) compares
both halves against the [exact rational model](../../tests/f16_packed_model.py).
Compute checks full and sparse EXEC readbacks, including inactive lanes and
buffer guards. Pixel checks the same FMA cases and alternates ADD and MUL in
the other two output channels. Two FMA cases distinguish one binary16 rounding
from a nearest-even binary32 intermediate. The first stores `0x3e053e01`,
where the double-rounded version would store `0x3e043e02`. The second stores
`0x6201be01` instead of `0x6202be02`. Compute replay requires wave32.

On Windows 11 with SDK 10.0.26100 and DXC 1.9.2602.17, the RTX 4070
(driver `32.0.16.2124`) matched all 2,064 Compute readback words in each of
the full and sparse dispatches. Pixel matched all ten cases on both the RTX
4070 and WARP (`10.0.26100.10068`). The local WARP adapter exposes four
lanes, so the wave32 Compute replay used the RTX 4070.

## References

- [AMD RDNA 2 ISA, section 12.10](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf)
and [LLVM 21.1.0 GFX1030 assembly syntax](https://releases.llvm.org/21.1.0/docs/AMDGPU/AMDGPUAsmGFX1030.html#vop3p)
document the operand fields. The LLVM release is `3623fe661ae35c6c80ac221f14d85be76aa870f1`, Apache-2.0 WITH LLVM-exception.
- [Boldo and Melquiond, *Emulation of a FMA and Correctly Rounded Sums*](https://guillaume.melquiond.fr/doc/08-tc.pdf)
explains rounding to odd and the subsequent nearest-even conversion.
- [shadPS4 #4354](https://github.com/shadps4-emu/shadPS4/pull/4354) demonstrates
the corresponding translation scope. Observed 2026-11-27 at
`34b35b526e3bfbb8a6f22c11035cb051174ac6f1`, GPL-2.0. The code and
fixtures in this repository were developed independently.
122 changes: 122 additions & 0 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
Expand Up @@ -1062,8 +1062,128 @@ struct DirectCompute {
h = select(nan, ir.binary("or", ir.binary("lshr", frac, "13"), "32256"), h);
return ir.binary("or", h, sign);
}
static bool packed_f16_arithmetic(Name n) {
return n == "v_pk_add_f16" || n == "v_pk_mul_f16" || n == "v_pk_fma_f16";
}
string fused_half_rne(const string &a, const string &b, const string &c) {
auto both = [&](const string &x, const string &y) { return ir.value("and i1 " + x + ", " + y); };
auto either = [&](const string &x, const string &y) { return ir.value("or i1 " + x + ", " + y); };
auto clz = [&](const string &value) {
// FirstbitHi counts from the most significant bit. OR-ing in bit
// zero leaves every nonzero count unchanged and bounds zero's shift.
return ir.invoke("i32", "unaryBits.i32", 33,
{{"i32", ir.binary("or", value, "1")}}, "nounwind readnone");
};
struct Half { string magnitude, sign, significand, exponent; };
auto decode = [&](const string &word) {
auto magnitude = ir.binary("and", word, "32767");
auto field = ir.binary("lshr", magnitude, "10");
auto normal = cmp("ne", field, "0");
auto hidden = select(normal, "1024", "0");
return Half{magnitude, ir.binary("and", word, "32768"),
ir.binary("or", ir.binary("and", word, "1023"), hidden),
ir.binary("sub", select(normal, field, "1"), "25")};
};
auto x = decode(a), y = decode(b), z = decode(c);
auto product_sign = ir.binary("xor", x.sign, y.sign);
auto product = ir.binary("mul", x.significand, y.significand);
auto product_exp = ir.binary("add", x.exponent, y.exponent);

// Normalize both exact terms at bit 30, leaving space for a carry.
// The product has at most 22 bits and the addend at most 11. Close
// exponents therefore align exactly, including after cancellation.
auto normalize = [&](const string &mantissa, const string &exponent) {
auto leading = clz(mantissa);
return std::pair{
ir.binary("shl", mantissa, ir.binary("sub", leading, "1")),
select(cmp("eq", mantissa, "0"), "-128",
ir.binary("add", exponent, ir.binary("sub", "31", leading)))};
};
auto [product_mantissa, product_top] = normalize(product, product_exp);
auto [addend_mantissa, addend_top] = normalize(z.significand, z.exponent);
auto product_larger = either(cmp("sgt", product_top, addend_top),
both(cmp("eq", product_top, addend_top), cmp("uge", product_mantissa, addend_mantissa)));
auto big = select(product_larger, product_mantissa, addend_mantissa);
auto smaller_mantissa = select(product_larger, addend_mantissa, product_mantissa);
auto big_exp = select(product_larger, product_top, addend_top);
auto small_exp = select(product_larger, addend_top, product_top);
auto sign = select(product_larger, product_sign, z.sign);
auto distance = ir.binary("sub", big_exp, small_exp);
auto shift = select(cmp("ult", distance, "31"), distance, "31");
auto aligned = ir.binary("lshr", smaller_mantissa, shift);
// A wide alignment has no significant cancellation. Retain a sticky
// bit for discarded data so a nearby midpoint still rounds correctly.
auto sticky = cmp("ne", ir.binary("shl", aligned, shift), smaller_mantissa);
aligned = ir.binary("or", aligned, ir.value("zext i1 " + sticky + " to i32"));
auto same_sign = cmp("eq", product_sign, z.sign);
auto magnitude = select(same_sign, ir.binary("add", big, aligned), ir.binary("sub", big, aligned));
auto leading = clz(magnitude);
auto normalized = ir.binary("shl", magnitude, leading);
auto exponent = ir.binary("sub", ir.binary("add", big_exp, "128"), leading);

// Encode the exact sum rounded to odd at binary32 precision. If any
// bits were lost, set the last retained bit. The final binary16
// nearest-even conversion then sees the correct side of every tie.
auto odd = cmp("ne", ir.binary("and", normalized, "255"), "0");
auto significand = ir.binary("or", ir.binary("lshr", normalized, "8"),
ir.value("zext i1 " + odd + " to i32"));
auto binary32 = ir.binary("or", ir.binary("shl", sign, "16"),
ir.binary("or", ir.binary("shl", exponent, "23"), ir.binary("and", significand, "8388607")));
auto zero = select(both(cmp("eq", product, "0"), cmp("eq", z.magnitude, "0")),
ir.binary("and", product_sign, z.sign), "0");
auto finite = select(cmp("eq", magnitude, "0"), zero, packed_half_rne(binary32));

auto x_inf = cmp("eq", x.magnitude, "31744"), y_inf = cmp("eq", y.magnitude, "31744");
auto product_inf = either(x_inf, y_inf), c_inf = cmp("eq", z.magnitude, "31744");
auto invalid_product = either(both(x_inf, cmp("eq", y.magnitude, "0")),
both(y_inf, cmp("eq", x.magnitude, "0")));
auto invalid_sum = both(both(product_inf, c_inf), cmp("ne", product_sign, z.sign));
auto nan = either(either(cmp("ugt", x.magnitude, "31744"), cmp("ugt", y.magnitude, "31744")),
either(cmp("ugt", z.magnitude, "31744"), either(invalid_product, invalid_sum)));
return select(nan, "32256",
select(product_inf, ir.binary("or", product_sign, "31744"), select(c_inf, c, finite)));
}
void packed_f16_alu(const Inst &i) {
const bool fused = i.name == "v_pk_fma_f16";
if (i.enc != Encoding::Mix || i.clamp || (!fused && (i.src[2] || (i.a & 0x2400) || (i.neg & 4))))
refuse(i.pc, "unsupported packed binary16 arithmetic encoding");
if (!half_mode_known || ((mode_bits ^ 0xf0u) & 0x8000ccu))
refuse(i.pc, "unsupported binary16 rounding or denormal mode");
std::array<string, 3> words;
for (unsigned j = 0; j < (fused ? 3u : 2u); ++j) {
unsigned r = i.src[j];
if (r > 105 && r < 256 && r != 128 && r != 255)
refuse(i.pc, "unsupported packed binary16 arithmetic source");
words[j] = operand32(i, r);
}
auto lane = [&](unsigned selectors, unsigned negate) {
auto operand = [&](unsigned j) {
auto bits = (selectors & (1u << j)) ? ir.binary("lshr", words[j], "16")
: ir.binary("and", words[j], "65535");
return (negate & (1u << j)) ? ir.binary("xor", bits, "32768") : bits;
};
auto a = operand(0), b = operand(1);
if (fused)
return fused_half_rne(a, b, operand(2));
auto widen = [&](const string &bits) {
return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone");
};
const auto op = i.name == "v_pk_mul_f16" ? "fmul" : "fadd";
auto result = ir.value(string(op) + " float " + widen(a) + ", " + widen(b));
auto bits = packed_half_rne(ir.value("bitcast float " + result + " to i32"));
return select(cmp("ugt", ir.binary("and", bits, "32767"), "31744"), "32256", bits);
};
// In VOP3P, NEG_HI occupies the ABS field. OP_SEL_HI[2] lives in word 0.
auto low = lane((i.a >> 11) & 7, i.neg);
auto high = lane(((i.b >> 27) & 3) | ((i.a >> 12) & 4), i.abs);
vector_write(i.dst, ir.binary("or", low, ir.binary("shl", high, "16")));
}
bool float_alu(const Inst &i, const string *permuted = nullptr) {
auto n = i.name;
if (packed_f16_arithmetic(n)) {
packed_f16_alu(i);
return true;
}
if ((i.subword || (!i.wide && !i.dpp_control && !permuted)) &&
(n == "v_cvt_f16_f32" || n == "v_cvt_f32_f16")) {
if (i.scale || i.clamp || i.src_sext[0])
Expand Down Expand Up @@ -3003,6 +3123,8 @@ struct DirectCompute {
if (op.name == "s_round_mode" || op.name == "s_denorm_mode" || op.name == "s_setreg_b32" ||
op.name == "s_setreg_imm32_b32")
mode_write = true;
if (packed_f16_arithmetic(op.name))
half_binary = true;
if (op.branch() && op.op != 2)
conditional = true;
}
Expand Down
16 changes: 16 additions & 0 deletions tests/cmake/native_packed_f16.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
if(TARGET compile_dxil AND TARGET native_store_replay AND TARGET offscreen_check AND
EXISTS "${INTAKE_PYTHON}" AND EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll")
set(checker "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_packed_f16_check.py")
add_test(NAME native_packed_f16_controls COMMAND "${INTAKE_PYTHON}" -B
"${checker}" controls "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
set_tests_properties(native_packed_f16_controls PROPERTIES TIMEOUT 60)
add_test(NAME native_packed_f16_compute_hardware COMMAND "${INTAKE_PYTHON}" -B
"${checker}" compute "$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}")
set_tests_properties(native_packed_f16_compute_hardware PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77)
foreach(adapter IN ITEMS warp hardware)
add_test(NAME native_packed_f16_pixel_${adapter} COMMAND "${INTAKE_PYTHON}" -B
"${checker}" pixel "$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}" "$<TARGET_FILE:offscreen_check>" ${adapter})
set_tests_properties(native_packed_f16_pixel_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77)
endforeach()
unset(checker)
endif()
Loading
Loading