GPU rectangle CPU fallback: FP16 conversion turns NaN into infinity and rounds ties up #245

Open
opened 2026-11-26 03:39:11 +00:00 by github-bot · 1 comment
Owner

@⁠Bennet0k on GitHub · 2026-11-24 22:59 UTC · original

Source

Reproduction. Exercise expand_rects with an R16_FLOAT attribute. Corners 1.0, 0, 2^-11 produce 0x3c01 for the generated corner, while round-to-nearest ties-to-even gives 0x3c00. A quiet NaN corner (0x7e00) with other corners zero produces infinity (0x7c00). Both regressions failed with the original Rust module.

Proposed fix. Handle NaN separately from overflow and infinity, with a nonzero quiet NaN mantissa. For normal values use the retained mantissa parity to resolve exact ties, consistent with the subnormal path. With this change in a temporary copy, both regressions and the four existing tests pass. This test covers the CPU fallback.

Found in an AI-assisted audit of 2119b0e.

**@⁠Bennet0k** on GitHub · 2026-11-24 22:59 UTC · [original](https://github.com/fxceless/victory-fork/issues/245) [Source](https://github.com/fxceless/victory-fork/blob/2119b0e44c53aa9648307b0c5c73590290305b1f/crates/victory-gpu/src/primitive.rs#L127-L154) **Reproduction.** Exercise `expand_rects` with an `R16_FLOAT` attribute. Corners `1.0, 0, 2^-11` produce `0x3c01` for the generated corner, while round-to-nearest ties-to-even gives `0x3c00`. A quiet NaN corner (`0x7e00`) with other corners zero produces infinity (`0x7c00`). Both regressions failed with the original Rust module. **Proposed fix.** Handle NaN separately from overflow and infinity, with a nonzero quiet NaN mantissa. For normal values use the retained mantissa parity to resolve exact ties, consistent with the subnormal path. With this change in a temporary copy, both regressions and the four existing tests pass. This test covers the CPU fallback. Found in an AI-assisted audit of `2119b0e`.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:39:11 +00:00
Author
Owner

@⁠x-nihil0 on GitHub · 2026-11-25 00:49 UTC · original

Exhaustive check of the five fixes opened for this issue (#315, #316, #326, #335, #337)

I ran every one of the 2^32 f32 bit patterns through f32_to_half as it is on main (tested at 2119b0e; primitive.rs is the same at a803c87) and as it is in each PR, and compared the result with the CPU's own conversion (F16C vcvtps2ph, round to nearest even). A second reference written in f64 arithmetic agrees with F16C on every input.

Version Wrong results, non-NaN inputs NaN inputs that stop being NaN NaN result compared with F16C
main 2119b0e 30,720 (all exact ties) 16,777,214 (every NaN becomes infinity) –
#315 0 0 sign kept, payload dropped (sign | 0x7e00)
#316 0 0 bit-identical
#326 0 0 sign kept, payload dropped (sign | 0x7e00)
#335 0 0 bit-identical
#337 0 0 bit-identical

So the issue is confirmed as described, and all five PRs fix it for every number. (#335 has since been closed by its author as a duplicate of #315; its row stays for the comparison.) They differ only in what a NaN turns into: #316, #335 and #337 keep the top ten payload bits and set the quiet bit, as vcvtps2ph does; #315 and #326 return one fixed quiet NaN with the input's sign. I don't know which of the two the console does, and for a rectangle corner it may not matter.

The 30,720 on main are 30 exponents × 2 signs × the 512 ties whose kept mantissa is even: the ones that rounding half up gets wrong. First one: 0x3e001000 gives 0x3001, F16C gives 0x3000.

Also checked for each PR on its own branch (each is one commit on 2119b0e):

  • cargo test -p victory-gpu --lib --locked primitive passes. With main's f32_to_half put back under the PR's tests, at least one new test fails in every PR, so each PR's tests do catch the bug.
  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings is clean, and so is rustfmt --check on primitive.rs.
PR Diff New tests NaN
#315 +27 −3 1 fixed quiet NaN
#316 +41 −10 2 as F16C
#335 +53 −4 1 as F16C
#337 +104 −4 3 as F16C
#326 +120 −3 3 fixed quiet NaN

Run on Windows 11 (26300), Core Ultra 9 285, Rust 1.98.1; the whole sweep takes 3 s on 24 threads. The harness is below; its impls/*.rs files are f32_to_half from main and from each PR, copied unchanged with only pub added.

Harness (src/main.rs)
//! Exhaustive check of `f32_to_half` candidates for victory-fork issue #245.
//! Every one of the 2^32 f32 bit patterns goes through each candidate and is
//! compared with (a) the CPU's own conversion (F16C `vcvtps2ph`, round to
//! nearest even) and (b) a reference written here in f64 arithmetic.

mod impls {
    pub mod base;
    pub mod pr315;
    pub mod pr316;
    pub mod pr326;
    pub mod pr335;
    pub mod pr337;
}

use std::arch::x86_64::*;
use std::sync::atomic::{AtomicU64, Ordering};

const CANDIDATES: [(&str, fn(f32) -> u16); 6] = [
    ("main 2119b0e", impls::base::f32_to_half),
    ("PR #315", impls::pr315::f32_to_half),
    ("PR #316", impls::pr316::f32_to_half),
    ("PR #326", impls::pr326::f32_to_half),
    ("PR #335", impls::pr335::f32_to_half),
    ("PR #337", impls::pr337::f32_to_half),
];

#[target_feature(enable = "f16c,sse2")]
fn f16c(bits: u32) -> u16 {
    let v = _mm_castsi128_ps(_mm_cvtsi32_si128(bits as i32));
    let h = _mm_cvtps_ph::<_MM_FROUND_TO_NEAREST_INT>(v);
    _mm_cvtsi128_si32(h) as u16
}

/// Round to nearest, ties to even, in f64 (exact: an f32 has 24 significant
/// bits and the scalings are by powers of two). `None` for a NaN.
fn reference(bits: u32) -> Option<u16> {
    let x = f32::from_bits(bits);
    if x.is_nan() {
        return None;
    }
    let sign = ((bits >> 16) & 0x8000) as u16;
    let v = f64::from(x).abs();
    if v.is_infinite() {
        return Some(sign | 0x7c00);
    }
    if v < 2f64.powi(-14) {
        // Subnormal halves are m * 2^-24; m = 1024 is the smallest normal.
        return Some(sign | (v * 2f64.powi(24)).round_ties_even() as u16);
    }
    let mut e = ((v.to_bits() >> 52) & 0x7ff) as i32 - 1023;
    if e > 15 {
        return Some(sign | 0x7c00);
    }
    let mut r = (v * 2f64.powi(10 - e)).round_ties_even() as u32; // 1024..=2048
    if r == 2048 {
        e += 1;
        r = 1024;
    }
    if e > 15 {
        return Some(sign | 0x7c00);
    }
    Some(sign | ((((e + 15) as u32) << 10) | (r - 1024)) as u16)
}

fn is_nan16(h: u16) -> bool {
    h & 0x7c00 == 0x7c00 && h & 0x03ff != 0
}

#[derive(Default, Clone)]
struct Stats {
    wrong_number: u64,     // a non-NaN input whose result differs from F16C
    wrong_tie: u64,        // ... of which the input is exactly halfway between two halves
    nan_lost: u64,         // a NaN input whose result is not a NaN
    nan_sign: u64,         // a NaN result with another sign than its input
    nan_signaling: u64,    // a NaN result without the quiet bit
    nan_bits: u64,         // a NaN result that is a NaN but not F16C's bits
    examples: Vec<(u32, u16, u16)>,
}

impl Stats {
    fn add(&mut self, o: &Stats) {
        self.wrong_number += o.wrong_number;
        self.wrong_tie += o.wrong_tie;
        self.nan_lost += o.nan_lost;
        self.nan_sign += o.nan_sign;
        self.nan_signaling += o.nan_signaling;
        self.nan_bits += o.nan_bits;
        for e in &o.examples {
            if self.examples.len() < 6 {
                self.examples.push(*e);
            }
        }
    }
}

fn main() {
    assert!(is_x86_feature_detected!("f16c"), "this CPU has no F16C");
    let threads = std::thread::available_parallelism().map_or(8, |n| n.get());
    const CHUNK: u64 = 1 << 22;
    let next = AtomicU64::new(0);
    let started = std::time::Instant::now();

    // (per candidate, reference-vs-F16C disagreements, inputs seen)
    let results: Vec<(Vec<Stats>, u64, u64)> = std::thread::scope(|s| {
        let handles: Vec<_> = (0..threads)
            .map(|_| {
                s.spawn(|| {
                    let mut stats = vec![Stats::default(); CANDIDATES.len()];
                    let mut ref_bad = 0u64;
                    let mut seen = 0u64;
                    loop {
                        let start = next.fetch_add(CHUNK, Ordering::Relaxed);
                        if start >= 1 << 32 {
                            break;
                        }
                        for bits in start..start + CHUNK {
                            let bits = bits as u32;
                            seen += 1;
                            // SAFETY: F16C was checked at startup.
                            let hw = unsafe { f16c(bits) };
                            let nan = f32::from_bits(bits).is_nan();
                            match reference(bits) {
                                Some(r) => ref_bad += u64::from(r != hw),
                                None => ref_bad += u64::from(!is_nan16(hw)),
                            }
                            for (i, (_, f)) in CANDIDATES.iter().enumerate() {
                                let got = f(f32::from_bits(bits));
                                let st = &mut stats[i];
                                let mut bad = false;
                                if nan {
                                    if !is_nan16(got) {
                                        st.nan_lost += 1;
                                        bad = true;
                                    } else {
                                        if (got >> 15) as u32 != bits >> 31 {
                                            st.nan_sign += 1;
                                            bad = true;
                                        }
                                        if got & 0x0200 == 0 {
                                            st.nan_signaling += 1;
                                            bad = true;
                                        }
                                        if got != hw {
                                            st.nan_bits += 1;
                                        }
                                    }
                                } else if got != hw {
                                    st.wrong_number += 1;
                                    let exp = (bits >> 23) & 0xff;
                                    if (113..=142).contains(&exp) && bits & 0x1fff == 0x1000 {
                                        st.wrong_tie += 1;
                                    }
                                    bad = true;
                                }
                                if bad && st.examples.len() < 6 {
                                    st.examples.push((bits, got, hw));
                                }
                            }
                        }
                    }
                    (stats, ref_bad, seen)
                })
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });

    let mut total = vec![Stats::default(); CANDIDATES.len()];
    let (mut ref_bad, mut seen) = (0u64, 0u64);
    for (stats, r, n) in &results {
        ref_bad += r;
        seen += n;
        for (t, s) in total.iter_mut().zip(stats) {
            t.add(s);
        }
    }
    println!("inputs checked: {seen} (2^32 = {})", 1u64 << 32);
    println!("f64 reference vs F16C disagreements: {ref_bad}");
    println!("threads: {threads}, {:.1} s", started.elapsed().as_secs_f64());
    println!();
    println!("candidate    | wrong number | of which ties | NaN lost | NaN sign | NaN signaling | NaN != F16C bits");
    for ((name, _), s) in CANDIDATES.iter().zip(&total) {
        println!(
            "{name:<12} | {:>12} | {:>13} | {:>8} | {:>8} | {:>13} | {:>16}",
            s.wrong_number, s.wrong_tie, s.nan_lost, s.nan_sign, s.nan_signaling, s.nan_bits
        );
    }
    println!();
    for ((name, _), s) in CANDIDATES.iter().zip(&total) {
        for (bits, got, hw) in &s.examples {
            println!(
                "{name}: f32 {bits:#010x} ({:e}) -> {got:#06x}, F16C {hw:#06x}",
                f32::from_bits(*bits)
            );
        }
    }
}

Checked with an AI-assisted harness (Claude); no game files involved.

**@⁠x-nihil0** on GitHub · 2026-11-25 00:49 UTC · [original](https://github.com/fxceless/victory-fork/issues/245#issuecomment-7148919024) **Exhaustive check of the five fixes opened for this issue (#315, #316, #326, #335, #337)** I ran every one of the 2^32 `f32` bit patterns through `f32_to_half` as it is on `main` (tested at `2119b0e`; `primitive.rs` is the same at `a803c87`) and as it is in each PR, and compared the result with the CPU's own conversion (F16C `vcvtps2ph`, round to nearest even). A second reference written in `f64` arithmetic agrees with F16C on every input. | Version | Wrong results, non-NaN inputs | NaN inputs that stop being NaN | NaN result compared with F16C | |---|---|---|---| | `main` `2119b0e` | 30,720 (all exact ties) | 16,777,214 (every NaN becomes infinity) | – | | #315 | 0 | 0 | sign kept, payload dropped (`sign \| 0x7e00`) | | #316 | 0 | 0 | bit-identical | | #326 | 0 | 0 | sign kept, payload dropped (`sign \| 0x7e00`) | | #335 | 0 | 0 | bit-identical | | #337 | 0 | 0 | bit-identical | So the issue is confirmed as described, and all five PRs fix it for every number. (#335 has since been closed by its author as a duplicate of #315; its row stays for the comparison.) They differ only in what a NaN turns into: #316, #335 and #337 keep the top ten payload bits and set the quiet bit, as `vcvtps2ph` does; #315 and #326 return one fixed quiet NaN with the input's sign. I don't know which of the two the console does, and for a rectangle corner it may not matter. The 30,720 on `main` are 30 exponents × 2 signs × the 512 ties whose kept mantissa is even: the ones that rounding half up gets wrong. First one: `0x3e001000` gives `0x3001`, F16C gives `0x3000`. Also checked for each PR on its own branch (each is one commit on `2119b0e`): - `cargo test -p victory-gpu --lib --locked primitive` passes. With `main`'s `f32_to_half` put back under the PR's tests, at least one new test fails in every PR, so each PR's tests do catch the bug. - `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings` is clean, and so is `rustfmt --check` on `primitive.rs`. | PR | Diff | New tests | NaN | |---|---|---|---| | #315 | +27 −3 | 1 | fixed quiet NaN | | #316 | +41 −10 | 2 | as F16C | | #335 | +53 −4 | 1 | as F16C | | #337 | +104 −4 | 3 | as F16C | | #326 | +120 −3 | 3 | fixed quiet NaN | Run on Windows 11 (26300), Core Ultra 9 285, Rust 1.98.1; the whole sweep takes 3 s on 24 threads. The harness is below; its `impls/*.rs` files are `f32_to_half` from `main` and from each PR, copied unchanged with only `pub` added. <details> <summary>Harness (<code>src/main.rs</code>)</summary> ```rust //! Exhaustive check of `f32_to_half` candidates for victory-fork issue #245. //! Every one of the 2^32 f32 bit patterns goes through each candidate and is //! compared with (a) the CPU's own conversion (F16C `vcvtps2ph`, round to //! nearest even) and (b) a reference written here in f64 arithmetic. mod impls { pub mod base; pub mod pr315; pub mod pr316; pub mod pr326; pub mod pr335; pub mod pr337; } use std::arch::x86_64::*; use std::sync::atomic::{AtomicU64, Ordering}; const CANDIDATES: [(&str, fn(f32) -> u16); 6] = [ ("main 2119b0e", impls::base::f32_to_half), ("PR #315", impls::pr315::f32_to_half), ("PR #316", impls::pr316::f32_to_half), ("PR #326", impls::pr326::f32_to_half), ("PR #335", impls::pr335::f32_to_half), ("PR #337", impls::pr337::f32_to_half), ]; #[target_feature(enable = "f16c,sse2")] fn f16c(bits: u32) -> u16 { let v = _mm_castsi128_ps(_mm_cvtsi32_si128(bits as i32)); let h = _mm_cvtps_ph::<_MM_FROUND_TO_NEAREST_INT>(v); _mm_cvtsi128_si32(h) as u16 } /// Round to nearest, ties to even, in f64 (exact: an f32 has 24 significant /// bits and the scalings are by powers of two). `None` for a NaN. fn reference(bits: u32) -> Option<u16> { let x = f32::from_bits(bits); if x.is_nan() { return None; } let sign = ((bits >> 16) & 0x8000) as u16; let v = f64::from(x).abs(); if v.is_infinite() { return Some(sign | 0x7c00); } if v < 2f64.powi(-14) { // Subnormal halves are m * 2^-24; m = 1024 is the smallest normal. return Some(sign | (v * 2f64.powi(24)).round_ties_even() as u16); } let mut e = ((v.to_bits() >> 52) & 0x7ff) as i32 - 1023; if e > 15 { return Some(sign | 0x7c00); } let mut r = (v * 2f64.powi(10 - e)).round_ties_even() as u32; // 1024..=2048 if r == 2048 { e += 1; r = 1024; } if e > 15 { return Some(sign | 0x7c00); } Some(sign | ((((e + 15) as u32) << 10) | (r - 1024)) as u16) } fn is_nan16(h: u16) -> bool { h & 0x7c00 == 0x7c00 && h & 0x03ff != 0 } #[derive(Default, Clone)] struct Stats { wrong_number: u64, // a non-NaN input whose result differs from F16C wrong_tie: u64, // ... of which the input is exactly halfway between two halves nan_lost: u64, // a NaN input whose result is not a NaN nan_sign: u64, // a NaN result with another sign than its input nan_signaling: u64, // a NaN result without the quiet bit nan_bits: u64, // a NaN result that is a NaN but not F16C's bits examples: Vec<(u32, u16, u16)>, } impl Stats { fn add(&mut self, o: &Stats) { self.wrong_number += o.wrong_number; self.wrong_tie += o.wrong_tie; self.nan_lost += o.nan_lost; self.nan_sign += o.nan_sign; self.nan_signaling += o.nan_signaling; self.nan_bits += o.nan_bits; for e in &o.examples { if self.examples.len() < 6 { self.examples.push(*e); } } } } fn main() { assert!(is_x86_feature_detected!("f16c"), "this CPU has no F16C"); let threads = std::thread::available_parallelism().map_or(8, |n| n.get()); const CHUNK: u64 = 1 << 22; let next = AtomicU64::new(0); let started = std::time::Instant::now(); // (per candidate, reference-vs-F16C disagreements, inputs seen) let results: Vec<(Vec<Stats>, u64, u64)> = std::thread::scope(|s| { let handles: Vec<_> = (0..threads) .map(|_| { s.spawn(|| { let mut stats = vec![Stats::default(); CANDIDATES.len()]; let mut ref_bad = 0u64; let mut seen = 0u64; loop { let start = next.fetch_add(CHUNK, Ordering::Relaxed); if start >= 1 << 32 { break; } for bits in start..start + CHUNK { let bits = bits as u32; seen += 1; // SAFETY: F16C was checked at startup. let hw = unsafe { f16c(bits) }; let nan = f32::from_bits(bits).is_nan(); match reference(bits) { Some(r) => ref_bad += u64::from(r != hw), None => ref_bad += u64::from(!is_nan16(hw)), } for (i, (_, f)) in CANDIDATES.iter().enumerate() { let got = f(f32::from_bits(bits)); let st = &mut stats[i]; let mut bad = false; if nan { if !is_nan16(got) { st.nan_lost += 1; bad = true; } else { if (got >> 15) as u32 != bits >> 31 { st.nan_sign += 1; bad = true; } if got & 0x0200 == 0 { st.nan_signaling += 1; bad = true; } if got != hw { st.nan_bits += 1; } } } else if got != hw { st.wrong_number += 1; let exp = (bits >> 23) & 0xff; if (113..=142).contains(&exp) && bits & 0x1fff == 0x1000 { st.wrong_tie += 1; } bad = true; } if bad && st.examples.len() < 6 { st.examples.push((bits, got, hw)); } } } } (stats, ref_bad, seen) }) }) .collect(); handles.into_iter().map(|h| h.join().unwrap()).collect() }); let mut total = vec![Stats::default(); CANDIDATES.len()]; let (mut ref_bad, mut seen) = (0u64, 0u64); for (stats, r, n) in &results { ref_bad += r; seen += n; for (t, s) in total.iter_mut().zip(stats) { t.add(s); } } println!("inputs checked: {seen} (2^32 = {})", 1u64 << 32); println!("f64 reference vs F16C disagreements: {ref_bad}"); println!("threads: {threads}, {:.1} s", started.elapsed().as_secs_f64()); println!(); println!("candidate | wrong number | of which ties | NaN lost | NaN sign | NaN signaling | NaN != F16C bits"); for ((name, _), s) in CANDIDATES.iter().zip(&total) { println!( "{name:<12} | {:>12} | {:>13} | {:>8} | {:>8} | {:>13} | {:>16}", s.wrong_number, s.wrong_tie, s.nan_lost, s.nan_sign, s.nan_signaling, s.nan_bits ); } println!(); for ((name, _), s) in CANDIDATES.iter().zip(&total) { for (bits, got, hw) in &s.examples { println!( "{name}: f32 {bits:#010x} ({:e}) -> {got:#06x}, F16C {hw:#06x}", f32::from_bits(*bits) ); } } } ``` </details> Checked with an AI-assisted harness (Claude); no game files involved.
This discussion has been locked. Commenting is limited to contributors.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/fxceless--victory-fork#245
No description provided.