From 2e30f9f758da36220bba23a22012baaf0902085d Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:38:13 +0100 Subject: [PATCH 1/3] compute: lower binary16 v_rcp_f16, v_sqrt_f16 and v_exp_f16 The direct compute path lowered the binary16 VOP2 ALU ops only. The three VOP1 ops now take the same route, plain and SDWA: the selected half is widened with legacyF16ToF32, the f32 op is applied (fdiv 1.0, dx.op Sqrt, dx.op Exp), and the result is rounded to binary16 with the nearest-even conversion v_cvt_f16_f32 uses, keeping D[31:16] or placing it per SDWA dst_sel. The same MODE contract applies. v_rsq_f16 and v_log_f16 stay refused. native_f16_alu and native_sdwa_f16 check the three ops against f16_packed_model: rcp and sqrt bit-exact, exp within one binary16 ULP, NaN by class. AI-assisted. --- docs/experiments/f16-alu-direct.md | 18 +++-- src/gfx1013_compute_native.cpp | 9 ++- src/gfx1013_direct_compute.inl | 30 +++++--- tests/f16_packed_model.py | 24 +++++- tests/native_f16_alu_check.py | 119 ++++++++++++++++++++++------- tests/native_sdwa_f16_check.py | 21 ++++- 6 files changed, 167 insertions(+), 54 deletions(-) diff --git a/docs/experiments/f16-alu-direct.md b/docs/experiments/f16-alu-direct.md index bfe744c700..98a6967f1a 100644 --- a/docs/experiments/f16-alu-direct.md +++ b/docs/experiments/f16-alu-direct.md @@ -1,17 +1,19 @@ -# 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` and `v_exp_f16`. All seven 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. Square root and base-two exponentiation use DXIL Sqrt (24) and Exp (21). +- 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, and positive zero at and below -25 after binary16 rounding. +- 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. - `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). +The reference is `half_op` in [`tests/f16_packed_model.py`](../../tests/f16_packed_model.py). Reciprocal uses exact rational rounding and square root uses float64 before binary16 rounding. Both are compared bit for bit. Nonzero finite exp2 results allow one binary16 ULP, and zeros and infinities match exactly. NaN results match by class. The checks are [`tests/native_f16_alu_check.py`](../../tests/native_f16_alu_check.py) and [`tests/native_sdwa_f16_check.py`](../../tests/native_sdwa_f16_check.py). ## Refused forms @@ -27,7 +29,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 and exp (rsq, log and the rest) stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16`, `v_min_f16`, `v_rsq_f16` and `v_log_f16`. VOP3P arithmetic has a [separate experiment](native-packed-f16.md). ## Linux @@ -38,8 +40,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..f62388075e 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -29,6 +29,10 @@ 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"; +} + [[noreturn]] void refuse(unsigned pc, const string &reason) { std::ostringstream out; out << "native compute +0x" << std::hex << pc << ": " << reason; @@ -287,9 +291,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..40cada270a 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -22,7 +22,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 +1650,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) @@ -1699,17 +1699,23 @@ struct DirectCompute { 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); + string widened; + if (n == "v_rcp_f16") { + widened = ir.value("fdiv float 1.000000e+00, " + a); + } else if (n == "v_sqrt_f16" || n == "v_exp_f16") { + widened = ir.invoke("float", "unary.f32", n == "v_sqrt_f16" ? 24 : 21, + {{"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 + // 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 +3790,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_packed_model.py b/tests/f16_packed_model.py index f788b40af0..2b57cebf0b 100644 --- a/tests/f16_packed_model.py +++ b/tests/f16_packed_model.py @@ -55,8 +55,28 @@ def round_exact(x): return neg | (n if e == -14 and n < 0x400 else ((e + 15) << 10) | (n & 0x3ff)) -def half_op(op, a, b, c=0): - """One binary16 lane: op is 'mul', 'add' or 'fma' (a * b + c).""" +def half_unary_value(op, x): + """Evaluate reciprocal, square root or exp2 in float64, including IEEE special values.""" + if op == 'rcp': + return math.copysign(math.inf, x) if x == 0 else 1.0 / x + if op == 'sqrt': + return math.nan if x < 0 else math.sqrt(x) + assert op == 'exp' + return math.inf if x >= 128 else math.exp2(x) + + +def half_op(op, a, b=0, c=0): + """Round one binary16 operation, including unary rcp, sqrt and exp (base two).""" + 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) + return same_binary16(got & 0xffff, want & 0xffff, op) -def same_binary16(got, want): - """Bit equality of two binary16 values (16 bits each). Any NaN matches any NaN.""" +def same_binary16(got, want, op=None): + """Match NaNs by class, allow one binary16 ULP for positive finite exp2 results.""" if got >> 16 or want >> 16: return False if M.is_nan(got) or M.is_nan(want): return M.is_nan(got) and M.is_nan(want) + if op == 'exp' and 0 < got < 0x7c00 and 0 < want < 0x7c00: + return abs(got - want) <= 1 return got == want @@ -130,9 +135,12 @@ 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] bits = struct.unpack('= 1.0 else val) values[name] = ('float', struct.unpack('> self.shift, (self.want & self.mask) >> self.shift)) + fixture.same_binary16((got & self.mask) >> self.shift, (self.want & self.mask) >> self.shift, + self.op)) def cases(): @@ -97,6 +104,9 @@ 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)) assert len(items) < fixture.STRIDE return items @@ -135,6 +145,9 @@ 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(0x56, WORD_0, PAD, WORD_0, unary=True), 'unimplemented direct SDWA operand profile'), + (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) From 56859b7d960f5908c5bb6ffb5622734e4eec592d Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:54:05 +0100 Subject: [PATCH 2/3] compute: lower binary16 v_rsq_f16 and v_log_f16 Extends the binary16 VOP1 lowering to v_rsq_f16 (dx.op Rsqrt) and v_log_f16 (dx.op Log, base 2), plain and SDWA, with the same widen, f32 op and nearest-even rounding. The special results are selected from the f16 input bits, because the D3D contract does not fix them: a negative nonzero input (including -inf) or NaN gives a quiet NaN, rsq(+-0) is +-inf, rsq(+inf) is +0, log(+-0) is -inf, log(+inf) is +inf and log(1) is +0. The f16 checks compare rsq and log within one binary16 ULP, the special results exactly and NaN by class. AI-assisted. --- docs/experiments/f16-alu-direct.md | 14 +++--- src/gfx1013_compute_native.cpp | 3 +- src/gfx1013_direct_compute.inl | 23 ++++++++-- tests/f16_packed_model.py | 28 ++++++++++-- tests/native_f16_alu_check.py | 68 ++++++++++++++++++------------ tests/native_sdwa_f16_check.py | 10 ++--- 6 files changed, 100 insertions(+), 46 deletions(-) diff --git a/docs/experiments/f16-alu-direct.md b/docs/experiments/f16-alu-direct.md index 98a6967f1a..9e5e1f9e5a 100644 --- a/docs/experiments/f16-alu-direct.md +++ b/docs/experiments/f16-alu-direct.md @@ -1,19 +1,23 @@ # Binary16 arithmetic in the direct compute path -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` and `v_exp_f16`. All seven operations support SDWA. Graphics programs keep the generic direct-lowering refusal. +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`, `v_log_f16` and `v_exp_f16`. All nine operations support SDWA. Graphics programs keep the generic direct-lowering refusal. ## Semantics - 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. -- Reciprocal computes `1.0 / x` in f32. Square root and base-two exponentiation use DXIL Sqrt (24) and Exp (21). -- 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, and positive zero at and below -25 after binary16 rounding. +- Reciprocal computes `1.0 / x` in f32. The other unary operations use DXIL Sqrt (24), Rsqrt (25), Log (23, base two) and Exp (21). +- 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, and positive zero at and below -25 (the exact tie at -25 is checked in the CPU model only, since an Exp one f32 ULP high rounds it to the smallest denormal) after binary16 rounding. - 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. Log maps either signed zero to -infinity, +infinity to +infinity and 1 to +0. Both return 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 reference is `half_op` in [`tests/f16_packed_model.py`](../../tests/f16_packed_model.py). Reciprocal uses exact rational rounding and square root uses float64 before binary16 rounding. Both are compared bit for bit. Nonzero finite exp2 results allow one binary16 ULP, and zeros and infinities match exactly. NaN results match by class. The checks are [`tests/native_f16_alu_check.py`](../../tests/native_f16_alu_check.py) and [`tests/native_sdwa_f16_check.py`](../../tests/native_sdwa_f16_check.py). +The reference is `half_op` in [`tests/f16_packed_model.py`](../../tests/f16_packed_model.py). Reciprocal uses exact rational rounding. Square root, reciprocal square root, log2 and exp2 use float64 before binary16 rounding. Nonzero finite exp2, rsq and log2 results allow one binary16 ULP. Other numeric results match exactly, including signed zeros and infinities. NaN results match by class. + +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 and log. ## Refused forms @@ -29,7 +33,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 the VOP1 ops other than rcp, sqrt and exp (rsq, log and the rest) stay on the generic direct-lowering diagnostic. The fixture checks `v_fmac_f16`, `v_min_f16`, `v_rsq_f16` and `v_log_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, rsq and log 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 diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index f62388075e..01346cf32b 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -30,7 +30,8 @@ static bool binary16_alu(std::string_view name) { } static bool binary16_unary(std::string_view name) { - return name == "v_rcp_f16" || name == "v_sqrt_f16" || name == "v_exp_f16"; + return name == "v_rcp_f16" || name == "v_sqrt_f16" || name == "v_exp_f16" || + name == "v_rsq_f16" || name == "v_log_f16"; } [[noreturn]] void refuse(unsigned pc, const string &reason) { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 40cada270a..7d2eed083f 100644 --- a/src/gfx1013_direct_compute.inl +++ b/src/gfx1013_direct_compute.inl @@ -1698,13 +1698,15 @@ struct DirectCompute { auto widen = [&](const string &bits) { return ir.invoke("float", "legacyF16ToF32", 131, {{"i32", bits}}, "nounwind readnone"); }; - auto a = widen(half_bits(0)); + const auto source = half_bits(0); + auto a = widen(source); + const bool rsq = n == "v_rsq_f16", log = n == "v_log_f16"; string widened; if (n == "v_rcp_f16") { widened = ir.value("fdiv float 1.000000e+00, " + a); - } else if (n == "v_sqrt_f16" || n == "v_exp_f16") { - widened = ir.invoke("float", "unary.f32", n == "v_sqrt_f16" ? 24 : 21, - {{"float", a}}, "nounwind readnone"); + } else if (binary16_unary(n)) { + const unsigned opcode = rsq ? 25 : log ? 23 : n == "v_sqrt_f16" ? 24 : 21; + widened = ir.invoke("float", "unary.f32", opcode, {{"float", a}}, "nounwind readnone"); } else { auto b = widen(half_bits(1)); if (n == "v_subrev_f16") @@ -1715,6 +1717,19 @@ struct DirectCompute { auto bits = ir.value("bitcast float " + widened + " to i32"); // Round with the same integer nearest-even conversion v_cvt_f16_f32 uses. auto rounded = packed_half_rne(bits); + if (rsq || log) { + // 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"), rsq ? "0" : "31744", rounded); + const auto zero_result = rsq ? ir.binary("or", source, "31744") : "64512"; + rounded = select(cmp("eq", magnitude, "0"), zero_result, rounded); + if (log) + rounded = select(cmp("eq", source, "15360"), "0", 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) diff --git a/tests/f16_packed_model.py b/tests/f16_packed_model.py index 2b57cebf0b..88a2f14854 100644 --- a/tests/f16_packed_model.py +++ b/tests/f16_packed_model.py @@ -56,18 +56,26 @@ def round_exact(x): def half_unary_value(op, x): - """Evaluate reciprocal, square root or exp2 in float64, including IEEE special values.""" + """Evaluate binary16 unary operations in float64, including special values.""" if op == 'rcp': return math.copysign(math.inf, x) if x == 0 else 1.0 / x if op == 'sqrt': return math.nan if x < 0 else math.sqrt(x) + if op == 'rsq': + if x == 0: + return math.copysign(math.inf, x) + return math.nan if x < 0 else 1.0 / math.sqrt(x) + if op == 'log': + if x == 0: + return -math.inf + return math.nan if x < 0 else math.log2(x) assert op == 'exp' return math.inf if x >= 128 else math.exp2(x) def half_op(op, a, b=0, c=0): - """Round one binary16 operation, including unary rcp, sqrt and exp (base two).""" - if op in ('rcp', 'sqrt', 'exp'): + """Round one binary16 operation, including unary rcp, sqrt, rsq, log2 and exp2.""" + if op in ('rcp', 'sqrt', 'rsq', 'log', 'exp'): x = h2f(a) if op == 'rcp' and math.isfinite(x) and x != 0: return round_exact(1 / Fraction(x)) @@ -109,6 +117,20 @@ def pick(word, high): return (word >> 16 if high else word) & 0xffff +def same_half_result(got, want, op=None): + """Allow one binary16 ULP for nonzero finite exp2, rsq and log2 results. + + Match NaNs by class and zeros and infinities exactly. + """ + if got >> 16 or want >> 16: + return False + if is_nan(got) or is_nan(want): + return is_nan(got) and is_nan(want) + if op in ('exp', 'rsq', 'log') and 0 < (got & 0x7fff) < 0x7c00 and 0 < (want & 0x7fff) < 0x7c00: + return abs(got - want) <= 1 + return got == want + + def packed(op, words, op_sel, op_sel_hi): """Result word of v_pk__f16 over 32-bit source words.""" n = len(words) diff --git a/tests/native_f16_alu_check.py b/tests/native_f16_alu_check.py index a22a7f46e0..f5fdbc04a6 100644 --- a/tests/native_f16_alu_check.py +++ b/tests/native_f16_alu_check.py @@ -1,12 +1,12 @@ -"""Binary16 binary ALU, reciprocal, square root and exp2 in the direct C++ compute path. +"""Binary16 binary and unary ALU in the direct C++ compute path. Each source contributes its low 16 bits. abs clears bit 15 of that half, then neg toggles it. The operation runs in f32 and rounds to binary16 the way v_cvt_f16_f32 does. The result is the low 16 bits and the destination's high half keeps its value (LLVM GCNSubtarget::zeroesHigh16BitsOfDest: "On gfx10, all 16-bit instructions preserve the high bits"). Every destination holds HI_A in its high half before the operation, so each stored word is HI_A | result. The reference is half_op in f16_packed_model.py (sub is an add of -the negated second source, subrev swaps the sources). NaNs match by class. Nonzero finite exp2 -results allow one binary16 ULP, with bit-exact comparison for the other numeric results. +the negated second source, subrev swaps the sources). NaNs match by class. Nonzero finite exp2, +rsq and log2 results allow one binary16 ULP. Other numeric results match exactly. native_f16_alu_check.py model no dumper and no GPU: the case table, the f32 rounding cross-check, and the two mutants @@ -32,15 +32,15 @@ WORDS = 2064 SENTINEL = 0x69696969 # native_store_replay fills untouched words with 0x69 BASE = 8 -STRIDE = 256 -SHIFT = 10 +STRIDE = 512 +SHIFT = 11 assert 4 * STRIDE == 1 << SHIFT OPS = ('add', 'sub', 'subrev', 'mul') OP_CODE = {'add': 0x32, 'sub': 0x33, 'subrev': 0x34, 'mul': 0x35} -UNARY_CODE = {'rcp': 0x54, 'sqrt': 0x55, 'exp': 0x58} -UNARY_INPUTS = M.GRID + [0x8001, 0x0400, 0x4000, 0x4400, 0x3555, - 0x4bff, 0x4c00, 0x4c40, 0xce00, 0xce40, 0xce80] +UNARY_CODE = {'rcp': 0x54, 'sqrt': 0x55, 'exp': 0x58, 'rsq': 0x56, 'log': 0x57} +UNARY_INPUTS = M.GRID + [0x8001, 0x0400, 0x3800, 0x4000, 0x4400, 0x3555, + 0x4bff, 0x4c00, 0x4c40, 0xce00, 0xce80] # no 0xce40: exp(-25) is an exact tie to zero # Binary16 rounding of the nine inline float encodings, in encoding order. INLINE_F16 = { 240: 0x3800, 241: 0xb800, 242: 0x3c00, 243: 0xbc00, 244: 0x4000, @@ -83,24 +83,25 @@ def modified(bits, abs_mask, neg, index): return bits & 0xffff -def same_half(got, want, op=None): - """Check the preserved HI_A and compare the low half using the operation's tolerance.""" - if got >> 16 != HI_A >> 16 or want >> 16 not in (0, HI_A >> 16): - return False - return same_binary16(got & 0xffff, want & 0xffff, op) - +def same_binary16(got, want): + """Bit equality of two binary16 values (16 bits each). Any NaN matches any NaN. -def same_binary16(got, want, op=None): - """Match NaNs by class, allow one binary16 ULP for positive finite exp2 results.""" + Exact comparator kept for tests/native_fma_f16_check.py; the unary results use + same_half / f16_packed_model.same_half_result with their one-ULP tolerance.""" if got >> 16 or want >> 16: return False if M.is_nan(got) or M.is_nan(want): return M.is_nan(got) and M.is_nan(want) - if op == 'exp' and 0 < got < 0x7c00 and 0 < want < 0x7c00: - return abs(got - want) <= 1 return got == want +def same_half(got, want, op=None): + """Check the preserved HI_A and compare the low half using the operation's tolerance.""" + if got >> 16 != HI_A >> 16 or want >> 16 not in (0, HI_A >> 16): + return False + return M.same_half_result(got & 0xffff, want & 0xffff, op) + + def _u32(value): return value & 0xffffffff @@ -327,9 +328,22 @@ def check_model(items): assert M.half_op('exp', 0x4c00) == 0x7c00 # 2**16 overflows binary16. assert M.half_op('exp', 0xce00) == 0x0001 # 2**-24 is the least subnormal. assert M.half_op('exp', 0xce40) == 0x0000 # 2**-25 ties to zero. - assert same_binary16(0x4001, 0x4000, 'exp') - assert not same_binary16(0x4002, 0x4000, 'exp') - assert not same_binary16(0x4001, 0x4000, 'rcp') + for source, rsq, log in ((0x0000, 0x7c00, 0xfc00), (0x8000, 0xfc00, 0xfc00), + (0x7c00, 0x0000, 0x7c00), (0x3c00, 0x3c00, 0x0000), + (0x0001, 0x6c00, 0xce00), (0x4400, 0x3800, 0x4000)): + assert M.half_op('rsq', source) == rsq + assert M.half_op('log', source) == log + for source in (0xbc00, 0x8001, 0xfc00, 0x7e01): + assert M.is_nan(M.half_op('rsq', source)) + assert M.is_nan(M.half_op('log', source)) + for op in ('exp', 'rsq', 'log'): + assert M.same_half_result(0x4001, 0x4000, op) + assert not M.same_half_result(0x4002, 0x4000, op) + assert not M.same_half_result(0x7bff, 0x7c00, op) + assert not M.same_half_result(0x0001, 0x0000, op) + assert not M.same_half_result(0x8000, 0x0000, op) + assert M.same_half_result(0xbc01, 0xbc00, 'log') + assert not M.same_half_result(0x4001, 0x4000, 'rcp') for case in items: left = modified(case.a, case.abs_mask, case.neg, 0) right = modified(case.b, case.abs_mask, case.neg, 1) @@ -371,9 +385,6 @@ def refusal_programs(): for mode in (0xbfa4000c, 0xbfa50000): programs.append(([mode] + vop1(op, 3, 257) + [0xbf810000], 'unsupported binary16 rounding or denormal mode')) - for name, op in (('rsq', 0x56), ('log', 0x57)): - for instruction in (vop1(op, 3, 257), vop3(op, 3, 257, 0, unary=True)): - programs.append((instruction + [0xbf810000], 'direct DXIL lowering for v_%s_f16' % name)) return programs @@ -577,12 +588,13 @@ def bits_of(token): clamped = 0.0 if (math.isnan(val) or val <= 0.0) else (1.0 if val >= 1.0 else val) values[name] = ('float', struct.unpack('> self.shift, (self.want & self.mask) >> self.shift, - self.op)) + model.same_half_result((got & self.mask) >> self.shift, (self.want & self.mask) >> self.shift, + self.op)) def cases(): @@ -107,6 +107,8 @@ def cases(): 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)) + for op in ('rsq', 'log'): + items.append(Case(op, 0x44000000, 0, WORD_1, PAD, WORD_0 | NEG, 0)) assert len(items) < fixture.STRIDE return items @@ -146,8 +148,6 @@ def refusals(): (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(0x56, WORD_0, PAD, WORD_0, unary=True), 'unimplemented direct SDWA operand profile'), - (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) @@ -239,7 +239,7 @@ def run_gpu(gpu, sdk, items, code): elif shift is not None: mask = 0xffff << shift matches = (got & ~mask == want & ~mask and - fixture.same_binary16((got & mask) >> shift, (want & mask) >> shift)) + model.same_half_result((got & mask) >> shift, (want & mask) >> shift)) else: matches = got == want assert matches, (index, slot, hex(got), hex(want)) From 41d79706aa9f024dff5b77d6cbc9d2598fb1434d Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:02:43 +0100 Subject: [PATCH 3/3] compute: bound binary16 exp and rsq rounding, keep log refused exp: the binary32 exp2 result is rounded to binary16 as before, then the 70 inputs whose exact result lies closer than 8 binary32 ULP to a binary16 rounding midpoint take their correctly rounded value from a table. 8 ULP covers the documented D3D exp relative error of 2^-21. tests/f16_exp_midpoints.py regenerates the table from a 90-digit reference and checks the C++ array. The exact tie exp2(-25) rounds to +0. exp results are now compared bit for bit. rsq: the documented relative error of 2^-21 is at most 2^-10 of a binary16 ULP, so the result stays within 0.5 + 2^-10 < 0.51 ULP. The test requires the correctly rounded value, and accepts the other neighbouring encoding only within 8 binary32 ULP of a midpoint. log: v_log_f16 is refused again, as on main. Its documented absolute error of 2^-21 on [0.5, 2] can exceed 0.51 binary16 ULP near 1. AI-assisted. --- docs/experiments/f16-alu-direct.md | 20 +++--- src/gfx1013_compute_native.cpp | 2 +- src/gfx1013_direct_compute.inl | 43 ++++++++++--- tests/f16_exp_midpoints.py | 58 +++++++++++++++++ tests/f16_packed_model.py | 60 ++++++++++++------ tests/native_f16_alu_check.py | 99 ++++++++++++++++++------------ tests/native_sdwa_f16_check.py | 28 +++++---- 7 files changed, 224 insertions(+), 86 deletions(-) create mode 100644 tests/f16_exp_midpoints.py diff --git a/docs/experiments/f16-alu-direct.md b/docs/experiments/f16-alu-direct.md index 9e5e1f9e5a..0e12b27e1f 100644 --- a/docs/experiments/f16-alu-direct.md +++ b/docs/experiments/f16-alu-direct.md @@ -1,23 +1,29 @@ # Binary16 arithmetic in the direct compute path -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`, `v_log_f16` and `v_exp_f16`. All nine operations support SDWA. Graphics programs keep the generic direct-lowering refusal. +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 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. -- Reciprocal computes `1.0 / x` in f32. The other unary operations use DXIL Sqrt (24), Rsqrt (25), Log (23, base two) and Exp (21). -- 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, and positive zero at and below -25 (the exact tie at -25 is checked in the CPU model only, since an Exp one f32 ULP high rounds it to the smallest denormal) after binary16 rounding. +- 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. Log maps either signed zero to -infinity, +infinity to +infinity and 1 to +0. Both return a quiet NaN for NaN and negative nonzero inputs, including -infinity. +- 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 reference is `half_op` in [`tests/f16_packed_model.py`](../../tests/f16_packed_model.py). Reciprocal uses exact rational rounding. Square root, reciprocal square root, log2 and exp2 use float64 before binary16 rounding. Nonzero finite exp2, rsq and log2 results allow one binary16 ULP. Other numeric results match exactly, including signed zeros and infinities. NaN results match by class. +## Exp and rsq accuracy -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 and log. +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 @@ -33,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 the VOP1 ops other than rcp, sqrt, exp, rsq and log 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 diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 01346cf32b..712cbb015f 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -31,7 +31,7 @@ static bool binary16_alu(std::string_view name) { 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" || name == "v_log_f16"; + name == "v_rsq_f16"; } [[noreturn]] void refuse(unsigned pc, const string &reason) { diff --git a/src/gfx1013_direct_compute.inl b/src/gfx1013_direct_compute.inl index 7d2eed083f..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; @@ -1700,12 +1724,12 @@ struct DirectCompute { }; const auto source = half_bits(0); auto a = widen(source); - const bool rsq = n == "v_rsq_f16", log = n == "v_log_f16"; + 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 : log ? 23 : n == "v_sqrt_f16" ? 24 : 21; + 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)); @@ -1717,18 +1741,23 @@ struct DirectCompute { auto bits = ir.value("bitcast float " + widened + " to i32"); // Round with the same integer nearest-even conversion v_cvt_f16_f32 uses. auto rounded = packed_half_rne(bits); - if (rsq || log) { + 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"), rsq ? "0" : "31744", rounded); - const auto zero_result = rsq ? ir.binary("or", source, "31744") : "64512"; + 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); - if (log) - rounded = select(cmp("eq", source, "15360"), "0", 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. 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, log2 and exp2.""" - if op in ('rcp', 'sqrt', 'rsq', 'log', 'exp'): + """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)) @@ -117,20 +151,6 @@ def pick(word, high): return (word >> 16 if high else word) & 0xffff -def same_half_result(got, want, op=None): - """Allow one binary16 ULP for nonzero finite exp2, rsq and log2 results. - - Match NaNs by class and zeros and infinities exactly. - """ - if got >> 16 or want >> 16: - return False - if is_nan(got) or is_nan(want): - return is_nan(got) and is_nan(want) - if op in ('exp', 'rsq', 'log') and 0 < (got & 0x7fff) < 0x7c00 and 0 < (want & 0x7fff) < 0x7c00: - return abs(got - want) <= 1 - return got == want - - def packed(op, words, op_sel, op_sel_hi): """Result word of v_pk__f16 over 32-bit source words.""" n = len(words) diff --git a/tests/native_f16_alu_check.py b/tests/native_f16_alu_check.py index f5fdbc04a6..c1b8f1f9f6 100644 --- a/tests/native_f16_alu_check.py +++ b/tests/native_f16_alu_check.py @@ -5,8 +5,9 @@ 16 bits and the destination's high half keeps its value (LLVM GCNSubtarget::zeroesHigh16BitsOfDest: "On gfx10, all 16-bit instructions preserve the high bits"). Every destination holds HI_A in its high half before the operation, so each stored word is HI_A | result. The reference is half_op in f16_packed_model.py (sub is an add of -the negated second source, subrev swaps the sources). NaNs match by class. Nonzero finite exp2, -rsq and log2 results allow one binary16 ULP. Other numeric results match exactly. +the negated second source, subrev swaps the sources). Exp2 matches exact bits. +Rsq permits the other encoding only within 8 f32 ULP of a binary16 midpoint. +For the other operations NaNs match by class. native_f16_alu_check.py model no dumper and no GPU: the case table, the f32 rounding cross-check, and the two mutants @@ -24,6 +25,7 @@ from pathlib import Path import f16_packed_model as M +from f16_exp_midpoints import check_cpp_table, exp_f16_midpoints from native_compute_clear_check import write_request from native_direct_container_check import pack, words from native_scalar_lds_check import scalar, sop1, vmove @@ -38,9 +40,9 @@ OPS = ('add', 'sub', 'subrev', 'mul') OP_CODE = {'add': 0x32, 'sub': 0x33, 'subrev': 0x34, 'mul': 0x35} -UNARY_CODE = {'rcp': 0x54, 'sqrt': 0x55, 'exp': 0x58, 'rsq': 0x56, 'log': 0x57} +UNARY_CODE = {'rcp': 0x54, 'sqrt': 0x55, 'exp': 0x58, 'rsq': 0x56} UNARY_INPUTS = M.GRID + [0x8001, 0x0400, 0x3800, 0x4000, 0x4400, 0x3555, - 0x4bff, 0x4c00, 0x4c40, 0xce00, 0xce80] # no 0xce40: exp(-25) is an exact tie to zero + 0x4bff, 0x4c00, 0x4c40, 0xce00, 0xce40, 0xce80] # Binary16 rounding of the nine inline float encodings, in encoding order. INLINE_F16 = { 240: 0x3800, 241: 0xb800, 242: 0x3c00, 243: 0xbc00, 244: 0x4000, @@ -72,6 +74,8 @@ def binary16(op, a, b): return M.half_op('add', a, b ^ 0x8000) if op == 'subrev': return M.half_op('add', b, a ^ 0x8000) + if op == 'exp' and a in exp_f16_midpoints(): + return exp_f16_midpoints()[a] return M.half_op(op, a, b) @@ -84,10 +88,7 @@ def modified(bits, abs_mask, neg, index): def same_binary16(got, want): - """Bit equality of two binary16 values (16 bits each). Any NaN matches any NaN. - - Exact comparator kept for tests/native_fma_f16_check.py; the unary results use - same_half / f16_packed_model.same_half_result with their one-ULP tolerance.""" + """Bit equality of two binary16 values (16 bits each). Any NaN matches any NaN.""" if got >> 16 or want >> 16: return False if M.is_nan(got) or M.is_nan(want): @@ -95,11 +96,18 @@ def same_binary16(got, want): return got == want -def same_half(got, want, op=None): - """Check the preserved HI_A and compare the low half using the operation's tolerance.""" +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 M.same_half_result(got & 0xffff, want & 0xffff, op) + return same_alu_result(got & 0xffff, want & 0xffff, + case.op if case else None, case.alternate if case else None) def _u32(value): @@ -142,6 +150,13 @@ def f32_half(op, a, b): 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, - self.op)) + fixture.same_alu_result((got & self.mask) >> self.shift, + (self.want & self.mask) >> self.shift, self.op, self.alternate)) def cases(): @@ -107,8 +107,11 @@ def cases(): 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)) - for op in ('rsq', 'log'): - items.append(Case(op, 0x44000000, 0, WORD_1, PAD, WORD_0 | 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 @@ -148,6 +151,7 @@ def refusals(): (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) @@ -239,7 +243,7 @@ def run_gpu(gpu, sdk, items, code): elif shift is not None: mask = 0xffff << shift matches = (got & ~mask == want & ~mask and - model.same_half_result((got & mask) >> shift, (want & mask) >> shift)) + fixture.same_binary16((got & mask) >> shift, (want & mask) >> shift)) else: matches = got == want assert matches, (index, slot, hex(got), hex(want))