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
28 changes: 20 additions & 8 deletions docs/experiments/f16-alu-direct.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
# Binary16 add, sub, subrev and mul in the direct compute path
# Binary16 arithmetic in the direct compute path

Lowers VOP2 and VOP3 `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16` in the direct C++ compute frontend ([`src/gfx1013_direct_compute.inl`](../../src/gfx1013_direct_compute.inl)). The handler returns without lowering when the stage is graphics, so a graphics program keeps the generic direct-lowering refusal. A graphics container was not dumped on this host.
The direct C++ compute frontend supports VOP2 and VOP3 `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_mul_f16`, plus VOP1 and VOP3 `v_rcp_f16`, `v_sqrt_f16`, `v_rsq_f16` and `v_exp_f16`. All eight operations support SDWA. Graphics programs keep the generic direct-lowering refusal.

## Semantics

- Each source is its low 16 bits. An inline float uses the binary16 rounding of that f32 value. An integer inline or a literal uses its low 16 bits.
- Each source is its low 16 bits by default. An inline float uses the binary16 rounding of that f32 value. An integer inline or a literal uses its low 16 bits. SDWA accepts WORD_0, WORD_1 or DWORD (low half).
- abs clears bit 15 of the half, then neg toggles it.
- 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.
- Reciprocal computes `1.0 / x` in f32. The other unary operations use DXIL Sqrt (24), Rsqrt (25) and Exp (21, base two).
- Reciprocal exchanges signed zeros and signed infinities. Square root preserves signed zero and produces NaN for negative nonzero inputs. Exp returns 1 for either signed zero, infinity at and above 16, positive zero at and below -25, and the canonical quiet NaN for NaN inputs. The emitter handles the exact underflow tie at -25 explicitly.
- 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 preserved. SDWA writes the selected half and pads or preserves the other half.
- Rsq maps +0 to +infinity, -0 to -infinity and +infinity to +0. It returns a quiet NaN for NaN and negative nonzero inputs, including -infinity.
- The emitter selects these results using the binary16 source bits after abs and neg. D3D Rsqrt does not guarantee -infinity for -0, so the rsq zero result takes its sign directly from the source.
- `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).
## Exp and rsq accuracy

The Shader Model 4 assembly references specify a maximum relative error of 2^-21 for both host operations. For a normal f32 result this is less than eight f32 ULP. Every binary16 exp rounding midpoint is in the normal f32 range. [Microsoft Learn exp](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/exp--sm4---asm-) and [Microsoft Learn rsq](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/rsq--sm4---asm-).

Exp targets RDNA 2's 0.5 ULP by selecting the correctly rounded half for the 70 non-tie inputs within that window and resolving the exact tie separately. The [90-digit generator](../../tests/f16_exp_midpoints.py) enumerates the binary16 inputs and the model check compares its entries with the C++ array. The IR and GPU comparisons require exact exp bits, including the canonical NaN, the tie at -25, and all 70 inputs in both VOP1 and VOP3. The table covers 0x11c4, 0x11c5 and 0x11c6. Modifier cases exercise correction after source selection and modification.

For positive finite rsq results, a relative error of 2^-21 contributes at most 2^-10 of a binary16 ULP. Integer RNE adds at most 0.5 ULP in the rounding interval, for a total of at most 0.5 + 2^-10 < 0.51 ULP. The [reference model](../../tests/f16_packed_model.py) compares squared rational endpoints against the exact input to locate the result. It accepts either adjoining half only when the exact result is closer than eight f32 ULP to their midpoint. Both plain encodings and SDWA cover 0x3bfe, which exercises the alternate result.

The [plain-form fixture](../../tests/native_f16_alu_check.py) covers signed zeros and infinities, quiet and signaling NaNs, negative finite values, subnormals, 1, powers of two and general values. Its IR interpreter models Rsqrt returning +infinity for -0 to exercise the sign fix. The [SDWA fixture](../../tests/native_sdwa_f16_check.py) exercises source selection and modifiers, destination padding and preservation, and negation of +0 before rsq.

## Refused forms

Expand All @@ -27,7 +39,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.

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).
For the plain scalar-half forms, fma, fmac, fmamk, fmaak, min, max, ldexp, the min3/max3/med3 forms, div_fixup and the VOP1 ops other than rcp, sqrt, exp and rsq stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16`, `v_min_f16` and `v_log_f16`. The host Log absolute error allowance of 2^-21 near an input of 1 can exceed 0.51 ULP of the small binary16 result, so log needs a tighter bound or a bounded correction before lowering. [Microsoft Learn log](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/log--sm4---asm-).

