Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions crates/victory-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1401,6 +1401,89 @@ impl<'a> Lower<'a> {
)
}

/// `f` as a 16-bit snorm (`signed`) or unorm in the low bits, the high
/// bits 0: clamped to [-1, 1] or [0, 1], scaled by 32767 or 65535 and
/// rounded to nearest even once, from the exact product. NaN gives 0.
///
/// The product is formed in integers from the float's bits: in f32,
/// `x * 32767` can need up to 39 significant bits and would round
/// before the rounding to an integer. Denormals give 0 (below 2^-126,
/// the scaled value is far under one half).
fn norm16(&mut self, f: V, signed: bool) -> V {
let c = self.cur;
let (i32t, i64t) = (self.s.t.i32, self.s.m.int(64));
self.s.flags |= flags::INT64;
let k = |l: &mut Self, v: u32| l.s.m.i32(v);
let k64 = |l: &mut Self, v: i64| l.s.m.int_const(i64t, v);
let max: u32 = if signed { 0x7FFF } else { 0xFFFF };
let bits = self.as_int(f);
let abs_mask = k(self, 0x7FFF_FFFF);
let mag = self.s.m.bin(c, Bin::And, bits, abs_mask);
// Exponent 1..=126 (magnitudes in [2^-126, 1)); the rest below.
let exp = {
let k23 = k(self, 23);
self.s.m.bin(c, Bin::LShr, mag, k23)
};
let mant = {
let m = k(self, 0x7F_FFFF);
let one = k(self, 0x80_0000);
let m = self.s.m.bin(c, Bin::And, mag, m);
self.s.m.bin(c, Bin::Or, m, one)
};
let mant = self.s.m.cast(c, Cast::ZExt, mant, i64t);
let scale = k64(self, i64::from(max));
let p = self.s.m.bin(c, Bin::Mul, mant, scale);
// The value is p / 2^s with s = 150 - exp, at least 24. From s = 41
// on, p < 2^40 is under one half of 2^s: capping s at 63 keeps the
// shifts defined and the result (0) the same.
let s = {
let k150 = k(self, 150);
let s = self.s.m.bin(c, Bin::Sub, k150, exp);
let k63 = k(self, 63);
let big = self.s.m.cmp(c, pred::IUGT, s, k63);
let s = self.s.m.select(c, big, k63, s);
self.s.m.cast(c, Cast::ZExt, s, i64t)
};
let q = self.s.m.bin(c, Bin::LShr, p, s);
let one = k64(self, 1);
let unit = self.s.m.bin(c, Bin::Shl, one, s);
let low = self.s.m.bin(c, Bin::Sub, unit, one);
let rem = self.s.m.bin(c, Bin::And, p, low);
let half = self.s.m.bin(c, Bin::LShr, unit, one);
let above = self.s.m.cmp(c, pred::IUGT, rem, half);
let tie = self.s.m.cmp(c, pred::EQ, rem, half);
let odd = self.s.m.bin(c, Bin::And, q, one);
let zero64 = k64(self, 0);
let odd = self.s.m.cmp(c, pred::NE, odd, zero64);
let tie_up = self.s.m.bin(c, Bin::And, tie, odd);
let up = self.s.m.bin(c, Bin::Or, above, tie_up);
let up = self.s.m.cast(c, Cast::ZExt, up, i64t);
let n = self.s.m.bin(c, Bin::Add, q, up);
let n = self.s.m.cast(c, Cast::Trunc, n, i32t);
// Magnitudes of 1 and more (and infinity) give the maximum; below
// 2^-126 (zero, denormals) 0; NaN 0.
let one_f = k(self, 0x3F80_0000);
let sat = self.s.m.cmp(c, pred::IUGE, mag, one_f);
let kmax = k(self, max);
let n = self.s.m.select(c, sat, kmax, n);
let zero = k(self, 0);
let tiny = self.s.m.cmp(c, pred::EQ, exp, zero);
let n = self.s.m.select(c, tiny, zero, n);
let inf = k(self, 0x7F80_0000);
let nan = self.s.m.cmp(c, pred::IUGT, mag, inf);
let n = self.s.m.select(c, nan, zero, n);
// The sign: negated for snorm, 0 for unorm.
let neg = self.s.m.cmp(c, pred::NE, mag, bits);
if signed {
let minus = self.s.m.bin(c, Bin::Sub, zero, n);
let r = self.s.m.select(c, neg, minus, n);
let ffff = k(self, 0xFFFF);
self.s.m.bin(c, Bin::And, r, ffff)
} else {
self.s.m.select(c, neg, zero, n)
}
}

