diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 5e373200d6..21e571e152 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -554,9 +554,7 @@ impl Lw { }), "v_sin_f32" | "v_cos_f32" => { let x = fs!(0); - let k = self.fc(6.283_185_3); - let x = self.fmul(x, k); - fr!(self.un(if name == "v_sin_f32" { op::SIN } else { op::COS }, x)) + fr!(self.trig_turns(x, name == "v_sin_f32")) } "v_fract_f32" => { let x = fs!(0); diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index 04eab931d0..d877485834 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -552,10 +552,17 @@ impl Lw { "v_exp_f16" => f1!(|s: &mut Self, x| s.un(op::EXP, x)), "v_sin_f16" | "v_cos_f16" => { let x = fh(self, 0); - let k = self.fc(6.283_185_3); - let x = self.fmul(x, k); - let e = self.un(if name == "v_sin_f16" { op::SIN } else { op::COS }, x); - fr(self, e) + let e = self.trig_turns(x, name == "v_sin_f16"); + let h = fr(self, e); + if m.clamp { + h + } else { + // ±Inf gives the f16 NaN 0xFE00, as the HLSL path selects it + let x = hb(self, 0); + let mag = self.andc(x, 0x7FFF); + let inf = self.cmpc(Pred::Eq, mag, 0x7C00); + self.selc(inf, 0xFE00, h) + } } "v_fract_f16" => f1!(|s: &mut Self, x| s.fract_f(x)), "v_floor_f16" => f1!(|s: &mut Self, x| s.un(op::ROUND_NI, x)), diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index ddc09c0f35..4775468bd5 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -78,6 +78,38 @@ impl Lw { let k = self.s.m.f32c(0x3F7F_FFFF); self.sel(ge, k, r) } + /// `sin_turns` / `cos_turns`: the argument in turns, reduced exactly (x - trunc(x)) before + /// the scaling to radians; exact zeros at whole and half turns (sin, with sin(±0) = x) and + /// quarter turns (cos, of |r|). `trig_nonfinite`: ±inf gives 0xFFC00000, a NaN itself, quiet. + pub fn trig_turns(&mut self, x: Value, sin: bool) -> Value { + let t = self.un(op::ROUND_Z, x); + let r = self.fsub(x, t); + let ar = self.fabs(r); + let (r, k0, k1) = if sin { (r, 0.0, 0.5) } else { (ar, 0.25, 0.75) }; + let k0 = self.fc(k0); + let k1 = self.fc(k1); + let e0 = self.fcmp(Pred::FOEq, r, k0); + let e1 = self.fcmp(Pred::FOEq, ar, k1); + let exact = self.lor(e0, e1); + let k = self.fc(6.283_185_3); + let rad = self.fmul(r, k); + let v = self.un(if sin { op::SIN } else { op::COS }, rad); + let z = self.fc(0.0); + let v = self.sel(exact, z, v); + let xb = self.bits(x); + let mut vb = self.bits(v); + if sin { + let x0 = self.fcmp(Pred::FOEq, x, z); + vb = self.sel(x0, xb, vb); + } + let mag = self.andc(xb, 0x7FFF_FFFF); + let inf = self.cmpc(Pred::Eq, mag, 0x7F80_0000); + let quiet = self.orc(xb, 0x0040_0000); + let nf = self.selc(inf, 0xFFC0_0000, quiet); + let nonfinite = self.cmpc(Pred::UGe, mag, 0x7F80_0000); + let res = self.sel(nonfinite, nf, vb); + self.f(res) + } /// HLSL `frexp` as DXC lowers it: (mantissa, exponent as float). fn frexp_dxc(&mut self, x: Value) -> (Value, Value) { let i = self.bits(x); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 7851791c94..6c6db2513f 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3489,8 +3489,13 @@ impl Em { "v_sqrt_f16" => fr(format!("sqrt({})", fh(0))), "v_log_f16" => fr(format!("log2({})", fh(0))), "v_exp_f16" => fr(format!("exp2({})", fh(0))), - "v_sin_f16" => fr(format!("sin({} * 6.2831853f)", fh(0))), - "v_cos_f16" => fr(format!("cos({} * 6.2831853f)", fh(0))), + // ±Inf gives the f16 NaN 0xFE00 on RDNA2 (ivall/xcl#796); f32tof16 of the f32 NaN may not. + "v_sin_f16" | "v_cos_f16" if !m.clamp => { + let f = if name == "v_sin_f16" { "sin_turns" } else { "cos_turns" }; + format!("select(({} & 0x7FFFu) == 0x7C00u, 0xFE00u, {})", hb(0), fr(format!("{f}({})", fh(0)))) + } + "v_sin_f16" => fr(format!("sin_turns({})", fh(0))), + "v_cos_f16" => fr(format!("cos_turns({})", fh(0))), "v_fract_f16" => fr(format!("fract_f({})", fh(0))), "v_floor_f16" => fr(format!("floor({})", fh(0))), "v_ceil_f16" => fr(format!("ceil({})", fh(0))), @@ -3827,8 +3832,8 @@ impl Em { "v_sqrt_f32" => fr(format!("sqrt({})", fs(0))), "v_exp_f32" => fr(format!("exp2({})", fs(0))), "v_log_f32" => fr(format!("log2({})", fs(0))), - "v_sin_f32" => fr(format!("sin({} * 6.2831853f)", fs(0))), - "v_cos_f32" => fr(format!("cos({} * 6.2831853f)", fs(0))), + "v_sin_f32" => fr(format!("sin_turns({})", fs(0))), + "v_cos_f32" => fr(format!("cos_turns({})", fs(0))), "v_fract_f32" => fr(format!("fract_f({})", fs(0))), "v_trunc_f32" => fr(format!("trunc({})", fs(0))), "v_floor_f32" => fr(format!("floor({})", fs(0))), @@ -6273,6 +6278,13 @@ float mad_nf_f16(float a, float b, float c, uint rm) { precise float p = a * b; float med3f(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); } uint med3u(uint a, uint b, uint c) { return max(min(a, b), min(max(a, b), c)); } int med3i(int a, int b, int c) { return max(min(a, b), min(max(a, b), c)); } +// v_sin / v_cos take the argument in turns: reduced exactly (x - trunc(x)) before the scaling to +// radians, so a large argument keeps its phase (RDNA 2 ISA: sin(-MaxFloat) = 0, cos(-MaxFloat) = 1). +// Exact zeros at whole and half turns (sin) and quarter turns (cos); sin(-0) = -0. ±inf gives the +// ISA's 0xFFC00000 and a NaN itself, quiet, on the bits (DXC's relaxed float math loses inf - inf). +uint trig_nonfinite(float x) { uint u = asuint(x); return select((u & 0x7FFFFFFFu) == 0x7F800000u, 0xFFC00000u, u | 0x00400000u); } +float sin_turns(float x) { float r = x - trunc(x); float s = select(or(r == 0.0f, abs(r) == 0.5f), 0.0f, sin(r * 6.2831853f)); return asfloat(select((asuint(x) & 0x7FFFFFFFu) >= 0x7F800000u, trig_nonfinite(x), select(x == 0.0f, asuint(x), asuint(s)))); } +float cos_turns(float x) { float r = abs(x - trunc(x)); float c = select(or(r == 0.25f, r == 0.75f), 0.0f, cos(r * 6.2831853f)); return asfloat(select((asuint(x) & 0x7FFFFFFFu) >= 0x7F800000u, trig_nonfinite(x), asuint(c))); } // x - floor(x) below 1.0 (RDNA: a NaN stays NaN and ±inf gives NaN – min() would return the // clamp for both: HLSL min returns its non-NaN operand) float fract_f(float x) { float r = x - floor(x); return select(r >= 1.0f, asfloat(0x3F7FFFFFu), r); } diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index a940dcb6fc..504ae8a29d 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -555,6 +555,28 @@ mod tests { } } + /// v_sin / v_cos (f32 and f16) reduce the argument in turns before Sin / Cos, as the HLSL + /// path's `sin_turns` / `cos_turns` (with `trig_nonfinite`, and 0xFE00 for an f16 ±inf): + /// a plain Sin of x · 2π gives sin(-0.5) = -0 there, against the HLSL path's +0. + #[test] + fn sin_and_cos_reduce_the_argument_in_turns() { + let lines: &[I] = &[ + ("V_SIN_F32", "ENC_VOP1", &[("VDST", 1), ("SRC0", V + 5)]), + ("V_COS_F32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 6)]), + ("V_SIN_F16", "ENC_VOP1", &[("VDST", 3), ("SRC0", V + 7)]), + ("V_COS_F16", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 8)]), + ENDPGM, + ]; + let dxil = super::kernel(&decode(lines), false).unwrap_or_else(|e| panic!("{e}")).0; + if crate::gpu::dxil::validate::validator_supported() { + crate::gpu::dxil::validate::validate(&dxil).unwrap(); + } + let Ok(dis) = crate::gpu::dxil::validate::disassemble(&dxil) else { return }; + for (what, n) in [("; Round_z(", 4), ("; Sin(", 2), ("; Cos(", 2), ("i32 -4194304", 4), ("i32 65024", 2)] { + assert_eq!(dis.matches(what).count(), n, "{what}\n{dis}"); + } + } + /// The f16 and packed programs of `lower`'s tests, as `f32_programs_on_the_gpu`. #[test] fn f16_programs_on_the_gpu() { diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 8965a41caf..19665be13d 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1182,6 +1182,110 @@ fn gpu_valu_float_and_int() { } } +/// v_sin / v_cos take turns and reduce them exactly: every functional example the RDNA 2 ISA +/// prints for V_SIN_F32 / V_COS_F32 (p.142) and V_SIN_F16 / V_COS_F16 (p.149), exact zeros at +/// whole, half and quarter turns, and large arguments that keep their phase (2π·(x - trunc(x))). +/// Rows marked `hw` are native RDNA2 results (RX 6800M, gfx1031), measured by luckyteagirl in +/// https://github.com/ivall/xcl/issues/796#issuecomment-7123464342. Where the hardware value comes +/// from its own sine approximation (0.125 turns), `Ulps` allows one ulp, as the driver's sin() differs. +#[test] +fn gpu_sin_cos_reduce_in_turns() { + if !gpu_ready() { + return; + } + #[derive(Clone, Copy, Debug)] + enum E { + Bits(u32), + Nan, + Near(f64), + Ulps(u32, u32), + } + use E::*; + let turn = |x: f64, f: fn(f64) -> f64| f(2.0 * std::f64::consts::PI * (x - x.trunc())); + let near = |x: f32| (Near(turn(x as f64, f64::sin)), Near(turn(x as f64, f64::cos))); + // (input, sin, cos) + let mut c32: Vec<(u32, E, E)> = vec![ + // the ISA's examples + (0xFF80_0000, Bits(0xFFC0_0000), Bits(0xFFC0_0000)), // hw + (0xFF7F_FFFF, Bits(0), Bits(0x3F80_0000)), // hw + (0x8000_0000, Bits(0x8000_0000), Bits(0x3F80_0000)), // hw + (0x3E80_0000, Bits(0x3F80_0000), Bits(0)), // hw + (0x7F80_0000, Bits(0xFFC0_0000), Bits(0xFFC0_0000)), // hw + (0x7FC0_1234, Nan, Nan), // a NaN stays NaN + (0x7F7F_FFFF, Bits(0), Bits(0x3F80_0000)), // hw, +MaxFloat + // exact zeros and ones at half and quarter turns + (f(0.5), Bits(0), Bits(0xBF80_0000)), // hw + (f(-0.75), Bits(0x3F80_0000), Bits(0)), // hw + (f(8388607.5), Bits(0), Bits(0xBF80_0000)), // hw + (f(12345.5), Bits(0), Near(-1.0)), + (f(7.25), Near(1.0), Bits(0)), + ]; + // hw: an eighth of a turn gives the same bits at every whole-turn offset + for x in [0.125f32, 255.125, 100000.125, 1000000.125] { + c32.push((f(x), Ulps(0x3F35_04F4, 1), Ulps(0x3F35_04F3, 1))); + } + for x in [0.1f32, -3.3, -2097151.875] { + let (s, c) = near(x); + c32.push((f(x), s, c)); + } + let f16v = |h: u32| -> f64 { + let (s, e, m) = (if h & 0x8000 != 0 { -1.0 } else { 1.0 }, (h >> 10) & 0x1F, (h & 0x3FF) as f64); + s * if e == 0 { m * 2f64.powi(-24) } else { (1.0 + m / 1024.0) * 2f64.powi(e as i32 - 15) } + }; + let c16: Vec<(u32, E, E)> = vec![ + (0xFC00, Bits(0xFE00), Bits(0xFE00)), // hw + (0xFBFF, Bits(0), Bits(0x3C00)), // hw, -65504 + (0x8000, Bits(0x8000), Bits(0x3C00)), // hw + (0x3400, Bits(0x3C00), Bits(0)), + (0x7BFF, Bits(0), Bits(0x3C00)), // hw, +65504 + (0x7C00, Bits(0xFE00), Bits(0xFE00)), // hw + (0x7E01, Nan, Nan), + (0x5BF8, Bits(0), Bits(0x3C00)), // hw, 255 turns + (0x3800, Bits(0), Near(-1.0)), // half a turn + (0x3000, Ulps(0x39A8, 1), Ulps(0x39A8, 1)), // hw, 0.125 turns + (0x5BF9, Ulps(0x39A8, 1), Ulps(0x39A8, 1)), // hw, 255.125 turns + (0xD640, Near(turn(-100.0, f64::sin)), Near(turn(-100.0, f64::cos))), // -100 + ]; + let p = prog(&[ + ("V_SIN_F32", "ENC_VOP1", &[("VDST", 2), ("SRC0", V + 1)], None), + ("V_COS_F32", "ENC_VOP1", &[("VDST", 3), ("SRC0", V + 1)], None), + ("V_SIN_F16", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 6)], None), + ("V_COS_F16", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 6)], None), + ]); + let mut st = KernelState::default(); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[1] = c32[l % c32.len()].0; + r[6] = c16[l % c16.len()].0; + } + let r = runner::run_code(&p, &st, &[]).unwrap(); + let mut bad = Vec::new(); + let mut check = |name: &str, x: u32, got: u32, want: E, is_nan: bool, value: f64, tol: f64| { + let ok = match want { + Bits(b) => got == b, + Nan => is_nan, + Near(v) => (value - v).abs() <= tol, + Ulps(b, n) => (got as i64 - b as i64).abs() <= n as i64, + }; + if !ok { + bad.push(format!("{name}({x:#X}) = {got:#X} ({value}), want {want:?}")); + } + }; + for l in 0..64 { + let v = &r.vgpr[l]; + let (x, s, c) = c32[l % c32.len()]; + for (name, got, want) in [("v_sin_f32", v[2], s), ("v_cos_f32", v[3], c)] { + check(name, x, got, want, f32::from_bits(got).is_nan(), f32::from_bits(got) as f64, 2f64.powi(-16)); + } + let (x, s, c) = c16[l % c16.len()]; + for (name, got, want) in [("v_sin_f16", v[4] & 0xFFFF, s), ("v_cos_f16", v[5] & 0xFFFF, c)] { + check(name, x, got, want, got & 0x7C00 == 0x7C00 && got & 0x3FF != 0, f16v(got), 2f64.powi(-10)); + } + } + bad.sort(); + bad.dedup(); + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + /// Output modifiers each instruction kind applies: omod on f64 (clamp stays in double /// precision) and on the f64 → f32 / f32 → f16 conversions, and the integer clamp (saturation) of the /// unsigned adds, the packed 16-bit adds and the integer dot products.