Compute half + - * and fma in 16 bits under the 16-bit float controls

On a device whose half roundings take the 16-bit float controls (RoundingModeRTE, DenormPreserve
and SignedZeroInfNanPreserve for 16 bits with shaderFloat16: ANV and RADV among the committed
profiles), a half + - * is now the device's 16-bit OpFAdd, OpFSub or Fma(a, b, -0.0), kept apart,
between exact conversions (ops::f16_binary, the form the measured MoltenVK fact already takes).
Where shaderFmaFloat16 is enabled too, a half fused multiply-add is OpFmaKHR on 16 bits (new
fma::Route::F16Khr), under either policy. Elsewhere the f32 operation and its rounding pair, the
round-to-odd routine and native device maths' Fma stay as they were.

Exact: Vulkan's precision table lists OpFAdd, OpFSub and OpFMul for half precision, and OpFmaKHR,
as correctly rounded, to nearest even under RoundingModeRTE, with denormals kept under
DenormPreserve and zero signs under SignedZeroInfNanPreserve, the modes the entry declares where it
computes in 16 bits (narrow::computes_in_16_bits). That is Metal's half arithmetic and Metal's
half fma, which the round-to-odd routine emulated. A NaN's bits are the device's, as the
controlled rounding's already are; Metal's NaN is selected around the instruction where the
profile asks for it. The half fma under native device maths no longer records NativeFma there.

Why: the device's compiler spent most of a large half fragment function's making on the f32 ->
f16 -> f32 rounding pairs, most of which follow a + - * or a fused multiply-add. On ANV a
consumer's largest fragment library made in about 4 s, and about 2.2 s without its rounding pairs.

New: VkFeature::ShaderFmaFloat16 (the Khronos table, enables, the ash and runtime feature chains,
derivation, the codec), OpFmaKHR's feature by its operands' width, the builder's OpFmaKHR on 16-bit
floats, and the owned fixture engine/hfb_filter_bank (a 32-case switch of runtime-sampler tap
loops and half arithmetic chains) with its engine inventory rows. The validation engine's enable
list enables shaderFmaFloat16 from VkPhysicalDeviceShaderFmaFeaturesKHR beside shaderFmaFloat32,
and the opened-chains pin records it for the profiles that list it. Docs: docs/FAST-PATHS.md's half
rounding row, and the NativeFma notice in artifact.rs and docs/API.md.

Verified, as the commits state:
- On the UHD 770 (ANV, Mesa 26.2.4) the fixture's fragment library made in 1.74-1.89 s against
  4.64-5.26 s before (3 alternating rounds, no driver caches), SIMD8 instructions 25,902 ->
  18,736, translation 0.17 s release; driver_deviations::half_arithmetic_answers_as_metal passes
  there.
- On the UHD 770 in the release m2v_gpu build, the groups that failed before the engine enabled
  the feature pass: candidate engine runs, platform enables and device, engine_render,
  engine_compute, engine_textures, acceptance_pipelines, the runtime lanes kernel_textures,
  sparse_textures, renders, argument_buffers and runtime_probe, and the half and fma driver
  deviations.
- Debug translator tests: engine_arith, lower::arith, the fma, derivation, device, ash_interop,
  cache and fast_paths tests, and the engine inventory's llvm_as parts; engine_native_half
  (counting the 16-bit operations and their exact conversions) and engine_spirv_cross_forms (no
  NativeFma where the half fma route is F16Khr), with fused and engine_arith, 213 passed.
- clippy of metal2vulkan.
This commit is contained in:
Anees Iqbal committed 2026-10-19 00:16:00 +03:00
1 parent b6addb96c0
commit d77bd86377
35 files changed
+18104 -123

No files matched your search

