diff --git a/docs/experiments/f16-alu-direct.md b/docs/experiments/f16-alu-direct.md index bfe744c700..0e12b27e1f 100644 --- a/docs/experiments/f16-alu-direct.md +++ b/docs/experiments/f16-alu-direct.md @@ -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 @@ -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 @@ -38,8 +50,8 @@ python3 -B tests/native_f16_alu_check.py model python3 -B tests/native_f16_alu_check.py ir ``` -- `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. diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index dafa8d5a44..712cbb015f 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -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; @@ -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; diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 473dcb443f..d616180f75 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -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; @@ -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 @@ -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) @@ -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"), @@ -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" || diff --git a/tests/f16_exp_midpoints.py b/tests/f16_exp_midpoints.py new file mode 100644 index 0000000000..24eab4f008 --- /dev/null +++ b/tests/f16_exp_midpoints.py @@ -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(' 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('= 128 else math.exp2(x) + + +def rsq_rounding(bits): + """Return the exact RNE result and any alternate allowed by the f32 midpoint window.""" + if not 0 < bits < 0x7c00: + value = half_unary_value('rsq', h2f(bits)) + result = 0x7e00 if math.isnan(value) else struct.unpack(' 1: + mid = (lo + hi) // 2 + if below_rsq(Fraction(h2f(mid))): + lo = mid + else: + hi = mid + lower, upper = Fraction(h2f(lo)), Fraction(h2f(hi)) + if source * upper * upper == 1: + return hi, None + midpoint = (lower + upper) / 2 + if source * midpoint * midpoint == 1: + rounded = lo if lo % 2 == 0 else hi + else: + rounded = hi if below_rsq(midpoint) else lo + # The result and midpoint share the lower encoding's binade. Compare + # the exact reciprocal square root to each endpoint by squaring. + radius = Fraction(2) ** ((lo >> 10) - 15 - 20) + near = below_rsq(midpoint - radius) and source * (midpoint + radius) ** 2 > 1 + return rounded, (lo if rounded == hi else hi) if near else None + + +def half_op(op, a, b=0, c=0): + """Round one binary16 operation, including unary rcp, sqrt, rsq and exp2.""" + if op == 'rsq': + return rsq_rounding(a)[0] + if op in ('rcp', 'sqrt', 'exp'): + x = h2f(a) + if op == 'rcp' and math.isfinite(x) and x != 0: + return round_exact(1 / Fraction(x)) + value = half_unary_value(op, x) + if math.isnan(value): + return 0x7e00 + if value == 0 or math.isinf(value): + return struct.unpack('> 16 != HI_A >> 16 or want >> 16 not in (0, HI_A >> 16): - return False - return same_binary16(got & 0xffff, want & 0xffff) - - def same_binary16(got, want): """Bit equality of two binary16 values (16 bits each). Any NaN matches any NaN.""" if got >> 16 or want >> 16: @@ -96,6 +96,20 @@ def same_binary16(got, want): return got == want +def same_alu_result(got, want, op, alternate): + if op == 'exp': + return got == want + return same_binary16(got, want) or got == alternate + + +def same_half(got, want, case=None): + """Check the preserved HI_A and compare the low half with the reference.""" + if got >> 16 != HI_A >> 16 or want >> 16 not in (0, HI_A >> 16): + return False + return same_alu_result(got & 0xffff, want & 0xffff, + case.op if case else None, case.alternate if case else None) + + def _u32(value): return value & 0xffffffff @@ -130,9 +144,19 @@ def round_shift(value, shift, half): def f32_half(op, a, b): - """f32 operation of two exact f16 values, then the integer binary16 round.""" + """f32 operation on exact f16 inputs, then the integer binary16 round.""" left, right = M.h2f(a), M.h2f(b) - value = {'add': left + right, 'sub': left - right, 'subrev': right - left, 'mul': left * right}[op] + if op in UNARY_CODE: + value = M.half_unary_value(op, left) + else: + value = {'add': left + right, 'sub': left - right, 'subrev': right - left, 'mul': left * right}[op] + if op == 'exp': + if M.is_nan(a): + return 0x7e00 + if a == 0xce40: + return 0 + if a in exp_f16_midpoints(): + return exp_f16_midpoints()[a] bits = struct.unpack('= 1.0 else val) values[name] = ('float', struct.unpack('> self.shift, (self.want & self.mask) >> self.shift)) + fixture.same_alu_result((got & self.mask) >> self.shift, + (self.want & self.mask) >> self.shift, self.op, self.alternate)) def cases(): @@ -97,6 +104,14 @@ def cases(): # neg on one source and abs on the other: -(1.0) + |-2.0| = 1.0; dropping either modifier changes the sum. Case('add', 0x44003c00, 0xc0004500, WORD_1, PAD, WORD_0 | NEG, WORD_1 | ABS), ] + for op in fixture.UNARY_CODE: + items.append(Case(op, 0xc4003800, 0, WORD_1, PRESERVE, WORD_1 | ABS, 0)) + items.append(Case(op, 0x44004000, 0, WORD_0, PAD, DWORD | NEG, 0)) + items += [ + Case('rsq', 0x44000000, 0, WORD_1, PAD, WORD_0 | NEG, 0), + Case('rsq', 0x3bfe4400, 0, WORD_1, PRESERVE, WORD_1, 0), + Case('exp', 0x91c54400, 0, WORD_1, PRESERVE, WORD_1 | ABS, 0), + ] assert len(items) < fixture.STRIDE return items @@ -135,6 +150,8 @@ def refusals(): (cvt_sdwa(WORD_1, CLAMP | (1 << 14)), dest_error), (sdwa(0x39, WORD_0, PAD, WORD_0, WORD_0), 'unimplemented direct SDWA operand profile'), # max (sdwa(0x3a, WORD_0, PAD, WORD_0, WORD_0), 'unimplemented direct SDWA operand profile'), # min + (sdwa(0x55, WORD_0, PAD, DWORD, dst_mod=1 << 13, unary=True), dest_error), + (sdwa(0x57, WORD_0, PAD, WORD_0, unary=True), 'unimplemented direct SDWA operand profile'), ] + [ (sdwa(op, WORD_0, PAD, DWORD, DWORD, dst_mod=1 << modifier), dest_error) for op in (PKRTZ, ADD_CO_CI) for modifier in (13, 14)