Translator: half +, -, *, / and fma on the 16-bit instructions record NativeHalfConversion

Under the 16-bit float controls, a half +, -, * or / and a half fused multiply-add run on the
device's 16-bit instructions, between exact conversions. By the Vulkan spec their results are
Metal's. A driver's compiler may still compute them in float and leave them unrounded. Intel's
Windows driver 101.2145 on a UHD Graphics 630 does:

- A standalone tree of three 16-bit OpFAdds, or Fmas of a product, each decorated NoContraction
  under all three 16-bit controls, ran on 4,096 invocations. 2,284 sums and 4,080 products
  matched neither the half tree nor the float tree rounded once (job m3-max-83092).
- The Iris Xe under Mesa ANV 26.2.6 gave the half tree on every invocation (job m3-max-83093).
- In the runtime's quad test on the UHD, 112 of the 1,536 compared halves are the float chain
  rounded once at the store (job m3-max-82918).

Per the planner's ruling, the operation carries the static note on every device, with no device
check. narrow::computes_half_arithmetic looks in the emitted module for a 16-bit OpFAdd, OpFSub,
OpFMul, OpVectorTimesScalar or OpFDiv, or a GLSL.std.450 Fma. Where it finds one, the pipeline
records NativeHalfConversion, beside the conversion pair's existing cases. A Sqrt alone records
nothing, and neither does the simdgroup half tree's ClusteredReduce.

The note's reach in validation narrows to half arithmetic. Until now it reached every word fed by
any float family. The AIR word scan now feeds a new family, HalfArithmetic, beside the
operation's own family, from these operations:
- an fadd, fsub, fmul, fdiv, frem or fneg with a half result;
- a float cast whose result or operand is a half;
- a call of a modelled family whose result or an argument is a half.
NativeHalfConversion reaches only that family. A half word that only float arithmetic fed,
through a move, is no longer reached. The note stays unbounded at the word, now on the
comparison's stay-unbounded list with its reason. A driver may leave the chain unrounded and
round it once at the store, and with cancellation the two answers differ by more than the stored
value's ulps (40 codes measured on the UHD). How far rests on the operands, which a word does
not carry.

Docs:
- The note's API.md catalogue entry and its PrecisionNote doc said those operations "take no such
  rounding". They now say the operations record the note, and give the UHD 630 measurement beside
  NVIDIA's fold and RADV's fusion.
- The DeviceHalfDenormals entry points to it.
- VALIDATION.md names the half family among those the word scan reads.

Tests:
- engine_native_half: the controlled-conversion test's sum kernel now records the note, as every
  kernel there does.
- engine_float_call_notes sets the module-level note aside for 16-bit arithmetic, as it does for
  the conversion pair.
- half_simd_reductions accepts, where the quad pipeline records the note, a quad word whose
  every half is Metal's or the float operations rounded once. The model is the new devtools
  quads_once.
- In validation:
  - the scan's packed-halves test expects HalfArithmetic on the half word alone;
  - a words test shows the note reaching a half word only when half arithmetic feeds it;
  - the reach row is pinned.