@@ -751,6 +751,7 @@ members! {
RasterOrder.raster_order.rasterization_order_depth_attachment_access => RasterizationOrderDepthAttachmentAccess;
RasterOrder.raster_order.rasterization_order_stencil_attachment_access => RasterizationOrderStencilAttachmentAccess;
Maintenance8.maintenance8.maintenance8 => Maintenance8;
ShaderFma.shader_fma.shader_fma_float16 => ShaderFmaFloat16;
ShaderFma.shader_fma.shader_fma_float32 => ShaderFmaFloat32;
Maintenance5.maintenance5.maintenance5 => Maintenance5;
BorderColorSwizzle.border_color_swizzle.border_color_swizzle => BorderColorSwizzle;
@@ -113,6 +113,7 @@ fixture gsm2_helper_threads_msl22: metal: Apple metal version 32023.921 (metalfe
fixture gsm2_helper_threads: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture gsm2_quad_ops: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture gsm2_simd_products: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture hfb_filter_bank: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture hlf_float_linear: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture hlf_float_read: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
fixture hlf_half_access: metal: Apple metal version 32023.921 (metalfe-32023.921.6); macosx-sdk: 27.0 (26A425)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,118 @@
// Owned fixture: a large `half` fragment function, for the size of its translation and the time a
// device's compiler takes to make its fragment library. A pass mode (`HfbParams::mode`) picks one
// of 32 filters in a switch; each filter loops over its taps, eight samples of a texture through a
// runtime sampler an iteration, accumulated by `half` fused multiply-adds, and then runs chains of
// `half` arithmetic (products kept apart, sums, differences, clamps, floors, maxima). Every filter
// differs in its constants, so no compiler merges two. `hfb_quad` draws the full-target triangle
// the fragment function runs over.
//
// Written for this repository; no third-party source.
#include <metal_stdlib>
using namespace metal;
struct HfbIn {
float4 position [[position]];
float2 uv;
};
struct HfbParams {
uint mode;
uint taps;
float2 texel;
half4 tint;
half4 lift;
half gain;
half bias;
};
// The triangle over the whole target, its texture coordinates over the unit square.
vertex HfbIn hfb_quad(uint vid [[vertex_id]]) {
float2 corner = float2(vid == 1u ? 2.0f : 0.0f, vid == 2u ? 2.0f : 0.0f);
HfbIn out;
out.position = float4(corner * 2.0f - 1.0f, 0.0f, 1.0f);
out.uv = corner;
return out;
}
// One tap: the sample at `uv + o * texel` weighted by `w` into `acc`.
#define HFB_TAP(acc, o, w) acc = fma(src.sample(smp, uv + (o) * p.texel), half4(w), acc)
// A chain of `half` arithmetic on `v`: the product `t0` is used twice, so it stays its own
// rounding; `t1 * x + y` fuses.
#define HFB_STAGE(v, k, s) \
{ \
half4 t0 = v * v; \
half4 t1 = t0 * v; \
v = v - t1 * half(0.1h + half(k & 3) * 0.01h + half(s) * 0.003h) \
+ t0 * half(0.05h + half(s) * 0.002h); \
v = clamp(v * p.gain + p.bias, half4(-2.0h), half4(2.0h + half(k & 1))); \
v = floor(v * half(16 + s)) * half(1.0h / half(16 + s)) + t0 * 0.001h; \
v = max(v, t0 - half4(1.0h)) * p.tint + p.lift * half(0.25h * half(s)); \
v = v - t0 * t1 + t0; \
}
// Filter `k`: its loop of taps, then three chains and one more sample.
#define HFB_CASE(k) \
case k: { \
half4 acc = half4(0.0h); \
for (uint i = 0; i < p.taps; i++) { \
float d = float(i) + 0.5f + 0.125f * float(k % 5); \
HFB_TAP(acc, float2(d, 0.0f), 0.0625h + half(k) * 0.001h); \
HFB_TAP(acc, float2(-d, 0.0f), 0.0625h - half(k) * 0.0007h); \
HFB_TAP(acc, float2(0.0f, d), 0.05h + half(k & 7) * 0.002h); \
HFB_TAP(acc, float2(0.0f, -d), 0.05h - half(k & 3) * 0.001h); \
HFB_TAP(acc, float2(d, d), 0.03h + half(k) * 0.0005h); \
HFB_TAP(acc, float2(-d, d), 0.03h); \
HFB_TAP(acc, float2(d, -d), 0.03h - half(k) * 0.0003h); \
HFB_TAP(acc, float2(-d, -d), 0.03h + half(k & 1) * 0.004h); \
acc = clamp(acc * p.gain + p.bias, half4(0.0h), half4(4.0h)); \
} \
HFB_STAGE(acc, k, 1) \
HFB_STAGE(acc, k, 2) \
HFB_STAGE(acc, k, 3) \
HFB_TAP(acc, float2(0.5f * float(k), 0.25f), 0.125h + half(k) * 0.002h); \
c = acc; \
} break;
fragment half4 hfb_filter_bank(HfbIn in [[stage_in]],
texture2d<half> src [[texture(0)]],
sampler smp [[sampler(0)]],
constant HfbParams &p [[buffer(0)]]) {
float2 uv = in.uv;
half4 c = half4(0.0h);
switch (p.mode & 31u) {
HFB_CASE(0)
HFB_CASE(1)
HFB_CASE(2)
HFB_CASE(3)
HFB_CASE(4)
HFB_CASE(5)
HFB_CASE(6)
HFB_CASE(7)
HFB_CASE(8)
HFB_CASE(9)
HFB_CASE(10)
HFB_CASE(11)
HFB_CASE(12)
HFB_CASE(13)
HFB_CASE(14)
HFB_CASE(15)
HFB_CASE(16)
HFB_CASE(17)
HFB_CASE(18)
HFB_CASE(19)
HFB_CASE(20)
HFB_CASE(21)
HFB_CASE(22)
HFB_CASE(23)
HFB_CASE(24)
HFB_CASE(25)
HFB_CASE(26)
HFB_CASE(27)
HFB_CASE(28)
HFB_CASE(29)
HFB_CASE(30)
HFB_CASE(31)
}
return c;
}
@@ -1102,6 +1102,7 @@ members! {
RasterOrder.raster_order.rasterization_order_stencil_attachment_access =>
Some(F::RasterizationOrderStencilAttachmentAccess);
Maintenance8.maintenance8.maintenance8 => Some(F::Maintenance8);
ShaderFma.shader_fma.shader_fma_float16 => Some(F::ShaderFmaFloat16);
ShaderFma.shader_fma.shader_fma_float32 => Some(F::ShaderFmaFloat32);
FloatControls2.float_controls2.shader_float_controls2 => None;
Maintenance5.maintenance5.maintenance5 => Some(F::Maintenance5);
@@ -1,3 +1,15 @@
amd-780m-radv device Stated 0cc531dd635d7d82e73477489d07ce6ba405d531fa5683c335770b23b77edd67 members=142 extensions=47
amd-780m-radv device RobustnessOff f33782de62b710a0814dcb662ebdfb6f7de6706f24985ff41e1341d06f532f4d members=138 extensions=47
amd-780m-radv restricted Stated 1b5f9f1fc3798e0010ad6acb6b78e91a8776a453fbd5c2cab55734b5112f74f4 members=141 extensions=29
amd-780m-radv restricted RobustnessOff 07e19d701860f12bce0b1e49c8c8e29191c2675038a795f2da8b226eebc2e514 members=137 extensions=29
amd-rdna2-apu-radv device Stated b76f37f55200d1fced399f18d8fe0475891f9b6cf2226e06724cd8b42d1dcc76 members=143 extensions=47
amd-rdna2-apu-radv device RobustnessOff e2e16838fd44bdb782ce48775d8355f53c9aed2b84f9ce0718bfd134e62c7c4c members=139 extensions=47
amd-rdna2-apu-radv restricted Stated 13caf55aab9e1c9666affed572011479938670505a4a2f365d9631d0052ec4d0 members=142 extensions=29
amd-rdna2-apu-radv restricted RobustnessOff 2b63ab2428b460150ce4118b9071bf2b5c67488071187011750cfbb1acef10a0 members=138 extensions=29
amd-rdna3-radv device Stated 0cc531dd635d7d82e73477489d07ce6ba405d531fa5683c335770b23b77edd67 members=142 extensions=47
amd-rdna3-radv device RobustnessOff f33782de62b710a0814dcb662ebdfb6f7de6706f24985ff41e1341d06f532f4d members=138 extensions=47
amd-rdna3-radv restricted Stated 1b5f9f1fc3798e0010ad6acb6b78e91a8776a453fbd5c2cab55734b5112f74f4 members=141 extensions=29
amd-rdna3-radv restricted RobustnessOff 07e19d701860f12bce0b1e49c8c8e29191c2675038a795f2da8b226eebc2e514 members=137 extensions=29
gate-lavapipe device Stated a1c8cb8a8f52f3b551a37fc379805f3efa45b9e9249a016eb0a304c1938c0769 members=139 extensions=44
gate-lavapipe device RobustnessOff 7e77da3e144cb073d55ba58c930ad035c54f1a8776f8c78b30d73144f1c9b906 members=135 extensions=44
gate-lavapipe restricted Stated 259dd14f4c73f675744f93724edeee7daf175f02da3b05611ff848b750c7c683 members=138 extensions=26
@@ -6,6 +18,22 @@ gate-lavapipe-x86_64 device Stated a1c8cb8a8f52f3b551a37fc379805f3efa45b9e9249a0
gate-lavapipe-x86_64 device RobustnessOff 7e77da3e144cb073d55ba58c930ad035c54f1a8776f8c78b30d73144f1c9b906 members=135 extensions=44
gate-lavapipe-x86_64 restricted Stated 259dd14f4c73f675744f93724edeee7daf175f02da3b05611ff848b750c7c683 members=138 extensions=26
gate-lavapipe-x86_64 restricted RobustnessOff 71ad847017a2e5b5f9611f81943bc4ddeff7067b2ac04252fec17ba5ba448809 members=134 extensions=26
intel-arl-anv device Stated cb9e4b907a81bd6dc754581a08efbab5a667af40f782758914fb09bbaac38577 members=141 extensions=45
intel-arl-anv device RobustnessOff 97e150de6bb0cc7652dcdf6809230b487429f6bfbd4a30badd106e00ebfdb487 members=137 extensions=45
intel-arl-anv restricted Stated 22a946c2c1a345e47a1c2425f714ee5e49c59562cefd2a7570380753e8ee5abc members=140 extensions=27
intel-arl-anv restricted RobustnessOff 8c79afd1fd77f53e199c0f11d7afd81b25d793e280c53f1450ad239b8a575309 members=136 extensions=27
intel-irisxe-anv device Stated e5c10329557a57ed0a95bfa3d127331fe8612a79291eb7046407f49655007174 members=128 extensions=41
intel-irisxe-anv device RobustnessOff 1320d61dd3886a50881d42fd799ab9cbb35849d7b10db21bf514e5671ce641de members=124 extensions=41
intel-irisxe-anv restricted Stated e6a13df8106972a9adb8dc93f6be5ee8ce0871842614a0bfa8a49d34c69184fb members=127 extensions=23
intel-irisxe-anv restricted RobustnessOff 9ac5e8302022bcc1a32e81e0239936cb54b9f662cd3e141ebe2873e004ed9c5e members=123 extensions=23
intel-irisxe-rplp-anv device Stated e5c10329557a57ed0a95bfa3d127331fe8612a79291eb7046407f49655007174 members=128 extensions=41
intel-irisxe-rplp-anv device RobustnessOff 1320d61dd3886a50881d42fd799ab9cbb35849d7b10db21bf514e5671ce641de members=124 extensions=41
intel-irisxe-rplp-anv restricted Stated e6a13df8106972a9adb8dc93f6be5ee8ce0871842614a0bfa8a49d34c69184fb members=127 extensions=23
intel-irisxe-rplp-anv restricted RobustnessOff 9ac5e8302022bcc1a32e81e0239936cb54b9f662cd3e141ebe2873e004ed9c5e members=123 extensions=23
intel-uhd770-rpls-anv device Stated e5c10329557a57ed0a95bfa3d127331fe8612a79291eb7046407f49655007174 members=128 extensions=41
intel-uhd770-rpls-anv device RobustnessOff 1320d61dd3886a50881d42fd799ab9cbb35849d7b10db21bf514e5671ce641de members=124 extensions=41
intel-uhd770-rpls-anv restricted Stated e6a13df8106972a9adb8dc93f6be5ee8ce0871842614a0bfa8a49d34c69184fb members=127 extensions=23
intel-uhd770-rpls-anv restricted RobustnessOff 9ac5e8302022bcc1a32e81e0239936cb54b9f662cd3e141ebe2873e004ed9c5e members=123 extensions=23
lavapipe device Stated a1c8cb8a8f52f3b551a37fc379805f3efa45b9e9249a016eb0a304c1938c0769 members=139 extensions=44
lavapipe device RobustnessOff 7e77da3e144cb073d55ba58c930ad035c54f1a8776f8c78b30d73144f1c9b906 members=135 extensions=44
lavapipe restricted Stated 259dd14f4c73f675744f93724edeee7daf175f02da3b05611ff848b750c7c683 members=138 extensions=26
@@ -14,18 +42,26 @@ lunarg-desktop-baseline-2023 device Stated 874afb3cbcd8a813f7d1dffaf2b3108c612fa
lunarg-desktop-baseline-2023 device RobustnessOff 3d72e0d627ce569a8a6750f24d89b3d1afc4b2c175c30ddb66428a92fdc37584 members=53 extensions=5
lunarg-desktop-baseline-2023 restricted Stated 874afb3cbcd8a813f7d1dffaf2b3108c612fa8910dee201427eeec23b291383a members=56 extensions=5
lunarg-desktop-baseline-2023 restricted RobustnessOff 3d72e0d627ce569a8a6750f24d89b3d1afc4b2c175c30ddb66428a92fdc37584 members=53 extensions=5
moltenvk-m3 device Stated 5472a8522c4d442b37c18839e5e2bcba4bfdf3c33f371a80773473c9462fbdec members=113 extensions=34
moltenvk-m3 device RobustnessOff 503ff67e7aac3df8846d123d8284d0d6341092fb35813dc19a8f4dff8b3dae70 members=110 extensions=34
moltenvk-m3 restricted Stated 2bc2afb190da2862d60f3b2704519d23f731955b139577cd4f7f3c664361f6c6 members=111 extensions=15
moltenvk-m3 restricted RobustnessOff 0158036adc6c623fddbd24085ada8feb6d4f2e1257d66aed0527e99a1bc82753 members=108 extensions=15
moltenvk-m4 device Stated 5472a8522c4d442b37c18839e5e2bcba4bfdf3c33f371a80773473c9462fbdec members=113 extensions=34
moltenvk-m4 device RobustnessOff 503ff67e7aac3df8846d123d8284d0d6341092fb35813dc19a8f4dff8b3dae70 members=110 extensions=34
moltenvk-m4 restricted Stated 2bc2afb190da2862d60f3b2704519d23f731955b139577cd4f7f3c664361f6c6 members=111 extensions=15
moltenvk-m4 restricted RobustnessOff 0158036adc6c623fddbd24085ada8feb6d4f2e1257d66aed0527e99a1bc82753 members=108 extensions=15
nvidia-pascal-linux device Stated 435f6082527ee3bc09c5445c399dde4f5760ebdbfb86d993506f8d0e5ea0654e members=128 extensions=37
nvidia-pascal-linux device RobustnessOff 77f450c5aad37db19d52ee6df004e767d1a0a1341708ecd5b93804c68468b3d2 members=124 extensions=37
nvidia-pascal-linux restricted Stated 649cabe33b51c8b1345c1144f6ba1232aba48a021381b11b3131fef26c0c92b5 members=127 extensions=19
nvidia-pascal-linux restricted RobustnessOff 13271c88375fe5daa18c52337b3b46584f40e81c5737f5109403345d6bcad309 members=123 extensions=19
nvidia-rtx50-linux device Stated 2783205fec5c67405a65e21fcefabd9ead9b23d0be560d49ee22ab7c1458db36 members=139 extensions=44
nvidia-rtx50-linux device RobustnessOff a77a5aa2fc03ec1de7c3a985b7f9e2d9695b7cb2191021a38fca9ededa8d1a59 members=135 extensions=44
nvidia-rtx50-linux restricted Stated d8e7c3aa62da331a03997a65a418b45be5b7e8d1e41049c8a3e7558588d6938d members=138 extensions=27
nvidia-rtx50-linux restricted RobustnessOff 6ed2d128b2eefd0cdad09c2432fa943d986e27a3cbb26ef1102977297eb38e2b members=134 extensions=27
nvidia-rtx5080-laptop device Stated 2783205fec5c67405a65e21fcefabd9ead9b23d0be560d49ee22ab7c1458db36 members=139 extensions=44
nvidia-rtx5080-laptop device RobustnessOff a77a5aa2fc03ec1de7c3a985b7f9e2d9695b7cb2191021a38fca9ededa8d1a59 members=135 extensions=44
nvidia-rtx5080-laptop restricted Stated d8e7c3aa62da331a03997a65a418b45be5b7e8d1e41049c8a3e7558588d6938d members=138 extensions=27
nvidia-rtx5080-laptop restricted RobustnessOff 6ed2d128b2eefd0cdad09c2432fa943d986e27a3cbb26ef1102977297eb38e2b members=134 extensions=27
nvidia-rtx50-linux device Stated a5ac45edd9b82e1a2abb93f299480e4e1facbfa5aab8a5a1660a61a11449351d members=140 extensions=45
nvidia-rtx50-linux device RobustnessOff b35ed123271a2bfb2f52047b610f3c2239703b1ba38fb5ea590ace146943a3b4 members=136 extensions=45
nvidia-rtx50-linux restricted Stated da49a0b31d535cc4e3ee98796915342db1f1484b6538f7fad8c0ff5e059eba29 members=139 extensions=27
nvidia-rtx50-linux restricted RobustnessOff 59b0405779a2fd38ca3fb3c93bc8784ebc8395fa3b04dbb1bf2dd7aba86d7ecb members=135 extensions=27
nvidia-rtx5080-laptop device Stated a5ac45edd9b82e1a2abb93f299480e4e1facbfa5aab8a5a1660a61a11449351d members=140 extensions=45
nvidia-rtx5080-laptop device RobustnessOff b35ed123271a2bfb2f52047b610f3c2239703b1ba38fb5ea590ace146943a3b4 members=136 extensions=45
nvidia-rtx5080-laptop restricted Stated da49a0b31d535cc4e3ee98796915342db1f1484b6538f7fad8c0ff5e059eba29 members=139 extensions=27
nvidia-rtx5080-laptop restricted RobustnessOff 59b0405779a2fd38ca3fb3c93bc8784ebc8395fa3b04dbb1bf2dd7aba86d7ecb members=135 extensions=27
roadmap-2022 device Stated ea14a46708f56d5478ab06ec0852c15420809b3e7d942a028f6d6289a46e12fd members=42 extensions=1
roadmap-2022 device RobustnessOff bea5bd603a66d567ab6f940ab92a878cf3d449d44d4ca8e300ef41956271b1cb members=41 extensions=1
roadmap-2022 restricted Stated dc3f83af671640f6f93547f5e595a81efd20e15be8b01b66847fddba2db1332c members=51 extensions=1
@@ -771,6 +771,7 @@ feature_sources! { c, x;
ImageView2DOn3DImage => on(c.portability_subset.image_view2_d_on3_d_image);
SeparateStencilMaskRef => on(c.portability_subset.separate_stencil_mask_ref);
ImageViewFormatSwizzle => on(c.portability_subset.image_view_format_swizzle);
ShaderFmaFloat16 => on(c.shader_fma.shader_fma_float16);
ShaderFmaFloat32 => on(c.shader_fma.shader_fma_float32);
Maintenance5 => on(c.maintenance5.maintenance5);
TaskShader => on(c.mesh_shader.task_shader);
@@ -572,6 +572,7 @@ fn unexposed_structures_are_never_chained() {
VkFeature::ExtendedDynamicState2,
VkFeature::ShaderSubgroupRotate,
VkFeature::Maintenance8,
VkFeature::ShaderFmaFloat16,
VkFeature::ShaderFmaFloat32,
VkFeature::Maintenance5,
VkFeature::DepthBiasControl,
+1
View File
@@ -926,6 +926,7 @@ codec_enum! {
ShaderQuadControl,
ShaderTessellationAndGeometryPointSize, MultiviewGeometryShader,
AttachmentFeedbackLoopLayout, ExtendedDynamicState3ColorWriteMask,
ShaderFmaFloat16,
}
VkExtension {
ExtRobustness2, ExtImageRobustness, ExtShaderAtomicFloat, ExtShaderAtomicFloat2,
+1
View File
@@ -255,6 +255,7 @@ fn derive_fields(
fragment_stores_and_atomics: has(VkFeature::FragmentStoresAndAtomics),
zero_initialize_workgroup_memory: has(VkFeature::ShaderZeroInitializeWorkgroupMemory),
fma32: has(VkFeature::ShaderFmaFloat32),
fma16: has(VkFeature::ShaderFmaFloat16),
};
let images = ImageCaps {
storage_read_without_format: has(VkFeature::ShaderStorageImageReadWithoutFormat),
+1 -1
View File
@@ -286,7 +286,7 @@ exposures! {
Extension(&[E::KhrShaderSubgroupUniformControlFlow]) => [ShaderSubgroupUniformControlFlow];
Extension(DERIVATIVES) => [ComputeDerivativeGroupQuads, ComputeDerivativeGroupLinear];
Extension(&[E::KhrMaintenance8]) => [Maintenance8];
Extension(&[E::KhrShaderFma]) => [ShaderFmaFloat32];
Extension(&[E::KhrShaderFma]) => [ShaderFmaFloat16, ShaderFmaFloat32];
Extension(BORDER_SWIZZLE) => [BorderColorSwizzle, BorderColorSwizzleFromImage];
Extension(&[E::ExtDepthBiasControl]) => [DepthBiasControl, FloatRepresentation, DepthBiasExact];
Extension(&[E::ExtDepthClipEnable]) => [DepthClipEnable];
@@ -1530,6 +1530,7 @@ pub(super) const FEATURE_MEMBERS: &[(&str, VkFeature)] = {
("depthBiasControl", F::DepthBiasControl),
("floatRepresentation", F::FloatRepresentation),
("depthBiasExact", F::DepthBiasExact),
("shaderFmaFloat16", F::ShaderFmaFloat16),
("shaderFmaFloat32", F::ShaderFmaFloat32),
("synchronization2", F::Synchronization2),
("extendedDynamicState", F::ExtendedDynamicState),
@@ -817,6 +817,8 @@ pub struct LeafCaps {
pub zero_initialize_workgroup_memory: bool,
/// `OpFmaKHR` on 32-bit floats (`shaderFmaFloat32`): a correctly rounded fused multiply-add.
pub fma32: bool,
/// `OpFmaKHR` on 16-bit floats (`shaderFmaFloat16`): a correctly rounded fused multiply-add.
pub fma16: bool,
}
/// Image and sampler capabilities ([`DeviceProfile::images`]). Each field without its own note is
@@ -316,6 +316,11 @@ pub enum VkFeature {
/// `VK_EXT_extended_dynamic_state3`'s `extendedDynamicState3ColorWriteMask`: the dynamic
/// state `VK_DYNAMIC_STATE_COLOR_WRITE_MASK_EXT`, set by `vkCmdSetColorWriteMaskEXT`.
ExtendedDynamicState3ColorWriteMask,
// Appended.
/// `VK_KHR_shader_fma`'s `shaderFmaFloat16`: `OpFmaKHR` on 16-bit floats
/// (`VUID-RuntimeSpirv-shaderFmaFloat16-10977`), which Vulkan's precision table makes correctly
/// rounded: a `half` fused multiply-add in one instruction under the 16-bit float controls.
ShaderFmaFloat16,
}
/// A Vulkan device extension the new core can require.
+12 -6
View File
@@ -114,9 +114,12 @@ impl Path {
pub fn on(p: &DeviceProfile) -> Path {
match fma::float_route(p) {
Route::Khr => Path::Fused,
Route::Wide | Route::Soft | Route::HalfOdd | Route::F16 | Route::Native => {
Path::Integer
}
Route::Wide
| Route::Soft
| Route::HalfOdd
| Route::F16
| Route::F16Khr
| Route::Native => Path::Integer,
}
}
}
@@ -291,9 +294,12 @@ impl Reciprocal {
pub fn of(route: Route) -> Reciprocal {
match route {
Route::Khr => Reciprocal::Rounded,
Route::Wide | Route::Soft | Route::HalfOdd | Route::F16 | Route::Native => {
Reciprocal::Device
}
Route::Wide
| Route::Soft
| Route::HalfOdd
| Route::F16
| Route::F16Khr
| Route::Native => Reciprocal::Device,
}
}
+49 -12
View File
@@ -62,6 +62,19 @@
//! a few instructions per use and no routine, where MoltenVK inlines [`Route::HalfOdd`]'s routine
//! at every call and Metal's back end compiles each copy: one corpus kernel with 800 `half` fused
//! multiply-adds took 6 s to create through the routine.
//!
//! Where the profile has `shaderFmaFloat16` and rounds to `half` under the 16-bit float controls
//! ([`QuantizeForm::Controlled`], [`narrow::controlled_modes`]), a `half` one takes
//! [`Route::F16Khr`]: its operands convert to 16 bits exactly, `OpFmaKHR` on them rounds the exact
//! sum once, and its result widens exactly. Vulkan's precision table lists `OpFmaKHR` as "Correctly
//! rounded", "according to IEEE 754 roundTiesToEven" under `RoundingModeRTE`, with denormals kept
//! under `DenormPreserve` and zero signs under `SignedZeroInfNanPreserve`, which the entry then
//! declares (`narrow::computes_in_16_bits`): the one rounding [`Route::HalfOdd`]'s round-to-odd
//! sequence emulates, and Metal's `half` `fma`, with no fact. A NaN's bits are the device's, as the
//! controlled rounding's are; a fused pair's NaN is selected as on every route
//! (`super::contract`). It replaces that sequence, or native device maths' `float` `Fma` and its
//! rounding to `half` ([`Route::Native`], noted `NativeFma`), with one instruction whose
//! conversions the device folds into its neighbours'.
use crate::device::profile::FloatFunctions;
use crate::device::DeviceProfile;
@@ -90,6 +103,9 @@ pub enum Route {
/// A `half` fused multiply-add by the device's `Fma` on 16-bit floats, Metal's own
/// ([`half_route`]).
F16,
/// A `half` fused multiply-add by `OpFmaKHR` on 16-bit floats under the 16-bit float
/// controls, correctly rounded by the Vulkan spec ([`half_route`]).
F16Khr,
/// Native device maths (`FloatFunctions::Native`): the device's `GLSL.std.450 Fma` on the
/// `float` lanes (a `half`'s held in `float`, its result rounded to `half`), within
/// Vulkan's precision rather than rounded once (`PrecisionNote::NativeFma`).
@@ -118,6 +134,8 @@ pub const HALF: &str = "arith.fma.half";
/// See [`KHR`].
pub const F16: &str = "arith.fma.f16";
/// See [`KHR`].
pub const F16_KHR: &str = "arith.fma.f16.khr";
/// See [`KHR`].
pub const NATIVE: &str = "arith.fma.native";
/// Every route [`float_route`] answers, which the tests run each of.
@@ -163,11 +181,15 @@ pub fn tiny_route(p: &DeviceProfile) -> Option<Route> {
/// The `half` route profile `p` offers: [`Route::F16`] where the driver is measured to compute a
/// 16-bit `Fma` as Metal's own `half` `fma` (`DriverDeviation::MetalHalfFma`) and `shaderFloat16`
/// is enabled, else the device's `float` `Fma` rounded to `half` under native device maths, else
/// is enabled, else [`Route::F16Khr`] where `shaderFmaFloat16` is and the profile rounds to `half`
/// under the 16-bit float controls (which need `shaderFloat16`), under either policy since it is
/// Metal's, else the device's `float` `Fma` rounded to `half` under native device maths, else
/// [`Route::HalfOdd`].
pub fn half_route(p: &DeviceProfile) -> Route {
if p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && p.fields().leaf.float16 {
Route::F16
} else if p.fields().leaf.fma16 && narrow::quantize_form(p) == QuantizeForm::Controlled {
Route::F16Khr
} else if p.fields().float_functions == FloatFunctions::Native {
Route::Native
} else {
@@ -249,7 +271,7 @@ impl Fma {
(Route::Wide | Route::Soft | Route::HalfOdd, _) => self.route,
(Route::Khr, Some(Route::Wide)) => Route::Khr,
(Route::Khr, Some(tiny)) => tiny,
(Route::Khr | Route::F16 | Route::Native, _) => return None,
(Route::Khr | Route::F16 | Route::F16Khr | Route::Native, _) => return None,
};
Some(Routine {
route,
@@ -266,12 +288,14 @@ impl Fma {
Route::Soft => SOFT,
Route::HalfOdd => HALF,
Route::F16 => F16,
Route::F16Khr => F16_KHR,
Route::Native => NATIVE,
}
}
/// An upper estimate of the SPIR-V words per use: the instruction or the call; on
/// [`Route::F16`] the three conversions, the instruction and the widening; checked
/// [`Route::F16`] and [`Route::F16Khr`] the three conversions, the instruction and the
/// widening; checked
/// ([`checked`]), the instruction, the test of its magnitude, the selection, the call and the
/// merge. A routine's own words are the module's, charged once ([`Routine::words`]).
pub fn words(self) -> u32 {
@@ -279,7 +303,7 @@ impl Fma {
Route::Khr if self.checked() => 112,
Route::Khr => 16,
Route::Wide | Route::Soft | Route::HalfOdd => 24,
Route::F16 => 32,
Route::F16 | Route::F16Khr => 32,
// The instruction, and a `half` result's rounding.
Route::Native => 64,
}
@@ -450,7 +474,9 @@ pub fn define(mb: &mut ModuleBuilder, r: Routine) -> BResult<FuncId> {
let s = half_sum(&mut fb, h, a, b, c)?;
narrow::round(&mut fb, h, s)?
}
Route::F16 | Route::Native => return Err(BuildError::Type(TypeRule::FunctionSignature)),
Route::F16 | Route::F16Khr | Route::Native => {
return Err(BuildError::Type(TypeRule::FunctionSignature))
}
};
fb.ret(Some(v))?;
fb.finish()
@@ -500,7 +526,8 @@ pub fn emit(
| (Route::Khr | Route::Wide | Route::Soft, Some(FloatFmt::F32)) => {
float(fb, fma, a, b, c, routine)
}
(Route::F16, Some(FloatFmt::Half)) => f16(fb, fma.form.lanes, a, b, c),
(Route::F16, Some(FloatFmt::Half)) => f16(fb, fma.form.lanes, [a, b, c], false),
(Route::F16Khr, Some(FloatFmt::Half)) => f16(fb, fma.form.lanes, [a, b, c], true),
// Native device maths: the device's `Fma`; on `half` operands held in `float` the product
// is exact, so only the sum's rounding and the rounding to `half` differ from Metal's one
// rounding.
@@ -514,11 +541,17 @@ pub fn emit(
}
/// The `half` fused multiply-add of `a`, `b`, `c` (`half` values held in `float` lanes of
/// `lanes` lanes) by the device's `Fma` on 16-bit floats ([`Route::F16`]): each operand converted
/// to 16 bits, exactly since it is a `half`, the `Fma`, and its result widened, exactly. The
/// device rounds the exact sum once, as Metal's `half` `fma` does where the profile takes
/// `DriverDeviation::MetalHalfFma`.
fn f16(fb: &mut FunctionBuilder<'_>, lanes: u8, a: Value, b: Value, c: Value) -> BResult<Value> {
/// `lanes` lanes) by the device's `Fma` on 16-bit floats ([`Route::F16`]), or by `OpFmaKHR` on
/// them where `khr` ([`Route::F16Khr`]): each operand converted to 16 bits, exactly since it is a
/// `half`, the instruction, and its result widened, exactly. The device rounds the exact sum once,
/// as Metal's `half` `fma` does: measured where the profile takes `DriverDeviation::MetalHalfFma`,
/// by the Vulkan spec for `OpFmaKHR` under the 16-bit float controls.
fn f16(
fb: &mut FunctionBuilder<'_>,
lanes: u8,
[a, b, c]: [Value; 3],
khr: bool,
) -> BResult<Value> {
let lanes_of = |fb: &mut FunctionBuilder<'_>, width: u8| -> BResult<_> {
let e = fb.module().ty(Type::Float { width })?;
match lanes {
@@ -529,7 +562,11 @@ fn f16(fb: &mut FunctionBuilder<'_>, lanes: u8, a: Value, b: Value, c: Value) ->
let (h, w) = (lanes_of(fb, 16)?, lanes_of(fb, 32)?);
let narrow = |fb: &mut FunctionBuilder<'_>, x: Value| fb.convert(ConvOp::FConvert, x, h);
let (a, b, c) = (narrow(fb, a)?, narrow(fb, b)?, narrow(fb, c)?);
let r = fb.glsl(GlslOp::Fma, &[a, b, c])?;
let r = if khr {
fb.fma(a, b, c)?
} else {
fb.glsl(GlslOp::Fma, &[a, b, c])?
};
fb.convert(ConvOp::FConvert, r, w)
}
+45 -19
View File
@@ -23,9 +23,10 @@
//! and `double` are native (`f64` needs `shaderFloat64`), and `half` and `bfloat` are held widened
//! in an `f32` that is always a value of the narrow format ([`narrow`]): each operation rounds its
//! `f32` result back to the format, so no profile needs `shaderFloat16`; where the device's 16-bit
//! `+ - *` is measured to be Metal's `half` arithmetic and the profile has `shaderFloat16`, a
//! `half` `+ - *` is that instruction, kept apart, between exact conversions instead
//! ([`ArithStrategy::F16`]).
//! `+ - *` is Metal's `half` arithmetic and the profile has `shaderFloat16`, a `half` `+ - *` is
//! that instruction, kept apart, between exact conversions instead ([`ArithStrategy::F16`]): where
//! it is measured to be, and where the 16-bit float controls the module then declares make it so
//! by the Vulkan spec ([`narrow::controlled_modes`]).
//!
//! Precision: a `half` rounding keeps half denormals, as Metal does; a `float` or `half` fused
//! multiply-add (`air.fma`, `llvm.fma`, and `llvm.fmuladd`, which Metal fuses) rounds once on every
@@ -199,9 +200,9 @@ pub enum ArithStrategy {
contract: Contraction,
},
/// A `half` `fadd`, `fsub` or `fmul` on lanes of `form` by the device's 16-bit arithmetic,
/// Metal's own in the forms that keep it apart (`DriverDeviation::MetalHalfArithmetic`,
/// [`ops::f16_binary`]): the operands narrowed to 16 bits, exactly, the instruction kept
/// apart, and its result widened, exactly.
/// Metal's own in the forms that keep it apart (measured, `DriverDeviation::MetalHalfArithmetic`,
/// or by the Vulkan spec under the 16-bit float controls, [`ops::f16_binary`]): the operands
/// narrowed to 16 bits, exactly, the instruction kept apart, and its result widened, exactly.
F16 {
op: AirBin,
form: Form,
@@ -2256,10 +2257,12 @@ fn select_in(
} else {
s
}
} else if f16_arithmetic(cx.profile, *op, f) {
// The device's own `half` arithmetic, measured to be Metal's in the forms
// that keep it apart, which the AIR's flags allow whatever they are.
cx.families.arith.f16_arith = true;
} else if let Some(basis) = f16_arithmetic(cx.profile, *op, f) {
// The device's own `half` arithmetic, Metal's in the forms that keep it
// apart, which the AIR's flags allow whatever they are. Only the measured
// basis is a property the module requires; the float controls are modes
// its entry declares.
cx.families.arith.f16_arith |= basis == F16Basis::Measured;
let s = S::F16 { op: *op, form: f };
with_nan(cx, at, s, nan::binary_answer(*op, fmt), f)
} else {
@@ -2946,19 +2949,42 @@ fn native_min_max(p: &DeviceProfile, op: FloatFn, f: Form) -> bool {
&& p.fields().min_max == MinMaxRoute::Native
}
/// Why the device's 16-bit `+ - *` answers as Metal's `half` arithmetic ([`f16_arithmetic`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum F16Basis {
/// Measured (`DriverDeviation::MetalHalfArithmetic`): the module requires
/// `VkProperty::MetalHalfArithmetic`.
Measured,
/// The 16-bit float controls the module's `half` roundings take ([`QuantizeForm::Controlled`],
/// [`narrow::controlled_modes`]), which its entry then declares ([`narrow::computes_in_16_bits`]):
/// no fact.
Controlled,
}
/// Whether the float binary operator `op` on lanes of form `f` takes the device's 16-bit
/// arithmetic ([`ArithStrategy::F16`]): a `half` `fadd`, `fsub` or `fmul`, on one to four lanes (a
/// chunk's own form), where profile `p` takes `DriverDeviation::MetalHalfArithmetic` and has
/// `shaderFloat16`. A `half` `fdiv` keeps the shared precise routine: Metal's fast and relaxed
/// compiles answer the device's 16-bit quotient of widened operands as a `float` one (EV
/// `CRT2-ha2-m4`), and it has no form that keeps it apart. A `half` `frem` is not measured.
fn f16_arithmetic(p: &DeviceProfile, op: AirBin, f: Form) -> bool {
/// arithmetic ([`ArithStrategy::F16`]), and on what basis: a `half` `fadd`, `fsub` or `fmul`, on
/// one to four lanes (a chunk's own form), where profile `p` has `shaderFloat16` and takes
/// `DriverDeviation::MetalHalfArithmetic` ([`F16Basis::Measured`]) or rounds to `half` under the
/// 16-bit float controls ([`F16Basis::Controlled`]). Under those controls the instruction is Metal's
/// by the Vulkan spec ([`ops::f16_binary`]). A `half` `fdiv` keeps the shared precise routine:
/// Metal's fast and relaxed compiles answer the device's 16-bit quotient of widened operands as a
/// `float` one, it has no form that keeps it apart, and Vulkan's precision table
/// does not make a 16-bit quotient correctly rounded. A `half` `frem` is not measured.
fn f16_arithmetic(p: &DeviceProfile, op: AirBin, f: Form) -> Option<F16Basis> {
use crate::error::DriverDeviation;
matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul)
let applies = matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul)
&& f.float_fmt() == Some(FloatFmt::Half)
&& (1..=4).contains(&f.lanes)
&& p.takes_driver_deviation(DriverDeviation::MetalHalfArithmetic)
&& p.fields().leaf.float16
&& p.fields().leaf.float16;
if !applies {
None
} else if p.takes_driver_deviation(DriverDeviation::MetalHalfArithmetic) {
Some(F16Basis::Measured)
} else if narrow::quantize_form(p) == QuantizeForm::Controlled {
Some(F16Basis::Controlled)
} else {
None
}
}
/// The fast division routine a float function call of form `f` lowered as `how` calls:
+32 -3
View File
@@ -29,9 +29,11 @@
//! device decoded ([`round_texel`]) unless the profile leaves NaN bits to the device under native
//! half rounding or the float controls; `bfloat` rounds through an
//! exact integer round-to-nearest-even of the `f32` bits. Where the device's 16-bit `+ - *`, kept
//! apart, is measured to be Metal's `half` arithmetic (`DriverDeviation::MetalHalfArithmetic`) and
//! the profile has `shaderFloat16`, a `half` `+ - *` is that instruction between exact conversions
//! instead, with no rounding here (`ops::f16_binary`). For `+ - * /` and square root the double
//! apart, is Metal's `half` arithmetic and the profile has `shaderFloat16`, a `half` `+ - *` is
//! that instruction between exact conversions instead, with no rounding here (`ops::f16_binary`):
//! where it is measured to be (`DriverDeviation::MetalHalfArithmetic`), and under the float
//! controls of [`QuantizeForm::Controlled`], which make it so by the Vulkan spec and which the
//! entry then declares ([`computes_in_16_bits`]). For `+ - * /` and square root the double
//! rounding (the exact result to `f32`, then to the narrow format) is innocuous, because `f32`
//! carries at least `2p + 2` significand bits for both formats; a `half` fused multiply-add is not,
//! so it rounds its exact `f32` sum to odd first (`super::fma`), and a `bfloat` one is corrected
@@ -1271,6 +1273,33 @@ pub fn widens_bits(m: &TypedModule, meter: &mut Meter) -> Result<bool, Error> {
Ok(found)
}
/// Whether module `m` computes in 16-bit floats: an `OpFAdd`, `OpFSub` or `OpFMul`, an `OpFmaKHR`
/// or a `GLSL.std.450 Fma` whose result is a 16-bit float or a vector of them, the device's own
/// `half` arithmetic (`super::ops::f16_binary`, `super::fma`). Under the 16-bit float controls
/// ([`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 {
let half = |v: Value| -> bool {
let Ok(ty) = m.value(v).map(|v| v.ty) else {
return false;
};
let ty = match m.types().get(ty) {
Ok(Type::Vector { elem, .. }) => *elem,
_ => ty,
};
matches!(m.types().get(ty), Ok(Type::Float { width: 16 }))
};
m.blocks().iter().flat_map(|b| &b.insts).any(|n| {
let arithmetic = match &n.inst {
Inst::Binary { op, .. } => matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul),
Inst::Fma { .. } => true,
Inst::Glsl { op, .. } => *op == GlslOp::Fma,
_ => false,
};
arithmetic && n.result.is_some_and(half)
})
}
/// Half bits `h` (the low 16 bits of each lane) to the `f32` bits of the same value: the
/// magnitude's bits moved up by 13 and rebiased by `112 << 23`, or, for an infinity or NaN, by `224
/// << 23`, which gives the `f32`'s all-ones exponent with the payload moved up (the half exponent
+18 -5
View File
@@ -271,11 +271,24 @@ pub fn f16_binary_words(f: Form) -> u32 {
}
/// The `half` `fadd`, `fsub` or `fmul` of `a` and `b` (`half` values held in `float` lanes of
/// `lanes` lanes) by the device's 16-bit arithmetic, Metal's own where the profile takes
/// `DriverDeviation::MetalHalfArithmetic`: each operand narrowed to 16 bits, exactly since it is a
/// `half`, the instruction, which rounds the exact result once as Metal's `half` arithmetic does,
/// and its result widened, exactly. No rounding of the module's own ([`narrow::round`]), so no
/// conversion barrier.
/// `lanes` lanes) by the device's 16-bit arithmetic: each operand narrowed to 16 bits, exactly
/// since it is a `half`, the instruction, which rounds the exact result once as Metal's `half`
/// arithmetic does, and its result widened, exactly. No rounding of the module's own
/// ([`narrow::round`]), so no conversion barrier and no conversion pair, which a device's compiler
/// spends most on (ANV's register allocation grows with the values the pairs add).
///
/// The instruction is Metal's where the profile takes `DriverDeviation::MetalHalfArithmetic`, and,
/// by the Vulkan spec, in an entry declaring the 16-bit float controls the module's roundings take
/// ([`narrow::controlled_modes`]): the precision table "for IEEE754 half- (16 bit) and single- (32
/// bit) precision instructions" lists `OpFAdd`, `OpFSub` and `OpFMul` as "Correctly rounded",
/// "according to IEEE 754 roundTiesToEven" under `RoundingModeRTE`, `DenormPreserve` keeps
/// denormal operands and results, and `SignedZeroInfNanPreserve` the zero signs IEEE 754 gives. That
/// is the value the `float` operation rounded once to `half` gives too ([`f16_binary`]'s
/// alternative, [`float_binary`]): `float`'s 24-bit significand is at least `2 · 11 + 2` bits, so
/// rounding its correctly rounded sum, difference or product to `half` rounds the exact result once
/// (the double rounding is innocuous). A NaN's bits are the device's, as the controlled rounding's
/// are; Metal's NaN, where the profile asks for it, is selected around the instruction
/// (`ArithStrategy::Nan`).
///
/// The instruction is always kept apart, whatever the AIR's flags allow: a sum or difference
/// decorated `NoContraction` (SPIRV-Cross writes its `[[clang::optnone]]` `spvFAdd` or `spvFSub`),
@@ -707,8 +707,9 @@ fn the_half_reference_rounds_the_exact_sum() {
/// The route follows the profile: `OpFmaKHR` where `shaderFmaFloat32` is enabled, else `double`
/// where 64-bit floats and integers are, else the integer routine; `half` has its own, the device's
/// 16-bit `Fma` where the driver is measured to compute it as Metal's `half` `fma` and
/// `shaderFloat16` is enabled (the MoltenVK captures alone), and `bfloat` and `double` keep their
/// own lowering.
/// `shaderFloat16` is enabled (the MoltenVK captures alone), else `OpFmaKHR` on 16 bits where
/// `shaderFmaFloat16` is enabled and the profile rounds under the 16-bit float controls, under
/// either policy, and `bfloat` and `double` keep their own lowering.
///
/// Under native device maths (the default policy) a profile whose functions are not Metal's takes
/// the device's `Fma` ([`Route::Native`]) where it would take a routine. Under
@@ -722,7 +723,23 @@ fn the_fused_multiply_add_route_follows_the_profile() {
use crate::error::DriverDeviation;
use crate::pipeline::testing::exact_maths;
use crate::spirv::testing::{committed_profiles_with, is_moltenvk_capture};
// The `half` route a profile offers whatever its policy: Metal's measured `Fma`, or `OpFmaKHR`
// on 16 bits under the float controls, or none.
let exact_half = |p: &crate::device::DeviceProfile| {
let l = &p.fields().leaf;
if p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && l.float16 {
Some(Route::F16)
} else if l.fma16
&& crate::lower::arith::narrow::quantize_form(p)
== crate::spirv::builder::QuantizeForm::Controlled
{
Some(Route::F16Khr)
} else {
None
}
};
let mut native = 0;
let mut khr16 = 0;
for (stem, p) in committed_profiles().expect("profiles") {
let l = &p.fields().leaf;
if p.fields().float_functions != FloatFunctions::Native {
@@ -733,13 +750,12 @@ fn the_fused_multiply_add_route_follows_the_profile() {
let f = Fma::on(&p, float(32)).expect("float");
assert_eq!((f.route, f.routine()), (want, None), "{stem}");
let h = Fma::on(&p, float(16)).expect("half");
let half = match p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && l.float16 {
true => Route::F16,
false => Route::Native,
};
let half = exact_half(&p).unwrap_or(Route::Native);
assert_eq!((h.route, h.routine()), (half, None), "{stem}");
khr16 += usize::from(half == Route::F16Khr);
}
assert!(native >= 10, "{native} profiles take native device maths");
assert!(khr16 >= 2, "{khr16} profiles take OpFmaKHR on 16 bits");
let mut seen = std::collections::BTreeSet::new();
let mut f16 = Vec::new();
let mut checked = 0;
@@ -779,10 +795,7 @@ fn the_fused_multiply_add_route_follows_the_profile() {
flushing += usize::from(
tiny.is_some() && p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals),
);
let half = match p.takes_driver_deviation(DriverDeviation::MetalHalfFma) && l.float16 {
true => Route::F16,
false => Route::HalfOdd,
};
let half = exact_half(&p).unwrap_or(Route::HalfOdd);
let h = Fma::on(&p, float(16)).expect("half");
assert_eq!(h.route, half, "{stem}");
assert_eq!(
@@ -2678,43 +2678,59 @@ fn srgb_conversions_are_named_apart_and_charge_their_table_once() {
assert_eq!(routine_words(&ArithPlan::default()).count(), 0);
}
/// A `half` `fadd`, `fsub` or `fmul` takes the device's 16-bit arithmetic exactly where the profile
/// takes `DriverDeviation::MetalHalfArithmetic` and has `shaderFloat16` (the MoltenVK captures
/// alone), on one to four lanes; `fdiv`, `frem`, other formats, and a chunk wider than four lanes
/// A `half` `fadd`, `fsub` or `fmul` takes the device's 16-bit arithmetic, on one to four lanes,
/// exactly where the profile has `shaderFloat16` and takes `DriverDeviation::MetalHalfArithmetic`
/// (the MoltenVK captures alone, measured) or rounds to `half` under the 16-bit float controls (by
/// the Vulkan spec, with no fact); `fdiv`, `frem`, other formats, and a chunk wider than four lanes
/// never do.
#[test]
fn half_arithmetic_on_the_device_follows_the_profile() {
use super::super::F16Basis;
use crate::error::DriverDeviation;
use crate::spirv::builder::QuantizeForm;
use crate::spirv::testing::is_moltenvk_capture;
let mut taken = 0;
let (mut measured, mut controlled) = (0, 0);
for (stem, p) in committed_profiles().expect("profiles") {
let device = p.takes_driver_deviation(DriverDeviation::MetalHalfArithmetic)
&& p.fields().leaf.float16;
assert_eq!(device, is_moltenvk_capture(&stem), "{stem}");
let float16 = p.fields().leaf.float16;
let fact = p.takes_driver_deviation(DriverDeviation::MetalHalfArithmetic) && float16;
assert_eq!(fact, is_moltenvk_capture(&stem), "{stem}");
let controls = super::super::narrow::quantize_form(&p) == QuantizeForm::Controlled;
let basis = match (fact, controls) {
(true, _) => Some(F16Basis::Measured),
(false, true) => Some(F16Basis::Controlled),
(false, false) => None,
};
for op in [AirBin::FAdd, AirBin::FSub, AirBin::FMul] {
for lanes in 1..=4 {
assert_eq!(
super::super::f16_arithmetic(&p, op, vec(half(), lanes)),
device,
basis,
"{stem}: {op:?} on {lanes} lanes"
);
}
for f in [vec(half(), 8), float(32), bfloat(), float(64)] {
assert!(
!super::super::f16_arithmetic(&p, op, f),
assert_eq!(
super::super::f16_arithmetic(&p, op, f),
None,
"{stem}: {op:?} on {f:?}"
);
}
}
for op in [AirBin::FDiv, AirBin::FRem] {
assert!(
!super::super::f16_arithmetic(&p, op, half()),
assert_eq!(
super::super::f16_arithmetic(&p, op, half()),
None,
"{stem}: {op:?}"
);
}
taken += usize::from(device);
measured += usize::from(basis == Some(F16Basis::Measured));
controlled += usize::from(basis == Some(F16Basis::Controlled));
}
assert!(taken >= 2, "the MoltenVK captures take it");
assert!(measured >= 2, "the MoltenVK captures take it, measured");
assert!(
controlled >= 2,
"the float-controls profiles take it, by the spec"
);
}
/// The device's `half` `+ - *` ([`ops::f16_binary`]) is the exact result rounded once to `half`, on
@@ -23,7 +23,7 @@ use crate::spirv::ir::TypedModule;
fn routines(b: &mut ModuleBuilder, fma: Fma) -> BResult<SnapRoutines> {
let (path, khr) = match fma.route {
Route::Khr => (Path::Fused, true),
Route::Wide | Route::Soft | Route::HalfOdd | Route::F16 | Route::Native => {
Route::Wide | Route::Soft | Route::HalfOdd | Route::F16 | Route::F16Khr | Route::Native => {
(Path::Integer, false)
}
};
+3 -2
View File
@@ -1531,8 +1531,9 @@ pub enum PrecisionNote {
/// tolerance from it.
NativeDivision,
/// Native device maths: a `float` fused multiply-add on a device without `OpFmaKHR`, or a
/// `half` one where the device's 16-bit `Fma` is not measured to be Metal's, is the device's
/// `GLSL.std.450 Fma` (on the `half` operands held in `float`, its result rounded to `half`),
/// `half` one where the device's 16-bit `Fma` is not measured to be Metal's and the device has
/// no 16-bit `OpFmaKHR` under the 16-bit float controls, is the device's `GLSL.std.450 Fma`
/// (on the `half` operands held in `float`, its result rounded to `half`),
/// not the translation's correctly rounded routine, under `FloatMathsPolicy::Native` (the
/// default). **Recorded bound:** a `half` result within one unit in its last place of
/// Metal's (the product of two `half` values is exact in `float`, so only the two roundings
+9 -5
View File
@@ -2248,13 +2248,17 @@ fn compile_kept<K>(
let converts = plan.families.arith.quantize == crate::spirv::builder::QuantizeForm::Converted
&& crate::lower::arith::narrow::rounds_by_conversion(&module, m)?;
// A `half` rounded through the device's conversion and its widening, each decorated
// `NoContraction`, under the float controls that make it Metal's, 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 module that
// widens so leaves a NaN's bits to the device, as the profile does (`NanMinMaxPolicy::Native`).
// `NoContraction`, under the float controls that make it Metal's, computed by the device's
// 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 module that widens
// so leaves a NaN's bits to the device, as the profile does (`NanMinMaxPolicy::Native`).
if plan.families.arith.quantize == crate::spirv::builder::QuantizeForm::Controlled {
let widens = crate::lower::arith::narrow::widens_bits(&module, m)?;
if widens || crate::lower::arith::narrow::rounds_by_conversion(&module, m)? {
if widens
|| crate::lower::arith::narrow::computes_in_16_bits(&module)
|| crate::lower::arith::narrow::rounds_by_conversion(&module, m)?
{
let modes = crate::lower::arith::narrow::controlled_modes(p).unwrap_or_default();
module.declare_modes(&modes)?;
}
@@ -348,12 +348,13 @@ impl FunctionBuilder<'_> {
}
/// `OpFmaKHR` (`SPV_KHR_fma`): `a * b + c` with one rounding, which Vulkan's precision table
/// makes correctly rounded. The three operands share one 32-bit float scalar or vector type,
/// the only width the core emits it at (its feature is `shaderFmaFloat32`). Result: that type.
/// makes correctly rounded. The three operands share one 16- or 32-bit float scalar or vector
/// type, the widths the core emits it at (its feature is `shaderFmaFloat16` or
/// `shaderFmaFloat32`). Result: that type.
pub fn fma(&mut self, a: Value, b: Value, c: Value) -> BResult<Value> {
const OP: crate::spv::Op = crate::spv::Op::FmaKHR;
let x = self.want(OP, 0, a, Num::is_float)?;
if x.width != 32 {
if x.width != 32 && x.width != 16 {
return Err(err(OP, OperandRule::Width(0)));
}
if self.value_ty(b)? != x.ty {
@@ -201,10 +201,11 @@ fn comparisons_derive_bool_of_the_component_count() {
});
}
/// `OpFmaKHR` takes three operands of one 32-bit float scalar or vector type and gives that type;
/// the core never emits it at another width (its feature is `shaderFmaFloat32`).
/// `OpFmaKHR` takes three operands of one 16- or 32-bit float scalar or vector type and gives that
/// type; the core never emits it at another width (its feature is `shaderFmaFloat16` or
/// `shaderFmaFloat32`).
#[test]
fn fma_khr_takes_three_floats_of_one_32_bit_type() {
fn fma_khr_takes_three_floats_of_one_16_or_32_bit_type() {
in_fn(|f, t| {
let (x, v) = (p(f, t.f32_), p(f, t.vec4));
let r = f.fma(x, x, x).expect("scalar");
@@ -212,7 +213,8 @@ fn fma_khr_takes_three_floats_of_one_32_bit_type() {
let r = f.fma(v, v, v).expect("vector");
assert_eq!(ty(f, r), t.vec4);
let (h, d, u) = (p(f, t.f16), p(f, t.f64_), p(f, t.u32_));
assert_eq!(f.fma(h, h, h), op_err(Op::FmaKHR, OperandRule::Width(0)));
let r = f.fma(h, h, h).expect("16-bit scalar");
assert_eq!(ty(f, r), t.f16);
assert_eq!(f.fma(d, d, d), op_err(Op::FmaKHR, OperandRule::Width(0)));
assert_eq!(f.fma(u, u, u), op_err(Op::FmaKHR, OperandRule::Category(0)));
assert_eq!(f.fma(x, v, x), op_err(Op::FmaKHR, OperandRule::Mismatch(1)));
@@ -1157,12 +1157,21 @@ impl Deriver<'_> {
self.cap(Cap::RayTraversalPrimitiveCullingKHR);
}
}
// The builder admits 32-bit floats only (`FunctionBuilder::fma`), so `shaderFmaFloat32`
// is the feature (VUID-RuntimeSpirv-shaderFmaFloat32-10978).
Inst::Fma { .. } => {
// The builder admits 16- and 32-bit floats (`FunctionBuilder::fma`): `shaderFmaFloat16`
// or `shaderFmaFloat32` by the operands' width, the result's
// (VUID-RuntimeSpirv-shaderFmaFloat16-10977, VUID-RuntimeSpirv-shaderFmaFloat32-10978).
Inst::Fma { a, .. } => {
self.cap(Cap::Fmakhr);
self.ext(SpirvExtension::KhrFma);
self.feat(VkFeature::ShaderFmaFloat32);
let half = matches!(
self.scalar_of(self.value_ty(*a)?)?,
Type::Float { width: 16 }
);
self.feat(if half {
VkFeature::ShaderFmaFloat16
} else {
VkFeature::ShaderFmaFloat32
});
}
Inst::DemoteToHelperInvocation | Inst::IsHelperInvocation => {
self.cap(Cap::DemoteToHelperInvocation);
@@ -8,8 +8,8 @@ use crate::device::requirements::{Requirements, SpirvCapability, VkExtension, Vk
use crate::pipeline::sym::ResourceKind;
use crate::spirv::builder::ModuleBuilder;
use crate::spirv::ir::{
natural_layout, AtomicOp, ExecModel, ImageOperands, IoDir, LayoutRule, MemAccess, MemoryOrder,
Scope, Semantics, StorageClass, Type, TypedModule,
natural_layout, AtomicOp, ConvOp, ExecModel, ImageOperands, IoDir, LayoutRule, MemAccess,
MemoryOrder, Scope, Semantics, StorageClass, Type, TypedModule,
};
use crate::spirv::requirements::{uses_physical_storage_buffer, uses_vulkan_memory_model};
use crate::spirv::testing::{spirv_val_with, TargetEnv, ValOptions};
@@ -78,6 +78,28 @@ fn fma_khr_derives_its_capability_extension_and_feature() {
assert!(r.extensions.contains(&VkExtension::KhrShaderFma), "{r:?}");
}
/// `OpFmaKHR` on 16-bit floats derives `shaderFmaFloat16` in place of `shaderFmaFloat32`, beside
/// the 16-bit float's own `Float16`, and passes `spirv-val`.
#[test]
fn fma_khr_on_16_bit_floats_derives_the_16_bit_feature() {
let mut b = ModuleBuilder::new();
let t = tys(&mut b);
let buf = ssbo(&mut b, 0, t.f32_, 4);
let main = compute(&mut b, |f| {
let i = gid_x(f);
let p = elem_ptr(f, buf, i);
let x = f.load(p, MemAccess::default()).expect("load");
let h = f.convert(ConvOp::FConvert, x, t.f16).expect("narrow");
let r = f.fma(h, h, h).expect("fma");
let w = f.convert(ConvOp::FConvert, r, t.f32_).expect("widen");
f.store(p, w, MemAccess::default()).expect("store");
});
let r = checked(finish_compute(b, main));
has(&r, &[Capability::Fmakhr], &[VkFeature::ShaderFmaFloat16]);
assert!(!r.features.contains(&VkFeature::ShaderFmaFloat32), "{r:?}");
assert!(r.extensions.contains(&VkExtension::KhrShaderFma), "{r:?}");
}
#[test]
fn availability_semantics_select_the_vulkan_memory_model() {
let mut b = ModuleBuilder::new();
+14 -7
View File
@@ -3034,8 +3034,13 @@ fn half_rounding_follows_the_operation() {
let round_even = count_ops(&words, |w| {
w[0] & 0xFFFF == crate::spv::Op::ExtInst as u32 && w.len() > 4 && w[4] == 2
});
// The fused pairs on 16-bit floats: the device's `Fma` measured Metal's, or `OpFmaKHR`
// under the 16-bit float controls; each converts three operands and widens its result.
let f16 = kk.name == "fast_chain"
&& p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfFma);
&& matches!(
crate::lower::arith::fma::half_route(&p),
crate::lower::arith::fma::Route::F16 | crate::lower::arith::fma::Route::F16Khr
);
let (q, c, r) = match (kk.name == "fast_chain", f16) {
(true, true) => (3, 7 * 4, 2),
(true, false) => (4, 0, 3),
@@ -3056,13 +3061,15 @@ fn half_rounding_follows_the_operation() {
let device = p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfQuantize)
&& !converted
&& !controlled;
// Where the device's 16-bit `+ - *` is Metal's, the operations among the roundings:
// sixteen of the strict chain's seventeen, the first addition and the last multiply of
// the fast chain's three. The conversion's rounding stays the module's.
let ha = p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic)
&& p.fields().leaf.float16;
// Where the device's 16-bit `+ - *` is Metal's, measured or under the 16-bit float
// controls, the operations among the roundings: sixteen of the strict chain's
// seventeen, the first addition and the last multiply of the fast chain's three. The
// conversion's rounding stays the module's.
let ha = (p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic)
&& p.fields().leaf.float16)
|| controlled;
assert!(
!ha || converted,
!ha || converted || controlled,
"{what}: the half arithmetic beside the conversion"
);
let kept = match (ha, kk.name == "fast_chain") {
@@ -532,8 +532,8 @@ fn a_texels_nan_is_kept_under_native_half_rounding_only_where_the_nan_switch_ask
}
/// What a module's words say of its `half` rounding: its execution modes with a float width, the
/// conversions from 32- to 16-bit floats and back with how many carry `NoContraction`, and its
/// `OpQuantizeToF16`s.
/// conversions from 32- to 16-bit floats and back with how many carry `NoContraction`, its
/// `OpQuantizeToF16`s, and its 16-bit float arithmetic.
#[derive(Debug, Default)]
struct Rounding {
modes: std::collections::BTreeSet<(u32, u32)>,
@@ -543,6 +543,9 @@ struct Rounding {
quantizes: usize,
/// `OpConstant`s of 32-bit float type with Metal's canonical NaN, `0x7FC00000`.
canonical_nans: usize,
/// `OpFAdd`s, `OpFSub`s and extended instructions of a 16-bit float type: a `half` operation
/// on the device's 16-bit arithmetic (`ops::f16_binary`), between exact conversions.
f16_ops: usize,
}
/// [`Rounding`] of `words`, read back through the test parser.
@@ -604,6 +607,10 @@ fn rounding(words: &[u32]) -> Rounding {
}
}
for i in &parsed.instructions {
let width = i.result_type.and_then(|t| widths.get(&t).copied());
if matches!(i.opcode, Op::FAdd | Op::FSub | Op::ExtInst) && width == Some(16) {
r.f16_ops += 1;
}
if i.opcode != Op::FConvert {
continue;
}
@@ -627,8 +634,9 @@ fn rounding(words: &[u32]) -> Rounding {
/// Where the profile has `shaderFloat16` and the float controls that make a conversion to 16 bits
/// Metal's `half(float)` by the Vulkan spec (every ANV and RADV profile), and its driver does not
/// fold the round trip (`DriverWorkaround::HalfConversionPairFolded`, NVIDIA's), each kernel
/// rounds its `half` through that conversion and its
/// widening, every one decorated `NoContraction`, with no quantize, under either policy; its entry
/// rounds its `half` through that conversion and its widening, every one decorated
/// `NoContraction`, with no quantize, under either policy, and computes its `half` sum on the
/// device's 16-bit arithmetic, between conversions that are exact and undecorated; its entry
/// declares `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits and the
/// 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
@@ -693,7 +701,13 @@ fn a_controlled_conversion_rounds_half_where_the_float_controls_allow() {
let r = rounding(&a.module.words);
assert_eq!(r.quantizes, 0, "{what}: {r:?}");
assert!(r.narrowings > 0 && r.widenings > 0, "{what}: {r:?}");
assert_eq!(r.uncontracted, r.narrowings + r.widenings, "{what}: {r:?}");
assert_eq!(r.f16_ops, usize::from(*name == "half_sum"), "{what}: {r:?}");
// Each 16-bit operation narrows its two operands and widens its result, exactly.
assert_eq!(
r.uncontracted + 3 * r.f16_ops,
r.narrowings + r.widenings,
"{what}: {r:?}"
);
// Less `SignedZeroInfNanPreserve` for 32 and 64 bits, which the entry's own `float`
// arithmetic declares.
let declared: std::collections::BTreeSet<(u32, u32)> = r
@@ -286,12 +286,14 @@ fn only_the_entry_reads_the_coverage_of_a_looped_body() {
/// `fmx_fma_precise` computes a `half` `fma` and a `half` `a * b + c` (`llvm.fmuladd`, which Metal
/// fuses) beside their `float` forms. On a MoltenVK capture each `half` one is the device's 16-bit
/// `Fma`, inline: the module defines no function but its entry, declares a 16-bit float, and
/// requires `VkProperty::MetalHalfFma`; on macOS it compiles as MoltenVK's MSL. Every other
/// committed profile takes native device maths (the default): the device's `float` `Fma` rounded to
/// `half`, inline too, under `PrecisionNote::NativeFma`; it holds a 16-bit float only where it
/// rounds a `half` through the device's conversion, measured (`QuantizeForm::Converted`) or under
/// the float controls (`QuantizeForm::Controlled`: ANV and RADV). Under `FloatMathsPolicy::Exact`
/// it calls the `half` routine.
/// requires `VkProperty::MetalHalfFma`; on macOS it compiles as MoltenVK's MSL. A profile that
/// rounds a `half` under the 16-bit float controls (`QuantizeForm::Controlled`: ANV and RADV) with
/// `shaderFmaFloat16` takes `OpFmaKHR` on 16 bits (`fma::Route::F16Khr`), inline and under no note.
/// Every other committed profile takes native device maths (the default): the device's `float`
/// `Fma` rounded to `half`, inline too, under `PrecisionNote::NativeFma`; it holds a 16-bit float
/// only where it rounds a `half` through the device's conversion, measured
/// (`QuantizeForm::Converted`) or under the float controls. Under `FloatMathsPolicy::Exact` it
/// calls the `half` routine where it takes neither 16-bit form.
#[test]
fn a_half_fused_multiply_add_is_inline_on_moltenvk() {
let Some(lib) = library("fmx_fma_precise") else {
@@ -332,7 +334,9 @@ fn a_half_fused_multiply_add_is_inline_on_moltenvk() {
.stage
.precision_notes
.contains(&crate::pipeline::PrecisionNote::NativeFma);
assert_eq!(native, !moltenvk, "{what}");
let khr16 = crate::lower::arith::fma::half_route(dev.profile())
== crate::lower::arith::fma::Route::F16Khr;
assert_eq!(native, !moltenvk && !khr16, "{what}");
inline += usize::from(moltenvk);
compiles_as_moltenvk_msl(&stem, words, &what);
}
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -2472,9 +2472,10 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound.
whose division is not Metal's own, under `FloatMathsPolicy::Native` (the default).
- `metal2vulkan-degrade-native-fma` (precision). `PrecisionNote::NativeFma`: Native device maths: a
`float` fused multiply-add on a device without `OpFmaKHR`, or a `half` one where the device's
16-bit `Fma` is not measured to be Metal's, is the device's `GLSL.std.450 Fma` (on the `half`
operands held in `float`, its result rounded to `half`), not the translation's correctly rounded
routine, under `FloatMathsPolicy::Native` (the default).
16-bit `Fma` is not measured to be Metal's and the device has no 16-bit `OpFmaKHR` under the
16-bit float controls, is the device's `GLSL.std.450 Fma` (on the `half` operands held in
`float`, its result rounded to `half`), not the translation's correctly rounded routine, under
`FloatMathsPolicy::Native` (the default).
- `metal2vulkan-degrade-device-texel-conversion` (precision).
`PrecisionNote::DeviceTexelConversion`: Native device sampling (a texel conversion): the module
hands a read, sample or gather with a `float` result the device's own conversion of the texel's
+1 -2
View File
@@ -35,8 +35,7 @@ a cell that names another source took its numbers there.
| The maths library (`sin`, `exp`, `log`, `pow`, `atan2`...), divisions and Metal's fast reciprocal, and a fused multiply-add without `OpFmaKHR` are the device's instructions, not routines of Metal's answers. Off MoltenVK a `float` multiply, and a fused multiply-add by `OpFmaKHR`, keep the device's rounding before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it. | `float_maths = FloatMathsPolicy::Native` | `float_maths = FloatMathsPolicy::Exact`; there off MoltenVK a `float` product of `±2^-126` is Metal's zero where the exact product lies below `2^-126`, decided inline without a branch by one `OpFmaKHR` on the operands' magnitudes, or by their bits without `OpFmaKHR` (`arith.float.tiny`, `dot`'s first product too), and `OpFmaKHR` is checked: a result at most `2^-126` in magnitude, zero included, is answered by a routine called only then, with `double` one that decides only the exact sum's sign and whether it lies below `2^-126`, else the integer `fma`; a module with either check, or with a fused multiply-add the translation computes itself (the `double` and integer routines without `OpFmaKHR`, and every `half` one), declares `SignedZeroInfNanPreserve` at 32 bits, and at 64 for a `double` routine, where the device supports it, so the device keeps the zero signs they answer (without it Vulkan lets the device answer a zero of either sign; else `DeviceSignedZeroInfNan`) | Vulkan's precision table (`Sin` 2^-11 absolute in [-π, π], `Exp` 3 + 2·\|x\| ulp, `Atan` 4096 ulp) against Metal's 4-6 ulp; division 2.5 ulp; `fma` one `half` ulp (a `float` one may round twice); an `f32` denormal in a maths function, `fast::fmod` among them, read as the device reads it (`DeviceDenormals`); a product or fused multiply-add whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign, announced once per device as it is made. `NativeTranscendentals` (`native-transcendentals`), `NativeDivision` (`native-division`), `NativeFma` (`native-fma`), `FloatTininessAfterRounding` (`float-tininess-after-rounding`) | A2X 0.99-1.02 → 9.66-9.83 s, GPU 0.097-0.098 → 0.222-0.225 ms; Xgc14 0.87-0.90 → 12.6-13.6 s, 0.038 → 0.124-0.135 ms; Xgc15 0.63-0.65 → 9.40-9.54 s, 0.089 → 0.208 ms (at 7a9d65147f, before these modules declared `SignedZeroInfNanPreserve`; its cost is not measured). Off MoltenVK a product's check is 12 instructions inline (23 without `OpFmaKHR`), and a checked `OpFmaKHR` adds its test, a branch and a call of a routine of about 40 instructions (with `double`), which the device's compiler copies into each use |
| A NaN result's bits are the device's (no select of Metal's NaN), and `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` are the device's `NMin`, `NMax` and `NClamp`. | `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact` | A NaN where Metal answers one, its bits the device's; the operand Metal picks but at two NaNs, `+0` against `-0`, and `f32` denormals. `NativeNanEncoding` (`native-nan-encoding`), `NativeMinMax` (`native-min-max`) | A2X 1.00-1.02 → 1.85-1.88 s, GPU 0.098 → 0.116 ms; Xgc14 0.88-0.89 → 1.59-1.63 s, 0.039 → 0.048 ms; Xgc15 0.65-0.66 → 1.25-1.28 s, 0.090 → 0.102 ms |
| `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt`, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | `rounding_order = RoundingOrderPolicy::Native` | `rounding_order = RoundingOrderPolicy::Exact` (MoltenVK takes Metal's order under every policy): Metal's chain over every lane of a `dot` of any width (test `wide_dot_is_metals_fused_chain_in_metals_order`) | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp; `FMix` and `Sqrt` read an `f32` denormal as the device does (`DeviceDenormals`). `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, an `f32` denormal read as the device reads it, `DeviceArithmetic` (`device-arithmetic`) and `DeviceDenormals` | A2X 1.00-1.02 → 1.03-1.06 s, GPU 0.098 → 0.101 ms; Xgc14 0.88-0.89 → 0.97-1.02 s, 0.039 → 0.041 ms; Xgc15 0.65-0.66 → 0.73 s, 0.090 → 0.088 ms |
| A `half` result computed in `float` rounds through the device's conversion to 16 bits (three instructions), or its `OpQuantizeToF16` without `shaderFloat16`, not Metal's rounding in integer arithmetic (about twenty), on a device whose conversion is neither measured to be Metal's nor made Metal's by its float controls. ANV and RADV round through the conversion and its widening, each `NoContraction`, under `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits: exact by the Vulkan spec under either policy, no note. NVIDIA's driver folds that pair (`DriverWorkaround::HalfConversionPairFolded`), so NVIDIA takes this row. | `half_rounding = HalfRoundingPolicy::Native` | `half_rounding = HalfRoundingPolicy::Exact` | One `half` ulp; 65504 where Metal answers infinity on a device rounding toward zero; a half denormal may flush; NaN bits and a zero's sign the device's. Or no rounding at all, measured: NVIDIA (RTX 3090, 615.71.09) drops the conversion pair, and lavapipe does 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, whose arithmetic measured rounded, so the result keeps `float` precision, its differences compounding across operations, and a value past `half`'s range stays finite until a `half` store saturates it to infinity; the RTX 5080 Laptop GPU (615.71.09) rounds, measured: 8192 of 8192 narrowed sums are Metal's. `NativeHalfConversion` (`native-half-conversion`), `NativeHalfQuantize` (`native-half-quantize`) | A2X 0.99-1.04 → 7.19-7.21 s, GPU 0.098-0.100 → 0.139-0.140 ms (+40%); Xgc14 0.86-0.87 → 0.87-0.92 s, Xgc15 0.63-0.66 → 0.69-0.70 s, GPU unchanged (RTX 5080). Rounding natively by `OpQuantizeToF16` instead, which the RTX 3090 and lavapipe honour (Metal's answer on every operand tested), was measured and declined: A2X 1.3 s → 18-22 s, GPU 0.14 → 1.5 ms on an RTX 3090 |
| A `half` read from its bits (a load, a reinterpretation, a texel's bits) outside every loop is widened by the device (`UnpackHalf2x16`), not decoded exactly. | `half_rounding = HalfRoundingPolicy::Native` | `half_rounding = HalfRoundingPolicy::Exact` (with the row above) | A half denormal may read as zero where the device flushes them; NaN payload the device's. `NativeHalfConversion` (`native-half-conversion`) | Not measured alone on today's master. At its merge: A2X 1.04-1.07 s with it against 1.27-1.28 s with the exact decode; Xgc unchanged |
| A `half` result computed in `float` rounds through the device's conversion to 16 bits (three instructions), or its `OpQuantizeToF16` without `shaderFloat16`, not Metal's rounding in integer arithmetic (about twenty), on a device whose conversion is neither measured to be Metal's nor made Metal's by its float controls. ANV and RADV round through the conversion and its widening, each `NoContraction`, under `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 bits: exact by the Vulkan spec under either policy, no note. Under the same controls a `half` `+ - *` is the device's 16-bit instruction, kept apart, and a `half` fused multiply-add is `OpFmaKHR` on 16 bits where `shaderFmaFloat16` is enabled, each correctly rounded by Vulkan's precision table, so neither rounds through the pair. NVIDIA's driver folds that pair (`DriverWorkaround::HalfConversionPairFolded`), so NVIDIA takes this row. | `half_rounding = HalfRoundingPolicy::Native` | `half_rounding = HalfRoundingPolicy::Exact` | One `half` ulp; 65504 where Metal answers infinity on a device rounding toward zero; a half denormal may flush; NaN bits and a zero's sign the device's. Or no rounding at all, measured: NVIDIA (RTX 3090, 615.71.09) drops the conversion pair, and lavapipe does 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, whose arithmetic measured rounded, so the result keeps `float` precision, its differences compounding across operations, and a value past `half`'s range stays finite until a `half` store saturates it to infinity; the RTX 5080 Laptop GPU (615.71.09) rounds, measured: 8192 of 8192 narrowed sums are Metal's. `NativeHalfConversion` (`native-half-conversion`), `NativeHalfQuantize` (`native-half-quantize`) | A2X 1.39-1.42 → 10.09-10.14 s, GPU 0.137-0.153 → 1.27-1.36 ms; Xgc14 1.15-1.16 → 1.16-1.19 s, Xgc15 0.81-0.87 → 0.82-0.86 s, GPU unchanged (RTX 3090). Rounding natively by `OpQuantizeToF16` instead, which the RTX 3090 and lavapipe honour (Metal's answer on every operand tested), was measured and declined: A2X 1.3 s → 18-22 s, GPU 0.14 → 1.5 ms on an RTX 3090 |
| The `half` conversion converts the value itself (no `NoContraction` barrier), so the device's compiler may fold it into the instruction computing the value, rounding once. | `half_rounding = HalfRoundingPolicy::Native` | `half_rounding = HalfRoundingPolicy::Exact` (with the rows above) | The row above's: on NVIDIA (RTX 3090), and on lavapipe for a loaded texel (Mesa 26.0.8), the pair is dropped whether or not the barrier stands, so the barrier does not restore the rounding there. `NativeHalfConversion` (`native-half-conversion`) | At its merge: A2X 0.99-1.02 s without the barrier against 1.00-1.05 s with it; Xgc within a round's spread |
| A `half` texel's NaN is the rounding's own NaN, not the texel's bits (the keep's four instructions a texel are left out). | `half_rounding = HalfRoundingPolicy::Native` and `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact` (the keep under native half rounding, master ecd39568bb); `half_rounding = HalfRoundingPolicy::Exact` also keeps it, at that row's cost. The same switch also gives Metal's full rule: `0x7e00` for every NaN but a one-texel read, nearest sample or gather of a 16-bit float texture, by the slot's format class read as data, a heap handle's class index and a runtime sampler's filter. A gather with a `half` result fetches its four texels where the class is a half-float one, since NVIDIA's gather hands back every NaN as `0x7fffffff`. **Not yet exact:** a cube gather, bicubic and emulated linear, fetched or compared samples; and on ANV (Iris Xe, Mesa 26.2.4) every 16-bit float texel's NaN, which its image decode answers as `0xFFC00000` (`0xFE00` as a `half`) before any keep: reading the texel's bits through an unsigned integer view would answer Metal's. Possible, not built: the runtime sampler's filter read as push data rather than specialized, which would spare the remake below. Measured on the RTX 5080: under the switch no `half` lane of the runtime lane's texel reads, samples and gathers differs from Metal's (1,469 differ by default). Under the switch `DeviceNanEncoding` is still announced; the consumer logs notes, so no device fact is built to drop it | NaN bits the device's (`0x7FFF` on the RTX 5080), where Metal hands back a 16-bit float texel's own bits on a read, nearest sample or gather, and `0x7e00` for a 32-bit or small float texel's NaN and a linear sample's. `NativeHalfConversion` (`native-half-conversion`); the read also records `DeviceNanEncoding` (`device-nan-encoding`) | Measured on top of the NaN switch's own row (its probe with the keep, c0a814a13, against its probe without, 3e8a01c54): A2X 341,299 → 347,519 words, 1.82-1.86 → 1.81-1.87 s, GPU 0.115-0.117 → 0.115-0.116 ms, within noise; Xgc14 and Xgc15 read no `half` texel (words unchanged). The full rule (its probe a5c642ebe against the same tip without it, 851650c81): A2X 347,519 → 372,429 words (+7.2%), creation 1.85-1.88 → 1.99-2.04 s; where a linear runtime sampler is bound at the draw the sampler word's filter is now specialized, so the first draw remakes (1.94-1.96 s) and its GPU time rises 0.115-0.117 → 0.124-0.125 ms; with a nearest sampler GPU 0.115-0.116 → 0.115-0.117 ms; Xgc14 and Xgc15 words unchanged. On the RTX 3090 the same pair: A2X creation 2.91-3.06 → 3.17-3.23 s, the first draw's remake 3.0 s and its GPU time 0.17-0.18 → 0.79-1.15 ms, with a nearest sampler 0.17-0.18 ms both |
| On ANV and RADV, which round a `half` through the device's conversion under the float controls, a `half` read from its bits (a load, a reinterpretation, a texel's bits) is the device's widening of them as a 16-bit float, loops included, and a `half` texel takes that conversion's NaN (no keep): every value but a NaN is exact by the Vulkan spec. | `nan_and_min_max = NanMinMaxPolicy::Native` | `nan_and_min_max = NanMinMaxPolicy::Exact`: the integer decode and the texel's keep; a `half` widened to `float` then answers Metal's `0x7fc00000` for every NaN, read from memory, a texel or a select alike | A `half` NaN widened to `float` has the device's bits (ANV quiets a signalling NaN, RADV keeps it), where Metal answers `0x7fc00000`; a `half` stored back unchanged keeps its bits. `NativeNanEncoding` (`native-nan-encoding`); a texel's, `DeviceNanEncoding` (`device-nan-encoding`) | ANV (Iris Xe, Mesa 26.2.4), A2X: making 4.06-4.36 → 5.76-5.87 s, 269,828 → 280,070 words, peak RSS 0.35 → 0.51 GB, GPU 4.48 → 4.62 ms (warm); RADV (Radeon 780M, Mesa 26.2.4): 379-467 → 535-665 ms, GPU within its clock states' spread |