Translator: a mode-2 fragment write to a texture buffer held as words rounds half and small floats to nearest even

A texture buffer of a format a device holds as words is written by lower/texture/words.rs's
write_texel, which rounded a half-float or RG11B10Float channel toward zero at either
textureWriteRoundingMode. Metal's texture buffer rounds those to nearest even at mode 2, as its
storage texture does (the probe below). So a fragment function in a mode-2 pipeline that wrote a
half-float or RG11B10Float texture buffer on a device holding that format as words stored a code
one below Metal's on 36% to 44% of the probe's channels, and 65504 where Metal stores the infinity.

Now, where Write::half_up marks the write (a fragment function's, in a pipeline of mode 2):
- a half-float channel (R16Float and RG16Float, the half-float formats a device may hold as
  words) takes ChannelWrite::FloatNearestEven, a finite value past the largest to the infinity, as
  Metal's RGBA16Float texture buffer stores it;
- an RG11B10Float channel takes nearest even too, and a lane that rounds to the infinity from a
  finite value is held at its format's largest finite value (65024 for the 11-bit channels, 64512
  for the 10-bit one), as Metal's stores it; an infinity stays, and a NaN is the quiet NaN still.
The RGB9E5Float word's half-up rounding is unchanged; the probe shows Metal's texture buffer
storing the same bytes as its storage texture there. A write at mode 0 or 1, and every kernel's
write, still rounds toward zero.

