Rust-GPU / Rust-GPU/rust-gpu

Rust and SPIR-V float rounding semantics are different

Open
#229 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
3.4k
Forks
125
PR merge metrics
No merged PRs in 30d

Description

There is a footgun when trying to share code between CPU and GPU. Rust and SPIR-V have different semantics when rounding floats:

Rust:

  • Rust’s built-in conversion using as truncates the fractional part, effectively rounding toward zero.
  • For example, 1743028479.999... becomes 1743028479.
    Rust Language Reference

SPIR-V:

fn main() {
    let x = 1743028480i32;
    let y = (x as f64) * (1.0 / (i32::MAX as f64));

    // Without explicit rounding, differs:
    let without = (y * (i32::MAX as f64)) as i32;
    // Using `trunc()` forces Rust’s truncation:
    let with = (y * (i32::MAX as f64)).trunc() as i32;

    println!("x = {}. Without rounding = {}. With trunc() = {}.", x, without, with);
}

I'm not sure which should be the default. If it is Rust's we'll want to polyfill on the spir-v side. Might be good to have this user controlled in any case.

Originally posted by @LegNeato in https://github.com/Rust-GPU/rust-gpu/discussions/228#discussioncomment-12784276

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at crates/rustc_codegen_spirv/src/builder/builder_methods.rs around the referenced OpConvertFToS generation, then compare the Rust reference and SPIR-V specification linked in the issue. Determine the intended default or user-controlled behavior for float-to-integer conversion and validate it against the provided example. Done means the chosen semantics are explicitly agreed and the CPU/GPU behavior is aligned or deliberately configurable.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.