/// `f` as an f16 in the low bits, rounded toward zero: the nearest-even
/// conversion, one step back toward zero where it rounded away (which
/// also turns an overflow to infinity into the largest finite half).
Expand Down Expand Up @@ -3942,6 +4025,25 @@ impl<'a> Lower<'a> {
self.write(inst, Reg::V(reg), x, guard);
Ok(())
}
"v_cvt_pknorm_i16_f32"
| "v_cvt_pknorm_u16_f32"
| "v_cvt_pknorm_i16_f16"
| "v_cvt_pknorm_u16_f16" => {
// src0 into the low half, src1 into the high half, each
// clamped and scaled to a 16-bit snorm or unorm.
let signed = name.contains("_i16_");
let (a, bb) = if name.ends_with("_f16") {
(self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?)
} else {
(f(self, 0)?, f(self, 1)?)
};
let lo = self.norm16(a, signed);
let hi = self.norm16(bb, signed);
let sh = self.s.m.i32(16);
let hi = self.s.m.bin(c, Bin::Shl, hi, sh);
let r = self.s.m.bin(c, Bin::Or, lo, hi);
int(self, r)
}
"v_cvt_pkrtz_f16_f32" => {
let (a, bb) = (f(self, 0)?, f(self, 1)?);
let lo = self.f16_toward_zero(a);
Expand Down
151 changes: 150 additions & 1 deletion crates/victory-shader/src/emit/valu_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
//!
//! Covers RDNA2 hardware semantics that differ from naive DXIL lowering:
//! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16`
//! near `1.0`, and turn-range reduction for `v_sin_*`/`v_cos_*`.
//! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the exact
//! rounding of `v_cvt_pknorm_*`.

use super::host::{Dispatch, Host, Root, View};
use super::{HostShader, lower, validator};
Expand Down Expand Up @@ -933,3 +934,151 @@ fn v_cmp_class_f16_matches_rdna2() {
);
});
}

/// A 16-bit snorm (`signed`) or unorm of `x`, as the RDNA2 ISA reference
/// gives `v_cvt_pknorm_*`: clamped, scaled, rounded to nearest even from the
/// exact product (exact in f64), NaN as 0.
fn norm16_ref(x: f32, signed: bool) -> u16 {
if x.is_nan() {
return 0;
}
let (lo, k) = if signed {
(-1.0, 32767.0)
} else {
(0.0, 65535.0)
};
let n = (f64::from(x.clamp(lo, 1.0)) * k).round_ties_even() as i32;
n as u16
}

/// Inputs in [0.5, 1) and near 0.001 whose f32 product with the scale lands
/// exactly on a tie although the exact product does not: a translation that
/// multiplies in f32 rounds them the wrong way.
fn f32_tie_traps(signed: bool) -> Vec<f32> {
let k: f32 = if signed { 32767.0 } else { 65535.0 };
let mut traps = Vec::new();
for start in [0.5f32, 0.001] {
let first = start.to_bits();
for b in first..first + 4_000_000 {
let x = f32::from_bits(b);
let p = x * k;
if p.fract() == 0.5 && f64::from(x) * f64::from(k) != f64::from(p) {
traps.push(x);
if traps.len() % 3 == 0 {
break;
}
}
}
}
traps
}