The probe is committed as crates/metal2vulkan-conformance/probes/texture_buffer_write_rounding.m:
texture_write_rounding_storage.m with texture_buffer<T, access::write> targets, made from a Shared
buffer with MTLTextureTypeTextureBuffer and written at texel y * 256 + x, over the same 65,536
texels. On an Apple M3 Max under macOS 27.0.1 (job m3-max-83395), mode 0 matched toward zero on
every channel, and mode 2 matched nearest even on every channel that is not a NaN: RGBA16Float
float texels 262,112 of 262,112 (to the infinity past the largest), RG11B10Float float and half
texels 196,583 of 196,583 each (held at the largest), and RGB9E5Float 65,536 of 65,536 at both
texel types (half up, its hashes equal to the storage texture's).

Docs: words.rs's module doc, Write::half_up and write_texel; API.md's words line names mode 2.

SEMANTICS_VERSION moves above development's: a texture buffer write's answer changes.

Verified on the CPU with no device (job m3-max-83575): the color_write and words tests pass (79), the
golden table differs from development's (semantics 2334) in 109 cells, as at a535f1dc17, and the
refusal surface is unchanged; cargo fmt, clippy (plain, --cfg m2v_gpu, --cfg m2v_cpu_icd),
Rustdoc, the API reference check and the doctests pass; the suites pass 3740 of 3741 (24 skipped),
the one failure golden_hashes_match_the_table, bless due; the validation suite passes 1340 (3
skipped) and the conformance suite 1052. The states-only plays of this tree (m3-max-83669) make
what 126ee4fdf5's make (m3-max-83443): the gb-3090-r2 stream 10643 render and 15299 compute
states, the 780M windrag stream 8972 and 225, none refused.
This commit is contained in:
Anees Iqbal committed 2026-12-03 05:55:06 -08:00
1 parent 9aa7d9e7b0
commit 011540217d
4 files changed
+520 -25

No files matched your search

@@ -0,0 +1,448 @@
// texture_write_rounding_storage.m with texture buffers for targets: what a fragment function's
// write to a texture buffer (`texture_buffer<T, access::write>`, a texture a buffer makes with
// `MTLTextureTypeTextureBuffer`) stores under Apple's `textureWriteRoundingMode` 2 against the
// default, for a `float` and a `half` texel into `RGBA16Float`, `RG11B10Float` and `RGB9E5Float`;
// a format whose texture buffer Metal refuses is printed and passed over. Each case draws one
// fullscreen triangle over a 256 x 256 target; the fragment function writes buffer 0's texel for
// its pixel into texture buffer 0 at texel `y * 256 + x`, once in a pipeline of mode 0 and once of
// mode 2, and the two texture buffers' codes are compared channel by channel with each other and with
// candidate rules computed here: toward zero (Metal's default), nearest even with an overflow to
// the infinity or held at the largest finite value and, for `RGB9E5Float`, the shared exponent of
// the largest clamped channel with each mantissa rounded (toward zero, to nearest even, half up),
// a mantissa of 512 either moving the exponent up or held at 511.
//
// The texels: each value of a list (zeros, infinities, NaN, negatives, the formats' largest finite
// values and the values past them, every tie of a 10-, 9-, 8-, 6- and 5-bit mantissa at a spread of
// exponents and one `f32` step either side, and random values) in all four channels, then random
// texels whose green and blue are the red scaled by a random factor in (0, 1], drawn from
// SplitMix64 seeded 7. A `half` texel is the `float` texel rounded to `half` on the host. `HASH`
// lines give the FNV-1a hashes of the inputs and of each texture buffer's bytes at each mode, which
// `metal2vulkan`'s tests `half_and_small_float_words_are_metals_at_either_mode` and
// `rgb9e5_words_are_metals_at_either_mode` hold a texture buffer's words to.
//
// xcrun clang -fobjc-arc -framework Metal -framework Foundation -o texture_buffer_write_rounding \
// texture_buffer_write_rounding.m
// /usr/bin/env -u MTL_DEBUG_LAYER ./texture_buffer_write_rounding
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#import <objc/message.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { W = 256, H = 256, N = W * H };
static const char *SRC =
"#include <metal_stdlib>\n"
"using namespace metal;\n"
"struct V { float4 p [[position]]; };\n"
"vertex V vs(uint id [[vertex_id]]) {\n"
" float2 xy = float2((id << 1) & 2, id & 2);\n"
" V v; v.p = float4(xy * 2.0 - 1.0, 0.0, 1.0); return v;\n"
"}\n"
"fragment float4 fs_float(V in [[stage_in]], texture_buffer<float, access::write> t [[texture(0)]],\n"
" device const float4 *src [[buffer(0)]]) {\n"
" uint2 c = uint2(in.p.xy);\n"
" t.write(src[c.y * 256 + c.x], c.y * 256 + c.x);\n"
" return float4(0.0);\n"
"}\n"
"fragment float4 fs_half(V in [[stage_in]], texture_buffer<half, access::write> t [[texture(0)]],\n"
" device const half4 *src [[buffer(0)]]) {\n"
" uint2 c = uint2(in.p.xy);\n"
" t.write(src[c.y * 256 + c.x], c.y * 256 + c.x);\n"
" return float4(0.0);\n"
"}\n";
enum Round { RTZ, RNE, RHU };
enum Over { INF, SAT };
// `v` as a float of `mb` mantissa and `eb` exponent bits (signed where `sign`), rounded by `r`, a
// value past the largest finite one to the infinity or held at the largest (`o`; toward zero
// always held). A NaN is the quiet NaN of the top mantissa bit; an unsigned format's negative 0.
static uint32_t enc(double v, int mb, int eb, int sign, enum Round r, enum Over o) {
uint32_t expall = (1u << eb) - 1, bias = (1u << (eb - 1)) - 1, s = 0;
if (isnan(v)) return (expall << mb) | (1u << (mb - 1));
if (v < 0 || (v == 0 && signbit(v))) {
if (!sign) return 0;
s = 1u << (mb + eb);
v = -v;
}
uint32_t maxfin = ((expall - 1) << mb) | ((1u << mb) - 1);
if (isinf(v)) return s | (expall << mb);
if (v == 0) return s;
int x;
frexp(v, &x);
int e = x - 1;
int denorm = e < 1 - (int)bias;
double q = denorm ? ldexp(v, (int)bias - 1 + mb) : ldexp(v, mb - e);
double qi = r == RTZ ? floor(q) : r == RNE ? nearbyint(q) : floor(q + 0.5);
uint32_t code;
if (denorm) {
code = (uint32_t)qi;
} else {
if (qi >= ldexp(1, mb + 1)) {
e += 1;
qi = ldexp(1, mb);
}
if (e + (int)bias >= (int)expall) return s | ((r == RTZ || o == SAT) ? maxfin : (expall << mb));
code = ((uint32_t)(e + (int)bias) << mb) | ((uint32_t)qi - (1u << mb));
}
return s | code;
}
static double dec(uint32_t c, int mb, int eb, int sign) {
uint32_t expall = (1u << eb) - 1, bias = (1u << (eb - 1)) - 1;
double sg = (sign && (c >> (mb + eb)) & 1) ? -1 : 1;
uint32_t e = (c >> mb) & expall, m = c & ((1u << mb) - 1);
if (e == expall) return m ? NAN : sg * INFINITY;
if (e == 0) return sg * ldexp(m, 1 - (int)bias - mb);
return sg * ldexp(m + (1u << mb), (int)e - (int)bias - mb);
}
static double clamp9(double v) { return isnan(v) || v < 0 ? 0 : v > 65408 ? 65408 : v; }
// RGB9E5: the shared exponent of the largest clamped channel, each mantissa rounded by `r`; a
// largest mantissa of 512 moves the exponent up where `bump`, else is held at 511.
static uint32_t rgb9e5(const double *c, enum Round r, int bump) {
double v[3], mx = 0;
for (int i = 0; i < 3; i++) {
v[i] = clamp9(c[i]);
if (v[i] > mx) mx = v[i];
}
if (mx == 0) return 0;
int x;
frexp(mx, &x);
int e = (x - 1 < -16 ? -16 : x - 1) + 16;
for (int pass = 0; pass < 2; pass++) {
uint32_t m[3], over = 0;
for (int i = 0; i < 3; i++) {
double q = ldexp(v[i], 24 - e);
double qi = r == RTZ ? floor(q) : r == RNE ? nearbyint(q) : floor(q + 0.5);
if (qi > 511) {
over = 1;
qi = 511;
}
m[i] = (uint32_t)qi;
}
if (over && bump && pass == 0 && e < 31) {
e += 1;
continue;
}
return ((uint32_t)e << 27) | (m[2] << 18) | (m[1] << 9) | m[0];
}
return 0;
}
static void dec9(uint32_t w, double *o) {
int e = (int)(w >> 27);
for (int i = 0; i < 3; i++) o[i] = ldexp((w >> (9 * i)) & 511, e - 24);
}
typedef struct {
const char *name;
MTLPixelFormat pf;
int bytes, kind; // kind 0: RGBA16Float, 1: RG11B10Float, 2: RGB9E5Float
} Fmt;
// The inputs' generator (SplitMix64 from 7), which `metal2vulkan`'s test of the words
// (`lower/arith/tests/color_write.rs`, `probe_texels`) takes again.
static uint64_t sm = 7;
static uint64_t next64(void) {
uint64_t z = (sm += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
static uint32_t r32(void) { return (uint32_t)(next64() >> 32); }
// FNV-1a over `n` bytes, from `h`.
static uint64_t fnv(uint64_t h, const void *p, size_t n) {
const uint8_t *b = p;
for (size_t i = 0; i < n; i++) h = (h ^ b[i]) * 0x100000001b3ull;
return h;
}
static const uint64_t FNV0 = 0xcbf29ce484222325ull;
static float vals[40000];
static int nv;
static void add(double v) {
if (nv < 40000) vals[nv++] = (float)v;
}
static void build_values(void) {
double sp[] = {0, -0.0, -1, -65504, INFINITY, -INFINITY, NAN, 65504, 65505, 65519, 65519.99,
65520, 65521, 65536, 1e5, 1e9, 65024, 65040, 65055.99, 65056, 65057, 64512,
64528, 64543.99, 64544, 64545, 65408, 65407, 65409, 65416, 65424, 65471, 65472,
65473, 1e-10, 1e-40, ldexp(1, -24), ldexp(1, -25), ldexp(3, -26), ldexp(1, -20),
ldexp(1, -21), ldexp(3, -22), ldexp(1, -24) * 1.5, ldexp(1, -14), ldexp(1, -15),
ldexp(1, -16), ldexp(1, -17), 0.5, 1, 1.5, 2, 3};
for (unsigned i = 0; i < sizeof sp / sizeof sp[0]; i++) add(sp[i]);
int widths[] = {10, 9, 8, 6, 5};
for (int wi = 0; wi < 5; wi++) {
int mb = widths[wi];
for (int e = -26; e <= 16; e++) {
int ks[8] = {0, 1, 2, 3, (1 << mb) - 2, (1 << mb) - 1, 0, 0};
ks[6] = (int)(r32() % (1u << mb));
ks[7] = (int)(r32() % (1u << mb));
for (int k = 0; k < 8; k++) {
float t = (float)ldexp(1.0 + (ks[k] + 0.5) / ldexp(1, mb), e);
add(t);
add(nextafterf(t, INFINITY));
add(nextafterf(t, -INFINITY));
}
}
}
while (nv < 12000) {
int e = (int)(r32() % 44) - 27;
uint32_t mant = r32() & 0x7fffff;
double v = ldexp(1.0 + (double)mant / 8388608.0, e);
int neg = r32() % 16 == 0;
add(neg ? -v : v);
}
}
static double urand(void) { return (double)((r32() & 0xffffff) + 1) / 16777216.0; }
int main(int argc, char **argv) {
(void)argc;
(void)argv;
@autoreleasepool {
build_values();
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
printf("device %s\n", dev.name.UTF8String);
SEL sup = NSSelectorFromString(@"supportsTextureWriteRoundingMode:");
if ([dev respondsToSelector:sup]) {
for (NSUInteger m = 0; m <= 2; m++)
printf("supportsTextureWriteRoundingMode:%lu %d\n", (unsigned long)m,
((BOOL(*)(id, SEL, NSUInteger))objc_msgSend)(dev, sup, m));
}
NSError *err = nil;
MTLCompileOptions *co = [MTLCompileOptions new];
co.mathMode = MTLMathModeSafe;
id<MTLLibrary> lib = [dev newLibraryWithSource:@(SRC) options:co error:&err];
if (!lib) {
printf("library: %s\n", err.description.UTF8String);
return 1;
}
// The texels, `float` and `half`.
float *ftex = calloc(N * 4, sizeof(float));
__fp16 *htex = calloc(N * 4, sizeof(__fp16));
for (int i = 0; i < N; i++) {
float *t = ftex + 4 * i;
if (i < nv) {
t[0] = t[1] = t[2] = t[3] = vals[i];
} else {
float r = vals[r32() % (uint32_t)nv];
t[0] = r;
t[1] = (float)(r * urand());
if (r32() % 4 == 0) {
t[2] = vals[r32() % (uint32_t)nv];
} else {
t[2] = (float)(r * urand());
}
t[3] = vals[r32() % (uint32_t)nv];
}
for (int c = 0; c < 4; c++) htex[4 * i + c] = (__fp16)t[c];
}
printf("HASH inputs %016llx halves %016llx values %d\n", (unsigned long long)fnv(FNV0, ftex, N * 16),
(unsigned long long)fnv(FNV0, htex, N * 8), nv);
id<MTLBuffer> fbuf = [dev newBufferWithBytes:ftex length:N * 16 options:MTLResourceStorageModeShared];
id<MTLBuffer> hbuf = [dev newBufferWithBytes:htex length:N * 8 options:MTLResourceStorageModeShared];
MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:W
height:H
mipmapped:NO];
td.usage = MTLTextureUsageRenderTarget;
td.storageMode = MTLStorageModePrivate;
id<MTLTexture> rt = [dev newTextureWithDescriptor:td];
id<MTLCommandQueue> q = [dev newCommandQueue];
Fmt fmts[] = {{"RGBA16Float", MTLPixelFormatRGBA16Float, 8, 0},
{"RG11B10Float", MTLPixelFormatRG11B10Float, 4, 1},
{"RGB9E5Float", MTLPixelFormatRGB9E5Float, 4, 2}};
SEL set = NSSelectorFromString(@"setTextureWriteRoundingMode:");
SEL get = NSSelectorFromString(@"textureWriteRoundingMode");
for (int fi = 0; fi < 3; fi++) {
for (int half = 0; half < 2; half++) {
Fmt f = fmts[fi];
if (half && f.kind == 0) continue; // a half into a half-float texture is exact
uint8_t *out[2] = {NULL, NULL};
for (int mode = 0; mode < 2; mode++) {
MTLRenderPipelineDescriptor *pd = [MTLRenderPipelineDescriptor new];
pd.vertexFunction = [lib newFunctionWithName:@"vs"];
pd.fragmentFunction = [lib newFunctionWithName:half ? @"fs_half" : @"fs_float"];
pd.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm;
if (![pd respondsToSelector:set]) {
printf("no setTextureWriteRoundingMode:\n");
return 2;
}
((void (*)(id, SEL, NSUInteger))objc_msgSend)(pd, set, mode ? 2 : 0);
NSUInteger took = ((NSUInteger(*)(id, SEL))objc_msgSend)(pd, get);
id<MTLRenderPipelineState> ps = [dev newRenderPipelineStateWithDescriptor:pd error:&err];
if (!ps) {
printf("%s %s mode %d: pipeline: %s\n", f.name, half ? "half" : "float", mode ? 2 : 0,
err.description.UTF8String);
return 1;
}
MTLTextureDescriptor *sd =
[MTLTextureDescriptor textureBufferDescriptorWithPixelFormat:f.pf
width:N
resourceOptions:MTLResourceStorageModeShared
usage:MTLTextureUsageShaderWrite |
MTLTextureUsageShaderRead];
id<MTLBuffer> sb = [dev newBufferWithLength:(NSUInteger)N * f.bytes options:MTLResourceStorageModeShared];
memset(sb.contents, 0xA5, (size_t)N * f.bytes);
id<MTLTexture> st = [sb newTextureWithDescriptor:sd offset:0 bytesPerRow:(NSUInteger)N * f.bytes];
if (!st) {
printf("%s %s mode %d: no texture buffer of this format\n", f.name, half ? "half" : "float", mode ? 2 : 0);
break;
}
uint8_t *fill = malloc(N * f.bytes);
MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
rp.colorAttachments[0].texture = rt;
rp.colorAttachments[0].loadAction = MTLLoadActionDontCare;
rp.colorAttachments[0].storeAction = MTLStoreActionDontCare;
id<MTLCommandBuffer> cb = [q commandBuffer];
id<MTLRenderCommandEncoder> en = [cb renderCommandEncoderWithDescriptor:rp];
[en setRenderPipelineState:ps];
[en setFragmentTexture:st atIndex:0];
[en setFragmentBuffer:half ? hbuf : fbuf offset:0 atIndex:0];
[en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[en endEncoding];
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted) {
printf("%s: command buffer status %ld\n", f.name, (long)cb.status);
return 1;
}
out[mode] = fill;
memcpy(fill, sb.contents, (size_t)N * f.bytes);
printf("%s %s mode %d (descriptor reads %lu)\n", f.name, half ? "half" : "float", mode ? 2 : 0,
(unsigned long)took);
}
if (!out[0] || !out[1]) {
free(out[0]);
continue;
}
printf("HASH %s %s mode0 %016llx mode2 %016llx\n", f.name, half ? "half" : "float",
(unsigned long long)fnv(FNV0, out[0], (size_t)N * f.bytes),
(unsigned long long)fnv(FNV0, out[1], (size_t)N * f.bytes));
// Per channel: the input, mode 0's and mode 2's codes, and the candidates'.
int chans = f.kind == 0 ? 4 : 3;
long total = 0, same = 0, unwritten = 0, dist[5] = {0}, nanish = 0;
const char *cn[] = {"rtz", "rne-inf", "rne-sat", "rhu-hold", "rne-bump", "rhu-bump", "rne-hold", "rtz-bump"};
long m0[8] = {0}, m2[8] = {0};
int ncand = f.kind == 2 ? 6 : 3;
int shown = 0;
double maxd = 0;
for (int i = 0; i < N; i++) {
double in[4];
for (int c = 0; c < 4; c++) in[c] = half ? (double)htex[4 * i + c] : (double)ftex[4 * i + c];
uint32_t w0 = 0, w2 = 0;
memcpy(&w0, out[0] + i * f.bytes, 4);
memcpy(&w2, out[1] + i * f.bytes, 4);
if (f.kind == 2) {
if (w0 == 0xA5A5A5A5u || w2 == 0xA5A5A5A5u) {
unwritten++;
continue;
}
uint32_t cand[6] = {rgb9e5(in, RTZ, 0), rgb9e5(in, RNE, 0), rgb9e5(in, RHU, 0),
rgb9e5(in, RNE, 1), rgb9e5(in, RHU, 1), rgb9e5(in, RTZ, 1)};
const int order[6] = {0, 6, 3, 4, 5, 7};
for (int k = 0; k < 6; k++) {
m0[order[k]] += cand[k] == w0;
m2[order[k]] += cand[k] == w2;
}
total++;
same += w0 == w2;
if (w0 != w2) {
double d0[3], d2[3];
dec9(w0, d0);
dec9(w2, d2);
int e = (int)((w0 >> 27) > (w2 >> 27) ? (w0 >> 27) : (w2 >> 27));
double ulp = ldexp(1, e - 24), d = 0;
for (int c = 0; c < 3; c++) d = fmax(d, fabs(d2[c] - d0[c]) / ulp);
maxd = fmax(maxd, d);
dist[d <= 1 ? 1 : d <= 2 ? 2 : 3]++;
if (shown < 6) {
shown++;
printf(" in (%.9g %.9g %.9g) mode0 %08x mode2 %08x rtz %08x rne %08x rhu %08x rne-bump %08x\n",
in[0], in[1], in[2], w0, w2, cand[0], cand[1], cand[2], cand[3]);
}
}
continue;
}
for (int c = 0; c < chans; c++) {
uint32_t c0, c2;
int mb, eb, sg;
if (f.kind == 0) {
uint16_t a, b;
memcpy(&a, out[0] + i * 8 + 2 * c, 2);
memcpy(&b, out[1] + i * 8 + 2 * c, 2);
c0 = a;
c2 = b;
mb = 10, eb = 5, sg = 1;
if (a == 0xA5A5 || b == 0xA5A5) {
unwritten++;
continue;
}
} else {
if (w0 == 0xA5A5A5A5u || w2 == 0xA5A5A5A5u) {
unwritten++;
continue;
}
int sh = c == 0 ? 0 : c == 1 ? 11 : 22;
mb = c == 2 ? 5 : 6, eb = 5, sg = 0;
c0 = (w0 >> sh) & ((1u << (mb + eb)) - 1);
c2 = (w2 >> sh) & ((1u << (mb + eb)) - 1);
}
total++;
double v0 = dec(c0, mb, eb, sg), v2 = dec(c2, mb, eb, sg);
if (isnan(in[c]) || isnan(v0) || isnan(v2)) {
nanish++;
same += isnan(v0) == isnan(v2);
continue;
}
uint32_t cand[3] = {enc(in[c], mb, eb, sg, RTZ, SAT), enc(in[c], mb, eb, sg, RNE, INF),
enc(in[c], mb, eb, sg, RNE, SAT)};
for (int k = 0; k < 3; k++) {
m0[k] += cand[k] == c0;
m2[k] += cand[k] == c2;
}
same += c0 == c2;
if (c0 != c2) {
// Codes of one sign are ordered by magnitude.
long a0 = (long)(c0 & ((1u << (mb + eb)) - 1)), a2 = (long)(c2 & ((1u << (mb + eb)) - 1));
long d = labs(a2 - a0);
if (isinf(v0) != isinf(v2)) d = 4;
dist[d >= 4 ? 4 : d >= 3 ? 3 : d]++;
if (shown < 6) {
shown++;
printf(" in %.9g (%a) mode0 %04x (%.9g) mode2 %04x (%.9g) rtz %04x rne-inf %04x rne-sat %04x\n",
in[c], in[c], c0, v0, c2, v2, cand[0], cand[1], cand[2]);
}
}
}
}
printf("RESULT %s %s: %ld %s, %ld unwritten, %ld NaN-ish; mode 2 = mode 0 on %ld; differing by 1: %ld, 2: %ld, "
"more: %ld, inf/finite: %ld%s",
f.name, half ? "half" : "float", total, f.kind == 2 ? "texels" : "channels", unwritten, nanish, same,
dist[1], dist[2], dist[3], dist[4], f.kind == 2 ? "" : "\n");
if (f.kind == 2) printf(" (max %.3g units of the larger exponent's last place)\n", maxd);
for (int k = 0; k < 8; k++) {
if (f.kind != 2 && k >= ncand) break;
if (f.kind == 2 && !(k == 0 || k >= 3)) continue;
printf(" candidate %-9s mode 0 %ld, mode 2 %ld\n", cn[k], m0[k], m2[k]);
}
free(out[0]);
free(out[1]);
}
}
}
return 0;
}
+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 = 2344;
pub const SEMANTICS_VERSION: u32 = 2345;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
+61 -20
View File
@@ -50,10 +50,14 @@
//! A write converts as Metal writes a kernel's texel: a normalized channel's value clamped (a NaN
//! 0) times `2^n - 1` (`2^(n-1) - 1` signed), the exact product rounded to nearest even; a half or
//! small float rounded toward zero, a finite value past the largest to the largest, an infinity
//! kept, a NaN to the quiet NaN (`color_write::small_float`); `RGB9E5Float` as
//! `emit::rgb9e5_word`; an integer saturated to its channel. An 8-bit sRGB colour channel is
//! encoded by the MSL transfer through the device's `Pow` and `PackUnorm4x8`, and an
//! extended-range texel by `extended_range::encode` (both `PrecisionNote::DevicePackConversion`).
//! kept, a NaN to the quiet NaN (`color_write::small_float`); `RGB9E5Float` as `emit::rgb9e5_word`;
//! an integer saturated to its channel. A fragment function's write in a pipeline of
//! `textureWriteRoundingMode` 2 rounds a half or small float to nearest even instead (a
//! half-float's finite value past the largest to the infinity, an `RG11B10Float` one's held at the
//! largest) and an `RGB9E5Float` word's mantissas half up, as Metal's texture buffer does. An 8-bit
//! sRGB colour channel is encoded by the MSL transfer through the device's `Pow` and
//! `PackUnorm4x8`, and an extended-range texel by `extended_range::encode` (both
//! `PrecisionNote::DevicePackConversion`).
//!
//! A texel of four or eight bytes is written with plain stores of its words. A texel of one or two
//! bytes shares its word with its neighbours: the write clears its bits with an atomic AND and
@@ -138,8 +142,9 @@ pub struct WordsPlan {
/// The codes the profile holds as words, by usage: bit `c` for code `c`
/// (`metal::format::texel_buffer_word_codes`).
pub codes: WordCodes,
/// Its writes store an `RGB9E5Float` word's mantissas rounded half up (`Write::half_up`: a
/// fragment function's, in a pipeline of `textureWriteRoundingMode` 2), else toward zero.
/// Its writes round as Metal's mode 2 does (`Write::half_up`: a fragment function's, in a
/// pipeline of `textureWriteRoundingMode` 2): a half-float or `RG11B10Float` channel to nearest
/// even and an `RGB9E5Float` word's mantissas half up (`write_texel`), else toward zero.
pub half_up: bool,
}
@@ -1038,6 +1043,24 @@ fn read_texel(
}
}
/// `h`, each lane of `v` (a `vec4` of `f32`) rounded to nearest even to a small float, with a lane
/// that rounded to the infinity from a finite value held at its format's largest finite value
/// (`largest`): an infinity stays, and a NaN is the quiet NaN still.
fn held_finite(
fb: &mut FunctionBuilder<'_>,
v: SValue,
h: SValue,
largest: [f32; 4],
) -> BResult<SValue> {
let infinity = kf4(fb, [f32::INFINITY; 4])?;
let past = fb.binary(BinOp::FOrdEqual, h, infinity)?;
let was = fb.unary(UnOp::IsInf, v)?;
let finite = fb.unary(UnOp::LogicalNot, was)?;
let held = fb.binary(BinOp::LogicalAnd, past, finite)?;
let top = kf4(fb, largest)?;
fb.select(held, top, h)
}
/// For the tests: the words `(lo, hi)` a write of `v` (a `vec4` of `f32`) stores in a texel of
/// `pf`, a format held as words ([`write_texel`]), at `textureWriteRoundingMode` 2 where
/// `half_up`.
@@ -1053,8 +1076,12 @@ pub(crate) fn written_words(
}
/// The words `(lo, hi)` of the texel of `layout` that a write of `v` (a `vec4` of `f32` for the
/// float class, of `u32` for an integer one) stores, a narrow texel's bits at the bottom of `lo`;
/// an `RGB9E5Float` word's mantissas rounded half up where `half_up` (`emit::rgb9e5_word`).
/// float class, of `u32` for an integer one) stores, a narrow texel's bits at the bottom of `lo`.
/// Where `half_up` (a fragment function's write in a pipeline of `textureWriteRoundingMode` 2), a
/// half-float channel is rounded to nearest even, a finite value past the largest to the infinity,
/// an `RG11B10Float` channel to nearest even held at the largest finite value, and an
/// `RGB9E5Float` word's mantissas half up (`emit::rgb9e5_word`), as Metal's texture buffer stores
/// them (the conformance crate's probe `texture_buffer_write_rounding`).
fn write_texel(
fb: &mut FunctionBuilder<'_>,
(layout, half_up): (WordLayout, bool),
@@ -1100,9 +1127,15 @@ fn write_texel(
fb.select(neg, minus, m)?
}
FieldKind::Half => {
let rule = ChannelWrite::FloatTowardZero {
mantissa: 10,
signed: true,
let rule = match half_up {
true => ChannelWrite::FloatNearestEven {
mantissa: 10,
signed: true,
},
false => ChannelWrite::FloatTowardZero {
mantissa: 10,
signed: true,
},
};
let h = crate::lower::arith::color_write::small_float(fb, f4, v, rule)?;
small_float_bits(fb, h, [10; 4], [true; 4])?
@@ -1132,17 +1165,25 @@ fn write_texel(
Ok((word, zero))
}
WordLayout::SmallFloats => {
let eleven = ChannelWrite::FloatTowardZero {
mantissa: 6,
signed: false,
let rule = |mantissa| match half_up {
true => ChannelWrite::FloatNearestEven {
mantissa,
signed: false,
},
false => ChannelWrite::FloatTowardZero {
mantissa,
signed: false,
},
};
let ten = ChannelWrite::FloatTowardZero {
mantissa: 5,
signed: false,
};
let rg = crate::lower::arith::color_write::small_float(fb, f4, v, eleven)?;
let b = crate::lower::arith::color_write::small_float(fb, f4, v, ten)?;
let rg = crate::lower::arith::color_write::small_float(fb, f4, v, rule(6))?;
let b = crate::lower::arith::color_write::small_float(fb, f4, v, rule(5))?;
let h = fb.vector_shuffle(rg, b, &[0, 1, 6, 3])?;
// Metal's mode 2 holds a finite value past the largest at the largest (65024 for an
// 11-bit float, 64512 for a 10-bit one), where nearest even gives the infinity.
let h = match half_up {
true => held_finite(fb, v, h, [65024.0, 65024.0, 64512.0, 65024.0])?,
false => h,
};
let codes = small_float_bits(fb, h, [6, 6, 5, 6], [false; 4])?;
// Red's bits from bit 0, green's from 11, blue's from 22.
let field = |shift, bits| {
+10 -4
View File
@@ -2616,10 +2616,16 @@ category, and says what makes an operation carry the note and what may differ. E
`unorm4x8_srgb`'s pack; its `float` read and write record the note where the profile holds an
extended-range format's texture buffers as words, and its write where it holds an 8-bit sRGB
one's so, the routine converting every format the profile holds as words. Its other
conversions are exact: a
normalized code to its correctly rounded quotient, a value to the exact product's code rounded
to nearest even, a half or small float exactly, and a write's half or small float toward zero,
as Metal's kernel writes.
conversions are exact: a normalized code to its correctly rounded quotient, a value to the exact
product's code rounded to nearest even, a half or small float exactly, and a write's half or
small float toward zero, as Metal's kernel writes. A fragment function's write in a pipeline of
`TextureWriteRoundingMode::NearestEven` rounds a half or small float to nearest even instead (a
half-float channel's finite value past the largest to the infinity, an `RG11B10Float` channel's
held at the largest finite value) and an `RGB9E5Float` word's mantissas half up, as Metal's
texture buffer stores them at that mode (an Apple M3 Max, macOS 27.0.1, by the conformance
crate's probe `texture_buffer_write_rounding`: every channel that is not a NaN, 262,112
half-float and 196,583 `RG11B10Float` channels of each texel type, and 65,536 `RGB9E5Float`
texels).
- `metal2vulkan-degrade-device-fragment-runs` (precision). `PrecisionNote::DeviceFragmentRuns`: A
fragment function that writes memory (`StageInterface::writes_memory`) in a render pipeline of
more than one sample, which the pipeline's compile records on its fragment stage, decided by the