test(xtask): cover the host API, BC formats, every copy shape and queue sequences in the Metal suite

This commit is contained in:
Tyler Smith committed 2026-11-05 05:14:33 +00:00
1 parent 8723512b7b
commit f93e096d4e
19 files changed
+3583 -72

No files matched your search

@@ -0,0 +1,232 @@
// The API surface around shaders: storage modes, host copies, inline
// constants, counters, visibility results, logging, reflection, resolves
// and render targets within a texture.
#include <metal_stdlib>
using namespace metal;
// Each element doubled plus its index.
kernel void touch(device uint *data [[buffer(0)]], uint i [[thread_position_in_grid]])
{
data[i] = data[i] * 2u + i;
}
// Nothing: a case whose outputs come from the host's copies alone.
kernel void nothing() {}
// Constants set inline with setBytes.
struct Params {
uint scale;
uint offset;
float4 weights;
};
kernel void params(device uint *data [[buffer(0)]], constant Params &p [[buffer(1)]],
uint i [[thread_position_in_grid]])
{
data[i] = data[i] * p.scale + p.offset + uint(p.weights[i % 4]);
}
// One minus each texel, from one texture into another.
kernel void invert_texture(texture2d<float, access::read> in [[texture(0)]],
texture2d<float, access::write> out [[texture(1)]],
uint2 p [[thread_position_in_grid]])
{
out.write(1.0f - in.read(p), p);
}
// Each texel of a 2D texture, row by row.
kernel void read_rows(texture2d<float> t [[texture(0)]], device float4 *out [[buffer(0)]],
uint2 p [[thread_position_in_grid]])
{
out[p.y * t.get_width() + p.x] = t.read(p);
}
// What the shader logs: formatted values, on the default log and on a
// named subsystem and category at each level.
constant os_log suite_log("com.stela.suite", "api");
kernel void log_values(device const uint *data [[buffer(0)]], uint i [[thread_position_in_grid]])
{
if (i != 0)
return;
os_log_default.log("value %u signed %d hex %x", data[0], int(data[1]), data[2]);
suite_log.log_debug("debug %u", data[3]);
suite_log.log_info("info %.3f", float(data[4]) / 8.0f);
suite_log.log_error("error text %u", data[2] & 0xFu);
suite_log.log_fault("fault %u", data[5]);
}
// A kernel whose every binding reflection reports.
struct Item {
float4 position;
uint id;
half2 uv;
float3x3 basis;
};
kernel void reflected(device Item *items [[buffer(0)]], constant float4 *weights [[buffer(2)]],
device const uint *ids [[buffer(5)]],
texture2d<half, access::read> src [[texture(0)]],
texture2d_array<uint, access::write> dst [[texture(3)]],
depth2d<float> shadow [[texture(4)]], sampler s [[sampler(1)]],
threadgroup float *scratch [[threadgroup(0)]],
uint i [[thread_position_in_grid]], uint l [[thread_index_in_threadgroup]])
{
threadgroup uint fixed[64];
fixed[l % 64] = ids[i];
scratch[l] = weights[i].x + float(src.read(uint2(i, 0)).x) + shadow.sample(s, float2(0.5f));
threadgroup_barrier(mem_flags::mem_threadgroup);
items[i].id = fixed[(l + 1) % 64] + uint(scratch[l]);
dst.write(uint4(items[i].id), uint2(i, 0), 0);
}
// Rectangles at a depth, four vertices each: x0, y0, x1, y1 and z.
struct DepthRect {
float4 rect;
float4 depth;
};
struct Placed {
float4 position [[position]];
};
vertex Placed vert_depth_rect(device const DepthRect *rects [[buffer(0)]], uint v [[vertex_id]])
{
DepthRect r = rects[v / 4];
uint c = v % 4;
return {float4(c & 1 ? r.rect.z : r.rect.x, c & 2 ? r.rect.w : r.rect.y, r.depth.x, 1.0f)};
}
fragment float4 frag_flat(Placed in [[stage_in]], constant float4 &color [[buffer(0)]])
{
return color;
}
// The fragment's depth as its colour.
fragment float4 frag_depth_color(Placed in [[stage_in]])
{
return float4(in.position.z);
}
// A rectangle and colour given inline with setVertexBytes and
// setFragmentBytes.
vertex Placed vert_inline_rect(constant float4 &r [[buffer(0)]], uint v [[vertex_id]])
{
return {float4(v & 1 ? r.z : r.x, v & 2 ? r.w : r.y, 0.0f, 1.0f)};
}
// Corners from a buffer, for indexed strips.
vertex Placed vert_corner(device const float2 *corners [[buffer(0)]], uint v [[vertex_id]])
{
return {float4(corners[v], 0.0f, 1.0f)};
}
// A colour whose alpha alpha-to-one replaces.
fragment float4 frag_translucent()
{
return float4(0.25f, 0.5f, 0.75f, 0.3f);
}
// Per sample: depth 0.1 * (sample + 1) and stencil sample + 1, for
// resolving each by its filter.
struct SampleDepth {
float4 color [[color(0)]];
float depth [[depth(any)]];
uint stencil [[stencil]];
};
fragment SampleDepth frag_sample_depth(Placed in [[stage_in]], uint s [[sample_id]])
{
return {float4(float(s) / 8.0f), 0.1f * float(s + 1), s + 1};
}
struct SampleDepthOnly {
float4 color [[color(0)]];
float depth [[depth(any)]];
};
fragment SampleDepthOnly frag_sample_depth_only(Placed in [[stage_in]], uint s [[sample_id]])
{
return {float4(float(s) / 8.0f), 0.1f * float(s + 1)};
}
fragment float4 frag_sample_value(Placed in [[stage_in]], uint s [[sample_id]])
{
return float4(float(s) / 8.0f);
}
// Each texel 1 where it is lit, for checking which lines a wireframe
// lights: per edge, whether enough texels within a texel of it are lit.
kernel void edge_hits(texture2d<float> t [[texture(0)]], device const float4 *edges [[buffer(0)]],
device uint *hits [[buffer(1)]], uint e [[thread_position_in_grid]])
{
float4 line = edges[e];
uint lit = 0, steps = 64;
for (uint k = 1; k < steps; k++) {
float2 p = mix(line.xy, line.zw, float(k) / float(steps));
bool near = false;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++) {
int2 q = int2(p) + int2(dx, dy);
if (q.x >= 0 && q.y >= 0 && q.x < int(t.get_width()) && q.y < int(t.get_height()))
near = near || t.read(uint2(q)).x > 0.0f;
}
lit += near ? 1u : 0u;
}
hits[e] = lit >= steps - 1 - 4 ? 1u : 0u;
}
// Each texel's stencil, read through a stencil view.
kernel void read_stencil(texture2d<uint> t [[texture(0)]], device uint *out [[buffer(0)]],
uint2 p [[thread_position_in_grid]])
{
out[p.y * t.get_width() + p.x] = t.read(p).x;
}
// A 1024-thread threadgroup over 32 KiB of threadgroup memory: each
// thread fills its share, then sums the mirrored share.
kernel void big_group(device uint *out [[buffer(0)]], threadgroup uint *shared [[threadgroup(0)]],
uint l [[thread_index_in_threadgroup]], uint n [[threads_per_threadgroup]])
{
for (uint k = l; k < 8192; k += n)
shared[k] = k * 3u;
threadgroup_barrier(mem_flags::mem_threadgroup);
uint sum = 0;
for (uint k = l; k < 8192; k += n)
sum += shared[8191 - k];
out[l] = sum;
}
// Bindings at the last index of the buffer, texture and sampler tables.
kernel void last_slots(device uint *out [[buffer(30)]], constant uint &k [[buffer(29)]],
texture2d<float> t [[texture(127)]], sampler s [[sampler(15)]])
{
out[0] = uint(round(t.sample(s, float2(0.5f)).x * 255.0f)) + k;
}
// Eight colour attachments, each written its index plus one.
struct Eight {
float c0 [[color(0)]];
float c1 [[color(1)]];
float c2 [[color(2)]];
float c3 [[color(3)]];
float c4 [[color(4)]];
float c5 [[color(5)]];
float c6 [[color(6)]];
float c7 [[color(7)]];
};
fragment Eight frag_eight(Placed in [[stage_in]])
{
return {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f};
}
// A position fetched from the last vertex attribute and buffer.
struct LastAttribute {
float2 position [[attribute(30)]];
};
vertex Placed vert_last_attribute(LastAttribute in [[stage_in]])
{
return {float4(in.position, 0.0f, 1.0f)};
}
@@ -0,0 +1,13 @@
// Compiled by the device at run time: SCALE and OFFSET come from the
// compile options' macros, and the language version from their version.
#include <metal_stdlib>
using namespace metal;
#ifndef OFFSET
#define OFFSET 7u
#endif
kernel void runtime_scale(device uint *data [[buffer(0)]], uint i [[thread_position_in_grid]])
{
data[i] = data[i] * SCALE + OFFSET + __METAL_VERSION__;
}
@@ -35,6 +35,30 @@ kernel void constants(device uint *out [[buffer(0)]],
out[9 + k] = as_type<uint>(c_vector[k]);
}
// The other scalar and vector types a constant can have.
constant char k_char [[function_constant(20)]];
constant uchar k_uchar [[function_constant(21)]];
constant ushort k_ushort [[function_constant(22)]];
constant int2 k_int2 [[function_constant(23)]];
constant uint4 k_uint4 [[function_constant(24)]];
constant half4 k_half4 [[function_constant(25)]];
constant float2 k_float2 [[function_constant(26)]];
kernel void constants_more(device uint *out [[buffer(0)]])
{
out[0] = uint(int(k_char));
out[1] = k_uchar;
out[2] = k_ushort;
out[3] = uint(k_int2.x);
out[4] = uint(k_int2.y);
for (uint k = 0; k < 4; k++) {
out[5 + k] = k_uint4[k];
out[9 + k] = as_type<ushort>(k_half4[k]);
}
out[13] = as_type<uint>(k_float2.x);
out[14] = as_type<uint>(k_float2.y);
}
// Constants select code: a loop bound and a branch the compiler removes.
kernel void constant_branches(device const float *in [[buffer(0)]], device float *out [[buffer(1)]],
uint i [[thread_position_in_grid]])
@@ -133,6 +157,26 @@ fragment float4 frag_visible(VisiblePixel p [[stage_in]], device const float *in
}
#endif
// An argument buffer read from a fragment function: a texture and a
// pointer to constants.
struct FragmentArguments {
texture2d<float> image;
constant float4 *tint;
};
struct ArgumentPixel {
float4 position [[position]];
};
vertex ArgumentPixel vert_argument_pixel(uint v [[vertex_id]])
{ return {float4(v & 1 ? 1.0f : -1.0f, v & 2 ? 1.0f : -1.0f, 0.0f, 1.0f)}; }
fragment float4 frag_arguments(ArgumentPixel p [[stage_in]], constant FragmentArguments &args [[buffer(0)]])
{
uint2 at = uint2(p.position.xy);
return args.image.read(at) * args.tint[at.x % 2];
}
#ifndef SKIP_stitched_call
[[stitchable]] float stitch_mul(float a, float b)
{
@@ -243,6 +243,19 @@ kernel void simdgroup_matrix(device const float *a [[buffer(0)]], device const f
}
#endif
#ifndef SKIP_simdgroup_matrix_bfloat
// An 8x8 bfloat SIMD-group matrix product, A * B + A.
kernel void simdgroup_matrix_bfloat(device const bfloat *a [[buffer(0)]], device const bfloat *b [[buffer(1)]],
device bfloat *out [[buffer(2)]])
{
simdgroup_bfloat8x8 ma, mb, mc;
simdgroup_load(ma, a, 8);
simdgroup_load(mb, b, 8);
simdgroup_multiply_accumulate(mc, ma, mb, ma);
simdgroup_store(mc, out, 8);
}
#endif
struct Mixed {
char c;
short s;
@@ -155,6 +155,19 @@ fragment float4 frag_color(Full in [[stage_in]], device const float4 *c [[buffer
return c[pixel(in.position, width)];
}
// Integer outputs for integer targets, from the same per-pixel buffer.
fragment uint4 frag_color_uint(Full in [[stage_in]], device const uint4 *c [[buffer(0)]],
constant uint &width [[buffer(1)]])
{
return c[pixel(in.position, width)];
}
fragment int4 frag_color_int(Full in [[stage_in]], device const int4 *c [[buffer(0)]],
constant uint &width [[buffer(1)]])
{
return c[pixel(in.position, width)];
}
fragment half4 frag_color_half(Full in [[stage_in]], device const float4 *c [[buffer(0)]],
constant uint &width [[buffer(1)]])
{
@@ -164,6 +164,82 @@ kernel void read_write(texture2d<float, access::read_write> t [[texture(0)]], ui
}
#endif
#ifndef SKIP_read_write
// Read-write integer textures: each texel times three plus its rotated
// lanes, plus or minus one.
kernel void read_write_uint(texture2d<uint, access::read_write> t [[texture(0)]], uint2 p [[thread_position_in_grid]])
{
uint4 v = t.read(p);
t.fence();
t.write(v * 3u + v.yzwx + 1u, p);
}
kernel void read_write_int(texture2d<int, access::read_write> t [[texture(0)]], uint2 p [[thread_position_in_grid]])
{
int4 v = t.read(p);
t.fence();
t.write(v * 3 + v.yzwx - 1, p);
}
#endif
#ifndef SKIP_texture_atomics_ops
// Every texture atomic: thread i applies op i % 8 to texel i % 8 of row 0;
// in row 1, every thread tries once to swap 0 for its index + 1 and
// counts its success, and exchanges its index + 1 into texel 1.
template <typename T>
static void atomic_ops(texture2d<T, access::read_write> t, device atomic_uint *wins, T v, uint i)
{
uint2 p = uint2(i % 8, 0);
switch (i % 8) {
case 0: t.atomic_fetch_add(p, v); break;
case 1: t.atomic_fetch_sub(p, v); break;
case 2: t.atomic_fetch_and(p, v); break;
case 3: t.atomic_fetch_or(p, v); break;
case 4: t.atomic_fetch_xor(p, v); break;
case 5: t.atomic_fetch_min(p, v); break;
case 6: t.atomic_fetch_max(p, v); break;
default: t.atomic_fetch_add(p, T(1)); break;
}
// A weak exchange may fail spuriously: retried while the texel is 0.
vec<T, 4> expected = vec<T, 4>(0);
while (!t.atomic_compare_exchange_weak(uint2(0, 1), &expected, T(i + 1))) {
if (expected.x != 0)
break;
}
if (expected.x == 0)
atomic_fetch_add_explicit(wins, 1u, memory_order_relaxed);
t.atomic_exchange(uint2(1, 1), T(i + 1));
}
kernel void texture_atomics_uint(texture2d<uint, access::read_write> t [[texture(0)]], device const uint *v [[buffer(0)]],
device atomic_uint *wins [[buffer(1)]], uint i [[thread_position_in_grid]])
{
atomic_ops(t, wins, v[i], i);
}
kernel void texture_atomics_int(texture2d<int, access::read_write> t [[texture(0)]], device const int *v [[buffer(0)]],
device atomic_uint *wins [[buffer(1)]], uint i [[thread_position_in_grid]])
{
atomic_ops(t, wins, v[i], i);
}
// An atomic add on each texture type that has atomics, at texel i % 4.
kernel void texture_atomics_types(texture1d<uint, access::read_write> t1 [[texture(0)]],
texture1d_array<uint, access::read_write> t1a [[texture(1)]],
texture2d_array<uint, access::read_write> t2a [[texture(2)]],
texture3d<uint, access::read_write> t3 [[texture(3)]],
texture_buffer<uint, access::read_write> tb [[texture(4)]],
uint i [[thread_position_in_grid]])
{
uint k = i % 4;
t1.atomic_fetch_add(k, 1u);
t1a.atomic_fetch_add(k, 1, 2u);
t2a.atomic_fetch_add(uint2(k, 1), 1, 3u);
t3.atomic_fetch_add(uint3(k, 1, 1), 4u);
tb.atomic_fetch_add(k, 5u);
}
#endif
#ifndef SKIP_texture_atomics
// Texture atomics: every thread adds to one of 16 texels.
kernel void texture_atomics(texture2d<uint, access::read_write> t [[texture(0)]],
@@ -15,7 +15,9 @@
* Nothing here interprets results: the plan says what to bind and dispatch.
*/
#import <Foundation/Foundation.h>
#import <CoreImage/CoreImage.h>
#import <Metal/Metal.h>
#import <MetalPerformanceShaders/MetalPerformanceShaders.h>
#include <stdio.h>
static NSString *plan_dir;
@@ -38,6 +40,7 @@ static BOOL timing;
@property(retain) NSMutableDictionary<NSString *, id<MTLHeap>> *heaps;
@property(retain) NSMutableDictionary *libraries;
@property(retain) NSDictionary *plan;
@property(retain) id<MTLCommandQueue> queue;
@end
@implementation Case
@end
@@ -80,6 +83,7 @@ static NSDictionary<NSString *, NSNumber *> *pixel_formats(void)
@"r16uint" : @(MTLPixelFormatR16Uint), @"r16sint" : @(MTLPixelFormatR16Sint),
@"r16float" : @(MTLPixelFormatR16Float), @"rg8unorm" : @(MTLPixelFormatRG8Unorm),
@"rg8snorm" : @(MTLPixelFormatRG8Snorm), @"rg8uint" : @(MTLPixelFormatRG8Uint),
@"rg8sint" : @(MTLPixelFormatRG8Sint), @"rg8unorm_srgb" : @(MTLPixelFormatRG8Unorm_sRGB),
@"b5g6r5unorm" : @(MTLPixelFormatB5G6R5Unorm), @"a1bgr5unorm" : @(MTLPixelFormatA1BGR5Unorm),
@"abgr4unorm" : @(MTLPixelFormatABGR4Unorm), @"bgr5a1unorm" : @(MTLPixelFormatBGR5A1Unorm),
@"r32uint" : @(MTLPixelFormatR32Uint), @"r32sint" : @(MTLPixelFormatR32Sint),
@@ -100,7 +104,13 @@ static NSDictionary<NSString *, NSNumber *> *pixel_formats(void)
@"rgba32sint" : @(MTLPixelFormatRGBA32Sint), @"rgba32float" : @(MTLPixelFormatRGBA32Float),
@"bc1_rgba" : @(MTLPixelFormatBC1_RGBA), @"bc3_rgba" : @(MTLPixelFormatBC3_RGBA),
@"bc4_runorm" : @(MTLPixelFormatBC4_RUnorm), @"bc5_rgunorm" : @(MTLPixelFormatBC5_RGUnorm),
@"bc7_rgbaunorm" : @(MTLPixelFormatBC7_RGBAUnorm),
@"bc7_rgbaunorm" : @(MTLPixelFormatBC7_RGBAUnorm), @"bc7_rgbaunorm_srgb" : @(MTLPixelFormatBC7_RGBAUnorm_sRGB),
@"bc1_rgba_srgb" : @(MTLPixelFormatBC1_RGBA_sRGB), @"bc2_rgba" : @(MTLPixelFormatBC2_RGBA),
@"bc2_rgba_srgb" : @(MTLPixelFormatBC2_RGBA_sRGB), @"bc3_rgba_srgb" : @(MTLPixelFormatBC3_RGBA_sRGB),
@"bc4_rsnorm" : @(MTLPixelFormatBC4_RSnorm), @"bc5_rgsnorm" : @(MTLPixelFormatBC5_RGSnorm),
@"bc6h_rgbfloat" : @(MTLPixelFormatBC6H_RGBFloat), @"bc6h_rgbufloat" : @(MTLPixelFormatBC6H_RGBUfloat),
@"depth24unorm_stencil8" : @(MTLPixelFormatDepth24Unorm_Stencil8),
@"x32_stencil8" : @(MTLPixelFormatX32_Stencil8), @"x24_stencil8" : @(MTLPixelFormatX24_Stencil8),
@"depth16unorm" : @(MTLPixelFormatDepth16Unorm), @"depth32float" : @(MTLPixelFormatDepth32Float),
@"stencil8" : @(MTLPixelFormatStencil8),
@"depth32float_stencil8" : @(MTLPixelFormatDepth32Float_Stencil8),
@@ -258,6 +268,31 @@ static id<MTLLibrary> library_named(id<MTLDevice> device, NSDictionary *plan, NS
id where = plan[@"libraries"][name];
if (!where)
@throw failure(@"plan has no library %@", name);
if ([where isKindOfClass:[NSDictionary class]]) {
/* Compiled from source by the device at run time, with the
* options an application passes. */
NSDictionary *w = where;
NSString *source = [[NSString alloc] initWithData:read_file(w[@"source"]) encoding:NSUTF8StringEncoding];
MTLCompileOptions *o = [MTLCompileOptions new];
NSDictionary *versions = @{@"2.0" : @(MTLLanguageVersion2_0), @"2.1" : @(MTLLanguageVersion2_1), @"2.2" : @(MTLLanguageVersion2_2),
@"2.3" : @(MTLLanguageVersion2_3), @"2.4" : @(MTLLanguageVersion2_4), @"3.0" : @(MTLLanguageVersion3_0),
@"3.1" : @(MTLLanguageVersion3_1)};
if (w[@"language"])
o.languageVersion = lookup(versions, @"language version", w[@"language"]);
if (w[@"fast_math"])
o.fastMathEnabled = [w[@"fast_math"] boolValue];
if (w[@"macros"])
o.preprocessorMacros = w[@"macros"];
o.preserveInvariance = [w[@"preserve_invariance"] boolValue];
if ([w[@"optimization"] isEqualToString:@"size"])
o.optimizationLevel = MTLLibraryOptimizationLevelSize;
NSError *error = nil;
id<MTLLibrary> library = [device newLibraryWithSource:source options:o error:&error];
if (!library)
@throw failure(@"library %@ from source: %@", name, error.localizedDescription);
cache[name] = library;
return library;
}
NSArray *candidates = [where isKindOfClass:[NSArray class]] ? where : @[ [plan_dir stringByAppendingPathComponent:where] ];
for (NSString *path in candidates) {
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
@@ -357,9 +392,20 @@ static id<MTLHeap> make_heap(Case *c, NSDictionary *h)
return heap;
}
static MTLResourceOptions storage_option(NSString *storage)
{
if ([storage isEqualToString:@"private"])
return MTLResourceStorageModePrivate;
if ([storage isEqualToString:@"managed"])
return MTLResourceStorageModeManaged;
if (storage && ![storage isEqualToString:@"shared"])
@throw failure(@"unknown storage mode %@", storage);
return MTLResourceStorageModeShared;
}
static MTLResourceOptions buffer_options(NSDictionary *b)
{
MTLResourceOptions options = MTLResourceStorageModeShared;
MTLResourceOptions options = storage_option(b[@"storage"]);
if ([b[@"untracked"] boolValue])
options |= MTLResourceHazardTrackingModeUntracked;
return options;
@@ -369,6 +415,15 @@ static MTLResourceOptions buffer_options(NSDictionary *b)
* an offset when that heap places its resources. */
static id<MTLBuffer> allocate_buffer(Case *c, NSDictionary *b, NSUInteger length)
{
if ([b[@"no_copy"] boolValue]) {
/* Memory the application owns, wrapped without a copy. */
NSUInteger page = (NSUInteger)getpagesize(), bytes = (length + page - 1) / page * page;
void *memory = NULL;
if (posix_memalign(&memory, page, bytes))
return nil;
return [c.device newBufferWithBytesNoCopy:memory length:bytes options:buffer_options(b)
deallocator:^(void *pointer, NSUInteger _) { free(pointer); }];
}
if (!b[@"heap"])
return [c.device newBufferWithLength:length options:buffer_options(b)];
id<MTLHeap> heap = c.heaps[b[@"heap"]];
@@ -381,25 +436,44 @@ static id<MTLBuffer> allocate_buffer(Case *c, NSDictionary *b, NSUInteger length
return [heap newBufferWithLength:length options:options];
}
/* Runs one blit on the case's queue and waits for it. */
static void blit_now(Case *c, void (^encode)(id<MTLBlitCommandEncoder>))
{
id<MTLCommandBuffer> cb = [c.queue commandBuffer];
id<MTLBlitCommandEncoder> e = [cb blitCommandEncoder];
encode(e);
[e endEncoding];
[cb commit];
[cb waitUntilCompleted];
if (cb.error)
@throw failure(@"blit: %@", cb.error.localizedDescription);
}
static id<MTLBuffer> make_buffer(Case *c, NSDictionary *b)
{
id<MTLBuffer> buffer;
if (b[@"file"]) {
NSData *data = read_file(b[@"file"]);
NSUInteger length = MAX(number(b, @"length", data.length), data.length);
buffer = allocate_buffer(c, b, MAX(length, 16));
if (buffer && !b[@"alias_of"])
memcpy(buffer.contents, data.bytes, data.length);
} else {
NSUInteger length = number(b, @"length", 16);
buffer = allocate_buffer(c, b, MAX(length, 16));
/* An alias keeps the bytes of the resource it overlaps. */
if (buffer && !b[@"alias_of"])
memset(buffer.contents, (int)number(b, @"fill", 0), buffer.length);
}
NSData *data = b[@"file"] ? read_file(b[@"file"]) : nil;
NSUInteger length = MAX(MAX(number(b, @"length", data ? data.length : 16), data.length), (NSUInteger)16);
id<MTLBuffer> buffer = allocate_buffer(c, b, length);
if (!buffer)
@throw failure(@"buffer %@ allocation failed", b[@"name"]);
buffer.label = b[@"name"];
/* An alias keeps the bytes of the resource it overlaps. */
if (b[@"alias_of"])
return buffer;
/* The initial bytes go in through the CPU, or through a staging
* buffer and a blit when the CPU cannot reach the storage. */
id<MTLBuffer> target = buffer;
if (buffer.storageMode == MTLStorageModePrivate)
target = [c.device newBufferWithLength:buffer.length options:MTLResourceStorageModeShared];
memset(target.contents, (int)number(b, @"fill", 0), target.length);
if (data)
memcpy(target.contents, data.bytes, data.length);
if (buffer.storageMode == MTLStorageModeManaged)
[buffer didModifyRange:NSMakeRange(0, buffer.length)];
if (target != buffer)
blit_now(c, ^(id<MTLBlitCommandEncoder> e) {
[e copyFromBuffer:target sourceOffset:0 toBuffer:buffer destinationOffset:0 size:buffer.length];
});
return buffer;
}
@@ -416,6 +490,7 @@ static NSUInteger pixel_bytes(MTLPixelFormat f, NSUInteger *block)
case MTLPixelFormatR16Unorm: case MTLPixelFormatR16Snorm: case MTLPixelFormatR16Uint:
case MTLPixelFormatR16Sint: case MTLPixelFormatR16Float: case MTLPixelFormatRG8Unorm:
case MTLPixelFormatRG8Snorm: case MTLPixelFormatRG8Uint: case MTLPixelFormatB5G6R5Unorm:
case MTLPixelFormatRG8Sint: case MTLPixelFormatRG8Unorm_sRGB:
case MTLPixelFormatA1BGR5Unorm: case MTLPixelFormatABGR4Unorm: case MTLPixelFormatBGR5A1Unorm:
case MTLPixelFormatDepth16Unorm:
return 2;
@@ -425,10 +500,12 @@ static NSUInteger pixel_bytes(MTLPixelFormat f, NSUInteger *block)
return 8;
case MTLPixelFormatRGBA32Uint: case MTLPixelFormatRGBA32Sint: case MTLPixelFormatRGBA32Float:
return 16;
case MTLPixelFormatBC1_RGBA: case MTLPixelFormatBC4_RUnorm:
case MTLPixelFormatBC1_RGBA: case MTLPixelFormatBC1_RGBA_sRGB: case MTLPixelFormatBC4_RUnorm: case MTLPixelFormatBC4_RSnorm:
*block = 4;
return 8;
case MTLPixelFormatBC3_RGBA: case MTLPixelFormatBC5_RGUnorm: case MTLPixelFormatBC7_RGBAUnorm:
case MTLPixelFormatBC2_RGBA: case MTLPixelFormatBC2_RGBA_sRGB: case MTLPixelFormatBC3_RGBA: case MTLPixelFormatBC3_RGBA_sRGB:
case MTLPixelFormatBC5_RGUnorm: case MTLPixelFormatBC5_RGSnorm: case MTLPixelFormatBC6H_RGBFloat:
case MTLPixelFormatBC6H_RGBUfloat: case MTLPixelFormatBC7_RGBAUnorm: case MTLPixelFormatBC7_RGBAUnorm_sRGB:
*block = 4;
return 16;
default:
@@ -452,7 +529,7 @@ static NSArray<NSValue *> *regions_of(id<MTLTexture> t, NSString *aspect, NSUInt
{
NSMutableArray *out = [NSMutableArray new];
NSUInteger block, bytes = pixel_bytes(t.pixelFormat, &block), offset = 0;
if (t.pixelFormat == MTLPixelFormatDepth32Float_Stencil8)
if (t.pixelFormat == MTLPixelFormatDepth32Float_Stencil8 || t.pixelFormat == MTLPixelFormatDepth24Unorm_Stencil8)
bytes = [aspect isEqualToString:@"stencil"] ? 1 : 4;
NSUInteger slices = t.arrayLength * (t.textureType == MTLTextureTypeCube || t.textureType == MTLTextureTypeCubeArray ? 6 : 1);
for (NSUInteger slice = 0; slice < slices; slice++) {
@@ -471,11 +548,25 @@ static NSArray<NSValue *> *regions_of(id<MTLTexture> t, NSString *aspect, NSUInt
static MTLBlitOption blit_option(MTLPixelFormat f, NSString *aspect)
{
if (f == MTLPixelFormatDepth32Float_Stencil8)
if (f == MTLPixelFormatDepth32Float_Stencil8 || f == MTLPixelFormatDepth24Unorm_Stencil8)
return [aspect isEqualToString:@"stencil"] ? MTLBlitOptionStencilFromDepthStencil : MTLBlitOptionDepthFromDepthStencil;
return MTLBlitOptionNone;
}
static MTLTextureUsage texture_usage(NSDictionary *t)
{
MTLTextureUsage usage = 0;
for (NSString *u in t[@"usage"] ?: @[ @"read" ]) {
if ([u isEqualToString:@"read"]) usage |= MTLTextureUsageShaderRead;
else if ([u isEqualToString:@"write"]) usage |= MTLTextureUsageShaderWrite;
else if ([u isEqualToString:@"render"]) usage |= MTLTextureUsageRenderTarget;
else if ([u isEqualToString:@"atomic"]) usage |= MTLTextureUsageShaderAtomic;
else if ([u isEqualToString:@"view"]) usage |= MTLTextureUsagePixelFormatView;
else @throw failure(@"unknown texture usage %@", u);
}
return usage;
}
/* A texture buffer: a linear view of one of the case's buffers. */
static id<MTLTexture> make_texture_buffer(Case *c, NSDictionary *t)
{
@@ -488,7 +579,7 @@ static id<MTLTexture> make_texture_buffer(Case *c, NSDictionary *t)
NSUInteger align = [c.device minimumTextureBufferAlignmentForPixelFormat:format];
MTLTextureDescriptor *d = [MTLTextureDescriptor textureBufferDescriptorWithPixelFormat:format width:width
resourceOptions:storage.resourceOptions
usage:MTLTextureUsageShaderRead];
usage:texture_usage(t)];
id<MTLTexture> texture = [storage newTextureWithDescriptor:d offset:number(t, @"offset", 0)
bytesPerRow:(row + align - 1) / align * align];
if (!texture)
@@ -534,19 +625,20 @@ static id<MTLTexture> make_texture(Case *c, NSDictionary *t, id<MTLCommandQueue>
d.arrayLength = number(t, @"array", 1);
d.mipmapLevelCount = number(t, @"mipmaps", 1);
d.sampleCount = number(t, @"samples", 1);
d.storageMode = MTLStorageModePrivate;
MTLTextureUsage usage = 0;
for (NSString *u in t[@"usage"] ?: @[ @"read" ]) {
if ([u isEqualToString:@"read"]) usage |= MTLTextureUsageShaderRead;
else if ([u isEqualToString:@"write"]) usage |= MTLTextureUsageShaderWrite;
else if ([u isEqualToString:@"render"]) usage |= MTLTextureUsageRenderTarget;
else if ([u isEqualToString:@"atomic"]) usage |= MTLTextureUsageShaderAtomic;
else if ([u isEqualToString:@"view"]) usage |= MTLTextureUsagePixelFormatView;
else @throw failure(@"unknown texture usage %@", u);
}
d.usage = usage;
d.storageMode = t[@"storage"] ? (MTLStorageMode)(storage_option(t[@"storage"]) >> MTLResourceStorageModeShift)
: MTLStorageModePrivate;
d.usage = texture_usage(t);
id<MTLTexture> texture;
if (t[@"heap"]) {
if (t[@"over_buffer"]) {
/* A linear 2D texture over a buffer's bytes, rows `bytes_per_row`
* apart, the buffer's contents its texels. */
id<MTLBuffer> storage = c.buffers[t[@"over_buffer"]];
if (!storage)
@throw failure(@"texture %@ names no buffer", t[@"name"]);
d.storageMode = storage.storageMode;
d.resourceOptions = storage.resourceOptions;
texture = [storage newTextureWithDescriptor:d offset:number(t, @"offset", 0) bytesPerRow:number(t, @"bytes_per_row", 256)];
} else if (t[@"heap"]) {
id<MTLHeap> heap = c.heaps[t[@"heap"]];
if (!heap)
@throw failure(@"texture %@ names no heap", t[@"name"]);
@@ -569,6 +661,24 @@ static id<MTLTexture> make_texture(Case *c, NSDictionary *t, id<MTLCommandQueue>
NSArray *regions = regions_of(texture, aspect, &total);
if (data.length < total)
@throw failure(@"texture %@ input has %lu bytes, needs %lu", t[@"name"], (unsigned long)data.length, (unsigned long)total);
if (texture.storageMode != MTLStorageModePrivate) {
/* A texture the CPU reaches takes its texels from the CPU,
* rows and images `row_padding` bytes apart beyond their
* texels. */
NSUInteger pad = number(t, @"row_padding", 0);
for (NSValue *v in regions) {
struct region r;
[v getValue:&r];
NSUInteger rows = r.bytes_per_image / r.bytes_per_row, row = r.bytes_per_row + pad;
NSMutableData *padded = [NSMutableData dataWithLength:row * rows * r.size.depth];
for (NSUInteger k = 0; k < rows * r.size.depth; k++)
memcpy((uint8_t *)padded.mutableBytes + k * row, (const uint8_t *)data.bytes + r.offset + k * r.bytes_per_row,
r.bytes_per_row);
[texture replaceRegion:MTLRegionMake3D(0, 0, 0, r.size.width, r.size.height, r.size.depth)
mipmapLevel:r.level slice:r.slice withBytes:padded.bytes bytesPerRow:row bytesPerImage:row * rows];
}
continue;
}
id<MTLBuffer> staging = [c.device newBufferWithBytes:data.bytes length:total options:MTLResourceStorageModeShared];
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
@@ -624,6 +734,17 @@ static id<MTLSamplerState> make_sampler(Case *c, NSDictionary *s)
if (s[@"compare"])
d.compareFunction = lookup(compare_functions(), @"compare function", s[@"compare"]);
d.supportArgumentBuffers = [s[@"argument_buffers"] boolValue];
if (s[@"reduction"] || s[@"lod_bias"]) {
if (@available(macOS 26.0, *)) {
NSDictionary *reductions = @{@"weighted_average" : @(MTLSamplerReductionModeWeightedAverage),
@"minimum" : @(MTLSamplerReductionModeMinimum),
@"maximum" : @(MTLSamplerReductionModeMaximum)};
d.reductionMode = lookup(reductions, @"reduction mode", s[@"reduction"] ?: @"weighted_average");
d.lodBias = [s[@"lod_bias"] floatValue];
} else {
@throw [NSException exceptionWithName:@"CaseUnsupported" reason:@"sampler reduction and bias need macOS 26" userInfo:nil];
}
}
id<MTLSamplerState> sampler = [c.device newSamplerStateWithDescriptor:d];
if (!sampler)
@throw failure(@"sampler %@ creation failed", s[@"name"]);
@@ -730,11 +851,25 @@ static void encode_arguments(Case *c, NSDictionary *a)
}
}
/* The bytes an inline buffer records: its declared length, or all of it. */
static NSUInteger inline_length(NSDictionary *b, id<MTLBuffer> buffer)
{
NSUInteger length = number(b, @"length", 0);
return length ? MIN(length, buffer.length) : buffer.length;
}
static void bind_compute(Case *c, id<MTLComputeCommandEncoder> e, NSDictionary *spec)
{
for (NSDictionary *b in spec[@"buffers"])
if (b[@"index"])
[e setBuffer:c.buffers[b[@"name"]] offset:number(b, @"offset", 0) atIndex:number(b, @"index", 0)];
for (NSDictionary *b in spec[@"buffers"]) {
if (!b[@"index"])
continue;
id<MTLBuffer> buffer = c.buffers[b[@"name"]];
/* An inline buffer's bytes are recorded into the command. */
if ([b[@"inline"] boolValue])
[e setBytes:buffer.contents length:inline_length(b, buffer) atIndex:number(b, @"index", 0)];
else
[e setBuffer:buffer offset:number(b, @"offset", 0) atIndex:number(b, @"index", 0)];
}
for (NSDictionary *t in spec[@"textures"])
if (t[@"index"])
[e setTexture:c.textures[t[@"name"]] atIndex:number(t, @"index", 0)];
@@ -759,9 +894,19 @@ static void bind_render(Case *c, id<MTLRenderCommandEncoder> e, NSDictionary *sp
NSString *stage = b[@"stage"] ?: @"fragment";
id<MTLBuffer> buffer = c.buffers[b[@"name"]];
NSUInteger offset = number(b, @"offset", 0), index = number(b, @"index", 0);
if ([stage isEqualToString:@"vertex"] || [stage isEqualToString:@"both"])
BOOL vertex = [stage isEqualToString:@"vertex"] || [stage isEqualToString:@"both"];
BOOL fragment = [stage isEqualToString:@"fragment"] || [stage isEqualToString:@"both"];
if ([b[@"inline"] boolValue]) {
NSUInteger length = inline_length(b, buffer);
if (vertex)
[e setVertexBytes:buffer.contents length:length atIndex:index];
if (fragment)
[e setFragmentBytes:buffer.contents length:length atIndex:index];
continue;
}
if (vertex)
[e setVertexBuffer:buffer offset:offset atIndex:index];
if ([stage isEqualToString:@"fragment"] || [stage isEqualToString:@"both"])
if (fragment)
[e setFragmentBuffer:buffer offset:offset atIndex:index];
if ([stage isEqualToString:@"object"])
[e setObjectBuffer:buffer offset:offset atIndex:index];
@@ -831,6 +976,132 @@ static id<MTLFunction> stitched_function(Case *c, id<MTLLibrary> library, NSDict
return function_named(stitched, g[@"name"], nil);
}
/* The device's counter set of a common name: timestamp or statistic. */
static id<MTLCounterSet> counter_set(id<MTLDevice> d, NSString *name)
{
NSString *common = [name isEqualToString:@"statistic"] ? MTLCommonCounterSetStatistic : MTLCommonCounterSetTimestamp;
for (id<MTLCounterSet> set in d.counterSets)
if ([set.name isEqualToString:common])
return set;
@throw [NSException exceptionWithName:@"CaseUnsupported" reason:[NSString stringWithFormat:@"no %@ counter set", name] userInfo:nil];
}
/* Once the command buffer completes, the samples resolved into the named
* buffer: timestamps as sampled, statistics as the counts between each
* pair of samples. */
static void resolve_counters_after(Case *c, id<MTLCommandBuffer> cb, id<MTLCounterSampleBuffer> samples, NSUInteger count,
NSDictionary *spec)
{
id<MTLBuffer> out = c.buffers[spec[@"buffer"]];
if (!out)
@throw failure(@"counters name no buffer %@", spec[@"buffer"]);
BOOL statistic = [spec[@"counters"] isEqualToString:@"statistic"];
[cb addCompletedHandler:^(id<MTLCommandBuffer> _) {
NSData *data = [samples resolveCounterRange:NSMakeRange(0, count)];
memset(out.contents, 0, out.length);
if (!statistic) {
memcpy(out.contents, data.bytes, MIN(data.length, out.length));
return;
}
const MTLCounterResultStatistic *s = data.bytes;
uint64_t *o = out.contents;
const NSUInteger fields = sizeof(MTLCounterResultStatistic) / sizeof(uint64_t);
for (NSUInteger pair = 0; pair + 1 < count && (pair / 2 + 1) * fields * 8 <= out.length; pair += 2) {
const uint64_t *from = (const uint64_t *)&s[pair], *to = (const uint64_t *)&s[pair + 1];
for (NSUInteger f = 0; f < fields; f++)
o[pair / 2 * fields + f] = to[f] - from[f];
}
}];
}
/* The named buffer's bytes replaced by a text and zeros after it. */
static void write_text(Case *c, NSString *name, NSString *text)
{
id<MTLBuffer> out = c.buffers[name];
if (!out)
@throw failure(@"text output names no buffer %@", name);
NSData *bytes = [text dataUsingEncoding:NSUTF8StringEncoding];
memset(out.contents, 0, out.length);
memcpy(out.contents, bytes.bytes, MIN(bytes.length, out.length));
}
/* A command buffer, with a log state that collects what its shaders log
* when the case asks for `log`. */
static id<MTLCommandBuffer> command_buffer(Case *c, id<MTLCommandQueue> queue, NSDictionary *spec, NSMutableArray *lines)
{
if (!spec[@"log"])
return [queue commandBuffer];
if (@available(macOS 15.0, *)) {
MTLLogStateDescriptor *ld = [MTLLogStateDescriptor new];
ld.level = MTLLogLevelDebug;
ld.bufferSize = 65536;
NSError *error = nil;
id<MTLLogState> state = [c.device newLogStateWithDescriptor:ld error:&error];
if (!state)
@throw failure(@"log state: %@", error.localizedDescription);
[state addLogHandler:^(NSString *subsystem, NSString *category, MTLLogLevel level, NSString *message) {
@synchronized(lines) {
[lines addObject:[NSString stringWithFormat:@"%@ %@ %ld %@", subsystem ?: @"-", category ?: @"-", (long)level, message]];
}
}];
MTLCommandBufferDescriptor *cd = [MTLCommandBufferDescriptor new];
cd.logState = state;
return [queue commandBufferWithDescriptor:cd];
}
@throw [NSException exceptionWithName:@"CaseUnsupported" reason:@"shader logging needs macOS 15" userInfo:nil];
}
/* The logged lines, once `count` have arrived or two seconds passed, in
* the order the log handler received them. */
static void store_log(Case *c, NSDictionary *spec, NSMutableArray *lines)
{
NSUInteger want = number(spec[@"log"], @"lines", 1);
for (int k = 0; k < 200; k++) {
@synchronized(lines) {
if (lines.count >= want)
break;
}
usleep(10000);
}
@synchronized(lines) {
write_text(c, spec[@"log"][@"buffer"], [[lines componentsJoinedByString:@"\n"] stringByAppendingString:@"\n"]);
}
}
/* A pipeline's bindings, one line each in index order within each kind:
* what an application learns from reflection. */
static NSString *bindings_text(NSArray<id<MTLBinding>> *bindings)
{
NSMutableArray *lines = [NSMutableArray new];
NSArray *sorted = [bindings sortedArrayUsingComparator:^NSComparisonResult(id<MTLBinding> a, id<MTLBinding> b) {
if (a.type != b.type)
return a.type < b.type ? NSOrderedAscending : NSOrderedDescending;
return a.index < b.index ? NSOrderedAscending : a.index > b.index ? NSOrderedDescending : NSOrderedSame;
}];
for (id<MTLBinding> b in sorted) {
NSMutableString *line = [NSMutableString stringWithFormat:@"%@ type=%ld index=%lu access=%ld used=%d argument=%d", b.name,
(long)b.type, (unsigned long)b.index, (long)b.access, b.used, b.argument];
if ([b conformsToProtocol:@protocol(MTLBufferBinding)]) {
id<MTLBufferBinding> bb = (id<MTLBufferBinding>)b;
[line appendFormat:@" size=%lu align=%lu data=%ld", (unsigned long)bb.bufferDataSize, (unsigned long)bb.bufferAlignment,
(long)bb.bufferDataType];
if (bb.bufferStructType)
for (MTLStructMember *m in bb.bufferStructType.members)
[line appendFormat:@" %@@%lu:%ld", m.name, (unsigned long)m.offset, (long)m.dataType];
} else if ([b conformsToProtocol:@protocol(MTLTextureBinding)]) {
id<MTLTextureBinding> tb = (id<MTLTextureBinding>)b;
[line appendFormat:@" texture=%ld data=%ld depth=%d array=%lu", (long)tb.textureType, (long)tb.textureDataType,
tb.depthTexture, (unsigned long)tb.arrayLength];
} else if ([b conformsToProtocol:@protocol(MTLThreadgroupBinding)]) {
id<MTLThreadgroupBinding> gb = (id<MTLThreadgroupBinding>)b;
[line appendFormat:@" size=%lu align=%lu", (unsigned long)gb.threadgroupMemoryDataSize,
(unsigned long)gb.threadgroupMemoryAlignment];
}
[lines addObject:line];
}
return [lines componentsJoinedByString:@"\n"];
}
static void wait_for(id<MTLCommandBuffer> cb, NSDictionary *spec)
{
dispatch_semaphore_t done = dispatch_semaphore_create(0);
@@ -940,13 +1211,44 @@ static id<MTLComputeCommandEncoder> encode_compute(Case *c, id<MTLCommandBuffer>
d.linkedFunctions = l;
}
NSError *error = nil;
MTLComputePipelineReflection *reflection = nil;
id<MTLComputePipelineState> pipeline = [c.device newComputePipelineStateWithDescriptor:d
options:MTLPipelineOptionNone
reflection:nil
options:spec[@"reflection"] ? MTLPipelineOptionBindingInfo | MTLPipelineOptionBufferTypeInfo : MTLPipelineOptionNone
reflection:spec[@"reflection"] ? &reflection : nil
error:&error];
if (!pipeline)
@throw failure(@"compute pipeline: %@", error.localizedDescription);
id<MTLComputeCommandEncoder> e = open ?: [cb computeCommandEncoder];
if (spec[@"reflection"])
write_text(c, spec[@"reflection"], [NSString stringWithFormat:@"%@\nstatic_threadgroup_memory=%lu\n",
bindings_text(reflection.bindings),
(unsigned long)pipeline.staticThreadgroupMemoryLength]);
id<MTLComputeCommandEncoder> e = open;
/* A barrier between dispatches of one encoder, scoped as named. */
if (e && spec[@"barrier"]) {
NSString *b = spec[@"barrier"];
MTLBarrierScope scope = ([b containsString:@"buffers"] ? MTLBarrierScopeBuffers : 0) |
([b containsString:@"textures"] ? MTLBarrierScopeTextures : 0);
[e memoryBarrierWithScope:scope];
}
if (!e && [spec[@"concurrent"] boolValue])
e = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent];
if (!e && spec[@"timestamps"]) {
/* Samples at the start and end of the encoder's work. */
MTLCounterSampleBufferDescriptor *sd = [MTLCounterSampleBufferDescriptor new];
sd.counterSet = counter_set(c.device, spec[@"timestamps"][@"counters"] ?: @"timestamp");
sd.sampleCount = 2;
sd.storageMode = MTLStorageModeShared;
id<MTLCounterSampleBuffer> samples = [c.device newCounterSampleBufferWithDescriptor:sd error:&error];
if (!samples)
@throw failure(@"counter sample buffer: %@", error.localizedDescription);
MTLComputePassDescriptor *cp = [MTLComputePassDescriptor computePassDescriptor];
cp.sampleBufferAttachments[0].sampleBuffer = samples;
cp.sampleBufferAttachments[0].startOfEncoderSampleIndex = 0;
cp.sampleBufferAttachments[0].endOfEncoderSampleIndex = 1;
resolve_counters_after(c, cb, samples, 2, spec[@"timestamps"]);
e = [cb computeCommandEncoderWithDescriptor:cp];
}
e = e ?: [cb computeCommandEncoder];
if (!open)
wait_fences(c, e, spec);
[e setComputePipelineState:pipeline];
@@ -1002,7 +1304,8 @@ static id<MTLComputeCommandEncoder> encode_compute(Case *c, id<MTLCommandBuffer>
static void run_compute(Case *c, id<MTLCommandQueue> queue, id<MTLLibrary> library, NSDictionary *spec)
{
id<MTLCommandBuffer> cb = [queue commandBuffer];
NSMutableArray *lines = [NSMutableArray new];
id<MTLCommandBuffer> cb = command_buffer(c, queue, spec, lines);
if (spec[@"residency_set"]) {
/* The named buffers resident through a residency set alone. */
if (@available(macOS 15.0, *)) {
@@ -1023,6 +1326,8 @@ static void run_compute(Case *c, id<MTLCommandQueue> queue, id<MTLLibrary> libra
update_fences(c, e, spec);
[e endEncoding];
wait_for(cb, spec);
if (spec[@"log"])
store_log(c, spec, lines);
}
static void encode_render(Case *c, id<MTLCommandBuffer> cb, id<MTLLibrary> library, NSDictionary *spec)
@@ -1049,6 +1354,7 @@ static void encode_render(Case *c, id<MTLCommandBuffer> cb, id<MTLLibrary> libra
d.fragmentFunction = function_named(library, spec[@"fragment"], spec[@"constants"]);
d.rasterSampleCount = number(r, @"samples", 1);
d.alphaToCoverageEnabled = [r[@"alpha_to_coverage"] boolValue];
d.alphaToOneEnabled = [r[@"alpha_to_one"] boolValue];
d.supportIndirectCommandBuffers = [r[@"supports_icb"] boolValue];
NSDictionary *tess = r[@"tessellation"];
if (tess) {
@@ -1102,6 +1408,27 @@ static void encode_render(Case *c, id<MTLCommandBuffer> cb, id<MTLLibrary> libra
[pass setSamplePositions:positions count:count];
}
NSArray *colors = r[@"colors"] ?: @[];
if (r[@"visibility"])
pass.visibilityResultBuffer = c.buffers[r[@"visibility"][@"buffer"]];
if (r[@"timestamps"]) {
/* Timestamps at the start and end of the vertex and fragment
* stages, resolved after the pass into the named buffer. */
MTLCounterSampleBufferDescriptor *sd = [MTLCounterSampleBufferDescriptor new];
sd.counterSet = counter_set(c.device, r[@"timestamps"][@"counters"] ?: @"timestamp");
sd.sampleCount = 4;
sd.storageMode = MTLStorageModeShared;
NSError *error = nil;
id<MTLCounterSampleBuffer> samples = [c.device newCounterSampleBufferWithDescriptor:sd error:&error];
if (!samples)
@throw failure(@"counter sample buffer: %@", error.localizedDescription);
MTLRenderPassSampleBufferAttachmentDescriptor *sa = pass.sampleBufferAttachments[0];
sa.sampleBuffer = samples;
sa.startOfVertexSampleIndex = 0;
sa.endOfVertexSampleIndex = 1;
sa.startOfFragmentSampleIndex = 2;
sa.endOfFragmentSampleIndex = 3;
resolve_counters_after(c, cb, samples, 4, r[@"timestamps"]);
}
if (r[@"target_size"]) {
pass.renderTargetWidth = [r[@"target_size"][0] unsignedIntegerValue];
pass.renderTargetHeight = [r[@"target_size"][1] unsignedIntegerValue];
@@ -1134,8 +1461,15 @@ static void encode_render(Case *c, id<MTLCommandBuffer> cb, id<MTLLibrary> libra
}
MTLRenderPassColorAttachmentDescriptor *ca = pass.colorAttachments[i];
ca.texture = t;
/* An array target is layered: the vertex function picks the slice. */
if (t.textureType == MTLTextureType2DArray || t.textureType == MTLTextureType2DMultisampleArray)
/* One level, slice or 3D plane of the texture. */
ca.level = number(a, @"level", 0);
ca.slice = number(a, @"slice", 0);
ca.depthPlane = number(a, @"depth_plane", 0);
ca.resolveLevel = number(a, @"resolve_level", 0);
ca.resolveSlice = number(a, @"resolve_slice", 0);
/* An array target is layered, the vertex function picking the
* slice, unless the attachment names one. */
if ((t.textureType == MTLTextureType2DArray || t.textureType == MTLTextureType2DMultisampleArray) && !a[@"slice"])
pass.renderTargetArrayLength = t.arrayLength;
NSArray *clear = a[@"clear"];
ca.loadAction = clear ? MTLLoadActionClear : MTLLoadActionLoad;
@@ -1158,7 +1492,10 @@ static void encode_render(Case *c, id<MTLCommandBuffer> cb, id<MTLLibrary> libra
pass.depthAttachment.clearDepth = [a[@"clear"] doubleValue];
pass.depthAttachment.storeAction = MTLStoreActionStore;
if (a[@"resolve"]) {
NSDictionary *filters = @{@"sample0" : @(MTLMultisampleDepthResolveFilterSample0),
@"min" : @(MTLMultisampleDepthResolveFilterMin), @"max" : @(MTLMultisampleDepthResolveFilterMax)};
pass.depthAttachment.resolveTexture = c.textures[a[@"resolve"]];
pass.depthAttachment.depthResolveFilter = lookup(filters, @"depth resolve filter", a[@"resolve_filter"] ?: @"sample0");
pass.depthAttachment.storeAction = MTLStoreActionStoreAndMultisampleResolve;
}
ds.depthCompareFunction = lookup(compare_functions(), @"compare function", a[@"compare"] ?: @"always");
@@ -1172,6 +1509,13 @@ static void encode_render(Case *c, id<MTLCommandBuffer> cb, id<MTLLibrary> libra
pass.stencilAttachment.loadAction = a[@"clear"] ? MTLLoadActionClear : MTLLoadActionLoad;
pass.stencilAttachment.clearStencil = (uint32_t)number(a, @"clear", 0);
pass.stencilAttachment.storeAction = MTLStoreActionStore;
if (a[@"resolve"]) {
NSDictionary *filters = @{@"sample0" : @(MTLMultisampleStencilResolveFilterSample0),
@"depth_resolved" : @(MTLMultisampleStencilResolveFilterDepthResolvedSample)};
pass.stencilAttachment.resolveTexture = c.textures[a[@"resolve"]];
pass.stencilAttachment.stencilResolveFilter = lookup(filters, @"stencil resolve filter", a[@"resolve_filter"] ?: @"sample0");
pass.stencilAttachment.storeAction = MTLStoreActionStoreAndMultisampleResolve;
}
for (NSString *face in @[ @"front", @"back" ]) {
MTLStencilDescriptor *s = [MTLStencilDescriptor new];
NSDictionary *f = a[face] ?: a;
@@ -1204,6 +1548,14 @@ static void encode_render(Case *c, id<MTLCommandBuffer> cb, id<MTLLibrary> libra
m.maxTotalThreadsPerObjectThreadgroup = number(mesh, @"max_object_threads", 0);
m.maxTotalThreadsPerMeshThreadgroup = number(mesh, @"max_mesh_threads", 0);
pipeline = [c.device newRenderPipelineStateWithMeshDescriptor:m options:MTLPipelineOptionNone reflection:nil error:&error];
} else if (spec[@"reflection"]) {
MTLRenderPipelineReflection *reflection = nil;
pipeline = [c.device newRenderPipelineStateWithDescriptor:d options:MTLPipelineOptionBindingInfo | MTLPipelineOptionBufferTypeInfo
reflection:&reflection error:&error];
if (pipeline)
write_text(c, spec[@"reflection"], [NSString stringWithFormat:@"vertex\n%@\nfragment\n%@\n",
bindings_text(reflection.vertexBindings),
bindings_text(reflection.fragmentBindings)]);
} else {
pipeline = [c.device newRenderPipelineStateWithDescriptor:d error:&error];
}
@@ -1319,7 +1671,23 @@ static void encode_render(Case *c, id<MTLCommandBuffer> cb, id<MTLLibrary> libra
[e executeCommandsInBuffer:c.icbs[x[@"icb"]] withRange:NSMakeRange(number(x, @"start", 0), number(x, @"count", 1))];
} else if (r[@"indirect"]) {
NSDictionary *i = r[@"indirect"];
[e drawPrimitives:primitive indirectBuffer:c.buffers[i[@"buffer"]] indirectBufferOffset:number(i, @"offset", 0)];
if (r[@"index_buffer"])
[e drawIndexedPrimitives:primitive indexType:[r[@"index_type"] isEqualToString:@"uint32"] ? MTLIndexTypeUInt32 : MTLIndexTypeUInt16
indexBuffer:c.buffers[r[@"index_buffer"]] indexBufferOffset:number(r, @"index_offset", 0)
indirectBuffer:c.buffers[i[@"buffer"]] indirectBufferOffset:number(i, @"offset", 0)];
else
[e drawPrimitives:primitive indirectBuffer:c.buffers[i[@"buffer"]] indirectBufferOffset:number(i, @"offset", 0)];
} else if (r[@"draws"]) {
/* Several draws, each counted into its own visibility result. */
NSDictionary *modes = @{@"boolean" : @(MTLVisibilityResultModeBoolean), @"counting" : @(MTLVisibilityResultModeCounting),
@"disabled" : @(MTLVisibilityResultModeDisabled)};
for (NSDictionary *draw in r[@"draws"]) {
if (r[@"visibility"])
[e setVisibilityResultMode:lookup(modes, @"visibility mode", r[@"visibility"][@"mode"] ?: @"counting")
offset:number(draw, @"visibility_offset", 0)];
[e drawPrimitives:primitive vertexStart:number(draw, @"vertex_start", 0) vertexCount:number(draw, @"vertex_count", 3)
instanceCount:number(draw, @"instance_count", 1) baseInstance:base_instance];
}
} else if (r[@"index_buffer"]) {
id<MTLBuffer> indices = c.buffers[r[@"index_buffer"]];
BOOL wide = [r[@"index_type"] isEqualToString:@"uint32"];
@@ -1405,6 +1773,33 @@ static void encode_blits(Case *c, id<MTLCommandBuffer> cb, NSDictionary *spec)
sourceSize:size_of(op[@"size"]) toTexture:c.textures[op[@"dst"]]
destinationSlice:number(op, @"dst_slice", 0) destinationLevel:number(op, @"dst_level", 0)
destinationOrigin:origin_of(op[@"dst_origin"])];
} else if ([kind isEqualToString:@"buffer_to_texture_plane"]) {
/* One plane of a depth-stencil texture, chosen by aspect. */
id<MTLTexture> t = c.textures[op[@"dst"]];
[e copyFromBuffer:c.buffers[op[@"src"]] sourceOffset:number(op, @"src_offset", 0)
sourceBytesPerRow:number(op, @"bytes_per_row", 0) sourceBytesPerImage:number(op, @"bytes_per_image", 0)
sourceSize:size_of(op[@"size"]) toTexture:t destinationSlice:number(op, @"slice", 0)
destinationLevel:number(op, @"level", 0) destinationOrigin:origin_of(op[@"origin"])
options:blit_option(t.pixelFormat, op[@"aspect"])];
} else if ([kind isEqualToString:@"texture_to_buffer_plane"]) {
id<MTLTexture> t = c.textures[op[@"src"]];
[e copyFromTexture:t sourceSlice:number(op, @"slice", 0) sourceLevel:number(op, @"level", 0)
sourceOrigin:origin_of(op[@"origin"]) sourceSize:size_of(op[@"size"])
toBuffer:c.buffers[op[@"dst"]] destinationOffset:number(op, @"dst_offset", 0)
destinationBytesPerRow:number(op, @"bytes_per_row", 0)
destinationBytesPerImage:number(op, @"bytes_per_image", 0)
options:blit_option(t.pixelFormat, op[@"aspect"])];
} else if ([kind isEqualToString:@"copy_whole_texture"]) {
[e copyFromTexture:c.textures[op[@"src"]] toTexture:c.textures[op[@"dst"]]];
} else if ([kind isEqualToString:@"copy_slices"]) {
[e copyFromTexture:c.textures[op[@"src"]] sourceSlice:number(op, @"src_slice", 0)
sourceLevel:number(op, @"src_level", 0) toTexture:c.textures[op[@"dst"]]
destinationSlice:number(op, @"dst_slice", 0) destinationLevel:number(op, @"dst_level", 0)
sliceCount:number(op, @"slices", 1) levelCount:number(op, @"levels", 1)];
} else if ([kind isEqualToString:@"optimize_gpu_access"]) {
[e optimizeContentsForGPUAccess:c.textures[op[@"texture"]]];
} else if ([kind isEqualToString:@"optimize_cpu_access"]) {
[e optimizeContentsForCPUAccess:c.textures[op[@"texture"]]];
} else if ([kind isEqualToString:@"generate_mipmaps"]) {
[e generateMipmapsForTexture:c.textures[op[@"texture"]]];
} else if ([kind isEqualToString:@"reset_icb"]) {
@@ -1436,6 +1831,16 @@ static id<MTLEvent> event_named(Case *c, NSString *name)
return c.events[name];
}
/* Records, per command buffer in commit order, when it was scheduled and
* completed, for checking the order a queue keeps. */
@interface Handlers : NSObject
@property(retain) NSMutableArray<NSNumber *> *completed;
@property NSUInteger scheduled;
@property BOOL scheduled_first;
@end
@implementation Handlers
@end
/* Steps of compute, render and blit work over the case's resources, in one
* command buffer unless a step starts a new one. A compute step may
* continue the previous compute encoder; a step may wait for and update
@@ -1444,7 +1849,35 @@ static id<MTLEvent> event_named(Case *c, NSString *name)
static void run_sequence(Case *c, id<MTLCommandQueue> queue, NSDictionary *plan, NSDictionary *spec,
NSMutableDictionary *libraries)
{
id<MTLCommandBuffer> cb = [queue commandBuffer];
/* Steps run on the case's queue or on others it creates by index;
* command buffers retain their resources unless `unretained`. */
NSMutableDictionary<NSNumber *, id<MTLCommandQueue>> *queues = [NSMutableDictionary dictionaryWithObject:queue forKey:@0];
BOOL unretained = [spec[@"unretained"] boolValue];
Handlers *handlers = [Handlers new];
handlers.completed = [NSMutableArray new];
handlers.scheduled_first = YES;
__block NSUInteger committed = 0;
id<MTLCommandBuffer> (^make)(id<MTLCommandQueue>) = ^(id<MTLCommandQueue> q) {
id<MTLCommandBuffer> b = unretained ? [q commandBufferWithUnretainedReferences] : [q commandBuffer];
NSUInteger k = committed++;
if (spec[@"handlers"]) {
[b addScheduledHandler:^(id<MTLCommandBuffer> _) {
@synchronized(handlers) {
handlers.scheduled++;
}
}];
[b addCompletedHandler:^(id<MTLCommandBuffer> _) {
@synchronized(handlers) {
if (handlers.scheduled < handlers.completed.count + 1)
handlers.scheduled_first = NO;
[handlers.completed addObject:@(k)];
}
}];
}
return b;
};
NSNumber *on = @0;
id<MTLCommandBuffer> cb = make(queue);
id<MTLComputeCommandEncoder> open = nil;
NSDictionary *open_step = nil;
for (NSDictionary *step in spec[@"steps"]) {
@@ -1455,9 +1888,13 @@ static void run_sequence(Case *c, id<MTLCommandQueue> queue, NSDictionary *plan,
[open endEncoding];
open = nil;
}
if ([step[@"new_command_buffer"] boolValue]) {
NSNumber *wanted = step[@"queue"] ?: @0;
if (!queues[wanted])
queues[wanted] = [c.device newCommandQueue];
if ([step[@"new_command_buffer"] boolValue] || ![wanted isEqual:on]) {
[cb commit];
cb = [queue commandBuffer];
on = wanted;
cb = make(queues[on]);
}
for (NSArray *w in step[@"wait_events"])
[cb encodeWaitForEvent:event_named(c, w[0]) value:[w[1] unsignedLongLongValue]];
@@ -1496,7 +1933,51 @@ static void run_sequence(Case *c, id<MTLCommandQueue> queue, NSDictionary *plan,
for (NSArray *h in host)
((id<MTLSharedEvent>)c.events[h[0]]).signaledValue = [h[1] unsignedLongLongValue];
});
/* Listeners the host registers for values the GPU signals. */
MTLSharedEventListener *listener = nil;
NSMutableSet *heard = [NSMutableSet new];
for (NSArray *l in spec[@"listen"]) {
listener = listener ?: [[MTLSharedEventListener alloc] initWithDispatchQueue:dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)];
id<MTLSharedEvent> event = (id<MTLSharedEvent>)event_named(c, l[0]);
NSString *name = l[2];
[event notifyListener:listener atValue:[l[1] unsignedLongLongValue] block:^(id<MTLSharedEvent> e, uint64_t value) {
@synchronized(heard) {
[heard addObject:name];
}
}];
}
wait_for(cb, spec);
for (NSArray *l in spec[@"listen"]) {
BOOL got = NO;
for (int k = 0; k < 200 && !got; k++) {
@synchronized(heard) {
got = [heard containsObject:l[2]];
}
if (!got)
usleep(10000);
}
uint32_t *out = c.buffers[l[2]].contents;
out[0] = got;
out[1] = (uint32_t)((id<MTLSharedEvent>)c.events[l[0]]).signaledValue;
}
if (spec[@"handlers"]) {
/* Completion in commit order, each after its scheduling, and the
* last buffer's final status. */
for (int k = 0; k < 200; k++) {
@synchronized(handlers) {
if (handlers.completed.count == committed)
break;
}
usleep(10000);
}
uint32_t *out = c.buffers[spec[@"handlers"]].contents;
@synchronized(handlers) {
for (NSUInteger k = 0; k < handlers.completed.count && k < 8; k++)
out[k] = handlers.completed[k].unsignedIntValue;
out[8] = handlers.scheduled_first;
out[9] = (uint32_t)cb.status;
}
}
}
static void store_outputs(Case *c, id<MTLCommandQueue> queue, NSDictionary *spec)
@@ -1506,9 +1987,18 @@ static void store_outputs(Case *c, id<MTLCommandQueue> queue, NSDictionary *spec
NSString *name = o[@"name"];
NSString *path = [c.dir stringByAppendingPathComponent:[(o[@"as"] ?: name) stringByAppendingString:@".bin"]];
if (c.buffers[name]) {
id<MTLBuffer> b = c.buffers[name];
id<MTLBuffer> b = c.buffers[name], shared = b;
if (b.storageMode == MTLStorageModePrivate)
shared = [c.device newBufferWithLength:b.length options:MTLResourceStorageModeShared];
if (b.storageMode != MTLStorageModeShared)
blit_now(c, ^(id<MTLBlitCommandEncoder> e) {
if (shared != b)
[e copyFromBuffer:b sourceOffset:0 toBuffer:shared destinationOffset:0 size:b.length];
else
[e synchronizeResource:b];
});
NSUInteger length = number(o, @"length", b.length);
[[NSData dataWithBytes:b.contents length:MIN(length, b.length)] writeToFile:path atomically:YES];
[[NSData dataWithBytes:shared.contents length:MIN(length, b.length)] writeToFile:path atomically:YES];
continue;
}
id<MTLTexture> t = c.textures[name];
@@ -1516,6 +2006,22 @@ static void store_outputs(Case *c, id<MTLCommandQueue> queue, NSDictionary *spec
@throw failure(@"output %@ is neither a buffer nor a texture", name);
NSUInteger total;
NSArray *regions = regions_of(t, o[@"aspect"], &total);
if (t.storageMode != MTLStorageModePrivate && !t.buffer) {
/* Read back by the CPU, after a synchronization when managed. */
if (t.storageMode == MTLStorageModeManaged)
blit_now(c, ^(id<MTLBlitCommandEncoder> e) {
[e synchronizeResource:t];
});
NSMutableData *out = [NSMutableData dataWithLength:total];
for (NSValue *v in regions) {
struct region r;
[v getValue:&r];
[t getBytes:(uint8_t *)out.mutableBytes + r.offset bytesPerRow:r.bytes_per_row bytesPerImage:r.bytes_per_image
fromRegion:MTLRegionMake3D(0, 0, 0, r.size.width, r.size.height, r.size.depth) mipmapLevel:r.level slice:r.slice];
}
[out writeToFile:path atomically:YES];
continue;
}
id<MTLBuffer> staging = [c.device newBufferWithLength:MAX(total, 16) options:MTLResourceStorageModeShared];
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLBlitCommandEncoder> e = [cb blitCommandEncoder];
@@ -1548,6 +2054,21 @@ static NSDictionary<NSString *, NSNumber *> *gpu_families(void)
/* Whether the device has a feature a case names; nil for a name the runner
* does not know, which is an error in the plan. */
static BOOL has_counter_set(id<MTLDevice> d, NSString *name)
{
for (id<MTLCounterSet> set in d.counterSets)
if ([set.name isEqualToString:name])
return YES;
return NO;
}
static BOOL logging_available(void)
{
if (@available(macOS 15.0, *))
return YES;
return NO;
}
static NSNumber *feature(id<MTLDevice> d, NSString *name)
{
if ([name hasPrefix:@"samples"])
@@ -1572,6 +2093,10 @@ static NSNumber *feature(id<MTLDevice> d, NSString *name)
@"primitive_motion_blur" : @(d.supportsPrimitiveMotionBlur),
@"vertex_amplification2" : @([d supportsVertexAmplificationCount:2]),
@"simd_reduction" : @([d supportsFamily:MTLGPUFamilyApple7] || [d supportsFamily:MTLGPUFamilyMac2]),
@"counters_stage_boundary" : @([d supportsCounterSampling:MTLCounterSamplingPointAtStageBoundary]),
@"counter_set_timestamp" : @(has_counter_set(d, MTLCommonCounterSetTimestamp)),
@"counter_set_statistic" : @(has_counter_set(d, MTLCommonCounterSetStatistic)),
@"logging" : @(logging_available()),
};
return t[name];
}
@@ -1743,6 +2268,51 @@ static id<MTLIndirectCommandBuffer> make_icb(Case *c, NSDictionary *b)
return icb;
}
/* Work Apple's frameworks encode with their own shaders: an MPS matrix
* product and box filter, and a Core Image filter, each over the case's
* resources. */
static void run_framework(Case *c, id<MTLCommandQueue> queue, NSDictionary *spec)
{
NSDictionary *f = spec[@"framework"];
NSString *kind = f[@"kind"];
id<MTLCommandBuffer> cb = [queue commandBuffer];
if ([kind hasPrefix:@"mps"] && !MPSSupportsMTLDevice(c.device))
@throw [NSException exceptionWithName:@"CaseUnsupported" reason:@"MPS does not support the device" userInfo:nil];
if ([kind isEqualToString:@"mps_matrix_multiply"]) {
NSUInteger m = number(f, @"rows", 1), n = number(f, @"columns", 1), k = number(f, @"interior", 1);
MPSMatrix *(^matrix)(NSString *, NSUInteger, NSUInteger) = ^(NSString *name, NSUInteger rows, NSUInteger columns) {
MPSMatrixDescriptor *d = [MPSMatrixDescriptor matrixDescriptorWithRows:rows columns:columns
rowBytes:columns * sizeof(float)
dataType:MPSDataTypeFloat32];
return [[MPSMatrix alloc] initWithBuffer:c.buffers[name] descriptor:d];
};
MPSMatrixMultiplication *mm = [[MPSMatrixMultiplication alloc] initWithDevice:c.device transposeLeft:NO transposeRight:NO
resultRows:m resultColumns:n interiorColumns:k
alpha:1.0 beta:0.0];
[mm encodeToCommandBuffer:cb leftMatrix:matrix(@"a", m, k) rightMatrix:matrix(@"b", k, n) resultMatrix:matrix(@"c", m, n)];
} else if ([kind isEqualToString:@"mps_image_box"]) {
MPSImageBox *box = [[MPSImageBox alloc] initWithDevice:c.device kernelWidth:3 kernelHeight:3];
box.edgeMode = MPSImageEdgeModeClamp;
[box encodeToCommandBuffer:cb sourceTexture:c.textures[@"in"] destinationTexture:c.textures[@"out"]];
} else if ([kind isEqualToString:@"core_image_invert"]) {
/* No colour management: the filter sees the texels as stored. */
CIContext *context = [CIContext contextWithMTLDevice:c.device
options:@{kCIContextWorkingColorSpace : [NSNull null],
kCIContextOutputColorSpace : [NSNull null]}];
CIImage *image = [CIImage imageWithMTLTexture:c.textures[@"in"] options:@{kCIImageColorSpace : [NSNull null]}];
CIFilter *invert = [CIFilter filterWithName:@"CIColorInvert"];
[invert setValue:image forKey:kCIInputImageKey];
id<MTLTexture> out = c.textures[@"out"];
/* A null output space skips colour matching, though the header marks it nonnull. */
CGColorSpaceRef unmatched = NULL;
[context render:invert.outputImage toMTLTexture:out commandBuffer:cb
bounds:CGRectMake(0, 0, out.width, out.height) colorSpace:unmatched];
} else {
@throw failure(@"unknown framework work %@", kind);
}
wait_for(cb, spec);
}
static void run_case(id<MTLDevice> device, id<MTLCommandQueue> queue, NSDictionary *plan, NSDictionary *spec,
NSString *dir, NSMutableDictionary *libraries)
{
@@ -1761,6 +2331,7 @@ static void run_case(id<MTLDevice> device, id<MTLCommandQueue> queue, NSDictiona
c.heaps = [NSMutableDictionary new];
c.libraries = libraries;
c.plan = plan;
c.queue = queue;
NSString *missing = unmet(device, spec[@"requires"]);
if (missing)
@throw [NSException exceptionWithName:@"CaseUnsupported" reason:missing userInfo:nil];
@@ -1783,6 +2354,8 @@ static void run_case(id<MTLDevice> device, id<MTLCommandQueue> queue, NSDictiona
}
if ([kind isEqualToString:@"blit"]) {
run_blits(c, queue, spec);
} else if ([kind isEqualToString:@"framework"]) {
run_framework(c, queue, spec);
} else if ([kind isEqualToString:@"sequence"]) {
run_sequence(c, queue, plan, spec, libraries);
} else {
+3
View File
@@ -23,9 +23,11 @@ use anyhow::{Context, Result, bail};
use clap::{Args, Subcommand};
use std::{fs, path::PathBuf};
mod api;
mod arguments;
mod blits;
mod check;
mod compressed;
mod compute;
mod convert;
mod coverage;
@@ -200,6 +202,7 @@ fn build(plan: &mut plan::Plan) {
stages::build(plan);
resources::build(plan);
extras::build(plan);
api::build(plan);
}
fn availability() -> Result<plan::Availability> {
File diff suppressed because it is too large. Load diff
+74
View File
@@ -434,10 +434,84 @@ fn dynamic_libraries(plan: &mut Plan, rng: &mut Random) {
);
}
/// The constant types `constants` leaves out, set by their bytes.
fn more_constants(plan: &mut Plan, library: &str) {
let ints = |v: &[i32]| -> Vec<u8> { v.iter().flat_map(|x| x.to_le_bytes()).collect() };
let words = [0xDEAD_BEEFu32, 1, 0x8000_0000, 42];
let halves = [0.5f64, -1.0, 65504.0, -0.0];
let floats2 = [3.25f32, -7.5];
let list = json!([
constant("char", 20, -5),
constant("uchar", 21, 250),
constant("ushort", 22, 65000),
{"type": "int2", "index": 23, "bytes": base64(&ints(&[-9, 123_456]))},
{"type": "uint4", "index": 24, "bytes": base64(&u32s(&words))},
{"type": "half4", "index": 25, "bytes": base64(&halves.iter().flat_map(|&h| f16_bits(h).to_le_bytes()).collect::<Vec<_>>())},
{"type": "float2", "index": 26, "bytes": base64(&floats2.iter().flat_map(|f| f.to_le_bytes()).collect::<Vec<_>>())},
]);
let mut expected = vec![(-5i32) as u32, 250, 65000, (-9i32) as u32, 123_456];
expected.extend(words);
expected.extend(halves.map(|h| u32::from(f16_bits(h))));
expected.extend(floats2.map(f32::to_bits));
plan.add(
Case::compute(
"arguments.constants.more_types",
library,
"constants_more",
[1, 1, 1],
[1, 1, 1],
)
.set("constants", list)
.buffer(Buffer::zeroed("out", 0, 64))
.output(
Output::new("out", Dtype::U32, Tolerance::exact())
.expect_same(u32s(&expected))
.set("length", 60),
),
);
}
/// A Tier 2 argument buffer a fragment function reads: each pixel's texel
/// times one of two tints.
fn fragment_arguments(plan: &mut Plan, library: &str) {
let mut rng = Random::new(1005);
let size = 8u32;
let image: Vec<f64> = (0..size * size * 4)
.map(|_| f32r(rng.uniform(0.0, 1.0)))
.collect();
let tints = [0.5, 1.0, 0.25, 2.0, 1.5, 0.75, 1.0, 0.5];
let expected: Vec<f64> = (0..(size * size) as usize)
.flat_map(|i| {
let tint = &tints[4 * (i % 2)..4 * (i % 2) + 4];
(0..4).map(move |k| (i, k, tint[k]))
})
.map(|(i, k, t)| f32r(image[4 * i + k] * t))
.collect();
plan.add(
Case::render(
"arguments.argument_buffer.fragment",
library,
"vert_argument_pixel",
Some("frag_arguments"),
json!({"colors": [{"texture": "a", "clear": [0, 0, 0, 0]}], "primitive": "triangle_strip",
"vertex_count": 4}),
)
.requires(&[], &["argument_buffers_tier2"])
.buffer(Buffer::zeroed("args", 0, 16).stage("fragment"))
.buffer(Buffer::data("tint", 0, f32s(&tints)).unbound())
.texture(Texture::d2("image", "rgba32float", size, size).data(f32s(&image)))
.texture(Texture::d2("a", "rgba32float", size, size).usage(&["render"]))
.set("arguments", json!([{"buffer": "args", "entries": [entry("texture", 0, "image"), entry("buffer", 8, "tint")]}]))
.output(Output::new("a", Dtype::F32, Tolerance::ulp(1.0)).expect_same(f32s(&expected))),
);
}
pub fn build(plan: &mut Plan) {
let library = plan.library("arguments", SOURCE, &[], LATEST);
constants(plan, &library);
more_constants(plan, &library);
argument_buffers(plan, &library);
fragment_arguments(plan, &library);
function_pointers(plan, &library);
dynamic_libraries(plan, &mut Random::new(1004));
}
+289 -3
View File
@@ -1,6 +1,9 @@
//! Blit commands: buffer copies and fills, copies between buffers and
//! textures with row and image pitches, texture copies between levels and
//! slices, and mipmap generation.
//! Blit commands: buffer copies and fills, small and large, copies between
//! buffers and textures with row and image pitches into any slice, level,
//! 3D region or depth-stencil plane, texture copies of a region, of whole
//! textures and of slice and level ranges, of compressed blocks, mipmap
//! generation for 2D, array, cube and 3D textures, and access hints that
//! leave contents as they were.
use super::plan::{Buffer, Case, Output, Plan, Texture, Tolerance};
use super::values::{Dtype, Random};
use serde_json::json;
@@ -13,8 +16,291 @@ fn exact(name: &str, data: Vec<u8>) -> Output {
Output::new(name, Dtype::U8, Tolerance::exact()).expect_same(data)
}
/// Where each (slice, level) of a texture starts in the runner's packed
/// layout (slices outermost, levels inner), and the total length.
struct Layout {
size: [usize; 3],
slices: usize,
levels: usize,
texel: usize,
}
impl Layout {
fn extent(&self, level: usize) -> [usize; 3] {
self.size.map(|s| (s >> level).max(1))
}
fn level_bytes(&self, level: usize) -> usize {
self.extent(level).iter().product::<usize>() * self.texel
}
fn offset(&self, slice: usize, level: usize) -> usize {
let per_slice: usize = (0..self.levels).map(|l| self.level_bytes(l)).sum();
slice * per_slice + (0..level).map(|l| self.level_bytes(l)).sum::<usize>()
}
fn total(&self) -> usize {
self.offset(self.slices, 0)
}
/// The byte of texel (x, y, z) of a subresource.
fn at(&self, slice: usize, level: usize, [x, y, z]: [usize; 3]) -> usize {
let [w, h, _] = self.extent(level);
self.offset(slice, level) + ((z * h + y) * w + x) * self.texel
}
}
/// A 2x2 (2x2x2 for 3D) box filter of one level into the next, rounded
/// to the nearest unorm8 step.
fn box_level(level: &[u8], [w, h, d]: [usize; 3], channels: usize) -> Vec<u8> {
let next = [(w / 2).max(1), (h / 2).max(1), (d / 2).max(1)];
let mut out = vec![0u8; next.iter().product::<usize>() * channels];
for z in 0..next[2] {
for y in 0..next[1] {
for x in 0..next[0] {
for c in 0..channels {
let mut sum = 0.0;
let mut count = 0.0;
for dz in 0..if d > 1 { 2 } else { 1 } {
for dy in 0..if h > 1 { 2 } else { 1 } {
for dx in 0..if w > 1 { 2 } else { 1 } {
let (xx, yy, zz) = (2 * x + dx, 2 * y + dy, 2 * z + dz);
sum += f64::from(level[((zz * h + yy) * w + xx) * channels + c]);
count += 1.0;
}
}
}
out[((z * next[1] + y) * next[0] + x) * channels + c] =
(sum / count).round() as u8;
}
}
}
}
out
}
fn more(plan: &mut Plan, rng: &mut Random) {
// A buffer region into level 1 of slice 1 of an array, rows padded.
let array = Layout {
size: [8, 8, 1],
slices: 2,
levels: 2,
texel: 4,
};
let texture = bytes(rng, array.total());
let source = bytes(rng, 32 * 2);
let mut expected = texture.clone();
for y in 0..2 {
let to = array.at(1, 1, [1, 1 + y, 0]);
expected[to..to + 12].copy_from_slice(&source[y * 32..y * 32 + 12]);
}
plan.add(
Case::blit(
"blit.buffer_to_texture.array_level",
json!([{"op": "buffer_to_texture", "src": "staging", "bytes_per_row": 32, "bytes_per_image": 64,
"size": [3, 2, 1], "dst": "t", "slice": 1, "level": 1, "origin": [1, 1, 0]}]),
)
.buffer(Buffer::data("staging", 0, source).unbound())
.texture(Texture::new("t", "rgba8unorm", "2d_array", [8, 8, 1]).array(2).mipmaps(2).data(texture))
.output(exact("t", expected)),
);
// A 2x2x2 region of a 3D texture from and to buffers with padded rows
// and images.
let volume = Layout {
size: [4, 4, 4],
slices: 1,
levels: 1,
texel: 4,
};
let texture = bytes(rng, volume.total());
let source = bytes(rng, 48 * 2);
let mut expected = texture.clone();
let mut read = vec![0x33u8; 48 * 2];
for z in 0..2 {
for y in 0..2 {
let at = volume.at(0, 0, [1, 1 + y, 1 + z]);
expected[at..at + 8].copy_from_slice(&source[z * 48 + y * 16..z * 48 + y * 16 + 8]);
read[z * 48 + y * 16..z * 48 + y * 16 + 8].copy_from_slice(&texture[at..at + 8]);
}
}
plan.add(
Case::blit(
"blit.buffer_to_texture.volume",
json!([{"op": "buffer_to_texture", "src": "staging", "bytes_per_row": 16, "bytes_per_image": 48,
"size": [2, 2, 2], "dst": "t", "origin": [1, 1, 1]}]),
)
.buffer(Buffer::data("staging", 0, source).unbound())
.texture(Texture::new("t", "r32uint", "3d", [4, 4, 4]).data(texture.clone()))
.output(exact("t", expected)),
);
plan.add(
Case::blit(
"blit.texture_to_buffer.volume",
json!([{"op": "texture_to_buffer", "src": "t", "origin": [1, 1, 1], "size": [2, 2, 2], "dst": "out",
"bytes_per_row": 16, "bytes_per_image": 48}]),
)
.buffer(Buffer::data("out", 0, vec![0x33; 96]).unbound())
.texture(Texture::new("t", "r32uint", "3d", [4, 4, 4]).data(texture))
.output(exact("out", read)),
);
// Each plane of a depth-stencil texture written and read on its own.
let (w, h) = (8usize, 4usize);
let depth: Vec<u8> = (0..w * h)
.flat_map(|i| (i as f32 / 32.0).to_le_bytes())
.collect();
let stencil = bytes(rng, w * h);
plan.add(
Case::blit(
"blit.depth_stencil_planes",
json!([{"op": "buffer_to_texture_plane", "aspect": "depth", "src": "depth", "bytes_per_row": w * 4,
"bytes_per_image": w * h * 4, "size": [w, h, 1], "dst": "ds", "origin": [0, 0, 0]},
{"op": "buffer_to_texture_plane", "aspect": "stencil", "src": "stencil", "bytes_per_row": w,
"bytes_per_image": w * h, "size": [w, h, 1], "dst": "ds", "origin": [0, 0, 0]},
{"op": "texture_to_buffer_plane", "aspect": "stencil", "src": "ds", "origin": [0, 0, 0],
"size": [w, h, 1], "dst": "stencil_out", "bytes_per_row": w, "bytes_per_image": w * h}]),
)
.buffer(Buffer::data("depth", 0, depth.clone()).unbound())
.buffer(Buffer::data("stencil", 0, stencil.clone()).unbound())
.buffer(Buffer::zeroed("stencil_out", 0, w * h).unbound())
.texture(Texture::d2("ds", "depth32float_stencil8", w as u32, h as u32).usage(&["render"]))
.output(exact("stencil_out", stencil))
.output(exact("ds", depth).set("aspect", "depth")),
);
// A whole mipmapped array, then two of four slices with both levels.
let full = Layout {
size: [8, 4, 1],
slices: 4,
levels: 2,
texel: 8,
};
let a = bytes(rng, full.total());
let b = bytes(rng, full.total());
let mut sliced = b.clone();
for slice in 0..2 {
for level in 0..2 {
let (from, to) = (full.offset(slice + 1, level), full.offset(slice, level));
let n = full.level_bytes(level);
sliced[to..to + n].copy_from_slice(&a[from..from + n]);
}
}
let arrays = |data: &[u8]| {
Texture::new("", "rgba16uint", "2d_array", [8, 4, 1])
.array(4)
.mipmaps(2)
.data(data.to_vec())
};
let named = |t: Texture, name: &str| t.set("name", name);
plan.add(
Case::blit(
"blit.copy_whole_texture",
json!([{"op": "copy_whole_texture", "src": "a", "dst": "b"}]),
)
.texture(named(arrays(&a), "a"))
.texture(named(arrays(&b), "b"))
.output(exact("b", a.clone())),
);
plan.add(
Case::blit(
"blit.copy_slices",
json!([{"op": "copy_slices", "src": "a", "src_slice": 1, "dst": "b", "dst_slice": 0, "slices": 2, "levels": 2}]),
)
.texture(named(arrays(&a), "a"))
.texture(named(arrays(&b), "b"))
.output(exact("b", sliced)),
);
// A block of a compressed texture copied to another position.
let blocks = bytes(rng, 4 * 8);
let mut moved = blocks.clone();
moved[3 * 8..4 * 8].copy_from_slice(&blocks[..8]);
plan.add(
Case::blit(
"blit.copy_texture.compressed",
json!([{"op": "copy_texture", "src": "a", "src_origin": [0, 0, 0], "size": [4, 4, 1], "dst": "b",
"dst_origin": [4, 4, 0]}]),
)
.requires(&[], &["bc_compression"])
.texture(Texture::d2("a", "bc1_rgba", 8, 8).data(blocks.clone()))
.texture(Texture::d2("b", "bc1_rgba", 8, 8).data(blocks))
.output(exact("b", moved)),
);
// Large copies and fills, past any single transfer's size.
let large = 4 << 20;
let src = bytes(rng, large + 16);
let mut expected = vec![0u8; large + 16];
expected[8..8 + large].copy_from_slice(&src[4..4 + large]);
plan.add(
Case::blit(
"blit.buffers.large",
json!([{"op": "copy_buffer", "src": "src", "src_offset": 4, "dst": "dst", "dst_offset": 8, "size": large},
{"op": "fill_buffer", "dst": "filled", "offset": 0, "size": large, "value": 0x5C}]),
)
.buffer(Buffer::data("src", 0, src).unbound())
.buffer(Buffer::zeroed("dst", 0, large + 16).unbound())
.buffer(Buffer::zeroed("filled", 0, large).unbound())
.output(exact("dst", expected))
.output(exact("filled", vec![0x5C; large])),
);
// Mipmaps of each slice of an array, each face of a cube and a volume.
for (name, kind, size, slices) in [
("array", "2d_array", [8usize, 8, 1], 2usize),
("cube", "cube", [8, 8, 1], 6),
("volume", "3d", [8, 8, 8], 1),
] {
let layout = Layout {
size,
slices,
levels: 4,
texel: 4,
};
let mut data = vec![0u8; layout.total()];
let mut expected = vec![0u8; layout.total()];
for slice in 0..slices {
let mut level = bytes(rng, layout.level_bytes(0));
let at = layout.offset(slice, 0);
data[at..at + level.len()].copy_from_slice(&level);
expected[at..at + level.len()].copy_from_slice(&level);
for l in 1..4 {
level = box_level(&level, layout.extent(l - 1), 4);
let at = layout.offset(slice, l);
expected[at..at + level.len()].copy_from_slice(&level);
}
}
let mut t = Texture::new(
"t",
"rgba8unorm",
kind,
[size[0] as u32, size[1] as u32, size[2] as u32],
)
.mipmaps(4)
.usage(&["read", "render"])
.data(data);
if kind == "2d_array" {
t = t.array(slices as u32);
}
plan.add(
Case::blit(
&format!("blit.generate_mipmaps.{name}"),
json!([{"op": "generate_mipmaps", "texture": "t"}]),
)
.texture(t)
.output(Output::new("t", Dtype::U8, Tolerance::units(2.0)).expect_same(expected)),
);
}
// Access hints change no texel.
let data = bytes(rng, 16 * 16 * 4);
plan.add(
Case::blit(
"blit.optimize_access",
json!([{"op": "optimize_gpu_access", "texture": "t"}, {"op": "optimize_cpu_access", "texture": "t"}]),
)
.texture(Texture::d2("t", "rgba8unorm", 16, 16).data(data.clone()))
.output(exact("t", data)),
);
}
pub fn build(plan: &mut Plan) {
let mut rng = Random::new(1101);
more(plan, &mut Random::new(1102));
// Copies and fills at 4-byte aligned offsets and sizes, overlapping
// nothing, then a copy within one buffer to a disjoint range.
let (src, dst) = (bytes(&mut rng, 256), bytes(&mut rng, 256));
+66 -8
View File
@@ -45,6 +45,27 @@ impl Elements {
self
}
/// The property an output's `derive` names, element by element:
/// `nonzero` (1 where an element is not zero) or `ordered` (1 where it
/// is not zero and not below the element before it), for results whose
/// values Metal leaves open but whose relations it fixes.
fn derive(self, kind: &str) -> Result<Self> {
fn property<T: PartialOrd + Default>(v: &[T], kind: &str) -> Result<Vec<i128>> {
let zero = T::default();
Ok(match kind {
"nonzero" => v.iter().map(|x| i128::from(*x != zero)).collect(),
"ordered" => (0..v.len())
.map(|i| i128::from(v[i] != zero && (i == 0 || v[i] >= v[i - 1])))
.collect(),
other => bail!("unknown derived property {other}"),
})
}
Ok(Self::Int(match &self {
Self::Int(v) => property(v, kind)?,
Self::Float(v, _) => property(v, kind)?,
}))
}
fn show(&self, i: usize) -> String {
match self {
Self::Float(v, _) => format!("{:?}", v[i]),
@@ -180,6 +201,11 @@ fn compare(
out
}
/// Whether a results directory holds the reference device's results.
fn is_reference(results: &Path) -> bool {
results.file_name().is_some_and(|n| n == "mac")
}
fn status(dir: &Path) -> Value {
fs::read_to_string(dir.join("status.json"))
.ok()
@@ -363,7 +389,11 @@ pub fn run(
lines.push(format!("UNSUPPORTED {name}: {}", error(&test_status)));
continue;
}
let reference_root = if status_name(&ref_status) == "unsupported" {
// A case the reference device diverges on is held to its
// expectation, not to that device's results.
let reference_root = if status_name(&ref_status) == "unsupported"
|| case["reference_divergence"].is_string()
{
None
} else {
reference
@@ -433,12 +463,14 @@ pub fn run(
data.extend(read(by_name.get(next).context("appended output")?)?);
}
let dtype = dtype_of(output)?;
let e = Elements::of(dtype, &data);
Ok(if output["sorted_compare"].as_bool() == Some(true) {
e.sorted()
} else {
e
})
let mut e = Elements::of(dtype, &data);
if output["sorted_compare"].as_bool() == Some(true) {
e = e.sorted();
}
match output["derive"].as_str() {
Some(kind) => e.derive(kind),
None => Ok(e),
}
};
let mut problems = vec![];
let mut checked = 0;
@@ -458,6 +490,12 @@ pub fn run(
} else if let Some(file) = output["expect"].as_str() {
let read = |f: &str| -> Result<Elements> {
let data = fs::read(plan_dir.join(f)).with_context(|| f.to_string())?;
// A derived output's expectation is the property itself.
let dtype = if output["derive"].is_null() {
dtype
} else {
Dtype::U32
};
let e = Elements::of(dtype, &data);
Ok(if output["sorted_compare"].as_bool() == Some(true) {
e.sorted()
@@ -511,7 +549,12 @@ pub fn run(
summary.add("match");
continue;
}
let informational = case["informational"].as_bool() == Some(true);
// A divergence the reference device is known for counts against
// that device only as information; every other device is held to
// the specification.
let divergence =
case["reference_divergence"].is_string() && reference.is_none() && is_reference(test);
let informational = case["informational"].as_bool() == Some(true) || divergence;
summary.add(if informational {
"informational"
} else {
@@ -519,6 +562,7 @@ pub fn run(
});
let note = case["note"]
.as_str()
.or(case["reference_divergence"].as_str().filter(|_| divergence))
.map(|n| format!(" ({n})"))
.unwrap_or_default();
lines.push(format!(
@@ -676,6 +720,20 @@ mod tests {
);
}
#[test]
fn derived_properties_replace_open_values() {
let t = Elements::Int(vec![5, 0, 7, 6, 9]);
assert_eq!(
t.clone().derive("nonzero").unwrap(),
Elements::Int(vec![1, 0, 1, 1, 1])
);
assert_eq!(
t.derive("ordered").unwrap(),
Elements::Int(vec![1, 0, 1, 0, 1])
);
assert!(Elements::Int(vec![]).derive("other").is_err());
}
#[test]
fn slow_cases_are_reported_not_failed() {
let lines = slow(&[
+314
View File
@@ -0,0 +1,314 @@
//! Block-compressed formats: random blocks of each BC format a texture is
//! read from texel by texel, decoded as the BC specification (Direct3D's
//! functional specification of BC1 to BC7, which Metal's formats follow)
//! fixes them. Endpoint interpolation rounds as each decoder chooses, so
//! normalized results are held to two steps of their endpoints' precision.
use super::plan::{Buffer, Case, Output, Plan, Texture, Tolerance};
use super::textures::srgb;
use super::values::{Dtype, Random, f16_from_bits, f32s};
type Texel = [f64; 4];
fn bits(block: &[u8], at: usize, count: usize) -> u64 {
(0..count).fold(0, |v, k| {
let bit = at + k;
v | (u64::from(block[bit / 8] >> (bit % 8) & 1) << k)
})
}
fn rgb565(c: u64) -> [f64; 3] {
let (r, g, b) = ((c >> 11) & 31, (c >> 5) & 63, c & 31);
[r as f64 / 31.0, g as f64 / 63.0, b as f64 / 31.0]
}
fn mix(a: f64, b: f64, wb: f64) -> f64 {
a * (1.0 - wb) + b * wb
}
/// A BC1 colour block's 16 texels; `four` forces the four-colour palette
/// that BC2 and BC3 always use.
fn bc1(block: &[u8], four: bool) -> Vec<Texel> {
let (c0, c1) = (bits(block, 0, 16), bits(block, 16, 16));
let (a, b) = (rgb565(c0), rgb565(c1));
let palette: Vec<Texel> = if four || c0 > c1 {
[0.0, 1.0, 1.0 / 3.0, 2.0 / 3.0]
.iter()
.map(|&w| {
[
mix(a[0], b[0], w),
mix(a[1], b[1], w),
mix(a[2], b[2], w),
1.0,
]
})
.collect()
} else {
let half = [0.0, 1.0, 0.5].map(|w| {
[
mix(a[0], b[0], w),
mix(a[1], b[1], w),
mix(a[2], b[2], w),
1.0,
]
});
vec![half[0], half[1], half[2], [0.0; 4]]
};
(0..16)
.map(|i| palette[bits(block, 32 + 2 * i, 2) as usize])
.collect()
}
/// A BC4 channel block's 16 values, unsigned or signed.
fn bc4(block: &[u8], signed: bool) -> Vec<f64> {
let end = |v: u64| {
if signed {
(f64::from(v as u8 as i8)).max(-127.0) / 127.0
} else {
v as f64 / 255.0
}
};
let (r0, r1) = (bits(block, 0, 8), bits(block, 8, 8));
let (a, b) = (end(r0), end(r1));
let greater = if signed {
(r0 as u8 as i8) > (r1 as u8 as i8)
} else {
r0 > r1
};
let mut palette = vec![a, b];
if greater {
palette.extend((1..7).map(|k| mix(a, b, f64::from(k) / 7.0)));
} else {
palette.extend((1..5).map(|k| mix(a, b, f64::from(k) / 5.0)));
palette.extend([if signed { -1.0 } else { 0.0 }, 1.0]);
}
(0..16)
.map(|i| palette[bits(block, 16 + 3 * i, 3) as usize])
.collect()
}
/// A BC7 mode 6 block: one subset, 7-bit RGBA endpoints with a p-bit
/// each, and 4-bit indices.
fn bc7_mode6(block: &[u8]) -> Vec<Texel> {
const WEIGHTS: [u64; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64];
let mut at = 7;
let mut take = |n: usize| {
let v = bits(block, at, n);
at += n;
v
};
let mut e = [[0u64; 4]; 2];
for c in 0..4 {
for end in &mut e {
end[c] = take(7);
}
}
let p = [take(1), take(1)];
for (end, p) in e.iter_mut().zip(p) {
for c in end.iter_mut() {
*c = *c << 1 | p;
}
}
(0..16)
.map(|i| {
let w = WEIGHTS[take(if i == 0 { 3 } else { 4 }) as usize];
[0, 1, 2, 3].map(|c| (((64 - w) * e[0][c] + w * e[1][c] + 32) >> 6) as f64 / 255.0)
})
.collect()
}
/// A BC6H mode 11 block: one region of untransformed 10-bit endpoints and
/// 4-bit indices, unsigned or signed, as half floats.
fn bc6h_mode11(block: &[u8], signed: bool) -> Vec<Texel> {
const WEIGHTS: [i64; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64];
let field = |at: usize| {
let v = bits(block, at, 10) as i64;
if signed && v & 512 != 0 { v - 1024 } else { v }
};
let ends: [[i64; 3]; 2] = [
[field(5), field(15), field(25)],
[field(35), field(45), field(55)],
];
let unquantize = |e: i64| -> i64 {
if signed {
let (s, a) = (e < 0, e.abs());
let u = if a == 0 {
0
} else if a >= 511 {
0x7FFF
} else {
((a << 15) + 0x4000) >> 9
};
if s { -u } else { u }
} else if e == 0 {
0
} else if e == 1023 {
0xFFFF
} else {
((e << 16) + 0x8000) >> 10
}
};
let finish = |x: i64| -> u16 {
if signed {
if x < 0 {
0x8000 | ((-x * 31) >> 5) as u16
} else {
((x * 31) >> 5) as u16
}
} else {
((x * 31) >> 6) as u16
}
};
let mut at = 65;
(0..16)
.map(|i| {
let n = if i == 0 { 3 } else { 4 };
let w = WEIGHTS[bits(block, at, n) as usize];
at += n;
let mut t = [1.0; 4];
for c in 0..3 {
let (a, b) = (unquantize(ends[0][c]), unquantize(ends[1][c]));
let x = ((64 - w) * a + w * b + 32) >> 6;
t[c] = f16_from_bits(finish(x));
}
t
})
.collect()
}
struct Format {
name: &'static str,
bytes: usize,
half: bool,
decode: fn(&[u8]) -> Vec<Texel>,
}
fn with_srgb(t: Vec<Texel>) -> Vec<Texel> {
t.into_iter()
.map(|[r, g, b, a]| [srgb(r), srgb(g), srgb(b), a])
.collect()
}
fn bc2(block: &[u8]) -> Vec<Texel> {
let mut t = bc1(&block[8..], true);
for (i, texel) in t.iter_mut().enumerate() {
texel[3] = bits(block, 4 * i, 4) as f64 / 15.0;
}
t
}
fn bc3(block: &[u8]) -> Vec<Texel> {
let alpha = bc4(&block[..8], false);
let mut t = bc1(&block[8..], true);
for (texel, a) in t.iter_mut().zip(alpha) {
texel[3] = a;
}
t
}
fn bc5(block: &[u8], signed: bool) -> Vec<Texel> {
let (r, g) = (bc4(&block[..8], signed), bc4(&block[8..], signed));
r.into_iter()
.zip(g)
.map(|(r, g)| [r, g, 0.0, 1.0])
.collect()
}
fn formats() -> Vec<Format> {
let f = |name, bytes, half, decode| Format {
name,
bytes,
half,
decode,
};
vec![
f("bc1_rgba", 8, false, |b| bc1(b, false)),
f("bc1_rgba_srgb", 8, false, |b| with_srgb(bc1(b, false))),
f("bc2_rgba", 16, false, bc2),
f("bc2_rgba_srgb", 16, false, |b| with_srgb(bc2(b))),
f("bc3_rgba", 16, false, bc3),
f("bc3_rgba_srgb", 16, false, |b| with_srgb(bc3(b))),
f("bc4_runorm", 8, false, |b| {
bc4(b, false)
.into_iter()
.map(|r| [r, 0.0, 0.0, 1.0])
.collect()
}),
f("bc4_rsnorm", 8, false, |b| {
bc4(b, true)
.into_iter()
.map(|r| [r, 0.0, 0.0, 1.0])
.collect()
}),
f("bc5_rgunorm", 16, false, |b| bc5(b, false)),
f("bc5_rgsnorm", 16, false, |b| bc5(b, true)),
f("bc6h_rgbufloat", 16, true, |b| bc6h_mode11(b, false)),
f("bc6h_rgbfloat", 16, true, |b| bc6h_mode11(b, true)),
f("bc7_rgbaunorm", 16, false, bc7_mode6),
f("bc7_rgbaunorm_srgb", 16, false, |b| with_srgb(bc7_mode6(b))),
]
}
/// A random block of a format, in the mode the decoder above reads.
fn block(f: &Format, rng: &mut Random) -> Vec<u8> {
let mut b: Vec<u8> = (0..f.bytes).map(|_| (rng.u32() % 256) as u8).collect();
if f.name.starts_with("bc7") {
b[0] = (b[0] & 0x80) | 0x40;
}
if f.name.starts_with("bc6h") {
b[0] = (b[0] & 0xE0) | 0x03;
}
b
}
pub fn build(plan: &mut Plan, library: &str) {
let mut rng = Random::new(4093);
let (w, h) = (8u32, 8u32);
for f in formats() {
let blocks: Vec<Vec<u8>> = (0..(w / 4) * (h / 4))
.map(|_| block(&f, &mut rng))
.collect();
let decoded: Vec<Vec<Texel>> = blocks.iter().map(|b| (f.decode)(b)).collect();
let mut points = vec![];
let mut expect = vec![];
for y in 0..h {
for x in 0..w {
points.extend([x, y, 0, 0]);
let block = (y / 4 * (w / 4) + x / 4) as usize;
expect.extend(decoded[block][((y % 4) * 4 + x % 4) as usize]);
}
}
// Two steps of the endpoints' precision, through the sRGB curve's
// steepest slope for sRGB formats.
let tol = if f.half {
Tolerance::ulp(1.0)
} else if f.name.ends_with("srgb") {
Tolerance::abs(0.02)
} else if f.name.contains("snorm") {
Tolerance::abs(2.0 / 127.0)
} else {
Tolerance::abs(2.0 / 255.0)
}
.with_ftz(false);
plan.add(
Case::compute1(
&format!("texture.compressed.{}", f.name),
library,
"read2d_float",
w * h,
)
.requires(&[], &["bc_compression"])
.buffer(Buffer::data(
"coords",
0,
points.iter().flat_map(|v: &u32| v.to_le_bytes()).collect(),
))
.buffer(Buffer::zeroed("out", 1, (w * h * 16) as usize))
.output(Output::new("out", Dtype::F32, tol.clone()).expect(f32s(&expect), tol))
.texture(
Texture::d2("t", f.name, w, h)
.index(0)
.data(blocks.concat()),
),
);
}
}
+36
View File
@@ -426,6 +426,9 @@ fn simd(plan: &mut Plan, library: &str) {
.buffer(Buffer::zeroed("out", 1, n * 32))
.output(exact("out", Dtype::U32, words(&quad))),
);
if plan.has(SOURCE, "simdgroup_matrix_bfloat") {
simdgroup_matrix_bfloat(plan, library);
}
if plan.has(SOURCE, "simdgroup_matrix") {
let mut rng = Random::new(33);
let a: Vec<f64> = (0..64).map(|_| (rng.u32() % 7) as f64 - 3.0).collect();
@@ -464,6 +467,39 @@ fn simd(plan: &mut Plan, library: &str) {
}
}
/// An 8x8 bfloat SIMD-group matrix product of small integers, exact in
/// bfloat: A * B + A.
fn simdgroup_matrix_bfloat(plan: &mut Plan, library: &str) {
let mut rng = Random::new(34);
let a: Vec<f64> = (0..64).map(|_| (rng.u32() % 7) as f64 - 3.0).collect();
let b: Vec<f64> = (0..64).map(|_| (rng.u32() % 7) as f64 - 3.0).collect();
let bf = |v: &[f64]| -> Vec<u8> {
v.iter()
.flat_map(|&x| (((x as f32).to_bits() >> 16) as u16).to_le_bytes())
.collect()
};
let prod: Vec<f64> = (0..64)
.map(|i| {
let (r, c) = (i / 8, i % 8);
sum((0..8).map(|k| a[r * 8 + k] * b[k * 8 + c])) + a[i]
})
.collect();
plan.add(
Case::compute(
"compute.simdgroup_matrix.bfloat",
library,
"simdgroup_matrix_bfloat",
[32, 1, 1],
[32, 1, 1],
)
.buffer(Buffer::data("a", 0, bf(&a)))
.buffer(Buffer::data("b", 1, bf(&b)))
.buffer(Buffer::zeroed("out", 2, 128))
.output(exact("out", Dtype::U16, bf(&prod)))
.requires(&[], &["simd_reduction"]),
);
}
/// struct Mixed: char, short, float3 at 16, packed_float3 at 32, half at
/// 44, uchar4 at 48, float2x2 at 56, 80 bytes with its alignment.
#[allow(clippy::too_many_arguments)]
+34 -2
View File
@@ -539,6 +539,15 @@ impl Case {
case
}
/// Work one of Apple's frameworks encodes with its own shaders over
/// the case's resources: `framework` names it and its parameters.
pub fn framework(name: &str, framework: Value) -> Self {
let mut case = Self::new(name, "framework", None);
case.json.insert("framework".into(), framework);
case.render = true;
case
}
/// The device's families, features and limits.
pub fn device(name: &str) -> Self {
Self::new(name, "device", None)
@@ -616,6 +625,9 @@ pub struct Library {
pub dynamic: bool,
/// The dynamic libraries it links against.
pub links: Vec<String>,
/// Compiled by the device at run time from source, with these
/// `MTLCompileOptions`, in place of a metallib the Mac builds.
pub runtime: Option<Value>,
}
/// Which functions of each guarded corpus source Apple's compiler refuses
@@ -664,6 +676,7 @@ impl Plan {
flags: all,
dynamic: false,
links: vec![],
runtime: None,
},
);
}
@@ -678,6 +691,15 @@ impl Plan {
name
}
/// A library the device compiles from a corpus source at run time with
/// `options`: `language`, `fast_math`, `macros`, `preserve_invariance`
/// and `optimization`, as `MTLCompileOptions` takes them.
pub fn runtime_library(&mut self, name: &str, source: &str, options: Value) -> String {
let name = self.library(name, source, &[], LATEST);
self.libraries.get_mut(&name).unwrap().runtime = Some(options);
name
}
/// Links `name` against the dynamic libraries `dependencies`.
pub fn link(&mut self, name: &str, dependencies: &[&str]) {
self.libraries.get_mut(name).unwrap().links =
@@ -818,6 +840,7 @@ impl Plan {
used.extend(linked);
let mut libraries = Map::new();
let mut builds = Map::new();
let mut runtime_sources = vec![];
for (name, library) in &self.libraries {
if !used.contains(name.as_str()) {
continue;
@@ -828,7 +851,16 @@ impl Plan {
flags,
dynamic,
links,
runtime,
} = library;
let base = Path::new(source).file_name().unwrap().to_string_lossy();
if let Some(options) = runtime {
let mut entry = options.as_object().cloned().unwrap_or_default();
entry.insert("source".into(), format!("sources/{base}").into());
libraries.insert(name.clone(), entry.into());
runtime_sources.push(source.as_str());
continue;
}
libraries.insert(name.clone(), format!("lib/{name}.metallib").into());
builds.insert(
name.clone(),
@@ -844,8 +876,8 @@ impl Plan {
}
let sources = dir.join("sources");
fs::create_dir_all(&sources)?;
for build in builds.values() {
let source = build["source"].as_str().unwrap();
let built = builds.values().map(|b| b["source"].as_str().unwrap());
for source in built.chain(runtime_sources) {
let base = Path::new(source).file_name().unwrap();
fs::write(sources.join(base), self.source_text(source, corpus)?)?;
}
+2 -1
View File
@@ -85,7 +85,8 @@ fn mac_script(plan: &Value) -> String {
}
lines.push(
"clang -fobjc-arc -arch arm64 -mmacosx-version-min=14.0 -O1 -Wall -Wextra -Wno-unused-parameter \
-framework Foundation -framework Metal runner.m -o runner"
-framework Foundation -framework Metal -framework MetalPerformanceShaders -framework CoreImage \
-framework CoreGraphics runner.m -o runner"
.into(),
);
lines.join("\n") + "\n"
+225
View File
@@ -778,6 +778,45 @@ fn store(format: &str, texel: [f64; 4]) -> (Vec<u8>, Dtype) {
Dtype::U8,
),
"r8unorm" => (vec![unorm_bytes(r, 8) as u8], Dtype::U8),
"r8snorm" => (vec![snorm_bits(r, 8) as u8], Dtype::U8),
"rg8snorm" => (
vec![snorm_bits(r, 8) as u8, snorm_bits(g, 8) as u8],
Dtype::U8,
),
"r16unorm" => (u16s(&[unorm_bytes(r, 16)]), Dtype::U16),
"r16snorm" => (u16s(&[snorm_bits(r, 16)]), Dtype::U16),
"rg16unorm" => (u16s(&[unorm_bytes(r, 16), unorm_bytes(g, 16)]), Dtype::U16),
"rg16snorm" => (u16s(&[snorm_bits(r, 16), snorm_bits(g, 16)]), Dtype::U16),
"r8unorm_srgb" => (vec![unorm_bytes(srgb_encode(r), 8) as u8], Dtype::U8),
"rg8unorm_srgb" => (
vec![
unorm_bytes(srgb_encode(r), 8) as u8,
unorm_bytes(srgb_encode(g), 8) as u8,
],
Dtype::U8,
),
// Packed 16-bit formats, lanes from the least significant bits.
"abgr4unorm" => (
u16s(&[unorm_bytes(a, 4)
| unorm_bytes(b, 4) << 4
| unorm_bytes(g, 4) << 8
| unorm_bytes(r, 4) << 12]),
Dtype::U16,
),
"a1bgr5unorm" => (
u16s(&[unorm_bytes(a, 1)
| unorm_bytes(b, 5) << 1
| unorm_bytes(g, 5) << 6
| unorm_bytes(r, 5) << 11]),
Dtype::U16,
),
"bgr5a1unorm" => (
u16s(&[unorm_bytes(b, 5)
| unorm_bytes(g, 5) << 5
| unorm_bytes(r, 5) << 10
| unorm_bytes(a, 1) << 15]),
Dtype::U16,
),
"rg8unorm" => (
vec![unorm_bytes(r, 8) as u8, unorm_bytes(g, 8) as u8],
Dtype::U8,
@@ -874,12 +913,26 @@ fn targets(plan: &mut Plan, library: &str) {
"r32float",
"rg32float",
"rg11b10float",
"r8snorm",
"rg8snorm",
"r16unorm",
"r16snorm",
"rg16unorm",
"rg16snorm",
"r8unorm_srgb",
"rg8unorm_srgb",
"abgr4unorm",
"a1bgr5unorm",
"bgr5a1unorm",
] {
let float = format.contains("float");
let snorm = format.contains("snorm");
let steps = |lane: usize| match format {
"b5g6r5unorm" if lane == 1 => 63.0,
"b5g6r5unorm" => 31.0,
"abgr4unorm" => 15.0,
"a1bgr5unorm" | "bgr5a1unorm" if lane == 3 => 1.0,
"a1bgr5unorm" | "bgr5a1unorm" => 31.0,
f if f.contains("10a2") && lane == 3 => 3.0,
f if f.contains("10a2") => 1023.0,
f if f.contains("16") && snorm => 32767.0,
@@ -924,6 +977,94 @@ fn targets(plan: &mut Plan, library: &str) {
.output(Output::new("c", dtype, tol.clone()).expect(expected, tol)),
);
}
// Integer targets: in-range values stored as they are.
for (format, lanes, bits, signed) in [
("r8uint", 1, 8, false),
("r8sint", 1, 8, true),
("rg8uint", 2, 8, false),
("rg8sint", 2, 8, true),
("rgba8uint", 4, 8, false),
("rgba8sint", 4, 8, true),
("r16uint", 1, 16, false),
("r16sint", 1, 16, true),
("rg16uint", 2, 16, false),
("rg16sint", 2, 16, true),
("rgba16uint", 4, 16, false),
("rgba16sint", 4, 16, true),
("r32uint", 1, 32, false),
("r32sint", 1, 32, true),
("rg32uint", 2, 32, false),
("rg32sint", 2, 32, true),
("rgba32uint", 4, 32, false),
("rgba32sint", 4, 32, true),
("rgb10a2uint", 4, 10, false),
] {
let width = |lane: usize| {
if format == "rgb10a2uint" && lane == 3 {
2
} else {
bits
}
};
let texels: Vec<[i64; 4]> = (0..W * H)
.map(|_| {
std::array::from_fn(|lane| {
let w = width(lane);
let v = i64::from(rng.u32()) & ((1i64 << w) - 1);
if signed && v >= 1 << (w - 1) {
v - (1 << w)
} else {
v
}
})
})
.collect();
let shader: Vec<u8> = texels
.iter()
.flatten()
.flat_map(|&v| (v as i32).to_le_bytes())
.collect();
let stored: Vec<i128> = texels
.iter()
.flat_map(|t| t[..lanes].iter().map(|&v| i128::from(v)))
.collect();
let (dtype, bytes) = if format == "rgb10a2uint" {
let words: Vec<u32> = texels
.iter()
.map(|t| (t[0] | t[1] << 10 | t[2] << 20 | t[3] << 30) as u32)
.collect();
(Dtype::U32, u32s(&words))
} else {
let dtype = match (bits, signed) {
(8, false) => Dtype::U8,
(8, true) => Dtype::I8,
(16, false) => Dtype::U16,
(16, true) => Dtype::I16,
(_, false) => Dtype::U32,
_ => Dtype::I32,
};
(dtype, ints(dtype, &stored))
};
let fragment = if signed {
"frag_color_int"
} else {
"frag_color_uint"
};
plan.add(
Case::render(
&format!("render.target.{format}"),
library,
"vert_full",
Some(fragment),
json!({"vertex_count": 3, "colors": [{"texture": "c", "clear": [0, 0, 0, 0]}]}),
)
.buffer(Buffer::data("colors", 0, shader).stage("fragment"))
.buffer(Buffer::data("width", 1, u32s(&[W])).stage("fragment"))
.buffer(Buffer::data("depth", 2, f32s(&[0.5])).stage("vertex"))
.texture(target("c", format))
.output(Output::new("c", dtype, Tolerance::exact()).expect_same(bytes)),
);
}
// A half4 fragment output.
let texels: Vec<f64> = (0..W * H * 4)
.map(|_| f16r(rng.uniform(-8.0, 8.0)))
@@ -2084,6 +2225,82 @@ fn vertex_formats() -> Vec<VertexFormat> {
)),
vf!("uint4", 16, "uint", |b| [0, 1, 2, 3]
.map(|i| f64::from(u32_at(b, i)))),
vf!("uchar3", 3, "uint", |b| lanes(
&[0, 1, 2].map(|i| f64::from(b[i]))
)),
vf!("char2", 2, "int", |b| lanes(
&[0, 1].map(|i| f64::from(b[i] as i8))
)),
vf!("uchar3normalized", 3, "float", |b| lanes(
&[0, 1, 2].map(|i| f64::from(b[i]) / 255.0)
)),
vf!("charnormalized", 1, "float", |b| lanes(&[snorm_of(
f64::from(b[0] as i8),
127.0
)])),
vf!("char3normalized", 3, "float", |b| lanes(
&[0, 1, 2].map(|i| snorm_of(f64::from(b[i] as i8), 127.0))
)),
vf!("ushort2", 4, "uint", |b| lanes(
&[0, 1].map(|i| f64::from(u16_at(b, i)))
)),
vf!("ushort3", 6, "uint", |b| lanes(
&[0, 1, 2].map(|i| f64::from(u16_at(b, i)))
)),
vf!("short", 2, "int", |b| lanes(&[f64::from(
u16_at(b, 0) as i16
)])),
vf!("short3", 6, "int", |b| lanes(
&[0, 1, 2].map(|i| f64::from(u16_at(b, i) as i16))
)),
vf!("ushortnormalized", 2, "float", |b| lanes(&[f64::from(
u16_at(b, 0)
) / 65535.0])),
vf!("ushort3normalized", 6, "float", |b| lanes(
&[0, 1, 2].map(|i| f64::from(u16_at(b, i)) / 65535.0)
)),
vf!("shortnormalized", 2, "float", |b| lanes(&[snorm_of(
f64::from(u16_at(b, 0) as i16),
32767.0
)])),
vf!("short2normalized", 4, "float", |b| lanes(
&[0, 1].map(|i| snorm_of(f64::from(u16_at(b, i) as i16), 32767.0))
)),
vf!("short3normalized", 6, "float", |b| lanes(
&[0, 1, 2].map(|i| snorm_of(f64::from(u16_at(b, i) as i16), 32767.0))
)),
vf!("half3", 6, "half", |b| lanes(
&[0, 1, 2].map(|i| super::values::f16_from_bits(u16_at(b, i)))
)),
vf!("int2", 8, "int", |b| lanes(
&[0, 1].map(|i| f64::from(u32_at(b, i) as i32))
)),
vf!("int4", 16, "int", |b| [0, 1, 2, 3]
.map(|i| f64::from(u32_at(b, i) as i32))),
vf!("uint", 4, "uint", |b| lanes(&[f64::from(u32_at(b, 0))])),
vf!("uint3", 12, "uint", |b| lanes(
&[0, 1, 2].map(|i| f64::from(u32_at(b, i)))
)),
vf!("floatrg11b10", 4, "float", |b| {
let w = u32_at(b, 0);
let small = |at: u32, bits: u32, mantissa: u32| {
let q = (w >> at) & ((1 << bits) - 1);
let (e, m) = (q >> mantissa, q & ((1 << mantissa) - 1));
let fraction = f64::from(m) / f64::from(1u32 << mantissa);
if e == 0 {
fraction * 2f64.powi(-14)
} else {
(1.0 + fraction) * 2f64.powi(e as i32 - 15)
}
};
[small(0, 11, 6), small(11, 11, 6), small(22, 10, 5), 1.0]
}),
vf!("floatrgb9e5", 4, "float", |b| {
let w = u32_at(b, 0);
let scale = 2f64.powi((w >> 27) as i32 - 15 - 9);
let lane = |at: u32| f64::from((w >> at) & 511) * scale;
[lane(0), lane(9), lane(18), 1.0]
}),
vf!("int1010102normalized", 4, "float", |b| {
let w = u32_at(b, 0);
let field = |at: u32, bits: u32| {
@@ -2107,6 +2324,14 @@ fn vertex_formats() -> Vec<VertexFormat> {
/// Random bytes for a vertex format, finite for its float lanes.
fn vertex_bytes(f: &VertexFormat, rng: &mut Random) -> Vec<u8> {
if f.name == "floatrg11b10" {
// Exponents below 31: no infinities or NaNs.
let field = |rng: &mut Random, mantissa: u32| {
(rng.below(31) << mantissa) | rng.below(1 << mantissa)
};
let w = field(rng, 6) | (field(rng, 6) << 11) | (field(rng, 5) << 22);
return (w as u32).to_le_bytes().to_vec();
}
match f.shader {
"half" => (0..f.size / 2)
.flat_map(|_| f16_bits(f16r(rng.uniform(-100.0, 100.0))).to_le_bytes())
+65
View File
@@ -741,6 +741,70 @@ fn api_ordering(plan: &mut Plan, library: &str, rng: &mut Random) {
);
}
/// Ordering across queues and command buffers: a second queue's work an
/// event orders before the first's, a listener the host registers for a
/// value the GPU signals, command buffers that retain nothing, a
/// concurrent encoder whose barrier orders two dispatches, and completion
/// handlers that run in commit order after scheduling.
fn queues_and_handlers(plan: &mut Plan, library: &str, rng: &mut Random) {
let v: Vec<u32> = (0..N).map(|_| rng.u32()).collect();
let expect = u32s(&neighbours(&scaled(&v)));
let base = |name: &str, steps: Vec<Step>| {
Case::sequence(name, library, steps)
.buffer(Buffer::data("in", 0, u32s(&v)).unbound())
.buffer(Buffer::zeroed("mid", 0, N as usize * 4).unbound())
.buffer(Buffer::zeroed("out", 0, N as usize * 4).unbound())
.buffer(Buffer::data("n", 0, u32s(&[N])).unbound())
.output(exact("out", Dtype::U32, expect.clone()))
};
let scale = || Step::compute("scale", grid(N), [64, 1, 1]).bind(&[("in", 0), ("mid", 1)]);
let neighbour = || {
Step::compute("neighbours", grid(N), [64, 1, 1]).bind(&[("mid", 0), ("out", 1), ("n", 2)])
};
plan.add(base(
"sequence.queues.event",
vec![
scale().set("queue", 1).signal_events(&[("e", 1)]),
neighbour().wait_events(&[("e", 1)]),
],
));
plan.add(
base(
"sequence.event.listener",
vec![
scale().signal_events(&[("e", 5)]),
neighbour().new_command_buffer(),
],
)
.set("listen", json!([["e", 5, "heard"]]))
.buffer(Buffer::zeroed("heard", 0, 16).unbound())
.output(exact("heard", Dtype::U32, u32s(&[1, 5, 0, 0]))),
);
plan.add(base("sequence.unretained", vec![scale(), neighbour()]).set("unretained", true));
plan.add(base(
"sequence.compute.concurrent_barrier",
vec![
scale().set("concurrent", true),
neighbour().continues().set("barrier", "buffers"),
],
));
plan.add(
base(
"sequence.handlers",
vec![scale(), neighbour().new_command_buffer()],
)
.set("handlers", "order")
.buffer(Buffer::zeroed("order", 0, 40).unbound())
// Buffers 0 and 1 complete in order, each after its scheduling,
// the last with MTLCommandBufferStatusCompleted (4).
.output(exact(
"order",
Dtype::U32,
u32s(&[0, 1, 0, 0, 0, 0, 0, 0, 1, 4]),
)),
);
}
pub fn build(plan: &mut Plan) {
let library = plan.library("sequences", SOURCE, &[], super::plan::LATEST);
let mut rng = Random::new(5150);
@@ -750,4 +814,5 @@ pub fn build(plan: &mut Plan) {
indirect_commands(plan, &library, &mut rng);
indirect_commands_more(plan, &library, &mut rng);
api_ordering(plan, &library, &mut rng);
queues_and_handlers(plan, &library, &mut rng);
}
+434 -8
View File
@@ -256,6 +256,48 @@ fn formats() -> Vec<Format> {
let q = fields(word(b), &[10, 10, 10, 2]);
[q[0] as f64, q[1] as f64, q[2] as f64, q[3] as f64]
}),
entry!("a8unorm", 1, Float, |b| [
0.0,
0.0,
0.0,
unorm(b[0].into(), 8)
]),
entry!("r8unorm_srgb", 1, Float, |b| lanes(&[srgb(unorm(
b[0].into(),
8
))])),
entry!("rg8unorm_srgb", 2, Float, |b| lanes(&[
srgb(unorm(b[0].into(), 8)),
srgb(unorm(b[1].into(), 8))
])),
entry!("rg8snorm", 2, Float, |b| lanes(&[
snorm(b[0].into(), 8),
snorm(b[1].into(), 8)
])),
entry!("rg16snorm", 4, Float, |b| lanes(&[
snorm(short(b, 0), 16),
snorm(short(b, 1), 16)
])),
entry!("r8sint", 1, Int, |b| lanes(&[b[0] as i8 as f64])),
entry!("rg8sint", 2, Int, |b| lanes(&[
b[0] as i8 as f64,
b[1] as i8 as f64
])),
entry!("r16sint", 2, Int, |b| lanes(&[
signed(short(b, 0), 16) as f64
])),
entry!("rg16uint", 4, Uint, |b| lanes(&[
short(b, 0) as f64,
short(b, 1) as f64
])),
entry!("rg16sint", 4, Int, |b| lanes(&[
signed(short(b, 0), 16) as f64,
signed(short(b, 1), 16) as f64
])),
entry!("rg32sint", 8, Int, |b| lanes(&[
word(b) as u32 as i32 as f64,
word(&b[4..]) as u32 as i32 as f64
])),
]
}
@@ -540,6 +582,11 @@ struct Sampler {
border: &'static str,
lod: Option<(f64, f64)>,
compare: Option<&'static str>,
/// How filtered texels combine: their weighted average, or the
/// minimum or maximum of those with weight.
reduction: &'static str,
lod_bias: f64,
anisotropy: u32,
}
impl Sampler {
@@ -553,6 +600,9 @@ impl Sampler {
border: "transparent_black",
lod: None,
compare: None,
reduction: "weighted_average",
lod_bias: 0.0,
anisotropy: 1,
}
}
@@ -568,6 +618,15 @@ impl Sampler {
if let Some(c) = self.compare {
s["compare"] = json!(c);
}
if self.reduction != "weighted_average" {
s["reduction"] = json!(self.reduction);
}
if self.lod_bias != 0.0 {
s["lod_bias"] = json!(self.lod_bias);
}
if self.anisotropy > 1 {
s["anisotropy"] = json!(self.anisotropy);
}
s
}
@@ -630,7 +689,11 @@ impl Level {
let (x0, fx) = axis(x, true);
let (y0, fy) = axis(y, dims > 1);
let (z0, fz) = axis(z, dims > 2);
let mut out = [0.0; 4];
let mut out = match s.reduction {
"minimum" => [f64::INFINITY; 4],
"maximum" => [f64::NEG_INFINITY; 4],
_ => [0.0; 4],
};
for dz in 0..if dims > 2 { 2 } else { 1 } {
for dy in 0..if dims > 1 { 2 } else { 1 } {
for dx in 0..2 {
@@ -647,7 +710,12 @@ impl Level {
});
let t = self.fetch(s, x0 + dx, y0 + dy, z0 + dz);
for k in 0..4 {
out[k] += t[k] * weight;
out[k] = match s.reduction {
"minimum" if weight > 0.0 => out[k].min(t[k]),
"maximum" if weight > 0.0 => out[k].max(t[k]),
"minimum" | "maximum" => out[k],
_ => out[k] + t[k] * weight,
};
}
}
}
@@ -660,7 +728,10 @@ impl Level {
/// coordinates and a level of detail.
fn sample(levels: &[Level], s: &Sampler, uvw: [f64; 3], lod: f64, dims: u32) -> Texel {
let (lo, hi) = s.lod.unwrap_or((0.0, 1000.0));
let lod = lod.max(lo).min(hi).min((levels.len() - 1) as f64);
let lod = (lod + s.lod_bias)
.max(lo)
.min(hi)
.min((levels.len() - 1) as f64);
let linear = if lod <= 0.0 { s.mag } else { s.min } == "linear";
let at = |l: usize| levels[l].filter(s, linear, uvw[0], uvw[1], uvw[2], dims);
match s.mip {
@@ -674,7 +745,11 @@ fn sample(levels: &[Level], s: &Sampler, uvw: [f64; 3], lod: f64, dims: u32) ->
return first;
}
let second = at(base + 1);
[0, 1, 2, 3].map(|k| first[k] * (1.0 - frac) + second[k] * frac)
[0, 1, 2, 3].map(|k| match s.reduction {
"minimum" => first[k].min(second[k]),
"maximum" => first[k].max(second[k]),
_ => first[k] * (1.0 - frac) + second[k] * frac,
})
}
}
}
@@ -712,7 +787,11 @@ fn samplers() -> Vec<Sampler> {
clamp.lod = Some((1.0, 2.5));
let mut min_mag = mip("min_mag", "nearest", "nearest");
min_mag.mag = "linear";
// An explicit level of detail leaves anisotropy nothing to change.
let mut aniso = mip("anisotropic", "linear", "linear");
aniso.anisotropy = 16;
out.extend([
aniso,
black,
white,
mixed,
@@ -950,6 +1029,59 @@ fn forms(plan: &mut Plan, library: &str, rng: &mut Random) {
.sampler(lin.json()),
);
}
// The same gradients through samplers that bias the computed level
// of detail or reduce the footprint to its minimum or maximum.
if plan.has(SOURCE, "sample2d_grad") {
let mut biased = Sampler::new("biased", "linear", "repeat");
biased.mip = "linear";
biased.lod_bias = 0.75;
let reduced = |reduction| {
let mut s = Sampler::new("reduced", "linear", "repeat");
s.mip = "linear";
s.reduction = reduction;
s
};
for (label, sampler) in [
("lod_bias", biased),
("reduction.minimum", reduced("minimum")),
("reduction.maximum", reduced("maximum")),
] {
let mut coords = vec![];
let mut expected = vec![];
for p in &pts {
// A level that the bias keeps off the last one.
let lod = lattice(p[3] * 0.7);
let dx = f32r(2f64.powf(lod) / 16.0);
coords.extend([p[0], p[1], dx, dx]);
expected.extend(sample(&levels, &sampler, [p[0], p[1], 0.0], lod, 2).map(f32r));
}
let mut case = Case::compute1(
&format!("texture.sample.gradient.{label}"),
library,
"sample2d_grad",
256,
)
.buffer(Buffer::data("coords", 0, f32s(&coords)))
.buffer(Buffer::zeroed("out", 1, 256 * 16))
.output(
Output::new("out", Dtype::F32, mip.clone()).expect(f32s(&expected), mip.clone()),
)
.texture(tex())
.sampler(sampler.json());
// Both are macOS 26 sampler properties the M1 Pro ignores: it
// filters by weighted average at the unbiased level.
let ignored = if label == "lod_bias" {
"lodBias"
} else {
"reductionMode"
};
case = case.set(
"reference_divergence",
format!("the M1 Pro ignores {ignored}"),
);
plan.add(case);
}
}
// gradient2d((c.z, 0), (0, c.z)) with min_lod_clamp(c.w).
let mut coords = vec![];
let mut expected = vec![];
@@ -1347,10 +1479,12 @@ fn encode(name: &str, values: &[f64]) -> Vec<u8> {
v.iter()
.flat_map(|&x| (x as i64 as u32).to_le_bytes())
.collect()
} else if name.ends_with("16uint") {
v.iter().flat_map(|&x| (x as u16).to_le_bytes()).collect()
} else if name.ends_with("8uint") {
v.iter().map(|&x| x as u8).collect()
} else if name.ends_with("16uint") || name.ends_with("16sint") {
v.iter()
.flat_map(|&x| (x as i64 as u16).to_le_bytes())
.collect()
} else if name.ends_with("8uint") || name.ends_with("8sint") {
v.iter().map(|&x| x as i64 as u8).collect()
} else {
panic!("no encoder for {name}")
}
@@ -1409,6 +1543,74 @@ fn writes(plan: &mut Plan, library: &str) {
.texture(t2d("t", name, w, h).usage(&["read", "write"])),
);
}
// Every other format Metal makes writable on Apple7 and Mac2 GPUs:
// texels written as they read back give their bytes again. Signed
// normalized texels avoid their most negative value, which reads as
// -1 like the one above it.
for name in [
"r8snorm",
"r8uint",
"r8sint",
"r16unorm",
"r16snorm",
"r16uint",
"r16sint",
"r16float",
"rg8snorm",
"rg8uint",
"rg8sint",
"rg16unorm",
"rg16snorm",
"rg16uint",
"rg16sint",
"rg16float",
"rgba8snorm",
"rgba8sint",
"bgra8unorm",
"rgb10a2unorm",
"rgb10a2uint",
"rg32uint",
"rg32sint",
"rgba16unorm",
"rgba16snorm",
"rgba16sint",
] {
let f = format_named(name);
let texels: Vec<Vec<u8>> = (0..w * h)
.map(|_| {
loop {
let t = texel_bytes(&f, &mut rng);
let lane = if name.contains("16") { 2 } else { 1 };
let lowest = t.chunks(lane).any(|c| match lane {
1 => c[0] == 0x80,
_ => c == [0x00, 0x80],
});
if !(name.contains("snorm") && lowest) {
break t;
}
}
})
.collect();
let (shader, dtype) = match f.kind {
Kind::Float => ("float", Dtype::F32),
Kind::Uint => ("uint", Dtype::U32),
Kind::Int => ("int", Dtype::I32),
};
let values: Vec<f64> = texels.iter().flat_map(|t| decode(&f, t)).collect();
plan.add(
Case::compute(
&format!("texture.write.{name}"),
library,
&format!("write2d_{shader}"),
[w, h, 1],
[8, 8, 1],
)
.dispatch_threads()
.buffer(Buffer::data("values", 0, texels_as(dtype, &values)))
.output(Output::new("t", Dtype::U8, Tolerance::default()).expect_same(texels.concat()))
.texture(t2d("t", name, w, h).usage(&["read", "write"])),
);
}
let values: Vec<f64> = (0..8 * 4 * 4)
.map(|_| f32r(rng.uniform(-1.0, 1.0)))
.collect();
@@ -1486,6 +1688,12 @@ fn writes(plan: &mut Plan, library: &str) {
.requires(&[], &["read_write_textures_tier2"]),
);
}
if plan.has(SOURCE, "read_write") {
read_write_formats(plan, library, &mut rng);
}
if plan.has(SOURCE, "texture_atomics_ops") {
texture_atomic_ops(plan, library, &mut rng);
}
if plan.has(SOURCE, "texture_atomics") {
let n = 1024;
let values: Vec<u32> = (0..n).map(|_| rng.u32() % 100_000).collect();
@@ -1510,6 +1718,223 @@ fn writes(plan: &mut Plan, library: &str) {
}
}
/// Every format read-write textures of tier 2 support, each texel read,
/// changed and written back in place.
fn read_write_formats(plan: &mut Plan, library: &str, rng: &mut Random) {
let (w, h) = (8u32, 8u32);
for (name, lanes, kind) in [
("rgba16float", 4, Kind::Float),
("rgba8unorm", 4, Kind::Float),
("r32float", 1, Kind::Float),
("r16float", 1, Kind::Float),
("r8unorm", 1, Kind::Float),
("rgba32uint", 4, Kind::Uint),
("rgba16uint", 4, Kind::Uint),
("rgba8uint", 4, Kind::Uint),
("r32uint", 1, Kind::Uint),
("r16uint", 1, Kind::Uint),
("r8uint", 1, Kind::Uint),
("rgba32sint", 4, Kind::Int),
("rgba16sint", 4, Kind::Int),
("rgba8sint", 4, Kind::Int),
("r32sint", 1, Kind::Int),
("r16sint", 1, Kind::Int),
("r8sint", 1, Kind::Int),
] {
let bits: i64 = if name.contains("32") {
32
} else if name.contains("16") {
16
} else {
8
};
// Integers small enough that three times one plus another stays
// in range; floats exact in their format.
let value = |rng: &mut Random| -> f64 {
match kind {
Kind::Uint => (rng.u32() as i64 % (1i64 << (bits - 3))) as f64,
Kind::Int => {
((rng.u32() as i64 % (1i64 << (bits - 3))) - (1i64 << (bits - 4))) as f64
}
Kind::Float if name.contains("8unorm") => f64::from(rng.u32() % 256) / 255.0,
Kind::Float if name.contains("16float") => f16r(rng.uniform(-8.0, 8.0)),
Kind::Float => f32r(rng.uniform(-8.0, 8.0)),
}
};
let mut texels = vec![];
let mut expected = vec![];
for _ in 0..w * h {
let mut v = [0.0, 0.0, 0.0, 1.0];
for lane in v.iter_mut().take(lanes) {
*lane = value(rng);
}
texels.extend(encode(name, &v));
let rotated = [v[1], v[2], v[3], v[0]];
let out: Vec<f64> = match kind {
Kind::Float => [v[3], v[2], v[1], v[0]]
.iter()
.map(|x| f32r(x * 0.5 + 0.25))
.collect(),
Kind::Uint => (0..4).map(|k| v[k] * 3.0 + rotated[k] + 1.0).collect(),
Kind::Int => (0..4).map(|k| v[k] * 3.0 + rotated[k] - 1.0).collect(),
};
let out: Vec<f64> = if name.contains("16float") {
out.iter().map(|&x| f16r(x)).collect()
} else {
out
};
expected.extend(encode(name, &out));
}
let shader = match kind {
Kind::Float => "read_write",
Kind::Uint => "read_write_uint",
Kind::Int => "read_write_int",
};
// Unorm results round to the nearest step, half results either
// way from a float.
let (dtype, tol) = if name.contains("unorm") {
(Dtype::U8, Tolerance::units(1.0))
} else if name.contains("16float") {
(Dtype::F16, Tolerance::ulp(1.0))
} else {
(Dtype::U8, Tolerance::default())
};
plan.add(
Case::compute(
&format!("texture.read_write.{name}"),
library,
shader,
[w, h, 1],
[8, 8, 1],
)
.dispatch_threads()
.output(Output::new("t", dtype, tol.clone()).expect(expected, tol))
.texture(t2d("t", name, w, h).usage(&["read", "write"]).data(texels))
.requires(&[], &["read_write_textures_tier2"]),
);
}
}
/// Each texture atomic on 32-bit unsigned and signed texels, a compare
/// and exchange only one thread wins, and atomics on every texture type.
fn texture_atomic_ops(plan: &mut Plan, library: &str, rng: &mut Random) {
let n = 512u32;
for (format, signed) in [("r32uint", false), ("r32sint", true)] {
let values: Vec<u32> = (0..n).map(|_| rng.u32()).collect();
let mut row: [u32; 8] = [
0,
0,
u32::MAX,
0,
0,
if signed { i32::MAX as u32 } else { u32::MAX },
if signed { i32::MIN as u32 } else { 0 },
0,
];
let initial = row;
for (i, &v) in values.iter().enumerate() {
let t = &mut row[i % 8];
*t = match i % 8 {
0 => t.wrapping_add(v),
1 => t.wrapping_sub(v),
2 => *t & v,
3 => *t | v,
4 => *t ^ v,
5 if signed => (*t as i32).min(v as i32) as u32,
5 => (*t).min(v),
6 if signed => (*t as i32).max(v as i32) as u32,
6 => (*t).max(v),
_ => t.wrapping_add(1),
};
}
let mut data = u32s(&initial);
data.extend(vec![0u8; 32]);
let mut expected = u32s(&row);
expected.extend(vec![0u8; 32]);
let kernel = if signed {
"texture_atomics_int"
} else {
"texture_atomics_uint"
};
plan.add(
Case::compute1(&format!("texture.atomics.ops.{format}"), library, kernel, n)
.buffer(Buffer::data("values", 0, u32s(&values)))
.buffer(Buffer::zeroed("wins", 1, 16))
.output(
Output::new("t", Dtype::U32, Tolerance::default())
.expect_same(expected)
.expect_mask([vec![1; 8], vec![0; 8]].concat()),
)
.output(
Output::new("wins", Dtype::U32, Tolerance::default())
.expect_same(u32s(&[1, 0, 0, 0])),
)
.texture(
t2d("t", format, 8, 2)
.usage(&["read", "write", "atomic"])
.data(data),
),
);
}
// 64 threads, each adding to texel i % 4 of each texture type.
let adds = |k: u32| u32s(&[16 * k; 4]);
let zeros = |texels: usize| vec![0u8; texels * 4];
let place = |texels: usize, at: usize, k: u32| {
let mut v = zeros(texels);
v[at * 4..at * 4 + 16].copy_from_slice(&adds(k));
v
};
plan.add(
Case::compute1(
"texture.atomics.types",
library,
"texture_atomics_types",
64,
)
.buffer(Buffer::zeroed("storage", 0, 256).unbound())
.texture(
Texture::new("t1", "r32uint", "1d", [4, 1, 1])
.index(0)
.usage(&["read", "write", "atomic"])
.data(zeros(4)),
)
.texture(
Texture::new("t1a", "r32uint", "1d_array", [4, 1, 1])
.array(2)
.index(1)
.usage(&["read", "write", "atomic"])
.data(zeros(8)),
)
.texture(
Texture::new("t2a", "r32uint", "2d_array", [4, 2, 1])
.array(2)
.index(2)
.usage(&["read", "write", "atomic"])
.data(zeros(16)),
)
.texture(
Texture::new("t3", "r32uint", "3d", [4, 2, 2])
.index(3)
.usage(&["read", "write", "atomic"])
.data(zeros(16)),
)
.texture(
Texture::new("tb", "r32uint", "buffer", [4, 1, 1])
.index(4)
.usage(&["read", "write", "atomic"])
.set("buffer", "storage"),
)
.output(Output::new("t1", Dtype::U32, Tolerance::default()).expect_same(adds(1)))
.output(Output::new("t1a", Dtype::U32, Tolerance::default()).expect_same(place(8, 4, 2)))
.output(Output::new("t2a", Dtype::U32, Tolerance::default()).expect_same(place(16, 12, 3)))
.output(Output::new("t3", Dtype::U32, Tolerance::default()).expect_same(place(16, 12, 4)))
.output(
Output::new("storage", Dtype::U32, Tolerance::default())
.expect_same([adds(5), vec![0; 240]].concat()),
),
);
}
fn queries(plan: &mut Plan, library: &str) {
plan.add(
Case::compute("texture.queries", library, "queries", [1, 1, 1], [1, 1, 1])
@@ -1951,6 +2376,7 @@ pub fn build(plan: &mut Plan) {
writes(plan, &library);
queries(plan, &library);
variants(plan, &library, &mut Random::new(907));
super::compressed::build(plan, &library);
}
#[cfg(test)]