## Linux

Expand All @@ -38,8 +50,8 @@ python3 -B tests/native_f16_alu_check.py model
python3 -B tests/native_f16_alu_check.py ir <native_compute_ir_dump>
```

- `model` printed `native_f16_alu model: 82 results match f32-then-round; a sub/subrev swap and a non-zero upper half are rejected`.
- `ir` printed `native_f16_alu IR: 82 results match the model; 20 refusals carry the named diagnostic`. The module calls `legacyF16ToF32`, `fadd`, `fsub` and `fmul`, and the integer round contains the constant `939524096`.
- Before unary coverage was added, `model` checked 82 results, including controls for a sub/subrev swap and a zeroed upper half.
- Before unary coverage was added, `ir` reported 82 results and 20 refusals. The module used `legacyF16ToF32`, `fadd`, `fsub` and `fmul`, and the integer round contained the constant `939524096`.

`native_f16_alu_hardware` was not run. It is registered with skip code 77, the same code `native_store_replay` returns when the device cannot run a wave32 shader. WARP is expected to take that skip.

Expand Down
10 changes: 8 additions & 2 deletions src/gfx1013_compute_native.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ static bool binary16_alu(std::string_view name) {
return name == "v_add_f16" || name == "v_sub_f16" || name == "v_subrev_f16" || name == "v_mul_f16";
}

static bool binary16_unary(std::string_view name) {
return name == "v_rcp_f16" || name == "v_sqrt_f16" || name == "v_exp_f16" ||
name == "v_rsq_f16";
}

[[noreturn]] void refuse(unsigned pc, const string &reason) {
std::ostringstream out;
out << "native compute +0x" << std::hex << pc << ": " << reason;
Expand Down Expand Up @@ -287,9 +292,10 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa
} else
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);
const bool half_alu = !graphics && ((i.enc == Encoding::Vop2 && binary16_alu(encoded.name)) ||
(i.enc == Encoding::Vop1 && binary16_unary(encoded.name)));
const bool dpp8 = i.src[0] == 233 || i.src[0] == 234;
if (direct && half_alu && dpp8)
if (direct && half_alu && (dpp8 || (i.enc == Encoding::Vop1 && 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;
Expand Down
76 changes: 63 additions & 13 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,30 @@ struct DirectCompute {
// The nine inline float constants as binary16, which an f16 operand reads instead of the f32 pattern.
static constexpr Word inline_half_words[]{0x3800, 0xb800, 0x3c00, 0xbc00, 0x4000,
0xc000, 0x4400, 0xc400, 0x3118};
// D3D exp (sm4 asm) has relative error <= 2^-21, or < 8 ULP for normal f32 results.
// tests/f16_exp_midpoints.py generates the non-tie cases within that window
// using a 90-digit reference. The exact tie at -25 is handled separately.
struct ExpF16Midpoint { Word source, result; };
static constexpr ExpF16Midpoint exp_f16_midpoints[]{
{0x11c3, 0x3c00}, {0x11c4, 0x3c00}, {0x11c5, 0x3c01}, {0x11c6, 0x3c01},
{0x11c7, 0x3c01}, {0x1853, 0x3c01}, {0x1b34, 0x3c02}, {0x1b35, 0x3c03},
{0x1e7a, 0x3c04}, {0x1fea, 0x3c06}, {0x2164, 0x3c08}, {0x221b, 0x3c08},
{0x2389, 0x3c0a}, {0x2bdb, 0x3c2c}, {0x2e7c, 0x3c4a}, {0x2ea7, 0x3c4c},
{0x2fe7, 0x3c5b}, {0x36b6, 0x3d5a}, {0x3863, 0x3dd9}, {0x39f8, 0x3eb5},
{0x3a8a, 0x3f0c}, {0x3b12, 0x3f62}, {0x3b82, 0x3faa}, {0x3efc, 0x42b5},
{0x3f45, 0x430c}, {0x3f89, 0x4362}, {0x3fc1, 0x43aa}, {0x417e, 0x46b5},
{0x437e, 0x4ab5}, {0x44bf, 0x4eb5}, {0x45bf, 0x52b5}, {0x46bf, 0x56b5},
{0x47bf, 0x5ab5}, {0x8dc3, 0x3c00}, {0x8dc4, 0x3c00}, {0x8dc5, 0x3c00},
{0x8dc6, 0x3bff}, {0x8dc7, 0x3bff}, {0x8dc8, 0x3bff}, {0x9454, 0x3bff},
{0x9455, 0x3bfe}, {0x9738, 0x3bfd}, {0x990e, 0x3bfc}, {0x9a80, 0x3bfb},
{0x9bf2, 0x3bfb}, {0x9e25, 0x3bf7}, {0x9f98, 0x3bf5}, {0xa2b4, 0x3bed},
{0xa52d, 0x3be3}, {0xa86d, 0x3bd0}, {0xa8b4, 0x3bcc}, {0xa9d1, 0x3bc0},
{0xabe0, 0x3baa}, {0xaf57, 0x3b63}, {0xaf70, 0x3b62}, {0xb1d8, 0x3b0c},
{0xb410, 0x3ab5}, {0xb4db, 0x3a7c}, {0xb73a, 0x39d9}, {0xb8a5, 0x395a},
{0xbc3f, 0x37aa}, {0xbc77, 0x3762}, {0xbcbb, 0x370c}, {0xbd04, 0x36b5},
{0xc082, 0x32b5}, {0xc282, 0x2eb5}, {0xc441, 0x2ab5}, {0xc541, 0x26b5},
{0xc641, 0x22b5}, {0xc741, 0x1eb5},
};
static void validate_lane_shape(const Inst &i, unsigned threads, unsigned width) {
const auto constant = constant32(i, i.src[1]);
const auto remaining = threads % width;
Expand All @@ -22,7 +46,7 @@ struct DirectCompute {
HeapViewContract heap_view = HeapViewContract::none;
// heap_view is raw_buffer and the path is direct: the byte-address rewrite of a heap descriptor is tracked.
bool heap_window = false;
// Binary16 add, sub, subrev and mul are lowered only while MODE stays at
// Binary16 arithmetic is lowered only while MODE stays at
// the contract this path implements: round-to-nearest-even, f16 denormals
// kept on input and output, and FP16_OVFL clear. mode_bits holds the
// fields this path tracks (round in [3:0], denorm in [7:4], FP16_OVFL in
Expand Down Expand Up @@ -1650,7 +1674,7 @@ struct DirectCompute {
vector_write(i.dst, place_subword(i, result));
return true;
}
if (n == "v_add_f16" || n == "v_sub_f16" || n == "v_subrev_f16" || n == "v_mul_f16") {
if (binary16_alu(n) || binary16_unary(n)) {
// The graphics frontend shares this ALU. Leave those programs on the
// existing refusal; this lowering is the direct compute path.
if (graphics_input)
Expand Down Expand Up @@ -1698,18 +1722,44 @@ struct DirectCompute {
auto widen = [&](const string &bits) {
return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone");
};
auto a = widen(half_bits(0));
auto b = widen(half_bits(1));
if (n == "v_subrev_f16")
std::swap(a, b);
const char *op = n == "v_mul_f16" ? "fmul" : n == "v_add_f16" ? "fadd" : "fsub";
auto widened = ir.value(string(op) + " float " + a + ", " + b);
const auto source = half_bits(0);
auto a = widen(source);
const bool rsq = n == "v_rsq_f16", exp = n == "v_exp_f16";
string widened;
if (n == "v_rcp_f16") {
widened = ir.value("fdiv float 1.000000e+00, " + a);
} else if (binary16_unary(n)) {
const unsigned opcode = rsq ? 25 : exp ? 21 : 24;
widened = ir.invoke("float", "unary.f32", opcode, {{"float", a}}, "nounwind readnone");
} else {
auto b = widen(half_bits(1));
if (n == "v_subrev_f16")
std::swap(a, b);
const char *op = n == "v_mul_f16" ? "fmul" : n == "v_add_f16" ? "fadd" : "fsub";
widened = ir.value(string(op) + " float " + a + ", " + b);
}
auto bits = ir.value("bitcast float " + widened + " to i32");
// f32 has a 24-bit significand, which covers a correctly rounded f16
// add, sub or mul (2*11+2). Round with the same integer nearest-even
// conversion v_cvt_f16_f32 uses.
// Round with the same integer nearest-even conversion v_cvt_f16_f32 uses.
auto rounded = packed_half_rne(bits);
// D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest lists these four ops with
if (rsq) {
// Enforce RDNA2's exact special results from the modified half bits.
// The D3D Rsqrt contract does not guarantee a negative infinity for -0.
// Select the other special results explicitly as well.
const auto magnitude = ir.binary("and", source, "32767");
// Every encoding above +infinity is negative or a positive NaN.
rounded = select(cmp("ugt", source, "31744"), "32256", rounded);
rounded = select(cmp("eq", source, "31744"), "0", rounded);
const auto zero_result = ir.binary("or", source, "31744");
rounded = select(cmp("eq", magnitude, "0"), zero_result, rounded);
} else if (exp) {
for (const auto &entry : exp_f16_midpoints)
rounded = select(cmp("eq", source, to_string(entry.source)), to_string(entry.result), rounded);
// 2^-25 is exactly halfway between zero and the smallest half subnormal.
rounded = select(cmp("eq", source, to_string(0xce40)), "0", rounded);
const auto magnitude = ir.binary("and", source, "32767");
rounded = select(cmp("ugt", magnitude, "31744"), "32256", rounded);
}
// D[31:16] keeps its value: LLVM GCNSubtarget::zeroesHigh16BitsOfDest says
// "On gfx10, all 16-bit instructions preserve the high bits", as v_cvt_f16_f32 above already does.
vector_write(i.dst, i.subword ? place_subword(i, rounded)
: ir.binary("or", ir.binary("and", read(i.dst), "4294901760"),
Expand Down Expand Up @@ -3784,7 +3834,7 @@ struct DirectCompute {
if (!p.reached[k])
continue;
const auto &op = p.code[k];
if (binary16_alu(op.name) ||
if (binary16_alu(op.name) || binary16_unary(op.name) ||
op.name == "v_pk_min_f16" ||
op.name == "v_pk_max_f16" ||
op.name == "v_cvt_f16_u16" ||
Expand Down
58 changes: 58 additions & 0 deletions tests/f16_exp_midpoints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Generate the non-tie binary16 exp2 corrections for an 8 f32 ULP window."""
import re
import struct
from decimal import Decimal, localcontext
from fractions import Fraction
from functools import cache
from pathlib import Path


def floor_log2(value):
exponent = value.numerator.bit_length() - value.denominator.bit_length()
return exponent - (value < Fraction(2) ** exponent)


@cache
def exp_f16_midpoints():
entries = {}
with localcontext() as context:
context.prec = 90
ln2 = Decimal(2).ln()
for bits in range(0x10000):
if bits & 0x7fff >= 0x7c00:
continue
operand = struct.unpack('<e', struct.pack('<H', bits))[0]
# Beyond these limits the half result is fixed with ample error margin.
if operand < -25 or operand > 16:
continue
power = Fraction(operand)
integer = power.numerator // power.denominator
fractional = power - integer
exponent = Decimal(fractional.numerator) / Decimal(fractional.denominator)
value = Fraction(2) ** integer * Fraction((exponent * ln2).exp())
binade = floor_log2(value)
half_ulp = Fraction(2) ** (max(binade, -14) - 10)
lower = int(value / half_ulp) * half_ulp
midpoint = lower + half_ulp / 2
distance = abs(value - midpoint)
if distance == 0:
assert bits == 0xce40 # The emitter handles exp2(-25) explicitly.
elif distance < 8 * Fraction(2) ** (binade - 23):
rounded = lower if value < midpoint else lower + half_ulp
result = struct.unpack('<H', struct.pack('<e', float(rounded)))[0]
entries[bits] = result
return entries


def check_cpp_table():
source = Path(__file__).resolve().parents[1] / 'src' / 'gfx1013_direct_compute.inl'
array = re.search(r'exp_f16_midpoints\[\]\s*\{(.*?)\};',
source.read_text(encoding='utf-8'), re.DOTALL)
assert array, 'missing C++ exp_f16_midpoints array'
pairs = re.findall(r'\{\s*(0x[0-9a-f]+),\s*(0x[0-9a-f]+)\s*\}', array[1])
parsed = [(int(source, 16), int(result, 16)) for source, result in pairs]
assert len(parsed) == 70 and parsed == list(exp_f16_midpoints().items()), parsed


if __name__ == '__main__':
check_cpp_table()
Loading
Loading