fn pknorm_f32_inputs(signed: bool) -> Vec<f32> {
let mut xs = vec![
0.0,
-0.0,
1.0,
-1.0,
2.0,
-2.0,
f32::INFINITY,
f32::NEG_INFINITY,
f32::NAN,
-f32::NAN,
0.5,
-0.5,
0.25,
1.0 / 3.0,
-0.7,
0.999_99,
f32::MIN_POSITIVE,
1e-6,
-1e-6,
f32::from_bits(1), // denormal
1.0 / 65535.0,
0.5 / 65535.0,
1.5 / 32767.0,
f32::from_bits(0x3F7F_FFFF), // just below 1
];
xs.extend(f32_tie_traps(signed));
xs
}

#[test]
fn v_cvt_pknorm_f32_rounds_the_exact_product() {
for (op, signed, what) in [
(0x368u16, true, "v_cvt_pknorm_i16_f32"),
(0x369, false, "v_cvt_pknorm_u16_f32"),
] {
// The traps must tell an f32 product apart from the exact one.
let k: f32 = if signed { 32767.0 } else { 65535.0 };
let f32_product = |x: f32| (x * k).round_ties_even() as i32 as u16;
let traps = f32_tie_traps(signed);
assert!(
traps
.iter()
.any(|&x| f32_product(x) != norm16_ref(x, signed)),
"{what}: no input separates an f32 product from the exact one"
);
let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), 0));
let xs = pknorm_f32_inputs(signed);
// Each input once in each half, paired with its neighbour.
let cases: Vec<[u32; 4]> = (0..xs.len())
.map(|i| [xs[i].to_bits(), xs[(i + 1) % xs.len()].to_bits(), 0, 0])
.collect();
run_cases(&shader, &cases, |backend, _, inp, got| {
let (a, b) = (f32::from_bits(inp[0]), f32::from_bits(inp[1]));
let want = u32::from(norm16_ref(a, signed)) | u32::from(norm16_ref(b, signed)) << 16;
assert_eq!(
got, want,
"{backend}: {what}({a:e} [{:#010x}], {b:e} [{:#010x}]) = {got:#010x}, want {want:#010x}",
inp[0], inp[1],
);
});
}
}

#[test]
fn v_cvt_pknorm_f16_rounds_the_exact_product() {
let halves: Vec<u16> = vec![
0x0000, 0x8000, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x7C00, 0xFC00, 0x7E00, 0xFE00,
0x3800, // 0.5: a tie in both scales
0xB800, 0x3555, 0x0001, // smallest denormal
0x8001, 0x0400, // smallest normal
0x3BFF, // just below 1
0x1001, 0x2E66, 0xB266, 0x3A00, 0x3401,
// Large denormals, which scale to 1 or 2: kept, not flushed (the
// FP16 input-denormal mode RDNA2 measurements matched).
0x03D6, 0x83D6, 0x823F, 0x03FF,
];
// Measured on RDNA2 (gfx1036) with FP16 input denormals kept.
assert_eq!(norm16_ref(f16_to_f32(0x83D6), true), 0xFFFE);
assert_eq!(norm16_ref(f16_to_f32(0x823F), true), 0xFFFF);
for (op, signed, what) in [
(0x312u16, true, "v_cvt_pknorm_i16_f16"),
(0x313, false, "v_cvt_pknorm_u16_f16"),
] {
let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), 0));
let cases: Vec<[u32; 4]> = (0..halves.len())
.map(|i| {
let next = halves[(i + 1) % halves.len()];
// Junk in the high halves: only the low halves are read.
[
u32::from(halves[i]) | 0xABCD_0000,
u32::from(next) | 0x1234_0000,
0,
0,
]
})
.collect();
run_cases(&shader, &cases, |backend, _, inp, got| {
let (a, b) = (inp[0] as u16, inp[1] as u16);
let (fa, fb) = (f16_to_f32(a), f16_to_f32(b));
let want = u32::from(norm16_ref(fa, signed)) | u32::from(norm16_ref(fb, signed)) << 16;
assert_eq!(
got, want,
"{backend}: {what}({a:#06x}, {b:#06x}) = {got:#010x}, want {want:#010x}",
);
});
}
}