SEMANTICS_VERSION 2340 -> 2341 (precision notes added).
ENGINE_EXECUTOR_ABI vulkan-engine-v215 -> v216 (the word scan feeds HalfArithmetic, and the
note's reach narrows to it).

Golden hashes: no cell moves. The cells hash the final SPIR-V, which the note does not touch.
Job m3-max-83293 (Linux) ran golden_hashes_match_the_table twice: at this change, and with
compile.rs and cache/mod.rs at f42e61aa84. Both failed with the same 2 changed-cell lines, 0
lines differing between them: development's table is due its own bless. The fixtures that need
metal-as were skipped on Linux.

runtime-sources.sha256 is unchanged: no edited file is a fingerprint input.

Note-bounds figures (noted / matched within bounds / mismatches over the 1,168 public cases),
each arm built in one job, at 702916d9d3 and at this change on it (6edabebff2):
- lavapipe (Mesa 26.2.4, LLVM 23.1.1; job m3-max-83272): 151 / 27 / 15 before and after;
- Radeon 780M (RADV PHOENIX; job m3-max-83273): 166 / 24 / 21 before and after.
Every case's outcome and bounded line is the same in both arms, so no row is new. Only the per-note
word attribution moves: NativeHalfConversion's noted words fall from 3,267 to 1,168 on lavapipe and
from 3,558 to 1,276 on the 780M, as other notes reaching those words now take them.

Verified, at the probe db2bceb3f6, whose tree is this commit's (gate job m3-max-83293):
- the four red tests pass here and three fail with compile.rs at f42e61aa84 (EXIT=100);
- STEP clippy_plain EXIT=0, clippy_gpu EXIT=0, clippy_cpu EXIT=0;
- doc EXIT=0, privdoc EXIT=0;
- the translator's and AIR's suites minus the bless-due tables: EXIT=0;
- on lavapipe (host Mesa 26.2.6):
  - runtime: 983 passed, 4 skipped; half_simd_reductions 0 differ in all three pipelines;
  - validation: 1338 passed, 3 skipped, the runtime-sources guard among them.
- The conformance replay in the pinned lavapipe image (CI's venue, LLVM 23.1.1), at f42e61aa84
  and at this change (job m3-max-83337): 0 ledger drift in both arms, 4661 rows as expected.
  On the gate job's host lavapipe (Mesa 26.2.6, LLVM 23.1.4) its replay printed 12 drift lines,
  the bicubic-texel-classes rows among them. That run has no base arm.

The device legs of the half test:
- UHD Graphics 630, Intel's Windows driver 101.2145, at 6edabebff2 (this change on 702916d9d3;
  job m3-max-83288): every_device_sums_and_multiplies_half_simdgroups_as_metal passed.
  - The quad pipeline records NativeHalfConversion. 0 of 768 words differ from Metal's, and 96
    more are the float result rounded once.
  - The simd and masked pipelines: 0 differ.
- Apple M3 Max, KosmicKrisp (Mesa 26.3.1), at db2bceb3f6 (archive m3-max-83294, run
  m3-max-83297): passed. 0 words differ in each pipeline and none takes the rounded-once
  admission.

Landed with SEMANTICS_VERSION 2342 (renumbered above development's 2341); runtime-sources.sha256 recomputed on development, unchanged (a92fe0a8). States-only plays at the change (job 83345): gb-3090-r2 render 10643 and compute 15299 made, 0 refused; windrag-780m-b4 render 8972 and compute 225 made, 0 refused, equal to pin R.
This commit is contained in:
Anees Iqbal committed 2026-12-03 04:14:29 -08:00
1 parent e87fdd5a23
commit 9211eb3c10
16 files changed
+306 -62

No files matched your search

@@ -231,9 +231,48 @@ pub fn quads(w: u32) -> Option<u32> {
}
}
/// [`QUADS`]' word `w` as `float` arithmetic rounded to `half` once gives it, where this crate
/// models it: each operation of [`quads`]' tree or lane-order chain in `f32` (the empty answers
/// `-0` and 1), and the result rounded to `half` at the end. The answer
/// `PrecisionNote::NativeHalfConversion` admits for a word fed by `half` arithmetic where a driver
/// computes the device's 16-bit operations in `float` (Intel's Windows driver 101.2145 on a UHD
/// Graphics 630: every half of these words Metal's or this one).
pub fn quads_once(w: u32) -> Option<u32> {
let (t, k) = (w / QUAD_WORDS, w % QUAD_WORDS);
let operand = |table: &[[u16; 32]; 8], u: u32| table[(u / 32) as usize][(u % 32) as usize];
let base = t & !3;
// A `half` is exact in `f32`.
let lanes = |table| (base..base + 4).map(move |u| value(operand(table, u)) as f32);
let tree = |table, op: FloatOperation| {
let x: Vec<f32> = lanes(table).collect();
round(f64::from(op(op(x[0], x[1]), op(x[2], x[3]))))
};
let chain = |table, op: FloatOperation, empty: f32, inclusive: bool| {
let upto = (t - base) + u32::from(inclusive);
round(f64::from(lanes(table).take(upto as usize).fold(empty, op)))
};
let (add, mul): (FloatOperation, FloatOperation) = (|a, b| a + b, |a, b| a * b);
let pair = |low: u16, high: u16| u32::from(low) | (u32::from(high) << 16);
match k {
0 => Some(pair(tree(&SUM_OPERANDS, add), tree(&PRODUCT_OPERANDS, mul))),
1 => Some(pair(
chain(&SUM_OPERANDS, add, -0.0, true),
chain(&SUM_OPERANDS, add, -0.0, false),
)),
2 => Some(pair(
chain(&PRODUCT_OPERANDS, mul, 1.0, true),
chain(&PRODUCT_OPERANDS, mul, 1.0, false),
)),
_ => None,
}
}
/// A `half` operation of the model, on the operands' exact values.
type Operation = fn(f64, f64) -> f64;
/// A `float` operation of [`quads_once`], rounded to `f32`.
type FloatOperation = fn(f32, f32) -> f32;
/// The value of the `half` bits `h`.
fn value(h: u16) -> f64 {
let sign = if h & 0x8000 == 0 { 1.0 } else { -1.0 };
@@ -6,8 +6,11 @@
//! prefix operations. Every word the crate models is Metal's: each sum and product the tree of
//! rounded `half` operations Metal's is, each quad prefix operation the lane-order chain of them.
//! The simdgroup prefix operations' words, whose order Metal's measurements match no model of, are
//! counted, not compared. The device's kernel subgroup sizes, which decide the tier, are printed
//! with the pipelines' precision notes.
//! counted, not compared. Where a pipeline records `PrecisionNote::NativeHalfConversion`, which
//! reaches the words its `half` arithmetic feeds (a driver's compiler may compute the device's
//! 16-bit operations in `float`), a quad word's every `half` is Metal's or the `float` operations'
//! result rounded once (`quads_once`). The device's kernel subgroup sizes, which decide the tier,
//! are printed with the pipelines' precision notes.
//!
//! `llvm-as` assembles the module; without it the test skips visibly.
@@ -16,7 +19,7 @@ mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::{
ComputePipelineDescriptor, DispatchType, FunctionDescriptor, Library, MemoryClass,
StageSource,
PrecisionNote, StageSource,
};
use metal2vulkan_devtools::half_simd_reductions::{
self as h, FULL, MASKED, QUADS, QUAD_WORDS, THREADS,
@@ -38,15 +41,28 @@ mod on_device {
Err(error) => panic!("half_simd_reductions: {error:?}"),
};
let library = Library::from_air(&bitcode).expect("the library");
// Each kernel's threads, the words they write, and Metal's word where the crate models it.
let cases: [(&str, u32, u32, Model); 3] = [
(FULL, THREADS, THREADS, |w| Some(h::full(w))),
(MASKED, 3 * THREADS, 3 * THREADS, |w| Some(h::masked(w))),
(QUADS, THREADS, QUAD_WORDS * THREADS, h::quads),
// Each kernel's threads, the words they write, Metal's word where the crate models it, and
// the word its `float` operations rounded once give, where its `half` arithmetic feeds it.
let cases: [(&str, u32, u32, Model, Option<Model>); 3] = [
(FULL, THREADS, THREADS, |w| Some(h::full(w)), None),
(
MASKED,
3 * THREADS,
3 * THREADS,
|w| Some(h::masked(w)),
None,
),
(
QUADS,
THREADS,
QUAD_WORDS * THREADS,
h::quads,
Some(h::quads_once),
),
];
each_device("half_simd_reductions", |name, _, device| {
let kernel = device.core().translator.profile().subgroups().kernel;
for (entry, n, words, want) in cases {
for (entry, n, words, want, once) in cases {
let function = library.function(entry).expect("the kernel");
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
@@ -76,7 +92,10 @@ mod on_device {
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name} {entry}");
let contents = output.contents().expect("a Shared buffer");
let (mut wrong, mut compared) = (Vec::new(), 0);
// The word `float` arithmetic rounded once gives, where the note reaches it.
let notes = state.precision_notes();
let once = once.filter(|_| notes.contains(&PrecisionNote::NativeHalfConversion));
let (mut wrong, mut compared, mut rounded_once) = (Vec::new(), 0, 0);
for w in 0..words {
// SAFETY: the word lies in the buffer, which is alive, and its work completed.
let got = unsafe {
@@ -88,17 +107,31 @@ mod on_device {
continue;
};
compared += 1;
if got != metal {
if got == metal {
continue;
}
// Each `half` of the word Metal's or, where the note reaches, the `float`
// operations' rounded once.
let admitted = once.and_then(|f| f(w)).is_some_and(|alt| {
[0, 16].iter().all(|&s| {
let half = (got >> s) & 0xffff;
half == (metal >> s) & 0xffff || half == (alt >> s) & 0xffff
})
});
if admitted {
rounded_once += 1;
} else {
wrong.push(format!("{w}: {got:#010x} Metal {metal:#010x}"));
}
}
println!(
"{name} {entry}: kernel subgroup sizes {}..={} (pinnable {}); notes {:?}; \
{} of {compared} words differ from Metal's ({words} written)",
{} of {compared} words differ from Metal's ({words} written), {rounded_once} \
more the `float` result rounded once under NativeHalfConversion",
kernel.sizes.min,
kernel.sizes.max,
kernel.pinnable,
state.precision_notes(),
notes,
wrong.len()
);
assert!(wrong.is_empty(), "{name} {entry}: words differ: {wrong:?}");
@@ -95,7 +95,7 @@ pub mod variants;
/// how it decides a match. A change no recorded row can observe (a case kind no earlier executor
/// ran, or one it refused) needs no bump; its commit says why. The commit that bumps it says what
/// changed; this comment keeps no history.
pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v215";
pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v216";
/// One kernel case in the terms the runtime route takes: what this executor supports of an
/// [`AuthoredCase`] (buffers, device buffer arrays, argument-buffer buffers and textures,
@@ -627,9 +627,66 @@ impl Scan<'_> {
None
}
/// The bytes of `inst`'s value from its operands' current facts; `None` for an instruction
/// with no value, or whose operands the scan has not reached.
/// The bytes of `inst`'s value from its operands' current facts, each fed by
/// [`Family::HalfArithmetic`] too where `inst` is a `half` operation
/// ([`Self::half_operation`]); `None` for an instruction with no value, or whose operands the
/// scan has not reached.
fn transfer(&self, inst: &Inst) -> Option<Vec<ByteFact>> {
let bytes = self.transfer_bytes(inst)?;
if !self.half_operation(inst) {
return Some(bytes);
}
let half = Families::NONE.with(Family::HalfArithmetic);
Some(bytes.into_iter().map(|byte| byte.feed(half)).collect())
}
/// Whether `ty` is a `half` or a vector of them.
fn is_half(&self, ty: TypeId) -> bool {
match self.types().get(ty) {
Some(Type::Half) => true,
Some(Type::Vector { elem, .. }) => matches!(self.types().get(*elem), Some(Type::Half)),
_ => false,
}
}
/// Whether `inst` is a `half`-typed operation or a conversion to or from `half`
/// ([`Family::HalfArithmetic`]): a float operator or negation whose result is a `half`, a
/// float cast whose result or operand is one, or a call of a family ([`callee_families`]) whose
/// result or an argument is one.
fn half_operation(&self, inst: &Inst) -> bool {
match &inst.kind {
InstKind::BinOp { op, .. } => {
matches!(
op,
BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv | BinOp::FRem
) && self.is_half(inst.ty)
}
InstKind::FNeg { .. } => self.is_half(inst.ty),
InstKind::Cast { op, v } => {
matches!(
op,
CastOp::FPTrunc
| CastOp::FPExt
| CastOp::FPToUI
| CastOp::FPToSI
| CastOp::UIToFP
| CastOp::SIToFP
) && (self.is_half(inst.ty) || self.value_ty(*v).is_some_and(|t| self.is_half(t)))
}
InstKind::Call(call) => {
callee_families(&call.callee) != Families::NONE
&& (self.is_half(inst.ty)
|| call
.args
.iter()
.any(|arg| self.value_ty(*arg).is_some_and(|t| self.is_half(t))))
}
_ => false,
}
}
/// The bytes of `inst`'s value from its operands' current facts ([`Self::transfer`]).
fn transfer_bytes(&self, inst: &Inst) -> Option<Vec<ByteFact>> {
let ty = inst.ty;
let unknown = Families::NONE.with(Family::Unknown);
match &inst.kind {
@@ -79,7 +79,9 @@ fn placed_stores_give_each_word_its_own_operations() {
/// `fused-multiply-add-rounding-and-fmuladd-without-fast-math` stores one 16-byte vector a thread:
/// two `float` fused multiply-adds, a word of two `half` ones packed by `zext`, `shl` and `or`, and
/// a `float` product.
/// a `float` product. Only the `half` word is fed by `half` arithmetic: its bitcasts and packing
/// keep the family of the `half` operations, and the `float` words, whose operands are loaded and
/// never `half`, take none.
#[test]
fn packed_halves_keep_their_lanes_and_operations() {
let Some(words) = public_words("fused-multiply-add-rounding-and-fmuladd-without-fast-math")
@@ -87,6 +89,7 @@ fn packed_halves_keep_their_lanes_and_operations() {
return;
};
let fma = fed(&[Family::Fma]);
let half_fma = fed(&[Family::Fma, Family::HalfArithmetic]);
let float = |fed_by| WordFacts {
shape: WordShape::Float,
fed_by,
@@ -96,7 +99,7 @@ fn packed_halves_keep_their_lanes_and_operations() {
low: true,
high: true,
},
fed_by: fma,
fed_by: half_fma,
};
assert_eq!(
words.words,
@@ -300,6 +300,12 @@ impl UlpTable {
/// result, `sum |a_i * b_i|`, `|x * (1 - t)| + |y * t|`, a divisor in `[2^-126, 2^126]`), which a
/// word does not carry: with cancellation the result's own ulps say nothing of it. The fixture
/// knows its inputs, so a per-case bound from the operands is a later form.
/// - `NativeHalfConversion`: unbounded at the word. A driver may fold the conversion pair, fuse
/// the `float` operation into the narrowing, or compute the 16-bit arithmetic between the
/// conversions in `float` and leave it unrounded, so a chain of `half` operations is the `float`
/// chain rounded once at its store. With cancellation the two answers differ by more than the
/// stored value's ulps say (40 codes of a `half` measured on a UHD Graphics 630), and how far
/// rests on the chain's operands, which a word does not carry.
/// - Every other note bounds nothing on the stored value: Vulkan's transcendental and
/// arithmetic precision is stated per operation and input range (absolute error for
/// `sin`/`cos`, inherited bounds for `pow`), a device may drop signed zeros, infinities, and
@@ -50,6 +50,12 @@ pub enum Family {
/// A fragment function's input: a varying, a fragment built-in, an interpolant's
/// interpolation.
StageInput,
/// A `half`-typed operation, or a conversion to or from `half`: `fadd`, `fsub`, `fmul`,
/// `fdiv`, `frem` or `fneg` whose result is a `half` or a vector of them, a cast between a
/// float and another number whose result or operand is one, and a call of a family above whose
/// result or an argument is one. It feeds beside the operation's own family; a move (a load,
/// a select, a bitcast, a lane move) is no operation.
HalfArithmetic,
/// Another thread of the kernel may write the word: a store the scan cannot place among the
/// bytes of its own thread.
Unordered,
@@ -59,7 +65,7 @@ pub enum Family {
}
impl Family {
const ALL: [Family; 13] = [
const ALL: [Family; 14] = [
Family::FloatArithmetic,
Family::Division,
Family::Fma,
@@ -71,6 +77,7 @@ impl Family {
Family::Texture,
Family::Group,
Family::StageInput,
Family::HalfArithmetic,
Family::Unordered,
Family::Unknown,
];
@@ -253,11 +260,13 @@ pub fn reach(note: PrecisionNote) -> Reach {
N::DeviceArithmetic => families(&[F::Division, F::Fma, F::Dot, F::Function, F::Group]),
N::FastMathRewrites => families(&[F::FloatArithmetic, F::Fma]),
N::DevicePackConversion => families(&[F::Pack, F::Texture]),
// The device's rounding of a `half` (its conversion pair, or its 16-bit arithmetic, which
// a driver may leave unrounded): only the words `half` arithmetic feeds.
N::NativeHalfConversion => families(&[F::HalfArithmetic]),
N::DeviceDenormals
| N::DeviceNanEncoding
| N::DeviceSignedZeroInfNan
| N::DeviceHalfDenormals
| N::NativeHalfConversion
| N::NativeHalfQuantize => families(&ANY_FLOAT),
N::GradFromBias
| N::PixelSamplerScaling
@@ -210,6 +210,44 @@ fn the_access_order_note_reaches_only_words_another_thread_may_write() {
);
}
/// `NativeHalfConversion` reaches only a word `half` arithmetic feeds, and there excuses no
/// difference by a bound: a `half` word fed by `float` arithmetic alone, as a `float` result's
/// narrowing by a move would leave it, is a mismatch; the same word fed by a `half` operation, or a
/// `float` word fed by a conversion from `half`, is a noted difference.
#[test]
fn the_half_rounding_note_reaches_only_words_half_arithmetic_feeds() {
let halves = WordShape::Halves {
low: true,
high: true,
};
let note = [N::NativeHalfConversion];
let (metal, device) = (0x3c00_3c00, 0x3c00_3c28);
assert_eq!(
verdict(&note, halves, &[Family::FloatArithmetic], metal, device),
Verdict::Mismatch
);
assert_eq!(
verdict(
&note,
halves,
&[Family::FloatArithmetic, Family::HalfArithmetic],
metal,
device
),
Verdict::Noted
);
assert_eq!(
verdict(
&note,
WordShape::Float,
&[Family::HalfArithmetic],
0x3f80_0000,
0x3f80_2000
),
Verdict::Noted
);
}
/// `NativeNanEncoding` excuses a word only where both answers are NaNs of its lane's format.
#[test]
fn a_nan_encoding_excuses_only_two_nans() {
@@ -333,6 +371,10 @@ fn reach_rows_follow_the_notes_operations() {
reach(N::SimdgroupAccessOrder),
Reach::Families(Families::of(&[Family::Unordered]))
);
assert_eq!(
reach(N::NativeHalfConversion),
Reach::Families(Families::of(&[Family::HalfArithmetic]))
);
assert_eq!(reach(N::DeviceLineRasterization), Reach::Every);
assert_eq!(reach(N::NativeNanEncoding), Reach::Every);
let families = Families::of(&[Family::Texture, Family::Unknown]);
+1 -1
View File
@@ -60,7 +60,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 2341;
pub const SEMANTICS_VERSION: u32 = 2342;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
+26 -2
View File
@@ -26,7 +26,11 @@
//! that instruction between exact conversions instead, with no rounding here (`ops::f16_binary`):
//! under those float controls ([`half_controls`]), which make it so by the Vulkan spec and which the entry then
//! declares ([`computes_in_16_bits`]), on a driver that folds the conversion's round trip too
//! (NVIDIA's: the fold is the pair's, a 16-bit instruction keeps its rounding); there the emitted
//! (NVIDIA's: the fold is the pair's, a 16-bit instruction keeps its rounding). A driver's compiler
//! may compute that 16-bit arithmetic in `float` and leave it unrounded all the same (Intel's
//! Windows driver on a UHD Graphics 630 does), so a module holding a 16-bit `+ - * /` or fused
//! multiply-add records `PrecisionNote::NativeHalfConversion` on every device
//! ([`computes_half_arithmetic`]), a static note of the rounding. There the emitted
//! module holds every exact `half` at 16 bits, its moves, minimums, maximums and clamps, its
//! demotion variables and thread arrays, and its `dot` and `mix`, 16-bit instructions
//! (`spirv::half_hold`); a `half` `/` and `sqrt` under those controls are the device's 16-bit
@@ -1591,6 +1595,25 @@ fn has_bit(bits: &[u64], v: Value) -> bool {
/// ([`QuantizeForm::Controlled`]) the entry then declares [`controlled_modes`], which make that
/// arithmetic Metal's. One pass over the instructions.
pub fn computes_in_16_bits(m: &TypedModule) -> bool {
sixteen_bit_arithmetic(m, true)
}
/// Whether module `m` computes a `half` `+`, `-`, `*`, `/` or fused multiply-add on the device's
/// 16-bit instructions: an `OpFAdd`, `OpFSub`, `OpFMul`, `OpVectorTimesScalar` or `OpFDiv`, or a
/// `GLSL.std.450 Fma`, whose result is a 16-bit float or a vector of them ([`computes_in_16_bits`]
/// but a `Sqrt`). Metal's by the Vulkan spec under the controls the entry declares, but a driver's
/// compiler may compute it in `float` between its operands' narrowing and its result's widening and
/// leave it unrounded (Intel's Windows driver 101.2145 on a UHD Graphics 630 does), so the module
/// records `PrecisionNote::NativeHalfConversion` on every device, a static note of the rounding.
/// One pass over the instructions.
pub fn computes_half_arithmetic(m: &TypedModule) -> bool {
sixteen_bit_arithmetic(m, false)
}
/// Whether module `m` holds a 16-bit float arithmetic result: an `OpFAdd`, `OpFSub`, `OpFMul` or
/// `OpFDiv`, or a `GLSL.std.450 Fma`; and a `Sqrt` where `sqrt`, an `OpVectorTimesScalar` where
/// not.
fn sixteen_bit_arithmetic(m: &TypedModule, sqrt: bool) -> bool {
let half = |v: Value| -> bool {
let Ok(ty) = m.value(v).map(|v| v.ty) else {
return false;
@@ -1605,8 +1628,9 @@ pub fn computes_in_16_bits(m: &TypedModule) -> bool {
let arithmetic = match &n.inst {
Inst::Binary { op, .. } => {
matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv)
|| (!sqrt && *op == BinOp::VectorTimesScalar)
}
Inst::Glsl { op, .. } => matches!(op, GlslOp::Fma | GlslOp::Sqrt),
Inst::Glsl { op, .. } => *op == GlslOp::Fma || (sqrt && *op == GlslOp::Sqrt),
_ => false,
};
arithmetic && n.result.is_some_and(half)
+17 -8
View File
@@ -1531,13 +1531,16 @@ pub enum PrecisionNote {
/// MoltenVK, and any device without them. Lavapipe, without `DenormPreserve` for 16 bits,
/// computes under the other two ([`PrecisionNote::DeviceHalfDenormals`]), its pair recorded as
/// NVIDIA's is. NVIDIA's modules compute under those controls all the same: a `half` `+`,
/// `-`, `*`, `/` and `sqrt` there are the device's 16-bit instructions, whose results take
/// no such rounding. Without them Vulkan leaves the conversion's rounding mode and its 16-bit
/// denormals to the device. Also recorded under those controls on RADV where the `half` is the
/// result of an `f32` addition, subtraction, multiply or fused multiply-add: its compiler fuses
/// the operation into the conversion and rounds the exact result once, one unit in the last
/// place from
/// Metal's `half` of the `float` result where that result lies on a `half` midpoint. On a
/// `-`, `*`, `/` and `sqrt` there are the device's 16-bit instructions, between exact
/// conversions. Those instructions are Metal's by the Vulkan spec, but a driver's compiler may
/// compute them in `float` and leave them unrounded, so a module holding a 16-bit `+`, `-`,
/// `*`, `/` or fused multiply-add records this note too, on every device, a static note of the
/// rounding (a `sqrt` alone does not). Without them Vulkan leaves the conversion's rounding
/// mode and its 16-bit denormals to the device. Also recorded under those controls on RADV
/// where the `half` is the result of an `f32` addition, subtraction, multiply or fused
/// multiply-add: its compiler fuses the operation into the conversion and rounds the exact
/// result once, one unit in the last place from Metal's `half` of the `float` result where
/// that result lies on a `half` midpoint. On a
/// device `Device::from_queries` made, which reads no driver identity, every device with those
/// controls takes the pair (NVIDIA's included), and every module that rounds through it records
/// this note, a static note of the rounding: a driver's compiler may fold the pair or fuse the
@@ -1554,7 +1557,13 @@ pub enum PrecisionNote {
/// `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` too (of all 2^32
/// inputs, every `float` that is no `half` comes back unchanged); lavapipe drops it in arithmetic on Mesa 26.2.4 with
/// LLVM 23.1.1 and for a loaded texel on Mesa 26.0.8 with LLVM 21.1.8, barrier or not, whose
/// arithmetic measured rounded. The result is then the `float` computation itself: its
/// arithmetic measured rounded; Intel's Windows driver 101.2145 on a UHD Graphics 630
/// computes a 16-bit `OpFAdd`, or `Fma` of a product, decorated `NoContraction` under all
/// three 16-bit controls, in `float` between its operands' narrowing and its result's
/// widening, unrounded (a tree of three on 4,096 invocations: 2,284 sums and 4,080 products
/// matched neither the `half` tree nor the `float` tree rounded once, each printed one a
/// `float` of more significant bits than a `half` holds; the Iris Xe under Mesa ANV 26.2.6
/// gave the `half` tree on every one). The result is then the `float` computation itself: its
/// differences from Metal's compound across operations, and a value past the `half`'s range
/// stays finite until a `half` store narrows it by the device's conversion (to infinity, or
/// to 65504 rounding toward zero). The RTX 5080 Laptop GPU on the
+12 -5
View File
@@ -3136,8 +3136,9 @@ fn lower_bounded<K>(
// 16-bit arithmetic, which they make Metal's too, or read from its bits by the device's
// widening, which they make exact but for a NaN's bits: the entry declares them, and so
// requires the device's float-controls properties for them, and no fact. A driver may fold
// the round trip whatever the entry declares (NVIDIA's does): the pair's rounding is then the
// device's, the static note recorded below, and the rest is Metal's under them.
// the round trip whatever the entry declares (NVIDIA's does), or compute the 16-bit arithmetic
// in `float` unrounded (Intel's Windows driver on a UHD Graphics 630 does): the rounding is
// then the device's, the static note recorded below, and the rest is Metal's under them.
let declares_controls =
controls && (widens || crate::lower::arith::narrow::computes_in_16_bits(&module) || fused);
if declares_controls {
@@ -3153,14 +3154,20 @@ fn lower_bounded<K>(
// takes its reconvergence mode only where the module holds one in a loop a back edge re-enters
// from inside a selection.
let reconvergence = crate::lower::simd::reentry::settle(&plan.families.simd, &mut module)?;
// A `half` `+`, `-`, `*`, `/` or fused multiply-add on the device's 16-bit instructions:
// Metal's by the Vulkan spec under the controls the entry declares, but a driver's compiler may
// compute it in `float` between its operands' narrowing and its result's widening and leave it
// unrounded (Intel's Windows driver on a UHD Graphics 630 does). The module records the native
// note on every device, a static note of the rounding.
let half_arithmetic = crate::lower::arith::narrow::computes_half_arithmetic(&module);
// Native half rounding and widening: a module that rounds through the device's quantize or
// conversion, or widens a `half` by the device where that is not controlled to be Metal's,
// records each kind, and requires no fact.
// conversion, computes `half` on the device's 16-bit instructions, or widens a `half` by the
// device where that is not controlled to be Metal's, records each kind, and requires no fact.
let native_half = [
(widens, PrecisionNote::NativeNanEncoding),
(device_quantize, PrecisionNote::NativeHalfQuantize),
(
converts || native_widening || fused,
converts || native_widening || fused || half_arithmetic,
PrecisionNote::NativeHalfConversion,
),
(half_denormals, PrecisionNote::DeviceHalfDenormals),
@@ -12,11 +12,12 @@
//! and stores around it record none, but a `half` kernel's widening and rounding, which the module
//! records once by the profile's own form: its rounding's note (`narrow::native_rounding`), and
//! under the float controls `NativeHalfConversion` where the module rounds through the conversion
//! pair (`narrow::rounds_by_conversion`), which the test sets aside, and a module's widening of a
//! `half` from its bits or narrowing of one to them by the device (every profile), whose NaN's bits
//! are the device's (`narrow::widens_bits`, `narrow::encodes_bits`, `NativeNanEncoding`), and
//! without `shaderFloat16` its denormals too (`UnpackHalf2x16`, `PackHalf2x16`,
//! `NativeHalfConversion`), which the test adds to the operation's notes.
//! pair (`narrow::rounds_by_conversion`) or computes `half` arithmetic on the device's 16-bit
//! instructions (`narrow::computes_half_arithmetic`), which the test sets aside, and a module's
//! widening of a `half` from its bits or narrowing of one to them by the device (every profile),
//! whose NaN's bits are the device's (`narrow::widens_bits`, `narrow::encodes_bits`,
//! `NativeNanEncoding`), and without `shaderFloat16` its denormals too (`UnpackHalf2x16`,
//! `PackHalf2x16`, `NativeHalfConversion`), which the test adds to the operation's notes.
//!
//! `llvm-as` assembles the modules; without it the test skips visibly.
@@ -325,11 +326,12 @@ fn exported_float_notes_are_the_ones_a_compile_records() {
}
let (_, m) = typed_module(&bitcode, &k.name, p)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
// The module's rounding through the controlled conversion pair, noted on
// every device.
// The module's rounding through the controlled conversion pair, or its
// `half` arithmetic on the 16-bit instructions, noted on every device.
let fused = form == crate::spirv::builder::QuantizeForm::Controlled
&& narrow::rounds_by_conversion(&m, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
&& (narrow::rounds_by_conversion(&m, &mut meter())
.unwrap_or_else(|e| panic!("{what}: {e:?}"))
|| narrow::computes_half_arithmetic(&m));
if fused && !want.contains(&PrecisionNote::NativeHalfConversion) {
got.remove(&PrecisionNote::NativeHalfConversion);
}
@@ -715,13 +715,14 @@ fn rounding(words: &[u32]) -> Rounding {
/// modes the device's independence ties to them (`RoundingModeRTE` for 32 and 64 bits on ANV,
/// whose rounding modes are not independent; `RoundingModeRTE` and `DenormPreserve` for 64 bits on
/// RADV, independent for 32 bits only); the module requires those float-controls properties,
/// records `NativeHalfConversion` where it keeps the conversion and its widening as a pair (the
/// narrowing alone; the sum computes on 16-bit floats from the narrowings, with no pair), a static
/// note of the rounding on every device, as a driver's compiler may fold the pair or fuse the
/// arithmetic computing it into the narrowing, and passes L3. On the interpreter (whose conversion
/// rounds to nearest even) it answers Metal's `half(float)`: a tie to even, the largest half below
/// 65520 and infinity from it, a half denormal, a zero's sign, and a sum. MoltenVK, the floor and
/// Pascal's profile keep their forms.
/// records `NativeHalfConversion` for every kernel, a static note of the rounding on every device:
/// where it keeps the conversion and its widening as a pair (the narrowing alone), as a driver's
/// compiler may fold the pair or fuse the arithmetic computing it into the narrowing, and where it
/// computes on 16-bit floats from the narrowings with no pair (the sum), as a driver's compiler
/// may compute that arithmetic in `float` and leave it unrounded; and passes L3. On the
/// interpreter (whose conversion rounds to nearest even) it answers Metal's `half(float)`: a tie to
/// even, the largest half below 65520 and infinity from it, a half denormal, a zero's sign, and a
/// sum. MoltenVK, the floor and Pascal's profile keep their forms.
#[test]
fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() {
use crate::device::requirements::{FloatControl, FloatWidth};
@@ -810,9 +811,8 @@ fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() {
"{what}: {kind:?} {width:?}"
);
}
assert_eq!(
assert!(
a.precision.contains(&PrecisionNote::NativeHalfConversion),
!sum,
"{what}: {:?}",
a.precision
);
+19 -7
View File
@@ -2428,12 +2428,22 @@ category, and says what makes an operation carry the note and what may differ. E
exact result once (RADV's does, one `half` ulp from Metal's where the `float` result lies on a
`half` midpoint), so a pipeline that rounds through the pair records the note there too, a
static note of the rounding. Under those controls a `half` `+`, `-`, `*`, `/` and `sqrt` are the
device's 16-bit instructions, whose results take no such rounding. Also recorded where a `half`
read from its bits is the device's widening, or a `half` encoded to its bits (where they are not
the bits it was read from) is the device's narrowing, and that conversion is not under those
controls: the device's conversion without them, and `GLSL.std.450 UnpackHalf2x16` and
`PackHalf2x16` on every device without `shaderFloat16`. A half denormal may read or encode as the
zero of its sign.
device's 16-bit instructions between exact conversions, Metal's by the Vulkan spec, but a
driver's compiler may compute them in `float` and leave them unrounded, so a pipeline holding a
16-bit `+`, `-`, `*`, `/` or fused multiply-add records the note too, on every device, a static
note of the rounding (a `sqrt` alone does not). Intel's Windows driver 101.2145 on a UHD
Graphics 630 does so: a tree of three 16-bit `OpFAdd`s, or `Fma`s of a product, each decorated
`NoContraction` under all three 16-bit controls, on 4,096 invocations, matched neither the
`half` tree nor the `float` tree rounded once on 2,284 sums and 4,080 products, each printed one
a `float` of more significant bits than a `half` holds (job m3-max-83092; the Iris Xe under Mesa
ANV 26.2.6 gave the `half` tree on every one, job m3-max-83093). A chain the program then stores
as `half` is the `float` chain rounded once: in the runtime's quad test there, 112 of its 1,536
compared halves, by 1 code at 100 of them and by up to 40 where the operands cancel. Also
recorded where a `half` read from its bits is the device's widening, or a `half` encoded to its
bits (where they are not the bits it was read from) is the device's narrowing, and that
conversion is not under those controls: the device's conversion without them, and
`GLSL.std.450 UnpackHalf2x16` and `PackHalf2x16` on every device without `shaderFloat16`. A half
denormal may read or encode as the zero of its sign.
- `metal2vulkan-degrade-device-half-denormals` (precision). `PrecisionNote::DeviceHalfDenormals`:
half denormals may flush to zero where Metal preserves them. The module computes `half` under
the 16-bit float controls on a device that offers `shaderFloat16` with 16-bit `RoundingModeRTE`
@@ -2442,7 +2452,9 @@ category, and says what makes an operation carry the note and what may differ. E
the device's 16-bit instructions, its `half` values are held at 16 bits, a `float` rounds to
`half` through the conversion and its widening, and a `half` widens from and narrows to its bits
by the device's conversion, each Metal's but for a half denormal (a magnitude below `2^-14`),
operand or result, which the device may read or answer as the zero of its sign. Recorded by
operand or result, which the device may read or answer as the zero of its sign (and but for the
rounding `metal2vulkan-degrade-native-half-conversion` records for the 16-bit arithmetic and
the conversion pair). Recorded by
every module that declares those controls on such a device, and by no other: a device with
16-bit `DenormPreserve` declares it too and records nothing, and a device lacking another
control computes `half` in `float` (`metal2vulkan-degrade-native-half-conversion`,
+2 -1
View File
@@ -617,7 +617,8 @@ cargo run -p metal2vulkan-validation --release --bin corpus-vulkan -- \
it. What reaches a word is read from the case's AIR: the float lanes the word holds, and the
operation families whose results feed it (float arithmetic, division, fused multiply-add, `dot`,
`mix`, minimum and maximum, other functions, packs, textures, group operations, stage inputs,
and a store another thread of the kernel may make there). A note of the module whose entry
`half` operations and conversions to or from `half`, and a store another thread of the kernel
may make there). A note of the module whose entry
writes the output reaches the words its operations feed; a note of any other module reaches
every word, and so does every note of a word the scan cannot follow (a load of memory the
function writes, a call outside the intrinsic families). A note with a bound (a lane table, the