From 16632cf5304b5a8b2e314c25ab29d5a8543ecc1d Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:51:21 +0000 Subject: [PATCH] feat(metal): compute Metal's precise math and division in double precision --- .../stela-driver-gpu/src/compiler/air_math.c | 57 +- .../src/compiler/air_metadata.c | 4 +- .../src/compiler/air_precise.c | 647 ++++++++++++++++++ .../src/compiler/air_precise.h | 29 + .../src/compiler/air_to_nir.c | 17 +- .../stela-driver-gpu/src/compiler/meson.build | 11 +- .../src/compiler/tests/air_math.c | 24 +- .../src/compiler/tests/air_precise.c | 245 +++++++ .../src/compiler/tests/air_stage.c | 2 - .../src/compiler/tests/air_to_nir.c | 10 - xtask/src/gpu/nvk.rs | 1 + 11 files changed, 1010 insertions(+), 37 deletions(-) create mode 100644 crates/stela-driver-gpu/src/compiler/air_precise.c create mode 100644 crates/stela-driver-gpu/src/compiler/air_precise.h create mode 100644 crates/stela-driver-gpu/src/compiler/tests/air_precise.c diff --git a/crates/stela-driver-gpu/src/compiler/air_math.c b/crates/stela-driver-gpu/src/compiler/air_math.c index 77053be923..d16f61c1b8 100644 --- a/crates/stela-driver-gpu/src/compiler/air_math.c +++ b/crates/stela-driver-gpu/src/compiler/air_math.c @@ -18,11 +18,12 @@ * guessed. * * NIR computes approximate functions at the accuracy Vulkan requires, which - * matches Metal's fast variants, not its precise ones. Single-precision - * approximate functions therefore lower only as AIR's "fast_" variants or as - * LLVM intrinsics that allow approximation (afn); precise ones are refused. - * Half-precision approximate functions evaluate in single precision. */ + * matches Metal's fast variants, not its precise ones. AIR's "fast_" variants + * and LLVM intrinsics that allow approximation (afn) lower to NIR's; the + * others to air_precise.c. Half-precision approximate functions evaluate in + * single precision. */ #include "air_math.h" +#include "air_precise.h" #include "compiler/nir/nir_builtin_builder.h" #include "compiler/nir/nir_format_convert.h" #include @@ -309,6 +310,38 @@ floating_value(nir_builder *b, enum operation operation, nir_def **s, nir_def ** } } +/* An approximate function at Metal's precise accuracy. */ +static nir_def * +precise_value(nir_builder *b, enum operation operation, unsigned count, nir_def **s, nir_def **second) +{ + static stela_air_precise_function *const functions[] = { + [LOG2] = stela_air_precise_log2, [EXP2] = stela_air_precise_exp2, + [SQRT] = stela_air_precise_sqrt, [RSQRT] = stela_air_precise_rsqrt, + [COS] = stela_air_precise_cos, [SIN] = stela_air_precise_sin, + [TAN] = stela_air_precise_tan, [ACOS] = stela_air_precise_acos, + [ASIN] = stela_air_precise_asin, [ATAN] = stela_air_precise_atan, + [COSH] = stela_air_precise_cosh, [SINH] = stela_air_precise_sinh, + [TANH] = stela_air_precise_tanh, [ACOSH] = stela_air_precise_acosh, + [ASINH] = stela_air_precise_asinh, [ATANH] = stela_air_precise_atanh, + [EXP] = stela_air_precise_exp, [EXP10] = stela_air_precise_exp10, + [LOG] = stela_air_precise_log, [LOG10] = stela_air_precise_log10, + [COSPI] = stela_air_precise_cospi, [SINPI] = stela_air_precise_sinpi, + [TANPI] = stela_air_precise_tanpi, [POW] = stela_air_precise_pow, + [POWR] = stela_air_precise_powr, [ATAN2] = stela_air_precise_atan2, + [FMOD] = stela_air_precise_fmod, + }; + switch (operation) { + case NORMALIZE: return stela_air_precise_normalize(b, s[0]); + case LENGTH: return stela_air_precise_length(b, s[0], NULL); + case DISTANCE: return stela_air_precise_length(b, s[0], s[1]); + case SINCOS: + *second = stela_air_precise(b, stela_air_precise_cos, s[0], NULL); + return stela_air_precise(b, stela_air_precise_sin, s[0], NULL); + default: + return stela_air_precise(b, functions[operation], s[0], count > 1 ? s[1] : NULL); + } +} + /* x's bits counted from the least significant end of its lanes' width. */ static nir_def * reverse_bits(nir_builder *b, nir_def *x) @@ -548,26 +581,24 @@ lower(const struct stela_air_call_context *c, LLVMValueRef call, LLVMValueRef ca *result = integer_value(b, operation, sign == SIGNED, s); return STELA_AIR_CALL_LOWERED; } - unsigned lanes; - LLVMTypeRef scalar = stela_air_call_element(operand, &lanes); if (!stela_air_call_floating(operand) || type != result_type(operand, operation)) return stela_air_call_fail(c, STELA_AIR_TYPE, "unsupported floating-point function types"), STELA_AIR_CALL_FAILED; if ((operation == DFDX || operation == DFDY || operation == FWIDTH) && !c->fragment) return stela_air_call_fail(c, STELA_AIR_INSTRUCTION, "derivatives exist only in fragment functions"), STELA_AIR_CALL_FAILED; - if (approximate(operation) && !fast && LLVMGetTypeKind(scalar) == LLVMFloatTypeKind) - return stela_air_call_fail(c, STELA_AIR_INSTRUCTION, "precise single-precision function accuracy is unqualified"), - STELA_AIR_CALL_FAILED; if (!c->fp_environment(c->translator) || !operands(c, call, operation, count, s)) return STELA_AIR_CALL_FAILED; nir_def *second = NULL; - if (s[0]->bit_size == 16 && approximate(operation)) { + bool narrow = s[0]->bit_size == 16 && approximate(operation); + if (narrow) { for (unsigned i = 0; i < count; i++) s[i] = s[i] ? nir_f2f32(b, s[i]) : NULL; - *result = nir_f2f16(b, floating_value(b, operation, s, &second)); + } + *result = approximate(operation) && !fast ? precise_value(b, operation, count, s, &second) : + floating_value(b, operation, s, &second); + if (narrow) { + *result = nir_f2f16(b, *result); second = second ? nir_f2f16(b, second) : NULL; - } else { - *result = floating_value(b, operation, s, &second); } if (second && !c->store(c->translator, LLVMGetOperand(call, count - 1), NULL, second)) return STELA_AIR_CALL_FAILED; diff --git a/crates/stela-driver-gpu/src/compiler/air_metadata.c b/crates/stela-driver-gpu/src/compiler/air_metadata.c index 643ef2df1d..a213bc381e 100644 --- a/crates/stela-driver-gpu/src/compiler/air_metadata.c +++ b/crates/stela-driver-gpu/src/compiler/air_metadata.c @@ -385,11 +385,13 @@ stela_air_metadata_validate(struct stela_air_metadata *t) if (!stela_air_md_node(t, nodes[i], fields, &fields_count) || fields_count != 1 || !(stela_air_md_string(fields[0], "air.compile.denorms_disable") || stela_air_md_string(fields[0], "air.compile.fast_math_enable") || + stela_air_md_string(fields[0], "air.compile.fast_math_disable") || stela_air_md_string(fields[0], "air.compile.framebuffer_fetch_enable") || stela_air_md_string(fields[0], "air.compile.framebuffer_fetch_disable"))) return fail(t, STELA_AIR_METADATA, "unsupported AIR compile option"); unsigned bit = stela_air_md_string(fields[0], "air.compile.denorms_disable") ? 1 : - stela_air_md_string(fields[0], "air.compile.fast_math_enable") ? 2 : 4; + stela_air_md_string(fields[0], "air.compile.fast_math_enable") || + stela_air_md_string(fields[0], "air.compile.fast_math_disable") ? 2 : 4; if (seen & bit) return fail(t, STELA_AIR_METADATA, "duplicate/conflicting AIR compile option"); seen |= bit; diff --git a/crates/stela-driver-gpu/src/compiler/air_precise.c b/crates/stela-driver-gpu/src/compiler/air_precise.c new file mode 100644 index 0000000000..28a687a0b9 --- /dev/null +++ b/crates/stela-driver-gpu/src/compiler/air_precise.c @@ -0,0 +1,647 @@ +/* SPDX-License-Identifier: MIT */ +/* Metal's precise single-precision functions and division, which NIR's Vulkan + * accuracy does not reach. Every NVIDIA GPU Stela drives computes doubles in + * every stage, and Metal's accuracy leaves them ample room, so each function + * evaluates in double precision and rounds once: within about half a unit in + * the last place, against the 3 to 16 Metal allows, and correctly rounded for + * division, as Metal asks. Doubles have a fraction of single precision's + * throughput, which only functions that asked for accuracy pay. + * + * Series are Taylor series, which need no fitted coefficients, taken one term + * past what their reduced ranges need. Reciprocals and inverse square roots + * refine the hardware's single-precision estimates twice, each step doubling + * their 21 good bits, rather than use NIR's double lowerings. Large angles + * reduce by Payne and Hanek's method, multiplying the significand by the bits + * of 2/pi that matter at its exponent. */ +#include "air_precise.h" +#include "compiler/nir/nir_builtin_builder.h" +#include "util/macros.h" +#include + +/* Below this magnitude, odd functions round to their argument. */ +#define TINY 0x1p-12f +/* Above this magnitude, x + sqrt(x * x +- 1) rounds to 2x. */ +#define LARGE 0x1p13f + +/* M_PI_2 and M_LN2 less the values they round from, for Cody and Waite's + * reductions, in which FMA keeps every bit. */ +#define PI_2_REST 6.123233995736766e-17 +#define LN2_REST 2.3190468138462996e-17 + +/* The fractional bits of 2/pi, enough for any float's exponent. */ +static const uint32_t two_over_pi[] = { + 0xa2f9836e, 0x4e441529, 0xfc2757d1, 0xf534ddc0, 0xdb629599, 0x3c439041, 0xfe5163ab, +}; + +static nir_def * +imm(nir_builder *b, double value) +{ + return nir_imm_double(b, value); +} + +static nir_def * +high(nir_builder *b, nir_def *x) +{ + return nir_unpack_64_2x32_split_y(b, x); +} + +/* x with its high word replaced. */ +static nir_def * +with_high(nir_builder *b, nir_def *x, nir_def *word) +{ + return nir_pack_64_2x32_split(b, nir_unpack_64_2x32_split_x(b, x), word); +} + +/* 2^k, for k in a double's normal range. */ +static nir_def * +power(nir_builder *b, nir_def *k) +{ + return nir_pack_64_2x32_split(b, nir_imm_int(b, 0), nir_ishl_imm(b, nir_iadd_imm(b, k, 1023), 20)); +} + +/* A nonzero finite double's binary exponent. */ +static nir_def * +exponent(nir_builder *b, nir_def *x) +{ + return nir_iadd_imm(b, nir_iand_imm(b, nir_ushr_imm(b, high(b, x), 20), 0x7ff), -1023); +} + +/* c[0] + c[1] * x + ... */ +static nir_def * +series(nir_builder *b, nir_def *x, const double *c, unsigned count) +{ + nir_def *sum = imm(b, c[count - 1]); + for (unsigned i = count - 1; i-- > 0;) + sum = nir_ffma(b, sum, x, imm(b, c[i])); + return sum; +} + +static nir_def * +reciprocal(nir_builder *b, nir_def *x) +{ + nir_def *k = exponent(b, x); + nir_def *m = with_high(b, x, nir_isub(b, high(b, x), nir_ishl_imm(b, k, 20))); + nir_def *y = nir_f2f64(b, nir_frcp(b, nir_f2f32(b, m))); + for (unsigned i = 0; i < 2; i++) + y = nir_fadd(b, y, nir_fmul(b, y, nir_ffma(b, nir_fneg(b, m), y, imm(b, 1.0)))); + return nir_fmul(b, y, power(b, nir_ineg(b, k))); +} + +/* 1 / sqrt(x) of a positive finite double. */ +static nir_def * +inverse_root(nir_builder *b, nir_def *x) +{ + nir_def *k = nir_ishr_imm(b, exponent(b, x), 1); + nir_def *m = with_high(b, x, nir_isub(b, high(b, x), nir_ishl_imm(b, k, 21))); + nir_def *half = nir_fmul_imm(b, m, 0.5); + nir_def *y = nir_f2f64(b, nir_frsq(b, nir_f2f32(b, m))); + for (unsigned i = 0; i < 2; i++) + y = nir_fmul(b, y, nir_fsub(b, imm(b, 1.5), nir_fmul(b, nir_fmul(b, half, y), y))); + return nir_fmul(b, y, power(b, nir_ineg(b, k))); +} + +/* sqrt(x) of a nonnegative finite double. */ +static nir_def * +root(nir_builder *b, nir_def *x) +{ + return nir_bcsel(b, nir_feq(b, x, imm(b, 0.0)), x, nir_fmul(b, x, inverse_root(b, x))); +} + +/* Whether a float is negative, zeros and NaNs by their sign. */ +static nir_def * +sign_bit(nir_builder *b, nir_def *x) +{ + return nir_ilt_imm(b, x, 0); +} + +static nir_def * +negate_if(nir_builder *b, nir_def *condition, nir_def *x) +{ + return nir_bcsel(b, condition, nir_fneg(b, x), x); +} + +static nir_def * +unless_nan(nir_builder *b, nir_def *x, nir_def *value) +{ + return nir_bcsel(b, nir_fneu(b, x, x), x, value); +} + +static nir_def * +infinite(nir_builder *b, nir_def *x) +{ + return nir_feq(b, nir_fabs(b, x), nir_imm_float(b, INFINITY)); +} + +static nir_def * +positive_finite(nir_builder *b, nir_def *x) +{ + return nir_iand(b, nir_flt(b, nir_imm_float(b, 0.0f), x), nir_inot(b, infinite(b, x))); +} + +static nir_def * +not_a_number(nir_builder *b) +{ + return nir_imm_float(b, NAN); +} + +/* sin and cos of r + quadrant * pi / 2, for |r| <= pi / 4. */ +static void +trigonometric(nir_builder *b, nir_def *r, nir_def *quadrant, nir_def **sine, nir_def **cosine) +{ + static const double odd[] = {-1.0 / 6, 1.0 / 120, -1.0 / 5040, 1.0 / 362880, -1.0 / 39916800}; + static const double even[] = {-0.5, 1.0 / 24, -1.0 / 720, + 1.0 / 40320, -1.0 / 3628800, 1.0 / 479001600}; + nir_def *z = nir_fmul(b, r, r); + nir_def *s = nir_fmul(b, r, nir_fadd_imm(b, nir_fmul(b, z, series(b, z, odd, ARRAY_SIZE(odd))), 1.0)); + nir_def *c = nir_fadd_imm(b, nir_fmul(b, z, series(b, z, even, ARRAY_SIZE(even))), 1.0); + nir_def *swap = nir_i2b(b, nir_iand_imm(b, quadrant, 1)); + *sine = negate_if(b, nir_i2b(b, nir_iand_imm(b, quadrant, 2)), nir_bcsel(b, swap, c, s)); + *cosine = negate_if(b, nir_i2b(b, nir_iand_imm(b, nir_iadd_imm(b, quadrant, 1), 2)), + nir_bcsel(b, swap, s, c)); +} + +/* The table's words from `index` plus `word`, for an index of at most 3. */ +static nir_def * +table_word(nir_builder *b, nir_def *index, unsigned word) +{ + nir_def *value = nir_imm_int(b, two_over_pi[word]); + for (unsigned i = 1; i < 4; i++) + value = nir_bcsel(b, nir_uge_imm(b, index, i), nir_imm_int(b, two_over_pi[word + i]), value); + return value; +} + +/* A float's magnitude, 2^25 or above, as r + quadrant * pi / 2. Its significand + * m is an integer of unit 2^(e - 150), so bits of 2/pi of weight above + * 2^(151 - e) multiply it to multiples of 4, which turn nothing. The next 96 + * bits give the quadrant and 62 fractional bits. */ +static void +reduce_far(nir_builder *b, nir_def *m, nir_def *e, nir_def **r, nir_def **quadrant) +{ + nir_def *offset = nir_iadd_imm(b, e, -152); + nir_def *index = nir_ushr_imm(b, offset, 5), *shift = nir_iand_imm(b, offset, 31); + nir_def *words[3]; + for (unsigned i = 0; i < 3; i++) { + nir_def *next = nir_ushr_imm(b, table_word(b, index, i + 1), 1); + words[i] = nir_ior(b, nir_ishl(b, table_word(b, index, i), shift), + nir_ushr(b, next, nir_isub_imm(b, 31, shift))); + } + nir_def *turns = nir_iadd(b, nir_umul_2x32_64(b, m, words[1]), + nir_u2u64(b, nir_umul_high(b, m, words[2]))); + turns = nir_iadd(b, turns, nir_pack_64_2x32_split(b, nir_imm_int(b, 0), nir_imul(b, m, words[0]))); + /* Round to the nearest quadrant. */ + turns = nir_iadd_imm(b, turns, 1ull << 61); + nir_def *top = high(b, turns); + *quadrant = nir_ushr_imm(b, top, 30); + nir_def *rest = nir_iadd_imm(b, nir_iand_imm(b, top, 0x3fffffff), -(1 << 29)); + nir_def *fraction = nir_fadd(b, nir_fmul_imm(b, nir_i2f64(b, rest), 0x1p32), + nir_u2f64(b, nir_unpack_64_2x32_split_x(b, turns))); + *r = nir_fmul_imm(b, fraction, M_PI_2 * 0x1p-62); +} + +/* A finite x as r + quadrant * pi / 2, for |r| <= pi / 4. */ +static void +reduce(nir_builder *b, nir_def *x, nir_def **r, nir_def **quadrant) +{ + nir_def *magnitude = nir_f2f64(b, nir_fabs(b, x)); + nir_def *k = nir_f2i32(b, nir_fadd_imm(b, nir_fmul_imm(b, magnitude, M_2_PI), 0.5)); + nir_def *whole = nir_fneg(b, nir_i2f64(b, k)); + nir_def *near = nir_ffma(b, whole, imm(b, M_PI_2), magnitude); + near = nir_ffma(b, whole, imm(b, PI_2_REST), near); + + nir_def *e = nir_iand_imm(b, nir_ushr_imm(b, x, 23), 0xff); + nir_def *m = nir_ior_imm(b, nir_iand_imm(b, x, 0x7fffff), 0x800000); + nir_def *far, *turn; + reduce_far(b, m, e, &far, &turn); + + nir_def *distant = nir_uge_imm(b, e, 152); + nir_def *negative = sign_bit(b, x); + *r = negate_if(b, negative, nir_bcsel(b, distant, far, near)); + k = nir_bcsel(b, distant, turn, k); + *quadrant = nir_bcsel(b, negative, nir_ineg(b, k), k); +} + +/* A finite x, a multiple of pi, as r + quadrant * pi / 2 with |r| <= pi / 4; + * whole quarters of x stay exact. */ +static void +reduce_turns(nir_builder *b, nir_def *x, nir_def **r, nir_def **quadrant) +{ + nir_def *half = nir_fmul_imm(b, nir_f2f64(b, nir_fabs(b, x)), 0.5); + nir_def *rest = nir_fsub(b, half, nir_ffloor(b, half)); + nir_def *k = nir_f2i32(b, nir_fadd_imm(b, nir_fmul_imm(b, rest, 4.0), 0.5)); + nir_def *turn = nir_fsub(b, nir_fmul_imm(b, rest, 2.0), nir_fmul_imm(b, nir_i2f64(b, k), 0.5)); + nir_def *negative = sign_bit(b, x); + *r = negate_if(b, negative, nir_fmul_imm(b, turn, M_PI)); + *quadrant = nir_bcsel(b, negative, nir_ineg(b, k), k); +} + +static nir_def * +finite_or_nan(nir_builder *b, nir_def *x, nir_def *value) +{ + return nir_bcsel(b, nir_ior(b, infinite(b, x), nir_fneu(b, x, x)), not_a_number(b), + nir_f2f32(b, value)); +} + +nir_def * +stela_air_precise_sin(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *r, *quadrant, *sine, *cosine; + reduce(b, x, &r, &quadrant); + trigonometric(b, r, quadrant, &sine, &cosine); + return finite_or_nan(b, x, sine); +} + +nir_def * +stela_air_precise_cos(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *r, *quadrant, *sine, *cosine; + reduce(b, x, &r, &quadrant); + trigonometric(b, r, quadrant, &sine, &cosine); + return finite_or_nan(b, x, cosine); +} + +/* sine / cosine, infinite with sine's sign where cosine is exactly zero. */ +static nir_def * +tangent(nir_builder *b, nir_def *r, nir_def *quadrant) +{ + nir_def *sine, *cosine; + trigonometric(b, r, quadrant, &sine, &cosine); + return nir_bcsel(b, nir_feq(b, cosine, imm(b, 0.0)), + nir_fmul_imm(b, sine, INFINITY), + nir_fmul(b, sine, reciprocal(b, cosine))); +} + +nir_def * +stela_air_precise_tan(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *r, *quadrant; + reduce(b, x, &r, &quadrant); + return finite_or_nan(b, x, tangent(b, r, quadrant)); +} + +nir_def * +stela_air_precise_sinpi(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *r, *quadrant, *sine, *cosine; + reduce_turns(b, x, &r, &quadrant); + trigonometric(b, r, quadrant, &sine, &cosine); + return finite_or_nan(b, x, sine); +} + +nir_def * +stela_air_precise_cospi(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *r, *quadrant, *sine, *cosine; + reduce_turns(b, x, &r, &quadrant); + trigonometric(b, r, quadrant, &sine, &cosine); + return finite_or_nan(b, x, cosine); +} + +nir_def * +stela_air_precise_tanpi(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *r, *quadrant; + reduce_turns(b, x, &r, &quadrant); + return finite_or_nan(b, x, tangent(b, r, quadrant)); +} + +/* e^x, of a non-NaN double. Beyond +-200 a float's result stops changing. */ +static nir_def * +exponential(nir_builder *b, nir_def *x) +{ + static const double c[] = {1.0, 1.0, 1.0 / 2, 1.0 / 6, + 1.0 / 24, 1.0 / 120, 1.0 / 720, 1.0 / 5040, + 1.0 / 40320, 1.0 / 362880, 1.0 / 3628800, 1.0 / 39916800}; + x = nir_fmax(b, nir_fmin(b, x, imm(b, 200.0)), imm(b, -200.0)); + nir_def *half = nir_bcsel(b, nir_flt(b, x, imm(b, 0.0)), imm(b, -0.5), imm(b, 0.5)); + nir_def *k = nir_f2i32(b, nir_fadd(b, nir_fmul_imm(b, x, 1.0 / M_LN2), half)); + nir_def *whole = nir_fneg(b, nir_i2f64(b, k)); + nir_def *r = nir_ffma(b, whole, imm(b, M_LN2), x); + r = nir_ffma(b, whole, imm(b, LN2_REST), r); + return nir_fmul(b, series(b, r, c, ARRAY_SIZE(c)), power(b, k)); +} + +/* The natural logarithm of a positive finite double. */ +static nir_def * +logarithm(nir_builder *b, nir_def *x) +{ + static const double c[] = {1.0, 1.0 / 3, 1.0 / 5, 1.0 / 7, 1.0 / 9, 1.0 / 11, 1.0 / 13, 1.0 / 15}; + /* m is in [sqrt(1/2), sqrt(2)). */ + nir_def *top = nir_iadd_imm(b, high(b, x), 0x3ff00000 - 0x3fe6a09e); + nir_def *k = nir_iadd_imm(b, nir_ushr_imm(b, top, 20), -1023); + nir_def *m = with_high(b, x, nir_iadd_imm(b, nir_iand_imm(b, top, 0xfffff), 0x3fe6a09e)); + nir_def *s = nir_fmul(b, nir_fadd_imm(b, m, -1.0), reciprocal(b, nir_fadd_imm(b, m, 1.0))); + nir_def *z = nir_fmul(b, s, s); + return nir_fadd(b, nir_fmul_imm(b, nir_i2f64(b, k), M_LN2), + nir_fmul(b, nir_fmul_imm(b, s, 2.0), series(b, z, c, ARRAY_SIZE(c)))); +} + +/* A float's logarithm, in units of `unit` natural ones. */ +static nir_def * +logarithm_of(nir_builder *b, nir_def *x, double unit) +{ + nir_def *value = nir_f2f32(b, nir_fmul_imm(b, logarithm(b, nir_f2f64(b, x)), 1.0 / unit)); + return nir_bcsel(b, positive_finite(b, x), value, + nir_bcsel(b, nir_feq_imm(b, x, 0.0), nir_imm_float(b, -INFINITY), + nir_bcsel(b, nir_flt_imm(b, x, 0.0), not_a_number(b), x))); +} + +nir_def * +stela_air_precise_exp(nir_builder *b, nir_def *x, nir_def *y) +{ + return unless_nan(b, x, nir_f2f32(b, exponential(b, nir_f2f64(b, x)))); +} + +nir_def * +stela_air_precise_exp2(nir_builder *b, nir_def *x, nir_def *y) +{ + return unless_nan(b, x, nir_f2f32(b, exponential(b, nir_fmul_imm(b, nir_f2f64(b, x), M_LN2)))); +} + +nir_def * +stela_air_precise_exp10(nir_builder *b, nir_def *x, nir_def *y) +{ + return unless_nan(b, x, nir_f2f32(b, exponential(b, nir_fmul_imm(b, nir_f2f64(b, x), M_LN10)))); +} + +nir_def * +stela_air_precise_log(nir_builder *b, nir_def *x, nir_def *y) +{ + return logarithm_of(b, x, 1.0); +} + +nir_def * +stela_air_precise_log2(nir_builder *b, nir_def *x, nir_def *y) +{ + return logarithm_of(b, x, M_LN2); +} + +nir_def * +stela_air_precise_log10(nir_builder *b, nir_def *x, nir_def *y) +{ + return logarithm_of(b, x, M_LN10); +} + +nir_def * +stela_air_precise_pow(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *magnitude = nir_fabs(b, x), *reach = nir_fabs(b, y); + nir_def *one = nir_imm_float(b, 1.0f), *zero = nir_imm_float(b, 0.0f); + nir_def *infinity = nir_imm_float(b, INFINITY); + nir_def *whole = nir_feq(b, y, nir_ftrunc(b, y)); + nir_def *odd = nir_iand(b, nir_iand(b, whole, nir_flt_imm(b, reach, 0x1p24f)), + nir_i2b(b, nir_iand_imm(b, nir_f2i32(b, y), 1))); + nir_def *flips = nir_iand(b, odd, sign_bit(b, x)); + nir_def *inverse = sign_bit(b, y); + nir_def *scaled = nir_fmul(b, logarithm(b, nir_f2f64(b, magnitude)), nir_f2f64(b, y)); + + nir_def *value = negate_if(b, flips, nir_f2f32(b, exponential(b, scaled))); + value = nir_bcsel(b, nir_iand(b, nir_flt_imm(b, x, 0.0), nir_inot(b, whole)), not_a_number(b), value); + /* x past one to an infinite y runs away, or to zero. */ + nir_def *beyond = nir_bcsel(b, nir_feq(b, magnitude, one), one, + nir_bcsel(b, nir_ieq(b, nir_flt(b, magnitude, one), inverse), infinity, zero)); + value = nir_bcsel(b, infinite(b, y), beyond, value); + value = nir_bcsel(b, infinite(b, x), negate_if(b, flips, nir_bcsel(b, inverse, zero, infinity)), value); + value = nir_bcsel(b, nir_feq_imm(b, x, 0.0), negate_if(b, flips, nir_bcsel(b, inverse, infinity, zero)), value); + value = unless_nan(b, x, unless_nan(b, y, value)); + return nir_bcsel(b, nir_ior(b, nir_feq_imm(b, y, 0.0), nir_feq(b, x, one)), one, value); +} + +nir_def * +stela_air_precise_powr(nir_builder *b, nir_def *x, nir_def *y) +{ + return nir_bcsel(b, nir_flt_imm(b, x, 0.0), not_a_number(b), stela_air_precise_pow(b, x, y)); +} + +/* atan(y / x) of positive finite doubles. */ +static nir_def * +angle(nir_builder *b, nir_def *y, nir_def *x) +{ + static const double c[] = {1.0, -1.0 / 3, 1.0 / 5, -1.0 / 7, 1.0 / 9, + -1.0 / 11, 1.0 / 13, -1.0 / 15, 1.0 / 17, -1.0 / 19, + 1.0 / 21, -1.0 / 23, 1.0 / 25}; + nir_def *steep = nir_flt(b, x, y); + nir_def *t = nir_fmul(b, nir_bcsel(b, steep, x, y), reciprocal(b, nir_bcsel(b, steep, y, x))); + /* tan(pi / 8), which leaves atan(t) a pi / 4 from a shorter series. */ + nir_def *wide = nir_flt(b, imm(b, 0.41421356237309503), t); + nir_def *r = nir_bcsel(b, wide, + nir_fmul(b, nir_fadd_imm(b, t, -1.0), reciprocal(b, nir_fadd_imm(b, t, 1.0))), t); + nir_def *value = nir_fmul(b, r, series(b, nir_fmul(b, r, r), c, ARRAY_SIZE(c))); + value = nir_bcsel(b, wide, nir_fadd_imm(b, value, M_PI_4), value); + return nir_bcsel(b, steep, nir_fsub(b, imm(b, M_PI_2), value), value); +} + +/* atan2(y, x) of doubles that are not NaN, as C's libraries give it. */ +static nir_def * +arctangent(nir_builder *b, nir_def *y, nir_def *x) +{ + nir_def *rise = nir_fabs(b, y), *run = nir_fabs(b, x), *endless = imm(b, INFINITY); + nir_def *vertical = nir_feq(b, rise, endless), *level = nir_feq(b, run, endless); + nir_def *value = angle(b, rise, run); + value = nir_bcsel(b, nir_ior(b, vertical, nir_feq(b, run, imm(b, 0.0))), imm(b, M_PI_2), value); + value = nir_bcsel(b, nir_ior(b, level, nir_feq(b, rise, imm(b, 0.0))), imm(b, 0.0), value); + value = nir_bcsel(b, nir_iand(b, vertical, level), imm(b, M_PI_4), value); + value = nir_bcsel(b, nir_ilt_imm(b, high(b, x), 0), nir_fsub(b, imm(b, M_PI), value), value); + return negate_if(b, nir_ilt_imm(b, high(b, y), 0), value); +} + +nir_def * +stela_air_precise_atan2(nir_builder *b, nir_def *y, nir_def *x) +{ + return unless_nan(b, x, unless_nan(b, y, nir_f2f32(b, arctangent(b, nir_f2f64(b, y), nir_f2f64(b, x))))); +} + +nir_def * +stela_air_precise_atan(nir_builder *b, nir_def *x, nir_def *y) +{ + return stela_air_precise_atan2(b, x, nir_imm_float(b, 1.0f)); +} + +/* sqrt(1 - x * x) of a float within [-1, 1]. */ +static nir_def * +cofunction(nir_builder *b, nir_def *x) +{ + nir_def *wide = nir_f2f64(b, x); + return root(b, nir_fmul(b, nir_fsub(b, imm(b, 1.0), wide), nir_fadd_imm(b, wide, 1.0))); +} + +nir_def * +stela_air_precise_asin(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *value = nir_f2f32(b, arctangent(b, nir_f2f64(b, x), cofunction(b, x))); + return nir_bcsel(b, nir_fgt_imm(b, nir_fabs(b, x), 1.0), not_a_number(b), unless_nan(b, x, value)); +} + +nir_def * +stela_air_precise_acos(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *value = nir_f2f32(b, arctangent(b, cofunction(b, x), nir_f2f64(b, x))); + return nir_bcsel(b, nir_fgt_imm(b, nir_fabs(b, x), 1.0), not_a_number(b), unless_nan(b, x, value)); +} + +nir_def * +stela_air_precise_sinh(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *e = exponential(b, nir_f2f64(b, nir_fabs(b, x))); + nir_def *value = nir_f2f32(b, nir_fmul_imm(b, nir_fsub(b, e, reciprocal(b, e)), 0.5)); + return unless_nan(b, x, nir_bcsel(b, nir_flt_imm(b, nir_fabs(b, x), TINY), x, + negate_if(b, sign_bit(b, x), value))); +} + +nir_def * +stela_air_precise_cosh(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *e = exponential(b, nir_f2f64(b, nir_fabs(b, x))); + return unless_nan(b, x, nir_f2f32(b, nir_fmul_imm(b, nir_fadd(b, e, reciprocal(b, e)), 0.5))); +} + +nir_def * +stela_air_precise_tanh(nir_builder *b, nir_def *x, nir_def *y) +{ + /* e^40 leaves a float's tanh at one. */ + nir_def *e = exponential(b, nir_fmin(b, nir_fmul_imm(b, nir_f2f64(b, nir_fabs(b, x)), 2.0), imm(b, 40.0))); + nir_def *value = nir_f2f32(b, nir_fmul(b, nir_fadd_imm(b, e, -1.0), reciprocal(b, nir_fadd_imm(b, e, 1.0)))); + return unless_nan(b, x, nir_bcsel(b, nir_flt_imm(b, nir_fabs(b, x), TINY), x, + negate_if(b, sign_bit(b, x), value))); +} + +nir_def * +stela_air_precise_asinh(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *magnitude = nir_fabs(b, x), *wide = nir_f2f64(b, magnitude); + nir_def *near = nir_fadd(b, wide, root(b, nir_fadd_imm(b, nir_fmul(b, wide, wide), 1.0))); + nir_def *inner = nir_bcsel(b, nir_fge_imm(b, magnitude, LARGE), nir_fmul_imm(b, wide, 2.0), near); + nir_def *value = negate_if(b, sign_bit(b, x), nir_f2f32(b, logarithm(b, inner))); + value = nir_bcsel(b, nir_flt_imm(b, magnitude, TINY), x, value); + return unless_nan(b, x, nir_bcsel(b, infinite(b, x), x, value)); +} + +nir_def * +stela_air_precise_acosh(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *wide = nir_f2f64(b, x); + nir_def *rest = nir_fmul(b, nir_fadd_imm(b, wide, -1.0), nir_fadd_imm(b, wide, 1.0)); + nir_def *near = nir_fadd(b, wide, root(b, rest)); + nir_def *inner = nir_bcsel(b, nir_fge_imm(b, x, LARGE), nir_fmul_imm(b, wide, 2.0), near); + nir_def *value = nir_f2f32(b, logarithm(b, inner)); + value = nir_bcsel(b, nir_flt_imm(b, x, 1.0), not_a_number(b), value); + return unless_nan(b, x, nir_bcsel(b, nir_feq(b, x, nir_imm_float(b, INFINITY)), x, value)); +} + +nir_def * +stela_air_precise_atanh(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *magnitude = nir_fabs(b, x), *wide = nir_f2f64(b, magnitude); + nir_def *ratio = nir_fmul(b, nir_fadd_imm(b, wide, 1.0), reciprocal(b, nir_fsub(b, imm(b, 1.0), wide))); + nir_def *value = nir_f2f32(b, nir_fmul_imm(b, logarithm(b, ratio), 0.5)); + value = nir_bcsel(b, nir_feq_imm(b, magnitude, 1.0), nir_imm_float(b, INFINITY), value); + value = nir_bcsel(b, nir_flt_imm(b, magnitude, TINY), magnitude, value); + value = negate_if(b, sign_bit(b, x), value); + return unless_nan(b, x, nir_bcsel(b, nir_fgt_imm(b, magnitude, 1.0), not_a_number(b), value)); +} + +nir_def * +stela_air_precise_sqrt(nir_builder *b, nir_def *x, nir_def *y) +{ + return nir_bcsel(b, positive_finite(b, x), nir_f2f32(b, root(b, nir_f2f64(b, x))), + nir_bcsel(b, nir_flt_imm(b, x, 0.0), not_a_number(b), x)); +} + +nir_def * +stela_air_precise_rsqrt(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *edge = nir_bcsel(b, nir_feq_imm(b, x, 0.0), + negate_if(b, sign_bit(b, x), nir_imm_float(b, INFINITY)), + nir_bcsel(b, nir_flt_imm(b, x, 0.0), not_a_number(b), + nir_bcsel(b, infinite(b, x), nir_imm_float(b, 0.0f), x))); + return nir_bcsel(b, positive_finite(b, x), nir_f2f32(b, inverse_root(b, nir_f2f64(b, x))), edge); +} + +nir_def * +stela_air_precise_divide(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *n = nir_f2f64(b, x), *d = nir_f2f64(b, y); + nir_def *inverse = reciprocal(b, d); + nir_def *q = nir_fmul(b, n, inverse); + q = nir_ffma(b, nir_ffma(b, nir_fneg(b, d), q, n), inverse, q); + nir_def *ordinary = nir_iand(b, positive_finite(b, nir_fabs(b, x)), positive_finite(b, nir_fabs(b, y))); + /* Zeros, infinities and NaNs have exact quotients. */ + return nir_bcsel(b, ordinary, nir_f2f32(b, q), nir_fdiv(b, x, y)); +} + +/* x modulo y takes off whole multiples of y scaled by 2^(23 * i), from the + * largest of the 13 steps a float's exponents can need. Each remainder spans + * 47 bits, so a double holds it exactly. */ +nir_def * +stela_air_precise_fmod(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *divisor = nir_f2f64(b, nir_fabs(b, y)), *inverse = reciprocal(b, divisor); + nir_def *rest = nir_f2f64(b, nir_fabs(b, x)); + for (int step = 12; step >= 0; step--) { + double scale = ldexp(1.0, 23 * step); + nir_def *w = nir_fmul_imm(b, divisor, scale); + nir_def *q = nir_i2f64(b, nir_f2i32(b, nir_fmul_imm(b, nir_fmul(b, rest, inverse), 1.0 / scale))); + nir_def *less = nir_ffma(b, nir_fneg(b, q), w, rest); + less = nir_bcsel(b, nir_flt(b, less, imm(b, 0.0)), nir_fadd(b, less, w), less); + less = nir_bcsel(b, nir_fge(b, less, w), nir_fsub(b, less, w), less); + rest = nir_bcsel(b, nir_fge(b, rest, w), less, rest); + } + nir_def *value = negate_if(b, sign_bit(b, x), nir_f2f32(b, rest)); + nir_def *undefined = nir_ior(b, infinite(b, x), nir_ior(b, nir_feq_imm(b, y, 0.0), nir_fneu(b, y, y))); + value = nir_bcsel(b, nir_fneu(b, x, x), x, nir_bcsel(b, undefined, not_a_number(b), value)); + return nir_bcsel(b, nir_iand(b, infinite(b, y), nir_inot(b, infinite(b, x))), x, value); +} + +nir_def * +stela_air_precise(nir_builder *b, stela_air_precise_function *function, nir_def *x, nir_def *y) +{ + uint32_t control = b->fp_math_ctrl; + b->fp_math_ctrl = nir_fp_no_fast_math; + nir_def *lanes[NIR_MAX_VEC_COMPONENTS]; + for (unsigned i = 0; i < x->num_components; i++) + lanes[i] = function(b, nir_channel(b, x, i), y ? nir_channel(b, y, i) : NULL); + b->fp_math_ctrl = control; + return nir_vec(b, lanes, x->num_components); +} + +/* x - y's squared length, or x's without y. */ +static nir_def * +squared_length(nir_builder *b, nir_def *x, nir_def *y) +{ + nir_def *sum = imm(b, 0.0); + for (unsigned i = 0; i < x->num_components; i++) { + nir_def *lane = nir_f2f64(b, nir_channel(b, x, i)); + if (y) + lane = nir_fsub(b, lane, nir_f2f64(b, nir_channel(b, y, i))); + sum = nir_ffma(b, lane, lane, sum); + } + return sum; +} + +nir_def * +stela_air_precise_length(nir_builder *b, nir_def *x, nir_def *y) +{ + uint32_t control = b->fp_math_ctrl; + b->fp_math_ctrl = nir_fp_no_fast_math; + nir_def *sum = squared_length(b, x, y); + nir_def *value = nir_bcsel(b, nir_feq(b, sum, imm(b, INFINITY)), sum, root(b, sum)); + value = nir_f2f32(b, value); + b->fp_math_ctrl = control; + return value; +} + +nir_def * +stela_air_precise_normalize(nir_builder *b, nir_def *x) +{ + uint32_t control = b->fp_math_ctrl; + b->fp_math_ctrl = nir_fp_no_fast_math; + nir_def *sum = squared_length(b, x, NULL); + nir_def *inverse = inverse_root(b, sum); + nir_def *usable = nir_iand(b, nir_flt(b, imm(b, 0.0), sum), nir_fneu(b, sum, imm(b, INFINITY))); + nir_def *lanes[NIR_MAX_VEC_COMPONENTS]; + for (unsigned i = 0; i < x->num_components; i++) { + nir_def *lane = nir_fmul(b, nir_f2f64(b, nir_channel(b, x, i)), inverse); + lanes[i] = nir_bcsel(b, usable, nir_f2f32(b, lane), not_a_number(b)); + } + b->fp_math_ctrl = control; + return nir_vec(b, lanes, x->num_components); +} diff --git a/crates/stela-driver-gpu/src/compiler/air_precise.h b/crates/stela-driver-gpu/src/compiler/air_precise.h new file mode 100644 index 0000000000..784592cadd --- /dev/null +++ b/crates/stela-driver-gpu/src/compiler/air_precise.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_AIR_PRECISE_H +#define STELA_AIR_PRECISE_H +/* Compiler implementation only: Metal's precise single-precision functions + * and division in NIR. */ +#include "compiler/nir/nir_builder.h" + +/* A function of one lane. Those of one argument leave y unused. */ +typedef nir_def *stela_air_precise_function(nir_builder *b, nir_def *x, nir_def *y); + +/* `function` of each lane of x and y, of 32 bits, y possibly NULL. */ +nir_def *stela_air_precise(nir_builder *b, stela_air_precise_function *function, nir_def *x, + nir_def *y); + +stela_air_precise_function stela_air_precise_sin, stela_air_precise_cos, stela_air_precise_tan, + stela_air_precise_sinpi, stela_air_precise_cospi, stela_air_precise_tanpi, + stela_air_precise_asin, stela_air_precise_acos, stela_air_precise_atan, + stela_air_precise_atan2, stela_air_precise_sinh, stela_air_precise_cosh, + stela_air_precise_tanh, stela_air_precise_asinh, stela_air_precise_acosh, + stela_air_precise_atanh, stela_air_precise_exp, stela_air_precise_exp2, + stela_air_precise_exp10, stela_air_precise_log, stela_air_precise_log2, + stela_air_precise_log10, stela_air_precise_pow, stela_air_precise_powr, + stela_air_precise_sqrt, stela_air_precise_rsqrt, stela_air_precise_divide, + stela_air_precise_fmod; + +/* The length of x, or of x - y, as one lane. */ +nir_def *stela_air_precise_length(nir_builder *b, nir_def *x, nir_def *y); +nir_def *stela_air_precise_normalize(nir_builder *b, nir_def *x); +#endif diff --git a/crates/stela-driver-gpu/src/compiler/air_to_nir.c b/crates/stela-driver-gpu/src/compiler/air_to_nir.c index ecfd6e1bd2..b54d5f8f1d 100644 --- a/crates/stela-driver-gpu/src/compiler/air_to_nir.c +++ b/crates/stela-driver-gpu/src/compiler/air_to_nir.c @@ -7,6 +7,7 @@ #include "air_constants.h" #include "air_math.h" #include "air_matrix.h" +#include "air_precise.h" #include "air_simd.h" #include "air_texture.h" #include "llvm-c/Analysis.h" @@ -3538,6 +3539,20 @@ freeze(struct translator *t, LLVMValueRef inst) return put_value(t, inst, nir_vec(&t->b, lanes, v->components), 0); } +/* An FDiv or FRem at Metal's precise accuracy. */ +static bool +precise_division(struct translator *t, LLVMValueRef inst, LLVMOpcode op) +{ + nir_def *a = get_value(t, LLVMGetOperand(inst, 0)), *c = get_value(t, LLVMGetOperand(inst, 1)); + if (!a || !c || !fp_environment(t)) + return false; + bool narrow = a->bit_size == 16; + stela_air_precise_function *function = op == LLVMFDiv ? stela_air_precise_divide : stela_air_precise_fmod; + nir_def *value = stela_air_precise(&t->b, function, narrow ? nir_f2f32(&t->b, a) : a, + narrow ? nir_f2f32(&t->b, c) : c); + return put_value(t, inst, narrow ? nir_f2f16(&t->b, value) : value, 0); +} + static bool instruction(struct translator *t, LLVMValueRef inst) { @@ -3752,7 +3767,7 @@ instruction(struct translator *t, LLVMValueRef inst) return fp_conversion(t, inst, op); /* NIR divides at Vulkan's 2.5 ULP, which only fast math permits. */ if ((op == LLVMFDiv || op == LLVMFRem) && LLVMGetFastMathFlags(inst) != LLVMFastMathAll) - return fail(t, STELA_AIR_INSTRUCTION, "precise/partially relaxed FP division is unqualified"); + return precise_division(t, inst, op); if (op == LLVMFAdd || op == LLVMFSub || op == LLVMFMul || op == LLVMFDiv || op == LLVMFRem || op == LLVMFCmp) { if (!fp_environment(t)) diff --git a/crates/stela-driver-gpu/src/compiler/meson.build b/crates/stela-driver-gpu/src/compiler/meson.build index 67e29faedd..84ab3c2904 100644 --- a/crates/stela-driver-gpu/src/compiler/meson.build +++ b/crates/stela-driver-gpu/src/compiler/meson.build @@ -171,7 +171,8 @@ if stela_air_llvm != '' ) stela_air = static_library( 'stela_air_to_nir', - ['air_to_nir.c', 'air_metadata.c', 'air_texture.c', 'air_call.c', 'air_math.c', 'air_simd.c', + ['air_to_nir.c', 'air_metadata.c', 'air_texture.c', 'air_call.c', 'air_math.c', + 'air_precise.c', 'air_simd.c', 'air_matrix.c', 'air_constants.c', 'air_calls.c', 'air_commands.c', 'air_log.c', 'air_stitch.c'], include_directories : [inc_include, inc_src, inc_gpu], @@ -313,6 +314,14 @@ if stela_air_llvm != '' build_rpath : fs.parent(stela_air_llvm), ) test('stela_air_math', stela_air_math_test, suite : 'stela') + stela_air_precise_test = executable( + 'stela_air_precise_test', + 'tests/air_precise.c', + include_directories : [inc_include, inc_src, inc_gpu], + dependencies : [idep_stela_air], + build_rpath : fs.parent(stela_air_llvm), + ) + test('stela_air_precise', stela_air_precise_test, suite : 'stela') stela_air_sync_test = executable( 'stela_air_sync_test', 'tests/air_sync.c', diff --git a/crates/stela-driver-gpu/src/compiler/tests/air_math.c b/crates/stela-driver-gpu/src/compiler/tests/air_math.c index 72abbb9652..2f010e5850 100644 --- a/crates/stela-driver-gpu/src/compiler/tests/air_math.c +++ b/crates/stela-driver-gpu/src/compiler/tests/air_math.c @@ -473,20 +473,11 @@ refuses_misnamed_and_misplaced_functions(void) "call i16 @air.convert.s.i32.f.f32(float 1.0)", STELA_AIR_INSTRUCTION}, {"declare float @air.convert.s.f32.f.f32(float)\n", "float", "call float @air.convert.s.f32.f.f32(float 1.0)", STELA_AIR_INSTRUCTION}, - /* NIR's accuracy is Metal's fast accuracy, not its precise one. */ - {"declare float @air.sqrt.f32(float)\n", "float", "call float @air.sqrt.f32(float 1.0)", - STELA_AIR_INSTRUCTION}, - {"declare float @llvm.sqrt.f32(float)\n", "float", "call float @llvm.sqrt.f32(float 1.0)", - STELA_AIR_INSTRUCTION}, - {"", "float", "fdiv float 1.0, 4.0", STELA_AIR_INSTRUCTION}, - {"", "float", "frem nnan float 1.0, 4.0", STELA_AIR_INSTRUCTION}, /* A function's name spells its overload. */ {"declare float @air.sqrt.f16(float)\n", "float", "call float @air.sqrt.f16(float 1.0)", STELA_AIR_INSTRUCTION}, {"declare float @air.fast_frobnicate.f32(float)\n", "float", "call float @air.fast_frobnicate.f32(float 1.0)", STELA_AIR_INSTRUCTION}, - {"declare float @air.sincos.f32(float, ptr)\n", "float", - "call float @air.sincos.f32(float 1.0, ptr null)", STELA_AIR_INSTRUCTION}, /* ldexp takes an exponent per lane. */ {"declare <2 x float> @air.ldexp.v2f32(<2 x float>, i32)\n", "<2 x float>", "call <2 x float> @air.ldexp.v2f32(<2 x float> zeroinitializer, i32 1)", STELA_AIR_TYPE}, @@ -616,6 +607,21 @@ functions_compile(void) "call <2 x i64> @air.rotate.v2i64(<2 x i64> %a, <2 x i64> %b)"}, {"declare i32 @air.pack.unorm4x8.srgb.v4f32(<4 x float>)\n", "<4 x float>", "i32", "call i32 @air.pack.unorm4x8.srgb.v4f32(<4 x float> %a)"}, + /* Precise functions and division. */ + {"declare <2 x float> @air.sin.v2f32(<2 x float>)\n", "<2 x float>", "<2 x float>", + "call <2 x float> @air.sin.v2f32(<2 x float> %a)"}, + {"declare float @air.pow.f32(float, float)\n", "float", "float", + "call float @air.pow.f32(float %a, float %b)"}, + {"declare float @air.sincos.f32(float, ptr)\n", "float", "float", + "call float @air.sincos.f32(float %a, ptr %p)"}, + {"declare <3 x float> @air.normalize.v3f32(<3 x float>)\n", "<3 x float>", "<3 x float>", + "call <3 x float> @air.normalize.v3f32(<3 x float> %a)"}, + {"declare float @llvm.sqrt.f32(float)\n", "float", "float", + "call float @llvm.sqrt.f32(float %a)"}, + {"declare half @air.tanh.f16(half)\n", "half", "half", "call half @air.tanh.f16(half %a)"}, + {"", "float", "float", "fdiv float %a, %b"}, + {"", "half", "half", "fdiv half %a, %b"}, + {"", "float", "float", "frem nnan float %a, %b"}, {"declare <4 x half> @air.unpack.snorm4x8.v4f16(i32)\n", "i32", "<4 x half>", "call <4 x half> @air.unpack.snorm4x8.v4f16(i32 %a)"}, }; diff --git a/crates/stela-driver-gpu/src/compiler/tests/air_precise.c b/crates/stela-driver-gpu/src/compiler/tests/air_precise.c new file mode 100644 index 0000000000..7d98e50496 --- /dev/null +++ b/crates/stela-driver-gpu/src/compiler/tests/air_precise.c @@ -0,0 +1,245 @@ +/* SPDX-License-Identifier: MIT */ +/* air_precise.c's accuracy: each function, folded at sampled arguments, against + * the host's double-precision library rounded once. */ +#include "../air_precise.h" +#include "util/macros.h" +#include "util/ralloc.h" +#include +#include +#include +#include +#include +#include +#ifdef NDEBUG +#error "These tests require active assertions" +#endif + +static const nir_shader_compiler_options options = {.max_unroll_iterations = 32}; + +static uint64_t state = 0x9e3779b97f4a7c15ull; + +/* xorshift64*, so failures reproduce. */ +static uint32_t +random_word(void) +{ + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + return (state * 0x2545f4914f6cdd1dull) >> 32; +} + +static float +from_bits(uint32_t bits) +{ + float value; + memcpy(&value, &bits, sizeof(value)); + return value; +} + +static uint32_t +to_bits(float value) +{ + uint32_t bits; + memcpy(&bits, &value, sizeof(bits)); + return bits; +} + +/* Values every function meets at its edges. */ +static const float edges[] = { + 0.0f, -0.0f, 1.0f, -1.0f, 0.5f, -0.5f, 2.0f, -2.0f, 3.0f, -3.0f, 1.5f, 0.25f, 10.0f, 100.0f, + 1.17549435e-38f, FLT_MAX, -FLT_MAX, FLT_EPSILON, 1.0f - FLT_EPSILON / 2, 1.0f + FLT_EPSILON, + 0x1p24f, 0x1p25f, 0x1.fffffep24f, 3.14159274f, 1.57079637f, 0.785398185f, 6.28318548f, + INFINITY, -INFINITY, NAN, +}; + +/* An argument: an edge, any float, or one of moderate size. */ +static float +sample(void) +{ + uint32_t pick = random_word() % 8; + if (pick == 0) + return edges[random_word() % ARRAY_SIZE(edges)]; + if (pick < 4) + return from_bits(random_word()); + float unit = (float)random_word() / 0x1p32f - 0.5f; + return unit * (pick < 6 ? 4.0f : 200.0f); +} + +/* The floats between a and b; NaNs match each other only. */ +static uint64_t +ulps(float a, float b) +{ + if (isnan(a) || isnan(b)) + return isnan(a) && isnan(b) ? 0 : UINT64_MAX; + int64_t x = to_bits(a), y = to_bits(b); + x = x >> 31 ? 0x80000000ll - x : x; + y = y >> 31 ? 0x80000000ll - y : y; + return x > y ? x - y : y - x; +} + +static float +evaluate(stela_air_precise_function *function, float x, float y) +{ + nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_COMPUTE, &options, "precise"); + b.constant_fold_alu = true; + nir_def *value = stela_air_precise(&b, function, nir_imm_float(&b, x), nir_imm_float(&b, y)); + assert(nir_src_is_const(nir_src_for_ssa(value))); + float result = nir_src_as_float(nir_src_for_ssa(value)); + ralloc_free(b.shader); + return result; +} + +/* pi * x's sine and cosine stop at a rounded pi, so their zeros are written out. */ +static double +host_sinpi(double x) +{ + double turn = fmod(x, 2.0); + return fmod(turn, 1.0) == 0.0 ? 0.0 : sin(M_PI * turn); +} + +static double +host_cospi(double x) +{ + double turn = fmod(x, 2.0); + return fmod(turn + 0.5, 1.0) == 0.0 ? 0.0 : cos(M_PI * turn); +} + +static double +host_tanpi(double x) +{ + return host_sinpi(x) / host_cospi(x); +} + +static double host_exp10(double x) { return pow(10.0, x); } +static double host_rsqrt(double x) { return 1.0 / sqrt(x); } +static double host_powr(double x, double y) { return x < 0.0 ? NAN : pow(x, y); } +static double host_divide(double x, double y) { return x / y; } + +static const struct { + const char *name; + stela_air_precise_function *function; + double (*one)(double); + double (*two)(double, double); +} functions[] = { + {"sin", stela_air_precise_sin, sin}, + {"cos", stela_air_precise_cos, cos}, + {"tan", stela_air_precise_tan, tan}, + {"sinpi", stela_air_precise_sinpi, host_sinpi}, + {"cospi", stela_air_precise_cospi, host_cospi}, + {"tanpi", stela_air_precise_tanpi, host_tanpi}, + {"asin", stela_air_precise_asin, asin}, + {"acos", stela_air_precise_acos, acos}, + {"atan", stela_air_precise_atan, atan}, + {"sinh", stela_air_precise_sinh, sinh}, + {"cosh", stela_air_precise_cosh, cosh}, + {"tanh", stela_air_precise_tanh, tanh}, + {"asinh", stela_air_precise_asinh, asinh}, + {"acosh", stela_air_precise_acosh, acosh}, + {"atanh", stela_air_precise_atanh, atanh}, + {"exp", stela_air_precise_exp, exp}, + {"exp2", stela_air_precise_exp2, exp2}, + {"exp10", stela_air_precise_exp10, host_exp10}, + {"log", stela_air_precise_log, log}, + {"log2", stela_air_precise_log2, log2}, + {"log10", stela_air_precise_log10, log10}, + {"sqrt", stela_air_precise_sqrt, sqrt}, + {"rsqrt", stela_air_precise_rsqrt, host_rsqrt}, + {"atan2", stela_air_precise_atan2, NULL, atan2}, + {"pow", stela_air_precise_pow, NULL, pow}, + {"powr", stela_air_precise_powr, NULL, host_powr}, + {"divide", stela_air_precise_divide, NULL, host_divide}, + {"fmod", stela_air_precise_fmod, NULL, fmod}, +}; + +/* Every function stays within a unit of the host's, which is itself within + * half of the true value; Metal allows 3 or more, and division none. */ +static void +functions_match_the_host(unsigned samples) +{ + for (unsigned i = 0; i < ARRAY_SIZE(functions); i++) { + uint64_t worst = 0; + float worst_x = 0, worst_y = 0; + for (unsigned n = 0; n < samples; n++) { + float x = sample(), y = sample(); + /* Powers near one reach further into their exponents. */ + if (functions[i].function == stela_air_precise_pow && (random_word() & 1)) + x = 0.5f + fabsf(fmodf(x, 2.0f)); + double host = functions[i].one ? functions[i].one(x) : functions[i].two(x, y); + uint64_t distance = ulps(evaluate(functions[i].function, x, y), (float)host); + if (distance > worst) { + worst = distance; + worst_x = x; + worst_y = y; + } + } + if (worst > 1) + fprintf(stderr, "%s(%a, %a): %llu units\n", functions[i].name, worst_x, worst_y, + (unsigned long long)worst); + assert(worst <= 1); + } +} + +/* Division rounds correctly, and a remainder is exact. */ +static void +division_is_exact(unsigned samples) +{ + for (unsigned n = 0; n < samples; n++) { + float x = sample(), y = sample(); + assert(ulps(evaluate(stela_air_precise_divide, x, y), x / y) == 0); + assert(ulps(evaluate(stela_air_precise_fmod, x, y), fmodf(x, y)) == 0); + } +} + +static void +quarter_turns_are_exact(void) +{ + assert(evaluate(stela_air_precise_sinpi, 1.0f, 0.0f) == 0.0f); + assert(evaluate(stela_air_precise_cospi, 0.5f, 0.0f) == 0.0f); + assert(evaluate(stela_air_precise_sinpi, 0.5f, 0.0f) == 1.0f); + assert(evaluate(stela_air_precise_cospi, 1.0f, 0.0f) == -1.0f); + assert(evaluate(stela_air_precise_tanpi, 0.25f, 0.0f) == 1.0f); + assert(evaluate(stela_air_precise_sinpi, 0x1p30f, 0.0f) == 0.0f); +} + +/* Zeros keep their signs through odd functions. */ +static void +zeros_keep_their_signs(void) +{ + stela_air_precise_function *odd[] = { + stela_air_precise_sin, stela_air_precise_tan, stela_air_precise_asin, stela_air_precise_atan, + stela_air_precise_sinh, stela_air_precise_tanh, stela_air_precise_asinh, stela_air_precise_atanh, + stela_air_precise_sqrt, + }; + for (unsigned i = 0; i < ARRAY_SIZE(odd); i++) + assert(to_bits(evaluate(odd[i], -0.0f, 0.0f)) == 0x80000000); +} + +static void +vectors_measure_without_overflow(void) +{ + nir_builder b = nir_builder_init_simple_shader(MESA_SHADER_COMPUTE, &options, "precise"); + b.constant_fold_alu = true; + const float big = 0x1p100f; + nir_def *x = nir_imm_vec3(&b, 3.0f * big, 4.0f * big, 0.0f); + nir_def *y = nir_imm_vec3(&b, 0.0f, 0.0f, 0.0f); + assert(nir_src_as_float(nir_src_for_ssa(stela_air_precise_length(&b, x, NULL))) == 5.0f * big); + assert(nir_src_as_float(nir_src_for_ssa(stela_air_precise_length(&b, x, y))) == 5.0f * big); + nir_def *unit = stela_air_precise_normalize(&b, x); + assert(nir_src_comp_as_float(nir_src_for_ssa(unit), 0) == 0.6f); + assert(nir_src_comp_as_float(nir_src_for_ssa(unit), 1) == 0.8f); + assert(nir_src_comp_as_float(nir_src_for_ssa(unit), 2) == 0.0f); + assert(isnan(nir_src_comp_as_float(nir_src_for_ssa(stela_air_precise_normalize(&b, y)), 0))); + ralloc_free(b.shader); +} + +int +main(int argc, char **argv) +{ + unsigned samples = argc > 1 ? (unsigned)atoi(argv[1]) : 2000; + functions_match_the_host(samples); + division_is_exact(samples); + quarter_turns_are_exact(); + zeros_keep_their_signs(); + vectors_measure_without_overflow(); + return 0; +} diff --git a/crates/stela-driver-gpu/src/compiler/tests/air_stage.c b/crates/stela-driver-gpu/src/compiler/tests/air_stage.c index eb35617241..21e2e2eb1b 100644 --- a/crates/stela-driver-gpu/src/compiler/tests/air_stage.c +++ b/crates/stela-driver-gpu/src/compiler/tests/air_stage.c @@ -833,8 +833,6 @@ arithmetic_and_lane_semantics(void) CHECK(divisions_seen == 1); fold(nir); uint32_t result[4] = {divisions[i].result,0,0,0}; outputs(nir, NULL, result); ralloc_free(nir); LLVMDisposeMemoryBuffer(raw); - char *precise = fragment_body("{\n %q = fdiv float 1.0, 2.0\n %out = insertelement <4 x float> zeroinitializer, float %q, i32 0\n ret <4 x float> %out\n}", ""); - refusal(precise, "test_fragment", STELA_AIR_FRAGMENT, &o, STELA_AIR_INSTRUCTION); free(precise); } const uint32_t integers[] = {16777217, UINT32_MAX, 2147483649u, 0}; const uint32_t float_bits[] = {0x4b800000, 0x4f800000, 0x4f000000, 0}; diff --git a/crates/stela-driver-gpu/src/compiler/tests/air_to_nir.c b/crates/stela-driver-gpu/src/compiler/tests/air_to_nir.c index 619337edcf..4e5cc7285c 100644 --- a/crates/stela-driver-gpu/src/compiler/tests/air_to_nir.c +++ b/crates/stela-driver-gpu/src/compiler/tests/air_to_nir.c @@ -2185,16 +2185,6 @@ floating_contracts(void) LLVMDisposeMemoryBuffer(input); free(prefix); } - const char *unsupported[] = { - "%v = fdiv float 1.0, 2.0\nret void\n", - "%v = frem float 1.0, 2.0\nret void\n", - }; - for (unsigned i = 0; i < ARRAY_SIZE(unsupported); i++) { - LLVMMemoryBufferRef input = ieee_bitcode(stela_air_test_prefix, unsupported[i]); - struct stela_air_error error; - CHECK(!translate(input, &test_nir_options, 100, &error) && error.kind == STELA_AIR_INSTRUCTION); - LLVMDisposeMemoryBuffer(input); - } LLVMMemoryBufferRef constrained = ieee_bitcode_extra(stela_air_test_prefix, "%v = call float @llvm.experimental.constrained.fadd.f32(float 1.0, float 2.0, " "metadata !\"round.tonearest\", metadata !\"fpexcept.ignore\")\nret void\n", diff --git a/xtask/src/gpu/nvk.rs b/xtask/src/gpu/nvk.rs index b3211d2114..65012c9e53 100644 --- a/xtask/src/gpu/nvk.rs +++ b/xtask/src/gpu/nvk.rs @@ -89,6 +89,7 @@ const AIR: [&str; 15] = [ "air_constants", "air_log", "air_math", + "air_precise", "air_matrix", "air_metadata", "air_simd",