Sync upstream metal2vulkan for the Reims runtime

Preserve GPU suspend and replay, Places allocation isolation, and multi-draw indirect. Use the upstream render-offset deltas, static attachment feedback, and 64-bit device-address arithmetic.
This commit is contained in:
YXC0915 committed 2026-12-04 16:07:39 +08:00
commit 7b3aedb5fa
1095 files changed
+108429 -76851

No files matched your search

+104 -40
View File
@@ -42,22 +42,15 @@ jobs:
set -euo pipefail
sudo apt-get update
# llvm: llvm-dis; spirv-tools: spirv-val + the product passthrough path's spirv-as.
# lavapipe is the CPU Vulkan ICD for the `m2v_cpu_icd` execution tests and the explicit
# `corpus-vulkan --device-type cpu` qualification on GPU-less Linux runners.
# vulkan-validationlayers: every engine candidate and L4 run enables
# VK_LAYER_KHRONOS_validation and refuses to run without it.
sudo apt-get install -y llvm spirv-tools mesa-vulkan-drivers libvulkan1 vulkan-validationlayers
# libvulkan1 is the loader alone: this host has no Vulkan driver, and the steps that run
# on one (lavapipe) run in the lavapipe image below.
sudo apt-get install -y llvm spirv-tools libvulkan1
command -v llvm-dis
command -v spirv-val
command -v spirv-as
# Ubuntu's llvm is the oldest LLVM the committed `.ll` fixtures are written for:
# here the validation test that each assembles with it must run, not skip.
echo "METAL2VULKAN_TEST_REQUIRE_PINNED_LLVM=1" >> "$GITHUB_ENV"
# Fail setup early if the CPU-ICD steps would have no ICD.
shopt -s nullglob
icds=(/usr/share/vulkan/icd.d/*.json /etc/vulkan/icd.d/*.json)
echo "Vulkan ICDs: ${icds[*]:-none}"
test "${#icds[@]}" -gt 0
- name: Install LLVM + SPIR-V tools (macOS)
if: runner.os == 'macOS'
@@ -151,7 +144,8 @@ jobs:
run: cargo doc --workspace --all-features --no-deps
# The consumer reference of the new API's frozen surface: the library's
# rustdoc build, warnings denied, and no link to a hidden item.
# rustdoc build, warnings denied, and no link to a hidden item; first, no lab
# job id in the prose docs.
- name: Build the new API's consumer reference (warnings denied)
run: scripts/api-docs
@@ -167,6 +161,9 @@ jobs:
- name: Private intra-doc links (no new breakage)
env:
RUSTDOCFLAGS: -Dwarnings
# The count below reads lines that begin `error: `. Under the workflow's
# CARGO_TERM_COLOR=always each one begins with a colour code instead, so it counted none.
CARGO_TERM_COLOR: never
run: |
set -euo pipefail
log="$RUNNER_TEMP/private-doc-links.log"
@@ -208,61 +205,128 @@ jobs:
run: cargo package --workspace --exclude metal2vulkan-validation --exclude metal2vulkan-conformance --exclude metal2vulkan-devtools --exclude metal2vulkan-harness
# With the AIR front end's crate's own tests, and the dev-tools crate's:
# its tool runner and L3 checks.
# its tool runner and L3 checks. Every suite here runs to its end (--no-fail-fast), so one
# red test does not hide the tests after it; the step's verdict is the same.
- name: Test metal2vulkan
run: cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features
run: cargo nextest run --no-fail-fast -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features
# GPU-free on every host: tests that open a device compile only under `--cfg m2v_gpu` or
# `--cfg m2v_cpu_icd`, and no device-opening code runs without one of them.
- name: Test validation suite
run: cargo nextest run -p metal2vulkan-validation --all-features
run: cargo nextest run --no-fail-fast -p metal2vulkan-validation --all-features
# The conformance suite's own machinery, with no device: a stub side stands in for a GPU, so
# the transcript, the comparison, the justification rule, the verdicts, the recordings'
# staleness and the report are all checked on every host.
- name: Test the conformance suite
run: cargo nextest run -p metal2vulkan-conformance --all-features
run: cargo nextest run --no-fail-fast -p metal2vulkan-conformance --all-features
# nextest does not run doctests.
- name: Doc tests
run: cargo test --workspace --all-features --doc
# Device-executing validation tests, and the runtime's floor check, on lavapipe.
# `DeviceType::Cpu` matches only a CPU physical device, and the runtime's device tests under
# `m2v_cpu_icd` check only CPU devices, so this never reaches a GPU even on a runner that has
# one. macOS CI runs no device tests.
# The steps below that execute on a device run on lavapipe in the lavapipe image, and
# nowhere else: Arch Linux's packages of one Arch Linux Archive date, which
# scripts/lavapipe-image/pin pins with the bootstrap tarball's sha256, carrying the Mesa and
# LLVM the conformance ledger's llvmpipe rows hold on (its `# llvmpipe:` line). The image's
# downloads are cached keyed on the pin (its tarball's sha256, its date and its packages'
# versions), and saved as soon as the build has them, so a run whose pin has not moved
# downloads nothing, whatever the later steps answer.
- name: Restore the lavapipe image's downloads (Linux)
if: runner.os == 'Linux'
id: lavapipe-downloads
uses: actions/cache/restore@v4
with:
path: ~/.cache/m2v-lavapipe-image
key: lavapipe-image-${{ hashFiles('scripts/lavapipe-image/pin') }}
# Prints the image's pin, its packages, its device's name and driver, and whether its
# containers get /dev/udmabuf, and fails where the image differs from the pin or from the
# ledger's `# llvmpipe:` line. A fetch that fails ends this step with the URL it failed on,
# before any test runs. The limit fits a cold fetch at the slowest rate measured from the
# archive, one connection at 57 KB/s: the 127 MB tarball and 135 MB of databases and
# packages, 262 MB, take 77 minutes there.
- name: Build the lavapipe image (Linux)
if: runner.os == 'Linux'
timeout-minutes: 90
run: scripts/lavapipe-image/lavapipe-image ensure
- name: Save the lavapipe image's downloads (Linux)
if: runner.os == 'Linux' && steps.lavapipe-downloads.outputs.cache-hit != 'true'
uses: actions/cache/save@v4
with:
path: ~/.cache/m2v-lavapipe-image
key: lavapipe-image-${{ hashFiles('scripts/lavapipe-image/pin') }}
# The device tests of validation and the runtime, and the runtime's floor check, on lavapipe.
# They are the tests the `--cfg m2v_cpu_icd` build holds and the plain builds above do not: a
# test that opens a device compiles only under that cfg. The plain builds' tests ran on this
# host above, the `.ll` fixtures' test with Ubuntu's LLVM among them. The tests are built
# here, on the host, and only run in the image. Where its containers get no /dev/udmabuf,
# the tests scripts/lavapipe-image/needs-udmabuf names are skipped, each named in the log. `DeviceType::Cpu` matches only a CPU physical
# device, and the runtime's device tests under `m2v_cpu_icd` check only CPU devices. macOS CI
# runs no device tests.
- name: Test validation suite and the runtime on the CPU Vulkan ICD (Linux)
if: runner.os == 'Linux'
env:
RUSTFLAGS: -Dwarnings --cfg m2v_cpu_icd
LP_NUM_THREADS: "1"
run: cargo nextest run -p metal2vulkan-validation -p metal2vulkan-runtime --all-features
run: |
set -euo pipefail
out=$RUNNER_TEMP/cpu-icd
mkdir -p "$out"
cargo nextest list -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features --message-format json > "$out/plain-1.json"
cargo nextest list -p metal2vulkan-validation --all-features --message-format json > "$out/plain-2.json"
export RUSTFLAGS='-Dwarnings --cfg m2v_cpu_icd'
cargo nextest list -p metal2vulkan-validation -p metal2vulkan-runtime --all-features --message-format json > "$out/cpu-icd.json"
cargo nextest archive -p metal2vulkan-validation -p metal2vulkan-runtime --all-features --archive-file "$out/cpu-icd.tar.zst"
python3 -I scripts/lavapipe-image/only_in.py "$out/cpu-icd.json" "$out/plain-1.json" "$out/plain-2.json" > "$out/device-tests"
echo "$(wc -l < "$out/device-tests") device tests"
scripts/lavapipe-image/lavapipe-image nextest "$out/cpu-icd.tar.zst" "$out/device-tests" --no-fail-fast
# The conformance suite's replay leg on lavapipe: it reads the committed recordings, runs the
# runtime side and compares, with no Metal present. Its exit status is 0 only where the run
# holds no surprise: no unrecorded case, no stale recording, and exactly the gaps
# crates/metal2vulkan-conformance/known-gaps-rt.tsv expects on this venue. A refusal or a
# divergence that ledger does not list fails here, and so does a row it lists that the run no
# longer holds, so closing a gap forces the ledger edit. A venue that lacks a feature a case
# needs does not spoil it.
# The runtime's device tests again, the step above's archive, with llvmpipe at 128-bit vectors
# (LP_NATIVE_VECTOR_WIDTH=128): the width arm64 lavapipe runs at, where a fragment or compute
# subgroup is 4 lanes. The leg's Mesa shader cache is a directory of its own in the workspace:
# llvmpipe keys its disk cache without the vector width (Mesa 26.2.4), so a cache it shared
# with a 256-bit run would hand a 128-bit shader a 256-bit texture function. vulkaninfo's
# device name and subgroup sizes are printed first, and the step fails unless they show 128
# bits and subgroups of 4.
- name: Test the runtime on the CPU Vulkan ICD at 128-bit vectors (Linux)
if: runner.os == 'Linux'
run: |
set -euo pipefail
out=$RUNNER_TEMP/cpu-icd
cache=$PWD/target/mesa-shader-cache-128
mkdir -p "$cache"
scripts/lavapipe-image/lavapipe-image run --env LP_NATIVE_VECTOR_WIDTH=128 -- vulkaninfo > "$out/vulkaninfo-128.txt"
grep -E 'deviceName|subgroupSize|minSubgroupSize|maxSubgroupSize' "$out/vulkaninfo-128.txt" | sort -u
grep -q 'deviceName *= llvmpipe .*128 bits' "$out/vulkaninfo-128.txt"
grep -Eq 'maxSubgroupSize *= 4$' "$out/vulkaninfo-128.txt"
grep '^binary_id(=metal2vulkan-runtime[):]' "$out/device-tests" > "$out/device-tests-runtime"
echo "$(wc -l < "$out/device-tests-runtime") runtime device tests at 128-bit vectors"
scripts/lavapipe-image/lavapipe-image nextest --write "$cache" --env LP_NATIVE_VECTOR_WIDTH=128 \
--env MESA_SHADER_CACHE_DIR="$cache" "$out/cpu-icd.tar.zst" "$out/device-tests-runtime" --no-fail-fast
# The conformance suite's replay leg on lavapipe, in the image: it reads the committed
# recordings, runs the runtime side and compares, with no Metal present. Its exit status is 0
# only where the run holds no surprise: no unrecorded case, no stale recording, and exactly
# the gaps crates/metal2vulkan-conformance/known-gaps-rt.tsv expects on this venue. A refusal
# or a divergence that ledger does not list fails here, and so does a row it lists that the
# run no longer holds, so closing a gap forces the ledger edit. A venue that lacks a feature
# a case needs does not spoil it. Where the image's containers get no /dev/udmabuf, the
# cases scripts/lavapipe-image/needs-udmabuf names are left out, each named in the log.
- name: Replay the conformance suite on the CPU Vulkan ICD (Linux)
if: runner.os == 'Linux'
env:
LP_NUM_THREADS: "1"
run: |
set -euo pipefail
cargo build -p metal2vulkan-conformance --bin conformance
target/debug/conformance replay --cpu
scripts/lavapipe-image/lavapipe-image replay target/debug/conformance
# Machine-specific semantic qualification remains explicit. Linux CI has lavapipe, so it can
# execute the owned public cases with the engine, in both robustness legs, against their
# exact committed Metal observations without a physical GPU. Rows written here are ephemeral
# CI evidence, not committed environment slots (see the script's header).
# Machine-specific semantic qualification remains explicit. On lavapipe in the image, it
# executes the owned public cases with the engine, in both robustness legs, against their
# exact committed Metal observations without a physical GPU. Rows written here (in the
# corpus, the one directory the image may write) are ephemeral CI evidence, not committed
# environment slots (see the script's header).
- name: Qualify public cases on native Vulkan (Linux)
if: runner.os == 'Linux'
env:
LP_NUM_THREADS: "1"
run: |
set -euo pipefail
cargo build -p metal2vulkan-validation --bins
bash scripts/qualify-public-cases target/debug
scripts/lavapipe-image/lavapipe-image run --write crates/metal2vulkan-validation/corpus -- bash scripts/qualify-public-cases target/debug
+54 -13
View File
@@ -58,12 +58,17 @@ order, and a lower one never overrides a higher one.
limit and memory-type queries. Product code holds no vendor, device or driver ID, and no
runtime policy switch. A test enforces this for `metal2vulkan-runtime`. One form means one form per
Vulkan capability: where the floor cannot require a feature, that feature's query may choose a
second form, for twelve only: 16-bit floats, storage-image reads without a format, 64-bit
second form, for fourteen only: 16-bit floats, storage-image reads without a format, 64-bit
atomics, 64-bit floats, SIMD groups (the subgroup size range with its stages and operations,
and maximal reconvergence), unified memory (decided by
Vulkan's physical device type alone: one copy of a Managed buffer on an integrated or CPU
device, two elsewhere), the attachment feedback loop (a device without it reads a render
target through a counted copy of that target, recorded as a known gap), run-time texel
device, two elsewhere; a texture over a host-pointer import in place on an integrated or
CPU device, after one counted copy pair at its making, and through its per-use counted copy
elsewhere; and a Shared heap's image texture in its heap on an integrated or CPU device, and
elsewhere an optimal image of its own in device memory, its heap range left unused, whose
device memory beside the heap's block is recorded as a known gap), the attachment feedback
loop (a device without it reads a render target through a counted copy of that target,
recorded as a known gap), run-time texel
offsets (a device with the maintenance8 feature takes a run-time texel offset as the sampling
or read instruction's own operand; a device without it branches over the offset's values, and
that branch's compile time is recorded as a known gap), the push window (the device's
@@ -85,8 +90,29 @@ order, and a lower one never overrides a higher one.
device without them reaches them at their device addresses with each access checked in the
shader, and that check's cost is recorded as a known gap, as is the check that stays by
structure on a slot a wide pointer, a typed atomic or the stage-in fetch reaches, on a slot
bound below its argument's alignment, and on every render stage), and Shared memory's host
coherence (decided by the host-coherent flag of the memory type
bound below its argument's alignment, and on every render stage), mixed passes over a linear
plane (ruled 12-02; a device whose linear tiling offers a plane's format as a colour attachment
renders a surface plane in place in every pass; a device that offers it only where every
colour attachment of the pass is linear (the linear-colour-attachment feature) renders a plane
in place in a pass of planes alone, and in a pass that mixes a plane with an attachment that is
not one (another colour, a depth or stencil, a resolve) renders it through an optimal image of
the runtime's with a counted copy into the plane at the pass's end and, where its load action
is Load, a counted copy in at its begin; those copies and that image's memory are recorded as a
known gap), texture buffer formats (ruled 12-02; for each format, does the device serve it
natively for every access a texture buffer makes, as a uniform texel buffer, as a storage texel
buffer, and as a storage write without a format, and, for a texture buffer made with both
shader read and shader write usage, as a storage read without a format? A device that does
makes a texture buffer of it the format's own view; where any of those is missing, that
format's texture buffer of that usage is held as words, an `R32_UINT` view whose texels shaders
convert, one answer per format and usage per device; on a device that holds any format so, a
stage that reaches a texture buffer declares a stage constant, false by default, under which
every word arm is dead code at pipeline creation, and each of its `VkPipeline`s has a words twin
specialized with it true, made in the same make, which a draw or dispatch runs where a texture
buffer held as words is bound at a slot its stage reaches or, for a stage that reaches one
through a handle, while one lives on the device; the twins' second compile and memory, and the
words' cost, 7.3 times the own view's GPU time for an `R8Unorm` texture buffer written on an
RTX 3090, are recorded as a known gap), and Shared
memory's host coherence (decided by the host-coherent flag of the memory type
Shared takes, the first host-visible, host-cached type a buffer can use, a host-coherent one
first: a device whose type has it makes no flush or invalidate call; on a device whose type is
the cached type without coherence, the Shared memory a submission's command buffers and Managed
@@ -100,10 +126,14 @@ order, and a lower one never overrides a higher one.
3. **Native-like speed.** Structure decides speed: driver-owned memory, optimal images in real
layouts, direct addresses (for a compute function's buffer arguments, bound buffers where
rule 2's query takes them), nothing copied that Metal would not copy. Optimal images have two
exceptions. A texture over a Shared buffer: a linear image on that buffer's memory, in the
device's own layout, created so its first use keeps the bytes, with the alignment the guest
reads from Metal's minimum linear texture alignment, and where a format query offers no linear
image for the format and usage, a counted copy at commit. A plane texture of an exported
exceptions. A texture over a buffer, of any storage mode: a linear image on that buffer's
memory (a Managed buffer's device copy, where it has one), in the device's own layout, created
so its first use keeps the bytes, and where that memory is a
host-pointer import on an integrated or CPU device (rule 2's unified memory), whose images
must start undefined, a counted copy pair at the texture's making restores the bytes,
with the alignment the guest reads from Metal's minimum linear texture alignment, and where a
format query offers no linear image for the format and usage, a counted copy at commit. A
plane texture of an exported
surface: a linear image on the surface's own exported memory, at the pitch and plane starts the
surface's export states, and where the device offers no such image or cannot meet the layout
the consumer asked for, the copy form of the same call, counted and recorded as a known gap.
@@ -146,9 +176,13 @@ as a known gap.
- **Structure over names.** Decide lowering from IR structure (types, address spaces, access
chains, AIR's metadata ABI), never from a function, type, variable or shader name. Dispatching on
the stable `air.*` and `llvm.*` intrinsic families is allowed; prefer a structural test when one
exists. A name-keyed branch that passes one shader while failing identically shaped others is a
defect. No behavior keyed to an app, a shader hash or a corpus census.
the stable `air.*` and `llvm.*` intrinsic families is allowed; the same holds for the bodiless
runtime-library routines Metal's compiler links by symbol (the `___metal_*` maths routines and
the `__tensorops_impl_*` family), where the declaration has no body and the symbol is the only
thing that says what the routine is; an unknown member of such a family is a typed refusal.
Prefer a structural test when one exists. A name-keyed branch that passes one shader while
failing identically shaped others is a defect. No behavior keyed to an app, a shader hash or a
corpus census.
- **Honest FALLBACK.** Unsupported input returns a typed `Err` (the command line prints
`FALLBACK`). Never emit wrong-but-valid SPIR-V to silence a gate.
- **Scope.** The runtime has a floor: one Vulkan version plus a fixed extension list
@@ -318,7 +352,14 @@ cargo test --workspace --all-features --doc
clippy (all features, each feature alone, `--cfg m2v_gpu`), Rustdoc, the API reference check
(`scripts/api-docs`), packaging, the suites, doctests, and on Linux clippy of the published
crates and devtools for `x86_64-pc-windows-gnullvm` and `x86_64-pc-windows-msvc`, the device
tests and public case qualification on lavapipe.
tests (the runtime's twice: at lavapipe's own width, and at 128-bit vectors, subgroups of 4, with
a Mesa shader cache of their own) and public case qualification on lavapipe.
- On Linux, CI's steps that execute on a device (the `m2v_cpu_icd` device tests, the conformance
replay and public case qualification) run on lavapipe in the image `scripts/lavapipe-image`
builds from `scripts/lavapipe-image/pin` (the Arch Linux bootstrap tarball's sha256, one Arch
Linux Archive date and each package's exact version), and when the conformance ledger's llvmpipe
rows are re-recorded on another lavapipe, the pin and the ledger's `# llvmpipe:` line move in the
same commit.
When chasing a hang, read the whole nextest output; do not pipe it through `head` or `grep`.
+6 -1
View File
@@ -53,7 +53,7 @@ they bind people too.
cargo fmt --all
cargo clippy --workspace --all-targets --all-features -- -D warnings
RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps
scripts/api-docs # the translator's API reference; fails on a link to a hidden item
scripts/api-docs # the translator's API reference; fails on a link to a hidden item or a job id
cargo nextest run -p metal2vulkan -p metal2vulkan-air -p metal2vulkan-runtime -p metal2vulkan-devtools -p metal2vulkan-harness --all-features
cargo nextest run -p metal2vulkan-validation --all-features
cargo nextest run -p metal2vulkan-conformance --all-features
@@ -68,6 +68,11 @@ limits only with `--cfg m2v_gpu_hazards` too ([docs/VALIDATION.md](docs/VALIDATI
validation layer under `metal2vulkan-runtime`'s device tests"). On a machine that has no layer,
`METAL2VULKAN_TEST_UNVALIDATED=1` runs them without it, and the run says so.
CI runs the device tests, the conformance replay and public case qualification on lavapipe in the
container image `scripts/lavapipe-image` builds from one Arch Linux Archive date, pinned by
`scripts/lavapipe-image/pin`, and re-recording the conformance ledger's llvmpipe rows on another
lavapipe moves that pin and the ledger's `# llvmpipe:` line in the same commit.
To build the command:
```sh
+16 -9
View File
@@ -27,7 +27,9 @@ What the translator promises:
- **Typed refusals.** Input the device cannot run exactly fails with an error that names the Metal
feature and what would make it work. It never returns a module that computes something else.
- **Recorded differences.** Where a pipeline gives a near-equivalent of Metal's answer, its
artifact records a precision note, and the runtime announces it once with a stable code.
artifact records a precision note. The runtime records each state's notes when the state is
made and exposes them, each with a stable code (`PrecisionNote::code`); the caller announces
them.
- **The GPU's native arithmetic.** Where the device has a native form (its maths, rounding,
conversions and sampler), that form gives the answer, its difference from Metal's recorded.
- **Bounded work.** Every compile runs under a deadline, a cancellation token and deterministic
@@ -80,15 +82,20 @@ metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
- `--profile` is required: the crate ships no device description. Any Khronos profiles JSON works;
[`crates/metal2vulkan-validation/profiles/`](crates/metal2vulkan-validation/profiles) has
examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK. A profile compiles under
the runtime's policy (`DevicePolicy::default()`, the identity pointer and handle domains), so a
profile without `bufferDeviceAddress` and `shaderInt64` is refused. `--device FILE` takes its
place with a device description and policy as JSON (`{"description": ..., "policy": ...}`),
which is how a runtime's compile device is reproduced: metal2vulkan-runtime's is the
description restricted to the features it enables, under that policy.
the identity pointer and handle domains, the only form, so a profile without
`bufferDeviceAddress` and `shaderInt64` is refused. `--device FILE` takes its place with a
device description as JSON (`{"description": ...}`), which is how a runtime's compile device is
reproduced: metal2vulkan-runtime's is the description restricted to the features it enables.
- Without `--function` it compiles the library's only kernel or vertex function. A kernel with
`--color-format` compiles as a tile pipeline. A post-tessellation vertex function adds
`.tesc.spv` and `.tese.spv` modules; on a device without `tessellationShader` it answers
`FALLBACK`, naming the feature.
`FALLBACK`, naming the feature. `--tessellation FILE` sets its tessellation state (the JSON form
of `TessellationDescriptor`: its maximum factor, partition mode, factor format, step function,
winding, control-point index type and factor scale, for example
`{"max_tessellation_factor": 64, "partition_mode": "Pow2", "factor_format": "Half",
"factor_step_function": "Constant", "output_winding_order": "CounterClockwise",
"control_point_index_type": "UInt32", "factor_scale_enabled": false}`); without it the pipeline
has no tessellation state of its own, which is Metal's default state.
- A vertex function that returns no value, with no `--fragment`, compiles with rasterization
disabled, the one pipeline Metal makes of it.
- A compile that needs a pipeline input fails naming it and the option that supplies it:
@@ -109,13 +116,13 @@ The flow follows Metal's object lifecycle: describe the device, parse a library,
pipeline, then plan and instantiate each dispatch or draw.
```rust,ignore
use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
use metal2vulkan::device::{Device, DeviceDescription};
use metal2vulkan::library::Library;
use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
use metal2vulkan::Budget;
let description = DeviceDescription::from_khronos_json(&profile_json, None)?;
let device = Device::from_queries(description, DevicePolicy::default())?;
let device = Device::from_queries(description)?;
let library = Library::parse(&metallib_bytes)?;
let kernel = FunctionDescriptor::new(library.function("my_kernel")?);
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel));
+4
View File
@@ -443,6 +443,7 @@ fn bound_global(b: &mut ModuleBuilder, external: bool) -> GlobalId {
constant: true,
init: Some(undef),
externally_initialized: external,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -3237,6 +3238,7 @@ fn fc_global_as(
constant,
init,
externally_initialized,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::External,
@@ -3352,6 +3354,7 @@ fn sampler_global(b: &mut ModuleBuilder, words: &[u64]) -> GlobalId {
constant: true,
init: Some(init),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -4762,6 +4765,7 @@ fn kernel_with_constants(
constant: true,
init: Some(undef),
externally_initialized: true,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -623,8 +623,10 @@ impl<'a> ModuleDecoder<'a> {
let align = align(op(4)?).ok_or_else(|| s.malformed(MODULE_BLOCK, C))?;
let section = self.section(s, C, op(5)?)?;
let opt = |i: usize| s.ops().get(base + i).copied().unwrap_or(0);
// Thread-local storage and comdats are rejected at decode.
if opt(7) != 0 || opt(11) != 0 {
// Thread-local storage is read only in the thread space, where Metal gives each thread
// an object of its own; elsewhere, and comdats, are rejected at decode.
let thread_local = opt(7) != 0;
if (thread_local && space != AddrSpace::Thread) || opt(11) != 0 {
return Err(s.unsupported(Feature::ModuleRecord { code: C }));
}
let global = Global {
@@ -634,6 +636,7 @@ impl<'a> ModuleDecoder<'a> {
constant: flags & 1 != 0,
init: None,
externally_initialized: opt(9) != 0,
thread_local,
linkage,
visibility: visibility(linkage, opt(6)),
unnamed_addr: unnamed_addr(opt(8)),
+76 -2
View File
@@ -547,12 +547,20 @@ fn unknown_and_unsupported_records_are_typed() {
bitcode_kind(&e),
Some(&BitcodeError::UnknownBlock { block: 60 })
);
// A thread-local global.
let e = with_body(|w| w.unabbrev(7, &[0, 1, 0, 2, 0, 0, 0, 0, 0, 1])).unwrap_err();
// A thread-local global outside the thread address space (flags 14: explicit type,
// threadgroup): Metal gives a thread-local global meaning only in the thread space.
let e = with_body(|w| w.unabbrev(7, &[0, 1, 0, 14, 0, 0, 0, 0, 0, 1])).unwrap_err();
assert_eq!(
unsupported_feature(&e),
Some(&Feature::ModuleRecord { code: 7 })
);
// A thread-local global of the thread address space is read: each thread's own object.
let t = with_body(|w| w.unabbrev(7, &[0, 1, 0, 2, 0, 0, 0, 0, 0, 1])).unwrap();
let thread_locals = t.parts.globals.values().filter(|g| g.thread_local);
assert_eq!(
thread_locals.map(|g| g.space).collect::<Vec<_>>(),
[crate::ir::AddrSpace::Thread]
);
// A calling convention other than C or fast.
let e = with_body(|w| w.unabbrev(8, &[1, 1, 4, 9, 1, 0, 0, 0, 0])).unwrap_err();
assert_eq!(
@@ -1711,6 +1719,72 @@ fn a_public_fixture_survives_mutation() {
mutate(stream_of(&bytes));
}
/// Metal's runtime routines are taken by their symbol only on a declaration, which has no body to
/// say what it is: a module that declares `___metal_frexp_float_pthreadint32` calls the math
/// family's `frexp`, and one that defines a function of that name calls its own definition.
#[test]
fn a_defined_function_named_as_a_runtime_routine_is_the_modules_own() {
let Some(tool) = llvm_as() else {
eprintln!("SKIP a_defined_function_named_as_a_runtime_routine_is_the_modules_own: llvm-as not found");
return;
};
let scratch = Scratch::new();
let kernel = "define void @k(ptr addrspace(1) %out) {\n %e = alloca i32\n %r = call float @___metal_frexp_float_pthreadint32(float 1.0, ptr %e)\n store float %r, ptr addrspace(1) %out\n ret void\n}\n";
let decoded = |routine: &str, stem: &str| -> ModuleTables {
let ll = scratch.0.join(format!("{stem}.ll"));
std::fs::write(&ll, format!("{routine}\n{kernel}")).unwrap();
let out = scratch.0.join(format!("{stem}.bc"));
let bytes = assemble(&tool, &[ll.as_os_str()], &out)
.unwrap_or_else(|| panic!("llvm-as rejected the {stem} module"));
decode(stream_of(&bytes)).unwrap_or_else(|e| panic!("{stem}: {e}"))
};
let callee = |t: &ModuleTables| -> crate::ir::Callee {
let p = &t.parts;
let k = p
.funcs
.values()
.find(|f| p.symbols.get(f.name) == Some(&b"k"[..]))
.expect("the kernel");
let body = k.body.as_ref().expect("the kernel's body");
body.insts
.values()
.find_map(|i| match &i.kind {
crate::ir::InstKind::Call(c) => Some(c.callee.clone()),
_ => None,
})
.expect("the kernel's call")
};
let declared = decoded(
"declare float @___metal_frexp_float_pthreadint32(float, ptr)",
"declared",
);
let c = callee(&declared);
assert!(
matches!(
&c,
crate::ir::Callee::Air {
op: crate::intrinsics::AirIntrinsic::Math(m),
..
} if m.f == crate::intrinsics::MathFn::Frexp
),
"{c:?}"
);
let defined = decoded(
"define float @___metal_frexp_float_pthreadint32(float %x, ptr %e) {\n store i32 9, ptr %e\n ret float 2.5\n}",
"defined",
);
let c = callee(&defined);
let crate::ir::Callee::Direct(f) = c else {
panic!("{c:?}");
};
let f = defined.parts.funcs.get(f).expect("the callee");
assert!(f.body.is_some(), "the callee is the module's definition");
assert_eq!(
defined.parts.symbols.get(f.name),
Some(&b"___metal_frexp_float_pthreadint32"[..])
);
}
/// Whether `xcrun metal-as` exists. Tests that need it skip visibly when it does not, and fail
/// when it exists but rejects a committed fixture.
fn have_metal_as() -> bool {
@@ -108,6 +108,7 @@ fn variable(m: &mut ModuleBuilder, name: &str, ty: TypeId, init: Option<ConstId>
constant: init.is_some(),
init,
externally_initialized: false,
thread_local: false,
linkage: Linkage::External,
visibility: Visibility::Default,
unnamed_addr: Default::default(),
@@ -183,6 +184,7 @@ fn flat_table(m: &mut ModuleBuilder, imports: &[Item]) {
constant: false,
init: Some(init),
externally_initialized: false,
thread_local: false,
linkage: Linkage::External,
visibility: Visibility::Hidden,
unnamed_addr: Default::default(),
@@ -5,13 +5,13 @@
//! constant-space global, externally initialized and `undef`, makes each read of it (`&p`
//! included) a load of the pointer it holds, and lists it in `!air.global_bindings`
//! ([`GlobalBinding`]). Metal fills it from the executing stage's own argument table: measured on
//! an Apple M3 Max under macOS 27.0.1 (m3-max-70268), a kernel's global reads and writes the buffer
//! bound at its index, a vertex and a fragment function that read one global each read their own
//! stage's buffer there, and two globals of one type at one index, or a global and a parameter of
//! one type, read the one buffer bound there. So `expand` makes each load of a bound buffer's
//! pointer a read of a parameter of the entry: its own parameter of the binding's role and type
//! where it takes one, else one `expand` adds, shared by the bindings of one role and type.
//! Lowering then binds an added parameter where a `[[buffer(n)]]` parameter binds.
//! an Apple M3 Max under macOS 27.0.1, a kernel's global reads and writes the buffer bound at its
//! index, a vertex and a fragment function that read one global each read their own stage's buffer
//! there, and two globals of one type at one index, or a global and a parameter of one type, read
//! the one buffer bound there. So `expand` makes each load of a bound buffer's pointer a read of a
//! parameter of the entry: its own parameter of the binding's role and type where it takes one,
//! else one `expand` adds, shared by the bindings of one role and type. Lowering then binds an
//! added parameter where a `[[buffer(n)]]` parameter binds.
//!
//! Three shapes stay refused, each where it is found: an added parameter whose slot another
//! parameter of the entry binds ([`shared_slot`]), and, through what pruning keeps, any read of a
@@ -170,6 +170,7 @@ fn callee(name: &str, calls: &[&str]) -> LinkedModule {
constant: true,
init: Some(init),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -529,6 +530,7 @@ fn constant_callee() -> LinkedCode {
constant: false,
init: Some(undef),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
+29 -50
View File
@@ -293,8 +293,8 @@ pub struct Entry {
/// words: `ep` states each as a read-only device `Buffer`, and the interface says the slot
/// holds a table.
pub function_tables: BTreeSet<u32>,
/// The barriers that make the order of a simdgroup's lockstep explicit: empty from
/// canonicalization; `lower::simd::lockstep` fills it when it inserts them.
/// Whether the body holds a pair only a simdgroup's lockstep orders: unset from
/// canonicalization; `lower::simd::lockstep` sets it.
pub lockstep: Lockstep,
/// The call stack of the entry's recursion through visible functions: `None` when the entry has
/// none.
@@ -320,58 +320,19 @@ pub struct CallStack {
pub depth: u32,
}
/// The threadgroup and simdgroup barriers `lower::simd::lockstep` inserted into an entry's body.
/// What `lower::simd::lockstep` found in an entry's body.
///
/// Apple GPUs run a simdgroup's 32 threads in lockstep, so two conflicting threadgroup accesses
/// of different threads of one simdgroup between two barriers run in program order there; Vulkan
/// orders nothing between barriers. Each inserted barrier orders such a pair where the program
/// left it to lockstep.
/// Apple GPUs run a simdgroup's 32 threads in lockstep, so two conflicting threadgroup or device
/// accesses of different threads of one simdgroup between two barriers run in program order
/// there; Vulkan orders nothing between barriers, and documented Metal calls such a pair a data
/// race. The pass orders no pair: it finds them, and leaves them as the program wrote them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Lockstep {
/// The inserted barrier calls, sorted.
pub barriers: Vec<crate::ir::InstId>,
/// Some inserted simdgroup barrier stands where the lanes of a subgroup are not known to
/// reach it together, so it orders its pair only on emulated simdgroups, whose predicated
/// walk takes every thread of the workgroup through it: the kernel takes the `Emulated` tier.
/// Never set where a subgroup barrier in divergent flow orders the threads that run it together
/// (maximal reconvergence on 32-lane subgroups).
pub emulated: bool,
/// Every inserted simdgroup barrier orders only pairs whose threads meet where a simdgroup
/// spans two rows of its threadgroup (two of its threads then share their position's `x`, or
/// hold different `y`s or `z`s): in a threadgroup whose simdgroups each lie within one row (a
/// single row, or rows of a multiple of 32 threads) no pair a simdgroup barrier orders
/// conflicts. The inserted threadgroup barriers may order pairs that meet there too; a
/// threadgroup barrier stands where the whole threadgroup runs together, orders every pair a
/// simdgroup barrier at its place would, and needs no subgroup size, so a pipeline for such
/// threadgroups keeps them and leaves out only the simdgroup barriers, and with them the
/// subgroup size they pinned: an exact removal. Decided where a subgroup barrier keeps a
/// 32-lane tier (maximal reconvergence on 32-lane subgroups); `false` elsewhere and where no
/// barrier is inserted.
pub rows: bool,
/// The inserted threadgroup barriers that order only pairs whose threads meet where a
/// simdgroup spans two rows of its threadgroup, sorted: each runs only in a threadgroup whose
/// simdgroups may span two rows (more than one row, of a width not a multiple of 32), and in
/// any other no pair it orders meets.
pub across_rows: Vec<crate::ir::InstId>,
/// The kernel holds such a pair and no barrier was inserted for it: under a profile that
/// orders none (the identity domains), its pairs are found and left as the program wrote
/// them, and the kernel records that its answer there is the device's order's.
/// The kernel holds such a pair: its answer there is the device's order's, which the kernel
/// records.
pub unordered: bool,
}
impl Lockstep {
/// Whether instruction `i` is an inserted barrier.
pub fn inserted(&self, i: crate::ir::InstId) -> bool {
self.barriers.binary_search(&i).is_ok()
}
/// Whether instruction `i` is an inserted barrier that orders only pairs meeting across rows
/// (one of [`across_rows`](Self::across_rows)).
pub fn orders_across_rows(&self, i: crate::ir::InstId) -> bool {
self.across_rows.binary_search(&i).is_ok()
}
}
impl Entry {
/// Whether the entry may encode, reset or copy indirect commands: `false` only where its
/// metadata names no indirect command buffer it takes and its body proves it touches none.
@@ -806,7 +767,8 @@ pub fn specialize_dynamic(
// The AIR 2.7 simdgroup-matrix block loads and stores in their AIR 2.8 form.
let body = legacy_matrix::expand(body, &mut parts, m)?;
// Metal runtime routines: each `frexp` and `ilogb` call becomes the routine's measured answer
// in plain AIR.
// in plain AIR, each OpenCL C `mad` call its multiply and addition, and each `mul24` and
// `mad24` call the 32-bit product of its operands' low 24 bits (and the addition).
let body = routine::expand(body, &mut parts, m)?;
// Aggregate loads and stores of buffer and threadgroup memory as their members' accesses.
let body = aggregates::expand(body, &mut parts, func, m)?;
@@ -1488,6 +1450,10 @@ fn post_check(
.and_then(|f| parts.symbols.get(f.name))
.unwrap_or(b"?")
};
let section = |f: FuncId| match parts.funcs.get(f).and_then(|f| f.section) {
Some(crate::ir::Section::Other(s)) => parts.symbols.get(s),
_ => None,
};
let diag = |bytes: &[u8]| DiagName::new(String::from_utf8_lossy(bytes));
// A call to the declaration `f` this module does not define.
let undefined =
@@ -1503,9 +1469,22 @@ fn post_check(
Some(Stub::Resolved { .. }) => {
Err(invariant("a call to a resolved stub survived linking"))
}
// A dynamic-library import, or a declaration no library can define.
// A dynamic-library import, or a declaration no library can define: an
// unknown member of a family of Metal's runtime-library routines, which
// Metal supplies, is refused as its family, and any other needs linking.
None => match stubs.import_refusal(Item::Func(f), symbol(f)) {
Some(e) => Err(e),
None if intrinsics::is_routine_family(symbol(f)) => {
let kind =
InputErrorKind::Intrinsic(IntrinsicError::UnknownIntrinsic {
name: diag(symbol(f)),
});
Err(InputError::new(kind, at.clone()).into())
}
None if crate::tensor_ops::in_family(symbol(f), section(f)) => {
Ok(Unsupported::not_implemented(Feature::Tensors)
.naming(diag(symbol(f))))
}
None => Ok(Unsupported::not_implemented(Feature::Linking)
.naming(diag(symbol(f)))),
},
+131 -17
View File
@@ -1,4 +1,4 @@
//! Metal runtime routines as plain AIR.
//! Metal runtime routines, OpenCL C's `mad`, and `mul24` and `mad24`, as plain AIR.
//!
//! Apple's compiler emits MSL's `frexp` and `ilogb` as calls to routines its backend defines at
//! pipeline creation, `___metal_frexp_<T>_pthread<I>(T x, thread I *e)` and
@@ -30,10 +30,25 @@
//!
//! Runtime-compiled source keeps `float` denormals (`frexp(0x1p-149) = (0.5, -148)`): what it
//! compiles to is not this routine, which AIR the translator receives calls by name.
//!
//! **OpenCL C's `mad`.** [`expand`] also replaces each `air.mad` call ([`MathFn::Mad`]) by its
//! product, an `fmul` of `a` and `b`, and the `fadd` of that product and `c`, in `T`'s shape and
//! with no fast-math flags, whatever the call's own: each is rounded on its own and neither is
//! fused, as the M3 Max answers `mad` (`intrinsics::math`'s module doc). Lowering takes them as it
//! takes any such pair.
//!
//! **`mul24` and `mad24`.** [`expand`] replaces each `air.mul24` and `air.mad24` call
//! ([`MathFn::Mul24`], [`MathFn::Mad24`]) by the 32-bit `mul` of its operands' low 24 bits, each
//! zero-extended (`and` with `0xffffff`) for `u` or sign-extended (`shl` and then `ashr` by 8) for
//! `s`, and for `mad24` the 32-bit `add` of that product and `c`, in `T`'s shape, each wrapping (no
//! `nsw` or `nuw`). That is the specification's wording, "only the low 24 bits perform the
//! multiplication" (MSL section 6.4, Table 6.2), and the M3 Max's answer for every operand
//! measured, inside the range where the specification defines the product and outside it
//! (`intrinsics::math`'s module doc).
use crate::budget::Meter;
use crate::error::Error;
use crate::intrinsics::{AirIntrinsic, Elem, Math, MathFn};
use crate::intrinsics::{AirIntrinsic, Elem, Math, MathFn, Sign};
use crate::ir::{
BinOp, Block, Body, Call, Callee, CastOp, Const, FastMath, Idx, Inst, InstId, InstKind,
IntFlags, IntPredicate, ModuleParts, Type, TypeId, Value,
@@ -41,10 +56,36 @@ use crate::ir::{
use super::rewrite::invariant;
/// What a call [`expand`] replaces computes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Frexp,
Ilogb,
Mad,
/// `mul24`, `signed` for `s`.
Mul24 {
signed: bool,
},
/// `mad24`, `signed` for `s`.
Mad24 {
signed: bool,
},
}
impl Kind {
/// The call's operand count.
fn arity(self) -> usize {
match self {
Kind::Frexp | Kind::Ilogb | Kind::Mul24 { .. } => 2,
Kind::Mad | Kind::Mad24 { .. } => 3,
}
}
}
/// The routine a call is, and its value type's lanes and element.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Routine {
frexp: bool,
kind: Kind,
half: bool,
lanes: u32,
}
@@ -61,19 +102,28 @@ fn routine(kind: &InstKind) -> Option<(Routine, &Call)> {
else {
return None;
};
let frexp = match f {
MathFn::Frexp => true,
MathFn::Ilogb => false,
let kind = match f {
MathFn::Frexp => Kind::Frexp,
MathFn::Ilogb => Kind::Ilogb,
MathFn::Mad => Kind::Mad,
MathFn::Mul24(s) => Kind::Mul24 {
signed: s == Sign::Signed,
},
MathFn::Mad24(s) => Kind::Mad24 {
signed: s == Sign::Signed,
},
_ => return None,
};
let half = match ty.elem {
Elem::F16 => true,
Elem::F32 => false,
let half = match (kind, ty.elem) {
(Kind::Mul24 { .. } | Kind::Mad24 { .. }, Elem::I32) => false,
(Kind::Mul24 { .. } | Kind::Mad24 { .. }, _) => return None,
(_, Elem::F16) => true,
(_, Elem::F32) => false,
_ => return None,
};
Some((
Routine {
frexp,
kind,
half,
lanes: ty.lanes,
},
@@ -267,12 +317,72 @@ impl Sink<'_> {
Ok(())
}
/// `mad(a, b, c)`: the product, then the sum, each with no fast-math flags; the last
/// instruction is the sum.
fn mad(&mut self, r: Routine, [a, b, c]: [Value; 3], m: &mut Meter) -> Result<(), Error> {
let ty = self.shaped(if r.half { Type::Half } else { Type::Float }, m)?;
let product = self.push(
ty,
InstKind::BinOp {
op: BinOp::FMul,
flags: IntFlags::NONE,
fmf: FastMath::NONE,
a,
b,
},
m,
)?;
self.push(
ty,
InstKind::BinOp {
op: BinOp::FAdd,
flags: IntFlags::NONE,
fmf: FastMath::NONE,
a: product,
b: c,
},
m,
)?;
Ok(())
}
/// `x`'s low 24 bits as an `i32`: zero-extended, or sign-extended where `signed`.
fn low24(&mut self, x: Value, signed: bool, m: &mut Meter) -> Result<Value, Error> {
if !signed {
return self.bin_k(BinOp::And, x, 0x00ff_ffff, m);
}
let high = self.bin_k(BinOp::Shl, x, 8, m)?;
self.bin_k(BinOp::AShr, high, 8, m)
}
/// `mul24(a, b)`, and `mad24(a, b, c)` where `c` is given: the 32-bit product of the
/// operands' low 24 bits, then its 32-bit sum with `c`, each wrapping; the last instruction is
/// the result (the module docs).
fn int24(
&mut self,
signed: bool,
[a, b]: [Value; 2],
c: Option<Value>,
m: &mut Meter,
) -> Result<(), Error> {
let a = self.low24(a, signed, m)?;
let b = self.low24(b, signed, m)?;
let product = self.bin(BinOp::Mul, a, b, m)?;
if let Some(c) = c {
self.bin(BinOp::Add, product, c, m)?;
}
Ok(())
}
/// The instructions of call `r` with operands `args`; the last is the call's result.
fn emit(&mut self, r: Routine, args: &[Value], m: &mut Meter) -> Result<(), Error> {
match (r.frexp, args) {
(true, [x, p]) => self.frexp(r, *x, *p, m),
(false, [x, _mode]) => self.ilogb(r, *x, m),
_ => Err(invariant("a runtime routine's call without its operands")),
match (r.kind, args) {
(Kind::Frexp, [x, p]) => self.frexp(r, *x, *p, m),
(Kind::Ilogb, [x, _mode]) => self.ilogb(r, *x, m),
(Kind::Mad, [a, b, c]) => self.mad(r, [*a, *b, *c], m),
(Kind::Mul24 { signed }, [a, b]) => self.int24(signed, [*a, *b], None, m),
(Kind::Mad24 { signed }, [a, b, c]) => self.int24(signed, [*a, *b], Some(*c), m),
_ => Err(invariant("a replaced call without its operands")),
}
}
}
@@ -285,14 +395,18 @@ fn routine_len(r: Routine, parts: &mut ModuleParts, m: &mut Meter) -> Result<u32
parts,
lanes: r.lanes,
};
let any = Value::Inst(InstId::new(0));
s.emit(r, &[any, any], m)?;
let any = [Value::Inst(InstId::new(0)); 3];
let args = any
.get(..r.kind.arity())
.ok_or_else(|| invariant("a routine of more operands than three"))?;
s.emit(r, args, m)?;
let len = scratch.insts.len();
scratch.release(m);
u32::try_from(len).map_err(|_| invariant("routine length"))
}
/// Replace every `frexp` and `ilogb` routine call of `body` by its answer (the module docs).
/// Replace every `frexp` and `ilogb` routine call and every `mad`, `mul24` and `mad24` call of
/// `body` by its answer (the module docs).
pub(super) fn expand(body: Body, parts: &mut ModuleParts, m: &mut Meter) -> Result<Body, Error> {
if !body.insts.iter().any(|(_, i)| routine(&i.kind).is_some()) {
return Ok(body);
@@ -217,6 +217,7 @@ impl Fixture {
constant: true,
init: Some(undef),
externally_initialized: true,
thread_local: false,
linkage: Linkage::LinkOnceOdr,
align: None,
section: Some(Section::FcInitializer),
@@ -242,6 +243,7 @@ impl Fixture {
constant: true,
init: Some(two),
externally_initialized: false,
thread_local: false,
linkage: Linkage::Internal,
align: None,
section: None,
+72 -1
View File
@@ -111,6 +111,7 @@ pub(super) fn fc_global(m: &mut ModuleBuilder, name: &str, ty: TypeId) -> Global
constant: true,
init: Some(undef),
externally_initialized: true,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::LinkOnceOdr,
@@ -1855,6 +1856,7 @@ fn static_initializers_run_in_global_ctors_order() {
constant: false,
init: Some(list),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Appending,
@@ -2628,6 +2630,7 @@ fn constant_global(
constant: true,
init: Some(init),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -3476,7 +3479,8 @@ fn surviving_calls_are_refused_by_family_naming_the_callee() {
assert_eq!(u.location, Some(at.clone()));
assert_eq!(u.symbol, Some(DiagName::new("air.some_future_op")));
// An undefined external function (the shape of the tensor-ops library calls) needs linking.
// An undefined external function needs linking, one named as the tensor-ops library's included
// where it is not in that library's section, `air.externally_defined`.
let u = refusal(specialize_call(|m, fty| {
Callee::Direct(m.declare("__tensorops_impl_matmul2d_op_cooperative_tensor_init", fty))
}));
@@ -3502,6 +3506,73 @@ fn surviving_calls_are_refused_by_family_naming_the_callee() {
assert_eq!(u.symbol, None);
}
/// Marks `d` as declared in `air.externally_defined`, the tensor-ops library's section.
fn externally_defined(m: &mut ModuleBuilder, d: FuncId) {
let s = m.sym("air.externally_defined");
m.func_mut(d).unwrap().section = Some(Section::Other(s));
}
/// A body-less declaration of a family of Metal's runtime-library routines that nothing models is
/// refused at its call as its family, naming it: a `___metal_*` routine the math family does not
/// model is an unknown intrinsic, and a `__tensorops_impl_*` function in `air.externally_defined`
/// outside the `matmul2d` ABI is tensors, as an unmodeled function of that ABI is (the `matmul2d`
/// lowering's refusal). Outside the section a `__tensorops_impl_*` name is no member, and needs
/// linking like any other undefined function.
#[test]
fn an_unknown_runtime_library_routine_is_refused_as_its_family() {
let at = Location::function(DiagName::new("k"), Some(0), Some(0));
let declared = |name: &'static str, external: bool| {
refusal(specialize_call(move |m, fty| {
let d = m.declare(name, fty);
if external {
externally_defined(m, d);
}
Callee::Direct(d)
}))
};
for (name, external, feature) in [
("___metal_ldexp_float", false, Feature::UnknownIntrinsic),
(
"___metal_frexp_float_pthreadv2int32",
false,
Feature::UnknownIntrinsic,
),
("__tensorops_impl_conv2d_op_run", true, Feature::Tensors),
("__tensorops_impl_conv2d_op_run", false, Feature::Linking),
] {
let u = declared(name, external);
assert_eq!(u.feature, feature, "{name} external {external}");
assert_eq!(u.location, Some(at.clone()), "{name}");
assert_eq!(u.symbol, Some(DiagName::new(name)), "{name}");
}
let u = declared("__tensorops_impl_matmul2d_op_cooperative_tensor_copy", true);
assert_eq!(u.feature, Feature::Tensors);
assert_eq!(u.location, Some(at));
}
/// A function of the tensor-ops library is taken by its symbol only where the module declares it
/// without a body: one the module defines under the same name, in the same section, is the
/// module's own and is inlined like any other, where the body-less declaration is the `matmul2d`
/// ABI's (here refused as tensors, called without its operands).
#[test]
fn a_defined_function_named_as_a_tensor_op_is_the_modules_own() {
let name = "__tensorops_impl_matmul2d_op_cooperative_tensor_init";
let u = refusal(specialize_call(|m, fty| {
let d = m.declare(name, fty);
externally_defined(m, d);
Callee::Direct(d)
}));
assert_eq!(u.feature, Feature::Tensors);
let defined = specialize_call(|m, fty| {
let mut f = m.define(name, fty);
f.ret(None);
let d = f.finish();
externally_defined(m, d);
Callee::Direct(d)
});
assert!(defined.is_ok(), "{:?}", defined.err());
}
/// The decoder keeps a call through a function's own constant address indirect when the call's
/// function type is not the function's. Such a call is classified by that function, not as a
/// dynamic call: a defined function whose parameters cannot receive the call's arguments is invalid
@@ -69,6 +69,7 @@ fn moved(how: Move) -> Entry {
constant: false,
init: Some(tg_undef),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -45,6 +45,7 @@ fn configured(
constant: false,
init: Some(zero),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -20,6 +20,7 @@ fn bound_global(m: &mut ModuleBuilder, name: &str) -> GlobalId {
constant: true,
init: Some(undef),
externally_initialized: true,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -38,6 +38,7 @@ fn table_kernel(elements: &[Element]) -> Result<Entry, Error> {
constant: true,
init: Some(init),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
@@ -71,6 +72,7 @@ fn table_kernel(elements: &[Element]) -> Result<Entry, Error> {
constant: true,
init: Some(init),
externally_initialized: false,
thread_local: false,
visibility: Default::default(),
unnamed_addr: Default::default(),
linkage: Linkage::Internal,
+15 -3
View File
@@ -1101,16 +1101,28 @@ fn committed_air_fixtures_parse_and_link() {
return;
}
let out = std::env::temp_dir().join(format!("m2v-container-{}.metallib", std::process::id()));
let status = std::process::Command::new("xcrun")
let linked = std::process::Command::new("xcrun")
.args(["-sdk", "macosx", "metallib"])
.args(&airs)
.arg("-o")
.arg(&out)
.status()
.output()
.unwrap();
let bytes = std::fs::read(&out);
let _ = std::fs::remove_file(&out);
assert!(status.success());
let stderr = String::from_utf8_lossy(&linked.stderr);
// The fixtures are compiled by the SDK `scripts/regen-air-fixtures` ran on; an older SDK's
// linker refuses their newer AIR version ("air version set to 2.9.0 ..., but expecting 2.8").
// That linker cannot link them at all, so the half that compares with Apple's link is skipped
// there; the parse half above has run.
if !linked.status.success()
&& stderr.contains("air version set to")
&& stderr.contains("but expecting")
{
eprintln!("SKIPPED metallib half: this SDK's metallib links an older AIR version than the fixtures': {}", stderr.trim());
return;
}
assert!(linked.status.success(), "xcrun metallib: {stderr}");
let bytes = bytes.unwrap();
let lib = metallib(&bytes);
assert_eq!(lib.functions.len(), entries);
+6 -6
View File
@@ -833,20 +833,20 @@ pub enum Feature {
/// A texture, a sampler or threadgroup memory bound at program scope (MSL 3.2's
/// `!air.global_bindings`), one or an array, that the entry reads: only a bound buffer becomes
/// a parameter. Metal takes each: an Apple M3 Max under macOS 27.0.1 runs kernels that read a
/// bound texture and sampler, a bound sampler array and bound threadgroup memory (m3-max-70306).
/// Basis: metal-takes (an Apple M3 Max under macOS 27.0.1, potluck job m3-max-70306)
/// bound texture and sampler, a bound sampler array and bound threadgroup memory.
/// Basis: metal-takes (an Apple M3 Max under macOS 27.0.1)
ProgramScopeResource,
/// A buffer bound at program scope at a slot that a parameter of the entry, or another binding
/// it reads, binds with another role or type. Metal takes it: on an Apple M3 Max under macOS
/// 27.0.1, a `device float *` and a `constant uint *` bound at one index read the one buffer
/// bound there (m3-max-70268).
/// Basis: metal-takes (an Apple M3 Max under macOS 27.0.1, potluck job m3-max-70268)
/// bound there.
/// Basis: metal-takes (an Apple M3 Max under macOS 27.0.1)
ProgramScopeSharedSlot,
/// A program-scope binding in the module of a function a pipeline links (a visible function,
/// or a dynamic library's). Metal takes it: on an Apple M3 Max under macOS 27.0.1, a kernel's
/// pipeline links another library's visible function, which reads the buffer the kernel's
/// stage binds at the global's index (m3-max-70306).
/// Basis: metal-takes (an Apple M3 Max under macOS 27.0.1, potluck job m3-max-70306)
/// stage binds at the global's index.
/// Basis: metal-takes (an Apple M3 Max under macOS 27.0.1)
ProgramScopeLinked,
/// A read of a buffer bound at program scope other than a load of the pointer its global
/// holds. `xcrun metal` 32023.922 writes every read so, `&p` included, so only other AIR reaches
@@ -789,6 +789,11 @@ const OBSERVED: &[(&str, &str)] = &[
("air.native_exp10.v3f32", "v3f32 (v3f32)"),
("air.half_cos.v4f32", "v4f32 (v4f32)"),
("air.half_powr.v4f32", "v4f32 (v4f32, v4f32)"),
// OpenCL C's `mad(a, b, c)` of `float`, `float4` and `half` (Apple's OpenCL compiler in Metal's
// OpenCL mode, macOS 27.0.1, AIR 2.9).
("air.mad.f32", "f32 (f32, f32, f32)"),
("air.mad.v4f32", "v4f32 (v4f32, v4f32, v4f32)"),
("air.mad.f16", "f16 (f16, f16, f16)"),
// OpenCL C's vector data functions (the same compilers).
("air.vload.global.v3i32", "v3i32 (i64, p1)"),
("air.vload.constant.v16i8", "v16i8 (i64, p2)"),
+61 -4
View File
@@ -1,5 +1,5 @@
//! The math family: `air.[fast_]<function>[.<s|u>].<type>`, and OpenCL C's
//! `air.{native,half}_<function>.<type>`.
//! `air.{native,half}_<function>.<type>` and `air.mad.<type>`.
//!
//! One declarative table ([`TABLE`]) lists every function stem with its domain and operand
//! shape. A float function takes an optional `fast_` prefix and no sign token; a sign-sensitive
@@ -15,6 +15,27 @@
//! 27.0.1) and `0x1.4p+3` on a Radeon Pro 5300M (macOS 26.7.1). Each reads as the function at
//! [`Precision::Fast`], the device's fast form.
//!
//! It spells OpenCL C's `mad(a, b, c)` `air.mad.<type>`, `T (T, T, T)`, for the types
//! [`MAD_TYPES`] lists: `float`, `float4` and `half`, measured over our own kernels in Metal's
//! OpenCL mode (`newLibraryWithSource` with `sourceLanguage` 1, macOS 27.0.1, AIR 2.9; `fma` is
//! `air.fma`). OpenCL C leaves how `mad` rounds its product to the implementation; the M3 Max's GPU
//! rounds the product and then the sum, run through the OpenCL framework (macOS 27.0.1): at
//! `a = b = 1 + 2^-12`, `c = -(1 + 2^-11)` `mad` answers 0 where `fma` answers `2^-24`, on `float`
//! and on each lane of `float4`, and of `half` at `a = b = 1 + 2^-6`, `c = -(1 + 2^-5)` 0 where
//! `fma` answers `2^-12`. It reads as [`MathFn::Mad`], that multiply and addition.
//!
//! MSL's and OpenCL C's `mul24` and `mad24` of a 32-bit `int` or `uint` (MSL section 6.4,
//! Table 6.2) are `air.mul24.<s|u>.<T>(T, T)` and `air.mad24.<s|u>.<T>(T, T, T)`, `T` `i32` or a
//! vector of it; Apple's compiler spells MSL's at 1 to 4 lanes (MSL on macOS reserves the 8- and
//! 16-lane types). The specification multiplies "only the low 24 bits" of the two 32-bit operands
//! and returns "the 32-bit integer result", and calls the product implementation-defined for
//! operands outside `[0, 2^24 - 1]` unsigned and `[-2^23, 2^23 - 1]` signed. The M3 Max (macOS
//! 27.0.1) answers outside that range too as the product of the operands' low 24 bits, zero-extended
//! for `u` and sign-extended for `s`, the 32-bit sum with `z` for `mad24` (validation cases
//! `int24-products-in-range` and `int24-products-outside-24-bits`). They read as [`MathFn::Mul24`]
//! and [`MathFn::Mad24`], which canonicalization replaces by that product in plain AIR. A width
//! other than 32 bits stays undecoded.
//!
//! Two functions reach AIR as calls to Metal runtime routines instead, declarations Apple's
//! compiler emits and its backend defines at pipeline creation: `frexp` as
//! `___metal_frexp_<T>_pthread<I>(T, thread I*)` (AIR 2.9 spells the same operation
@@ -48,6 +69,17 @@ pub(super) const OPENCL_STEMS: &[&str] = &[
"cos", "exp", "exp10", "exp2", "log", "log10", "log2", "powr", "rsqrt", "sin", "sqrt", "tan",
];
/// The types of OpenCL C's `mad` that Apple's OpenCL compiler is measured to spell, as
/// `air.mad.<type>`: `float`, `float4` and `half` (module doc). Any other type stays undecoded.
pub(super) const MAD_TYPES: &[NumTy] = &[
NumTy::scalar(Elem::F32),
NumTy {
elem: Elem::F32,
lanes: 4,
},
NumTy::scalar(Elem::F16),
];
/// A math function. Integer functions whose result depends on signedness carry the [`Sign`] the
/// name spells; `Clz`/`Ctz` carry their `is_zero_undef` immediate.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -137,6 +169,11 @@ pub enum MathFn {
// Float, three operands.
/// `air.fma`: `a * b + c`, rounded once.
Fma,
/// `air.mad`: OpenCL C's `mad(a, b, c)`, `a * b + c` rounded twice, the product and then the
/// sum, as the M3 Max answers it; spelled for `float`, `float4` and `half` alone, as Apple's
/// OpenCL compiler is measured to spell it. Canonicalization replaces each call by that
/// multiply and addition in plain AIR.
Mad,
/// `air.mix`: `x + (y - x) * a`.
Mix,
/// `air.clamp` with a float type: `x` clamped to `[min, max]`.
@@ -181,6 +218,11 @@ pub enum MathFn {
MadHi(Sign),
/// `air.mad_sat.<s|u>`: `a * b + c`, saturated.
MadSat(Sign),
/// `air.mul24.<s|u>` of `i32` lanes: the 32-bit product of the operands' low 24 bits,
/// zero-extended (`u`) or sign-extended (`s`) (module doc).
Mul24(Sign),
/// `air.mad24.<s|u>` of `i32` lanes: `mul24(a, b) + c` in 32 bits (module doc).
Mad24(Sign),
/// `air.add_sat.<s|u>`: `x + y`, saturated.
AddSat(Sign),
/// `air.sub_sat.<s|u>`: `x - y`, saturated.
@@ -332,6 +374,8 @@ pub(super) const TABLE: &[(&str, Domain, Shape)] = {
("mul_hi", S(M::MulHi), Same(2)),
("mad_hi", S(M::MadHi), Same(3)),
("mad_sat", S(M::MadSat), Same(3)),
("mul24", S(M::Mul24), Same(2)),
("mad24", S(M::Mad24), Same(3)),
("add_sat", S(M::AddSat), Same(2)),
("sub_sat", S(M::SubSat), Same(2)),
("hadd", S(M::HAdd), Same(2)),
@@ -348,10 +392,19 @@ pub(super) const TABLE: &[(&str, Domain, Shape)] = {
};
impl Math {
/// Parse the part of a name after `air.`: `[fast_]stem.[s|u.]type`, or
/// `{native,half}_stem.type` of a stem [`OPENCL_STEMS`] lists and a `float` type. `None` is not
/// a math name (another family's, or an unknown one).
/// Parse the part of a name after `air.`: `[fast_]stem.[s|u.]type`,
/// `{native,half}_stem.type` of a stem [`OPENCL_STEMS`] lists and a `float` type, or
/// `mad.type` of a type [`MAD_TYPES`] lists. `None` is not a math name (another family's, or an
/// unknown one).
pub(super) fn parse(rest: &str) -> Option<Math> {
if let Some(ty) = rest.strip_prefix("mad.") {
let ty = NumTy::parse(ty)?;
return MAD_TYPES.contains(&ty).then_some(Math {
f: MathFn::Mad,
precision: Precision::Precise,
ty,
});
}
let opencl = ["native_", "half_"]
.iter()
.find_map(|p| rest.strip_prefix(p));
@@ -399,6 +452,9 @@ impl Math {
if f == MathFn::Dot && !ty.is_vector() {
return None;
}
if matches!(f, MathFn::Mul24(_) | MathFn::Mad24(_)) && ty.elem != Elem::I32 {
return None;
}
Some(Math { f, precision, ty })
}
@@ -455,6 +511,7 @@ impl Math {
match self.f {
MathFn::Frexp => return Shape::Frexp,
MathFn::Ilogb => return Shape::Ilogb,
MathFn::Mad => return Shape::Same(3),
_ => {}
}
TABLE
+12 -1
View File
@@ -418,13 +418,24 @@ pub enum DeclClass {
Mismatch,
}
/// The symbol prefix of Metal's runtime routines: functions Metal's compiler declares without a
/// body and Metal supplies, so the symbol is all that says which routine one is.
const ROUTINE_PREFIX: &[u8] = b"___metal_";
/// The Metal runtime routine a declaration named `name` is, when the math family models it:
/// `___metal_frexp_*` or `___metal_ilogb_*`.
fn routine(name: &[u8]) -> Option<Math> {
let rest = name.strip_prefix(b"___metal_")?;
let rest = name.strip_prefix(ROUTINE_PREFIX)?;
Math::parse_routine(std::str::from_utf8(rest).ok()?)
}
/// Whether a declaration named `name` is of the family of Metal's runtime routines, modeled or
/// not. A call that survives to a body-less one the math family does not model is an unknown
/// intrinsic: Metal defines it, and nothing here says what it does.
pub(crate) fn is_routine_family(name: &[u8]) -> bool {
name.starts_with(ROUTINE_PREFIX)
}
/// Whether a declaration named `name` is an intrinsic: its name has the `air.` or the `llvm.`
/// prefix of the stable ABI, or it is a Metal runtime routine the math family models (`frexp`,
/// `ilogb`). Any other declaration is an ordinary function.
@@ -159,6 +159,11 @@ fn every_math_entry_decodes_and_checks() {
if f == MathFn::Dot && !ty.is_vector() {
continue;
}
// `mul24` and `mad24` are of 32-bit lanes alone
// (`mul24_and_mad24_decode_on_32_bit_lanes_alone`).
if matches!(f, MathFn::Mul24(_) | MathFn::Mad24(_)) && ty.elem != Elem::I32 {
continue;
}
let name = format!("{prefix}.{}", token(ty));
let AirIntrinsic::Math(m) = air(&name) else {
panic!("{name}");
@@ -272,6 +277,11 @@ fn math_conversion_and_atomic_families_decode() {
"air.atomic.global.and.u.i32",
"air.load.system_coherent.volatile.i32.p1i32",
"air.store.device_coherent.v4f32.p1v4f32",
// A texture of MSL's `memory_coherence_device`, as Apple's compiler names its accesses.
"air.read_texture_2d.device_coherent.u.v4i32",
"air.write_texture_2d.device_coherent.i16.v4f16",
"air.read_texture_buffer_1d.device_coherent.u.v4i32",
"air.write_texture_3d.device_coherent.v4f32",
] {
air(name);
}
@@ -295,6 +305,10 @@ fn math_conversion_and_atomic_families_decode() {
"air.atomic.global.xchg.u.i32", // exchange takes no sign
"air.atomic.region.add.u.i32", // unknown space
"air.load.somewhat_coherent.i32.p1i32",
// Only a texture's read, block read and write name a coherence, before `.i16`.
"air.sample_texture_2d.device_coherent.v4f32",
"air.atomic_fetch_add_explicit_texture_2d.device_coherent.u.i32",
"air.read_texture_2d.i16.device_coherent.v4f16",
] {
assert_eq!(classify_self(name), DeclClass::Unknown, "{name}");
}
@@ -1234,6 +1248,86 @@ fn opencl_native_and_half_functions_read_as_the_fast_form() {
}
}
/// OpenCL C's `mad` decodes in the types Apple's OpenCL compiler is measured to spell it, `float`,
/// `float4` and `half`, as the precise `Mad`; any other type or spelling stays unknown.
#[test]
fn opencl_mad_decodes_in_its_measured_types_alone() {
for (name, elem, lanes) in [
("air.mad.f32", Elem::F32, 1),
("air.mad.v4f32", Elem::F32, 4),
("air.mad.f16", Elem::F16, 1),
] {
let AirIntrinsic::Math(m) = air(name) else {
panic!("{name}");
};
assert_eq!(
(m.f, m.precision, m.ty),
(MathFn::Mad, Precision::Precise, NumTy { elem, lanes }),
"{name}"
);
}
for name in [
"air.mad.v2f32", // not measured
"air.mad.v3f32", // not measured
"air.mad.v8f32", // not measured
"air.mad.v4f16", // not measured
"air.mad.bf16", // not measured
"air.mad.i32", // float types only
"air.fast_mad.f32", // no prefix
"air.native_mad.f32", // no prefix
"air.mad.s.f32", // no sign token
"air.mad.f32.extra", // trailing token
] {
assert_eq!(classify_self(name), DeclClass::Unknown, "{name}");
}
}
/// `mul24` and `mad24` decode in the sixteen names Apple's compiler spells (both signs, `i32` and
/// 2 to 4 of its lanes) as `Mul24` and `Mad24`; a width other than 32 bits, a float, or a
/// spelling without a sign stays unknown.
#[test]
fn mul24_and_mad24_decode_on_32_bit_lanes_alone() {
for (stem, sign) in [
("mul24.s", Sign::Signed),
("mul24.u", Sign::Unsigned),
("mad24.s", Sign::Signed),
("mad24.u", Sign::Unsigned),
] {
for (ty, lanes) in [("i32", 1), ("v2i32", 2), ("v3i32", 3), ("v4i32", 4)] {
let name = format!("air.{stem}.{ty}");
let AirIntrinsic::Math(m) = air(&name) else {
panic!("{name}");
};
let f = match stem.starts_with("mul") {
true => MathFn::Mul24(sign),
false => MathFn::Mad24(sign),
};
assert_eq!(
(m.f, m.precision, m.ty),
(
f,
Precision::Precise,
NumTy {
elem: Elem::I32,
lanes
}
),
"{name}"
);
}
}
for name in [
"air.mul24.u.i16", // 32-bit lanes only
"air.mad24.s.i64", // 32-bit lanes only
"air.mul24.s.v2i8", // 32-bit lanes only
"air.mul24.f32", // integer types only
"air.mul24.i32", // a sign token is required
"air.fast_mul24.u.i32", // no prefix
] {
assert_eq!(classify_self(name), DeclClass::Unknown, "{name}");
}
}
#[test]
fn opencl_vector_data_functions_decode_with_their_strides() {
use AddrSpace::{Constant as C, Device as G, Thread as P, Threadgroup as L};
@@ -1,5 +1,5 @@
//! Textures and samplers: `air.<op>_{texture,depth}_<dim>[.i16][.<s|u>].<type>` and
//! `air.get_read_sampler`.
//! Textures and samplers: `air.<op>_{texture,depth}_<dim>[.device_coherent][.i16][.<s|u>].<type>`
//! and `air.get_read_sampler`.
//!
//! The operand layout of each operation is derived from the variant ([`Texture::layout`]); every
//! position carries a [`TexRole`]. The layouts are the ones Apple's compiler emits, read from the
@@ -27,6 +27,11 @@
//! offset) without the status is not a form of it.
//! - **write** `void (tex, coord, [cube: face], [array: layer], texel, [not buffer: lod],
//! i32 access)`.
//! - a read, block read or write of a texture of MSL's `memory_coherence_device` names it
//! `.device_coherent` after the stem, before `.i16` ([`Texture::device_coherent`]), with the
//! operands of the same access to a texture of the default threadgroup coherence: Apple's
//! compiler (macOS 27's metal 32023) names a 2D, 3D and texture buffer's read and write so, at
//! 32-bit and 16-bit coordinates.
//! - **block_read** (Metal 4.1's `block_read<W, H>` and `sparse_block_read<W, H>` of a 2D, 2D
//! array, or 2D depth texture) `void (tex, smp, <2 x i32> coord, [array: i32 layer],
//! <2 x i32> offset, i32 lod, i32 access, ptr out, ptr status, <2 x i32> size)`: the `W x H`
@@ -259,6 +264,12 @@ pub struct Texture {
/// operation without it, and [`Texture::access`] is then `None`. `true` for an operation
/// whose layout states none in either form.
pub states_access: bool,
/// The name's `device_coherent` token, first after the stem
/// (`air.read_texture_2d.device_coherent.u.v4i32`): a read, block read or write of a texture
/// of MSL's `memory_coherence_device`, coherent at device scope, whose argument and operands
/// are those of the same access to a texture of the default threadgroup coherence. `false`
/// for every other access and operation, which no such token names.
pub device_coherent: bool,
}
/// What one texture operand position is.
@@ -701,6 +712,10 @@ impl Texture {
let mut tokens = tail
.map(|t| t.split('.').collect::<Vec<_>>())
.unwrap_or_default();
let device_coherent = tokens.first() == Some(&"device_coherent");
if device_coherent {
tokens.remove(0);
}
let coord16 = tokens.first() == Some(&"i16") && tokens.len() > 1;
if coord16 {
tokens.remove(0);
@@ -752,7 +767,12 @@ impl Texture {
status: true,
access: None,
states_access: true,
device_coherent,
};
// Only a read, a block read and a write name a coherence.
if device_coherent && !matches!(t.op, TexOp::Read | TexOp::BlockRead | TexOp::Write) {
return None;
}
// The `ulong` stems take a `ulong` texel, and the others none.
let ulong_stem = matches!(op_name, OpName::UlongAtomic(_));
let ulong_atomic = matches!(t.op, TexOp::Atomic(_)) && t.ulong();
+1
View File
@@ -167,6 +167,7 @@ impl ModuleBuilder {
constant: false,
init,
externally_initialized: false,
thread_local: false,
linkage: if init.is_some() {
Linkage::Internal
} else {
+4
View File
@@ -150,6 +150,10 @@ pub struct Global {
/// `externally_initialized`: the object may be given its value from outside the module
/// before execution starts.
pub externally_initialized: bool,
/// `thread_local`: each thread has an object of its own, which starts at the initializer, as
/// Metal runs a thread-local global of the thread space (the reader refuses one of any other
/// space).
pub thread_local: bool,
/// The linkage.
pub linkage: Linkage,
/// The visibility.
+12
View File
@@ -41,6 +41,18 @@ pub const SECTION: &[u8] = b"air.externally_defined";
/// The symbol prefix of the `matmul2d` ABI.
pub const PREFIX: &[u8] = b"__tensorops_impl_matmul2d_op_";
/// The symbol prefix of every function of the tensor-ops implementation headers, the `matmul2d`
/// ABI's among them.
const FAMILY: &[u8] = b"__tensorops_impl_";
/// Whether a declaration named `symbol` in `section` is of the tensor-ops implementation's family:
/// named under `__tensorops_impl_` in [`SECTION`]. Metal supplies each body-less one when it creates
/// the pipeline, so a call that survives to one [`MatMul2dFn::of_declaration`] does not model is
/// refused as tensors.
pub(crate) fn in_family(symbol: &[u8], section: Option<&[u8]>) -> bool {
section == Some(SECTION) && symbol.starts_with(FAMILY)
}
/// `__tensor_ops_datatype_invalid`: the scale type a `_v2` run passes for a tensor operand without
/// scale factors (`tensor_plane_scales`).
pub(crate) const NO_SCALE: u64 = 0;
+8 -2
View File
@@ -112,7 +112,7 @@ another's: a pipeline the runtime refuses on MoltenVK for a structural reason ca
lavapipe, and a global row would then fail the lavapipe run for existing. The field is held, without
case, against the venue's own description — its device name, for a CPU implementation the host's
widest vector instruction set (`llvmpipe (LLVM 23.1.4, 256 bits) on x86-64 AVX-512`, which its
compiler targets and its answers follow), then its driver and API version — so a row can name one
compiler targets), then its driver and API version — so a row can name one
device (`Apple M3 Max`), one implementation (`llvmpipe`), one host's (`on x86-64 AVX2`) or a family
of them, and a venue that joins later needs no new vocabulary. `*` means every venue, and it is the
**stronger** claim rather than the looser one: the row is then held on every venue the run selected
@@ -134,7 +134,12 @@ replaying one case does not read every other row as fixed, and a run on one venu
another venue's rows as fixed.
A row's identity is its case, the verdict it expects, the site and the answer there, so a gap that
changed into another gap at the same site is a new gap and not the old one.
changed into another gap at the same site is a new gap and not the old one. Where the hosts a venue
covers answer a site differently by a property the venue does not state, the row lists each answer
recorded there with ` | ` between them, and its gap names the run each came from: llvmpipe of one
Mesa and LLVM stores the `x3` sites of `fetch-ordered-*-srgb` at 6304 elements on one x86-64
AVX-512 host and at 6496 on others. Such a row covers each answer it lists and no other, and is
held while the run answers any of them.
For a divergence the answer says **how much** moved — how many of the site's leaves differ, and the
largest difference where the values are numbers — and never where the walk first noticed. Two
@@ -331,6 +336,7 @@ one.
| `color_write_masks` | Which channels of a texel a draw changes under a write mask of none, some and all of them | run on Metal |
| `blend_sweeps` | Every settable `MTLBlendFactor` in each of the four slots, every `MTLBlendOperation` against six factor pairs and against each other, all sixteen write masks with the blend on and off, blending enabled against disabled, the blend colour at and outside its range, and the `Source1` factors through a second fragment output | run on Metal |
| `fresh_contents` | What a new buffer or texture reads before anything writes it, and after memory that was written was released | run on Metal |
| `managed_naming` | Which commit takes a Managed buffer's named range to a second copy: a compute slot, `useResource:`, a vertex slot, a blit source and a reach through the address alone, each against a write after the name | carried; an AMD Radeon Pro 5300M's table, as the oracle keeps one copy |
| `argument_encoders` | What an argument encoder says of a layout, which word of an argument buffer each argument landed in, and what the kernel then sampled through it | run on Metal |
| `function_bindings` | What a kernel's reflection says each argument is: the binding, its subprotocol's fields, and an argument buffer's struct type member by member | run on Metal |
| `indirect_commands` | What an indirect command buffer's CPU-encoded compute and render commands ran: both dispatch kinds, ordinary and indexed draws, the resets, the barriers, an attribute stride, a stage-in region, and the descriptor properties no execution needs | run on Metal |
File diff suppressed because it is too large. Load diff
@@ -113,7 +113,9 @@ int main(void) {
height:kSide
mipmapped:NO];
t.usage = MTLTextureUsageRenderTarget;
t.storageMode = MTLStorageModeShared;
// A discrete GPU's Mac takes no Shared texture: there the read texture is Managed, and a
// blit synchronizes it before the CPU reads it.
t.storageMode = device.hasUnifiedMemory ? MTLStorageModeShared : MTLStorageModeManaged;
id<MTLTexture> read = [device newTextureWithDescriptor:t];
MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];
if (n > 1) {
@@ -146,6 +148,11 @@ int main(void) {
[e drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
}
[e endEncoding];
if (!device.hasUnifiedMemory) {
id<MTLBlitCommandEncoder> b = [cb blitCommandEncoder];
[b synchronizeResource:read];
[b endEncoding];
}
[cb commit];
[cb waitUntilCompleted];
if (cb.error) {
@@ -1,103 +1,218 @@
// Which pairs of pixel formats Metal takes in `copyFromTexture:sourceSlice:sourceLevel:
// sourceOrigin:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:`.
// sourceOrigin:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:`, and
// what bytes land where it takes them. Apple's page for the call asks the destination for "The
// pixel format is the same as `sourceTexture`. The sample count is the same as `sourceTexture`."
//
// ONE CASE PER PROCESS, chosen on the command line, run under MTL_DEBUG_LAYER=1: the validation
// layer stops the process at a copy it does not take, so a case that prints "taken" was taken.
// Both textures are Private 2D 8x8 with one level (the source of `samples` 2D multisample, four
// samples); the copy is the first 4x4 texels.
// ONE CASE PER PROCESS, chosen on the command line (CASE STORAGE [DEVICE], STORAGE `shared` or
// `private`, DEVICE an index into MTLCopyAllDevices, else the default device), each run plainly
// and under MTL_DEBUG_LAYER=1, whose validation layer stops the process at a copy it does not take.
// Both textures are 2D 8x8 with one level, usage ShaderRead (the source of `samples` 2D
// multisample of four samples, usage RenderTarget). A case marked `checked` loads the source with
// byte k = (37k + 11) & 0xff and the destination with 0xEE (a Private texture through Shared
// buffers, by blits in command buffers of their own), copies the source's 4x4 texels at (0, 0) to
// the destination's (2, 1), and prints whether the destination holds the source's region's bytes
// as they are there and 0xEE elsewhere. A case marked `validated` runs under the validation layer
// alone: plain Metal has no defined answer for it.
//
// same RGBA8Unorm into RGBA8Unorm (the control: taken)
// srgb RGBA8Unorm into RGBA8Unorm_sRGB
// uint RGBA8Unorm into RGBA8Uint
// word RGBA8Unorm into R32Uint
// float R32Uint into R32Float
// order RGBA8Unorm into BGRA8Unorm
// depth Depth32Float into R32Float
// block BC1_RGBA into RG32Uint
// samples RGBA8Unorm of four samples into RGBA8Unorm of one
// same RGBA8Unorm into RGBA8Unorm (the control) checked
// r8unorm_r8uint R8Unorm into R8Uint checked
// r8uint_r8unorm R8Uint into R8Unorm checked
// r8unorm_r8snorm R8Unorm into R8Snorm checked
// r8unorm_r8sint R8Unorm into R8Sint checked
// rg8unorm_r16uint RG8Unorm into R16Uint checked
// r16float_r16uint R16Float into R16Uint checked
// word RGBA8Unorm into R32Uint checked
// uint RGBA8Unorm into RGBA8Uint checked
// order RGBA8Unorm into BGRA8Unorm checked
// srgb RGBA8Unorm into RGBA8Unorm_sRGB checked
// float R32Uint into R32Float checked
// depth Depth32Float into R32Float, Private validated
// block BC1_RGBA into RG32Uint, Private validated
// samples RGBA8Unorm of four samples into one, Private validated
// sizes R8Unorm into RGBA8Unorm (two texel sizes) validated
//
// xcrun clang -fobjc-arc -framework Metal -framework Foundation \
// -o blit_copy_format_pairs blit_copy_format_pairs.m
// for c in same srgb uint word float order depth block samples; do
// MTL_DEBUG_LAYER=1 ./blit_copy_format_pairs $c; done
// for c in same r8unorm_r8uint r8uint_r8unorm r8unorm_r8snorm r8unorm_r8sint rg8unorm_r16uint \
// r16float_r16uint word uint order srgb float; do
// for s in shared private; do
// ./blit_copy_format_pairs $c $s; MTL_DEBUG_LAYER=1 ./blit_copy_format_pairs $c $s; done
// done
// for c in depth block samples sizes; do
// MTL_DEBUG_LAYER=1 ./blit_copy_format_pairs $c private; done
//
// WHAT IT MEASURED (Apple M3 Max, macOS 27.0.1, job m3-max-43465): `same` taken; every pair of
// two formats stopped by the validation layer with "[sourceTexture pixelFormat] must equal
// [destinationTexture pixelFormat]", and `samples` with "[sourceTexture sampleCount](4) must
// equal [destinationTexture sampleCount](1)".
// On the MacBook below the validation layer stops a Shared texture's descriptor, so there the
// Private rows are the answers; it runs each case with each storage once for each device
// (DEVICE 0 and 1).
//
// WHAT IT MEASURED. The Apple M3 Max (macOS 27.0.1), Shared and Private: plain Metal takes every
// checked case and copies the bytes as they are; the validation layer takes `same` and stops
// every other case with "[sourceTexture pixelFormat](...) must equal [destinationTexture
// pixelFormat](...)", `samples` with "[sourceTexture sampleCount](4) must equal
// [destinationTexture sampleCount](1)". The AMD Radeon Pro 5300M (macOS 26.7.1), Private: every
// checked case copies the bytes as they are, plainly and under the validation layer, which takes
// `depth` and `block` too, stops `samples` as the M3 Max's does, and stops `sizes` with
// "[sourceTexture pixelFormat](MTLPixelFormatR8Unorm) must be compatible with [destinationTexture
// pixelFormat](MTLPixelFormatRGBA8Unorm)". The Intel UHD Graphics 630 of the same MacBook (macOS
// 26.7.1), Private: `same` copies the bytes; every other checked case completes, plainly and under
// the validation layer, and leaves the destination unwritten; the validation layer answers
// `depth`, `block`, `samples` and `sizes` as on the 5300M.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static id<MTLTexture> make(id<MTLDevice> device, MTLPixelFormat format, NSUInteger samples) {
struct Case {
const char *name;
MTLPixelFormat from, to;
unsigned from_bytes, to_bytes;
NSUInteger samples;
int checked;
};
static const struct Case kCases[] = {
{"same", MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm, 4, 4, 1, 1},
{"r8unorm_r8uint", MTLPixelFormatR8Unorm, MTLPixelFormatR8Uint, 1, 1, 1, 1},
{"r8uint_r8unorm", MTLPixelFormatR8Uint, MTLPixelFormatR8Unorm, 1, 1, 1, 1},
{"r8unorm_r8snorm", MTLPixelFormatR8Unorm, MTLPixelFormatR8Snorm, 1, 1, 1, 1},
{"r8unorm_r8sint", MTLPixelFormatR8Unorm, MTLPixelFormatR8Sint, 1, 1, 1, 1},
{"rg8unorm_r16uint", MTLPixelFormatRG8Unorm, MTLPixelFormatR16Uint, 2, 2, 1, 1},
{"r16float_r16uint", MTLPixelFormatR16Float, MTLPixelFormatR16Uint, 2, 2, 1, 1},
{"word", MTLPixelFormatRGBA8Unorm, MTLPixelFormatR32Uint, 4, 4, 1, 1},
{"uint", MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Uint, 4, 4, 1, 1},
{"order", MTLPixelFormatRGBA8Unorm, MTLPixelFormatBGRA8Unorm, 4, 4, 1, 1},
{"srgb", MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm_sRGB, 4, 4, 1, 1},
{"float", MTLPixelFormatR32Uint, MTLPixelFormatR32Float, 4, 4, 1, 1},
{"depth", MTLPixelFormatDepth32Float, MTLPixelFormatR32Float, 4, 4, 1, 0},
{"block", MTLPixelFormatBC1_RGBA, MTLPixelFormatRG32Uint, 0, 8, 1, 0},
{"samples", MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm, 4, 4, 4, 0},
{"sizes", MTLPixelFormatR8Unorm, MTLPixelFormatRGBA8Unorm, 1, 4, 1, 0},
};
enum { SIDE = 8, N = 4, DX = 2, DY = 1 };
static id<MTLTexture> make(id<MTLDevice> dev, MTLPixelFormat format, NSUInteger samples, BOOL shared) {
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format width:8 height:8 mipmapped:NO];
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format width:SIDE height:SIDE mipmapped:NO];
desc.usage = MTLTextureUsageShaderRead;
desc.storageMode = MTLStorageModePrivate;
desc.storageMode = shared ? MTLStorageModeShared : MTLStorageModePrivate;
if (samples > 1) {
desc.textureType = MTLTextureType2DMultisample;
desc.sampleCount = samples;
desc.usage = MTLTextureUsageRenderTarget;
}
return [device newTextureWithDescriptor:desc];
return [dev newTextureWithDescriptor:desc];
}
static void run(id<MTLCommandQueue> queue, void (^encode)(id<MTLBlitCommandEncoder>), const char *what) {
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
encode(blit);
[blit endEncoding];
[cb commit];
[cb waitUntilCompleted];
printf("%s: status %ld%s%s\n", what, (long)cb.status, cb.error ? ", error " : "",
cb.error ? cb.error.localizedDescription.UTF8String : "");
}
int main(int argc, const char **argv) {
@autoreleasepool {
if (argc != 2) {
printf("usage: blit_copy_format_pairs CASE\n");
if (argc != 3 && argc != 4) {
printf("usage: blit_copy_format_pairs CASE shared|private [DEVICE]\n");
return 2;
}
const char *name = argv[1];
struct {
const char *name;
MTLPixelFormat from, to;
NSUInteger samples;
} cases[] = {
{"same", MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm, 1},
{"srgb", MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm_sRGB, 1},
{"uint", MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Uint, 1},
{"word", MTLPixelFormatRGBA8Unorm, MTLPixelFormatR32Uint, 1},
{"float", MTLPixelFormatR32Uint, MTLPixelFormatR32Float, 1},
{"order", MTLPixelFormatRGBA8Unorm, MTLPixelFormatBGRA8Unorm, 1},
{"depth", MTLPixelFormatDepth32Float, MTLPixelFormatR32Float, 1},
{"block", MTLPixelFormatBC1_RGBA, MTLPixelFormatRG32Uint, 1},
{"samples", MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm, 4},
};
int found = -1;
for (int i = 0; i < (int)(sizeof cases / sizeof cases[0]); i++) {
if (strcmp(cases[i].name, name) == 0) found = i;
const struct Case *c = NULL;
for (size_t i = 0; i < sizeof kCases / sizeof kCases[0]; i++) {
if (strcmp(kCases[i].name, argv[1]) == 0) c = &kCases[i];
}
if (found < 0) {
printf("no case %s\n", name);
if (!c) {
printf("no case %s\n", argv[1]);
return 2;
}
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLTexture> from = make(device, cases[found].from, cases[found].samples);
id<MTLTexture> to = make(device, cases[found].to, 1);
BOOL shared = strcmp(argv[2], "shared") == 0;
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
if (argc == 4) {
NSArray<id<MTLDevice>> *all = MTLCopyAllDevices();
int k = atoi(argv[3]);
if (k < 0 || k >= (int)all.count) {
printf("no device %d\n", k);
return 2;
}
dev = all[k];
}
const char *debug = getenv("MTL_DEBUG_LAYER");
printf("case %s storage %s debug %s device %s\n", c->name, shared ? "shared" : "private",
debug ? debug : "-", dev.name.UTF8String);
id<MTLTexture> from = make(dev, c->from, c->samples, shared);
id<MTLTexture> to = make(dev, c->to, 1, shared);
if (!from || !to) {
printf("%s: no texture\n", name);
printf("%s: no texture\n", c->name);
return 1;
}
id<MTLCommandQueue> queue = [device newCommandQueue];
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
NSUInteger n = 4;
[blit copyFromTexture:from
sourceSlice:0
sourceLevel:0
sourceOrigin:MTLOriginMake(0, 0, 0)
sourceSize:MTLSizeMake(n, n, 1)
toTexture:to
destinationSlice:0
destinationLevel:0
destinationOrigin:MTLOriginMake(0, 0, 0)];
[blit endEncoding];
[cb commit];
[cb waitUntilCompleted];
printf("%s: taken, status %ld%s%s\n", name, (long)cb.status, cb.error ? ", error " : "",
cb.error ? cb.error.localizedDescription.UTF8String : "");
id<MTLCommandQueue> queue = [dev newCommandQueue];
NSUInteger fpitch = SIDE * c->from_bytes, tpitch = SIDE * c->to_bytes;
unsigned char src[SIDE * SIDE * 8], dst[SIDE * SIDE * 8], got[SIDE * SIDE * 8];
for (unsigned k = 0; k < sizeof src; k++) src[k] = (unsigned char)((37 * k + 11) & 0xff);
memset(dst, 0xEE, sizeof dst);
memset(got, 0, sizeof got);
MTLRegion all = MTLRegionMake2D(0, 0, SIDE, SIDE);
id<MTLBuffer> back = nil;
if (c->checked && shared) {
[from replaceRegion:all mipmapLevel:0 withBytes:src bytesPerRow:fpitch];
[to replaceRegion:all mipmapLevel:0 withBytes:dst bytesPerRow:tpitch];
} else if (c->checked) {
id<MTLBuffer> sb = [dev newBufferWithBytes:src length:fpitch * SIDE options:MTLResourceStorageModeShared];
id<MTLBuffer> db = [dev newBufferWithBytes:dst length:tpitch * SIDE options:MTLResourceStorageModeShared];
run(queue, ^(id<MTLBlitCommandEncoder> blit) {
[blit copyFromBuffer:sb sourceOffset:0 sourceBytesPerRow:fpitch sourceBytesPerImage:fpitch * SIDE
sourceSize:MTLSizeMake(SIDE, SIDE, 1) toTexture:from destinationSlice:0
destinationLevel:0 destinationOrigin:MTLOriginMake(0, 0, 0)];
[blit copyFromBuffer:db sourceOffset:0 sourceBytesPerRow:tpitch sourceBytesPerImage:tpitch * SIDE
sourceSize:MTLSizeMake(SIDE, SIDE, 1) toTexture:to destinationSlice:0
destinationLevel:0 destinationOrigin:MTLOriginMake(0, 0, 0)];
}, "load");
back = [dev newBufferWithLength:tpitch * SIDE options:MTLResourceStorageModeShared];
}
run(queue, ^(id<MTLBlitCommandEncoder> blit) {
[blit copyFromTexture:from sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0)
sourceSize:MTLSizeMake(N, N, 1) toTexture:to destinationSlice:0 destinationLevel:0
destinationOrigin:MTLOriginMake(DX, DY, 0)];
}, "copy");
if (!c->checked) return 0;
if (shared) {
[to getBytes:got bytesPerRow:tpitch fromRegion:all mipmapLevel:0];
} else {
run(queue, ^(id<MTLBlitCommandEncoder> blit) {
[blit copyFromTexture:to sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0)
sourceSize:MTLSizeMake(SIDE, SIDE, 1) toBuffer:back destinationOffset:0
destinationBytesPerRow:tpitch destinationBytesPerImage:tpitch * SIDE];
}, "read-back");
memcpy(got, back.contents, tpitch * SIDE);
}
// The region holds the source's region's bytes as they are (the texel sizes are equal),
// the rest 0xEE.
int region = 1, rest = 1, first = -1;
for (unsigned y = 0; y < SIDE; y++) {
for (unsigned x = 0; x < tpitch; x++) {
unsigned char g = got[y * tpitch + x];
unsigned tx = x / c->to_bytes;
int inside = tx >= DX && tx < DX + N && y >= DY && y < DY + N;
int ok = inside ? g == src[(y - DY) * fpitch + (tx - DX) * c->from_bytes + x % c->to_bytes]
: g == 0xEE;
if (!ok) {
if (inside) region = 0;
else rest = 0;
if (first < 0) first = (int)(y * tpitch + x);
}
}
}
printf("bytes: region %s, outside %s", region ? "as copied" : "DIFFER", rest ? "0xEE" : "DIFFER");
if (first >= 0) printf(", first difference at byte %d: 0x%02x", first, got[first]);
printf("\nrow %u:", DY);
for (unsigned x = 0; x < tpitch; x++) printf(" %02x", got[DY * tpitch + x]);
printf("\n");
}
return 0;
}
@@ -0,0 +1,228 @@
// Whether a command buffer that waits for an event on one queue runs once another queue's command
// buffer signals it, or only after that whole command buffer, on Metal.
//
// The runtime submits every queue to one `VkQueue`, so its waiter runs after the signaller's whole
// command buffer (the runtime's README, the queues' known gaps). This probe measures Metal in the
// same two shapes, five rounds each, in one process:
//
// event A, on queue A: one short dispatch, a signal of an `MTLEvent` to the round's value, then
// about 100 ms of dispatches (25 of a kernel that spins about 4 ms, calibrated first,
// alone). B, on queue B and committed just after A: a wait for that value, then one
// dispatch of one thread over B's own buffer.
// host A: the 25 spins alone. B: a wait for an `MTLSharedEvent`'s round value, then the one
// thread; the host sets the value just after both commits.
//
// Each round reports A's GPU span, and when B's GPU work started and ended: from A's GPU start
// (event) or from the host's set (host). B's GPU start may include its wait, so the stall beyond
// the event's order is read from B's GPU end, B's one thread being about 0.01 ms: in the event
// shape B's end less A's start less A's short part (one dispatch of one thread and the signal,
// timed alone first); in the host shape B's end less the set. A and B share no resource, so only
// the event orders them. Each round's GPU work is about 0.1 s; nothing can hang: every wait's value
// is signalled in the same round.
//
// WHAT IT MEASURED (MTL_DEBUG_LAYER unset; one spin 4.00 ms at 275,795 iterations, A's short part
// 0.002 ms; job m3-max-79181):
//
// M3 Max, macOS 27.0.1: event, A ran 99.96-100.00 ms and B's GPU end came 0.01-0.08 ms after
// A's GPU start; host, A ran 99.95 ms from 0.13-0.14 ms after the set and B's GPU end came
// 0.13-0.15 ms after the set. No command buffer reported an error.
//
// So the M3 runs B once the event reaches its value, beside the rest of A's command buffer.
//
// Run: cross_queue_event_stall [DEVICE] (a part of a device's name, or the default device)
// Build: clang -fobjc-arc -O1 -fmodules -o cross_queue_event_stall cross_queue_event_stall.m \
// -framework Foundation -framework Metal
//
// Measuring runs keep `MTL_DEBUG_LAYER` OUT of the environment.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <mach/mach_time.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void P(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
fputs("RESULT ", stdout);
vfprintf(stdout, fmt, ap);
fputc('\n', stdout);
fflush(stdout);
va_end(ap);
}
/// The host's clock in seconds, the one `GPUStartTime` and `GPUEndTime` answer on.
static double host_seconds(void) {
static mach_timebase_info_data_t base;
if (base.denom == 0) {
mach_timebase_info(&base);
}
return (double)mach_absolute_time() * base.numer / base.denom / 1e9;
}
static const int ROUNDS = 5;
static const int SPINS = 25;
static const NSUInteger THREADS = 256;
static NSString *const kSource =
@"#include <metal_stdlib>\n"
"using namespace metal;\n"
"kernel void spin(device uint *b [[buffer(0)]],\n"
" constant uint &iters [[buffer(1)]],\n"
" uint gid [[thread_position_in_grid]]) {\n"
" uint x = gid * 2654435761u;\n"
" for (uint i = 0; i < iters; i++) { x = x * 1664525u + 1013904223u; }\n"
" b[gid] = x == 0x12345678u ? 1u : 0xFFFFFFFFu;\n"
"}\n"
"kernel void one(device uint *b [[buffer(0)]]) { b[0] = 7u; }\n";
typedef struct {
id<MTLDevice> device;
id<MTLComputePipelineState> spin;
id<MTLComputePipelineState> one;
id<MTLBuffer> a_words;
id<MTLBuffer> b_words;
} Probe;
static void encode_spins(Probe *p, id<MTLCommandBuffer> cb, uint32_t iters, int dispatches) {
id<MTLComputeCommandEncoder> e = [cb computeCommandEncoder];
[e setComputePipelineState:p->spin];
[e setBuffer:p->a_words offset:0 atIndex:0];
[e setBytes:&iters length:sizeof iters atIndex:1];
for (int d = 0; d < dispatches; d++) {
[e dispatchThreadgroups:MTLSizeMake(THREADS / 64, 1, 1)
threadsPerThreadgroup:MTLSizeMake(64, 1, 1)];
}
[e endEncoding];
}
/// One dispatch of one thread over `buffer`.
static void encode_one(Probe *p, id<MTLCommandBuffer> cb, id<MTLBuffer> buffer) {
id<MTLComputeCommandEncoder> e = [cb computeCommandEncoder];
[e setComputePipelineState:p->one];
[e setBuffer:buffer offset:0 atIndex:0];
[e dispatchThreadgroups:MTLSizeMake(1, 1, 1) threadsPerThreadgroup:MTLSizeMake(1, 1, 1)];
[e endEncoding];
}
static double span_ms(id<MTLCommandBuffer> cb) {
return (cb.GPUEndTime - cb.GPUStartTime) * 1000.0;
}
static const char *status(id<MTLCommandBuffer> cb) {
return cb.error ? cb.error.localizedDescription.UTF8String : "no error";
}
int main(int argc, char **argv) {
@autoreleasepool {
Probe p;
p.device = MTLCreateSystemDefaultDevice();
if (argc == 2) {
p.device = nil;
for (id<MTLDevice> device in MTLCopyAllDevices()) {
if (strstr(device.name.UTF8String, argv[1])) {
p.device = device;
}
}
if (!p.device) {
P("no device named like %s", argv[1]);
return 1;
}
}
NSOperatingSystemVersion v = [[NSProcessInfo processInfo] operatingSystemVersion];
P("device %s macOS %ld.%ld.%ld MTL_DEBUG_LAYER=%s", p.device.name.UTF8String,
(long)v.majorVersion, (long)v.minorVersion, (long)v.patchVersion,
getenv("MTL_DEBUG_LAYER") ? getenv("MTL_DEBUG_LAYER") : "unset");
NSError *error = nil;
id<MTLLibrary> library = [p.device newLibraryWithSource:kSource options:nil error:&error];
if (!library) {
P("library: %s", error.localizedDescription.UTF8String);
return 1;
}
p.spin = [p.device newComputePipelineStateWithFunction:[library newFunctionWithName:@"spin"]
error:&error];
p.one = [p.device newComputePipelineStateWithFunction:[library newFunctionWithName:@"one"]
error:&error];
if (!p.spin || !p.one) {
P("pipeline: %s", error.localizedDescription.UTF8String);
return 1;
}
p.a_words = [p.device newBufferWithLength:THREADS * 4 options:MTLResourceStorageModePrivate];
p.b_words = [p.device newBufferWithLength:4096 options:MTLResourceStorageModePrivate];
id<MTLBuffer> a_one = [p.device newBufferWithLength:4096 options:MTLResourceStorageModePrivate];
id<MTLCommandQueue> queue_a = [p.device newCommandQueue];
id<MTLCommandQueue> queue_b = [p.device newCommandQueue];
// Calibration on A's queue, alone: one spin of about 4 ms, then A's short part.
uint32_t iters = 1u << 10;
double one_ms = 0;
for (int step = 0; step < 14 && (one_ms < 3.5 || one_ms > 4.5); step++) {
if (step > 0) {
double scale = one_ms > 0.1 ? 4.0 / one_ms : 8.0;
iters = (uint32_t)MIN((double)(1u << 28), MAX(1.0, iters * scale));
}
id<MTLCommandBuffer> cb = [queue_a commandBuffer];
encode_spins(&p, cb, iters, 1);
[cb commit];
[cb waitUntilCompleted];
one_ms = span_ms(cb);
}
id<MTLEvent> warm_event = [p.device newEvent];
double short_ms = 0;
for (int w = 0; w < 3; w++) {
id<MTLCommandBuffer> cb = [queue_a commandBuffer];
encode_one(&p, cb, a_one);
[cb encodeSignalEvent:warm_event value:(uint64_t)(w + 1)];
[cb commit];
[cb waitUntilCompleted];
short_ms = span_ms(cb);
}
P("one spin alone: %u iterations, %.2f ms; the short part (one thread and a signal) %.3f ms; "
"A's long part %d spins",
iters, one_ms, short_ms, SPINS);
id<MTLEvent> event = [p.device newEvent];
for (int round = 1; round <= ROUNDS; round++) {
id<MTLCommandBuffer> a = [queue_a commandBuffer];
encode_one(&p, a, a_one);
[a encodeSignalEvent:event value:(uint64_t)round];
encode_spins(&p, a, iters, SPINS);
id<MTLCommandBuffer> b = [queue_b commandBuffer];
[b encodeWaitForEvent:event value:(uint64_t)round];
encode_one(&p, b, p.b_words);
[a commit];
[b commit];
[b waitUntilCompleted];
[a waitUntilCompleted];
double ms = 1000.0, a0 = a.GPUStartTime;
P("event round %d: A %.2f ms; B's GPU start %.2f and end %.2f ms after A's start (A ended "
"at %.2f); stall beyond the event's order (B's end) %.2f ms; A %s, B %s",
round, span_ms(a), (b.GPUStartTime - a0) * ms, (b.GPUEndTime - a0) * ms,
(a.GPUEndTime - a0) * ms, (b.GPUEndTime - a0) * ms - short_ms, status(a), status(b));
}
id<MTLSharedEvent> shared = [p.device newSharedEvent];
for (int round = 1; round <= ROUNDS; round++) {
id<MTLCommandBuffer> a = [queue_a commandBuffer];
encode_spins(&p, a, iters, SPINS);
id<MTLCommandBuffer> b = [queue_b commandBuffer];
[b encodeWaitForEvent:shared value:(uint64_t)round];
encode_one(&p, b, p.b_words);
[a commit];
[b commit];
double set = host_seconds();
shared.signaledValue = (uint64_t)round;
[b waitUntilCompleted];
[a waitUntilCompleted];
double ms = 1000.0;
P("host round %d: A %.2f ms, its GPU start %.2f ms after the host's set; B's GPU start %.2f "
"and end %.2f ms after the set (A ended at %.2f); stall beyond the event's order (B's "
"end) %.2f ms; A %s, B %s",
round, span_ms(a), (a.GPUStartTime - set) * ms, (b.GPUStartTime - set) * ms,
(b.GPUEndTime - set) * ms, (a.GPUEndTime - set) * ms, (b.GPUEndTime - set) * ms,
status(a), status(b));
}
}
return 0;
}
@@ -0,0 +1,66 @@
// What plain Metal answers for `-[MTLDevice getDefaultSamplePositions:count:]` at each sample count,
// those the device renders (`supportsTextureSampleCount:`) and those it does not, the reference
// metal2vulkan-runtime's `Device::default_sample_positions` is read against.
//
// default_sample_positions <count> one count a process: an assertion ends it.
// default_sample_positions list the counts.
//
// Each count prints whether the device renders it, then calls the method into 64 positions first
// set to (-1, -1), and prints every position it changed (index and value, each coordinate to 9
// digits), how many it changed, and an exception it raised, if any. A count Metal's validation
// stops ends the process; run it under MTL_DEBUG_LAYER=1 as well to see what the validation layer
// says (the exit status and the assertion's text on stderr).
//
// Build and run (macOS):
// clang -O2 -fobjc-arc -framework Metal -framework Foundation -o default_sample_positions \
// default_sample_positions.m
// for n in $(./default_sample_positions list); do ./default_sample_positions $n; echo "exit $?"; done
// for n in $(./default_sample_positions list); do MTL_DEBUG_LAYER=1 ./default_sample_positions $n;
// echo "exit $?"; done
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const unsigned long kCounts[] = {0, 1, 2, 3, 4, 5, 6, 8, 16, 17, 32, 33};
int main(int argc, const char *argv[]) {
@autoreleasepool {
if (argc != 2) {
fprintf(stderr, "usage: %s <count> | list\n", argv[0]);
return 2;
}
if (strcmp(argv[1], "list") == 0) {
for (size_t i = 0; i < sizeof kCounts / sizeof kCounts[0]; i++) printf("%lu\n", kCounts[i]);
return 0;
}
NSUInteger n = (NSUInteger)strtoul(argv[1], NULL, 10);
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
if (!device) {
fprintf(stderr, "no Metal device\n");
return 3;
}
printf("device %s; count %lu; supportsTextureSampleCount %s\n", device.name.UTF8String,
(unsigned long)n, [device supportsTextureSampleCount:n] ? "YES" : "NO");
enum { kSlots = 64 };
MTLSamplePosition pos[kSlots];
for (int i = 0; i < kSlots; i++) pos[i] = MTLSamplePositionMake(-1.0f, -1.0f);
fflush(stdout);
@try {
[device getDefaultSamplePositions:pos count:n];
} @catch (NSException *e) {
printf("count %lu: exception %s: %s\n", (unsigned long)n, e.name.UTF8String,
e.reason.UTF8String);
}
int changed = 0;
for (int i = 0; i < kSlots; i++) {
if (pos[i].x == -1.0f && pos[i].y == -1.0f) continue;
changed++;
printf("count %lu: position %d (%.9f, %.9f)\n", (unsigned long)n, i, pos[i].x, pos[i].y);
}
printf("count %lu: %d of %d positions changed\n", (unsigned long)n, changed, kSlots);
}
return 0;
}
@@ -0,0 +1,161 @@
// What a kernel's `[[stage_in]]` fetch reads through a layout of `MTLBufferLayoutStrideDynamic`
// whose buffer is bound by a setter WITHOUT an `attributeStride`: `setBuffer:offset:atIndex:`,
// `setBufferOffset:atIndex:` and `setBytes:length:atIndex:`, alone and after a stride setter
// bound the slot at a stride of its own.
//
// Metal's headers say the stride setters are the ones to call for such a layout ("only call this
// when the kernel-buffer is part of the stageInputDescriptor and has set its stride to
// `MTLBufferLayoutStrideDynamic`") and say nothing of what a plain bind of it reads. So the
// answer is a reading, and this probe takes it.
//
// The kernel reads one `uint` attribute (attribute 0, offset 0, buffer index 1) through a
// thread-position-in-grid-x layout at step rate 1 of a dynamic stride, and stores it at the
// thread's position in buffer 0. The source buffer holds `0x10 + w` at word `w`, so the words a
// row reads name the stride it fetched at: stride 0 reads `0x10` for every thread, 4 reads
// `0x10, 0x11, ...`, 8 reads `0x10, 0x12, ...`. Eight threads in one threadgroup, the stage-in
// region the grid's own; every fetch at a stride of at most 16 lies inside the 256-byte source.
//
// The rows, each its own command buffer and encoder:
//
// plain-buffer setBuffer:offset:0 atIndex:1, nothing else
// stride-8 setBuffer:offset:0 attributeStride:8 atIndex:1 (the control: it must
// read 0x10, 0x12, ..., or the probe measures nothing)
// stride-8-then-buffer the stride bind, then setBuffer:offset:0 atIndex:1 of the same buffer
// stride-8-then-offset the stride bind, then setBufferOffset:0 atIndex:1
// plain-bytes setBytes:length:256 atIndex:1 of the source's words
// stride-8-then-bytes the stride bind, then setBytes:length:256 atIndex:1
//
// Each row prints the eight words read, the stride they imply (or "other"), and the command
// buffer's status.
//
// xcrun clang -fobjc-arc -framework Metal -framework Foundation \
// -o dynamic_stride_plain_binds dynamic_stride_plain_binds.m
// ./dynamic_stride_plain_binds
// MTL_DEBUG_LAYER=1 MTL_DEBUG_LAYER_ERROR_MODE=nslog ./dynamic_stride_plain_binds
//
// The measuring run keeps `MTL_DEBUG_LAYER` out of the environment; the layer's messages are
// taken in the second run and reported as the layer's, never as plain Metal's answer.
//
// WHAT IT MEASURED: see the commit that adds the reading, with the run it came from.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <stdio.h>
#include <string.h>
static NSString *const SOURCE =
@"#include <metal_stdlib>\n"
"using namespace metal;\n"
"struct In { uint v [[attribute(0)]]; };\n"
"kernel void fetch(In in [[stage_in]], device uint *out [[buffer(0)]],\n"
" uint tid [[thread_position_in_grid]]) {\n"
" out[tid] = in.v;\n"
"}\n";
enum { THREADS = 8, WORDS = 64 };
typedef enum { PLAIN_BUFFER, STRIDE_8, STRIDE_THEN_BUFFER, STRIDE_THEN_OFFSET, PLAIN_BYTES,
STRIDE_THEN_BYTES, ROWS } Row;
static const char *NAMES[ROWS] = {"plain-buffer", "stride-8",
"stride-8-then-buffer", "stride-8-then-offset",
"plain-bytes", "stride-8-then-bytes"};
static void run(id<MTLDevice> device, id<MTLComputePipelineState> state,
id<MTLCommandQueue> queue, id<MTLBuffer> source, Row row) {
id<MTLBuffer> out = [device newBufferWithLength:THREADS * 4
options:MTLResourceStorageModeShared];
memset(out.contents, 0xee, THREADS * 4);
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLComputeCommandEncoder> encoder = [cb computeCommandEncoder];
[encoder setComputePipelineState:state];
[encoder setBuffer:out offset:0 atIndex:0];
switch (row) {
case PLAIN_BUFFER:
[encoder setBuffer:source offset:0 atIndex:1];
break;
case STRIDE_8:
[encoder setBuffer:source offset:0 attributeStride:8 atIndex:1];
break;
case STRIDE_THEN_BUFFER:
[encoder setBuffer:source offset:0 attributeStride:8 atIndex:1];
[encoder setBuffer:source offset:0 atIndex:1];
break;
case STRIDE_THEN_OFFSET:
[encoder setBuffer:source offset:0 attributeStride:8 atIndex:1];
[encoder setBufferOffset:0 atIndex:1];
break;
case PLAIN_BYTES:
[encoder setBytes:source.contents length:WORDS * 4 atIndex:1];
break;
case STRIDE_THEN_BYTES:
[encoder setBuffer:source offset:0 attributeStride:8 atIndex:1];
[encoder setBytes:source.contents length:WORDS * 4 atIndex:1];
break;
default:
break;
}
[encoder setStageInRegion:MTLRegionMake1D(0, THREADS)];
[encoder dispatchThreads:MTLSizeMake(THREADS, 1, 1)
threadsPerThreadgroup:MTLSizeMake(THREADS, 1, 1)];
[encoder endEncoding];
[cb commit];
[cb waitUntilCompleted];
const uint32_t *w = out.contents;
// The stride the words imply: every thread t read word t * k for one k, stride 4k bytes.
long stride = -1;
for (int k = 0; k <= 4 && stride < 0; k++) {
int all = 1;
for (int t = 0; t < THREADS; t++)
if (w[t] != 0x10u + (uint32_t)(t * k)) all = 0;
if (all) stride = 4 * k;
}
printf("%-21s status %ld%s:", NAMES[row], (long)cb.status, cb.error ? " (error)" : "");
for (int t = 0; t < THREADS; t++) printf(" %#x", w[t]);
if (stride >= 0)
printf(" -> stride %ld\n", stride);
else
printf(" -> other\n");
}
int main(void) {
@autoreleasepool {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
NSError *error = nil;
id<MTLLibrary> library = [device newLibraryWithSource:SOURCE
options:[MTLCompileOptions new]
error:&error];
if (!library) {
printf("library: %s\n", error.localizedDescription.UTF8String);
return 2;
}
MTLStageInputOutputDescriptor *stage = [MTLStageInputOutputDescriptor new];
stage.attributes[0].format = MTLAttributeFormatUInt;
stage.attributes[0].offset = 0;
stage.attributes[0].bufferIndex = 1;
stage.layouts[1].stride = MTLBufferLayoutStrideDynamic;
stage.layouts[1].stepFunction = MTLStepFunctionThreadPositionInGridX;
stage.layouts[1].stepRate = 1;
MTLComputePipelineDescriptor *descriptor = [MTLComputePipelineDescriptor new];
descriptor.computeFunction = [library newFunctionWithName:@"fetch"];
descriptor.stageInputDescriptor = stage;
id<MTLComputePipelineState> state =
[device newComputePipelineStateWithDescriptor:descriptor
options:MTLPipelineOptionNone
reflection:nil
error:&error];
if (!state) {
printf("state: %s\n", error.localizedDescription.UTF8String);
return 2;
}
id<MTLBuffer> source = [device newBufferWithLength:WORDS * 4
options:MTLResourceStorageModeShared];
uint32_t *words = source.contents;
for (int w = 0; w < WORDS; w++) words[w] = 0x10u + (uint32_t)w;
printf("%s, macOS %s\n", device.name.UTF8String,
NSProcessInfo.processInfo.operatingSystemVersionString.UTF8String);
id<MTLCommandQueue> queue = [device newCommandQueue];
for (int row = 0; row < ROWS; row++) run(device, state, queue, source, (Row)row);
}
return 0;
}
@@ -0,0 +1,260 @@
// How Metal blends an extended-range texture's two levels under a linear mip filter, for the forms
// `metal2vulkan`'s `lower/sampler/extended.rs` does not blend (`ExtendedRange::blends_levels`: the
// padded `R10Unorm_X6`, `RG10Unorm_X12` and their `_sRGB` twins, `RGB10A2Unorm_sRGB`, the bfloat
// formats) and, in 3D, for `BGR10_XR`, `BGRA10_XR` and their twins, against the rule the 2D
// samples of `BGR10_XR` and `BGRA10_XR` take: the two levels' samples blended by `mix` at the level
// fraction truncated onto sixty-fourths.
//
// Each form's texture (2D 16 x 16, or 3D 16 x 16 x 16, five levels, random codes: a padded form's
// low bits 0, a bfloat form's values in [0, 2)) is sampled by a kernel at 4,096 points per filter
// (nearest, linear), coordinates up to 0.15 past the edges and levels between two (a quarter on a
// sixty-fourth, a quarter one `f32` step beside one, the rest random), through a sampler clamping
// to the edge with a linear mip filter, and at the two levels themselves (the level's integer
// below and above) and at the point's own level through the same sampler with a nearest mip
// filter. For each lane the line counts the samples equal to the rule (`mix(a, b, w)` as
// `a * (1 - w) + b * w` in `f32`, no fused multiply-add), within one `f32` step of it, equal to
// the lower or upper level's sample or to the nearest mip filter's at the point's level (where
// the two levels differ), and equal to the blend at the unrounded fraction, and gives the largest
// distance from the rule, absolute and in units of the two samples' difference, after the level
// count of the texture Metal made. A two-plane form (`RGB10A8_2P_XR10` and its twin) is asked
// only whether a texture of five levels is made.
//
// xcrun clang -fobjc-arc -framework Metal -framework Foundation -o extended_linear_mip_blends \
// extended_linear_mip_blends.m
// /usr/bin/env -u MTL_DEBUG_LAYER ./extended_linear_mip_blends
#pragma STDC FP_CONTRACT OFF
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { SIDE = 16, LEVELS = 5, POINTS = 4096 };
static const char *SRC =
"#include <metal_stdlib>\n"
"using namespace metal;\n"
"kernel void k2(texture2d<float> t [[texture(0)]], sampler s [[sampler(0)]],\n"
" device const float4 *p [[buffer(0)]], device float4 *o [[buffer(1)]],\n"
" uint i [[thread_position_in_grid]]) {\n"
" o[i] = t.sample(s, p[i].xy, level(p[i].w));\n"
"}\n"
"kernel void k3(texture3d<float> t [[texture(0)]], sampler s [[sampler(0)]],\n"
" device const float4 *p [[buffer(0)]], device float4 *o [[buffer(1)]],\n"
" uint i [[thread_position_in_grid]]) {\n"
" o[i] = t.sample(s, p[i].xyz, level(p[i].w));\n"
"}\n";
static uint64_t sm = 11;
static uint64_t next64(void) {
uint64_t z = (sm += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
static uint32_t r32(void) { return (uint32_t)(next64() >> 32); }
static float unit(void) { return (float)(r32() >> 8) / 16777216.0f; }
// A form: its raw `MTLPixelFormat`, name, bytes per texel and how a random texel's bytes are made
// (0: every bit random, 1: 16-bit words with their low 6 bits 0, 2: 16-bit bfloats in [0, 2),
// 3: a 32-bit word of three 10-bit fields and two bits 0).
typedef struct {
NSUInteger raw;
const char *name;
int bytes, kind, volume;
} Form;
static void texel(const Form *f, uint8_t *out) {
for (int b = 0; b < f->bytes; b += 2) {
uint16_t w = (uint16_t)r32();
if (f->kind == 1) w &= 0xffc0;
if (f->kind == 2) w = (uint16_t)(0x3b00 + (r32() % 0x500)); // bfloat 2^-9 .. ~2
memcpy(out + b, &w, 2);
}
if (f->kind == 3) {
uint32_t w = r32() & 0x3fffffff;
memcpy(out, &w, 4);
}
}
int main(void) {
@autoreleasepool {
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
printf("device %s\n", dev.name.UTF8String);
NSError *err = nil;
MTLCompileOptions *co = [MTLCompileOptions new];
co.mathMode = MTLMathModeSafe;
id<MTLLibrary> lib = [dev newLibraryWithSource:@(SRC) options:co error:&err];
if (!lib) {
printf("library: %s\n", err.description.UTF8String);
return 1;
}
id<MTLComputePipelineState> k2 = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"k2"] error:&err];
id<MTLComputePipelineState> k3 = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"k3"] error:&err];
id<MTLCommandQueue> q = [dev newCommandQueue];
Form forms[] = {
{576, "R10Unorm_X6", 2, 1, 0}, {577, "R10Unorm_X6_sRGB", 2, 1, 0},
{578, "RG10Unorm_X12", 4, 1, 0}, {579, "RG10Unorm_X12_sRGB", 4, 1, 0},
{586, "RGB10A2Unorm_sRGB", 4, 0, 0}, {26, "R16Bfloat", 2, 2, 0},
{66, "RG16Bfloat", 4, 2, 0}, {116, "RGBA16Bfloat", 8, 2, 0},
{554, "BGR10_XR", 4, 3, 1}, {555, "BGR10_XR_sRGB", 4, 3, 1},
{552, "BGRA10_XR", 8, 1, 1}, {553, "BGRA10_XR_sRGB", 8, 1, 1},
{554, "BGR10_XR", 4, 3, 0}, {552, "BGRA10_XR", 8, 1, 0},
};
// The two-plane forms: whether a texture of five levels is made.
for (NSUInteger raw = 550; raw <= 551; raw++) {
MTLTextureDescriptor *td = [MTLTextureDescriptor new];
td.pixelFormat = (MTLPixelFormat)raw;
td.width = td.height = SIDE;
td.mipmapLevelCount = LEVELS;
td.usage = MTLTextureUsageShaderRead;
td.storageMode = MTLStorageModePrivate;
id<MTLTexture> t = [dev newTextureWithDescriptor:td];
printf("RESULT two-plane %lu: a texture of %d levels %s\n", (unsigned long)raw, LEVELS,
t ? "is made" : "is not made");
}
for (unsigned fi = 0; fi < sizeof forms / sizeof forms[0]; fi++) {
Form f = forms[fi];
MTLTextureDescriptor *td = [MTLTextureDescriptor new];
td.textureType = f.volume ? MTLTextureType3D : MTLTextureType2D;
td.pixelFormat = (MTLPixelFormat)f.raw;
td.width = td.height = SIDE;
td.depth = f.volume ? SIDE : 1;
td.mipmapLevelCount = LEVELS;
td.usage = MTLTextureUsageShaderRead;
td.storageMode = MTLStorageModePrivate;
id<MTLTexture> tex = [dev newTextureWithDescriptor:td];
if (!tex) {
printf("RESULT %s %s: no texture\n", f.name, f.volume ? "3d" : "2d");
continue;
}
printf("FORM %s %s: a texture of %lu levels\n", f.name, f.volume ? "3d" : "2d",
(unsigned long)tex.mipmapLevelCount);
// Each level's random texels, through a buffer.
id<MTLCommandBuffer> cb = [q commandBuffer];
id<MTLBlitCommandEncoder> bl = [cb blitCommandEncoder];
for (int l = 0; l < LEVELS; l++) {
NSUInteger w = SIDE >> l, d = f.volume ? w : 1, n = w * w * d;
NSUInteger row = w * (NSUInteger)f.bytes;
uint8_t *bytes = malloc(n * f.bytes);
for (NSUInteger t = 0; t < n; t++) texel(&f, bytes + t * f.bytes);
id<MTLBuffer> src = [dev newBufferWithBytes:bytes length:n * f.bytes options:MTLResourceStorageModeShared];
free(bytes);
[bl copyFromBuffer:src
sourceOffset:0
sourceBytesPerRow:row
sourceBytesPerImage:row * w
sourceSize:MTLSizeMake(w, w, d)
toTexture:tex
destinationSlice:0
destinationLevel:l
destinationOrigin:MTLOriginMake(0, 0, 0)];
}
[bl endEncoding];
[cb commit];
[cb waitUntilCompleted];
for (int linear = 0; linear < 2; linear++) {
// The points, and the same points at the level below and above.
float *pts = calloc(POINTS * 4 * 4, sizeof(float));
for (int i = 0; i < POINTS; i++) {
float *p = pts + 4 * i;
for (int c = 0; c < 3; c++) p[c] = unit() * 1.3f - 0.15f;
int l0 = (int)(r32() % 4);
float frac;
uint32_t pick = r32() % 4;
int k = 1 + (int)(r32() % 63);
if (pick == 0) {
frac = (float)k / 64.0f;
} else if (pick == 1) {
frac = nextafterf((float)k / 64.0f, (r32() & 1) ? 1.0f : 0.0f);
} else {
frac = unit();
if (frac == 0.0f) frac = 0.5f;
}
p[3] = (float)l0 + frac;
memcpy(pts + 4 * (POINTS + i), p, 16);
memcpy(pts + 4 * (2 * POINTS + i), p, 16);
memcpy(pts + 4 * (3 * POINTS + i), p, 16);
pts[4 * (POINTS + i) + 3] = (float)l0;
pts[4 * (2 * POINTS + i) + 3] = (float)(l0 + 1);
}
id<MTLBuffer> pb = [dev newBufferWithBytes:pts length:POINTS * 64 options:MTLResourceStorageModeShared];
id<MTLBuffer> ob = [dev newBufferWithLength:POINTS * 64 options:MTLResourceStorageModeShared];
id<MTLSamplerState> ss[2];
for (int mip = 0; mip < 2; mip++) {
MTLSamplerDescriptor *sd = [MTLSamplerDescriptor new];
sd.minFilter = sd.magFilter = linear ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
sd.mipFilter = mip ? MTLSamplerMipFilterNearest : MTLSamplerMipFilterLinear;
sd.sAddressMode = sd.tAddressMode = sd.rAddressMode = MTLSamplerAddressModeClampToEdge;
ss[mip] = [dev newSamplerStateWithDescriptor:sd];
}
cb = [q commandBuffer];
id<MTLComputeCommandEncoder> en = [cb computeCommandEncoder];
[en setComputePipelineState:f.volume ? k3 : k2];
[en setTexture:tex atIndex:0];
for (int part = 0; part < 4; part++) {
[en setSamplerState:ss[part == 0 ? 0 : 1] atIndex:0];
[en setBuffer:pb offset:part * POINTS * 16 atIndex:0];
[en setBuffer:ob offset:part * POINTS * 16 atIndex:1];
[en dispatchThreads:MTLSizeMake(POINTS, 1, 1) threadsPerThreadgroup:MTLSizeMake(64, 1, 1)];
}
[en endEncoding];
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted) {
printf("RESULT %s: command buffer status %ld\n", f.name, (long)cb.status);
return 1;
}
const float *o = ob.contents;
long lanes = 0, rule = 0, ulp = 0, lower = 0, upper = 0, unrounded = 0, flat = 0, nearest = 0;
double maxd = 0, maxrel = 0;
int shown = 0;
for (int i = 0; i < POINTS; i++) {
float frac = pts[4 * i + 3] - floorf(pts[4 * i + 3]);
float w = floorf(frac * 64.0f) / 64.0f;
for (int c = 0; c < 4; c++) {
float x = o[4 * i + c], a = o[4 * (POINTS + i) + c], b = o[4 * (2 * POINTS + i) + c];
nearest += x == o[4 * (3 * POINTS + i) + c] && a != b;
if (isnan(x) || isnan(a) || isnan(b)) continue;
lanes++;
float one = 1.0f - w;
float pa = a * one;
float pb2 = b * w;
float m = pa + pb2;
float mu = (float)((double)a + ((double)b - (double)a) * (double)frac);
if (a == b) flat++;
rule += x == m;
ulp += fabsf(x - m) <= fabsf(nextafterf(m, INFINITY) - m);
lower += x == a && a != b;
upper += x == b && a != b;
unrounded += x == mu;
double d = fabs((double)x - (double)m);
if (d > maxd) maxd = d;
if (a != b) {
double rel = d / fabs((double)b - (double)a);
if (rel > maxrel) maxrel = rel;
}
if (x != m && shown < 4) {
shown++;
printf(" %s %s point (%.6g %.6g %.6g) level %.9g lane %d: %.9g, rule %.9g (levels %.9g %.9g, w %.6g)\n",
f.name, linear ? "linear" : "nearest", pts[4 * i], pts[4 * i + 1], pts[4 * i + 2],
pts[4 * i + 3], c, x, m, a, b, w);
}
}
}
printf("RESULT %s %s %s: %ld lanes (%ld of equal levels); the rule %ld, within an f32 step %ld; "
"the lower level %ld, the upper %ld, the nearest mip filter's at the level %ld (of unequal levels); "
"the unrounded fraction %ld; largest distance %.3g (%.4g of the levels' difference)\n",
f.name, f.volume ? "3d" : "2d", linear ? "linear" : "nearest", lanes, flat, rule, ulp, lower,
upper, nearest, unrounded, maxd, maxrel);
free(pts);
}
}
}
return 0;
}
@@ -0,0 +1,156 @@
// What an imageblock slice write holds, in a partial threadgroup of a dispatchThreads grid, for
// the cells of the threads past the grid.
//
// The kernel has an explicit imageblock of one float4 per cell. Each thread stores
// (gx, gy, 7, 9) in its cell, gx and gy being its position in the grid, then a threadgroup
// barrier on imageblock memory. Then the thread at local (0, 0) writes the slice of that field
// (the imageblock's whole 8 by 8 extent, set with setImageblockWidth:height:) at its
// threadgroup's origin in an RGBA32Float texture. The grid is 21 by 13 threads in 8 by 8
// threadgroups, so three kinds of edge group are partial: in x (groups (2, 0)), in y ((0, 1)
// and (1, 1)), and in the corner ((2, 1)). The texture is 24 by 16, so every slice lies inside
// it. Before each dispatch every texel is set to a sentinel. Each run makes two dispatches into
// two textures, the first with sentinel (-1, -1, -1, -1) and the second with (-2, -2, -2, -2),
// and prints, for each kind of edge, how many of the cells past the grid hold:
//
// sentinel the texel as it was before the dispatch (the cell not written)
// as-if-ran (gx, gy, 7, 9) for the cell's own position (as if the thread had run)
// pattern (x, y, 7, 9) of another grid position (a cell some other thread stored)
// zero (0, 0, 0, 0)
// other anything else
//
// plus a hash of those texels, so that runs can be compared. It also counts the texels of grid
// threads that do not hold their own (gx, gy, 7, 9).
//
// xcrun clang -fobjc-arc -framework Metal -framework Foundation \
// -o imageblock_slice_past_the_grid imageblock_slice_past_the_grid.m
// ./imageblock_slice_past_the_grid; ./imageblock_slice_past_the_grid
//
// WHAT IT MEASURED: see the commit that added this probe, with the run it came from.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <string.h>
static NSString *const SOURCE =
@"#include <metal_stdlib>\n"
"using namespace metal;\n"
"struct Cell { float4 colour; };\n"
"kernel void slice_past_the_grid(imageblock<Cell, imageblock_layout_explicit> block,\n"
" texture2d<float, access::write> out [[texture(0)]],\n"
" ushort2 lid [[thread_position_in_threadgroup]],\n"
" ushort2 tgp [[threadgroup_position_in_grid]],\n"
" ushort2 gid [[thread_position_in_grid]]) {\n"
" threadgroup_imageblock Cell *cell = block.data(lid);\n"
" cell->colour = float4(float(gid.x), float(gid.y), 7.0, 9.0);\n"
" threadgroup_barrier(mem_flags::mem_threadgroup_imageblock);\n"
" if (lid.x == 0 && lid.y == 0) {\n"
" out.write(block.slice(block.data(ushort2(0))->colour), tgp * ushort2(8));\n"
" }\n"
"}\n";
enum { GRID_W = 21, GRID_H = 13, TEX_W = 24, TEX_H = 16, GROUP = 8 };
static const char *edge_of(int x, int y) {
BOOL past_x = x >= GRID_W, past_y = y >= GRID_H;
int gx = x / GROUP, gy = y / GROUP;
BOOL edge_x = gx == (GRID_W - 1) / GROUP, edge_y = gy == (GRID_H - 1) / GROUP;
if (!past_x && !past_y) return NULL;
if (edge_x && edge_y) return "corner";
return past_x ? "x-edge" : "y-edge";
}
static void report(id<MTLDevice> device, id<MTLComputePipelineState> state,
id<MTLCommandQueue> queue, float sentinel) {
MTLTextureDescriptor *d =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float
width:TEX_W
height:TEX_H
mipmapped:NO];
d.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead;
d.storageMode = MTLStorageModeShared;
id<MTLTexture> tex = [device newTextureWithDescriptor:d];
static float texels[TEX_H][TEX_W][4];
for (int y = 0; y < TEX_H; y++)
for (int x = 0; x < TEX_W; x++)
for (int c = 0; c < 4; c++) texels[y][x][c] = sentinel;
MTLRegion all = MTLRegionMake2D(0, 0, TEX_W, TEX_H);
[tex replaceRegion:all mipmapLevel:0 withBytes:texels bytesPerRow:TEX_W * 16];
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLComputeCommandEncoder> encoder = [cb computeCommandEncoder];
[encoder setComputePipelineState:state];
[encoder setTexture:tex atIndex:0];
[encoder setImageblockWidth:GROUP height:GROUP];
[encoder dispatchThreads:MTLSizeMake(GRID_W, GRID_H, 1)
threadsPerThreadgroup:MTLSizeMake(GROUP, GROUP, 1)];
[encoder endEncoding];
[cb commit];
[cb waitUntilCompleted];
memset(texels, 0, sizeof texels);
[tex getBytes:texels bytesPerRow:TEX_W * 16 fromRegion:all mipmapLevel:0];
const char *edges[3] = {"x-edge", "y-edge", "corner"};
int wrong_grid = 0;
for (int y = 0; y < TEX_H; y++)
for (int x = 0; x < TEX_W; x++) {
const float *t = texels[y][x];
if (!edge_of(x, y) &&
!(t[0] == x && t[1] == y && t[2] == 7.0f && t[3] == 9.0f))
wrong_grid++;
}
printf("sentinel %g, status %ld%s%s, grid texels not their own: %d\n", sentinel,
(long)cb.status, cb.error ? ", error " : "",
cb.error ? cb.error.localizedDescription.UTF8String : "", wrong_grid);
for (int e = 0; e < 3; e++) {
int cells = 0, kept = 0, ran = 0, pattern = 0, zero = 0, other = 0;
uint64_t hash = 1469598103934665603ull;
for (int y = 0; y < TEX_H; y++)
for (int x = 0; x < TEX_W; x++) {
const char *edge = edge_of(x, y);
if (!edge || strcmp(edge, edges[e]) != 0) continue;
const float *t = texels[y][x];
cells++;
if (t[0] == sentinel && t[1] == sentinel && t[2] == sentinel && t[3] == sentinel)
kept++;
else if (t[0] == x && t[1] == y && t[2] == 7.0f && t[3] == 9.0f)
ran++;
else if (t[2] == 7.0f && t[3] == 9.0f && t[0] >= 0 && t[0] < GRID_W &&
t[1] >= 0 && t[1] < GRID_H)
pattern++;
else if (t[0] == 0 && t[1] == 0 && t[2] == 0 && t[3] == 0)
zero++;
else
other++;
const unsigned char *b = (const unsigned char *)t;
for (int i = 0; i < 16; i++) hash = (hash ^ b[i]) * 1099511628211ull;
}
printf(" %s: %d cells past the grid: sentinel %d, as-if-ran %d, pattern %d, zero %d, "
"other %d; hash %016llx\n",
edges[e], cells, kept, ran, pattern, zero, other, (unsigned long long)hash);
}
}
int main(void) {
@autoreleasepool {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
NSError *error = nil;
id<MTLLibrary> library = [device newLibraryWithSource:SOURCE
options:[MTLCompileOptions new]
error:&error];
if (!library) {
printf("library: %s\n", error.localizedDescription.UTF8String);
return 2;
}
id<MTLComputePipelineState> state = [device
newComputePipelineStateWithFunction:[library newFunctionWithName:@"slice_past_the_grid"]
error:&error];
if (!state) {
printf("state: %s\n", error.localizedDescription.UTF8String);
return 2;
}
printf("%s, maxTotalThreadsPerThreadgroup %lu\n", device.name.UTF8String,
(unsigned long)state.maxTotalThreadsPerThreadgroup);
id<MTLCommandQueue> queue = [device newCommandQueue];
report(device, state, queue, -1.0f);
report(device, state, queue, -2.0f);
}
return 0;
}
@@ -0,0 +1,667 @@
// Whether a Metal blit copy gives the source's bytes from before the copy where its source and its
// destination are two resources over one memory: a texture placed in a placement heap and another
// resource of the heap placed over its bytes, and an IOSurface plane's texture and a no-copy buffer
// over the surface's own bytes.
//
// The runtime refuses the first (`Gap::OverlappingCopy`: a heap texture's texels lie as the device
// chooses, so no cut of Vulkan copy commands keeps one command's source and destination apart),
// and copies the second a row at a time from the source as it was before the copy. MTLHeap.h of a
// placement heap's resources: "Any resources that exist in this heap at overlapping half-open
// range [offset, offset + requiredSize) are implicitly aliased with the new resource."
//
// Cases, one a process, ROUNDS (8) rounds each, each round with words of its own:
//
// heap-<mode>-b2t a buffer and a 64x64 RGBA8Unorm texture, both at offset 0 of a placement
// heap: the buffer is written (a blit from a Shared buffer), then copied
// whole into the texture, which is then read out
// heap-<mode>-t2b the texture is written, then copied whole into the buffer, which is read out
// heap-<mode>-t2t two such textures at offset 0: the first is written, then copied whole into
// the second, which is read out
// heap-private-<shape>-apart
// controls: the second resource placed past the first's bytes
// tex-shift two such textures in a Private placement heap, the second one texture
// alignment on: `copyFromTexture:toTexture:` from the first to the second
// tex-half the second half the texture's bytes on (rounded up to the alignment)
// tex-region both at 0: the region method (`copyFromTexture:sourceSlice:...`) over the
// whole level
// tex-region-half the region method over the whole level, the second half the bytes on
// tex-region-part both at 0: the region method, texels (0, 0) to (31, 31) into (32, 32)
// tex-inplace-to a heap texture at 0 and a linear texture over a heap buffer at 0
// (`newTextureWithDescriptor:offset:bytesPerRow:`): `copyFromTexture:toTexture:`
// from the heap texture to the linear one
// tex-inplace-from the same, from the linear texture to the heap texture
// buf-alias-<way>-<n>
// two buffers at offset 0 of a Private placement heap, 64 KiB and 4 KiB more
// each: `copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:` of
// 64 KiB from the first to the second, the destination <n> bytes past the
// source (`up`) or the source <n> bytes past the destination (`down`)
// buf-one-up-4 control: one such buffer into itself, the destination 4 bytes past the
// source, which Apple's page for the copy allows only where the size is less
// than the offsets' distance
// surface-in-up a 64x16 BGRA8Unorm IOSurface's plane texture and a no-copy buffer over the
// surface's bytes: buffer rows 1-15 into texture rows 0-14
// surface-in-down buffer rows 0-14 into texture rows 1-15
// surface-in-right texels 0-55 of each buffer row into texels 8-63 of the texture's
// surface-out-up texture rows 1-15 into buffer rows 0-14
// surface-out-down texture rows 0-14 into buffer rows 1-15
// surface-out-right texels 0-55 of each texture row into texels 8-63 of the buffer's
//
// <mode> is the heap's storage mode, `private` or `shared`. Every resource is tracked. Each step is
// a command buffer of its own, waited for, so the copy is one blit command alone.
//
// Each heap round prints how many of the destination's 32-bit words hold the source's word from
// before the copy ("source") and how many do not ("other"), with the destination's FNV-1a 64. Each
// surface round prints, over the destination region, how many words hold the source's word from
// before the copy ("source"), the word a copy of texels in place front to back would leave
// ("forward"), back to front ("backward"), or none of them ("other"), and how many words outside
// the region changed ("outside"). Each case ends with `SUMMARY <case> whole <n> of <ROUNDS>`: the
// rounds whose every destination word was the source's.
//
// xcrun clang -O2 -fobjc-arc -framework Metal -framework Foundation -framework IOSurface \
// -o overlapping_alias_copies overlapping_alias_copies.m
// for c in $(./overlapping_alias_copies --list); do
// ./overlapping_alias_copies $c; MTL_DEBUG_LAYER=1 ./overlapping_alias_copies $c
// done
//
// Every case prints `DEVICE <name> / RELEASE <os>`, then `CASE <case>`, `READ` lines, and `DONE
// <case>`. A case whose process Metal ends prints no `DONE`, and its exit status is the reading.
//
// WHAT IT MEASURED: on an Apple M3 Max, macOS 27.0.1 (26A434), jobs m3-max-81486 (heap-*,
// surface-*) and m3-max-81493 (tex-*). The texture's heap footprint was 16512 bytes at an
// alignment of 128.
//
// - With the API validation off, every case gave the source's words from before the copy in 8 of
// 8 rounds, including the aliases at 0, 128 and 8320 bytes apart. The surface cases also left
// no word outside the region changed.
// - With MTL_DEBUG_LAYER=1, these cases end the process (status 134) at the copy:
// - heap-{private,shared}-{b2t,t2b}, tex-region, tex-region-half and tex-region-part:
// "validateResourceAliasing:332: failed assertion `blitting between aliasing resources is
// defined on a placement heap only when using a blit method copying entire texture surfaces,
// or when copying between buffers.'"
// - tex-inplace-to and tex-inplace-from: "validateResourceAliasing:332: failed assertion
// `blitting between aliasing resources is defined on a placement heap only when both textures
// are linear and have the same bufferBytesPerRow value.'"
// - Under validation, the other cases run to the end with the same words: heap-*-t2t, tex-shift
// and tex-half (copyFromTexture:toTexture:), the -apart controls, and every surface-* case.
// - Job m3-max-81544 (buf-*): with the API validation off, every case gave memmove's bytes in 8 of
// 8 rounds, buf-one-up-4 too. With MTL_DEBUG_LAYER=1, buf-one-up-4 runs to the end with the same
// bytes, and every buf-alias-* case ends the process (status 134) inside the layer's own
// aliasing check, "-[MTLDebugBuffer width]: unrecognized selector sent to instance",
// from `validateResourceAliasing` under `-[MTLDebugBlitCommandEncoder
// copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:]`: the layer's fault, not a
// refusal; its assertion text above names copies between buffers among the defined ones.
#import <Foundation/Foundation.h>
#import <IOSurface/IOSurface.h>
#import <Metal/Metal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
enum {
ROUNDS = 8,
SIDE = 64,
ROW = SIDE * 4,
TEXELS = SIDE * SIDE,
SURFACE_WIDTH = 64,
SURFACE_HEIGHT = 16,
SURFACE_PITCH = 256,
SHIFT = 8,
};
static id<MTLDevice> gDevice = nil;
static id<MTLCommandQueue> gQueue = nil;
static const char *kCases[] = {
"heap-private-b2t", "heap-private-t2b", "heap-private-t2t",
"heap-shared-b2t", "heap-shared-t2b", "heap-shared-t2t",
"heap-private-b2t-apart", "heap-private-t2b-apart", "heap-private-t2t-apart",
"tex-shift", "tex-half", "tex-region",
"tex-region-half", "tex-region-part", "tex-inplace-to",
"tex-inplace-from",
"buf-alias-up-4", "buf-alias-down-4", "buf-alias-up-4096",
"buf-alias-down-4096", "buf-one-up-4",
"surface-in-up", "surface-in-down", "surface-in-right",
"surface-out-up", "surface-out-down", "surface-out-right",
};
static NSUInteger round_up(NSUInteger value, NSUInteger multiple) {
return (value + multiple - 1) / multiple * multiple;
}
static uint64_t fnv(const uint8_t *bytes, size_t len) {
uint64_t h = 0xcbf29ce484222325ull;
for (size_t i = 0; i < len; i++) {
h ^= bytes[i];
h *= 0x100000001b3ull;
}
return h;
}
/// Commits `cb`, waits for it, and prints its status where it did not complete.
static void run(id<MTLCommandBuffer> cb, const char *step) {
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted) {
printf("READ step %s status %ld error %s\n", step, (long)cb.status,
cb.error ? cb.error.localizedDescription.UTF8String : "none");
fflush(stdout);
}
}
// ---- heap cases ----------------------------------------------------------------------------
static int heap_case(MTLStorageMode mode, const char *shape, BOOL apart, const char *name) {
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:SIDE
height:SIDE
mipmapped:NO];
td.usage = MTLTextureUsageShaderRead;
td.storageMode = mode;
td.hazardTrackingMode = MTLHazardTrackingModeTracked;
MTLResourceOptions bo =
(mode == MTLStorageModePrivate ? MTLResourceStorageModePrivate
: MTLResourceStorageModeShared) |
MTLResourceHazardTrackingModeTracked;
MTLSizeAndAlign ts = [gDevice heapTextureSizeAndAlignWithDescriptor:td];
NSUInteger blen = ts.size;
MTLSizeAndAlign bs = [gDevice heapBufferSizeAndAlignWithLength:blen options:bo];
NSUInteger align = MAX(ts.align, bs.align);
NSUInteger span = MAX(ts.size, bs.size);
NSUInteger second = apart ? round_up(span, align) : 0;
printf("READ texture_size %lu texture_align %lu buffer_size %lu buffer_align %lu second_at %lu\n",
(unsigned long)ts.size, (unsigned long)ts.align, (unsigned long)bs.size,
(unsigned long)bs.align, (unsigned long)second);
MTLHeapDescriptor *hd = [MTLHeapDescriptor new];
hd.type = MTLHeapTypePlacement;
hd.storageMode = mode;
hd.hazardTrackingMode = MTLHazardTrackingModeTracked;
hd.size = round_up(second + span, 1u << 16) + (1u << 16);
id<MTLHeap> heap = [gDevice newHeapWithDescriptor:hd];
if (!heap) {
printf("READ heap nil\n");
return 2;
}
BOOL b2t = strcmp(shape, "b2t") == 0, t2b = strcmp(shape, "t2b") == 0;
BOOL t2t = strcmp(shape, "t2t") == 0;
// The first resource at 0, the second at `second`: the texture first for t2b and t2t, the
// buffer first for b2t.
id<MTLTexture> texture = [heap newTextureWithDescriptor:td offset:(b2t ? second : 0)];
id<MTLBuffer> buffer =
(b2t || t2b) ? [heap newBufferWithLength:blen options:bo offset:(b2t ? 0 : second)] : nil;
id<MTLTexture> texture2 = t2t ? [heap newTextureWithDescriptor:td offset:second] : nil;
if (!texture || ((b2t || t2b) && !buffer) || (t2t && !texture2)) {
printf("READ resource nil texture %d buffer %d texture2 %d\n", texture != nil,
buffer != nil, texture2 != nil);
return 2;
}
id<MTLBuffer> src = [gDevice newBufferWithLength:TEXELS * 4 options:MTLResourceStorageModeShared];
id<MTLBuffer> out = [gDevice newBufferWithLength:TEXELS * 4 options:MTLResourceStorageModeShared];
MTLSize whole = MTLSizeMake(SIDE, SIDE, 1);
MTLOrigin zero = MTLOriginMake(0, 0, 0);
int wholeRounds = 0;
for (uint32_t round = 0; round < ROUNDS; round++) {
uint32_t *words = (uint32_t *)src.contents;
for (uint32_t i = 0; i < TEXELS; i++) words[i] = 0x80000000u | (round << 16) | i;
memset(out.contents, 0xEE, TEXELS * 4);
id<MTLCommandBuffer> cb = [gQueue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
if (b2t) {
[blit copyFromBuffer:src sourceOffset:0 toBuffer:buffer destinationOffset:0
size:TEXELS * 4];
} else {
[blit copyFromBuffer:src sourceOffset:0 sourceBytesPerRow:ROW
sourceBytesPerImage:ROW * SIDE sourceSize:whole toTexture:texture
destinationSlice:0 destinationLevel:0 destinationOrigin:zero];
}
[blit endEncoding];
run(cb, "write");
cb = [gQueue commandBuffer];
blit = [cb blitCommandEncoder];
if (b2t) {
[blit copyFromBuffer:buffer sourceOffset:0 sourceBytesPerRow:ROW
sourceBytesPerImage:ROW * SIDE sourceSize:whole toTexture:texture
destinationSlice:0 destinationLevel:0 destinationOrigin:zero];
} else if (t2b) {
[blit copyFromTexture:texture sourceSlice:0 sourceLevel:0 sourceOrigin:zero
sourceSize:whole toBuffer:buffer destinationOffset:0
destinationBytesPerRow:ROW destinationBytesPerImage:ROW * SIDE];
} else {
[blit copyFromTexture:texture toTexture:texture2];
}
[blit endEncoding];
run(cb, "copy");
cb = [gQueue commandBuffer];
blit = [cb blitCommandEncoder];
if (t2b) {
[blit copyFromBuffer:buffer sourceOffset:0 toBuffer:out destinationOffset:0
size:TEXELS * 4];
} else {
[blit copyFromTexture:(b2t ? texture : texture2) sourceSlice:0 sourceLevel:0
sourceOrigin:zero sourceSize:whole toBuffer:out destinationOffset:0
destinationBytesPerRow:ROW destinationBytesPerImage:ROW * SIDE];
}
[blit endEncoding];
run(cb, "read");
const uint32_t *got = (const uint32_t *)out.contents;
int source = 0, other = 0, first = -1;
for (int i = 0; i < TEXELS; i++) {
if (got[i] == words[i]) {
source++;
} else {
other++;
if (first < 0) first = i;
}
}
printf("READ %s round %u source %d other %d", name, round, source, other);
if (first >= 0) printf(" first_other %d word 0x%08x", first, got[first]);
printf(" fnv %016llx\n", (unsigned long long)fnv(out.contents, TEXELS * 4));
fflush(stdout);
if (other == 0) wholeRounds++;
}
printf("SUMMARY %s whole %d of %d\n", name, wholeRounds, ROUNDS);
return 0;
}
// ---- texture to texture in a Private placement heap ---------------------------------------
/// How a `tex-*` case copies: `copyFromTexture:toTexture:` (`WHOLE`), or the region method over
/// the whole level (`REGION_WHOLE`) or over its 32 x 32 texels at (0, 0) into (32, 32)
/// (`REGION_PART`).
typedef enum { WHOLE, REGION_WHOLE, REGION_PART } Method;
/// The second texture at `at` (`0`, `1` the texture alignment, `2` half the texture's bytes rounded
/// up to it); `inPlace` 1 where the destination, 2 where the source, is a linear texture over a heap
/// buffer at offset 0 (`newTextureWithDescriptor:offset:bytesPerRow:`) instead of a heap texture.
static int tex_case(int at, Method method, int inPlace, const char *name) {
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:SIDE
height:SIDE
mipmapped:NO];
td.usage = MTLTextureUsageShaderRead;
td.storageMode = MTLStorageModePrivate;
td.hazardTrackingMode = MTLHazardTrackingModeTracked;
MTLResourceOptions bo = MTLResourceStorageModePrivate | MTLResourceHazardTrackingModeTracked;
MTLSizeAndAlign ts = [gDevice heapTextureSizeAndAlignWithDescriptor:td];
NSUInteger second = at == 0 ? 0 : at == 1 ? ts.align : round_up(ts.size / 2, ts.align);
printf("READ texture_size %lu texture_align %lu second_at %lu linear_align %lu\n",
(unsigned long)ts.size, (unsigned long)ts.align, (unsigned long)second,
(unsigned long)[gDevice minimumLinearTextureAlignmentForPixelFormat:td.pixelFormat]);
MTLHeapDescriptor *hd = [MTLHeapDescriptor new];
hd.type = MTLHeapTypePlacement;
hd.storageMode = MTLStorageModePrivate;
hd.hazardTrackingMode = MTLHazardTrackingModeTracked;
hd.size = round_up(second + ts.size, 1u << 16) + (1u << 16);
id<MTLHeap> heap = [gDevice newHeapWithDescriptor:hd];
id<MTLTexture> first = [heap newTextureWithDescriptor:td offset:0];
id<MTLTexture> other = nil;
id<MTLBuffer> under = nil;
if (inPlace) {
under = [heap newBufferWithLength:ts.size options:bo offset:second];
other = [under newTextureWithDescriptor:td offset:0 bytesPerRow:ROW];
} else {
other = [heap newTextureWithDescriptor:td offset:second];
}
if (!heap || !first || !other) {
printf("READ resource nil heap %d first %d other %d\n", heap != nil, first != nil,
other != nil);
return 2;
}
id<MTLTexture> source = inPlace == 2 ? other : first;
id<MTLTexture> destination = inPlace == 2 ? first : other;
id<MTLBuffer> src = [gDevice newBufferWithLength:TEXELS * 4 options:MTLResourceStorageModeShared];
id<MTLBuffer> out = [gDevice newBufferWithLength:TEXELS * 4 options:MTLResourceStorageModeShared];
MTLSize whole = MTLSizeMake(SIDE, SIDE, 1);
MTLOrigin zero = MTLOriginMake(0, 0, 0);
int half = SIDE / 2, wholeRounds = 0;
for (uint32_t round = 0; round < ROUNDS; round++) {
uint32_t *words = (uint32_t *)src.contents;
for (uint32_t i = 0; i < TEXELS; i++) words[i] = 0x80000000u | (round << 16) | i;
memset(out.contents, 0xEE, TEXELS * 4);
id<MTLCommandBuffer> cb = [gQueue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit copyFromBuffer:src sourceOffset:0 sourceBytesPerRow:ROW
sourceBytesPerImage:ROW * SIDE sourceSize:whole toTexture:source
destinationSlice:0 destinationLevel:0 destinationOrigin:zero];
[blit endEncoding];
run(cb, "write");
cb = [gQueue commandBuffer];
blit = [cb blitCommandEncoder];
if (method == WHOLE) {
[blit copyFromTexture:source toTexture:destination];
} else {
BOOL part = method == REGION_PART;
[blit copyFromTexture:source sourceSlice:0 sourceLevel:0 sourceOrigin:zero
sourceSize:(part ? MTLSizeMake(half, half, 1) : whole)
toTexture:destination destinationSlice:0 destinationLevel:0
destinationOrigin:(part ? MTLOriginMake(half, half, 0) : zero)];
}
[blit endEncoding];
run(cb, "copy");
cb = [gQueue commandBuffer];
blit = [cb blitCommandEncoder];
[blit copyFromTexture:destination sourceSlice:0 sourceLevel:0 sourceOrigin:zero
sourceSize:whole toBuffer:out destinationOffset:0
destinationBytesPerRow:ROW destinationBytesPerImage:ROW * SIDE];
[blit endEncoding];
run(cb, "read");
const uint32_t *got = (const uint32_t *)out.contents;
int source_words = 0, other_words = 0, region = 0, firstOther = -1;
for (int y = 0; y < SIDE; y++) {
for (int x = 0; x < SIDE; x++) {
int i = y * SIDE + x, from = i;
if (method == REGION_PART) {
if (x < half || y < half) continue;
from = (y - half) * SIDE + (x - half);
}
region++;
if (got[i] == words[from]) {
source_words++;
} else {
other_words++;
if (firstOther < 0) firstOther = i;
}
}
}
printf("READ %s round %u region %d source %d other %d", name, round, region, source_words,
other_words);
if (firstOther >= 0) printf(" first_other %d word 0x%08x", firstOther, got[firstOther]);
printf(" fnv %016llx\n", (unsigned long long)fnv(out.contents, TEXELS * 4));
fflush(stdout);
if (other_words == 0) wholeRounds++;
}
printf("SUMMARY %s whole %d of %d\n", name, wholeRounds, ROUNDS);
return 0;
}
// ---- buffer to buffer in a Private placement heap ------------------------------------------
/// A copy of 64 KiB between two buffers at offset 0 of a placement heap (one buffer where `one`),
/// the destination `shift` bytes past the source (before it where negative). A third buffer over
/// the same bytes writes them first and reads them after; each round prints how many of the bytes
/// the copy's two ranges cover hold memmove's answer ("source") and how many do not ("other").
static int buf_case(long shift, BOOL one, const char *name) {
enum { SIZE = 64 << 10, MORE = 4 << 10, SPAN = SIZE + MORE };
MTLResourceOptions bo = MTLResourceStorageModePrivate | MTLResourceHazardTrackingModeTracked;
MTLSizeAndAlign bs = [gDevice heapBufferSizeAndAlignWithLength:SPAN options:bo];
printf("READ buffer_size %lu buffer_align %lu\n", (unsigned long)bs.size,
(unsigned long)bs.align);
MTLHeapDescriptor *hd = [MTLHeapDescriptor new];
hd.type = MTLHeapTypePlacement;
hd.storageMode = MTLStorageModePrivate;
hd.hazardTrackingMode = MTLHazardTrackingModeTracked;
hd.size = round_up(bs.size, 1u << 16) + (1u << 16);
id<MTLHeap> heap = [gDevice newHeapWithDescriptor:hd];
id<MTLBuffer> whole = [heap newBufferWithLength:SPAN options:bo offset:0];
id<MTLBuffer> first = [heap newBufferWithLength:SPAN options:bo offset:0];
id<MTLBuffer> second = one ? first : [heap newBufferWithLength:SPAN options:bo offset:0];
if (!heap || !whole || !first || !second) {
printf("READ resource nil\n");
return 2;
}
id<MTLBuffer> src = [gDevice newBufferWithLength:SPAN options:MTLResourceStorageModeShared];
id<MTLBuffer> out = [gDevice newBufferWithLength:SPAN options:MTLResourceStorageModeShared];
NSUInteger from = shift < 0 ? (NSUInteger)-shift : 0, to = shift < 0 ? 0 : (NSUInteger)shift;
uint8_t *want = malloc(SPAN);
int wholeRounds = 0;
for (uint32_t round = 0; round < ROUNDS; round++) {
uint8_t *bytes = (uint8_t *)src.contents;
for (uint32_t i = 0; i < SPAN; i++) bytes[i] = (uint8_t)(i * 131u + i / 251u + round * 17u);
memcpy(want, bytes, SPAN);
memmove(want + to, want + from, SIZE);
memset(out.contents, 0xEE, SPAN);
id<MTLCommandBuffer> cb = [gQueue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit copyFromBuffer:src sourceOffset:0 toBuffer:whole destinationOffset:0 size:SPAN];
[blit endEncoding];
run(cb, "write");
cb = [gQueue commandBuffer];
blit = [cb blitCommandEncoder];
[blit copyFromBuffer:first sourceOffset:from toBuffer:second destinationOffset:to size:SIZE];
[blit endEncoding];
run(cb, "copy");
cb = [gQueue commandBuffer];
blit = [cb blitCommandEncoder];
[blit copyFromBuffer:whole sourceOffset:0 toBuffer:out destinationOffset:0 size:SPAN];
[blit endEncoding];
run(cb, "read");
const uint8_t *got = (const uint8_t *)out.contents;
int source = 0, other = 0;
long firstOther = -1;
for (long i = 0; i < SPAN; i++) {
if (got[i] == want[i]) {
source++;
} else {
other++;
if (firstOther < 0) firstOther = i;
}
}
printf("READ %s round %u source %d other %d", name, round, source, other);
if (firstOther >= 0)
printf(" first_other %ld byte 0x%02x want 0x%02x", firstOther, got[firstOther],
want[firstOther]);
printf(" fnv %016llx\n", (unsigned long long)fnv(out.contents, SPAN));
fflush(stdout);
if (other == 0) wholeRounds++;
}
free(want);
printf("SUMMARY %s whole %d of %d\n", name, wholeRounds, ROUNDS);
return 0;
}
// ---- surface cases -------------------------------------------------------------------------
/// A copy of `w` by `h` texels from `(sx, sy)` to `(dx, dy)` on the plane's grid of words, done
/// in place one word at a time, front to back (`forward`) or back to front.
static void in_place(uint32_t *grid, int pitchWords, int sx, int sy, int dx, int dy, int w, int h,
BOOL forward) {
for (int k = 0; k < w * h; k++) {
int i = forward ? k : w * h - 1 - k;
int x = i % w, y = i / w;
grid[(dy + y) * pitchWords + dx + x] = grid[(sy + y) * pitchWords + sx + x];
}
}
static int surface_case(const char *shape, const char *name) {
NSDictionary *props = @{
(__bridge NSString *)kIOSurfaceWidth : @(SURFACE_WIDTH),
(__bridge NSString *)kIOSurfaceHeight : @(SURFACE_HEIGHT),
(__bridge NSString *)kIOSurfaceBytesPerElement : @4,
(__bridge NSString *)kIOSurfaceBytesPerRow : @(SURFACE_PITCH),
(__bridge NSString *)kIOSurfacePixelFormat : @((uint32_t)'BGRA'),
};
IOSurfaceRef surface = IOSurfaceCreate((__bridge CFDictionaryRef)props);
if (!surface) {
printf("READ surface nil\n");
return 2;
}
uint8_t *base = (uint8_t *)IOSurfaceGetBaseAddress(surface);
size_t alloc = IOSurfaceGetAllocSize(surface), pitch = IOSurfaceGetBytesPerRow(surface);
size_t page = (size_t)getpagesize();
printf("READ surface alloc %zu pitch %zu base_page_offset %zu page %zu\n", alloc, pitch,
(size_t)((uintptr_t)base % page), page);
if ((uintptr_t)base % page != 0 || pitch % 4 != 0) {
printf("READ skipped: the surface's bytes take no no-copy buffer\n");
return 2;
}
id<MTLBuffer> buffer = [gDevice
newBufferWithBytesNoCopy:base
length:round_up(alloc, page)
options:MTLResourceStorageModeShared | MTLResourceHazardTrackingModeTracked
deallocator:nil];
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:SURFACE_WIDTH
height:SURFACE_HEIGHT
mipmapped:NO];
td.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite;
td.storageMode = MTLStorageModeShared;
td.hazardTrackingMode = MTLHazardTrackingModeTracked;
id<MTLTexture> texture = [gDevice newTextureWithDescriptor:td iosurface:surface plane:0];
if (!buffer || !texture) {
printf("READ resource nil buffer %d texture %d\n", buffer != nil, texture != nil);
return 2;
}
BOOL into = strncmp(shape, "in-", 3) == 0;
const char *move = shape + (into ? 3 : 4);
int sx = 0, sy = 0, dx = 0, dy = 0, w = SURFACE_WIDTH, h = SURFACE_HEIGHT;
if (strcmp(move, "up") == 0) {
sy = 1;
h -= 1;
} else if (strcmp(move, "down") == 0) {
dy = 1;
h -= 1;
} else {
dx = SHIFT;
w -= SHIFT;
}
int pitchWords = (int)(pitch / 4);
size_t bytes = pitch * SURFACE_HEIGHT;
uint32_t *before = malloc(bytes), *expect = malloc(bytes), *forward = malloc(bytes),
*backward = malloc(bytes);
int wholeRounds = 0;
for (uint32_t round = 0; round < ROUNDS; round++) {
IOSurfaceLock(surface, 0, NULL);
uint32_t *grid = (uint32_t *)base;
for (int y = 0; y < SURFACE_HEIGHT; y++)
for (int x = 0; x < pitchWords; x++)
grid[y * pitchWords + x] = 0xC0000000u | (round << 16) | ((uint32_t)y << 8) |
(uint32_t)x;
memcpy(before, grid, bytes);
IOSurfaceUnlock(surface, 0, NULL);
memcpy(expect, before, bytes);
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
expect[(dy + y) * pitchWords + dx + x] = before[(sy + y) * pitchWords + sx + x];
memcpy(forward, before, bytes);
in_place(forward, pitchWords, sx, sy, dx, dy, w, h, YES);
memcpy(backward, before, bytes);
in_place(backward, pitchWords, sx, sy, dx, dy, w, h, NO);
id<MTLCommandBuffer> cb = [gQueue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
if (into) {
[blit copyFromBuffer:buffer sourceOffset:(NSUInteger)(sy * pitch + sx * 4)
sourceBytesPerRow:pitch sourceBytesPerImage:pitch * h
sourceSize:MTLSizeMake(w, h, 1) toTexture:texture destinationSlice:0
destinationLevel:0 destinationOrigin:MTLOriginMake(dx, dy, 0)];
} else {
[blit copyFromTexture:texture sourceSlice:0 sourceLevel:0
sourceOrigin:MTLOriginMake(sx, sy, 0) sourceSize:MTLSizeMake(w, h, 1)
toBuffer:buffer destinationOffset:(NSUInteger)(dy * pitch + dx * 4)
destinationBytesPerRow:pitch destinationBytesPerImage:pitch * h];
}
[blit endEncoding];
run(cb, "copy");
IOSurfaceLock(surface, kIOSurfaceLockReadOnly, NULL);
const uint32_t *got = (const uint32_t *)base;
int source = 0, fwd = 0, bwd = 0, other = 0, outside = 0, first = -1;
for (int y = 0; y < SURFACE_HEIGHT; y++) {
for (int x = 0; x < pitchWords; x++) {
int i = y * pitchWords + x;
BOOL inRegion = y >= dy && y < dy + h && x >= dx && x < dx + w;
if (!inRegion) {
outside += got[i] != before[i];
continue;
}
BOOL any = NO;
if (got[i] == expect[i]) source++, any = YES;
if (got[i] == forward[i]) fwd++, any = YES;
if (got[i] == backward[i]) bwd++, any = YES;
if (!any) {
other++;
if (first < 0) first = i;
}
}
}
printf("READ %s round %u region %d source %d forward %d backward %d other %d outside %d",
name, round, w * h, source, fwd, bwd, other, outside);
if (first >= 0) printf(" first_other %d word 0x%08x", first, got[first]);
printf("\n");
fflush(stdout);
if (source == w * h && outside == 0) wholeRounds++;
IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, NULL);
}
printf("SUMMARY %s whole %d of %d\n", name, wholeRounds, ROUNDS);
free(before);
free(expect);
free(forward);
free(backward);
CFRelease(surface);
return 0;
}
int main(int argc, char **argv) {
@autoreleasepool {
if (argc != 2) {
fprintf(stderr, "usage: %s <case> | --list\n", argv[0]);
return 64;
}
if (strcmp(argv[1], "--list") == 0) {
for (size_t i = 0; i < sizeof kCases / sizeof kCases[0]; i++) printf("%s\n", kCases[i]);
return 0;
}
const char *name = argv[1];
BOOL known = NO;
for (size_t i = 0; i < sizeof kCases / sizeof kCases[0]; i++)
known |= strcmp(kCases[i], name) == 0;
if (!known) {
fprintf(stderr, "unknown case %s\n", name);
return 64;
}
gDevice = MTLCreateSystemDefaultDevice();
gQueue = [gDevice newCommandQueue];
printf("DEVICE %s\n", gDevice.name.UTF8String);
printf("RELEASE macOS %s\n",
[NSProcessInfo processInfo].operatingSystemVersionString.UTF8String);
printf("CASE %s\n", name);
fflush(stdout);
int rc;
if (strncmp(name, "heap-", 5) == 0) {
MTLStorageMode mode = strncmp(name + 5, "private", 7) == 0 ? MTLStorageModePrivate
: MTLStorageModeShared;
const char *shape = name + 5 + (mode == MTLStorageModePrivate ? 8 : 7);
char base[8] = {0};
strncpy(base, shape, 3);
rc = heap_case(mode, base, strstr(shape, "-apart") != NULL, name);
} else if (strncmp(name, "buf-", 4) == 0) {
BOOL one = strncmp(name, "buf-one-", 8) == 0;
const char *way = name + (one ? 8 : 10);
BOOL up = strncmp(way, "up-", 3) == 0;
long n = atol(way + (up ? 3 : 5));
rc = buf_case(up ? n : -n, one, name);
} else if (strncmp(name, "tex-", 4) == 0) {
const char *t = name + 4;
if (strcmp(t, "shift") == 0) rc = tex_case(1, WHOLE, 0, name);
else if (strcmp(t, "half") == 0) rc = tex_case(2, WHOLE, 0, name);
else if (strcmp(t, "region") == 0) rc = tex_case(0, REGION_WHOLE, 0, name);
else if (strcmp(t, "region-half") == 0) rc = tex_case(2, REGION_WHOLE, 0, name);
else if (strcmp(t, "region-part") == 0) rc = tex_case(0, REGION_PART, 0, name);
else if (strcmp(t, "inplace-to") == 0) rc = tex_case(0, WHOLE, 1, name);
else rc = tex_case(0, WHOLE, 2, name);
} else {
rc = surface_case(name + 8, name);
}
printf("DONE %s\n", name);
fflush(stdout);
return rc;
}
}
@@ -114,7 +114,11 @@ static float *draw(NSString *fragment, MTLPixelFormat format, int targets, int s
height:side
mipmapped:NO];
td.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
td.storageMode = samples > 1 ? MTLStorageModePrivate : MTLStorageModeShared;
// A discrete GPU's Mac takes no Shared texture: there a single-sample attachment is Managed,
// and a blit synchronizes it before the CPU reads it.
td.storageMode = samples > 1 ? MTLStorageModePrivate
: gDevice.hasUnifiedMemory ? MTLStorageModeShared
: MTLStorageModeManaged;
td.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D;
td.sampleCount = samples;
id<MTLTexture> textures[8];
@@ -158,6 +162,11 @@ static float *draw(NSString *fragment, MTLPixelFormat format, int targets, int s
[ce endEncoding];
}
}
if (samples == 1 && !gDevice.hasUnifiedMemory) {
id<MTLBlitCommandEncoder> b = [cb blitCommandEncoder];
for (int i = 0; i < targets; i++) [b synchronizeResource:textures[i]];
[b endEncoding];
}
[cb commit];
[cb waitUntilCompleted];
if (cb.error) {
@@ -0,0 +1,158 @@
// Whether Metal's MultisampleResolve writes the resolve texture past the pass's render area
// (`renderTargetWidth` and `renderTargetHeight`), where the runtime's Vulkan render area is the
// Metal one rounded up to 32 texels a side.
//
// ONE CASE PER PROCESS, chosen on the command line, run once under MTL_DEBUG_LAYER=1 and once
// without it. The attachment is a 600x600 4-sample BGRA8Unorm colour texture (RenderTarget,
// Private); the resolve texture a 600x600 1-sample BGRA8Unorm 2D texture (RenderTarget |
// ShaderRead, Private), whose bytes a blit from a Shared buffer first sets to 0xee. A first pass
// over the whole 600x600 clears the attachment to (0.25, 0.5, 0.75, 1.0) and stores it. The
// case's pass draws nothing and resolves the attachment into the resolve texture
// (MultisampleResolve):
//
// load loads the attachment, render area 300x300
// clear clears the attachment to (1.0, 0.0, 0.0, 1.0), render area 300x300
// full loads the attachment, no render area set (the control: all 600x600 resolve)
//
// Read back by a blit into a Shared buffer (BGRA bytes, rows tight), the case prints the command
// buffers' status and error, and for three regions how many texels changed from 0xee: the area
// (x and y below 300), the band (x and y below 320, not in the area) and the rest (x or y at 320
// or past). It prints the texels at (0, 0), (310, 0), (0, 310), (310, 310), (330, 0) and
// (599, 599).
//
// xcrun clang -fobjc-arc -framework Metal -framework Foundation \
// -o resolve_band_past_render_area resolve_band_past_render_area.m
// for c in load clear full; do
// MTL_DEBUG_LAYER=1 ./resolve_band_past_render_area $c
// env -u MTL_DEBUG_LAYER ./resolve_band_past_render_area $c
// done
//
// WHAT IT MEASURED (Apple M3 Max, macOS 27.0.1, job m3-max-83924; the same with and without the
// layer, every command buffer completed without an error):
//
// load area 90000 of 90000, band 12400 of 12400, rest 0 of 257600 changed: the loaded
// clear (BGRA bf 80 40 ff) to 320 a side, 0xee past it
// clear every texel of all three regions changed, to the clear (BGRA 00 00 ff ff)
// full every texel of all three regions changed, to the loaded clear
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <string.h>
static const NSUInteger SIDE = 600;
static const NSUInteger AREA = 300;
static const NSUInteger BAND = 320;
static id<MTLTexture> texture(id<MTLDevice> device, NSUInteger samples, MTLTextureUsage usage) {
MTLTextureDescriptor *d = [MTLTextureDescriptor new];
d.textureType = samples > 1 ? MTLTextureType2DMultisample : MTLTextureType2D;
d.pixelFormat = MTLPixelFormatBGRA8Unorm;
d.width = SIDE;
d.height = SIDE;
d.sampleCount = samples;
d.usage = usage;
d.storageMode = MTLStorageModePrivate;
return [device newTextureWithDescriptor:d];
}
static void finish(const char *name, const char *what, id<MTLCommandBuffer> cb) {
[cb commit];
[cb waitUntilCompleted];
printf("%s: %s: status %ld, error %s\n", name, what, (long)cb.status,
cb.error ? cb.error.description.UTF8String : "none");
}
int main(int argc, const char **argv) {
@autoreleasepool {
if (argc != 2) {
printf("usage: resolve_band_past_render_area CASE\n");
return 2;
}
const char *name = argv[1];
BOOL load = strcmp(name, "load") == 0 || strcmp(name, "full") == 0;
BOOL area = strcmp(name, "full") != 0;
if (!load && strcmp(name, "clear") != 0) {
printf("no case %s\n", name);
return 2;
}
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
printf("%s: device %s\n", name, device.name.UTF8String);
id<MTLTexture> msaa = texture(device, 4, MTLTextureUsageRenderTarget);
id<MTLTexture> resolve =
texture(device, 1, MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead);
const NSUInteger row = SIDE * 4;
id<MTLBuffer> bytes = [device newBufferWithLength:row * SIDE
options:MTLResourceStorageModeShared];
memset(bytes.contents, 0xee, bytes.length);
id<MTLCommandQueue> queue = [device newCommandQueue];
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLBlitCommandEncoder> fill = [cb blitCommandEncoder];
[fill copyFromBuffer:bytes
sourceOffset:0
sourceBytesPerRow:row
sourceBytesPerImage:row * SIDE
sourceSize:MTLSizeMake(SIDE, SIDE, 1)
toTexture:resolve
destinationSlice:0
destinationLevel:0
destinationOrigin:MTLOriginMake(0, 0, 0)];
[fill endEncoding];
MTLRenderPassDescriptor *first = [MTLRenderPassDescriptor renderPassDescriptor];
first.colorAttachments[0].texture = msaa;
first.colorAttachments[0].loadAction = MTLLoadActionClear;
first.colorAttachments[0].storeAction = MTLStoreActionStore;
first.colorAttachments[0].clearColor = MTLClearColorMake(0.25, 0.5, 0.75, 1.0);
[[cb renderCommandEncoderWithDescriptor:first] endEncoding];
finish(name, "fill and first pass", cb);
cb = [queue commandBuffer];
MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];
pass.colorAttachments[0].texture = msaa;
pass.colorAttachments[0].resolveTexture = resolve;
pass.colorAttachments[0].loadAction = load ? MTLLoadActionLoad : MTLLoadActionClear;
pass.colorAttachments[0].clearColor = MTLClearColorMake(1.0, 0.0, 0.0, 1.0);
pass.colorAttachments[0].storeAction = MTLStoreActionMultisampleResolve;
if (area) {
pass.renderTargetWidth = AREA;
pass.renderTargetHeight = AREA;
}
id<MTLRenderCommandEncoder> encoder = [cb renderCommandEncoderWithDescriptor:pass];
printf("%s: encoder %s\n", name, encoder ? "made" : "not made");
[encoder endEncoding];
id<MTLBlitCommandEncoder> read = [cb blitCommandEncoder];
[read copyFromTexture:resolve
sourceSlice:0
sourceLevel:0
sourceOrigin:MTLOriginMake(0, 0, 0)
sourceSize:MTLSizeMake(SIDE, SIDE, 1)
toBuffer:bytes
destinationOffset:0
destinationBytesPerRow:row
destinationBytesPerImage:row * SIDE];
[read endEncoding];
finish(name, "case pass and read back", cb);
const uint8_t *texels = bytes.contents;
NSUInteger changed[3] = {0, 0, 0};
for (NSUInteger y = 0; y < SIDE; y++) {
for (NSUInteger x = 0; x < SIDE; x++) {
const uint8_t *t = texels + y * row + x * 4;
BOOL kept = t[0] == 0xee && t[1] == 0xee && t[2] == 0xee && t[3] == 0xee;
NSUInteger region = (x < AREA && y < AREA) ? 0 : (x < BAND && y < BAND) ? 1 : 2;
changed[region] += kept ? 0 : 1;
}
}
printf("%s: changed texels: area %lu of %lu, band %lu of %lu, rest %lu of %lu\n", name,
(unsigned long)changed[0], (unsigned long)(AREA * AREA),
(unsigned long)changed[1], (unsigned long)(BAND * BAND - AREA * AREA),
(unsigned long)changed[2], (unsigned long)(SIDE * SIDE - BAND * BAND));
const NSUInteger at[6][2] = {{0, 0}, {310, 0}, {0, 310}, {310, 310}, {330, 0}, {599, 599}};
for (int i = 0; i < 6; i++) {
const uint8_t *t = texels + at[i][1] * row + at[i][0] * 4;
printf("%s: texel (%lu, %lu) BGRA %02x %02x %02x %02x\n", name, (unsigned long)at[i][0],
(unsigned long)at[i][1], t[0], t[1], t[2], t[3]);
}
}
return 0;
}
@@ -0,0 +1,448 @@
// texture_write_rounding_storage.m with texture buffers for targets: what a fragment function's
// write to a texture buffer (`texture_buffer<T, access::write>`, a texture a buffer makes with
// `MTLTextureTypeTextureBuffer`) stores under Apple's `textureWriteRoundingMode` 2 against the
// default, for a `float` and a `half` texel into `RGBA16Float`, `RG11B10Float` and `RGB9E5Float`;
// a format whose texture buffer Metal refuses is printed and passed over. Each case draws one
// fullscreen triangle over a 256 x 256 target; the fragment function writes buffer 0's texel for
// its pixel into texture buffer 0 at texel `y * 256 + x`, once in a pipeline of mode 0 and once of
// mode 2, and the two texture buffers' codes are compared channel by channel with each other and with
// candidate rules computed here: toward zero (Metal's default), nearest even with an overflow to
// the infinity or held at the largest finite value and, for `RGB9E5Float`, the shared exponent of
// the largest clamped channel with each mantissa rounded (toward zero, to nearest even, half up),
// a mantissa of 512 either moving the exponent up or held at 511.
//
// The texels: each value of a list (zeros, infinities, NaN, negatives, the formats' largest finite
// values and the values past them, every tie of a 10-, 9-, 8-, 6- and 5-bit mantissa at a spread of
// exponents and one `f32` step either side, and random values) in all four channels, then random
// texels whose green and blue are the red scaled by a random factor in (0, 1], drawn from
// SplitMix64 seeded 7. A `half` texel is the `float` texel rounded to `half` on the host. `HASH`
// lines give the FNV-1a hashes of the inputs and of each texture buffer's bytes at each mode, which
// `metal2vulkan`'s tests `half_and_small_float_words_are_metals_at_either_mode` and
// `rgb9e5_words_are_metals_at_either_mode` hold a texture buffer's words to.
//
// xcrun clang -fobjc-arc -framework Metal -framework Foundation -o texture_buffer_write_rounding \
// texture_buffer_write_rounding.m
// /usr/bin/env -u MTL_DEBUG_LAYER ./texture_buffer_write_rounding
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#import <objc/message.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { W = 256, H = 256, N = W * H };
static const char *SRC =
"#include <metal_stdlib>\n"
"using namespace metal;\n"
"struct V { float4 p [[position]]; };\n"
"vertex V vs(uint id [[vertex_id]]) {\n"
" float2 xy = float2((id << 1) & 2, id & 2);\n"
" V v; v.p = float4(xy * 2.0 - 1.0, 0.0, 1.0); return v;\n"
"}\n"
"fragment float4 fs_float(V in [[stage_in]], texture_buffer<float, access::write> t [[texture(0)]],\n"
" device const float4 *src [[buffer(0)]]) {\n"
" uint2 c = uint2(in.p.xy);\n"
" t.write(src[c.y * 256 + c.x], c.y * 256 + c.x);\n"
" return float4(0.0);\n"
"}\n"
"fragment float4 fs_half(V in [[stage_in]], texture_buffer<half, access::write> t [[texture(0)]],\n"
" device const half4 *src [[buffer(0)]]) {\n"
" uint2 c = uint2(in.p.xy);\n"
" t.write(src[c.y * 256 + c.x], c.y * 256 + c.x);\n"
" return float4(0.0);\n"
"}\n";
enum Round { RTZ, RNE, RHU };
enum Over { INF, SAT };
// `v` as a float of `mb` mantissa and `eb` exponent bits (signed where `sign`), rounded by `r`, a
// value past the largest finite one to the infinity or held at the largest (`o`; toward zero
// always held). A NaN is the quiet NaN of the top mantissa bit; an unsigned format's negative 0.
static uint32_t enc(double v, int mb, int eb, int sign, enum Round r, enum Over o) {
uint32_t expall = (1u << eb) - 1, bias = (1u << (eb - 1)) - 1, s = 0;
if (isnan(v)) return (expall << mb) | (1u << (mb - 1));
if (v < 0 || (v == 0 && signbit(v))) {
if (!sign) return 0;
s = 1u << (mb + eb);
v = -v;
}
uint32_t maxfin = ((expall - 1) << mb) | ((1u << mb) - 1);
if (isinf(v)) return s | (expall << mb);
if (v == 0) return s;
int x;
frexp(v, &x);
int e = x - 1;
int denorm = e < 1 - (int)bias;
double q = denorm ? ldexp(v, (int)bias - 1 + mb) : ldexp(v, mb - e);
double qi = r == RTZ ? floor(q) : r == RNE ? nearbyint(q) : floor(q + 0.5);
uint32_t code;
if (denorm) {
code = (uint32_t)qi;
} else {
if (qi >= ldexp(1, mb + 1)) {
e += 1;
qi = ldexp(1, mb);
}
if (e + (int)bias >= (int)expall) return s | ((r == RTZ || o == SAT) ? maxfin : (expall << mb));
code = ((uint32_t)(e + (int)bias) << mb) | ((uint32_t)qi - (1u << mb));
}
return s | code;
}
static double dec(uint32_t c, int mb, int eb, int sign) {
uint32_t expall = (1u << eb) - 1, bias = (1u << (eb - 1)) - 1;
double sg = (sign && (c >> (mb + eb)) & 1) ? -1 : 1;
uint32_t e = (c >> mb) & expall, m = c & ((1u << mb) - 1);
if (e == expall) return m ? NAN : sg * INFINITY;
if (e == 0) return sg * ldexp(m, 1 - (int)bias - mb);
return sg * ldexp(m + (1u << mb), (int)e - (int)bias - mb);
}
static double clamp9(double v) { return isnan(v) || v < 0 ? 0 : v > 65408 ? 65408 : v; }
// RGB9E5: the shared exponent of the largest clamped channel, each mantissa rounded by `r`; a
// largest mantissa of 512 moves the exponent up where `bump`, else is held at 511.
static uint32_t rgb9e5(const double *c, enum Round r, int bump) {
double v[3], mx = 0;
for (int i = 0; i < 3; i++) {
v[i] = clamp9(c[i]);
if (v[i] > mx) mx = v[i];
}
if (mx == 0) return 0;
int x;
frexp(mx, &x);
int e = (x - 1 < -16 ? -16 : x - 1) + 16;
for (int pass = 0; pass < 2; pass++) {
uint32_t m[3], over = 0;
for (int i = 0; i < 3; i++) {
double q = ldexp(v[i], 24 - e);
double qi = r == RTZ ? floor(q) : r == RNE ? nearbyint(q) : floor(q + 0.5);
if (qi > 511) {
over = 1;
qi = 511;
}
m[i] = (uint32_t)qi;
}
if (over && bump && pass == 0 && e < 31) {
e += 1;
continue;
}
return ((uint32_t)e << 27) | (m[2] << 18) | (m[1] << 9) | m[0];
}
return 0;
}
static void dec9(uint32_t w, double *o) {
int e = (int)(w >> 27);
for (int i = 0; i < 3; i++) o[i] = ldexp((w >> (9 * i)) & 511, e - 24);
}
typedef struct {
const char *name;
MTLPixelFormat pf;
int bytes, kind; // kind 0: RGBA16Float, 1: RG11B10Float, 2: RGB9E5Float
} Fmt;
// The inputs' generator (SplitMix64 from 7), which `metal2vulkan`'s test of the words
// (`lower/arith/tests/color_write.rs`, `probe_texels`) takes again.
static uint64_t sm = 7;
static uint64_t next64(void) {
uint64_t z = (sm += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
static uint32_t r32(void) { return (uint32_t)(next64() >> 32); }
// FNV-1a over `n` bytes, from `h`.
static uint64_t fnv(uint64_t h, const void *p, size_t n) {
const uint8_t *b = p;
for (size_t i = 0; i < n; i++) h = (h ^ b[i]) * 0x100000001b3ull;
return h;
}
static const uint64_t FNV0 = 0xcbf29ce484222325ull;
static float vals[40000];
static int nv;
static void add(double v) {
if (nv < 40000) vals[nv++] = (float)v;
}
static void build_values(void) {
double sp[] = {0, -0.0, -1, -65504, INFINITY, -INFINITY, NAN, 65504, 65505, 65519, 65519.99,
65520, 65521, 65536, 1e5, 1e9, 65024, 65040, 65055.99, 65056, 65057, 64512,
64528, 64543.99, 64544, 64545, 65408, 65407, 65409, 65416, 65424, 65471, 65472,
65473, 1e-10, 1e-40, ldexp(1, -24), ldexp(1, -25), ldexp(3, -26), ldexp(1, -20),
ldexp(1, -21), ldexp(3, -22), ldexp(1, -24) * 1.5, ldexp(1, -14), ldexp(1, -15),
ldexp(1, -16), ldexp(1, -17), 0.5, 1, 1.5, 2, 3};
for (unsigned i = 0; i < sizeof sp / sizeof sp[0]; i++) add(sp[i]);
int widths[] = {10, 9, 8, 6, 5};
for (int wi = 0; wi < 5; wi++) {
int mb = widths[wi];
for (int e = -26; e <= 16; e++) {
int ks[8] = {0, 1, 2, 3, (1 << mb) - 2, (1 << mb) - 1, 0, 0};
ks[6] = (int)(r32() % (1u << mb));
ks[7] = (int)(r32() % (1u << mb));
for (int k = 0; k < 8; k++) {
float t = (float)ldexp(1.0 + (ks[k] + 0.5) / ldexp(1, mb), e);
add(t);
add(nextafterf(t, INFINITY));
add(nextafterf(t, -INFINITY));
}
}
}
while (nv < 12000) {
int e = (int)(r32() % 44) - 27;
uint32_t mant = r32() & 0x7fffff;
double v = ldexp(1.0 + (double)mant / 8388608.0, e);
int neg = r32() % 16 == 0;
add(neg ? -v : v);
}
}
static double urand(void) { return (double)((r32() & 0xffffff) + 1) / 16777216.0; }
int main(int argc, char **argv) {
(void)argc;
(void)argv;
@autoreleasepool {
build_values();
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
printf("device %s\n", dev.name.UTF8String);
SEL sup = NSSelectorFromString(@"supportsTextureWriteRoundingMode:");
if ([dev respondsToSelector:sup]) {
for (NSUInteger m = 0; m <= 2; m++)
printf("supportsTextureWriteRoundingMode:%lu %d\n", (unsigned long)m,
((BOOL(*)(id, SEL, NSUInteger))objc_msgSend)(dev, sup, m));
}
NSError *err = nil;
MTLCompileOptions *co = [MTLCompileOptions new];
co.mathMode = MTLMathModeSafe;
id<MTLLibrary> lib = [dev newLibraryWithSource:@(SRC) options:co error:&err];
if (!lib) {
printf("library: %s\n", err.description.UTF8String);
return 1;
}
// The texels, `float` and `half`.
float *ftex = calloc(N * 4, sizeof(float));
__fp16 *htex = calloc(N * 4, sizeof(__fp16));
for (int i = 0; i < N; i++) {
float *t = ftex + 4 * i;
if (i < nv) {
t[0] = t[1] = t[2] = t[3] = vals[i];
} else {
float r = vals[r32() % (uint32_t)nv];
t[0] = r;
t[1] = (float)(r * urand());
if (r32() % 4 == 0) {
t[2] = vals[r32() % (uint32_t)nv];
} else {
t[2] = (float)(r * urand());
}
t[3] = vals[r32() % (uint32_t)nv];
}
for (int c = 0; c < 4; c++) htex[4 * i + c] = (__fp16)t[c];
}
printf("HASH inputs %016llx halves %016llx values %d\n", (unsigned long long)fnv(FNV0, ftex, N * 16),
(unsigned long long)fnv(FNV0, htex, N * 8), nv);
id<MTLBuffer> fbuf = [dev newBufferWithBytes:ftex length:N * 16 options:MTLResourceStorageModeShared];
id<MTLBuffer> hbuf = [dev newBufferWithBytes:htex length:N * 8 options:MTLResourceStorageModeShared];
MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:W
height:H
mipmapped:NO];
td.usage = MTLTextureUsageRenderTarget;
td.storageMode = MTLStorageModePrivate;
id<MTLTexture> rt = [dev newTextureWithDescriptor:td];
id<MTLCommandQueue> q = [dev newCommandQueue];
Fmt fmts[] = {{"RGBA16Float", MTLPixelFormatRGBA16Float, 8, 0},
{"RG11B10Float", MTLPixelFormatRG11B10Float, 4, 1},
{"RGB9E5Float", MTLPixelFormatRGB9E5Float, 4, 2}};
SEL set = NSSelectorFromString(@"setTextureWriteRoundingMode:");
SEL get = NSSelectorFromString(@"textureWriteRoundingMode");
for (int fi = 0; fi < 3; fi++) {
for (int half = 0; half < 2; half++) {
Fmt f = fmts[fi];
if (half && f.kind == 0) continue; // a half into a half-float texture is exact
uint8_t *out[2] = {NULL, NULL};
for (int mode = 0; mode < 2; mode++) {
MTLRenderPipelineDescriptor *pd = [MTLRenderPipelineDescriptor new];
pd.vertexFunction = [lib newFunctionWithName:@"vs"];
pd.fragmentFunction = [lib newFunctionWithName:half ? @"fs_half" : @"fs_float"];
pd.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm;
if (![pd respondsToSelector:set]) {
printf("no setTextureWriteRoundingMode:\n");
return 2;
}
((void (*)(id, SEL, NSUInteger))objc_msgSend)(pd, set, mode ? 2 : 0);
NSUInteger took = ((NSUInteger(*)(id, SEL))objc_msgSend)(pd, get);
id<MTLRenderPipelineState> ps = [dev newRenderPipelineStateWithDescriptor:pd error:&err];
if (!ps) {
printf("%s %s mode %d: pipeline: %s\n", f.name, half ? "half" : "float", mode ? 2 : 0,
err.description.UTF8String);
return 1;
}
MTLTextureDescriptor *sd =
[MTLTextureDescriptor textureBufferDescriptorWithPixelFormat:f.pf
width:N
resourceOptions:MTLResourceStorageModeShared
usage:MTLTextureUsageShaderWrite |
MTLTextureUsageShaderRead];
id<MTLBuffer> sb = [dev newBufferWithLength:(NSUInteger)N * f.bytes options:MTLResourceStorageModeShared];
memset(sb.contents, 0xA5, (size_t)N * f.bytes);
id<MTLTexture> st = [sb newTextureWithDescriptor:sd offset:0 bytesPerRow:(NSUInteger)N * f.bytes];
if (!st) {
printf("%s %s mode %d: no texture buffer of this format\n", f.name, half ? "half" : "float", mode ? 2 : 0);
break;
}
uint8_t *fill = malloc(N * f.bytes);
MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
rp.colorAttachments[0].texture = rt;
rp.colorAttachments[0].loadAction = MTLLoadActionDontCare;
rp.colorAttachments[0].storeAction = MTLStoreActionDontCare;
id<MTLCommandBuffer> cb = [q commandBuffer];
id<MTLRenderCommandEncoder> en = [cb renderCommandEncoderWithDescriptor:rp];
[en setRenderPipelineState:ps];
[en setFragmentTexture:st atIndex:0];
[en setFragmentBuffer:half ? hbuf : fbuf offset:0 atIndex:0];
[en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[en endEncoding];
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted) {
printf("%s: command buffer status %ld\n", f.name, (long)cb.status);
return 1;
}
out[mode] = fill;
memcpy(fill, sb.contents, (size_t)N * f.bytes);
printf("%s %s mode %d (descriptor reads %lu)\n", f.name, half ? "half" : "float", mode ? 2 : 0,
(unsigned long)took);
}
if (!out[0] || !out[1]) {
free(out[0]);
continue;
}
printf("HASH %s %s mode0 %016llx mode2 %016llx\n", f.name, half ? "half" : "float",
(unsigned long long)fnv(FNV0, out[0], (size_t)N * f.bytes),
(unsigned long long)fnv(FNV0, out[1], (size_t)N * f.bytes));
// Per channel: the input, mode 0's and mode 2's codes, and the candidates'.
int chans = f.kind == 0 ? 4 : 3;
long total = 0, same = 0, unwritten = 0, dist[5] = {0}, nanish = 0;
const char *cn[] = {"rtz", "rne-inf", "rne-sat", "rhu-hold", "rne-bump", "rhu-bump", "rne-hold", "rtz-bump"};
long m0[8] = {0}, m2[8] = {0};
int ncand = f.kind == 2 ? 6 : 3;
int shown = 0;
double maxd = 0;
for (int i = 0; i < N; i++) {
double in[4];
for (int c = 0; c < 4; c++) in[c] = half ? (double)htex[4 * i + c] : (double)ftex[4 * i + c];
uint32_t w0 = 0, w2 = 0;
memcpy(&w0, out[0] + i * f.bytes, 4);
memcpy(&w2, out[1] + i * f.bytes, 4);
if (f.kind == 2) {
if (w0 == 0xA5A5A5A5u || w2 == 0xA5A5A5A5u) {
unwritten++;
continue;
}
uint32_t cand[6] = {rgb9e5(in, RTZ, 0), rgb9e5(in, RNE, 0), rgb9e5(in, RHU, 0),
rgb9e5(in, RNE, 1), rgb9e5(in, RHU, 1), rgb9e5(in, RTZ, 1)};
const int order[6] = {0, 6, 3, 4, 5, 7};
for (int k = 0; k < 6; k++) {
m0[order[k]] += cand[k] == w0;
m2[order[k]] += cand[k] == w2;
}
total++;
same += w0 == w2;
if (w0 != w2) {
double d0[3], d2[3];
dec9(w0, d0);
dec9(w2, d2);
int e = (int)((w0 >> 27) > (w2 >> 27) ? (w0 >> 27) : (w2 >> 27));
double ulp = ldexp(1, e - 24), d = 0;
for (int c = 0; c < 3; c++) d = fmax(d, fabs(d2[c] - d0[c]) / ulp);
maxd = fmax(maxd, d);
dist[d <= 1 ? 1 : d <= 2 ? 2 : 3]++;
if (shown < 6) {
shown++;
printf(" in (%.9g %.9g %.9g) mode0 %08x mode2 %08x rtz %08x rne %08x rhu %08x rne-bump %08x\n",
in[0], in[1], in[2], w0, w2, cand[0], cand[1], cand[2], cand[3]);
}
}
continue;
}
for (int c = 0; c < chans; c++) {
uint32_t c0, c2;
int mb, eb, sg;
if (f.kind == 0) {
uint16_t a, b;
memcpy(&a, out[0] + i * 8 + 2 * c, 2);
memcpy(&b, out[1] + i * 8 + 2 * c, 2);
c0 = a;
c2 = b;
mb = 10, eb = 5, sg = 1;
if (a == 0xA5A5 || b == 0xA5A5) {
unwritten++;
continue;
}
} else {
if (w0 == 0xA5A5A5A5u || w2 == 0xA5A5A5A5u) {
unwritten++;
continue;
}
int sh = c == 0 ? 0 : c == 1 ? 11 : 22;
mb = c == 2 ? 5 : 6, eb = 5, sg = 0;
c0 = (w0 >> sh) & ((1u << (mb + eb)) - 1);
c2 = (w2 >> sh) & ((1u << (mb + eb)) - 1);
}
total++;
double v0 = dec(c0, mb, eb, sg), v2 = dec(c2, mb, eb, sg);
if (isnan(in[c]) || isnan(v0) || isnan(v2)) {
nanish++;
same += isnan(v0) == isnan(v2);
continue;
}
uint32_t cand[3] = {enc(in[c], mb, eb, sg, RTZ, SAT), enc(in[c], mb, eb, sg, RNE, INF),
enc(in[c], mb, eb, sg, RNE, SAT)};
for (int k = 0; k < 3; k++) {
m0[k] += cand[k] == c0;
m2[k] += cand[k] == c2;
}
same += c0 == c2;
if (c0 != c2) {
// Codes of one sign are ordered by magnitude.
long a0 = (long)(c0 & ((1u << (mb + eb)) - 1)), a2 = (long)(c2 & ((1u << (mb + eb)) - 1));
long d = labs(a2 - a0);
if (isinf(v0) != isinf(v2)) d = 4;
dist[d >= 4 ? 4 : d >= 3 ? 3 : d]++;
if (shown < 6) {
shown++;
printf(" in %.9g (%a) mode0 %04x (%.9g) mode2 %04x (%.9g) rtz %04x rne-inf %04x rne-sat %04x\n",
in[c], in[c], c0, v0, c2, v2, cand[0], cand[1], cand[2]);
}
}
}
}
printf("RESULT %s %s: %ld %s, %ld unwritten, %ld NaN-ish; mode 2 = mode 0 on %ld; differing by 1: %ld, 2: %ld, "
"more: %ld, inf/finite: %ld%s",
f.name, half ? "half" : "float", total, f.kind == 2 ? "texels" : "channels", unwritten, nanish, same,
dist[1], dist[2], dist[3], dist[4], f.kind == 2 ? "" : "\n");
if (f.kind == 2) printf(" (max %.3g units of the larger exponent's last place)\n", maxd);
for (int k = 0; k < 8; k++) {
if (f.kind != 2 && k >= ncand) break;
if (f.kind == 2 && !(k == 0 || k >= 3)) continue;
printf(" candidate %-9s mode 0 %ld, mode 2 %ld\n", cn[k], m0[k], m2[k]);
}
free(out[0]);
free(out[1]);
}
}
}
return 0;
}
@@ -0,0 +1,438 @@
// What a fragment function's texture write stores under Apple's `textureWriteRoundingMode` 2
// (`-[MTLRenderPipelineDescriptor setTextureWriteRoundingMode:]`, SPI) against the default, for
// the writes `metal2vulkan`'s `lower/texture/mod.rs` (`mode_rounded_write`) names: a `float` and a
// `half` texel into `RGBA16Float`, `RG11B10Float` and `RGB9E5Float` storage textures. Each case
// draws one fullscreen triangle over a 256 x 256 target; the fragment function writes buffer 0's
// texel for its pixel into texture 0 (`access::write`), once in a pipeline of mode 0 and once of
// mode 2, and the two textures' codes are compared channel by channel with each other and with
// candidate rules computed here: toward zero (Metal's default), nearest even with an overflow to
// the infinity or held at the largest finite value and, for `RGB9E5Float`, the shared exponent of
// the largest clamped channel with each mantissa rounded (toward zero, to nearest even, half up),
// a mantissa of 512 either moving the exponent up or held at 511.
//
// The texels: each value of a list (zeros, infinities, NaN, negatives, the formats' largest finite
// values and the values past them, every tie of a 10-, 9-, 8-, 6- and 5-bit mantissa at a spread of
// exponents and one `f32` step either side, and random values) in all four channels, then random
// texels whose green and blue are the red scaled by a random factor in (0, 1], drawn from
// SplitMix64 seeded 7. A `half` texel is the `float` texel rounded to `half` on the host. `HASH`
// lines give the FNV-1a hashes of the inputs and of each texture's bytes at each mode, which
// `metal2vulkan`'s test `rgb9e5_words_are_metals_at_either_mode` holds its words to.
//
// xcrun clang -fobjc-arc -framework Metal -framework Foundation -o texture_write_rounding_storage \
// texture_write_rounding_storage.m
// /usr/bin/env -u MTL_DEBUG_LAYER ./texture_write_rounding_storage
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#import <objc/message.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { W = 256, H = 256, N = W * H };
static const char *SRC =
"#include <metal_stdlib>\n"
"using namespace metal;\n"
"struct V { float4 p [[position]]; };\n"
"vertex V vs(uint id [[vertex_id]]) {\n"
" float2 xy = float2((id << 1) & 2, id & 2);\n"
" V v; v.p = float4(xy * 2.0 - 1.0, 0.0, 1.0); return v;\n"
"}\n"
"fragment float4 fs_float(V in [[stage_in]], texture2d<float, access::write> t [[texture(0)]],\n"
" device const float4 *src [[buffer(0)]]) {\n"
" uint2 c = uint2(in.p.xy);\n"
" t.write(src[c.y * 256 + c.x], c);\n"
" return float4(0.0);\n"
"}\n"
"fragment float4 fs_half(V in [[stage_in]], texture2d<half, access::write> t [[texture(0)]],\n"
" device const half4 *src [[buffer(0)]]) {\n"
" uint2 c = uint2(in.p.xy);\n"
" t.write(src[c.y * 256 + c.x], c);\n"
" return float4(0.0);\n"
"}\n";
enum Round { RTZ, RNE, RHU };
enum Over { INF, SAT };
// `v` as a float of `mb` mantissa and `eb` exponent bits (signed where `sign`), rounded by `r`, a
// value past the largest finite one to the infinity or held at the largest (`o`; toward zero
// always held). A NaN is the quiet NaN of the top mantissa bit; an unsigned format's negative 0.
static uint32_t enc(double v, int mb, int eb, int sign, enum Round r, enum Over o) {
uint32_t expall = (1u << eb) - 1, bias = (1u << (eb - 1)) - 1, s = 0;
if (isnan(v)) return (expall << mb) | (1u << (mb - 1));
if (v < 0 || (v == 0 && signbit(v))) {
if (!sign) return 0;
s = 1u << (mb + eb);
v = -v;
}
uint32_t maxfin = ((expall - 1) << mb) | ((1u << mb) - 1);
if (isinf(v)) return s | (expall << mb);
if (v == 0) return s;
int x;
frexp(v, &x);
int e = x - 1;
int denorm = e < 1 - (int)bias;
double q = denorm ? ldexp(v, (int)bias - 1 + mb) : ldexp(v, mb - e);
double qi = r == RTZ ? floor(q) : r == RNE ? nearbyint(q) : floor(q + 0.5);
uint32_t code;
if (denorm) {
code = (uint32_t)qi;
} else {
if (qi >= ldexp(1, mb + 1)) {
e += 1;
qi = ldexp(1, mb);
}
if (e + (int)bias >= (int)expall) return s | ((r == RTZ || o == SAT) ? maxfin : (expall << mb));
code = ((uint32_t)(e + (int)bias) << mb) | ((uint32_t)qi - (1u << mb));
}
return s | code;
}
static double dec(uint32_t c, int mb, int eb, int sign) {
uint32_t expall = (1u << eb) - 1, bias = (1u << (eb - 1)) - 1;
double sg = (sign && (c >> (mb + eb)) & 1) ? -1 : 1;
uint32_t e = (c >> mb) & expall, m = c & ((1u << mb) - 1);
if (e == expall) return m ? NAN : sg * INFINITY;
if (e == 0) return sg * ldexp(m, 1 - (int)bias - mb);
return sg * ldexp(m + (1u << mb), (int)e - (int)bias - mb);
}
static double clamp9(double v) { return isnan(v) || v < 0 ? 0 : v > 65408 ? 65408 : v; }
// RGB9E5: the shared exponent of the largest clamped channel, each mantissa rounded by `r`; a
// largest mantissa of 512 moves the exponent up where `bump`, else is held at 511.
static uint32_t rgb9e5(const double *c, enum Round r, int bump) {
double v[3], mx = 0;
for (int i = 0; i < 3; i++) {
v[i] = clamp9(c[i]);
if (v[i] > mx) mx = v[i];
}
if (mx == 0) return 0;
int x;
frexp(mx, &x);
int e = (x - 1 < -16 ? -16 : x - 1) + 16;
for (int pass = 0; pass < 2; pass++) {
uint32_t m[3], over = 0;
for (int i = 0; i < 3; i++) {
double q = ldexp(v[i], 24 - e);
double qi = r == RTZ ? floor(q) : r == RNE ? nearbyint(q) : floor(q + 0.5);
if (qi > 511) {
over = 1;
qi = 511;
}
m[i] = (uint32_t)qi;
}
if (over && bump && pass == 0 && e < 31) {
e += 1;
continue;
}
return ((uint32_t)e << 27) | (m[2] << 18) | (m[1] << 9) | m[0];
}
return 0;
}
static void dec9(uint32_t w, double *o) {
int e = (int)(w >> 27);
for (int i = 0; i < 3; i++) o[i] = ldexp((w >> (9 * i)) & 511, e - 24);
}
typedef struct {
const char *name;
MTLPixelFormat pf;
int bytes, kind; // kind 0: RGBA16Float, 1: RG11B10Float, 2: RGB9E5Float
} Fmt;
// The inputs' generator (SplitMix64 from 7), which `metal2vulkan`'s test of the words
// (`lower/arith/tests/color_write.rs`, `probe_texels`) takes again.
static uint64_t sm = 7;
static uint64_t next64(void) {
uint64_t z = (sm += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
static uint32_t r32(void) { return (uint32_t)(next64() >> 32); }
// FNV-1a over `n` bytes, from `h`.
static uint64_t fnv(uint64_t h, const void *p, size_t n) {
const uint8_t *b = p;
for (size_t i = 0; i < n; i++) h = (h ^ b[i]) * 0x100000001b3ull;
return h;
}
static const uint64_t FNV0 = 0xcbf29ce484222325ull;
static float vals[40000];
static int nv;
static void add(double v) {
if (nv < 40000) vals[nv++] = (float)v;
}
static void build_values(void) {
double sp[] = {0, -0.0, -1, -65504, INFINITY, -INFINITY, NAN, 65504, 65505, 65519, 65519.99,
65520, 65521, 65536, 1e5, 1e9, 65024, 65040, 65055.99, 65056, 65057, 64512,
64528, 64543.99, 64544, 64545, 65408, 65407, 65409, 65416, 65424, 65471, 65472,
65473, 1e-10, 1e-40, ldexp(1, -24), ldexp(1, -25), ldexp(3, -26), ldexp(1, -20),
ldexp(1, -21), ldexp(3, -22), ldexp(1, -24) * 1.5, ldexp(1, -14), ldexp(1, -15),
ldexp(1, -16), ldexp(1, -17), 0.5, 1, 1.5, 2, 3};
for (unsigned i = 0; i < sizeof sp / sizeof sp[0]; i++) add(sp[i]);
int widths[] = {10, 9, 8, 6, 5};
for (int wi = 0; wi < 5; wi++) {
int mb = widths[wi];
for (int e = -26; e <= 16; e++) {
int ks[8] = {0, 1, 2, 3, (1 << mb) - 2, (1 << mb) - 1, 0, 0};
ks[6] = (int)(r32() % (1u << mb));
ks[7] = (int)(r32() % (1u << mb));
for (int k = 0; k < 8; k++) {
float t = (float)ldexp(1.0 + (ks[k] + 0.5) / ldexp(1, mb), e);
add(t);
add(nextafterf(t, INFINITY));
add(nextafterf(t, -INFINITY));
}
}
}
while (nv < 12000) {
int e = (int)(r32() % 44) - 27;
uint32_t mant = r32() & 0x7fffff;
double v = ldexp(1.0 + (double)mant / 8388608.0, e);
int neg = r32() % 16 == 0;
add(neg ? -v : v);
}
}
static double urand(void) { return (double)((r32() & 0xffffff) + 1) / 16777216.0; }
int main(int argc, char **argv) {
(void)argc;
(void)argv;
@autoreleasepool {
build_values();
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
printf("device %s\n", dev.name.UTF8String);
SEL sup = NSSelectorFromString(@"supportsTextureWriteRoundingMode:");
if ([dev respondsToSelector:sup]) {
for (NSUInteger m = 0; m <= 2; m++)
printf("supportsTextureWriteRoundingMode:%lu %d\n", (unsigned long)m,
((BOOL(*)(id, SEL, NSUInteger))objc_msgSend)(dev, sup, m));
}
NSError *err = nil;
MTLCompileOptions *co = [MTLCompileOptions new];
co.mathMode = MTLMathModeSafe;
id<MTLLibrary> lib = [dev newLibraryWithSource:@(SRC) options:co error:&err];
if (!lib) {
printf("library: %s\n", err.description.UTF8String);
return 1;
}
// The texels, `float` and `half`.
float *ftex = calloc(N * 4, sizeof(float));
__fp16 *htex = calloc(N * 4, sizeof(__fp16));
for (int i = 0; i < N; i++) {
float *t = ftex + 4 * i;
if (i < nv) {
t[0] = t[1] = t[2] = t[3] = vals[i];
} else {
float r = vals[r32() % (uint32_t)nv];
t[0] = r;
t[1] = (float)(r * urand());
if (r32() % 4 == 0) {
t[2] = vals[r32() % (uint32_t)nv];
} else {
t[2] = (float)(r * urand());
}
t[3] = vals[r32() % (uint32_t)nv];
}
for (int c = 0; c < 4; c++) htex[4 * i + c] = (__fp16)t[c];
}
printf("HASH inputs %016llx halves %016llx values %d\n", (unsigned long long)fnv(FNV0, ftex, N * 16),
(unsigned long long)fnv(FNV0, htex, N * 8), nv);
id<MTLBuffer> fbuf = [dev newBufferWithBytes:ftex length:N * 16 options:MTLResourceStorageModeShared];
id<MTLBuffer> hbuf = [dev newBufferWithBytes:htex length:N * 8 options:MTLResourceStorageModeShared];
MTLTextureDescriptor *td = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:W
height:H
mipmapped:NO];
td.usage = MTLTextureUsageRenderTarget;
td.storageMode = MTLStorageModePrivate;
id<MTLTexture> rt = [dev newTextureWithDescriptor:td];
id<MTLCommandQueue> q = [dev newCommandQueue];
Fmt fmts[] = {{"RGBA16Float", MTLPixelFormatRGBA16Float, 8, 0},
{"RG11B10Float", MTLPixelFormatRG11B10Float, 4, 1},
{"RGB9E5Float", MTLPixelFormatRGB9E5Float, 4, 2}};
SEL set = NSSelectorFromString(@"setTextureWriteRoundingMode:");
SEL get = NSSelectorFromString(@"textureWriteRoundingMode");
for (int fi = 0; fi < 3; fi++) {
for (int half = 0; half < 2; half++) {
Fmt f = fmts[fi];
if (half && f.kind == 0) continue; // a half into a half-float texture is exact
uint8_t *out[2];
for (int mode = 0; mode < 2; mode++) {
MTLRenderPipelineDescriptor *pd = [MTLRenderPipelineDescriptor new];
pd.vertexFunction = [lib newFunctionWithName:@"vs"];
pd.fragmentFunction = [lib newFunctionWithName:half ? @"fs_half" : @"fs_float"];
pd.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm;
if (![pd respondsToSelector:set]) {
printf("no setTextureWriteRoundingMode:\n");
return 2;
}
((void (*)(id, SEL, NSUInteger))objc_msgSend)(pd, set, mode ? 2 : 0);
NSUInteger took = ((NSUInteger(*)(id, SEL))objc_msgSend)(pd, get);
id<MTLRenderPipelineState> ps = [dev newRenderPipelineStateWithDescriptor:pd error:&err];
if (!ps) {
printf("%s %s mode %d: pipeline: %s\n", f.name, half ? "half" : "float", mode ? 2 : 0,
err.description.UTF8String);
return 1;
}
MTLTextureDescriptor *sd = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:f.pf
width:W
height:H
mipmapped:NO];
sd.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead;
sd.storageMode = MTLStorageModeShared;
id<MTLTexture> st = [dev newTextureWithDescriptor:sd];
uint8_t *fill = malloc(N * f.bytes);
memset(fill, 0xA5, N * f.bytes);
[st replaceRegion:MTLRegionMake2D(0, 0, W, H) mipmapLevel:0 withBytes:fill bytesPerRow:W * f.bytes];
MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
rp.colorAttachments[0].texture = rt;
rp.colorAttachments[0].loadAction = MTLLoadActionDontCare;
rp.colorAttachments[0].storeAction = MTLStoreActionDontCare;
id<MTLCommandBuffer> cb = [q commandBuffer];
id<MTLRenderCommandEncoder> en = [cb renderCommandEncoderWithDescriptor:rp];
[en setRenderPipelineState:ps];
[en setFragmentTexture:st atIndex:0];
[en setFragmentBuffer:half ? hbuf : fbuf offset:0 atIndex:0];
[en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[en endEncoding];
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted) {
printf("%s: command buffer status %ld\n", f.name, (long)cb.status);
return 1;
}
out[mode] = fill;
[st getBytes:fill bytesPerRow:W * f.bytes fromRegion:MTLRegionMake2D(0, 0, W, H) mipmapLevel:0];
printf("%s %s mode %d (descriptor reads %lu)\n", f.name, half ? "half" : "float", mode ? 2 : 0,
(unsigned long)took);
}
printf("HASH %s %s mode0 %016llx mode2 %016llx\n", f.name, half ? "half" : "float",
(unsigned long long)fnv(FNV0, out[0], (size_t)N * f.bytes),
(unsigned long long)fnv(FNV0, out[1], (size_t)N * f.bytes));
// Per channel: the input, mode 0's and mode 2's codes, and the candidates'.
int chans = f.kind == 0 ? 4 : 3;
long total = 0, same = 0, unwritten = 0, dist[5] = {0}, nanish = 0;
const char *cn[] = {"rtz", "rne-inf", "rne-sat", "rhu-hold", "rne-bump", "rhu-bump", "rne-hold", "rtz-bump"};
long m0[8] = {0}, m2[8] = {0};
int ncand = f.kind == 2 ? 6 : 3;
int shown = 0;
double maxd = 0;
for (int i = 0; i < N; i++) {
double in[4];
for (int c = 0; c < 4; c++) in[c] = half ? (double)htex[4 * i + c] : (double)ftex[4 * i + c];
uint32_t w0 = 0, w2 = 0;
memcpy(&w0, out[0] + i * f.bytes, 4);
memcpy(&w2, out[1] + i * f.bytes, 4);
if (f.kind == 2) {
if (w0 == 0xA5A5A5A5u || w2 == 0xA5A5A5A5u) {
unwritten++;
continue;
}
uint32_t cand[6] = {rgb9e5(in, RTZ, 0), rgb9e5(in, RNE, 0), rgb9e5(in, RHU, 0),
rgb9e5(in, RNE, 1), rgb9e5(in, RHU, 1), rgb9e5(in, RTZ, 1)};
const int order[6] = {0, 6, 3, 4, 5, 7};
for (int k = 0; k < 6; k++) {
m0[order[k]] += cand[k] == w0;
m2[order[k]] += cand[k] == w2;
}
total++;
same += w0 == w2;
if (w0 != w2) {
double d0[3], d2[3];
dec9(w0, d0);
dec9(w2, d2);
int e = (int)((w0 >> 27) > (w2 >> 27) ? (w0 >> 27) : (w2 >> 27));
double ulp = ldexp(1, e - 24), d = 0;
for (int c = 0; c < 3; c++) d = fmax(d, fabs(d2[c] - d0[c]) / ulp);
maxd = fmax(maxd, d);
dist[d <= 1 ? 1 : d <= 2 ? 2 : 3]++;
if (shown < 6) {
shown++;
printf(" in (%.9g %.9g %.9g) mode0 %08x mode2 %08x rtz %08x rne %08x rhu %08x rne-bump %08x\n",
in[0], in[1], in[2], w0, w2, cand[0], cand[1], cand[2], cand[3]);
}
}
continue;
}
for (int c = 0; c < chans; c++) {
uint32_t c0, c2;
int mb, eb, sg;
if (f.kind == 0) {
uint16_t a, b;
memcpy(&a, out[0] + i * 8 + 2 * c, 2);
memcpy(&b, out[1] + i * 8 + 2 * c, 2);
c0 = a;
c2 = b;
mb = 10, eb = 5, sg = 1;
if (a == 0xA5A5 || b == 0xA5A5) {
unwritten++;
continue;
}
} else {
if (w0 == 0xA5A5A5A5u || w2 == 0xA5A5A5A5u) {
unwritten++;
continue;
}
int sh = c == 0 ? 0 : c == 1 ? 11 : 22;
mb = c == 2 ? 5 : 6, eb = 5, sg = 0;
c0 = (w0 >> sh) & ((1u << (mb + eb)) - 1);
c2 = (w2 >> sh) & ((1u << (mb + eb)) - 1);
}
total++;
double v0 = dec(c0, mb, eb, sg), v2 = dec(c2, mb, eb, sg);
if (isnan(in[c]) || isnan(v0) || isnan(v2)) {
nanish++;
same += isnan(v0) == isnan(v2);
continue;
}
uint32_t cand[3] = {enc(in[c], mb, eb, sg, RTZ, SAT), enc(in[c], mb, eb, sg, RNE, INF),
enc(in[c], mb, eb, sg, RNE, SAT)};
for (int k = 0; k < 3; k++) {
m0[k] += cand[k] == c0;
m2[k] += cand[k] == c2;
}
same += c0 == c2;
if (c0 != c2) {
// Codes of one sign are ordered by magnitude.
long a0 = (long)(c0 & ((1u << (mb + eb)) - 1)), a2 = (long)(c2 & ((1u << (mb + eb)) - 1));
long d = labs(a2 - a0);
if (isinf(v0) != isinf(v2)) d = 4;
dist[d >= 4 ? 4 : d >= 3 ? 3 : d]++;
if (shown < 6) {
shown++;
printf(" in %.9g (%a) mode0 %04x (%.9g) mode2 %04x (%.9g) rtz %04x rne-inf %04x rne-sat %04x\n",
in[c], in[c], c0, v0, c2, v2, cand[0], cand[1], cand[2]);
}
}
}
}
printf("RESULT %s %s: %ld %s, %ld unwritten, %ld NaN-ish; mode 2 = mode 0 on %ld; differing by 1: %ld, 2: %ld, "
"more: %ld, inf/finite: %ld%s",
f.name, half ? "half" : "float", total, f.kind == 2 ? "texels" : "channels", unwritten, nanish, same,
dist[1], dist[2], dist[3], dist[4], f.kind == 2 ? "" : "\n");
if (f.kind == 2) printf(" (max %.3g units of the larger exponent's last place)\n", maxd);
for (int k = 0; k < 8; k++) {
if (f.kind != 2 && k >= ncand) break;
if (f.kind == 2 && !(k == 0 || k >= 3)) continue;
printf(" candidate %-9s mode 0 %ld, mode 2 %ld\n", cn[k], m0[k], m2[k]);
}
free(out[0]);
free(out[1]);
}
}
}
return 0;
}
@@ -0,0 +1,273 @@
// What Metal does with a viewport whose depth range lies past [0, 1], beside control ranges in it.
//
// One render pass per case into a 5 by 1 RGBA32Float colour target and, where the case has one, a
// 5 by 1 depth attachment (Depth32Float or Depth16Unorm) cleared to the case's depth, under the
// case's depth compare function with writes on, in the case's depth clip mode. Five quads cover
// the five columns, each at its own clip-space z (w = 1). Each fragment writes its
// [[position]].z, its .w and a 1 (the column was drawn) into the colour target, which is cleared
// to -9; the `depth` fragment also writes [[depth(any)]] = [[position]].z. For each case and
// column it prints the z the quad was drawn at, whether a fragment landed, the [[position]].z and
// .w it read, and the depth the attachment stored, with the command buffer's status.
//
// The cases ask, for a range past [0, 1]: what position.z reads; what a Depth32Float and a
// Depth16Unorm attachment store, from the rasterized depth and from a [[depth]] output; which
// value the depth test compares, on both sides of 0 and of 1; whether a quad past clip space's z
// bounds is clipped; and, in MTLDepthClipModeClamp, what the stored depth is clamped to (the
// viewport's range or [0, 1]). The [0, 1] and [0.25, 0.75] cases are the controls.
//
// xcrun clang -fobjc-arc -O1 -framework Foundation -framework Metal \
// -o viewport_depth_past_unit viewport_depth_past_unit.m
// ./viewport_depth_past_unit
// MTL_DEBUG_LAYER=1 MTL_DEBUG_LAYER_ERROR_MODE=nslog ./viewport_depth_past_unit
//
// The layer run says whether Metal's API validation takes the range; the plain run is Metal's
// answer (the layer is not passive).
//
// WHAT IT MEASURED, Apple M3 Max, macOS 27.0.1 (job m3-max-85541, the first five cases, which
// then printed no "drawn" field), the plain run and the layer run line for line alike, the layer
// printing nothing past "Metal API Validation Enabled":
//
// - setViewport takes znear -1, zfar 1, and every command buffer completes with no error;
// - [-1, 1]: position.z reads -1, -0.5, 0, 0.5 and 1 at clip z 0, 0.25, 0.5, 0.75 and 1
// (znear + z * (zfar - znear), unclamped), position.w 1, with a depth attachment or without;
// - [-1, 1]: the Depth32Float attachment stores 0, 0, 0, 0.5 and 1, that z clamped to [0, 1];
// a [[depth(any)]] output of position.z stores the same;
// - [0, 1], the control: position.z and the stored depth are clip z, with either fragment.
//
// WHAT IT MEASURED, Apple M3 Max, macOS 27.0.1 (job m3-max-85617, every case above), the plain
// run and the layer run byte for byte alike, every command buffer completed with no error, the
// layer printing nothing past "Metal API Validation Enabled":
//
// - the first five cases as before, each column drawn;
// - Clip mode: position.z is znear + z * (zfar - znear) unclamped, under every range ([-1, 1],
// [0, 2], the reversed [1, -1], [2, 3]); a quad at clip z -0.5, -0.01, 1.01 or 1.5 is not
// drawn under [-1, 1] or [0, 1], with a depth attachment or without: clip space's 0 <= z <= w
// holds whatever the range;
// - Clip mode: Depth32Float and Depth16Unorm store that z clamped to [0, 1], and so does a
// [[depth(any)]] output of it ([0, 2]: 0, 0.5, 1, 1, 1; Depth16Unorm raw 0, 32768, 65535,
// 65535, 65535; [2, 3]: 1 at every column);
// - Clip mode: the depth test compares the clamped value: Equal against a clear of 0 passes at
// position.z -1, -0.5 and 0 under [-1, 1], and Less against 0 at none, through [[depth]]
// too; Equal against a clear of 1 passes at 1, 1.5 and 2 under [0, 2], and Greater at none;
// Depth16Unorm alike;
// - Clamp mode: every quad is drawn (no z clip); position.z is unclamped (-0.25 to 2.75 under
// [0.5, 2]); the stored depth, from the rasterized z or a [[depth]] output, on Depth32Float
// and Depth16Unorm, is clamped to the range's part in [0, 1]: [0.25, 0.75] stores 0.25 to
// 0.75, [0.5, 2] stores 0.5, 0.5, 1, 1, 1 (raw 32768 and 65535), [-1, 1] and [0, 1] store 0
// to 1.
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
static void P(const char *fmt, ...) {
va_list ap; va_start(ap, fmt);
fputs("RESULT ", stdout); vfprintf(stdout, fmt, ap); fputc('\n', stdout); fflush(stdout);
va_end(ap);
}
static NSString *const SOURCE =
@"#include <metal_stdlib>\n"
"using namespace metal;\n"
"struct V { float4 pos [[position]]; };\n"
"vertex V quads(uint vid [[vertex_id]], constant float *Z [[buffer(0)]]) {\n"
" uint q = vid / 6, k = vid % 6;\n"
" float2 c[6] = {float2(0, 0), float2(1, 0), float2(0, 1), float2(1, 0), float2(1, 1), float2(0, 1)};\n"
" float x0 = -1.0 + 2.0 * float(q) / 5.0, x1 = -1.0 + 2.0 * float(q + 1) / 5.0;\n"
" V o; o.pos = float4(mix(x0, x1, c[k].x), mix(-1.0, 1.0, c[k].y), Z[q], 1.0); return o; }\n"
"fragment float4 plain(V in [[stage_in]]) { return float4(in.pos.z, in.pos.w, 1, 1); }\n"
"struct D { float4 c [[color(0)]]; float d [[depth(any)]]; };\n"
"fragment D depth(V in [[stage_in]]) {\n"
" D o; o.c = float4(in.pos.z, in.pos.w, 1, 1); o.d = in.pos.z; return o; }\n";
static const char *STATUS[] = {"NotEnqueued", "Enqueued", "Committed", "Scheduled", "Completed",
"Error"};
static id<MTLDevice> DEV;
static id<MTLCommandQueue> QUEUE;
static id<MTLLibrary> LIB;
// The clip-space z of the five quads: inside clip space, and across its bounds.
static const float INSIDE[5] = {0.0f, 0.25f, 0.5f, 0.75f, 1.0f};
static const float ACROSS[5] = {-0.5f, -0.01f, 0.5f, 1.01f, 1.5f};
enum DepthKind { NONE, D32, D16 };
typedef struct {
const char *name;
double znear, zfar;
enum DepthKind depth;
const char *fragment;
MTLDepthClipMode clip;
const float *z;
double clear;
MTLCompareFunction compare;
} Case;
static const char *depth_name(enum DepthKind k) {
return k == D32 ? "Depth32Float" : k == D16 ? "Depth16Unorm" : "none";
}
static const char *compare_name(MTLCompareFunction f) {
switch (f) {
case MTLCompareFunctionAlways: return "Always";
case MTLCompareFunctionEqual: return "Equal";
case MTLCompareFunctionLess: return "Less";
case MTLCompareFunctionGreater: return "Greater";
default: return "?";
}
}
static void run_case(const Case *k) {
NSError *e = nil;
MTLPixelFormat df = k->depth == D32 ? MTLPixelFormatDepth32Float
: k->depth == D16 ? MTLPixelFormatDepth16Unorm : MTLPixelFormatInvalid;
MTLRenderPipelineDescriptor *pd = [[MTLRenderPipelineDescriptor alloc] init];
pd.vertexFunction = [LIB newFunctionWithName:@"quads"];
pd.fragmentFunction = [LIB newFunctionWithName:[NSString stringWithUTF8String:k->fragment]];
pd.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA32Float;
if (k->depth != NONE) pd.depthAttachmentPixelFormat = df;
id<MTLRenderPipelineState> ps = [DEV newRenderPipelineStateWithDescriptor:pd error:&e];
if (!ps) { P("%s: pipeline failed: %s", k->name, [[e description] UTF8String]); return; }
MTLTextureDescriptor *cd = [MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA32Float width:5 height:1 mipmapped:NO];
cd.usage = MTLTextureUsageRenderTarget; cd.storageMode = MTLStorageModePrivate;
id<MTLTexture> colour = [DEV newTextureWithDescriptor:cd];
id<MTLTexture> depth = nil;
if (k->depth != NONE) {
MTLTextureDescriptor *dd = [MTLTextureDescriptor
texture2DDescriptorWithPixelFormat:df width:5 height:1 mipmapped:NO];
dd.usage = MTLTextureUsageRenderTarget; dd.storageMode = MTLStorageModePrivate;
depth = [DEV newTextureWithDescriptor:dd];
}
id<MTLBuffer> cread = [DEV newBufferWithLength:5 * 16 options:MTLResourceStorageModeShared];
id<MTLBuffer> dread = [DEV newBufferWithLength:256 options:MTLResourceStorageModeShared];
memset(cread.contents, 0xFF, cread.length); memset(dread.contents, 0xFF, dread.length);
MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
rp.colorAttachments[0].texture = colour;
rp.colorAttachments[0].loadAction = MTLLoadActionClear;
rp.colorAttachments[0].clearColor = MTLClearColorMake(-9, -9, -9, -9);
rp.colorAttachments[0].storeAction = MTLStoreActionStore;
if (depth) {
rp.depthAttachment.texture = depth;
rp.depthAttachment.loadAction = MTLLoadActionClear;
rp.depthAttachment.clearDepth = k->clear;
rp.depthAttachment.storeAction = MTLStoreActionStore;
}
MTLDepthStencilDescriptor *dsd = [[MTLDepthStencilDescriptor alloc] init];
dsd.depthCompareFunction = k->compare;
dsd.depthWriteEnabled = depth ? YES : NO;
id<MTLDepthStencilState> dss = [DEV newDepthStencilStateWithDescriptor:dsd];
id<MTLCommandBuffer> cb = [QUEUE commandBuffer];
id<MTLRenderCommandEncoder> re = [cb renderCommandEncoderWithDescriptor:rp];
[re setRenderPipelineState:ps];
[re setDepthStencilState:dss];
[re setDepthClipMode:k->clip];
[re setVertexBytes:k->z length:5 * sizeof(float) atIndex:0];
MTLViewport vp = {0, 0, 5, 1, k->znear, k->zfar};
[re setViewport:vp];
P("%s: znear %g zfar %g depth %s fragment %s clip mode %s clear %g compare %s", k->name, k->znear,
k->zfar, depth_name(k->depth), k->fragment,
k->clip == MTLDepthClipModeClamp ? "Clamp" : "Clip", k->clear, compare_name(k->compare));
[re drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:30];
[re endEncoding];
id<MTLBlitCommandEncoder> be = [cb blitCommandEncoder];
[be copyFromTexture:colour sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0)
sourceSize:MTLSizeMake(5, 1, 1) toBuffer:cread destinationOffset:0
destinationBytesPerRow:5 * 16 destinationBytesPerImage:5 * 16];
NSUInteger unit = k->depth == D16 ? 2 : 4;
if (depth) {
[be copyFromTexture:depth sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0)
sourceSize:MTLSizeMake(5, 1, 1) toBuffer:dread destinationOffset:0
destinationBytesPerRow:5 * unit destinationBytesPerImage:5 * unit];
}
[be endEncoding];
[cb commit];
[cb waitUntilCompleted];
NSError *err = cb.error;
P("%s: status %s error %s", k->name, ((unsigned)cb.status < 6) ? STATUS[cb.status] : "?",
err ? [[err localizedDescription] UTF8String] : "none");
const float *c = (const float *)cread.contents;
for (int i = 0; i < 5; i++) {
const float *t = c + i * 4;
int drawn = t[2] == 1.0f;
char stored[64];
if (k->depth == D32)
snprintf(stored, sizeof stored, "%.9g", ((const float *)dread.contents)[i]);
else if (k->depth == D16) {
unsigned raw = ((const unsigned short *)dread.contents)[i];
snprintf(stored, sizeof stored, "%.9g (raw %u)", raw / 65535.0, raw);
} else
snprintf(stored, sizeof stored, "(no depth attachment)");
if (drawn)
P("%s: clip z %.2f drawn position.z %.9g position.w %.9g stored depth %s", k->name, k->z[i],
t[0], t[1], stored);
else
P("%s: clip z %.2f not drawn (texel %g %g %g %g) stored depth %s", k->name, k->z[i], t[0],
t[1], t[2], t[3], stored);
}
}
int main(void) {
@autoreleasepool {
NSOperatingSystemVersion v = [[NSProcessInfo processInfo] operatingSystemVersion];
P("macOS %ld.%ld.%ld MTL_DEBUG_LAYER=%s", (long)v.majorVersion, (long)v.minorVersion,
(long)v.patchVersion, getenv("MTL_DEBUG_LAYER") ?: "unset");
DEV = MTLCreateSystemDefaultDevice();
if (!DEV) { P("fatal: no device"); return 3; }
P("device %s", [[DEV name] UTF8String]);
QUEUE = [DEV newCommandQueue];
NSError *e = nil;
LIB = [DEV newLibraryWithSource:SOURCE options:nil error:&e];
if (!LIB) { P("fatal: library: %s", [[e description] UTF8String]); return 3; }
const MTLDepthClipMode CLIP = MTLDepthClipModeClip, CLAMP = MTLDepthClipModeClamp;
const MTLCompareFunction ALWAYS = MTLCompareFunctionAlways;
const Case cases[] = {
// The first run's five.
{"unit-depth", 0, 1, D32, "plain", CLIP, INSIDE, 0.5, ALWAYS},
{"past-depth", -1, 1, D32, "plain", CLIP, INSIDE, 0.5, ALWAYS},
{"past-fragdepth", -1, 1, D32, "depth", CLIP, INSIDE, 0.5, ALWAYS},
{"unit-fragdepth", 0, 1, D32, "depth", CLIP, INSIDE, 0.5, ALWAYS},
{"past-nodepth", -1, 1, NONE, "plain", CLIP, INSIDE, 0.5, ALWAYS},
// Above 1, and Depth16Unorm on both sides.
{"high-depth", 0, 2, D32, "plain", CLIP, INSIDE, 0.5, ALWAYS},
{"high-fragdepth", 0, 2, D32, "depth", CLIP, INSIDE, 0.5, ALWAYS},
{"past-d16", -1, 1, D16, "plain", CLIP, INSIDE, 0.5, ALWAYS},
{"past-d16-fragdepth", -1, 1, D16, "depth", CLIP, INSIDE, 0.5, ALWAYS},
{"high-d16", 0, 2, D16, "plain", CLIP, INSIDE, 0.5, ALWAYS},
{"high-d16-fragdepth", 0, 2, D16, "depth", CLIP, INSIDE, 0.5, ALWAYS},
// The depth test on both sides of 0 and of 1: the clamped value or the unclamped one.
{"test-low-equal", -1, 1, D32, "plain", CLIP, INSIDE, 0.0, MTLCompareFunctionEqual},
{"test-low-less", -1, 1, D32, "plain", CLIP, INSIDE, 0.0, MTLCompareFunctionLess},
{"test-high-equal", 0, 2, D32, "plain", CLIP, INSIDE, 1.0, MTLCompareFunctionEqual},
{"test-high-greater", 0, 2, D32, "plain", CLIP, INSIDE, 1.0, MTLCompareFunctionGreater},
{"test-low-equal-d16", -1, 1, D16, "plain", CLIP, INSIDE, 0.0, MTLCompareFunctionEqual},
{"test-high-greater-d16", 0, 2, D16, "plain", CLIP, INSIDE, 1.0, MTLCompareFunctionGreater},
{"test-low-less-fragdepth", -1, 1, D32, "depth", CLIP, INSIDE, 0.0, MTLCompareFunctionLess},
// Clip space's z bounds under the range, in Clip mode.
{"clip-past", -1, 1, D32, "plain", CLIP, ACROSS, 0.5, ALWAYS},
{"clip-past-nodepth", -1, 1, NONE, "plain", CLIP, ACROSS, 0.5, ALWAYS},
{"clip-unit", 0, 1, D32, "plain", CLIP, ACROSS, 0.5, ALWAYS},
// Clamp mode: what the stored depth is clamped to, and what position.z reads.
{"clamp-unit", 0, 1, D32, "plain", CLAMP, ACROSS, 0.5, ALWAYS},
{"clamp-mid", 0.25, 0.75, D32, "plain", CLAMP, ACROSS, 0.5, ALWAYS},
{"clamp-past", -1, 1, D32, "plain", CLAMP, ACROSS, 0.5, ALWAYS},
{"clamp-high", 0.5, 2, D32, "plain", CLAMP, ACROSS, 0.5, ALWAYS},
{"clamp-high-fragdepth", 0.5, 2, D32, "depth", CLAMP, ACROSS, 0.5, ALWAYS},
{"clamp-high-d16", 0.5, 2, D16, "plain", CLAMP, ACROSS, 0.5, ALWAYS},
{"clamp-past-nodepth", -1, 1, NONE, "plain", CLAMP, ACROSS, 0.5, ALWAYS},
// A reversed range, and one wholly above 1.
{"reversed", 1, -1, D32, "plain", CLIP, INSIDE, 0.5, ALWAYS},
{"both-past", 2, 3, D32, "plain", CLIP, INSIDE, 0.5, ALWAYS},
};
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) run_case(&cases[i]);
P("done");
}
return 0;
}
@@ -0,0 +1,470 @@
{
"format": 1,
"case": "block-writes-only-writes",
"suite_version": 1,
"shaders": [
{
"fixture": "fpv_srgb_storage.ll",
"entry": "fpv_srgb_write",
"source_sha256": "1fd72038430e03760b7c9f3096b2babe5056900741128527111e4a801627d51a"
},
{
"fixture": "fpv_srgb_storage.air.ll",
"entry": "fpv_srgb_write",
"source_sha256": "61b9ec9c9f1a8c33f6f3735b399078d2c1b225f723323f1ced884a16b4524d75"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1fd72038430e03760b7c9f3096b2babe5056900741128527111e4a801627d51a"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "61b9ec9c9f1a8c33f6f3735b399078d2c1b225f723323f1ced884a16b4524d75"
}
}
},
{
"name": "buffer:0",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "57d0319aadc26913b6ea046b49d2c507337b6b165d642f3ebf4416cec7fc340c"
}
}
},
{
"name": "buffer:1",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "097328e8c957de2428283954f6a1ee8ff7ad7def12e100a600178407f5decf24"
}
}
},
{
"name": "usage-0x10005",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "fcb07099b8ea07b6bb835217dae8b2b58388361662a2866ecd32fd5a902aa195"
}
}
},
{
"name": "usage-0x10000",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2df39b56c7b28ac6609132b8fa6689918bf3320a39cd0326ae685e92691b743f"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer/0",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer/width",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "usage-0x10005/texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "usage-0x10005/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "usage-0x10005/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "usage-0x10005/texels",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "usage-0x10005/stored",
"observed": {
"value": {
"bytes": "AP8A/xDvJf4g30r9MM9v/EC/lPtQr7n6YJ/e+XCPA/iAfyj3kG9N9qBfcvWwT5f0wD+889Av4fLgHwbx8A8r8A=="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
16,
1,
1
]
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 64,
"row_pitch": 64,
"rows": 1,
"image_pitch": 64,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "usage-0x10000/texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "usage-0x10000/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "usage-0x10000/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "usage-0x10000/texels",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "usage-0x10000/stored",
"observed": {
"value": {
"bytes": "AP8A/xDvJf4g30r9MM9v/EC/lPtQr7n6YJ/e+XCPA/iAfyj3kG9N9qBfcvWwT5f0wD+889Av4fLgHwbx8A8r8A=="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
16,
1,
1
]
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 64,
"row_pitch": 64,
"rows": 1,
"image_pitch": 64,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 13.20",
"instrument": 281,
"times": {
"case": "block-writes-only-writes",
"calls": 12,
"in_calls": 31871083,
"on_cpu": 1321585,
"blocked": 30603626,
"elsewhere": 3358500,
"spend": 35193665,
"spend_least": 34528832,
"spend_most": 354111042,
"per_call": [
{
"call": "buffer",
"least_calls": 2,
"most_calls": 2,
"wall": 7500,
"on_cpu": 7708,
"blocked": 0,
"wall_least": 6833,
"wall_most": 9292,
"wall_total": 43209,
"on_cpu_total": 43667,
"blocked_total": 0
},
{
"call": "compute_pipeline",
"least_calls": 1,
"most_calls": 1,
"wall": 120250,
"on_cpu": 120750,
"blocked": 0,
"wall_least": 112125,
"wall_most": 1516416,
"wall_total": 120250,
"on_cpu_total": 120750,
"blocked_total": 0
},
{
"call": "dispatch",
"least_calls": 2,
"most_calls": 2,
"wall": 54500,
"on_cpu": 54709,
"blocked": 0,
"wall_least": 48292,
"wall_most": 60708,
"wall_total": 215292,
"on_cpu_total": 215666,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 27120084,
"on_cpu": 754209,
"blocked": 26324834,
"wall_least": 26707125,
"wall_most": 344126959,
"wall_total": 27120084,
"on_cpu_total": 754209,
"blocked_total": 26324834
},
{
"call": "read_texture",
"least_calls": 2,
"most_calls": 2,
"wall": 8166,
"on_cpu": 8375,
"blocked": 0,
"wall_least": 6125,
"wall_most": 12875,
"wall_total": 22374,
"on_cpu_total": 22709,
"blocked_total": 0
},
{
"call": "texture",
"least_calls": 2,
"most_calls": 2,
"wall": 51125,
"on_cpu": 51459,
"blocked": 0,
"wall_least": 49833,
"wall_most": 67750,
"wall_total": 112375,
"on_cpu_total": 112875,
"blocked_total": 0
},
{
"call": "wait",
"least_calls": 2,
"most_calls": 2,
"wall": 182334,
"on_cpu": 12292,
"blocked": 168001,
"wall_least": 172166,
"wall_most": 446959,
"wall_total": 4002000,
"on_cpu_total": 37833,
"blocked_total": 3956916
}
]
}
}
]
}
@@ -0,0 +1,394 @@
{
"format": 1,
"case": "compute-imageblock-slice-past-the-grid",
"suite_version": 1,
"shaders": [
{
"fixture": "tib_imageblock_slices.ll",
"entry": "tib_slot_half_slice",
"source_sha256": "e00dc828bc21cb59ff668559851fa8347208d36224e01e453c86090ab2b02609"
},
{
"fixture": "tib_imageblock_slices.air.ll",
"entry": "tib_slot_half_slice",
"source_sha256": "312d30f0c139ef278848e46bd114721c293f696ea15e331c555d73cce7204f2d"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "e00dc828bc21cb59ff668559851fa8347208d36224e01e453c86090ab2b02609"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "312d30f0c139ef278848e46bd114721c293f696ea15e331c555d73cce7204f2d"
}
}
},
{
"name": "entry",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "5811b06bddd6bca69b4920fba706707791afbfb9d86ce0fe8988d67ed561b83b"
}
}
},
{
"name": "texture:fill",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "812f3ff8152a5c6495088c0a040344831904a9ab5eeef3a59e18b43a8c52d123"
}
}
},
{
"name": "pass",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "57b97704c85415bc8c5702b34343a3460663ffa357a739b595dab79093ea4982"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pass",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "outcome",
"observed": {
"value": "absent"
},
"children": [
{
"name": "dispatch_type",
"observed": {
"value": {
"variant": {
"name": "Serial",
"payload": "absent"
}
}
}
},
{
"name": "status",
"observed": {
"value": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
},
{
"name": "error",
"observed": {
"value": {
"variant": {
"name": "None",
"payload": "absent"
}
}
}
},
{
"name": "step/0/setComputePipelineState",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "step/1/setTexture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "step/2/setImageblockWidth",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "step/3/dispatchThreads",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
}
]
},
{
"name": "read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texels",
"observed": {
"value": {
"bytes": "ACQAAAAAAAAAKAAAAAAAAAAqAAAAAAAAACwAAAAAAAAALQAAAAAAAAAuAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAwAAAAAAAAADEAAAAAAACAMQAAAAAAAAAyAAAAAAAAgDIAAAAAAAAAMwAAAAAAAAAAAAAAAAAAAAAAAAAAAABANAAAAAAAAIA0AAAAAAAAwDQAAAAAAAAANQAAAAAAAEA1AAAAAAAAgDUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQDYAAAAAAACANgAAAAAAAMA2AAAAAAAAADcAAAAAAABANwAAAAAAAIA3AAAAAAAAAAAAAAAAAAAAAAAAAAAAACA4AAAAAAAAQDgAAAAAAABgOAAAAAAAAIA4AAAAAAAAoDgAAAAAAADAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgOQAAAAAAAEA5AAAAAAAAYDkAAAAAAACAOQAAAAAAAKA5AAAAAAAAwDkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIDoAAAAAAABAOgAAAAAAAGA6AAAAAAAAgDoAAAAAAACgOgAAAAAAAMA6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
8,
8,
1
]
}
},
"element": "u16",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 8,
"rows": 64,
"image_pitch": 512,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 11.10",
"instrument": 231,
"times": {
"case": "compute-imageblock-slice-past-the-grid",
"calls": 5,
"in_calls": 31462875,
"on_cpu": 958584,
"blocked": 30501583,
"elsewhere": 3575750,
"spend": 35048708,
"spend_least": 34369333,
"spend_most": 44478166,
"per_call": [
{
"call": "compute_pass",
"least_calls": 1,
"most_calls": 1,
"wall": 4232083,
"on_cpu": 139666,
"blocked": 4089084,
"wall_least": 4057792,
"wall_most": 4507792,
"wall_total": 4232083,
"on_cpu_total": 139666,
"blocked_total": 4089084
},
{
"call": "compute_pipeline",
"least_calls": 1,
"most_calls": 1,
"wall": 106500,
"on_cpu": 106708,
"blocked": 0,
"wall_least": 92291,
"wall_most": 1042583,
"wall_total": 106500,
"on_cpu_total": 106708,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 27078750,
"on_cpu": 646583,
"blocked": 26401917,
"wall_least": 26175250,
"wall_most": 36828500,
"wall_total": 27078750,
"on_cpu_total": 646583,
"blocked_total": 26401917
},
{
"call": "read_texture",
"least_calls": 1,
"most_calls": 1,
"wall": 3000,
"on_cpu": 3250,
"blocked": 0,
"wall_least": 2667,
"wall_most": 4833,
"wall_total": 3000,
"on_cpu_total": 3250,
"blocked_total": 0
},
{
"call": "texture_2d_in_role",
"least_calls": 1,
"most_calls": 1,
"wall": 42250,
"on_cpu": 42459,
"blocked": 0,
"wall_least": 36584,
"wall_most": 59334,
"wall_total": 42250,
"on_cpu_total": 42459,
"blocked_total": 0
}
]
}
}
]
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,423 @@
{
"format": 1,
"case": "indirect-range-gpu-written-indexed-patch-draws",
"suite_version": 1,
"shaders": [
{
"fixture": "icb_merged_ipatches.ll",
"entry": "icb_merged_ipatches",
"source_sha256": "b25e68cedf24679d06f1c9c5b578dd24f9a6765c2730fe64c6748ec5ad9b8a94"
},
{
"fixture": "icb_merged_ipatches.air.ll",
"entry": "icb_merged_ipatches",
"source_sha256": "2e5e19c3a9c01d97e61c6ce7a55ecda1bb1cf7f5d078a5333db1f022ae68bf15"
},
{
"fixture": "icb_merged_ipatches.ll",
"entry": "icb_merged_ipatch_vertex",
"source_sha256": "b25e68cedf24679d06f1c9c5b578dd24f9a6765c2730fe64c6748ec5ad9b8a94"
},
{
"fixture": "icb_merged_ipatches.air.ll",
"entry": "icb_merged_ipatch_vertex",
"source_sha256": "2e5e19c3a9c01d97e61c6ce7a55ecda1bb1cf7f5d078a5333db1f022ae68bf15"
},
{
"fixture": "icb_merged_ipatches.ll",
"entry": "icb_merged_ipatch_fragment",
"source_sha256": "b25e68cedf24679d06f1c9c5b578dd24f9a6765c2730fe64c6748ec5ad9b8a94"
},
{
"fixture": "icb_merged_ipatches.air.ll",
"entry": "icb_merged_ipatch_fragment",
"source_sha256": "2e5e19c3a9c01d97e61c6ce7a55ecda1bb1cf7f5d078a5333db1f022ae68bf15"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b25e68cedf24679d06f1c9c5b578dd24f9a6765c2730fe64c6748ec5ad9b8a94"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2e5e19c3a9c01d97e61c6ce7a55ecda1bb1cf7f5d078a5333db1f022ae68bf15"
}
}
},
{
"name": "buffer:draws",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "0ce15fd22a62915fa73eb0f74d4591d48fbac3a3a7dd63add596ed5b943412d2"
}
}
},
{
"name": "buffer:marks",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2c050a4484712374bc0061534a9607f09e7bfa43dc246463b34d80eef0210fe7"
}
}
},
{
"name": "buffer:frame",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b7013c015db61a3fe79e6983697779e6f0d0cfa795ace130f2401424d94011c6"
}
}
},
{
"name": "buffer:corners",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "8387c9b2878550caca811c4689d84a51a39d96acd7883990dcafe6ce0c31ff36"
}
}
},
{
"name": "buffer:points",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "141f3df317a7b672aacc4d44f1571d23abbc11b483ee9e66678f5f2eb2f69184"
}
}
},
{
"name": "buffer:factors",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "6b915313f9a35aa1187c128f7a0b39416b7dde4a3c97d63fa1b1715a6630bd95"
}
}
},
{
"name": "buffer:range",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "dbec72d7af153cd0a8a4b33054d8ea7329136a5fc88f017d984653e93ce0b4a4"
}
}
},
{
"name": "buffer:copied-range",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "eca75f8497701d6223817cde38bf42cdd1124e01ef6b705bcfe9a584f7b42f0f"
}
}
},
{
"name": "execution",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "ad2aac34e8f61b894e782c47a2726c16f0dbbdf9789d95c68247c828bbad2621"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:draws",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:marks",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:frame",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:corners",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:points",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:factors",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:range",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:copied-range",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "execution",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "target-texels",
"observed": {
"value": {
"bytes": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
8,
16,
1
]
}
},
"element": "u32",
"row_offset": 0,
"row_elements": 32,
"row_pitch": 128,
"rows": 16,
"image_pitch": 2048,
"images": 1,
"gaps": "compared"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 10.54",
"instrument": 241,
"times": {
"case": "indirect-range-gpu-written-indexed-patch-draws",
"calls": 10,
"in_calls": 36194957,
"on_cpu": 1482498,
"blocked": 34785959,
"elsewhere": 8260000,
"spend": 44425792,
"spend_least": 43452459,
"spend_most": 46478627,
"per_call": [
{
"call": "buffer",
"least_calls": 8,
"most_calls": 8,
"wall": 2125,
"on_cpu": 2250,
"blocked": 0,
"wall_least": 1875,
"wall_most": 2750,
"wall_total": 46791,
"on_cpu_total": 48251,
"blocked_total": 0
},
{
"call": "encoded_range",
"least_calls": 1,
"most_calls": 1,
"wall": 9653625,
"on_cpu": 689792,
"blocked": 8828708,
"wall_least": 9103125,
"wall_most": 10684500,
"wall_total": 9653625,
"on_cpu_total": 689792,
"blocked_total": 8828708
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 26477750,
"on_cpu": 708084,
"blocked": 25811625,
"wall_least": 26255917,
"wall_most": 28317958,
"wall_total": 26477750,
"on_cpu_total": 708084,
"blocked_total": 25811625
}
]
}
}
]
}
@@ -0,0 +1,402 @@
{
"format": 1,
"case": "indirect-range-gpu-written-patch-draws",
"suite_version": 1,
"shaders": [
{
"fixture": "icb_merged_patches.ll",
"entry": "icb_merged_patches",
"source_sha256": "d71808b60017fb10c3b4cfcbc94106c0e463042539a5a7b167aebc68a6b9f0d6"
},
{
"fixture": "icb_merged_patches.air.ll",
"entry": "icb_merged_patches",
"source_sha256": "aad671f3480a454481577e25ee2c86d43b2b7cce5971456b1454319c59909219"
},
{
"fixture": "icb_merged_patches.ll",
"entry": "icb_merged_patch_vertex",
"source_sha256": "d71808b60017fb10c3b4cfcbc94106c0e463042539a5a7b167aebc68a6b9f0d6"
},
{
"fixture": "icb_merged_patches.air.ll",
"entry": "icb_merged_patch_vertex",
"source_sha256": "aad671f3480a454481577e25ee2c86d43b2b7cce5971456b1454319c59909219"
},
{
"fixture": "icb_merged_patches.ll",
"entry": "icb_merged_patch_fragment",
"source_sha256": "d71808b60017fb10c3b4cfcbc94106c0e463042539a5a7b167aebc68a6b9f0d6"
},
{
"fixture": "icb_merged_patches.air.ll",
"entry": "icb_merged_patch_fragment",
"source_sha256": "aad671f3480a454481577e25ee2c86d43b2b7cce5971456b1454319c59909219"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "d71808b60017fb10c3b4cfcbc94106c0e463042539a5a7b167aebc68a6b9f0d6"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "aad671f3480a454481577e25ee2c86d43b2b7cce5971456b1454319c59909219"
}
}
},
{
"name": "buffer:draws",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "0ce15fd22a62915fa73eb0f74d4591d48fbac3a3a7dd63add596ed5b943412d2"
}
}
},
{
"name": "buffer:marks",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2c050a4484712374bc0061534a9607f09e7bfa43dc246463b34d80eef0210fe7"
}
}
},
{
"name": "buffer:frame",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b7013c015db61a3fe79e6983697779e6f0d0cfa795ace130f2401424d94011c6"
}
}
},
{
"name": "buffer:xy",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "06eb16ee0c7fb7d2cce6f2d22c05ca75d3f43c96acd50cc50faa0b5cdaf67d0f"
}
}
},
{
"name": "buffer:factors",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "6b915313f9a35aa1187c128f7a0b39416b7dde4a3c97d63fa1b1715a6630bd95"
}
}
},
{
"name": "buffer:range",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "dbec72d7af153cd0a8a4b33054d8ea7329136a5fc88f017d984653e93ce0b4a4"
}
}
},
{
"name": "buffer:copied-range",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "eca75f8497701d6223817cde38bf42cdd1124e01ef6b705bcfe9a584f7b42f0f"
}
}
},
{
"name": "execution",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "47e37f4716e5483692d2930763ef674b40ebc015261a335cd1561a971ecab4fb"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:draws",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:marks",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:frame",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:xy",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:factors",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:range",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:copied-range",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "execution",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "target-texels",
"observed": {
"value": {
"bytes": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAABAQAAAQAAAAIAAAABAAAAAQEAAAEAAAACAAAAAQAAAAEBAAABAAAAAgAAAAEAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAgEAAAIAAAACAAAAAgAAAAIBAAACAAAAAgAAAAIAAAACAQAAAgAAAAIAAAACAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAMBAAADAAAABAAAAAMAAAADAQAAAwAAAAQAAAADAAAAAwEAAAMAAAAEAAAAAwAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAEAQAABAAAAAQAAAAEAAAABAEAAAQAAAAEAAAABAAAAAQBAAAEAAAABAAAAAQAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAABQEAAAUAAAAGAAAABQAAAAUBAAAFAAAABgAAAAUAAAAFAQAABQAAAAYAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
8,
16,
1
]
}
},
"element": "u32",
"row_offset": 0,
"row_elements": 32,
"row_pitch": 128,
"rows": 16,
"image_pitch": 2048,
"images": 1,
"gaps": "compared"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 9.22",
"instrument": 243,
"times": {
"case": "indirect-range-gpu-written-patch-draws",
"calls": 9,
"in_calls": 35987916,
"on_cpu": 1301625,
"blocked": 34623584,
"elsewhere": 8263083,
"spend": 44553706,
"spend_least": 43017916,
"spend_most": 51074958,
"per_call": [
{
"call": "buffer",
"least_calls": 7,
"most_calls": 7,
"wall": 2083,
"on_cpu": 2209,
"blocked": 0,
"wall_least": 1791,
"wall_most": 2459,
"wall_total": 41790,
"on_cpu_total": 42750,
"blocked_total": 0
},
{
"call": "encoded_range",
"least_calls": 1,
"most_calls": 1,
"wall": 9405375,
"on_cpu": 617625,
"blocked": 8797958,
"wall_least": 8986208,
"wall_most": 11068625,
"wall_total": 9405375,
"on_cpu_total": 617625,
"blocked_total": 8797958
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 26239083,
"on_cpu": 640542,
"blocked": 25567583,
"wall_least": 25508041,
"wall_most": 33501292,
"wall_total": 26239083,
"on_cpu_total": 640542,
"blocked_total": 25567583
}
]
}
}
]
}
@@ -0,0 +1,381 @@
{
"format": 1,
"case": "indirect-range-gpu-written-plain-draws",
"suite_version": 1,
"shaders": [
{
"fixture": "icb_merged_draws.ll",
"entry": "icb_merged_triangles",
"source_sha256": "62094586abf5f2e8b34451370f2110e510800d5f154fa05c3ad6726fda571ada"
},
{
"fixture": "icb_merged_draws.air.ll",
"entry": "icb_merged_triangles",
"source_sha256": "057557b1e38d8813b3b8284419f1ab80da59e0ba5736543e3dc3cff4ca48d622"
},
{
"fixture": "icb_merged_draws.ll",
"entry": "icb_merged_vertex",
"source_sha256": "62094586abf5f2e8b34451370f2110e510800d5f154fa05c3ad6726fda571ada"
},
{
"fixture": "icb_merged_draws.air.ll",
"entry": "icb_merged_vertex",
"source_sha256": "057557b1e38d8813b3b8284419f1ab80da59e0ba5736543e3dc3cff4ca48d622"
},
{
"fixture": "icb_merged_draws.ll",
"entry": "icb_merged_fragment",
"source_sha256": "62094586abf5f2e8b34451370f2110e510800d5f154fa05c3ad6726fda571ada"
},
{
"fixture": "icb_merged_draws.air.ll",
"entry": "icb_merged_fragment",
"source_sha256": "057557b1e38d8813b3b8284419f1ab80da59e0ba5736543e3dc3cff4ca48d622"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "62094586abf5f2e8b34451370f2110e510800d5f154fa05c3ad6726fda571ada"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "057557b1e38d8813b3b8284419f1ab80da59e0ba5736543e3dc3cff4ca48d622"
}
}
},
{
"name": "buffer:draws",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "a218b20cc7cb7430a0252189ca31754adb8261576bacf865b0476c1eeaaa5a2c"
}
}
},
{
"name": "buffer:marks",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2c050a4484712374bc0061534a9607f09e7bfa43dc246463b34d80eef0210fe7"
}
}
},
{
"name": "buffer:frame",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b7013c015db61a3fe79e6983697779e6f0d0cfa795ace130f2401424d94011c6"
}
}
},
{
"name": "buffer:xy",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2d1d34182af3ad3e082d0e0a210b30b782c1a506581fedd15b40447e2414c721"
}
}
},
{
"name": "buffer:range",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "dbec72d7af153cd0a8a4b33054d8ea7329136a5fc88f017d984653e93ce0b4a4"
}
}
},
{
"name": "buffer:copied-range",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "eca75f8497701d6223817cde38bf42cdd1124e01ef6b705bcfe9a584f7b42f0f"
}
}
},
{
"name": "execution",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "38a4728ce077a3a098320db29a766b6b7e727f063d0c724a232e1895a88507c9"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:draws",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:marks",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:frame",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:xy",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:range",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer:copied-range",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "execution",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "target-texels",
"observed": {
"value": {
"bytes": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEBAAAGAAAAAgAAAAEAAAABAQAABgAAAAIAAAABAAAAAQEAAAYAAAACAAAAAQAAAAEBAAAGAAAAAgAAAAEAAAABAQAABgAAAAIAAAABAAAAAQEAAAYAAAACAAAAAQAAAAEBAAAJAAAAAgAAAAEAAAABAQAACQAAAAIAAAABAAAAAQEAAAYAAAACAAAAAQAAAAEBAAAGAAAAAgAAAAEAAAABAQAACQAAAAIAAAABAAAAAQEAAAkAAAACAAAAAQAAAAEBAAAJAAAAAgAAAAEAAAABAQAACQAAAAIAAAABAAAAAQEAAAkAAAACAAAAAQAAAAEBAAAJAAAAAgAAAAEAAAACAQAADAAAAAIAAAACAAAAAgEAAAwAAAACAAAAAgAAAAIBAAAMAAAAAgAAAAIAAAACAQAADAAAAAIAAAACAAAAAgEAAAwAAAACAAAAAgAAAAIBAAAMAAAAAgAAAAIAAAACAQAADwAAAAIAAAACAAAAAgEAAA8AAAACAAAAAgAAAAIBAAAMAAAAAgAAAAIAAAACAQAADAAAAAIAAAACAAAAAgEAAA8AAAACAAAAAgAAAAIBAAAPAAAAAgAAAAIAAAACAQAADwAAAAIAAAACAAAAAgEAAA8AAAACAAAAAgAAAAIBAAAPAAAAAgAAAAIAAAACAQAADwAAAAIAAAACAAAAAwEAABIAAAAEAAAAAwAAAAMBAAASAAAABAAAAAMAAAADAQAAEgAAAAQAAAADAAAAAwEAABIAAAAEAAAAAwAAAAMBAAASAAAABAAAAAMAAAADAQAAEgAAAAQAAAADAAAAAwEAABUAAAAEAAAAAwAAAAMBAAAVAAAABAAAAAMAAAADAQAAEgAAAAQAAAADAAAAAwEAABIAAAAEAAAAAwAAAAMBAAAVAAAABAAAAAMAAAADAQAAFQAAAAQAAAADAAAAAwEAABUAAAAEAAAAAwAAAAMBAAAVAAAABAAAAAMAAAADAQAAFQAAAAQAAAADAAAAAwEAABUAAAAEAAAAAwAAAAQBAAAYAAAABAAAAAQAAAAEAQAAGAAAAAQAAAAEAAAABAEAABgAAAAEAAAABAAAAAQBAAAYAAAABAAAAAQAAAAEAQAAGAAAAAQAAAAEAAAABAEAABgAAAAEAAAABAAAAAQBAAAbAAAABAAAAAQAAAAEAQAAGwAAAAQAAAAEAAAABAEAABgAAAAEAAAABAAAAAQBAAAYAAAABAAAAAQAAAAEAQAAGwAAAAQAAAAEAAAABAEAABsAAAAEAAAABAAAAAQBAAAbAAAABAAAAAQAAAAEAQAAGwAAAAQAAAAEAAAABAEAABsAAAAEAAAABAAAAAQBAAAbAAAABAAAAAQAAAAFAQAAHgAAAAYAAAAFAAAABQEAAB4AAAAGAAAABQAAAAUBAAAeAAAABgAAAAUAAAAFAQAAHgAAAAYAAAAFAAAABQEAAB4AAAAGAAAABQAAAAUBAAAeAAAABgAAAAUAAAAFAQAAIQAAAAYAAAAFAAAABQEAACEAAAAGAAAABQAAAAUBAAAeAAAABgAAAAUAAAAFAQAAHgAAAAYAAAAFAAAABQEAACEAAAAGAAAABQAAAAUBAAAhAAAABgAAAAUAAAAFAQAAIQAAAAYAAAAFAAAABQEAACEAAAAGAAAABQAAAAUBAAAhAAAABgAAAAUAAAAFAQAAIQAAAAYAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
8,
16,
1
]
}
},
"element": "u32",
"row_offset": 0,
"row_elements": 32,
"row_pitch": 128,
"rows": 16,
"image_pitch": 2048,
"images": 1,
"gaps": "compared"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 8.69",
"instrument": 335,
"times": {
"case": "indirect-range-gpu-written-plain-draws",
"calls": 8,
"in_calls": 35681583,
"on_cpu": 1324710,
"blocked": 34355668,
"elsewhere": 8006709,
"spend": 43671958,
"spend_least": 43513917,
"spend_most": 360937126,
"per_call": [
{
"call": "buffer",
"least_calls": 6,
"most_calls": 6,
"wall": 2125,
"on_cpu": 2250,
"blocked": 0,
"wall_least": 2000,
"wall_most": 3958,
"wall_total": 37083,
"on_cpu_total": 38044,
"blocked_total": 0
},
{
"call": "encoded_range",
"least_calls": 1,
"most_calls": 1,
"wall": 9033125,
"on_cpu": 643250,
"blocked": 8376667,
"wall_least": 8846333,
"wall_most": 12209583,
"wall_total": 9033125,
"on_cpu_total": 643250,
"blocked_total": 8376667
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 26798167,
"on_cpu": 659500,
"blocked": 26109209,
"wall_least": 26143667,
"wall_most": 339176584,
"wall_total": 26798167,
"on_cpu_total": 659500,
"blocked_total": 26109209
}
]
}
}
]
}
@@ -0,0 +1,239 @@
{
"format": 1,
"case": "managed-named-address-only",
"suite_version": 1,
"shaders": [
{
"fixture": "examples/runtime_examples.ll",
"entry": "scale_and_offset",
"source_sha256": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
},
{
"fixture": "examples/runtime_examples.air.ll",
"entry": "scale_and_offset",
"source_sha256": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
},
{
"fixture": "ab_pointers.ll",
"entry": "ab_address",
"source_sha256": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
},
{
"fixture": "ab_pointers.air.ll",
"entry": "ab_address",
"source_sha256": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": {
"carried": {
"from": "an AMD Radeon Pro 5300M measurement under macOS 26.7.1, 8 rounds a reader (jobs 81602 and 81644), which found that a named Managed range reaches the GPU at the first commit whose encoders name the buffer, with its bytes as of that commit, and that a buffer no encoder names keeps the bytes its GPU copy last took",
"measured_on": "amd-radeon-pro-5300m"
}
},
"device": "apple-m3-max",
"runs": 8,
"outcomes": [
{
"runs": 8,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
}
}
},
{
"name": "air-typed:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
}
}
},
{
"name": "air:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
}
}
},
{
"name": "air-typed:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
}
},
{
"name": "contents:Synced",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "20c32b58f9dbd5416fe908e078a5ba1d76c369e08dc3c9d62c5c4e71ec4c9b05"
}
}
},
{
"name": "contents:Named",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2391a11b1f9ea5ba826528ca3c097c8d2144c199a679efe81e425ec575ee514e"
}
}
},
{
"name": "contents:Later",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "a18573742f763887800bcc4744b72900125a1b2c0e4b7a5f7f894aa3f9121d72"
}
}
},
{
"name": "reader",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "d80c9bf910f144738ef983724bc04bd6bd3f17c5c83ed57bedee1b1b9278e811"
}
}
}
]
},
{
"name": "examples",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pointers",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sequence",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "reads",
"observed": {
"value": {
"lines": [
"the bytes the GPU's copy last took"
]
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "not_run"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 11.59",
"instrument": 240,
"times": {
"case": "managed-named-address-only",
"calls": 0,
"in_calls": 0,
"on_cpu": 0,
"blocked": 0,
"elsewhere": 0,
"spend": 0,
"spend_least": 0,
"spend_most": 0,
"stopped": "the case forbids running its Metal leg here: the oracle keeps one copy of a Managed buffer (hasUnifiedMemory true), so its run answers what one copy holds, not which commit takes a range to a second copy",
"per_call": []
}
}
]
}
@@ -0,0 +1,239 @@
{
"format": 1,
"case": "managed-named-blit-source",
"suite_version": 1,
"shaders": [
{
"fixture": "examples/runtime_examples.ll",
"entry": "scale_and_offset",
"source_sha256": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
},
{
"fixture": "examples/runtime_examples.air.ll",
"entry": "scale_and_offset",
"source_sha256": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
},
{
"fixture": "ab_pointers.ll",
"entry": "ab_address",
"source_sha256": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
},
{
"fixture": "ab_pointers.air.ll",
"entry": "ab_address",
"source_sha256": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": {
"carried": {
"from": "an AMD Radeon Pro 5300M measurement under macOS 26.7.1, 8 rounds a reader (jobs 81602 and 81644), which found that a named Managed range reaches the GPU at the first commit whose encoders name the buffer, with its bytes as of that commit, and that a buffer no encoder names keeps the bytes its GPU copy last took",
"measured_on": "amd-radeon-pro-5300m"
}
},
"device": "apple-m3-max",
"runs": 8,
"outcomes": [
{
"runs": 8,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
}
}
},
{
"name": "air-typed:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
}
}
},
{
"name": "air:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
}
}
},
{
"name": "air-typed:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
}
},
{
"name": "contents:Synced",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "20c32b58f9dbd5416fe908e078a5ba1d76c369e08dc3c9d62c5c4e71ec4c9b05"
}
}
},
{
"name": "contents:Named",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2391a11b1f9ea5ba826528ca3c097c8d2144c199a679efe81e425ec575ee514e"
}
}
},
{
"name": "contents:Later",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "a18573742f763887800bcc4744b72900125a1b2c0e4b7a5f7f894aa3f9121d72"
}
}
},
{
"name": "reader",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1b2e19108e54dc09c92e23b90c30f27cda0ce0147bdaaf8c3971fff9b8f730b5"
}
}
}
]
},
{
"name": "examples",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pointers",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sequence",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "reads",
"observed": {
"value": {
"lines": [
"the bytes as of the reader's commit"
]
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "not_run"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 11.59",
"instrument": 240,
"times": {
"case": "managed-named-blit-source",
"calls": 0,
"in_calls": 0,
"on_cpu": 0,
"blocked": 0,
"elsewhere": 0,
"spend": 0,
"spend_least": 0,
"spend_most": 0,
"stopped": "the case forbids running its Metal leg here: the oracle keeps one copy of a Managed buffer (hasUnifiedMemory true), so its run answers what one copy holds, not which commit takes a range to a second copy",
"per_call": []
}
}
]
}
@@ -0,0 +1,239 @@
{
"format": 1,
"case": "managed-named-compute-slot",
"suite_version": 1,
"shaders": [
{
"fixture": "examples/runtime_examples.ll",
"entry": "scale_and_offset",
"source_sha256": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
},
{
"fixture": "examples/runtime_examples.air.ll",
"entry": "scale_and_offset",
"source_sha256": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
},
{
"fixture": "ab_pointers.ll",
"entry": "ab_address",
"source_sha256": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
},
{
"fixture": "ab_pointers.air.ll",
"entry": "ab_address",
"source_sha256": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": {
"carried": {
"from": "an AMD Radeon Pro 5300M measurement under macOS 26.7.1, 8 rounds a reader (jobs 81602 and 81644), which found that a named Managed range reaches the GPU at the first commit whose encoders name the buffer, with its bytes as of that commit, and that a buffer no encoder names keeps the bytes its GPU copy last took",
"measured_on": "amd-radeon-pro-5300m"
}
},
"device": "apple-m3-max",
"runs": 8,
"outcomes": [
{
"runs": 8,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
}
}
},
{
"name": "air-typed:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
}
}
},
{
"name": "air:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
}
}
},
{
"name": "air-typed:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
}
},
{
"name": "contents:Synced",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "20c32b58f9dbd5416fe908e078a5ba1d76c369e08dc3c9d62c5c4e71ec4c9b05"
}
}
},
{
"name": "contents:Named",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2391a11b1f9ea5ba826528ca3c097c8d2144c199a679efe81e425ec575ee514e"
}
}
},
{
"name": "contents:Later",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "a18573742f763887800bcc4744b72900125a1b2c0e4b7a5f7f894aa3f9121d72"
}
}
},
{
"name": "reader",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "55407f997e7be480140400a823d6eaf8df8b9088782e4e0399c05d73705f6c38"
}
}
}
]
},
{
"name": "examples",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pointers",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sequence",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "reads",
"observed": {
"value": {
"lines": [
"the bytes as of the reader's commit"
]
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "not_run"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 11.59",
"instrument": 240,
"times": {
"case": "managed-named-compute-slot",
"calls": 0,
"in_calls": 0,
"on_cpu": 0,
"blocked": 0,
"elsewhere": 0,
"spend": 0,
"spend_least": 0,
"spend_most": 0,
"stopped": "the case forbids running its Metal leg here: the oracle keeps one copy of a Managed buffer (hasUnifiedMemory true), so its run answers what one copy holds, not which commit takes a range to a second copy",
"per_call": []
}
}
]
}
@@ -0,0 +1,239 @@
{
"format": 1,
"case": "managed-named-declared",
"suite_version": 1,
"shaders": [
{
"fixture": "examples/runtime_examples.ll",
"entry": "scale_and_offset",
"source_sha256": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
},
{
"fixture": "examples/runtime_examples.air.ll",
"entry": "scale_and_offset",
"source_sha256": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
},
{
"fixture": "ab_pointers.ll",
"entry": "ab_address",
"source_sha256": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
},
{
"fixture": "ab_pointers.air.ll",
"entry": "ab_address",
"source_sha256": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": {
"carried": {
"from": "an AMD Radeon Pro 5300M measurement under macOS 26.7.1, 8 rounds a reader (jobs 81602 and 81644), which found that a named Managed range reaches the GPU at the first commit whose encoders name the buffer, with its bytes as of that commit, and that a buffer no encoder names keeps the bytes its GPU copy last took",
"measured_on": "amd-radeon-pro-5300m"
}
},
"device": "apple-m3-max",
"runs": 8,
"outcomes": [
{
"runs": 8,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
}
}
},
{
"name": "air-typed:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
}
}
},
{
"name": "air:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
}
}
},
{
"name": "air-typed:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
}
},
{
"name": "contents:Synced",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "20c32b58f9dbd5416fe908e078a5ba1d76c369e08dc3c9d62c5c4e71ec4c9b05"
}
}
},
{
"name": "contents:Named",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2391a11b1f9ea5ba826528ca3c097c8d2144c199a679efe81e425ec575ee514e"
}
}
},
{
"name": "contents:Later",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "a18573742f763887800bcc4744b72900125a1b2c0e4b7a5f7f894aa3f9121d72"
}
}
},
{
"name": "reader",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "f833228cb8681bbf3e38af9de7a212dfc542b3e3ba1312ec8a45bb2b67605dc7"
}
}
}
]
},
{
"name": "examples",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pointers",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sequence",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "reads",
"observed": {
"value": {
"lines": [
"the bytes as of the reader's commit"
]
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "not_run"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 11.59",
"instrument": 240,
"times": {
"case": "managed-named-declared",
"calls": 0,
"in_calls": 0,
"on_cpu": 0,
"blocked": 0,
"elsewhere": 0,
"spend": 0,
"spend_least": 0,
"spend_most": 0,
"stopped": "the case forbids running its Metal leg here: the oracle keeps one copy of a Managed buffer (hasUnifiedMemory true), so its run answers what one copy holds, not which commit takes a range to a second copy",
"per_call": []
}
}
]
}
@@ -0,0 +1,239 @@
{
"format": 1,
"case": "managed-named-vertex-slot",
"suite_version": 1,
"shaders": [
{
"fixture": "examples/runtime_examples.ll",
"entry": "scale_and_offset",
"source_sha256": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
},
{
"fixture": "examples/runtime_examples.air.ll",
"entry": "scale_and_offset",
"source_sha256": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
},
{
"fixture": "ab_pointers.ll",
"entry": "ab_address",
"source_sha256": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
},
{
"fixture": "ab_pointers.air.ll",
"entry": "ab_address",
"source_sha256": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": {
"carried": {
"from": "an AMD Radeon Pro 5300M measurement under macOS 26.7.1, 8 rounds a reader (jobs 81602 and 81644), which found that a named Managed range reaches the GPU at the first commit whose encoders name the buffer, with its bytes as of that commit, and that a buffer no encoder names keeps the bytes its GPU copy last took",
"measured_on": "amd-radeon-pro-5300m"
}
},
"device": "apple-m3-max",
"runs": 8,
"outcomes": [
{
"runs": 8,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "fbe310c683c1e125803f56d76f76eaceda8d4b7a7f1968715a583b8fad27c7d6"
}
}
},
{
"name": "air-typed:examples",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "579cc33e08cdfb18fdb85de70d8d81983d280dd737b2ed4894483ca0faa6e880"
}
}
},
{
"name": "air:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "7e51361c89fa9dc5f98df57f99923c3a734abb96253a55bf992370f088c01315"
}
}
},
{
"name": "air-typed:pointers",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1fdd7761a65caebbf70a505edfcb95c4627ae1a8a2ec5eb856adc270f18206a2"
}
}
},
{
"name": "contents:Synced",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "20c32b58f9dbd5416fe908e078a5ba1d76c369e08dc3c9d62c5c4e71ec4c9b05"
}
}
},
{
"name": "contents:Named",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2391a11b1f9ea5ba826528ca3c097c8d2144c199a679efe81e425ec575ee514e"
}
}
},
{
"name": "contents:Later",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "a18573742f763887800bcc4744b72900125a1b2c0e4b7a5f7f894aa3f9121d72"
}
}
},
{
"name": "reader",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "af7ad0b82e4819d2859b5a0ef4a1f6f77d03e74795f9bf8595785db2a066ef30"
}
}
}
]
},
{
"name": "examples",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pointers",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "sequence",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "reads",
"observed": {
"value": {
"lines": [
"the bytes as of the reader's commit"
]
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "not_run"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 11.59",
"instrument": 240,
"times": {
"case": "managed-named-vertex-slot",
"calls": 0,
"in_calls": 0,
"on_cpu": 0,
"blocked": 0,
"elsewhere": 0,
"spend": 0,
"spend_least": 0,
"spend_most": 0,
"stopped": "the case forbids running its Metal leg here: the oracle keeps one copy of a Managed buffer (hasUnifiedMemory true), so its run answers what one copy holds, not which commit takes a range to a second copy",
"per_call": []
}
}
]
}
@@ -0,0 +1,324 @@
{
"format": 1,
"case": "sample-positions-8x-custom-left",
"suite_version": 1,
"shaders": [
{
"fixture": "rt6_restart.ll",
"entry": "rt6_restart_vertex+rt6_restart_count",
"source_sha256": "ee3fb102a9172fb5214a2c468b5fb177a7000fb169043ed578a12dd5b43c0464"
},
{
"fixture": "rt6_restart.air.ll",
"entry": "rt6_restart_vertex+rt6_restart_count",
"source_sha256": "08138096f5f8bef1f56267558b5bbbf1c9780e08bae5d84b87f3da4025ab6d09"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": {
"carried": {
"from": "an AMD Radeon Pro 5300M under macOS 26.7.1 (job 82284): the family's pass at 8 samples, plain and under Metal's API validation layer, one run each",
"measured_on": "amd-radeon-pro-5300m"
}
},
"device": "apple-m3-max",
"runs": 1,
"outcomes": [
{
"runs": 1,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "ee3fb102a9172fb5214a2c468b5fb177a7000fb169043ed578a12dd5b43c0464"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "08138096f5f8bef1f56267558b5bbbf1c9780e08bae5d84b87f3da4025ab6d09"
}
}
},
{
"name": "render-pipeline",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "03f5943fa208ea15062a63d582f15aae90bb31a792f25b55a2e32f5d92791dfc"
}
}
},
{
"name": "target",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "46be23a3b9ab948bd0549700811244dda8e20f669e98aec2361cbff5c3cae246"
}
}
},
{
"name": "resolve",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "84d9f4366da2d180bd2c9a0c0c0ec5a5f91d7e745b28088b7971335c2aa913fb"
}
}
},
{
"name": "pass",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "93c0b0f95c6553ffab21916ad615f43281c739a17cb231feff569c06f875698f"
}
}
},
{
"name": "vertices",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "f2df32a2160f721d5a70c07c8cbc9134e1e986712ebd31c961c3bac754d632d2"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "render-pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "target",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "resolve",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "vertices",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "calls",
"observed": {
"value": "absent"
},
"children": [
{
"name": "0-renderCommandEncoder",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "1-copyFromTextureToBuffer",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
}
]
},
{
"name": "status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "coverage",
"observed": {
"value": {
"lines": [
"8 of 8 samples"
]
}
}
},
{
"name": "resolved",
"observed": {
"value": {
"bytes": "AQAA/w=="
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 4,
"rows": 1,
"image_pitch": 4,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "not_run"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 7.63",
"instrument": 288,
"times": {
"case": "sample-positions-8x-custom-left",
"calls": 0,
"in_calls": 0,
"on_cpu": 0,
"blocked": 0,
"elsewhere": 0,
"spend": 0,
"spend_least": 0,
"spend_most": 0,
"stopped": "the case forbids running its Metal leg here: the oracle renders no 8 samples (an Apple M3 Max answers supportsTextureSampleCount: no for 8), so a record run there must not encode an 8-sample texture",
"per_call": []
}
}
]
}
@@ -0,0 +1,324 @@
{
"format": 1,
"case": "sample-positions-8x-custom-mixed",
"suite_version": 1,
"shaders": [
{
"fixture": "rt6_restart.ll",
"entry": "rt6_restart_vertex+rt6_restart_count",
"source_sha256": "ee3fb102a9172fb5214a2c468b5fb177a7000fb169043ed578a12dd5b43c0464"
},
{
"fixture": "rt6_restart.air.ll",
"entry": "rt6_restart_vertex+rt6_restart_count",
"source_sha256": "08138096f5f8bef1f56267558b5bbbf1c9780e08bae5d84b87f3da4025ab6d09"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": {
"carried": {
"from": "an AMD Radeon Pro 5300M under macOS 26.7.1 (job 82284): the family's pass at 8 samples, plain and under Metal's API validation layer, one run each",
"measured_on": "amd-radeon-pro-5300m"
}
},
"device": "apple-m3-max",
"runs": 1,
"outcomes": [
{
"runs": 1,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "ee3fb102a9172fb5214a2c468b5fb177a7000fb169043ed578a12dd5b43c0464"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "08138096f5f8bef1f56267558b5bbbf1c9780e08bae5d84b87f3da4025ab6d09"
}
}
},
{
"name": "render-pipeline",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "03f5943fa208ea15062a63d582f15aae90bb31a792f25b55a2e32f5d92791dfc"
}
}
},
{
"name": "target",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "46be23a3b9ab948bd0549700811244dda8e20f669e98aec2361cbff5c3cae246"
}
}
},
{
"name": "resolve",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "84d9f4366da2d180bd2c9a0c0c0ec5a5f91d7e745b28088b7971335c2aa913fb"
}
}
},
{
"name": "pass",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "d87c873f5ca0e3476ac05aaa450b32d24bb1d91d199500d0fb52aa62b7ffdcc1"
}
}
},
{
"name": "vertices",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "f2df32a2160f721d5a70c07c8cbc9134e1e986712ebd31c961c3bac754d632d2"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "render-pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "target",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "resolve",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "vertices",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "calls",
"observed": {
"value": "absent"
},
"children": [
{
"name": "0-renderCommandEncoder",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "1-copyFromTextureToBuffer",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
}
]
},
{
"name": "status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "coverage",
"observed": {
"value": {
"lines": [
"1 of 8 samples"
]
}
}
},
{
"name": "resolved",
"observed": {
"value": {
"bytes": "AAAAIA=="
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 4,
"rows": 1,
"image_pitch": 4,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "not_run"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 7.63",
"instrument": 288,
"times": {
"case": "sample-positions-8x-custom-mixed",
"calls": 0,
"in_calls": 0,
"on_cpu": 0,
"blocked": 0,
"elsewhere": 0,
"spend": 0,
"spend_least": 0,
"spend_most": 0,
"stopped": "the case forbids running its Metal leg here: the oracle renders no 8 samples (an Apple M3 Max answers supportsTextureSampleCount: no for 8), so a record run there must not encode an 8-sample texture",
"per_call": []
}
}
]
}
@@ -0,0 +1,324 @@
{
"format": 1,
"case": "sample-positions-8x-default",
"suite_version": 1,
"shaders": [
{
"fixture": "rt6_restart.ll",
"entry": "rt6_restart_vertex+rt6_restart_count",
"source_sha256": "ee3fb102a9172fb5214a2c468b5fb177a7000fb169043ed578a12dd5b43c0464"
},
{
"fixture": "rt6_restart.air.ll",
"entry": "rt6_restart_vertex+rt6_restart_count",
"source_sha256": "08138096f5f8bef1f56267558b5bbbf1c9780e08bae5d84b87f3da4025ab6d09"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": {
"carried": {
"from": "an AMD Radeon Pro 5300M under macOS 26.7.1 (job 82284): the family's pass at 8 samples, plain and under Metal's API validation layer, one run each",
"measured_on": "amd-radeon-pro-5300m"
}
},
"device": "apple-m3-max",
"runs": 1,
"outcomes": [
{
"runs": 1,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "ee3fb102a9172fb5214a2c468b5fb177a7000fb169043ed578a12dd5b43c0464"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "08138096f5f8bef1f56267558b5bbbf1c9780e08bae5d84b87f3da4025ab6d09"
}
}
},
{
"name": "render-pipeline",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "03f5943fa208ea15062a63d582f15aae90bb31a792f25b55a2e32f5d92791dfc"
}
}
},
{
"name": "target",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "46be23a3b9ab948bd0549700811244dda8e20f669e98aec2361cbff5c3cae246"
}
}
},
{
"name": "resolve",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "84d9f4366da2d180bd2c9a0c0c0ec5a5f91d7e745b28088b7971335c2aa913fb"
}
}
},
{
"name": "pass",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "332dff968c8d5130d43c6b0e1a050413da9aefb004b8c46bd9344136283bb30d"
}
}
},
{
"name": "vertices",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "1a2ae8d6b0ceafa23db4dce5d5c4df98fa10a8ab3c8e382a230e022c63501385"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "render-pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "target",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "resolve",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "vertices",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "calls",
"observed": {
"value": "absent"
},
"children": [
{
"name": "0-renderCommandEncoder",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "1-copyFromTextureToBuffer",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
}
]
},
{
"name": "status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "coverage",
"observed": {
"value": {
"lines": [
"5 of 8 samples"
]
}
}
},
{
"name": "resolved",
"observed": {
"value": {
"bytes": "AQAAnw=="
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 4
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 4,
"row_pitch": 4,
"rows": 1,
"image_pitch": 4,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "not_run"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 7.63",
"instrument": 288,
"times": {
"case": "sample-positions-8x-default",
"calls": 0,
"in_calls": 0,
"on_cpu": 0,
"blocked": 0,
"elsewhere": 0,
"spend": 0,
"spend_least": 0,
"spend_most": 0,
"stopped": "the case forbids running its Metal leg here: the oracle renders no 8 samples (an Apple M3 Max answers supportsTextureSampleCount: no for 8), so a record run there must not encode an 8-sample texture",
"per_call": []
}
}
]
}
@@ -0,0 +1,351 @@
{
"format": 1,
"case": "sparse-status-plain",
"suite_version": 1,
"shaders": [
{
"fixture": "a2_sparse_status.ll",
"entry": "a2_sparse_status",
"source_sha256": "2be5a69bf51b85f711ea5cacf20dfed7108513c4298a7527c3ad4c37a457cf7e"
},
{
"fixture": "a2_sparse_status.air.ll",
"entry": "a2_sparse_status",
"source_sha256": "6a51e0c342640c58c9d39bbf70bb0cc28c230053e0ecaa9ccd64322030f032c2"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "2be5a69bf51b85f711ea5cacf20dfed7108513c4298a7527c3ad4c37a457cf7e"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "6a51e0c342640c58c9d39bbf70bb0cc28c230053e0ecaa9ccd64322030f032c2"
}
}
},
{
"name": "texture:sampled",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "75d705f39f984107bafb11e9d2fbd2d7e187e5ce1a52cda14d4bd685d09aebb0"
}
}
},
{
"name": "texture:read",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "9aa2a2bacda0da1efd1381c19ff13a66add7b19ea2be8c3b9dbb2065d27e5206"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texture/sampled",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "texture/read",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer/out",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "stored",
"observed": {
"value": {
"bytes": "AACAPgAAAD8AAAAAAACAPwAAgD4AAKA/AACgPwAAgD4AAEA/AACAPgAAAD8AAAA/AQAAAAEAAAABAAAAogAAAAAAoD8AAAA/AACAPQAAgD8AAKA/AAAQQAAAEEAAAKA/AADgPwAAgD4AABA/AAAAPwEAAAABAAAAAQAAAKIAAAAAABBAAAAAPwAAAD4AAIA/AAAQQAAAUEAAAFBAAAAQQAAAMEAAAIA+AAAgPwAAAD8BAAAAAQAAAAEAAACiAAAAAABQQAAAAD8AAEA+AACAPwAAUEAAAFBAAABQQAAAUEAAAHBAAACAPgAAMD8AAAA/AQAAAAEAAAABAAAAogAAAAAAgD4AAMA/AACAPgAAgD8AAIA+AACgPwAAoD8AAIA+AABAPwAAoD8AAEA/AAAAPwEAAAABAAAAAQAAAKIAAAAAAKA/AADAPwAAoD4AAIA/AACgPwAAEEAAABBAAACgPwAA4D8AAKA/AABQPwAAAD8BAAAAAQAAAAEAAACiAAAAAAAQQAAAwD8AAMA+AACAPwAAEEAAAFBAAABQQAAAEEAAADBAAACgPwAAYD8AAAA/AQAAAAEAAAABAAAAogAAAAAAUEAAAMA/AADgPgAAgD8AAFBAAABQQAAAUEAAAFBAAABwQAAAoD8AAHA/AAAAPwEAAAABAAAAAQAAAKIAAAAAAIA+AAAgQAAAAD8AAIA/AACAPgAAoD8AAKA/AACAPgAAQD8AABBAAACAPwAAAD8BAAAAAQAAAAEAAACiAAAAAACgPwAAIEAAABA/AACAPwAAoD8AABBAAAAQQAAAoD8AAOA/AAAQQAAAiD8AAAA/AQAAAAEAAAABAAAAogAAAAAAEEAAACBAAAAgPwAAgD8AABBAAABQQAAAUEAAABBAAAAwQAAAEEAAAJA/AAAAPwEAAAABAAAAAQAAAKIAAAAAAFBAAAAgQAAAMD8AAIA/AABQQAAAUEAAAFBAAABQQAAAcEAAABBAAACYPwAAAD8BAAAAAQAAAAEAAACiAAAAAACAPgAAYEAAAEA/AACAPwAAgD4AAKA/AACgPwAAgD4AAEA/AABQQAAAoD8AAAA/AQAAAAEAAAABAAAAogAAAAAAoD8AAGBAAABQPwAAgD8AAKA/AAAQQAAAEEAAAKA/AADgPwAAUEAAAKg/AAAAPwEAAAABAAAAAQAAAKIAAAAAABBAAABgQAAAYD8AAIA/AAAQQAAAUEAAAFBAAAAQQAAAMEAAAFBAAACwPwAAAD8BAAAAAQAAAAEAAACiAAAAAABQQAAAYEAAAHA/AACAPwAAUEAAAFBAAABQQAAAUEAAAHBAAABQQAAAuD8AAAA/AQAAAAEAAAABAAAAogAAAA=="
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 1024
}
},
"element": "u32",
"row_offset": 0,
"row_elements": 16,
"row_pitch": 64,
"rows": 16,
"image_pitch": 1024,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 12.22",
"instrument": 293,
"times": {
"case": "sparse-status-plain",
"calls": 8,
"in_calls": 33759586,
"on_cpu": 1273917,
"blocked": 32451042,
"elsewhere": 3828042,
"spend": 37595586,
"spend_least": 34959540,
"spend_most": 364203333,
"per_call": [
{
"call": "buffer",
"least_calls": 1,
"most_calls": 1,
"wall": 13708,
"on_cpu": 13875,
"blocked": 0,
"wall_least": 12250,
"wall_most": 47250,
"wall_total": 13708,
"on_cpu_total": 13875,
"blocked_total": 0
},
{
"call": "compute_pipeline",
"least_calls": 1,
"most_calls": 1,
"wall": 131167,
"on_cpu": 131584,
"blocked": 0,
"wall_least": 123667,
"wall_most": 1615167,
"wall_total": 131167,
"on_cpu_total": 131584,
"blocked_total": 0
},
{
"call": "dispatch_threads",
"least_calls": 1,
"most_calls": 1,
"wall": 175417,
"on_cpu": 175584,
"blocked": 0,
"wall_least": 168916,
"wall_most": 404667,
"wall_total": 175417,
"on_cpu_total": 175584,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 28968709,
"on_cpu": 773792,
"blocked": 28153626,
"wall_least": 26733333,
"wall_most": 353416250,
"wall_total": 28968709,
"on_cpu_total": 773792,
"blocked_total": 28153626
},
{
"call": "read_buffer",
"least_calls": 1,
"most_calls": 1,
"wall": 8250,
"on_cpu": 8500,
"blocked": 0,
"wall_least": 6875,
"wall_most": 9666,
"wall_total": 8250,
"on_cpu_total": 8500,
"blocked_total": 0
},
{
"call": "texture",
"least_calls": 2,
"most_calls": 2,
"wall": 38083,
"on_cpu": 38291,
"blocked": 0,
"wall_least": 35333,
"wall_most": 45000,
"wall_total": 127791,
"on_cpu_total": 128251,
"blocked_total": 0
},
{
"call": "wait",
"least_calls": 1,
"most_calls": 1,
"wall": 4287167,
"on_cpu": 23834,
"blocked": 4256334,
"wall_least": 4153250,
"wall_most": 4337500,
"wall_total": 4287167,
"on_cpu_total": 23834,
"blocked_total": 4256334
}
]
}
}
]
}
@@ -0,0 +1,760 @@
{
"format": 1,
"case": "srgb-storage-fragment-writes",
"suite_version": 1,
"shaders": [
{
"fixture": "fpv_srgb_draw_storage.ll",
"entry": "fpv_srgb_cover+fpv_srgb_fragment_write",
"source_sha256": "35dd732c5dc27582830992b27dfeed05647e9bd9c9977b23f103df3122ae225e"
},
{
"fixture": "fpv_srgb_draw_storage.air.ll",
"entry": "fpv_srgb_cover+fpv_srgb_fragment_write",
"source_sha256": "b4b2a37ad65ae7d5ac0619d7fd5786601468a85a3047bcde7e854f8412f6ab7b"
},
{
"fixture": "fpv_srgb_draw_storage.ll",
"entry": "fpv_srgb_cover+fpv_srgb_fragment_write_half",
"source_sha256": "35dd732c5dc27582830992b27dfeed05647e9bd9c9977b23f103df3122ae225e"
},
{
"fixture": "fpv_srgb_draw_storage.air.ll",
"entry": "fpv_srgb_cover+fpv_srgb_fragment_write_half",
"source_sha256": "b4b2a37ad65ae7d5ac0619d7fd5786601468a85a3047bcde7e854f8412f6ab7b"
}
],
"answers": [
{
"key": {
"chip": "apple-m3-max",
"os_version": "27.0.1",
"os_build": "26A434",
"metal_level": "27.0.1"
},
"provenance": "metal_run",
"device": "Apple M3 Max",
"runs": 3,
"outcomes": [
{
"runs": 3,
"transcript": {
"root": {
"name": "case",
"observed": {
"value": "absent"
},
"children": [
{
"name": "inputs",
"observed": {
"value": "absent"
},
"children": [
{
"name": "air",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "35dd732c5dc27582830992b27dfeed05647e9bd9c9977b23f103df3122ae225e"
}
}
},
{
"name": "air-typed",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "b4b2a37ad65ae7d5ac0619d7fd5786601468a85a3047bcde7e854f8412f6ab7b"
}
}
},
{
"name": "buffer:1",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "bf5e8ffa51a9e748985800c1d3d7f1a2a6ae7435136593ca8d9637e3f87c699c"
}
}
},
{
"name": "attachment",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "467d04c4e816c2c655992d28052cef204b216322e750da6f61201b8e84d48de4"
}
}
},
{
"name": "fpv_srgb_fragment_write/pipeline",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "aab2a1df4bf3fe9258270f83d86ecdec0b44cf044aefa24905a0cd235ffb24e4"
}
}
},
{
"name": "fpv_srgb_fragment_write/buffer:0",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "d04922fa8a9a89e9e7154b13f86ee53b8577a55039d63b1841a9dc09fcbac3a8"
}
}
},
{
"name": "fpv_srgb_fragment_write_half/pipeline",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "35846d793c51f78a7c1040ea71fceee7c1e410a48e6271c8103236711ea9041c"
}
}
},
{
"name": "fpv_srgb_fragment_write_half/buffer:0",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "d08866127ea15fb18bb754e0c61bc3c2e4392333b9cd28f4544b6e77aee06506"
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "f62e7fbd0b56f442221d9b2f93366fbe85bbc0c083bc9fff4589f79e1dde7803"
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "751eae77ae9d671d3c66bec6eb1b0e6359b8be839b8a93e5702d71e528297757"
}
}
}
]
},
{
"name": "library",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "buffer/width",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "fpv_srgb_fragment_write/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "fpv_srgb_fragment_write/buffer/0",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write/texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write/attachment",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write/draw",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write/pass",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write/texels",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write/stored",
"observed": {
"value": {
"bytes": "AP8AAAH+JQEC/UoCA/xvAwT7lAQF+rkFBvneBgf4AwcI9ygICfZNCQr1cgoL9JcLDPO8DA3y4Q0O8QYOD/ArDxDvUBAR7nUREu2aEhPsvxMU6+QUFeoJFRbpLhYX6FMXGOd4GBnmnRka5cIaG+TnGxzjDBwd4jEdHuFWHh/gex8g36AgId7FISLd6iIj3A8jJNs0JCXaWSUm2X4mJ9ijJyjXyCgp1u0pKtUSKivUNyss01wsLdKBLS7Rpi4v0MsvMM/wMDHOFTEyzToyM8xfMzTLhDQ1yqk1NsnONjfI8zc4xxg4OcY9OTrFYjo7xIc7PMOsPD3C0T0+wfY+P8AbP0C/QEBBvmVBQr2KQkO8r0NEu9RERbr5RUa5HkZHuENHSLdoSEm2jUlKtbJKS7TXS0yz/ExNsiFNTrFGTk+wa09Qr5BQUa61UVKt2lJTrP9TVKskVFWqSVVWqW5WV6iTV1inuFhZpt1ZWqUCWlukJ1tco0xcXaJxXV6hll5foLtfYJ/gYGGeBWFinSpiY5xPY2SbdGRlmpllZpm+ZmeY42dolwhoaZYtaWqVUmprlHdrbJOcbG2SwW1ukeZub5ALb3CPMHBxjlVxco16cnOMn3N0i8R0dYrpdXaJDnZ3iDN3eIdYeHmGfXl6haJ6e4THe3yD7Hx9ghF9foE2fn+AW3+Af4CAgX6lgYJ9yoKDfO+DhHsUhIV6OYWGeV6Gh3iDh4h3qIiJds2JinXyiot0F4uMczyMjXJhjY5xho6PcKuPkG/QkJFu9ZGSbRqSk2w/k5RrZJSVaomVlmmulpdo05eYZ/iYmWYdmZplQpqbZGebnGOMnJ1isZ2eYdaen2D7n6BfIKChXkWhol1qoqNcj6OkW7SkpVrZpaZZ/qanWCOnqFdIqKlWbamqVZKqq1S3q6xT3KytUgGtrlEmrq9QS6+wT3CwsU6VsbJNurKzTN+ztEsEtLVKKbW2SU62t0hzt7hHmLi5Rr25ukXiurtEB7u8Qyy8vUJRvb5Bdr6/QJu/wD/AwME+5cHCPQrCwzwvw8Q7VMTFOnnFxjmexsc4w8fIN+jIyTYNyco1MsrLNFfLzDN8zM0yoc3OMcbOzzDrz9AvENDRLjXR0i1a0tMsf9PUK6TU1SrJ1dYp7tbXKBPX2Cc42NkmXdnaJYLa2ySn29wjzNzdIvHd3iEW3t8gO9/gH2Dg4R6F4eIdquLjHM/j5Bv05OUaGeXmGT7m5xhj5+gXiOjpFq3p6hXS6usU9+vsExzs7RJB7e4RZu7vEIvv8A+w8PEO1fHyDfry8wwf8/QLRPT1Cmn19gmO9vcIs/f4B9j4+Qb9+foFIvr7BEf7/ANs/P0Ckf3+Abb+/wDb/wD/AP8A//8AAP///wAA/wD7lFH7+vlQ+vleU/n4w1L49yhd9/aNXPb18l/19Fde9PO8WfPyIVjy8YZb8fDrWvDvUEXv7rVE7u0aR+3sf0bs6+RB6+pJQOrprkPp6BNC6Od4Tefm3Uzm5UJP5eSnTuTjDEnj4nFI4uHWS+HgO0rg36B1394FdN7danfd3M923Ns0cdvamXDa2f5z2dhjctjXyH3X1i181tWSf9XU937U01x509LBeNLRJnvR0It60M/wZc/OVWTOzbpnzcwfZszLhGHLyulgyslOY8nIs2LIxxhtx8Z9bMbF4m/FxEduxMOsacPCEWjCwXZrwcDbasC/QBW/vqUUvr0KF728bxa8u9QRu7o5ELq5nhO5uAMSuLdoHbe2zRy2tTIftbSXHrSz/BmzsmEYsrHGG7GwKxqwr5AFr671BK6tWgetrL8GrKskAauqiQCqqe4DqahTAqinuA2nph0MpqWCD6Wk5w6ko0wJo6KxCKKhFguhoHsKoJ/gNZ+eRTSenao3nZwPNpybdDGbmtkwmpk+M5mYozKYlwg9l5ZtPJaV0j+VlDc+lJOcOZOSATiSkWY7kZDLOpCPMCWPjpUkjo36J42MXyaMi8Qhi4opIIqJjiOJiPMiiIdYLYeGvSyGhSIvhYSHLoSD7CmDglEogoG2K4GAGyqAf4DVf37l1H59Std9fK/WfHsU0Xt6edB6ed7TeXhD0nh3qN13dg3cdnVy33V01950czzZc3Kh2HJxBttxcGvacG/QxW9uNcRubZrHbWz/xmxrZMFrasnAamkuw2lok8JoZ/jNZ2ZdzGZlws9lZCfOZGOMyWNi8chiYVbLYWC7ymBfIPVfXoX0Xl3q911cT/ZcW7TxW1oZ8FpZfvNZWOPyWFdI/VdWrfxWVRL/VVR3/lRT3PlTUkH4UlGm+1FQC/pQT3DlT07V5E5NOudNTJ/mTEsE4UtKaeBKSc7jSUgz4khHmO1HRv3sRkVi70VEx+5EQyzpQ0KR6EJB9utBQFvqQD/AlT8+JZQ+PYqXPTzvljw7VJE7OrmQOjkekzk4g5I4N+idNzZNnDY1sp81NBeeNDN8mTMy4ZgyMUabMTCrmjAvEIUvLnWELi3ahy0sP4YsK6SBKyoJgCopboMpKNOCKCc4jScmnYwmJQKPJSRnjiQjzIkjIjGIIiGWiyEg+4ogH2C1Hx7FtB4dKrcdHI+2HBv0sRsaWbAaGb6zGRgjshgXiL0XFu28FhVSvxUUt74UExy5ExKBuBIR5rsREEu6EA+wpQ8OFaQODXqnDQzfpgwLRKELCqmgCgkOowkIc6IIB9itBwY9rAYFoq8FBAeuBANsqQMC0agCATarAQCbqgA="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
256,
2,
1
]
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 1024,
"row_pitch": 1024,
"rows": 2,
"image_pitch": 2048,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write/texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write/attachment",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write/draw",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write/pass",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write/texels",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write/stored",
"observed": {
"value": {
"bytes": "AP8AACX+AQFK/QICb/wDA5T7BAS5+gUF3vkGBgP4Bwco9wgITfYJCXL1CgqX9AsLvPMMDOHyDQ0G8Q4OK/APD1DvEBB17hERmu0SEr/sExPk6xQUCeoVFS7pFhZT6BcXeOcYGJ3mGRnC5Roa5+QbGwzjHBwx4h0dVuEeHnvgHx+g3yAgxd4hIerdIiIP3CMjNNskJFnaJSV+2SYmo9gnJ8jXKCjt1ikpEtUqKjfUKytc0ywsgdItLabRLi7L0C8v8M8wMBXOMTE6zTIyX8wzM4TLNDSpyjU1zsk2NvPINzcYxzg4PcY5OWLFOjqHxDs7rMM8PNHCPT32wT4+G8A/P0C/QEBlvkFBir1CQq+8Q0PUu0RE+bpFRR65RkZDuEdHaLdISI22SUmytUpK17RLS/yzTEwhsk1NRrFOTmuwT0+Qr1BQta5RUdqtUlL/rFNTJKtUVEmqVVVuqVZWk6hXV7inWFjdpllZAqVaWiekW1tMo1xccaJdXZahXl67oF9f4J9gYAWeYWEqnWJiT5xjY3SbZGSZmmVlvplmZuOYZ2cIl2hoLZZpaVKVamp3lGtrnJNsbMGSbW3mkW5uC5BvbzCPcHBVjnFxeo1ycp+Mc3PEi3R06Yp1dQ6JdnYziHd3WId4eH2GeXmihXp6x4R7e+yDfHwRgn19NoF+fluAf3+Af4CApX6Bgcp9goLvfIODFHuEhDl6hYVeeYaGg3iHh6h3iIjNdomJ8nWKihd0i4s8c4yMYXKNjYZxjo6rcI+P0G+QkPVukZEabZKSP2yTk2RrlJSJapWVrmmWltNol5f4Z5iYHWaZmUJlmppnZJubjGOcnLFinZ3WYZ6e+2CfnyBfoKBFXqGhal2ioo9co6O0W6Sk2Vqlpf5ZpqYjWKenSFeoqG1WqamSVaqqt1Srq9xTrKwBUq2tJlGurktQr69wT7CwlU6xsbpNsrLfTLOzBEu0tClKtbVOSba2c0i3t5hHuLi9Rrm54kW6ugdEu7ssQ7y8UUK9vXZBvr6bQL+/wD/AwOU+wcEKPcLCLzzDw1Q7xMR5OsXFnjnGxsM4x8foN8jIDTbJyTI1yspXNMvLfDPMzKEyzc3GMc7O6zDPzxAv0NA1LtHRWi3S0n8s09OkK9TUySrV1e4p1tYTKNfXOCfY2F0m2dmCJdrapyTb28wj3NzxIt3dFiHe3jsg399gH+DghR7h4aod4uLPHOPj9Bvk5Bka5eU+GebmYxjn54gX6OitFunp0hXq6vcU6+scE+zsQRLt7WYR7u6LEO/vsA/w8NUO8fH6DfLyHwzz80QL9PRpCvX1jgn29rMI9/fYB/j4/Qb5+SIF+vpHBPv7bAP8/JEC/f22Af7+2wD//wD/AP///wAA//8A//8AAABRlPv7UPn6+lNe+flSw/j4XSj391yN9vZf8vX1Xlf09Fm88/NYIfLyW4bx8Vrr8PBFUO/vRLXu7kca7e1Gf+zsQeTr60BJ6upDrunpQhPo6E145+dM3ebmT0Ll5U6n5ORJDOPjSHHi4kvW4eFKO+DgdaDf33QF3t53at3dds/c3HE029twmdrac/7Z2XJj2Nh9yNfXfC3W1n+S1dV+99TUeVzT03jB0tJ7JtHReovQ0GXwz89kVc7OZ7rNzWYfzMxhhMvLYOnKymNOyclis8jIbRjHx2x9xsZv4sXFbkfExGmsw8NoEcLCa3bBwWrbwMAVQL+/FKW+vhcKvb0Wb7y8EdS7uxA5uroTnrm5EgO4uB1ot7cczba2HzK1tR6XtLQZ/LOzGGGyshvGsbEaK7CwBZCvrwT1rq4HWq2tBr+srAEkq6sAiaqqA+6pqQJTqKgNuKenDB2mpg+CpaUO56SkCUyjowixoqILFqGhCnugoDXgn580RZ6eN6qdnTYPnJwxdJubMNmamjM+mZkyo5iYPQiXlzxtlpY/0pWVPjeUlDmck5M4AZKSO2aRkTrLkJAlMI+PJJWOjif6jY0mX4yMIcSLiyApioojjomJIvOIiC1Yh4csvYaGLyKFhS6HhIQp7IODKFGCgiu2gYEqG4CA1YB/f9Tlfn7XSn191q98fNEUe3vQeXp60955edJDeHjdqHd33A12dt9ydXXe13R02Txzc9ihcnLbBnFx2mtwcMXQb2/ENW5ux5ptbcb/bGzBZGtrwMlqasMuaWnCk2hozfhnZ8xdZmbPwmVlzidkZMmMY2PI8WJiy1ZhYcq7YGD1IF9f9IVeXvfqXV32T1xc8bRbW/AZWlrzfllZ8uNYWP1IV1f8rVZW/xJVVf53VFT53FNT+EFSUvumUVH6C1BQ5XBPT+TVTk7nOk1N5p9MTOEES0vgaUpK485JSeIzSEjtmEdH7P1GRu9iRUXux0RE6SxDQ+iRQkLr9kFB6ltAQJXAPz+UJT4+l4o9PZbvPDyRVDs7kLk6OpMeOTmSgzg4neg3N5xNNjafsjU1nhc0NJl8MzOY4TIym0YxMZqrMDCFEC8vhHUuLofaLS2GPywsgaQrK4AJKiqDbikpgtMoKI04JyeMnSYmjwIlJY5nJCSJzCMjiDEiIouWISGK+yAgtWAfH7TFHh63Kh0dto8cHLH0GxuwWRoas74ZGbIjGBi9iBcXvO0WFr9SFRW+txQUuRwTE7iBEhK75hERuksQEKWwDw+kFQ4Op3oNDabfDAyhRAsLoKkKCqMOCQmicwgIrdgHB6w9BgavogUFrgcEBKlsAwOo0QICqzYBAaqbAAA="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
256,
2,
1
]
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 1024,
"row_pitch": 1024,
"rows": 2,
"image_pitch": 2048,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "fpv_srgb_fragment_write_half/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "fpv_srgb_fragment_write_half/buffer/0",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write_half/texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write_half/attachment",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write_half/draw",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write_half/pass",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write_half/texels",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatRGBA8Unorm_sRGB/fpv_srgb_fragment_write_half/stored",
"observed": {
"value": {
"bytes": "AP8AAAH+JQEC/UoCA/xvAwT7lAQF+rkFBvneBgf4AwcI9ygICfZNCQr1cgoL9JcLDPO8DA3y4Q0O8QYOD/ArDxDvUBAR7nUREu2aEhPsvxMU6+QUFeoJFRbpLhYX6FMXGOd4GBnmnRka5cIaG+TnGxzjDBwd4jEdHuFWHh/gex8g36AgId7FISLd6iIj3A8jJNs0JCXaWSUm2X4mJ9ijJyjXyCgp1u0pKtUSKivUNyss01wsLdKBLS7Rpi4v0MsvMM/wMDHOFTEyzToyM8xfMzTLhDQ1yqk1NsnONjfI8zc4xxg4OcY9OTrFYjo7xIc7PMOsPD3C0T0+wfY+P8AbP0C/QEBBvmVBQr2KQkO8r0NEu9RERbr5RUa5HkZHuENHSLdoSEm2jUlKtbJKS7TXS0yz/ExNsiFNTrFGTk+wa09Qr5BQUa61UVKt2lJTrP9TVKskVFWqSVVWqW5WV6iTV1inuFhZpt1ZWqUCWlukJ1tco0xcXaJxXV6hll5foLtfYJ/gYGGeBWFinSpiY5xPY2SbdGRlmpllZpm+ZmeY42dolwhoaZYtaWqVUmprlHdrbJOcbG2SwW1ukeZub5ALb3CPMHBxjlVxco16cnOMn3N0i8R0dYrpdXaJDnZ3iDN3eIdYeHmGfXl6haJ6e4THe3yD7Hx9ghF9foE2fn+AW3+Af4CAgX6lgYJ9yoKDfO+DhHsUhIV6OYWGeV6Gh3iDh4h3qIiJds2JinXyiot0F4uMczyMjXJhjY5xho6PcKuPkG/QkJFu9ZGSbRqSk2w/k5RrZJSVaomVlmmulpdo05eYZ/iYmWYdmZplQpqbZGebnGOMnJ1isZ2eYdaen2D7n6BfIKChXkWhol1qoqNcj6OkW7SkpVrZpaZZ/qanWCOnqFdIqKlWbamqVZKqq1S3q6xT3KytUgGtrlEmrq9QS6+wT3CwsU6VsbJNurKzTN+ztEsEtLVKKbW2SU62t0hzt7hHmLi5Rr25ukXiurtEB7u8Qyy8vUJRvb5Bdr6/QJu/wD/AwME+5cHCPQrCwzwvw8Q7VMTFOnnFxjmexsc4w8fIN+jIyTYNyco1MsrLNFfLzDN8zM0yoc3OMcbOzzDrz9AvENDRLjXR0i1a0tMsf9PUK6TU1SrJ1dYp7tbXKBPX2Cc42NkmXdnaJYLa2ySn29wjzNzdIvHd3iEW3t8gO9/gH2Dg4R6F4eIdquLjHM/j5Bv05OUaGeXmGT7m5xhj5+gXiOjpFq3p6hXS6usU9+vsExzs7RJB7e4RZu7vEIvv8A+w8PEO1fHyDfry8wwf8/QLRPT1Cmn19gmO9vcIs/f4B9j4+Qb9+foFIvr7BEf7/ANs/P0Ckf3+Abb+/wDb/wD/AP8A//8AAP///wAA/wD7lFH7+vlQ+vleU/n4w1L49yhd9/aNXPb18l/19Fde9PO8WfPyIVjy8YZb8fDrWvDvUEXv7rVE7u0aR+3sf0bs6+RB6+pJQOrprkPp6BNC6Od4Tefm3Uzm5UJP5eSnTuTjDEnj4nFI4uHWS+HgO0rg36B1394FdN7danfd3M923Ns0cdvamXDa2f5z2dhjctjXyH3X1i181tWSf9XU937U01x509LBeNLRJnvR0It60M/wZc/OVWTOzbpnzcwfZszLhGHLyulgyslOY8nIs2LIxxhtx8Z9bMbF4m/FxEduxMOsacPCEWjCwXZrwcDbasC/QBW/vqUUvr0KF728bxa8u9QRu7o5ELq5nhO5uAMSuLdoHbe2zRy2tTIftbSXHrSz/BmzsmEYsrHGG7GwKxqwr5AFr671BK6tWgetrL8GrKskAauqiQCqqe4DqahTAqinuA2nph0MpqWCD6Wk5w6ko0wJo6KxCKKhFguhoHsKoJ/gNZ+eRTSenao3nZwPNpybdDGbmtkwmpk+M5mYozKYlwg9l5ZtPJaV0j+VlDc+lJOcOZOSATiSkWY7kZDLOpCPMCWPjpUkjo36J42MXyaMi8Qhi4opIIqJjiOJiPMiiIdYLYeGvSyGhSIvhYSHLoSD7CmDglEogoG2K4GAGyqAf4DVf37l1H59Std9fK/WfHsU0Xt6edB6ed7TeXhD0nh3qN13dg3cdnVy33V01950czzZc3Kh2HJxBttxcGvacG/QxW9uNcRubZrHbWz/xmxrZMFrasnAamkuw2lok8JoZ/jNZ2ZdzGZlws9lZCfOZGOMyWNi8chiYVbLYWC7ymBfIPVfXoX0Xl3q911cT/ZcW7TxW1oZ8FpZfvNZWOPyWFdI/VdWrfxWVRL/VVR3/lRT3PlTUkH4UlGm+1FQC/pQT3DlT07V5E5NOudNTJ/mTEsE4UtKaeBKSc7jSUgz4khHmO1HRv3sRkVi70VEx+5EQyzpQ0KR6EJB9utBQFvqQD/AlT8+JZQ+PYqXPTzvljw7VJE7OrmQOjkekzk4g5I4N+idNzZNnDY1sp81NBeeNDN8mTMy4ZgyMUabMTCrmjAvEIUvLnWELi3ahy0sP4YsK6SBKyoJgCopboMpKNOCKCc4jScmnYwmJQKPJSRnjiQjzIkjIjGIIiGWiyEg+4ogH2C1Hx7FtB4dKrcdHI+2HBv0sRsaWbAaGb6zGRgjshgXiL0XFu28FhVSvxUUt74UExy5ExKBuBIR5rsREEu6EA+wpQ8OFaQODXqnDQzfpgwLRKELCqmgCgkOowkIc6IIB9itBwY9rAYFoq8FBAeuBANsqQMC0agCATarAQCbqgA="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
256,
2,
1
]
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 1024,
"row_pitch": 1024,
"rows": 2,
"image_pitch": 2048,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write_half/texture",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write_half/attachment",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write_half/draw",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write_half/pass",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write_half/texels",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "MTLPixelFormatBGRA8Unorm_sRGB/fpv_srgb_fragment_write_half/stored",
"observed": {
"value": {
"bytes": "AP8AACX+AQFK/QICb/wDA5T7BAS5+gUF3vkGBgP4Bwco9wgITfYJCXL1CgqX9AsLvPMMDOHyDQ0G8Q4OK/APD1DvEBB17hERmu0SEr/sExPk6xQUCeoVFS7pFhZT6BcXeOcYGJ3mGRnC5Roa5+QbGwzjHBwx4h0dVuEeHnvgHx+g3yAgxd4hIerdIiIP3CMjNNskJFnaJSV+2SYmo9gnJ8jXKCjt1ikpEtUqKjfUKytc0ywsgdItLabRLi7L0C8v8M8wMBXOMTE6zTIyX8wzM4TLNDSpyjU1zsk2NvPINzcYxzg4PcY5OWLFOjqHxDs7rMM8PNHCPT32wT4+G8A/P0C/QEBlvkFBir1CQq+8Q0PUu0RE+bpFRR65RkZDuEdHaLdISI22SUmytUpK17RLS/yzTEwhsk1NRrFOTmuwT0+Qr1BQta5RUdqtUlL/rFNTJKtUVEmqVVVuqVZWk6hXV7inWFjdpllZAqVaWiekW1tMo1xccaJdXZahXl67oF9f4J9gYAWeYWEqnWJiT5xjY3SbZGSZmmVlvplmZuOYZ2cIl2hoLZZpaVKVamp3lGtrnJNsbMGSbW3mkW5uC5BvbzCPcHBVjnFxeo1ycp+Mc3PEi3R06Yp1dQ6JdnYziHd3WId4eH2GeXmihXp6x4R7e+yDfHwRgn19NoF+fluAf3+Af4CApX6Bgcp9goLvfIODFHuEhDl6hYVeeYaGg3iHh6h3iIjNdomJ8nWKihd0i4s8c4yMYXKNjYZxjo6rcI+P0G+QkPVukZEabZKSP2yTk2RrlJSJapWVrmmWltNol5f4Z5iYHWaZmUJlmppnZJubjGOcnLFinZ3WYZ6e+2CfnyBfoKBFXqGhal2ioo9co6O0W6Sk2Vqlpf5ZpqYjWKenSFeoqG1WqamSVaqqt1Srq9xTrKwBUq2tJlGurktQr69wT7CwlU6xsbpNsrLfTLOzBEu0tClKtbVOSba2c0i3t5hHuLi9Rrm54kW6ugdEu7ssQ7y8UUK9vXZBvr6bQL+/wD/AwOU+wcEKPcLCLzzDw1Q7xMR5OsXFnjnGxsM4x8foN8jIDTbJyTI1yspXNMvLfDPMzKEyzc3GMc7O6zDPzxAv0NA1LtHRWi3S0n8s09OkK9TUySrV1e4p1tYTKNfXOCfY2F0m2dmCJdrapyTb28wj3NzxIt3dFiHe3jsg399gH+DghR7h4aod4uLPHOPj9Bvk5Bka5eU+GebmYxjn54gX6OitFunp0hXq6vcU6+scE+zsQRLt7WYR7u6LEO/vsA/w8NUO8fH6DfLyHwzz80QL9PRpCvX1jgn29rMI9/fYB/j4/Qb5+SIF+vpHBPv7bAP8/JEC/f22Af7+2wD//wD/AP///wAA//8A//8AAABRlPv7UPn6+lNe+flSw/j4XSj391yN9vZf8vX1Xlf09Fm88/NYIfLyW4bx8Vrr8PBFUO/vRLXu7kca7e1Gf+zsQeTr60BJ6upDrunpQhPo6E145+dM3ebmT0Ll5U6n5ORJDOPjSHHi4kvW4eFKO+DgdaDf33QF3t53at3dds/c3HE029twmdrac/7Z2XJj2Nh9yNfXfC3W1n+S1dV+99TUeVzT03jB0tJ7JtHReovQ0GXwz89kVc7OZ7rNzWYfzMxhhMvLYOnKymNOyclis8jIbRjHx2x9xsZv4sXFbkfExGmsw8NoEcLCa3bBwWrbwMAVQL+/FKW+vhcKvb0Wb7y8EdS7uxA5uroTnrm5EgO4uB1ot7cczba2HzK1tR6XtLQZ/LOzGGGyshvGsbEaK7CwBZCvrwT1rq4HWq2tBr+srAEkq6sAiaqqA+6pqQJTqKgNuKenDB2mpg+CpaUO56SkCUyjowixoqILFqGhCnugoDXgn580RZ6eN6qdnTYPnJwxdJubMNmamjM+mZkyo5iYPQiXlzxtlpY/0pWVPjeUlDmck5M4AZKSO2aRkTrLkJAlMI+PJJWOjif6jY0mX4yMIcSLiyApioojjomJIvOIiC1Yh4csvYaGLyKFhS6HhIQp7IODKFGCgiu2gYEqG4CA1YB/f9Tlfn7XSn191q98fNEUe3vQeXp60955edJDeHjdqHd33A12dt9ydXXe13R02Txzc9ihcnLbBnFx2mtwcMXQb2/ENW5ux5ptbcb/bGzBZGtrwMlqasMuaWnCk2hozfhnZ8xdZmbPwmVlzidkZMmMY2PI8WJiy1ZhYcq7YGD1IF9f9IVeXvfqXV32T1xc8bRbW/AZWlrzfllZ8uNYWP1IV1f8rVZW/xJVVf53VFT53FNT+EFSUvumUVH6C1BQ5XBPT+TVTk7nOk1N5p9MTOEES0vgaUpK485JSeIzSEjtmEdH7P1GRu9iRUXux0RE6SxDQ+iRQkLr9kFB6ltAQJXAPz+UJT4+l4o9PZbvPDyRVDs7kLk6OpMeOTmSgzg4neg3N5xNNjafsjU1nhc0NJl8MzOY4TIym0YxMZqrMDCFEC8vhHUuLofaLS2GPywsgaQrK4AJKiqDbikpgtMoKI04JyeMnSYmjwIlJY5nJCSJzCMjiDEiIouWISGK+yAgtWAfH7TFHh63Kh0dto8cHLH0GxuwWRoas74ZGbIjGBi9iBcXvO0WFr9SFRW+txQUuRwTE7iBEhK75hERuksQEKWwDw+kFQ4Op3oNDabfDAyhRAsLoKkKCqMOCQmicwgIrdgHB6w9BgavogUFrgcEBKlsAwOo0QICqzYBAaqbAAA="
},
"shape": {
"bytes": {
"region": {
"texture": {
"level": 0,
"slice": 0,
"aspect": "color",
"sample": 0,
"origin": [
0,
0,
0
],
"size": [
256,
2,
1
]
}
},
"element": "u8",
"row_offset": 0,
"row_elements": 1024,
"row_pitch": 1024,
"rows": 2,
"image_pitch": 2048,
"images": 1,
"gaps": "ignored"
}
}
}
},
{
"name": "notices",
"observed": {
"value": "absent"
},
"children": [
{
"name": "set",
"observed": {
"value": {
"nothing": "announced_nothing"
}
}
},
{
"name": "counts",
"observed": {
"value": {
"fields": {}
}
}
}
]
}
]
}
}
}
],
"validated": "ran"
}
],
"times": [
{
"venue": "native Metal",
"chip": "apple-m3-max",
"os_build": "26A434",
"rounds": 8,
"measured": "8 round(s) of the whole selection, in the case set's own order; a figure is the median of the rounds' own medians; Metal's leg ran at a one-minute load average of 10.89",
"instrument": 403,
"times": {
"case": "srgb-storage-fragment-writes",
"calls": 22,
"in_calls": 35642498,
"on_cpu": 1511293,
"blocked": 33999251,
"elsewhere": 5715708,
"spend": 41352665,
"spend_least": 40894126,
"spend_most": 42391958,
"per_call": [
{
"call": "buffer",
"least_calls": 3,
"most_calls": 3,
"wall": 8542,
"on_cpu": 8708,
"blocked": 0,
"wall_least": 6417,
"wall_most": 20000,
"wall_total": 42750,
"on_cpu_total": 43251,
"blocked_total": 0
},
{
"call": "library",
"least_calls": 1,
"most_calls": 1,
"wall": 27575542,
"on_cpu": 701708,
"blocked": 26745333,
"wall_least": 26782125,
"wall_most": 27968500,
"wall_total": 27575542,
"on_cpu_total": 701708,
"blocked_total": 26745333
},
{
"call": "read_texture",
"least_calls": 4,
"most_calls": 4,
"wall": 1333,
"on_cpu": 1458,
"blocked": 0,
"wall_least": 1083,
"wall_most": 1584,
"wall_total": 7459,
"on_cpu_total": 8084,
"blocked_total": 0
},
{
"call": "render",
"least_calls": 4,
"most_calls": 4,
"wall": 383792,
"on_cpu": 27542,
"blocked": 344167,
"wall_least": 345500,
"wall_most": 677500,
"wall_total": 7677876,
"on_cpu_total": 332917,
"blocked_total": 7175833
},
{
"call": "render_pipeline",
"least_calls": 2,
"most_calls": 2,
"wall": 123583,
"on_cpu": 123875,
"blocked": 0,
"wall_least": 112750,
"wall_most": 172458,
"wall_total": 294958,
"on_cpu_total": 295458,
"blocked_total": 0
},
{
"call": "target",
"least_calls": 4,
"most_calls": 4,
"wall": 5708,
"on_cpu": 5834,
"blocked": 0,
"wall_least": 4917,
"wall_most": 7250,
"wall_total": 25749,
"on_cpu_total": 26292,
"blocked_total": 0
},
{
"call": "texture",
"least_calls": 4,
"most_calls": 4,
"wall": 14042,
"on_cpu": 14208,
"blocked": 0,
"wall_least": 6625,
"wall_most": 16250,
"wall_total": 73918,
"on_cpu_total": 74750,
"blocked_total": 0
}
]
}
}
]
}
@@ -390,6 +390,36 @@
"hex": "32f0cae59a0afb15a1b89edfa2a946c79a2e8b91d811e665f84560da4d62ef0d"
}
}
},
{
"name": "row:xi_rate2_o1_r3_g8",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "59645711db9e3d94ae3333cfb98a0ee8e5829833c3548b476a2b2a1dfccc1887"
}
}
},
{
"name": "row:xi_rate3_o2_r4_g12",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "439d3c3b1a1155cd8a6c1c643adc0646c9f6e00ea60cfc0aa836dcf3f50d943d"
}
}
},
{
"name": "row:yi_rate2_o1_r2_g2x8",
"observed": {
"value": "absent",
"digest": {
"kind": "sha256",
"hex": "978597d33189d31952da85e0fa8d77e209511a2ad4140734f62661dc425a389e"
}
}
}
]
},
@@ -3377,6 +3407,321 @@
}
]
},
{
"name": "xi_rate2_o1_r3_g8/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate2_o1_r3_g8/buffer/0",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate2_o1_r3_g8/buffer/region",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate2_o1_r3_g8/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate2_o1_r3_g8/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "xi_rate2_o1_r3_g8/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate2_o1_r3_g8",
"observed": {
"value": "absent"
},
"children": [
{
"name": "output",
"observed": {
"value": {
"bytes": "JQEAACUBAAAnAQAAJwEAACkBAAApAQAAKQEAACkBAADu7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7g=="
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 1024
}
},
"element": "u32",
"row_offset": 0,
"row_elements": 8,
"row_pitch": 32,
"rows": 1,
"image_pitch": 1024,
"images": 1,
"gaps": "compared"
}
}
}
}
]
},
{
"name": "xi_rate3_o2_r4_g12/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate3_o2_r4_g12/buffer/0",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate3_o2_r4_g12/buffer/region",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate3_o2_r4_g12/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate3_o2_r4_g12/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "xi_rate3_o2_r4_g12/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "xi_rate3_o2_r4_g12",
"observed": {
"value": "absent"
},
"children": [
{
"name": "output",
"observed": {
"value": {
"bytes": "JgEAACYBAAAmAQAAKAEAACgBAAAoAQAAKgEAACoBAAAqAQAALAEAACwBAAAsAQAA7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7g=="
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 1024
}
},
"element": "u32",
"row_offset": 0,
"row_elements": 12,
"row_pitch": 48,
"rows": 1,
"image_pitch": 1024,
"images": 1,
"gaps": "compared"
}
}
}
}
]
},
{
"name": "yi_rate2_o1_r2_g2x8/pipeline",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "yi_rate2_o1_r2_g2x8/buffer/0",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "yi_rate2_o1_r2_g2x8/buffer/region",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "yi_rate2_o1_r2_g2x8/dispatch",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "yi_rate2_o1_r2_g2x8/status",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": {
"variant": {
"name": "Completed",
"payload": "absent"
}
}
}
}
}
},
{
"name": "yi_rate2_o1_r2_g2x8/read-back",
"observed": {
"value": {
"variant": {
"name": "Ok",
"payload": "absent"
}
}
}
},
{
"name": "yi_rate2_o1_r2_g2x8",
"observed": {
"value": "absent"
},
"children": [
{
"name": "output",
"observed": {
"value": {
"bytes": "JQEAACUBAAAlAQAAJQEAACcBAAAnAQAAJwEAACcBAAAnAQAAJwEAACcBAAAnAQAAJwEAACcBAAAnAQAAJwEAAO7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7g=="
},
"shape": {
"bytes": {
"region": {
"buffer": {
"offset": 0,
"length": 1024
}
},
"element": "u32",
"row_offset": 0,
"row_elements": 2,
"row_pitch": 8,
"rows": 8,
"image_pitch": 1024,
"images": 1,
"gaps": "compared"
}
}
}
}
]
},
{
"name": "notices",
"observed": {
@@ -3406,7 +3751,12 @@
}
}
],
"validated": "not_run"
"validated": {
"stopped": {
"call": "dispatch_threads",
"message": "unused binding in compute encoder at Buffer index 2.\nunused binding in compute encoder at Buffer index 3."
}
}
}
],
"times": [
+43 -9
View File
@@ -20,8 +20,8 @@ use crate::transcript::{Node, NodeName, Observed, Sites, Transcript, Value};
use crate::verdict::device_gap_of;
use metal2vulkan::metal::state::DepthStencilDescriptor;
use metal2vulkan::metal::{
AttributeFormat, BindingAccess, CompareFunction, IndexType, PixelFormat, RenderStages,
SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter, SamplerMipFilter,
AttributeFormat, BindingAccess, CompareFunction, IndexType, IndirectCommandType, PixelFormat,
RenderStages, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter, SamplerMipFilter,
SamplerReductionMode, StepFunction,
};
@@ -715,10 +715,11 @@ pub struct Venue {
pub lossless_compression: bool,
/// For a CPU implementation (`DeviceKind::Cpu`), the host's widest vector instruction set
/// ([`host_vector_isa`]), which its shader compiler targets; `None` for a GPU. The device's
/// name and driver do not carry it, and its answers follow it: one llvmpipe build (Mesa 26.2.6,
/// LLVM 23.1.4) stored a code from Metal's at 6,496 texels of `fetch-ordered-rgba8unorm-srgb`'s
/// `x3` on a host with AVX-512 (a Ryzen 7 7840HS) and at 6,304 on one with AVX2 alone (an
/// i9-13900H).
/// name and driver do not carry it. Answers can also part by a finer property of the host than
/// this: llvmpipe of Mesa 26.2.4 and LLVM 23.1.1 stored a code from Metal's at 6,304 texels of
/// `fetch-ordered-rgba8unorm-srgb`'s `x3` on the x86-64 AVX-512 runner of one CI run and at
/// 6,496 on those of two others, so the ledger's row there lists both answers
/// ([`crate::known_gaps::KnownGap::answers`]).
pub host: Option<String>,
}
@@ -787,6 +788,16 @@ pub trait Side {
/// Where the side runs.
fn venue(&self) -> Venue;
/// The macOS release and build the side runs on, as `sw_vers -productVersion` and
/// `-buildVersion` answer them on this host (empty where it does not answer): what record mode
/// holds against the oracle the suite names before it takes an answer
/// ([`crate::record::record`]). Every side runs on its host's; a test's stub states the one it
/// stands for.
#[cfg(target_os = "macos")]
fn macos_release(&self) -> (String, String) {
crate::record::sw_vers()
}
/// A library of the shader's AIR, from whichever of its forms the side reads
/// ([`ShaderSource`]).
fn library(&mut self, source: &ShaderSource<'_>) -> Answer<Handle>;
@@ -2155,6 +2166,22 @@ pub trait Side {
Err(Failure::unavailable("empty_command_buffers"))
}
/// The sequence of [`crate::managed_naming`] with `way`'s reader, made of `libraries`: a
/// Managed buffer's contents synced, named and passed by a commit that does not name the
/// buffer, then written again after the reader is encoded, and the reader's command buffer
/// committed. Answers the bytes the reader wrote ([`crate::managed_naming::Way::reads`]). A
/// side whose device keeps one copy of a Managed buffer answers a reader that reaches the
/// buffer through its address alone with the venue's gap: the row asks what the device's
/// second copy holds.
fn managed_naming(
&mut self,
way: crate::managed_naming::Way,
libraries: crate::managed_naming::Libraries,
) -> Answer<Vec<u8>> {
let _ = (way, libraries);
Err(Failure::unavailable("managed_naming"))
}
/// A command queue's limit on uncompleted command buffers, by the probe both sides run
/// ([`crate::queue_slots`]): the queue is made with `max` as its
/// `maxCommandBufferCount` (`newCommandQueue` where `max` is `None`), and at most `cap` command
@@ -3159,9 +3186,9 @@ pub struct FragmentFilled {
}
/// One execution of a kernel-encoded indirect command buffer over a range a buffer holds, which
/// the GPU writes first: the one shape of indirect command buffer both sides build, indexed
/// triangle draws that inherit the pipeline state and bind their own buffers, encoded by a
/// kernel through the buffer's `gpuResourceID`.
/// the GPU writes first: the one shape of indirect command buffer both sides build, plain or
/// indexed triangle draws or plain or indexed patch draws that inherit the pipeline state and bind
/// their own buffers, encoded by a kernel through the buffer's `gpuResourceID`.
#[derive(Clone, Copy, Debug)]
pub struct EncodedRange<'a> {
/// The library of the kernel and of the drawing functions.
@@ -3174,6 +3201,8 @@ pub struct EncodedRange<'a> {
pub buffers: &'a [Handle],
/// The commands the indirect command buffer holds, which the kernel's threads encode.
pub commands: u32,
/// The buffer's `commandTypes`: one kind alone, the kind the kernel encodes.
pub command_types: IndirectCommandType,
/// `maxVertexBufferBindCount` and `maxFragmentBufferBindCount`.
pub bind_counts: [u32; 2],
/// The pipeline the commands inherit: these vertex and fragment functions over one color
@@ -3181,6 +3210,11 @@ pub struct EncodedRange<'a> {
pub vertex: &'a str,
pub fragment: &'a str,
pub format: PixelFormat,
/// That pipeline's `vertexDescriptor` and tessellation state, where the case states them (a
/// post-tessellation vertex function that reads control points under a control-point index
/// type); `None` leaves Metal's defaults.
pub vertex_layout: Option<crate::render::VertexLayout<'a>>,
pub tessellation: Option<crate::render::TessellationState>,
/// The target's extent in texels, cleared to zero, and the row pitch of its read-back.
pub size: [u32; 2],
pub row_pitch: u32,
@@ -47,6 +47,7 @@ pub mod blend_interactions;
pub mod blend_sweeps;
pub mod blit_encoder_commands;
pub mod blit_indirect_commands;
pub mod block_writes_only;
pub mod border_swizzles;
pub mod buffer_bind_off_alignment;
pub mod buffer_blits;
@@ -71,6 +72,7 @@ pub mod compute_render_chains;
pub mod compute_threadgroups;
pub mod copy_out_strides;
pub mod denormal_word_fetches;
pub mod depth_colour_reads;
pub mod depth_resolve_pairs;
pub mod depth_stencil_copies;
pub mod depth_stencil_space;
@@ -110,6 +112,7 @@ pub mod heap_metal_sizes;
pub mod host_detach;
pub mod host_page_writes;
pub mod imageblock_sizes;
pub mod imageblock_slice_past_grid;
pub mod indirect_command_depth;
pub mod indirect_commands;
pub mod indirect_private_types;
@@ -118,6 +121,7 @@ pub mod int_attributes;
pub mod layered_targets;
pub mod level_sizes;
pub mod library_facts;
pub mod managed_naming;
pub mod math_routines;
pub mod mesh_barriers;
pub mod mesh_commands;
@@ -182,8 +186,10 @@ pub mod simdgroup_lockstep;
pub mod snorm_tile_store;
pub mod sparse_heaps;
pub mod sparse_mappings;
pub mod sparse_status;
pub mod sparse_tiles;
pub mod srgb_fetch;
pub mod srgb_storage_fragment_writes;
pub mod srgb_storage_writes;
pub mod stage_in_regions;
pub mod stage_in_unread;
@@ -384,6 +390,9 @@ pub fn all() -> Vec<Box<dyn Case>> {
for case in depth_texel_reads::all() {
cases.push(Box::new(case));
}
for case in depth_colour_reads::all() {
cases.push(Box::new(case));
}
for case in extended_range_two_planes::all() {
cases.push(Box::new(case));
}
@@ -590,6 +599,7 @@ pub fn all() -> Vec<Box<dyn Case>> {
cases.extend(sparse_mappings::all());
cases.extend(command_buffer_facts::all());
cases.extend(empty_command_buffers::all());
cases.extend(managed_naming::all());
cases.extend(fresh_contents::all());
cases.extend(sample_positions::all());
cases.extend(
@@ -615,6 +625,11 @@ pub fn all() -> Vec<Box<dyn Case>> {
cases.push(Box::new(case));
}
cases.push(Box::new(srgb_storage_writes::SrgbStorageWrites));
cases.push(Box::new(block_writes_only::BlockWritesOnlyWrites));
cases.push(Box::new(sparse_status::SparseStatusPlain));
cases.push(Box::new(
srgb_storage_fragment_writes::SrgbStorageFragmentWrites,
));
cases.extend(norm_storage_writes::NormStorageWrites::all());
cases.extend(texel_swizzles::all());
for case in swizzled_storage::all() {
@@ -656,6 +671,9 @@ pub fn all() -> Vec<Box<dyn Case>> {
cases.push(Box::new(buffer_bind_off_alignment::BufferBindOffAlignment));
cases.push(Box::new(threadgroup_start::ThreadgroupStart));
cases.push(Box::new(imageblock_sizes::ImageblockSizes));
cases.push(Box::new(
imageblock_slice_past_grid::ImageblockSlicePastGrid,
));
cases.push(Box::new(nan_integer_conversions::NanIntegerConversions));
cases.push(Box::new(function_constants_half3::FunctionConstantsHalf3));
cases.push(Box::new(bicubic_texel_classes::BicubicTexelClasses));
@@ -0,0 +1,205 @@
//! `block-writes-only-writes`: what a kernel's `access::write` stores into a texture whose usage
//! holds the private bit `BlockWritesOnly` (`0x10000`) and no `ShaderWrite`.
//!
//! The public `MTLTexture.h` of macOS 27.0.1 does not define the bit. On an Apple M3 Max under
//! macOS 27.0.1 (job m3-max-83917), a kernel's write to an `RGBA8Unorm` texture of `ShaderRead |
//! RenderTarget | BlockWritesOnly` (`0x10005`) lands, in Shared and Private storage, plain and
//! under Metal's validation layer, which passes it, where it stops the same write to a texture of
//! `ShaderRead | RenderTarget` (`0x5`): `writes texture (t[1]) whose usage (0x05) doesn't specify
//! MTLTextureUsageShaderWrite (0x02)`. This case records the write's texels for that usage and for
//! the bit alone (`0x10000`).
//!
//! The kernel is the owned fixture `fpv_srgb_storage`'s `fpv_srgb_write`, which writes buffer 0's
//! `float4` at the thread's texel of a row [`WIDTH`] texels wide (buffer 1). Each value is a code
//! over 255, so the stored byte is that code exactly, away from where a device's conversion rounds.
//!
//! One compute pass a usage, one thread a texel, no loop and no sampling: nothing here can fault a
//! GPU.
use crate::case::{call, made, Abort, Bindings, Case, Failure, Input, MetalSource, Side};
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::texture::TextureRequest;
use crate::transcript::{Aspect, ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites};
use metal2vulkan::metal::{PixelFormat, TextureUsage};
/// The fixture the kernel lives in.
const FIXTURE: &str = "fpv_srgb_storage";
/// The kernel the case runs.
const KERNEL: &str = "fpv_srgb_write";
/// The texture's width, which buffer 1 holds.
pub const WIDTH: u32 = 16;
/// The texture's height.
pub const HEIGHT: u32 = 1;
/// The usages the case writes a texture of: the guest's `ShaderRead | RenderTarget |
/// BlockWritesOnly`, and the bit alone.
pub fn usages() -> [TextureUsage; 2] {
let block = TextureUsage::BLOCK_WRITES_ONLY;
[
TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET | block,
block,
]
}
/// Texel `i`'s four codes.
pub fn codes(i: u32) -> [u32; 4] {
[i * 16, 255 - i * 16, (i * 37) & 255, 255 - i]
}
/// Buffer 0's bytes: each texel's codes over 255, as `float4`s.
fn values() -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(codes)
.flat_map(|code| (code as f32 / 255.0).to_bits().to_le_bytes())
.collect()
}
/// Buffer 1's bytes: the row's width, as the kernel's `constant uint &width`.
fn width_bytes() -> Vec<u8> {
WIDTH.to_le_bytes().to_vec()
}
/// The texture a write of `usage` reaches: shared storage, so the host reads it back.
fn request(usage: TextureUsage) -> TextureRequest<'static> {
TextureRequest::read_2d(PixelFormat::RGBA8Unorm.as_raw(), WIDTH, HEIGHT).used(usage)
}
/// The layout the stored bytes are read under: one row a texel row, one code a channel.
fn stored_layout() -> ByteLayout {
let pitch = WIDTH * 4;
ByteLayout {
region: Region::Texture {
level: 0,
slice: 0,
aspect: Aspect::Color,
sample: 0,
origin: [0, 0, 0],
size: [WIDTH, HEIGHT, 1],
},
element: Element::U8,
row_offset: 0,
row_elements: pitch,
row_pitch: pitch,
rows: HEIGHT,
image_pitch: pitch * HEIGHT,
images: 1,
// Four codes a texel cover every byte of a row, so there is no gap.
gaps: Gaps::Ignored,
}
}
/// The case.
pub struct BlockWritesOnlyWrites;
impl Case for BlockWritesOnlyWrites {
fn name(&self) -> &'static str {
"block-writes-only-writes"
}
fn metal_source(&self) -> MetalSource {
MetalSource::Run
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let fixture = Fixture {
name: FIXTURE,
entry: KERNEL,
};
let mut shaders = Vec::new();
for extension in [RUNTIME_TEXT, METAL_TEXT] {
shaders.push(ShaderRef {
fixture: format!("{FIXTURE}{extension}"),
entry: KERNEL.to_owned(),
source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()),
});
}
Ok(shaders)
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let fixture = Fixture::new(FIXTURE);
let mut inputs = vec![
Input {
name: "air".to_owned(),
digest: Digest::sha256(fixture.text(RUNTIME_TEXT)?.as_bytes()),
},
Input {
name: "air-typed".to_owned(),
digest: Digest::sha256(fixture.text(METAL_TEXT)?.as_bytes()),
},
Input::bytes("buffer:0", &values()),
Input::bytes("buffer:1", &width_bytes()),
];
for usage in usages() {
inputs.push(Input::bytes(
format!("usage-{:#x}", usage.as_raw()),
&request(usage).words(),
));
}
Ok(inputs)
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let loaded = Fixture::new(FIXTURE).loaded().map_err(|why| Abort {
at: "library".to_owned(),
failure: Failure::named("FixtureNotRead", why),
})?;
let library = made(sites, "library", side.library(&loaded.source()))?;
let pipeline = made(sites, "pipeline", side.compute_pipeline(library, KERNEL))?;
let values = made(sites, "buffer/0", side.buffer(&values()))?;
let shape = made(sites, "buffer/width", side.buffer(&width_bytes()))?;
for usage in usages() {
let at = |site: &str| format!("usage-{:#x}/{site}", usage.as_raw());
let texture = made(sites, &at("texture"), side.texture(&request(usage)))?;
let command_buffer = made(
sites,
&at("dispatch"),
side.dispatch(
pipeline,
&Bindings::new(&[texture], &[values, shape]),
[WIDTH / 16, HEIGHT, 1],
[16, 1, 1],
),
)?;
call(
sites,
&at("status"),
side.wait(command_buffer),
Clone::clone,
)?;
let stored = call(
sites,
&at("texels"),
side.read_texture(texture, [WIDTH, HEIGHT], WIDTH * 4),
|_| crate::transcript::Value::Absent,
)?;
sites.push(Node::leaf(
at("stored"),
Observed::bytes(stored, stored_layout()),
));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every code's value lands on the code itself: its product with 255 is within a hundredth of
/// it, far from the half-code where a conversion rounds.
#[test]
fn every_value_stores_its_code() {
for i in 0..WIDTH * HEIGHT {
for code in codes(i) {
assert!(code <= 255, "texel {i}: {code}");
let back = f64::from(code as f32 / 255.0) * 255.0;
assert!((back - f64::from(code)).abs() < 0.01, "{code}: {back}");
}
}
}
}
@@ -4,7 +4,10 @@
//! Metal's answer here is a **rule**, not a table — "each copy unit of the buffer lands in its
//! sample by the layout measured for colour, texel `(x, y)` sample `s` at
//! `offset + y * bytesPerRow + (x * n + s) * bpp`, the samples outside a region keep the clear, and
//! the copy back out returns the buffer bit for bit" — measured by a probe on an **Apple M4**.
//! the copy back out returns the buffer bit for bit" — measured by a probe on an **Apple M3 Max**
//! under macOS 27.0.1 and on a **Radeon Pro 5300M** and an **Intel UHD Graphics 630** under macOS
//! 26.7.1, each plainly and under Metal's API validation layer; Apple's documentation of the two
//! calls says nothing of a multisample texture.
//! Every call on the path is public: a render pass that clears and draws nothing,
//! `copyFromBuffer:toTexture:` into the depth or stencil aspect, a dispatch that reads every
//! sample, and `copyFromTexture:toBuffer:` back. So record mode **runs** these cases on the oracle,
@@ -38,7 +41,9 @@
//! Nothing here faults a GPU, hangs one or trips a watchdog: one command buffer a row, a clear that
//! draws nothing, two blits and one dispatch of a thread a sample.
use crate::allowance::Allowance;
use crate::case::{call, Abort, Case, Input, MetalSource, Side};
use crate::degradation::Degradation;
use crate::fixture::{Fixture, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::transcript::{ByteLayout, Element, Gaps, Node, Observed, Region, Sites, Value};
@@ -124,12 +129,10 @@ const fn part(name: &'static str, format: u32) -> Row {
/// The rows: the stencil aspect at both sample counts and over a region inside the texture, and
/// the 16-bit depth aspect at both sample counts.
///
/// The two `Depth16Unorm` rows are **open gaps of ours**, each with a `known-gaps-rt.tsv` row:
/// Metal copies the buffer into the 16-bit aspect and back, and we refuse the copy in
/// (`RuntimeGap::MultisampledBufferCopy`, on a device without `maintenance8` or carrying the
/// measured copy defect). A refusal of something plain Metal does is a bug of ours by the owner's
/// standing rule, so the rows stay here and stay red in the ledger's own way: the run prints them
/// as refusals, counts them as refusals, and fails the day either stops refusing.
/// The runtime copies each row as its own work (the runtime's README, the blit encoder's copies):
/// a draw into each sample, and a dispatch out of them. Its copy into a 16-bit depth carries the
/// static note `rounded-sample-depth-copy` (`Texture::SAMPLE_DEPTH_COPY_NOTE`), which the
/// `Depth16Unorm` rows declare.
///
/// # The four rows this family does not yet hold, and what measuring them found
///
@@ -140,12 +143,11 @@ const fn part(name: &'static str, format: u32) -> Row {
/// - **`Depth32Float`, four rows** (54 x 54 and 80 x 80 at 4 samples, 54 x 54 at 2, and a region
/// inside 8 x 8). Metal returns the buffer **bit for bit**, every edge value included: both
/// denormals, every NaN payload, both infinities, -1, 1, the float after 1, 2 and the largest
/// float all come back unchanged, and the samples outside a region keep the clear. Ours differs
/// at **one element of all four rows** — copy unit 1, the edge value **-0**, which Metal keeps
/// and we answer as +0. The suite has no way to allow that alone: an
/// [`Allowance`](crate::allowance::Allowance) covers a **site**, and loosening a 46,656-byte site
/// to tolerate four bytes would throw away the comparison that makes the row worth having. A
/// per-element allowance on a bytes site is what these rows are waiting for.
/// float all come back unchanged, and the samples outside a region keep the clear. The runtime
/// refuses the copy of a multisample 32-bit float depth (`Gap::TextureBytes` of
/// `TextureBytesCause::MultisampleFloatDepth`): the draw that would write it takes no value
/// outside `[0, 1]` through `FragDepth`, and Metal's answer for those values is to be read on a
/// Mac again first.
const ROWS: [Row; 5] = [
whole("buffer-depth-samples-s8-54-4", STENCIL8, 4, 54),
whole("buffer-depth-samples-s8-54-2", STENCIL8, 2, 54),
@@ -371,6 +373,16 @@ impl Case for BufferDepthSamples {
MetalSource::Run
}
fn allowances(&self) -> Vec<Allowance> {
// The runtime's copy into a multisample 16-bit depth carries its static note
// (`rounded-sample-depth-copy`), which moves no code on a device that rounds to nearest
// or toward zero: one declaration, which loosens the notices site alone.
(self.row.format == DEPTH16UNORM)
.then(|| crate::replay::notice_allowance(Degradation::RoundedSampleDepthCopy.code()))
.into_iter()
.collect()
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let fixture = Fixture::new(KERNELS);
Ok(vec![ShaderRef {
@@ -0,0 +1,569 @@
//! What a kernel reads of a `Depth32Float` texture bound to a `texture2d<float>` slot: its
//! samples, its gathers of green and alpha, and the same reads through a view swizzled
//! `(Green, Red, One, Zero)`, beside the texture's `depth2d` sample and comparison.
//!
//! The owned fixture `dvw_depth_views` holds the five kernels. Each reads slot 0 through the
//! runtime sampler at slot 0 at lane `i`'s normalized coordinate (buffer 1) and writes one
//! `float4` (buffer 0): the sample, the gather of green (`component::y`) or of alpha
//! (`component::w`), the `depth2d` sample in red, or the `depth2d` comparison against 0.5 in red.
//! The texture is 8 by 5, columns 0 to 3 holding 0.25 and columns 4 to 7 holding 0.75, and the
//! five lanes sit on row 2's centre at texel-space `x` 1.5, 3.75, 4.25, 6.5 and -3: two texel
//! centres, a quarter texel each side of the edge between the values, and one past the left edge.
//! Every coordinate is exact in `float`, and so is every weight they make. The M3 Max filters a
//! comparison at a quarter exactly; at 7/32 its sum is 0.2188725 (a recording at other lanes),
//! where a device of exact weights answers 0.21875.
//!
//! **Metal's GPU families answer the colour channels three ways.** Metal states no channels for a
//! depth texture read as a colour texture. Probed with the same kernels on a 6 by 5 texture of the
//! same halves at `x` 1.5, 2.75, 3.25, 4.5 and -3 (`d` is the texel's depth):
//!
//! | Read | Apple M3 Max | AMD Radeon Pro 5300M | Intel UHD Graphics 630 |
//! |---|---|---|---|
//! | sample | `(d, d, d, 1)` | `(d, d, d, d)` | `(d, 0, 0, 1)` |
//! | sample past the edge, opaque white border | `(1, 1, 1, 1)` | `(1, 1, 1, 1)` | `(1, 0, 0, 1)` |
//! | gather of green | `d` | `d` | `0` |
//! | gather of alpha | `1` | `d` | `1` |
//! | sample through the swizzled view | `(d, d, 1, 0)` | `(d, d, 1, 0)` | `(0, d, 1, 0)` |
//! | gather of green through the swizzled view | `d` | `d` | `d` |
//!
//! The M3 Max under macOS 27.0.1 (job m3-max-84755), the 5300M and the 630 in one MacBook Pro
//! under macOS 26.7.1 (job m3-max-84762); `Depth16Unorm` read the same way on each. The red channel
//! is the depth on every Mac, and each composes a view's swizzle over its own answer. The
//! `depth2d` sample and comparison answered alike on all three.
//!
//! **What is compared.** The recording is the M3 Max's. Every element compares exactly, except
//! where the 630's answer differs from the M3 Max's: there the element may hold the 630's value as
//! well, under docs/API.md's accepted difference `DEPTH_AS_COLOUR`. The runtime's answer is the
//! device's view of the depth aspect, Vulkan's `(D, 0, 0, 1)` (the specification's conversion to
//! RGBA and component substitution), which is the 630's. The `depth2d` reads compare exactly.
//!
//! Nothing here can fault a GPU: thirteen compute passes of five threads each, one sample a
//! thread.
use crate::allowance::{Allowance, Justification, Loosening};
use crate::case::{
call, made, Abort, Bindings, Case, Failure, Input, MetalSource, SamplerSpec, Side,
};
use crate::degradation::Degradation;
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::replay::notice_allowance;
use crate::texture::{TextureRequest, Upload};
use crate::transcript::{ByteLayout, Digest, Element, FloatWidth, Node, Observed, Sites, Value};
use metal2vulkan::metal::{
CompareFunction, PixelFormat, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter,
TextureSwizzle, TextureSwizzleChannels, TextureUsage,
};
/// The fixture the five kernels live in.
const FIXTURE: &str = "dvw_depth_views";
/// The accepted difference the colour channels' allowances name, by its slug.
const DEPTH_AS_COLOUR: &str = "a-depth-texture-read-through-a-colour-texture-slot-reads-d-0-0-1";
/// The texture's width and height.
const SIZE: [u32; 2] = [8, 5];
/// Each lane's texel-space `x` on row 2's centre.
const LANES: [f32; 5] = [1.5, 3.75, 4.25, 6.5, -3.0];
/// The byte every output word holds before the pass.
const BLANK: u8 = 0xab;
/// The depth of column `x`.
fn depth(x: u32) -> f32 {
if x >= 4 {
0.75
} else {
0.25
}
}
/// The texture a read takes: the parent, or the view swizzled `(Green, Red, One, Zero)`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Through {
Plain,
Swizzled,
}
/// A sampler state the reads take.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Sampler {
Nearest,
Linear,
NearestWhiteBorder,
LinearWhiteBorder,
NearestLess,
LinearLess,
}
impl Sampler {
const ALL: [Sampler; 6] = [
Sampler::Nearest,
Sampler::Linear,
Sampler::NearestWhiteBorder,
Sampler::LinearWhiteBorder,
Sampler::NearestLess,
Sampler::LinearLess,
];
fn name(self) -> &'static str {
match self {
Sampler::Nearest => "nearest",
Sampler::Linear => "linear",
Sampler::NearestWhiteBorder => "nearest-white-border",
Sampler::LinearWhiteBorder => "linear-white-border",
Sampler::NearestLess => "nearest-less",
Sampler::LinearLess => "linear-less",
}
}
fn spec(self) -> SamplerSpec {
let filter = match self {
Sampler::Nearest | Sampler::NearestWhiteBorder | Sampler::NearestLess => {
SamplerMinMagFilter::Nearest
}
Sampler::Linear | Sampler::LinearWhiteBorder | Sampler::LinearLess => {
SamplerMinMagFilter::Linear
}
};
let spec = SamplerSpec::filtered(filter);
match self {
Sampler::NearestWhiteBorder | Sampler::LinearWhiteBorder => spec
.addressed(SamplerAddressMode::ClampToBorderColor)
.bordered(SamplerBorderColor::OpaqueWhite),
Sampler::NearestLess | Sampler::LinearLess => spec.comparing(CompareFunction::Less),
Sampler::Nearest | Sampler::Linear => spec,
}
}
}
/// One read of the case: its site, its kernel, its sampler, the texture it reads, and the
/// components (0 red to 3 alpha) where the 630's answer differs from the M3 Max's, which hold
/// 0 there.
struct Read {
site: &'static str,
kernel: &'static str,
sampler: Sampler,
through: Through,
unlike: &'static [usize],
}
/// The reads, in order.
const READS: [Read; 13] = [
Read {
site: "sample/nearest",
kernel: "dvw_sample",
sampler: Sampler::Nearest,
through: Through::Plain,
unlike: &[1, 2],
},
Read {
site: "sample/linear",
kernel: "dvw_sample",
sampler: Sampler::Linear,
through: Through::Plain,
unlike: &[1, 2],
},
Read {
site: "sample/nearest-white-border",
kernel: "dvw_sample",
sampler: Sampler::NearestWhiteBorder,
through: Through::Plain,
unlike: &[1, 2],
},
Read {
site: "sample/linear-white-border",
kernel: "dvw_sample",
sampler: Sampler::LinearWhiteBorder,
through: Through::Plain,
unlike: &[1, 2],
},
Read {
site: "gather-green/nearest",
kernel: "dvw_gather_green",
sampler: Sampler::Nearest,
through: Through::Plain,
unlike: &[0, 1, 2, 3],
},
Read {
site: "gather-alpha/nearest",
kernel: "dvw_gather_alpha",
sampler: Sampler::Nearest,
through: Through::Plain,
unlike: &[],
},
Read {
site: "swizzled-sample/nearest",
kernel: "dvw_sample",
sampler: Sampler::Nearest,
through: Through::Swizzled,
unlike: &[0],
},
Read {
site: "swizzled-sample/nearest-white-border",
kernel: "dvw_sample",
sampler: Sampler::NearestWhiteBorder,
through: Through::Swizzled,
unlike: &[0],
},
Read {
site: "swizzled-gather-green/nearest",
kernel: "dvw_gather_green",
sampler: Sampler::Nearest,
through: Through::Swizzled,
unlike: &[],
},
Read {
site: "depth/nearest",
kernel: "dvw_depth",
sampler: Sampler::Nearest,
through: Through::Plain,
unlike: &[],
},
Read {
site: "depth/linear",
kernel: "dvw_depth",
sampler: Sampler::Linear,
through: Through::Plain,
unlike: &[],
},
Read {
site: "compare/nearest",
kernel: "dvw_compare",
sampler: Sampler::NearestLess,
through: Through::Plain,
unlike: &[],
},
Read {
site: "compare/linear",
kernel: "dvw_compare",
sampler: Sampler::LinearLess,
through: Through::Plain,
unlike: &[],
},
];
/// The kernels, each once.
const KERNELS: [&str; 5] = [
"dvw_sample",
"dvw_gather_green",
"dvw_gather_alpha",
"dvw_depth",
"dvw_compare",
];
/// The view's swizzle: `(Green, Red, One, Zero)`.
fn swizzle() -> TextureSwizzleChannels {
TextureSwizzleChannels::new(
TextureSwizzle::Green,
TextureSwizzle::Red,
TextureSwizzle::One,
TextureSwizzle::Zero,
)
}
/// The texture's texels, row major, four bytes each.
fn texels() -> Vec<u8> {
(0..SIZE[1])
.flat_map(|_| (0..SIZE[0]).flat_map(|x| depth(x).to_le_bytes()))
.collect()
}
/// The coordinates the kernels read at buffer 1: each lane's normalized `(x, y)`.
fn coords() -> Vec<u8> {
let [w, h] = SIZE.map(|s| s as f32);
LANES
.iter()
.flat_map(|x| [x / w, 2.5 / h])
.flat_map(f32::to_le_bytes)
.collect()
}
/// The output buffer before a pass: one `float4` a lane.
fn blank() -> Vec<u8> {
vec![BLANK; LANES.len() * 16]
}
/// The layout a read-back is read under: one row a lane, its four `float`s.
fn layout() -> ByteLayout {
let row = 16u32;
ByteLayout {
region: crate::transcript::Region::Buffer {
offset: 0,
length: u64::from(row) * LANES.len() as u64,
},
element: Element::F32,
row_offset: 0,
row_elements: 4,
row_pitch: row,
rows: LANES.len() as u32,
image_pitch: row * LANES.len() as u32,
images: 1,
gaps: crate::transcript::Gaps::Ignored,
}
}
/// The parent texture: `Depth32Float`, shader-read, and viewable as another texture, as the
/// probe made it.
fn texture() -> TextureRequest<'static> {
let mut request = TextureRequest::read_2d(PixelFormat::Depth32Float.as_raw(), SIZE[0], SIZE[1]);
request.usage = TextureUsage::SHADER_READ.union(TextureUsage::PIXEL_FORMAT_VIEW);
request
}
/// The case.
pub struct DepthColourReads;
/// The one case of the family.
pub fn all() -> Vec<DepthColourReads> {
vec![DepthColourReads]
}
impl Case for DepthColourReads {
fn name(&self) -> &'static str {
"depth-colour-reads"
}
fn metal_source(&self) -> MetalSource {
MetalSource::Run
}
fn allowances(&self) -> Vec<Allowance> {
// The samples are through a runtime sampler slot, which the runtime's pipelines note as
// scaled (`crate::replay::pixel_sampler_scaling_notice` holds why).
let mut allowances = vec![crate::replay::pixel_sampler_scaling_notice()];
// The comparing stage records that its texels hold no value outside [0, 1]
// (`restricted-depth-range`), and the upload into a 32-bit float depth carries its note
// (`restricted-depth-upload`). Every texel is 0.25 or 0.75, so neither moves a value:
// measured through the rt side on lavapipe, the notices site was the whole of their
// difference (job m3-max-84879).
allowances.push(notice_allowance(Degradation::RestrictedDepthRange.code()));
allowances.push(notice_allowance(Degradation::RestrictedDepthUpload.code()));
let zero = Value::Float {
bits: 0,
width: FloatWidth::Single,
};
for read in &READS {
for lane in 0..LANES.len() {
for &component in read.unlike {
let at = (lane * 4 + component) * 4;
allowances.push(Allowance::new(
format!("case/{}/words/{at}", read.site),
Loosening::AnyOf(vec![zero.clone()]),
Justification::accepted(DEPTH_AS_COLOUR),
));
}
}
}
allowances
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let mut shaders = Vec::new();
for kernel in KERNELS {
let fixture = Fixture {
name: FIXTURE,
entry: kernel,
};
for extension in [RUNTIME_TEXT, METAL_TEXT] {
shaders.push(ShaderRef {
fixture: format!("{FIXTURE}{extension}"),
entry: kernel.to_owned(),
source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()),
});
}
}
Ok(shaders)
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let fixture = Fixture::new(FIXTURE);
let bytes = texels();
let uploads = [Upload::level_0(SIZE, SIZE[0] * 4, SIZE[1], &bytes)];
let parent = texture().loaded(&uploads);
let mut view = parent;
view.swizzle = swizzle();
let mut inputs = vec![
Input {
name: "air".to_owned(),
digest: Digest::sha256(fixture.text(RUNTIME_TEXT)?.as_bytes()),
},
Input {
name: "air-typed".to_owned(),
digest: Digest::sha256(fixture.text(METAL_TEXT)?.as_bytes()),
},
Input::bytes("buffer:coords", &coords()),
Input::bytes("buffer:blank", &blank()),
Input::bytes("texture", &parent.words()),
Input::bytes("texture:swizzled-view", &view.words()),
];
for sampler in Sampler::ALL {
inputs.push(Input::bytes(
format!("sampler:{}", sampler.name()),
&sampler.spec().words(),
));
}
Ok(inputs)
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let stop = |at: &str, why: String| Abort {
at: at.to_owned(),
failure: Failure::named("FixtureNotRead", why),
};
let loaded = Fixture::new(FIXTURE)
.loaded()
.map_err(|why| stop("library", why))?;
let library = made(sites, "library", side.library(&loaded.source()))?;
let mut pipelines = Vec::with_capacity(KERNELS.len());
for kernel in KERNELS {
let at = format!("pipeline/{kernel}");
pipelines.push(made(sites, &at, side.compute_pipeline(library, kernel))?);
}
let bytes = texels();
let uploads = [Upload::level_0(SIZE, SIZE[0] * 4, SIZE[1], &bytes)];
let parent = made(sites, "texture", side.texture(&texture().loaded(&uploads)))?;
let mut view = texture().viewing(parent);
view.swizzle = swizzle();
let swizzled = made(sites, "texture/swizzled-view", side.texture(&view))?;
let mut samplers = Vec::with_capacity(Sampler::ALL.len());
for sampler in Sampler::ALL {
let at = format!("sampler/{}", sampler.name());
samplers.push(made(sites, &at, side.sampler(&sampler.spec()))?);
}
let coords = made(sites, "buffer/coords", side.buffer(&coords()))?;
for read in &READS {
let at = |site: &str| format!("{}/{site}", read.site);
let Some(index) = KERNELS.iter().position(|k| *k == read.kernel) else {
return Err(stop(read.site, format!("no kernel {}", read.kernel)));
};
let Some(sampler) = Sampler::ALL.iter().position(|s| *s == read.sampler) else {
return Err(stop(read.site, "no sampler".to_owned()));
};
let texture = match read.through {
Through::Plain => parent,
Through::Swizzled => swizzled,
};
let out = made(sites, &at("buffer/out"), side.buffer(&blank()))?;
let command_buffer = made(
sites,
&at("dispatch"),
side.dispatch_threads(
pipelines[index],
&Bindings::new(&[texture], &[out, coords]).sampled(&[samplers[sampler]]),
&[],
[LANES.len() as u32, 1, 1],
[LANES.len() as u32, 1, 1],
),
)?;
call(
sites,
&at("status"),
side.wait(command_buffer),
Clone::clone,
)?;
let words = call(
sites,
&at("read-back"),
side.read_buffer(out, 0, blank().len()),
|_| Value::Absent,
)?;
sites.push(
Node::branch(read.site, Vec::new())
.with(Node::leaf("words", Observed::bytes(words, layout()))),
);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A Mac family's answer to a read of the case: the probes' table (module docs), as rules of
/// the texel's depth `d`.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Mac {
M3Max,
Radeon5300M,
Uhd630,
}
impl Mac {
/// The texel a sample of depth `d` reads, before a view's swizzle; past the edge under
/// an opaque white border, `d` is 1.
fn texel(self, d: f32) -> [f32; 4] {
match self {
Mac::M3Max => [d, d, d, 1.0],
Mac::Radeon5300M => [d; 4],
Mac::Uhd630 => [d, 0.0, 0.0, 1.0],
}
}
}
/// The `(Green, Red, One, Zero)` swizzle of `t`.
fn swizzled(t: [f32; 4]) -> [f32; 4] {
[t[1], t[0], 1.0, 0.0]
}
/// The components where the 630's sample differs from the M3 Max's are the ones each read
/// lets hold 0, and 0 is the 630's value there, at any depth and past the edge under the
/// white border: the allowances admit the 630's answer and no other.
#[test]
fn the_allowed_components_are_where_the_630_differs_from_the_m3_max() {
for read in &READS {
let unlike: Vec<usize> = match (read.kernel, read.through) {
("dvw_sample", Through::Plain) => {
let (m3, intel) = (Mac::M3Max.texel(0.25), Mac::Uhd630.texel(0.25));
(0..4).filter(|&c| m3[c] != intel[c]).collect()
}
("dvw_sample", Through::Swizzled) => {
let m3 = swizzled(Mac::M3Max.texel(0.25));
let intel = swizzled(Mac::Uhd630.texel(0.25));
(0..4).filter(|&c| m3[c] != intel[c]).collect()
}
// A gather of green reads each tap's green: the 630's is 0, the M3 Max's the
// depth; through the view, green is red, the depth on both.
("dvw_gather_green", Through::Plain) => vec![0, 1, 2, 3],
("dvw_gather_green", Through::Swizzled) => vec![],
// A gather of alpha reads 1 on both; the `depth2d` reads agree on all three.
_ => vec![],
};
assert_eq!(read.unlike, unlike.as_slice(), "{}", read.site);
for &c in &unlike {
let intel = match read.through {
Through::Plain => Mac::Uhd630.texel(0.75),
Through::Swizzled => swizzled(Mac::Uhd630.texel(0.75)),
};
if read.kernel == "dvw_sample" {
assert_eq!(intel[c], 0.0, "{} component {c}", read.site);
}
}
}
}
/// The 5300M answers a sample's alpha with the depth, where the M3 Max and the 630 answer 1:
/// no one answer of the colour channels is every Mac's.
#[test]
fn no_one_answer_is_every_macs() {
let answers = [Mac::M3Max, Mac::Radeon5300M, Mac::Uhd630].map(|m| m.texel(0.25));
assert_ne!(answers[0], answers[1]);
assert_ne!(answers[0], answers[2]);
assert_ne!(answers[1], answers[2]);
assert!(
answers.iter().all(|t| t[0] == 0.25),
"red is the depth on every Mac"
);
}
/// Every coordinate is exact in `float`, so a linear weight is the same on every device.
#[test]
fn the_coordinates_are_exact() {
for x in LANES {
let u = x / SIZE[0] as f32;
assert_eq!(u * SIZE[0] as f32, x, "lane {x}");
}
}
}
@@ -249,19 +249,14 @@ fn unspecialized() -> HeapSizeCase {
}
}
/// The formats Metal describes no texture of alone: `RGBA16Float_XR`, `AnyDepth`, `AnyStencil` and
/// a two-plane YCbCr format. Each answers 0 bytes at its texture type's alignment, and no texture.
/// The formats Metal describes no texture of alone
/// ([`WITHOUT_TEXTURES`](crate::texture_query::WITHOUT_TEXTURES)). Each answers 0 bytes at its texture type's alignment, and no texture.
///
/// `AnyDepth` and `AnyStencil` are asked in the 2D and cube types alone: Metal's validation stops a
/// one-dimensional, 3D or buffer descriptor of either, which ends its process.
fn formats_without_textures() -> HeapSizeCase {
let mut queries = Vec::new();
for format in [
PixelFormat::RGBA16FloatXR,
PixelFormat::AnyDepth,
PixelFormat::AnyStencil,
PixelFormat::YCBCR84202P,
] {
for format in crate::texture_query::WITHOUT_TEXTURES {
let any_depth = matches!(format, PixelFormat::AnyDepth | PixelFormat::AnyStencil);
for (texture_type, depth, slices) in STACKABLE_TYPES {
let one_dimensional =
@@ -0,0 +1,270 @@
//! A kernel's explicit imageblock written through a slice from a partial threadgroup: what the
//! cells of the threads past the grid hold.
//!
//! The owned fixture `tib_imageblock_slices`'s `tib_slot_half_slice` (its source says what each
//! thread does) runs as one compute pass: the encoder sets a 4 by 4 imageblock, then
//! `dispatchThreads:threadsPerThreadgroup:` runs a grid of 6 by 7 threads in 4 by 4 threadgroups,
//! so three of the four threadgroups are partial: one in x, one in y and the corner. Each thread
//! stores its value in its own cell, and after the imageblock barrier the threadgroup's first
//! thread writes the whole 4 by 4 slice at its threadgroup's origin of an 8 by 8 `RGBA16Float`
//! texture, so every slice lies inside it.
//!
//! Metal's documentation says nothing of what a slice holds at the cells of threads a partial
//! threadgroup does not run. This case carries the answer the Apple M3 Max recorded, and claims no
//! more than that: every such cell's texel is zero, as a texel the slice did not write would keep
//! [`SENTINEL`] and a cell some thread stored would hold that thread's value.
//!
//! Every texel holds [`SENTINEL`] before the dispatch, and the texture is compared whole. Every
//! value is exact in a half. Nothing here can fault a GPU: one pass of one dispatch, four
//! threadgroups of at most 16 threads, loop-free, every cell a thread stores its own and every
//! slice inside the texture.
use crate::case::{
call, made, Abort, Case, Failure, Handle, Input, MetalSource, Side, TextureRole, TextureSpec,
};
use crate::compute_pass::{ComputePass, ComputeStep, Dispatching};
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::transcript::{
Aspect, ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites, Value,
};
use metal2vulkan::metal::PixelFormat;
/// The case.
pub struct ImageblockSlicePastGrid;
/// The case's name.
pub const NAME: &str = "compute-imageblock-slice-past-the-grid";
/// The fixture and the kernel the case runs.
const FIXTURE: Fixture = Fixture {
name: "tib_imageblock_slices",
entry: "tib_slot_half_slice",
};
/// A threadgroup's threads along x and y, which is the imageblock's extent too.
const GROUP: u32 = 4;
/// The grid, in threads: not a whole number of threadgroups along either axis.
const GRID: [u32; 3] = [6, 7, 1];
/// The texture's extent: the grid's threadgroups, whole.
const SIZE: [u32; 2] = [8, 8];
/// Bytes of one `RGBA16Float` texel.
const TEXEL: u32 = 8;
/// The half every channel of every texel holds before the dispatch: -1.
pub const SENTINEL: u16 = 0xbc00;
/// The texture's bytes before the dispatch.
fn fill() -> Vec<u8> {
SENTINEL
.to_le_bytes()
.repeat((SIZE[0] * SIZE[1] * 4) as usize)
}
fn spec() -> TextureSpec {
TextureSpec::new(
PixelFormat::RGBA16Float,
SIZE,
SIZE[0] * TEXEL,
TextureRole::Write,
)
}
/// The layout the texels are compared under: one row a texel, a half a channel, so a difference
/// names the texel (`y * 8 + x`) and the channel.
fn layout() -> ByteLayout {
let texels = SIZE[0] * SIZE[1];
ByteLayout {
region: Region::Texture {
level: 0,
slice: 0,
aspect: Aspect::Color,
sample: 0,
origin: [0, 0, 0],
size: [SIZE[0], SIZE[1], 1],
},
element: Element::U16,
row_offset: 0,
row_elements: 4,
row_pitch: TEXEL,
rows: texels,
image_pitch: texels * TEXEL,
images: 1,
// A row is one texel's channels and the texels abut, so there is no byte outside one.
gaps: Gaps::Ignored,
}
}
/// The pass: the texture at slot 0, the imageblock's size, one dispatch of the grid.
fn steps(pipeline: Handle, texture: Handle) -> Vec<ComputeStep> {
vec![
ComputeStep::Pipeline(pipeline),
ComputeStep::Texture { texture, index: 0 },
ComputeStep::ImageblockSize {
width: GROUP,
height: GROUP,
},
ComputeStep::DispatchThreads {
grid: GRID,
threads: [GROUP, GROUP, 1],
},
]
}
impl Case for ImageblockSlicePastGrid {
fn name(&self) -> &'static str {
NAME
}
fn metal_source(&self) -> MetalSource {
MetalSource::Run
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let mut shaders = Vec::new();
for extension in [RUNTIME_TEXT, METAL_TEXT] {
shaders.push(ShaderRef {
fixture: format!("{}{extension}", FIXTURE.name),
entry: FIXTURE.entry.to_owned(),
source_sha256: crate::sha256_hex(FIXTURE.text(extension)?.as_bytes()),
});
}
Ok(shaders)
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let steps = steps(Handle(0), Handle(0));
Ok(vec![
Input {
name: "air".to_owned(),
digest: Digest::sha256(FIXTURE.text(RUNTIME_TEXT)?.as_bytes()),
},
Input {
name: "air-typed".to_owned(),
digest: Digest::sha256(FIXTURE.text(METAL_TEXT)?.as_bytes()),
},
Input::bytes("entry", FIXTURE.entry.as_bytes()),
Input::bytes("texture:fill", &fill()),
// The pass, with its grid and threadgroup: a case re-pointed at another grid is
// another question, so its recording cannot stand for this one.
Input::bytes(
"pass",
&ComputePass {
dispatching: Dispatching::Serial,
steps: &steps,
}
.words(),
),
])
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let loaded = FIXTURE.loaded().map_err(|why| Abort {
at: "library".to_owned(),
failure: Failure::named("FixtureNotRead", why),
})?;
let library = made(sites, "library", side.library(&loaded.source()))?;
let pipeline = made(
sites,
"pipeline",
side.compute_pipeline(library, loaded.entry),
)?;
let texture = made(sites, "texture", side.texture_2d_in_role(&spec(), &fill()))?;
let steps = steps(pipeline, texture);
let outcome = made(
sites,
"pass",
side.compute_pass(&ComputePass {
dispatching: Dispatching::Serial,
steps: &steps,
}),
)?;
sites.push(outcome.node("outcome", &steps));
if let Some((at, failure)) = outcome.first_refusal() {
return Err(Abort {
at: format!("outcome/step/{at}/{}", steps[at].call()),
failure: failure.clone(),
});
}
let stored = call(
sites,
"read-back",
side.read_texture(texture, SIZE, SIZE[0] * TEXEL),
|_| Value::Absent,
)?;
sites.push(Node::leaf("texels", Observed::bytes(stored, layout())));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The half of `x`, which must be a normal value a half holds exactly.
fn half(x: f32) -> u16 {
let bits = x.to_bits();
let exponent = ((bits >> 23) & 0xff) as u16 - (127 - 15);
assert_eq!(bits & 0x1fff, 0, "{x} is not exact in a half");
(exponent << 10) | ((bits >> 13) & 0x3ff) as u16
}
/// The texels Metal's recording holds: at a grid position, the fixture's value
/// `(1 + x + 8 * y) / 64` and three zeros; at a position past the grid, inside a partial
/// threadgroup's slice, four zeros.
fn recorded() -> Vec<u8> {
let mut bytes = Vec::new();
for y in 0..SIZE[1] {
for x in 0..SIZE[0] {
let first = match x < GRID[0] && y < GRID[1] {
true => half((1 + x + 8 * y) as f32 / 64.0),
false => 0,
};
for channel in [first, 0, 0, 0] {
bytes.extend(channel.to_le_bytes());
}
}
}
bytes
}
/// Metal's recorded answer: every grid thread's texel is its own value, and every cell past
/// the grid is zero, neither the sentinel nor any thread's value.
#[test]
fn metal_recorded_zero_past_the_grid() {
let recording =
crate::recording::read(NAME).unwrap_or_else(|e| panic!("{NAME}: no recording: {e}"));
let want = recorded();
let mut answers = 0;
for metal in &recording.answers {
for outcome in &metal.outcomes {
answers += 1;
let got = outcome
.transcript
.root
.child("texels")
.map(|n| &n.observed.value);
assert!(
matches!(got, Some(Value::Bytes(b)) if *b == want),
"{NAME}: Metal's bytes are {got:?}"
);
}
}
assert!(answers > 0, "{NAME}: no Metal answer");
}
/// The grid leaves a partial threadgroup in x, one in y and the corner, every slice lies
/// inside the texture, and the sentinel is none of the answers.
#[test]
fn the_grid_holds_each_partial_threadgroup_inside_the_texture() {
let groups = GRID.map(|n| n.div_ceil(GROUP));
assert_eq!(groups, [2, 2, 1]);
assert!(!GRID[0].is_multiple_of(GROUP) && !GRID[1].is_multiple_of(GROUP));
assert_eq!(SIZE, [groups[0] * GROUP, groups[1] * GROUP]);
assert_ne!(SENTINEL, 0);
assert!((0..64u32).all(|k| half((1 + k) as f32 / 64.0) != SENTINEL));
}
}
@@ -4,36 +4,57 @@
//! The range is read when the execution runs, not when it is encoded, so each row writes it on the
//! GPU in the execution's own command buffer, over a stale range the host wrote first that would
//! draw every command: a side that read the range before the GPU wrote it draws all eight. The
//! commands are the one shape both sides build ([`EncodedRange`]): indexed triangle draws that
//! inherit the pipeline state and bind their own buffers, encoded by the owned fixture's
//! `icb_indexed_16` kernel through the buffer's `gpuResourceID`. Command `i` draws rows `2i` and
//! `2i + 1` of an 8 by 16 `RGBA32Uint` target, each texel its mark, the provoking vertex's
//! `vid`, its `iid` and its tint, so the target names exactly which commands drew.
//! commands are the one shape both sides build ([`EncodedRange`]): triangle draws that inherit the
//! pipeline state and bind their own buffers, encoded by an owned fixture's kernel through the
//! buffer's `gpuResourceID`. Command `i` draws rows `2i` and `2i + 1` of an 8 by 16 `RGBA32Uint`
//! target, so the target names exactly which commands drew:
//!
//! | Row | The range, and what writes it |
//! |---|---|
//! | [`AT_ZERO`] | commands 0 to 2, a blit's copy before the pass |
//! | [`PAST_ZERO`] | commands 5 and 6, a blit's copy before the pass |
//! | [`DRAWN`] | commands 2 to 5, an earlier draw of the same pass, behind a memory barrier |
//! - indexed draws (`MTLIndirectCommandTypeDrawIndexed`) of `icb_merged_indexed`'s
//! `icb_indexed_16`, each texel its mark, the provoking vertex's `vid`, its `iid` and its tint;
//! - plain draws (`MTLIndirectCommandTypeDraw`) of `icb_merged_draws`'s `icb_merged_triangles`,
//! each command six vertices from vertex `6i`, one instance for an even command and two drawn
//! over each other for an odd one, from base instance `i`, each texel its mark, the provoking
//! vertex's `vid`, its `iid` and the base instance;
//! - patch draws (`MTLIndirectCommandTypeDrawPatches`) of `icb_merged_patches`, each command one
//! quad patch of one control point from patch `i`, with no patch index buffer, its factors a
//! record of level 1, one instance for an even command and two drawn over each other for an odd
//! one, from base instance `i`, the patch a rectangle over the command's rows, each texel its
//! mark, the patch index, its `iid` and the base instance;
//! - indexed patch draws (`MTLIndirectCommandTypeDrawIndexedPatches`) of `icb_merged_ipatches`,
//! each command one quad patch of four control points from patch `i`, read through a
//! `PerPatchControlPoint` layout under the `UInt16` control-point index type: the points are
//! stored out of order and the indices name each corner, so a patch drawn over its rectangle
//! read its indices; with no patch index buffer, its factors a record of level 1, instances and
//! base instances as the patch draws', each texel its mark, the patch index, its `iid` and the
//! base instance.
//!
//! Every row is bounded by construction: eight commands of two triangles each, one target of 8
//! by 16, one kernel thread a command, and no function holds a loop.
//! | Row | The draws | The range, and what writes it |
//! |---|---|---|
//! | [`AT_ZERO`] | indexed | commands 0 to 2, a blit's copy before the pass |
//! | [`PAST_ZERO`] | indexed | commands 5 and 6, a blit's copy before the pass |
//! | [`DRAWN`] | indexed | commands 2 to 5, an earlier draw of the same pass, behind a memory barrier |
//! | [`PLAIN`] | plain | commands 1 to 5, a blit's copy before the pass |
//! | [`PATCHES`] | patches | commands 1 to 5, a blit's copy before the pass |
//! | [`INDEXED_PATCHES`] | indexed patches | commands 1 to 5, a blit's copy before the pass |
//!
//! Every row is bounded by construction: eight commands of two triangles each (an odd plain or
//! patch command's two instances, four; a quad patch of level 1 is two triangles), one target of
//! 8 by 16, one kernel thread a command, and no function holds a loop.
use super::indirect_commands::{fixture_inputs, shaders_of};
use crate::allowance::Allowance;
use crate::case::{call, made, Abort, Case, EncodedRange, Failure, Input, MetalSource, RangeWrite};
use crate::case::{Side, TARGET_TEXEL};
use crate::degradation::Degradation;
use crate::fixture::Fixture;
use crate::recording::ShaderRef;
use crate::render::VertexStride;
use crate::render::{TessellationState, VertexAttribute, VertexBufferLayout, VertexLayout};
use crate::transcript::{Aspect, ByteLayout, Element, Gaps, Node, Observed, Region, Sites};
use metal2vulkan::metal::PixelFormat;
/// The owned fixture whose kernel encodes the commands and whose functions they draw with.
const FIXTURE: &str = "icb_merged_indexed";
/// The kernel that encodes command `tid`, and the state's two functions.
const KERNEL: &str = "icb_indexed_16";
const VERTEX: &str = "icb_indexed_vertex";
const FRAGMENT: &str = "icb_indexed_fragment";
use metal2vulkan::metal::{
IndirectCommandType, PixelFormat, TessellationControlPointIndexType, VertexFormat,
VertexStepFunction,
};
/// The owned fixture whose rasterization-disabled vertex function writes
/// `params[0] * (vid + 1) + params[1]` to `out[vid]` (instance 0): the earlier draw that writes
@@ -62,10 +83,243 @@ const TINT: u32 = 0x200;
pub const AT_ZERO: &str = "indirect-range-gpu-written-at-zero";
pub const PAST_ZERO: &str = "indirect-range-gpu-written-past-zero";
pub const DRAWN: &str = "indirect-range-written-by-an-earlier-draw";
pub const PLAIN: &str = "indirect-range-gpu-written-plain-draws";
pub const PATCHES: &str = "indirect-range-gpu-written-patch-draws";
pub const INDEXED_PATCHES: &str = "indirect-range-gpu-written-indexed-patch-draws";
/// One row: its name, the range the GPU writes (location, length), and what writes it.
/// The indexed patches' control point: a `float2` at attribute 0 of vertex buffer 2.
const CORNER: [VertexAttribute; 1] = [VertexAttribute::new(0, VertexFormat::Float2, 0, 2)];
/// Vertex buffer 2 steps per patch control point, 8 bytes a point.
const CORNERS: [VertexBufferLayout; 1] = [VertexBufferLayout {
index: 2,
stride: VertexStride::Bytes(8),
step: VertexStepFunction::PerPatchControlPoint,
rate: 1,
}];
/// Where the indexed patches store corner `j` of a patch among its four points: the indices
/// put them back in order (point `4i + PLACES[j]` is corner `j` of patch `i`).
const PLACES: [u32; 4] = [2, 0, 3, 1];
/// The draws a row's commands make.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Draws {
/// `icb_merged_indexed`'s indexed draws of 16-bit indices.
Indexed,
/// `icb_merged_draws`'s plain draws.
Plain,
/// `icb_merged_patches`'s patch draws.
Patches,
/// `icb_merged_ipatches`'s indexed patch draws of 16-bit control-point indices.
IndexedPatches,
}
impl Draws {
/// The owned fixture whose kernel encodes the commands and whose functions they draw with.
fn fixture(self) -> &'static str {
match self {
Draws::Indexed => "icb_merged_indexed",
Draws::Plain => "icb_merged_draws",
Draws::Patches => "icb_merged_patches",
Draws::IndexedPatches => "icb_merged_ipatches",
}
}
/// The kernel that encodes command `tid`, and the state's vertex and fragment functions.
fn functions(self) -> [&'static str; 3] {
match self {
Draws::Indexed => [
"icb_indexed_16",
"icb_indexed_vertex",
"icb_indexed_fragment",
],
Draws::Plain => [
"icb_merged_triangles",
"icb_merged_vertex",
"icb_merged_fragment",
],
Draws::Patches => [
"icb_merged_patches",
"icb_merged_patch_vertex",
"icb_merged_patch_fragment",
],
Draws::IndexedPatches => [
"icb_merged_ipatches",
"icb_merged_ipatch_vertex",
"icb_merged_ipatch_fragment",
],
}
}
/// The buffer's `commandTypes`.
fn command_types(self) -> IndirectCommandType {
match self {
Draws::Indexed => IndirectCommandType::DRAW_INDEXED,
Draws::Plain => IndirectCommandType::DRAW,
Draws::Patches => IndirectCommandType::DRAW_PATCHES,
Draws::IndexedPatches => IndirectCommandType::DRAW_INDEXED_PATCHES,
}
}
/// `maxVertexBufferBindCount` and `maxFragmentBufferBindCount`: the vertex function's three
/// buffers, and the indexed fragment function's tint.
fn bind_counts(self) -> [u32; 2] {
match self {
Draws::Indexed => [3, 1],
Draws::Plain | Draws::Patches | Draws::IndexedPatches => [3, 0],
}
}
/// The kernel's buffers 1 and up, by name, and how many of them, from the second, the
/// commands read through their bindings.
///
/// Indexed: each command's draw (first index, index count, instances, base vertex, base
/// instance), the marks, the frame (the target's extent and no instance step), the pixel
/// corners of each command's quad, the tints, and two copies of a quad's six 16-bit indices,
/// command `i` drawing from copy `i % 2`. Plain: each command's draw (vertex start, vertex
/// count, instances, base instance), the marks, the frame, and the pixel positions of each
/// command's six vertices, two triangles over its rows. Patches: each command's draw (patch
/// start, patch count, instances, base instance), the marks, the frame, the pixel corners of
/// each patch's rectangle (top left, bottom right), and the factors: a quad factor record of
/// `half` 1.0 (four edges and two inside factors) for each patch position. Indexed patches:
/// the patch draws, the marks, the frame, each patch's four corners in pixels stored at their
/// [`PLACES`], the 16-bit control-point indices that name them in order, and the factors.
fn kernel_buffers(self) -> Vec<(&'static str, Vec<u8>)> {
let marks: Vec<u32> = (0..COMMANDS).map(|i| MARK + i).collect();
let frame = floats(&[SIZE[0] as f32, SIZE[1] as f32, 0.0, 0.0]);
let rows = |i: u32| ((2 * i) as f32, (2 * i + 2) as f32);
match self {
Draws::Indexed => {
let draws: Vec<u32> = (0..COMMANDS)
.flat_map(|i| [6 * (i % 2), 6, 1, 4 * i, i])
.collect();
let xy: Vec<f32> = (0..COMMANDS)
.flat_map(|i| {
let (top, bottom) = rows(i);
[0.0, top, 8.0, top, 0.0, bottom, 8.0, bottom]
})
.collect();
let tints: Vec<u32> = (0..COMMANDS).map(|i| TINT + i).collect();
let indices: Vec<u8> = [0u16, 1, 2, 2, 1, 3]
.repeat(2)
.iter()
.flat_map(|i| i.to_le_bytes())
.collect();
vec![
("buffer:draws", words(&draws)),
("buffer:marks", words(&marks)),
("buffer:frame", frame),
("buffer:xy", floats(&xy)),
("buffer:tints", words(&tints)),
("buffer:indices", indices),
]
}
Draws::Plain => {
let draws: Vec<u32> = (0..COMMANDS)
.flat_map(|i| [6 * i, 6, 1 + i % 2, i])
.collect();
let xy: Vec<f32> = (0..COMMANDS)
.flat_map(|i| {
let (top, bottom) = rows(i);
[
0.0, top, 8.0, top, 0.0, bottom, 0.0, bottom, 8.0, top, 8.0, bottom,
]
})
.collect();
vec![
("buffer:draws", words(&draws)),
("buffer:marks", words(&marks)),
("buffer:frame", frame),
("buffer:xy", floats(&xy)),
]
}
Draws::Patches => {
let draws: Vec<u32> = (0..COMMANDS).flat_map(|i| [i, 1, 1 + i % 2, i]).collect();
let xy: Vec<f32> = (0..COMMANDS)
.flat_map(|i| {
let (top, bottom) = rows(i);
[0.0, top, 8.0, bottom]
})
.collect();
// `half` 1.0 is 0x3c00.
let factors: Vec<u8> = [0x3c00u16; 6]
.repeat(COMMANDS as usize)
.iter()
.flat_map(|f| f.to_le_bytes())
.collect();
vec![
("buffer:draws", words(&draws)),
("buffer:marks", words(&marks)),
("buffer:frame", frame),
("buffer:xy", floats(&xy)),
("buffer:factors", factors),
]
}
Draws::IndexedPatches => {
let draws: Vec<u32> = (0..COMMANDS).flat_map(|i| [i, 1, 1 + i % 2, i]).collect();
let mut corners = vec![0f32; 8 * COMMANDS as usize];
let mut points = Vec::new();
for i in 0..COMMANDS {
let (top, bottom) = rows(i);
let corner = [[0.0, top], [8.0, top], [0.0, bottom], [8.0, bottom]];
for (j, xy) in corner.into_iter().enumerate() {
let at = 4 * i + PLACES[j];
corners[2 * at as usize..][..2].copy_from_slice(&xy);
points.extend((at as u16).to_le_bytes());
}
}
// `half` 1.0 is 0x3c00.
let factors: Vec<u8> = [0x3c00u16; 6]
.repeat(COMMANDS as usize)
.iter()
.flat_map(|f| f.to_le_bytes())
.collect();
vec![
("buffer:draws", words(&draws)),
("buffer:marks", words(&marks)),
("buffer:frame", frame),
("buffer:corners", floats(&corners)),
("buffer:points", points),
("buffer:factors", factors),
]
}
}
}
/// The execution's line among the inputs.
fn execution(self) -> &'static str {
match self {
Draws::Indexed => "DrawIndexed, inherited state, 3 vertex and 1 fragment buffers",
Draws::Plain => "Draw, inherited state, 3 vertex and 0 fragment buffers",
Draws::Patches => "DrawPatches, inherited state, 3 vertex and 0 fragment buffers",
Draws::IndexedPatches => {
"DrawIndexedPatches, inherited state, 3 vertex and 0 fragment buffers, control \
points a float2 at attribute 0 of buffer 2 stepped per patch control point at 8 \
bytes, UInt16 control-point indices"
}
}
}
/// The pipeline's vertex descriptor and tessellation state: the indexed patches' control
/// points and index type; Metal's defaults for the rest.
fn control_points(self) -> (Option<VertexLayout<'static>>, Option<TessellationState>) {
match self {
Draws::IndexedPatches => (
Some(VertexLayout::new(&CORNER, &CORNERS)),
Some(
TessellationState::new().indexed_by(TessellationControlPointIndexType::UInt16),
),
),
Draws::Indexed | Draws::Plain | Draws::Patches => (None, None),
}
}
}
/// One row: its name, its draws, the range the GPU writes (location, length), and what writes it.
pub struct GpuRange {
name: &'static str,
draws: Draws,
range: [u32; 2],
drawn: bool,
}
@@ -78,40 +332,6 @@ fn floats(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|v| v.to_le_bytes()).collect()
}
/// The kernel's buffers 1 to 6, by name: each command's draw (first index, index count,
/// instances, base vertex, base instance), the marks, the frame (the target's extent and no
/// instance step), the pixel corners of each command's quad, the tints, and two copies of a
/// quad's six 16-bit indices, command `i` drawing from copy `i % 2`.
fn kernel_buffers() -> [(&'static str, Vec<u8>); 6] {
let draws: Vec<u32> = (0..COMMANDS)
.flat_map(|i| [6 * (i % 2), 6, 1, 4 * i, i])
.collect();
let xy: Vec<f32> = (0..COMMANDS)
.flat_map(|i| {
let (top, bottom) = ((2 * i) as f32, (2 * i + 2) as f32);
[0.0, top, 8.0, top, 0.0, bottom, 8.0, bottom]
})
.collect();
let marks: Vec<u32> = (0..COMMANDS).map(|i| MARK + i).collect();
let tints: Vec<u32> = (0..COMMANDS).map(|i| TINT + i).collect();
let indices: Vec<u8> = [0u16, 1, 2, 2, 1, 3]
.repeat(2)
.iter()
.flat_map(|i| i.to_le_bytes())
.collect();
[
("buffer:draws", words(&draws)),
("buffer:marks", words(&marks)),
(
"buffer:frame",
floats(&[SIZE[0] as f32, SIZE[1] as f32, 0.0, 0.0]),
),
("buffer:xy", floats(&xy)),
("buffer:tints", words(&tints)),
("buffer:indices", indices),
]
}
impl GpuRange {
/// The bytes of the buffer the range is written from: a blit's source holds the range itself;
/// the writer's `params` the pair whose two vertices write the location and the length,
@@ -183,10 +403,30 @@ impl Case for GpuRange {
MetalSource::Run
}
fn allowances(&self) -> Vec<Allowance> {
// No value is loosened. The plain draws' vertex function writes `[[point_size]]`, so their
// render state carries the static note `device-point-size` on a device whose largest point
// is below Metal's, whatever primitive it draws; that notice is declared. The indexed
// draws' vertex function writes none. The patch draws' tessellating pipeline announces the
// tessellation notices every row that draws a patch declares
// (`tessellation_sweeps::tessellation_notices`), as do the indexed patch draws': none
// moves a texel of a quad patch of level 1, whose two triangles cover its rectangle in
// any order and winding.
match self.draws {
Draws::Indexed => Vec::new(),
Draws::Plain => vec![crate::replay::notice_allowance(
Degradation::DevicePointSize.code(),
)],
Draws::Patches | Draws::IndexedPatches => {
super::tessellation_sweeps::tessellation_notices()
}
}
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let mut shaders = Vec::new();
for entry in [KERNEL, VERTEX, FRAGMENT] {
shaders.extend(shaders_of(FIXTURE, entry)?);
for entry in self.draws.functions() {
shaders.extend(shaders_of(self.draws.fixture(), entry)?);
}
if self.drawn {
shaders.extend(shaders_of(WRITER, WRITER)?);
@@ -195,14 +435,14 @@ impl Case for GpuRange {
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let mut inputs = fixture_inputs(FIXTURE)?;
let mut inputs = fixture_inputs(self.draws.fixture())?;
if self.drawn {
for mut input in fixture_inputs(WRITER)? {
input.name = format!("writer-{}", input.name);
inputs.push(input);
}
}
for (name, bytes) in kernel_buffers() {
for (name, bytes) in self.draws.kernel_buffers() {
inputs.push(Input::bytes(name, &bytes));
}
inputs.push(Input::bytes("buffer:range", &words(&STALE)));
@@ -210,8 +450,9 @@ impl Case for GpuRange {
inputs.push(Input::bytes(
"execution",
format!(
"{COMMANDS} commands of DrawIndexed, inherited state, 3 vertex and 1 fragment \
buffers; the range at offset {OFFSET}; {}; target RGBA32Uint {}x{} cleared to 0",
"{COMMANDS} commands of {}; the range at offset {OFFSET}; {}; target RGBA32Uint \
{}x{} cleared to 0",
self.draws.execution(),
match self.drawn {
false => "copied by a blit before the pass",
true => "written by two points of the writer, then a barrier of buffers",
@@ -225,13 +466,13 @@ impl Case for GpuRange {
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let library_handle = library(side, sites, FIXTURE, "library")?;
let library_handle = library(side, sites, self.draws.fixture(), "library")?;
let writer = match self.drawn {
true => Some(library(side, sites, WRITER, "writer-library")?),
false => None,
};
let mut buffers = Vec::new();
for (name, bytes) in kernel_buffers() {
for (name, bytes) in self.draws.kernel_buffers() {
buffers.push(made(sites, name, side.buffer(&bytes))?);
}
let range = made(sites, "buffer:range", side.buffer(&words(&STALE)))?;
@@ -244,17 +485,22 @@ impl Case for GpuRange {
},
None => RangeWrite::Copied { from: source },
};
// The commands read the marks, the frame, the corners, the tints and the indices through
// their bindings; the draws only the kernel reads.
// The commands read every buffer after the draws through their bindings; the draws only
// the kernel reads.
let [kernel, vertex, fragment] = self.draws.functions();
let (vertex_layout, tessellation) = self.draws.control_points();
let run = EncodedRange {
library: library_handle,
kernel: KERNEL,
kernel,
buffers: &buffers,
commands: COMMANDS,
bind_counts: [3, 1],
vertex: VERTEX,
fragment: FRAGMENT,
command_types: self.draws.command_types(),
bind_counts: self.draws.bind_counts(),
vertex,
fragment,
format: PixelFormat::RGBA32Uint,
vertex_layout,
tessellation,
size: SIZE,
row_pitch: SIZE[0] * TARGET_TEXEL,
used: &buffers[1..],
@@ -276,11 +522,21 @@ impl Case for GpuRange {
/// The family's rows, in the order the report lists them.
pub fn boxed() -> Vec<Box<dyn Case>> {
[
(AT_ZERO, [0, 3], false),
(PAST_ZERO, [5, 2], false),
(DRAWN, [2, 4], true),
(AT_ZERO, Draws::Indexed, [0, 3], false),
(PAST_ZERO, Draws::Indexed, [5, 2], false),
(DRAWN, Draws::Indexed, [2, 4], true),
(PLAIN, Draws::Plain, [1, 5], false),
(PATCHES, Draws::Patches, [1, 5], false),
(INDEXED_PATCHES, Draws::IndexedPatches, [1, 5], false),
]
.into_iter()
.map(|(name, range, drawn)| Box::new(GpuRange { name, range, drawn }) as Box<dyn Case>)
.map(|(name, draws, range, drawn)| {
Box::new(GpuRange {
name,
draws,
range,
drawn,
}) as Box<dyn Case>
})
.collect()
}
@@ -0,0 +1,207 @@
//! Which commit takes a Managed buffer's named range to the GPU, one case a reader
//! ([`crate::managed_naming::Way`]): a compute slot, a declaration by `useResource:usage:`, a
//! reach through the buffer's address alone, a vertex slot with a draw, and a blit copy's source.
//! [`crate::managed_naming`] states the sequence and what each reader answers.
//!
//! # Where Metal's answer comes from
//!
//! Carried, from a table measured on an AMD Radeon Pro 5300M under macOS 26.7.1, 8 rounds a
//! reader, by a probe of the same sequence (jobs 81602 and 81644): the readers that name the
//! buffer read the bytes as of their own commit, and the reader through the address the bytes the
//! GPU's copy last took. The oracle keeps one copy of a Managed buffer (`hasUnifiedMemory` true),
//! so its run would answer another question, and record mode keeps the measured table. The site
//! holds which of the sequence's three contents the reader read, which is what the table states;
//! the probe's own bytes are not the case's.
//!
//! # Where it compares
//!
//! On a device that keeps one copy of a Managed buffer the runtime has no second copy to read
//! through an address, and the address row reads the venue's gap there; the other rows read the
//! bytes as of their commit in either form, as the 5300M's and a one-copy Intel UHD Graphics 630's
//! (jobs 81603 and 81645) did.
//!
//! # Why it is safe
//!
//! Every reader reads 256 bytes of a live buffer: two kernels of one thread an element, one
//! triangle over a 4 by 4 target, and blit copies and fills inside their buffers. Every wait is
//! bounded.
use crate::case::{answered, made, Abort, Case, Failure, Input, MetalSource, Side};
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::managed_naming::{Content, Libraries, Read, Way};
use crate::recording::ShaderRef;
use crate::replay::NOTICES_SITE;
use crate::transcript::{Sites, Transcript, Value};
/// The fixture of the compute slot's and the vertex slot's readers.
const EXAMPLES: Fixture = Fixture {
name: "examples/runtime_examples",
entry: "scale_and_offset",
};
/// The fixture of the readers through the address.
const POINTERS: Fixture = Fixture {
name: "ab_pointers",
entry: "ab_address",
};
/// The carried measurement, and where it is written down.
const CARRIED_FROM: &str = "an AMD Radeon Pro 5300M measurement under macOS 26.7.1, 8 rounds a \
reader (jobs 81602 and 81644), which found that a named Managed range \
reaches the GPU at the first commit whose encoders name the buffer, \
with its bytes as of that commit, and that a buffer no encoder names \
keeps the bytes its GPU copy last took";
/// Why record mode must not replace the carried table on the oracle.
const NEVER_RE_RECORD: &str = "the oracle keeps one copy of a Managed buffer (hasUnifiedMemory \
true), so its run answers what one copy holds, not which commit \
takes a range to a second copy";
/// The rounds the carried measurement stands on.
const CARRIED_RUNS: u32 = 8;
/// One case of the family: its name, its reader, and what the 5300M's reader read.
pub struct ManagedNaming {
name: &'static str,
way: Way,
metal: Content,
}
/// Every case of the family.
pub fn all() -> Vec<Box<dyn Case>> {
let case = |name, way, metal| -> Box<dyn Case> { Box::new(ManagedNaming { name, way, metal }) };
vec![
case(
"managed-named-compute-slot",
Way::ComputeSlot,
Content::Later,
),
case("managed-named-declared", Way::Declared, Content::Later),
case("managed-named-address-only", Way::Address, Content::Synced),
case("managed-named-vertex-slot", Way::VertexSlot, Content::Later),
case("managed-named-blit-source", Way::BlitSource, Content::Later),
]
}
/// The two fixtures' texts in both dialects.
fn shaders_of() -> Result<Vec<ShaderRef>, String> {
let mut shaders = Vec::new();
for fixture in [EXAMPLES, POINTERS] {
for extension in [RUNTIME_TEXT, METAL_TEXT] {
shaders.push(ShaderRef {
fixture: format!("{}{extension}", fixture.name),
entry: fixture.entry.to_owned(),
source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()),
});
}
}
Ok(shaders)
}
impl ManagedNaming {
/// The sites a run that read `content` emits.
fn transcript(&self, content: Content) -> Result<Transcript, String> {
let mut sites = Sites::new();
sites.push(crate::case::inputs_node(&self.inputs()?));
sites.leaf("examples", answered());
sites.leaf("pointers", answered());
sites.leaf("sequence", answered());
sites.value("reads", reads(Read::Content(content)));
sites.notices(NOTICES_SITE, &[] as &[&str]);
Ok(sites.finish())
}
}
/// The value the `reads` site holds.
fn reads(read: Read) -> Value {
Value::Lines(vec![read.word().to_owned()])
}
impl Case for ManagedNaming {
fn name(&self) -> &'static str {
self.name
}
fn metal_source(&self) -> MetalSource {
MetalSource::carried_only(CARRIED_FROM, NEVER_RE_RECORD)
.measured_on(crate::recording::AMD_RADEON_PRO_5300M)
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
shaders_of()
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let mut inputs = Vec::new();
for (fixture, short) in [(EXAMPLES, "examples"), (POINTERS, "pointers")] {
inputs.push(Input::bytes(
format!("air:{short}"),
fixture.text(RUNTIME_TEXT)?.as_bytes(),
));
inputs.push(Input::bytes(
format!("air-typed:{short}"),
fixture.text(METAL_TEXT)?.as_bytes(),
));
}
for content in Content::ALL {
inputs.push(Input::bytes(
format!("contents:{content:?}"),
&content.bytes(),
));
}
inputs.push(Input::bytes("reader", self.way.name().as_bytes()));
Ok(inputs)
}
fn carried_transcript(&self) -> Result<Option<(u32, Transcript)>, String> {
Ok(Some((CARRIED_RUNS, self.transcript(self.metal)?)))
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let load = |fixture: Fixture, at: &str| {
fixture.loaded().map_err(|why| Abort {
at: at.to_owned(),
failure: Failure::named("FixtureNotRead", why),
})
};
let (examples, pointers) = (load(EXAMPLES, "examples")?, load(POINTERS, "pointers")?);
let examples = made(sites, "examples", side.library(&examples.source()))?;
let pointers = made(sites, "pointers", side.library(&pointers.source()))?;
let libraries = Libraries { examples, pointers };
let read = made(sites, "sequence", side.managed_naming(self.way, libraries))?;
sites.value("reads", reads(self.way.read(&read)));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Five cases, one a reader, each named once, carrying the 5300M's answer: the bytes the
/// GPU's copy last took for the reader through the address alone, the bytes as of the
/// reader's commit for every other.
#[test]
fn every_reader_is_a_case_carrying_the_5300m_answer() {
let cases = all();
assert_eq!(cases.len(), 5);
let mut names: Vec<&str> = cases.iter().map(|case| case.name()).collect();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), 5);
for case in &cases {
let (runs, transcript) = (case.carried_transcript())
.expect("a carried answer")
.expect("carried");
assert_eq!(runs, CARRIED_RUNS);
assert!(case.allowances().is_empty());
let words = format!("{transcript:?}");
let address = case.name() == "managed-named-address-only";
let word = match address {
true => Content::Synced.word(),
false => Content::Later.word(),
};
assert!(words.contains(word), "{}: {words}", case.name());
}
}
}
@@ -47,12 +47,23 @@
//! outside the pixel is a value Metal asserts on and that reaches the sample grid. So they have no
//! oracle value here. [`crate::render::forbidden_positions`] refuses the two
//! fatal shapes from the input's own shape, so a case cannot build one by accident.
//!
//! **Carried from a discrete Mac** — the `EIGHT` table, the family's pass at 8 samples. The oracle
//! renders no 8 samples (an Apple M3 Max under macOS 27.0.1 answers `supportsTextureSampleCount:`
//! no for 8, job 82550), and a Mac with an AMD GPU does: an AMD Radeon Pro 5300M under macOS 26.7.1
//! ran the family's pass at 8 samples, plain and under Metal's API validation layer, which passed
//! it (job 82284, the probe `sample_positions_8.m` of the usage-edges probes). Each row carries the
//! resolved texel the probe read, so the bytes compare as a recorded row's do. Every row's coverage
//! avoids a resolve that halves a code: where the 5300M's average lies halfway between two codes it
//! rounds to the even one (4 of 8 samples: red 0, alpha 128), the M3 Max rounds a half up (2 of 4:
//! red 1), and that rounding is the device's own (`PrecisionNote::DeviceRoundedResolve`), so a row
//! there would compare two devices' rounding rather than where the samples are.
use crate::allowance::{Allowance, Justification, Loosening};
use crate::case::{answered, Abort, Case, Failure, Input, MetalSource, Side};
use crate::degradation::Degradation;
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::{ShaderRef, APPLE_M4};
use crate::recording::{ShaderRef, AMD_RADEON_PRO_5300M, APPLE_M4};
use crate::render::{
ColorState, PassColor, Plane, ReadAt, RenderPass, RenderPipelineSpec, RenderStep, RenderWork,
TargetSpec,
@@ -223,6 +234,71 @@ const FEWER: &[Shape] = &[
),
];
/// Eight positions at `(x, 0.5)`.
macro_rules! eight {
($x:expr) => {
&[
at($x, 0.5),
at($x, 0.5),
at($x, 0.5),
at($x, 0.5),
at($x, 0.5),
at($x, 0.5),
at($x, 0.5),
at($x, 0.5),
]
};
}
/// One row of the family at 8 samples, and the resolved texel an AMD Radeon Pro 5300M read.
struct Measured {
shape: Shape,
texel: [u8; TEXEL as usize],
}
/// The rows at 8 samples, carried from the 5300M (job 82284).
///
/// The device's own positions are Vulkan's standard 8 (each `x` an odd sixteenth, as the 5300M's
/// `getDefaultSamplePositions:count:` answers too), so an edge at 5/8 of the pixel covers five of
/// them: alpha 5/8 of 255 and red 5/8 of a code, each to the nearest code.
const EIGHT: &[Measured] = &[
Measured {
shape: Shape::new("sample-positions-8x-default", 8, &[], 0.25, 5),
texel: [1, 0, 0, 0x9f],
},
Measured {
shape: Shape::new("sample-positions-8x-custom-left", 8, eight!(0.25), 0.0, 8),
texel: [1, 0, 0, 0xff],
},
Measured {
shape: Shape::new(
"sample-positions-8x-custom-mixed",
8,
&[
at(0.25, 0.5),
at(0.75, 0.5),
at(0.75, 0.5),
at(0.75, 0.5),
at(0.75, 0.5),
at(0.75, 0.5),
at(0.75, 0.5),
at(0.75, 0.5),
],
0.0,
1,
),
texel: [0, 0, 0, 0x20],
},
];
/// Where the 8-sample rows' Metal answer was measured, and why record mode must not replace it.
const EIGHT_FROM: &str =
"an AMD Radeon Pro 5300M under macOS 26.7.1 (job 82284): the family's pass \
at 8 samples, plain and under Metal's API validation layer, one run each";
const EIGHT_NEVER_RE_RECORD: &str = "the oracle renders no 8 samples (an Apple M3 Max answers \
supportsTextureSampleCount: no for 8), so a record run there \
must not encode an 8-sample texture";
/// Where the carried rows' Metal answer was measured, and why record mode must not replace it.
const CARRIED_FROM: &str = "a Metal probe of custom sample positions on an Apple M4";
const NEVER_RE_RECORD: &str = "fewer custom sample positions than the pass's samples is a count \
@@ -535,26 +611,7 @@ impl Case for Fewer {
}
fn carried_transcript(&self) -> Result<Option<(u32, Transcript)>, String> {
let mut sites = Sites::new();
sites.push(crate::case::inputs_node(&self.inputs()?));
for call in SETUP_SITES {
sites.leaf(call, answered());
}
let mut calls = Node::branch("calls", Vec::new());
for (piece, call) in ["renderCommandEncoder", "copyFromTextureToBuffer"]
.into_iter()
.enumerate()
{
calls = calls.with(Node::leaf(
format!("{piece}-{call}"),
Observed::value(Value::ok(Value::Absent)),
));
}
sites.push(calls);
sites.leaf(
"status",
Observed::value(Value::ok(Value::unit_variant("Completed"))),
);
let mut sites = carried_sites(self.shape)?;
sites.leaf(
"coverage",
Observed::value(Value::Lines(vec![format!(
@@ -576,6 +633,83 @@ impl Case for Fewer {
}
}
/// The sites a carried row's run emits before its answer: the inputs, every set-up call answered,
/// both pieces of work answered and the command buffer completed.
fn carried_sites(shape: &Shape) -> Result<Sites, String> {
let mut sites = Sites::new();
sites.push(crate::case::inputs_node(&inputs(shape)?));
for call in SETUP_SITES {
sites.leaf(call, answered());
}
let mut calls = Node::branch("calls", Vec::new());
for (piece, call) in ["renderCommandEncoder", "copyFromTextureToBuffer"]
.into_iter()
.enumerate()
{
calls = calls.with(Node::leaf(
format!("{piece}-{call}"),
Observed::value(Value::ok(Value::Absent)),
));
}
sites.push(calls);
sites.leaf(
"status",
Observed::value(Value::ok(Value::unit_variant("Completed"))),
);
Ok(sites)
}
/// One row at 8 samples, whose Metal answer is carried from the 5300M: the resolved texel and the
/// coverage it comes to, as a recorded row holds them.
pub struct Eight {
row: &'static Measured,
}
impl Case for Eight {
fn name(&self) -> &'static str {
self.row.shape.name
}
fn metal_source(&self) -> MetalSource {
MetalSource::carried_only(EIGHT_FROM, EIGHT_NEVER_RE_RECORD)
.measured_on(AMD_RADEON_PRO_5300M)
}
fn allowances(&self) -> Vec<Allowance> {
allowances()
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
shaders()
}
fn inputs(&self) -> Result<Vec<Input>, String> {
inputs(&self.row.shape)
}
fn carried_transcript(&self) -> Result<Option<(u32, Transcript)>, String> {
let shape = &self.row.shape;
let mut sites = carried_sites(shape)?;
sites.leaf(
"coverage",
Observed::value(coverage(&self.row.texel, shape.samples)),
);
sites.leaf(
"resolved",
Observed::bytes(self.row.texel.to_vec(), layout()),
);
sites.notices(NOTICES_SITE, &[] as &[&str]);
Ok(Some((MEASURED_RUNS, sites.finish())))
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
Coverage {
shape: &self.row.shape,
}
.run(side, sites)
}
}
/// Every case of the family, in the order the report lists them.
pub fn all() -> Vec<Box<dyn Case>> {
let mut cases: Vec<Box<dyn Case>> = Vec::new();
@@ -585,6 +719,9 @@ pub fn all() -> Vec<Box<dyn Case>> {
for shape in FEWER {
cases.push(Box::new(Fewer { shape }));
}
for row in EIGHT {
cases.push(Box::new(Eight { row }));
}
cases
}
@@ -695,13 +832,56 @@ mod tests {
}
}
/// Every 8-sample row carries the 5300M's texel at the coverage its table states, alpha and red
/// each the covered fraction of its full code to the nearest code, never halfway; forbids record mode from
/// replacing it; and states the sites a run of the row emits, the resolved texel's included.
#[test]
fn every_eight_sample_row_carries_the_5300m_texel_at_its_coverage() {
for row in EIGHT {
let shape = &row.shape;
assert_eq!(shape.samples, 8, "{}", shape.name);
let nearest = |code: u64| {
let eighths = code * shape.covered;
assert_ne!(eighths % 8, 4, "{}: halfway between two codes", shape.name);
((code * shape.covered + 4) / 8) as u8
};
assert_eq!(
row.texel,
[nearest(1), 0, 0, nearest(255)],
"{}",
shape.name
);
let case = Eight { row };
assert!(case.metal_source().forbidden().is_some(), "{}", shape.name);
let (runs, transcript) = case
.carried_transcript()
.unwrap()
.unwrap_or_else(|| panic!("{}: no carried transcript", shape.name));
assert_eq!(runs, MEASURED_RUNS);
assert_eq!(
site(shape.name, &transcript, "coverage").observed.value,
Value::Lines(vec![format!("{} of 8 samples", shape.covered)])
);
assert_eq!(
site(shape.name, &transcript, "resolved").observed.value,
Value::Bytes(row.texel.to_vec())
);
for call in SETUP_SITES {
site(shape.name, &transcript, call);
}
site(shape.name, &transcript, "calls/1-copyFromTextureToBuffer");
site(shape.name, &transcript, "status");
}
}
/// Every row of the family states positions the Metal leg's guard takes, or none at all.
///
/// This is the separation made mechanical: a row whose count passes the pass's samples, or
/// whose coordinate leaves the pixel, cannot be added to either table without failing here.
#[test]
fn no_row_states_a_shape_the_metal_leg_may_not_encode() {
for shape in COVERAGE.iter().chain(FEWER) {
let eight = EIGHT.iter().map(|row| &row.shape);
for shape in COVERAGE.iter().chain(FEWER).chain(eight) {
assert!(
crate::render::forbidden_positions(shape.positions, shape.samples).is_none(),
"{}: the guard refuses its positions",
@@ -717,8 +897,11 @@ mod tests {
/// a near-equivalent. A case that loosened its coverage or its texel would fail here.
#[test]
fn every_case_is_tabled_and_loosens_its_notices_alone() {
let named: Vec<&str> = COVERAGE.iter().chain(FEWER).map(|row| row.name).collect();
assert_eq!(named.len(), COVERAGE.len() + FEWER.len());
let eight = EIGHT.iter().map(|row| &row.shape);
let named: Vec<&str> = (COVERAGE.iter().chain(FEWER).chain(eight))
.map(|row| row.name)
.collect();
assert_eq!(named.len(), COVERAGE.len() + FEWER.len() + EIGHT.len());
for case in all() {
assert!(
named.contains(&case.name()),
@@ -111,13 +111,23 @@
//! format cannot part them. Three distinct answers of the three colours under **both** modes, and
//! `ClampToZero` reads exactly what `ClampToBorderColor` reads for every one of the three.
//!
//! **`cubic`** — one row, a `Cubic` min and mag filter, which is the third value of
//! `MTLSamplerMinMagFilter` and no device's own. The coordinates are a quarter of a texel past
//! each texel's lower corner, where a sixteen-texel kernel's weights all differ rather than
//! collapsing onto the texel a symmetric kernel would read at a centre. Every one of the sixteen
//! samples compares with Metal bit for bit; the case's verdict is `announced` and not `exact`
//! because the runtime emulates the footprint and says its arithmetic is its own, which the case
//! declares and which loosens nothing.
//! **`cubic`** — one row, a `Cubic` min and mag filter: `MTLSamplerMinMagFilter`'s raw value 2,
//! which the SDK headers do not declare. The coordinates are a quarter of a texel past each
//! texel's lower corner, where a nearest filter reads the lane's own texel and a filter of a wider
//! footprint blends in its neighbours. Metal makes the state on every Mac measured, and what a
//! sample through it reads is the Mac's. The case's own inputs on three Macs (jobs m3-max-85003
//! and m3-max-85004), the runtime sampler's red channel at the sixteen lanes:
//!
//! | Mac | macOS | Red, lanes 0 to 15 |
//! |---|---|---|
//! | Apple M3 Max | 27.0.1 | 1, 1.75, 2.75, 3.75, 4, 4.75, 5.75, 6.75, 8, ..., 14.75: a filter of a wider footprint, the linear filter's values at these coordinates |
//! | Radeon Pro 5300M | 26.7.1 | 1 to 16, each lane's own texel: nearest |
//! | Intel UHD Graphics 630 | 26.7.1 | 1 to 16: nearest |
//!
//! The recording is the M3 Max's. The runtime filters such a state as nearest on every device,
//! the x86 Macs' answer (`docs/API.md`'s accepted difference `CUBIC_AS_NEAREST`), so each lane's
//! runtime red may also hold its own texel, the 5300M's and the 630's value. Lane 0's footprint
//! reads texel (0, 0) alone at the clamped edge on all three Macs, so it compares exactly.
//!
//! # What is not here, and why
//!
@@ -146,7 +156,7 @@
//! and `cubic` families sample at is inside its texture; the `r-address` and `border` families'
//! coordinates reach outside on purpose, which is what an address mode and a border are for.
use crate::allowance::Allowance;
use crate::allowance::{Allowance, Justification, Loosening};
use crate::case::{
call, made, Abort, Bindings, Case, Failure, Handle, Input, MetalSource, SamplerSpec, Side,
TextureRole, TextureSpec,
@@ -156,7 +166,9 @@ use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::replay::notice_allowance;
use crate::texture::{TextureRequest, Upload};
use crate::transcript::{ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites, Value};
use crate::transcript::{
ByteLayout, Digest, Element, FloatWidth, Gaps, Node, Observed, Region, Sites, Value,
};
use metal2vulkan::metal::{
CompareFunction, PixelFormat, SamplerAddressMode, SamplerBorderColor, SamplerMinMagFilter,
SamplerMipFilter, SamplerReductionMode, TextureType, TextureUsage,
@@ -292,6 +304,20 @@ fn centres() -> Vec<[f32; 2]> {
.collect()
}
/// The accepted difference the `cubic` family's allowances name, by its slug.
const CUBIC_AS_NEAREST: &str = "a-sampler-of-minfilter-or-magfilter-2-filters-as-nearest";
/// The lanes of the `cubic` family whose nearest texel is not the M3 Max's answer, each with that
/// texel's value: every lane but lane 0, whose footprint is texel (0, 0) alone (module docs).
fn cubic_as_nearest() -> Vec<(usize, f32)> {
(0..SIDE)
.flat_map(|y| (0..SIDE).map(move |x| (x, y)))
.enumerate()
.filter(|&(_, (x, y))| (x, y) != (0, 0))
.map(|(lane, (x, y))| (lane, level_texel(0, x, y)))
.collect()
}
/// The coordinates the `cubic` family samples at: a quarter of a texel past each texel's lower
/// corner, so the footprint is never centred on a texel.
///
@@ -565,7 +591,7 @@ enum Family {
/// Six rows: each `MTLSamplerBorderColor` on each of the two address modes that read a
/// border.
Border,
/// One row: a `Cubic` min and mag filter, the third value of `MTLSamplerMinMagFilter`.
/// One row: a `Cubic` min and mag filter, `MTLSamplerMinMagFilter`'s undeclared raw value 2.
Cubic,
}
@@ -853,17 +879,11 @@ impl Case for SamplerFiltering {
}
fn allowances(&self) -> Vec<Allowance> {
// Metal announces nothing, so a notice of ours is a difference at the notices site. One
// family here provokes one: a `Cubic` min and mag filter, which no device's own sampler
// has, so the runtime emulates Metal's bicubic footprint and announces that its arithmetic
// is its own (`bicubic-filter-arithmetic`).
// Metal announces nothing, so a notice of ours is a difference at the notices site. No
// family here declares one of its own but the border and compare rows' below, so a notice
// any other starts announcing reads as divergent at once.
//
// It is a **declaration and loosens nothing**: measured on the M3 Max, every one of the
// sixteen samples of `sampler-cubic-filter` compares with Metal bit for bit, and the
// notices site is the whole of the difference. The other families provoke no notice and
// declare none, so a notice any of them starts announcing reads as divergent at once.
//
// And every family samples through the runtime sampler at `[[sampler(0)]]`, which the
// Every family samples through the runtime sampler at `[[sampler(0)]]`, which the
// runtime's pipelines note as scaled (`crate::replay::pixel_sampler_scaling_notice` holds
// why). Measured through the rt side on lavapipe, the Radeon 780M and the RX 550: it fired
// for every row the side does not refuse (the mip, third-address-mode, reduction and
@@ -874,10 +894,19 @@ impl Case for SamplerFiltering {
if matches!(self.family, Family::Border) {
named.push(crate::replay::swizzled_border_notice());
}
// A `Cubic` filter reads as nearest (module docs): each lane's runtime red may hold the
// lane's own texel, the x86 Macs' answer, where it differs from the M3 Max's.
if matches!(self.family, Family::Cubic) {
named.push(notice_allowance(
Degradation::BicubicFilterArithmetic.code(),
));
for (lane, value) in cubic_as_nearest() {
named.push(Allowance::new(
format!("case/cubic/sampled/{}", lane * SLOT_LANE as usize + 16),
Loosening::AnyOf(vec![Value::Float {
bits: u64::from(value.to_bits()),
width: FloatWidth::Single,
}]),
Justification::accepted(CUBIC_AS_NEAREST),
));
}
}
// A `compare` row's comparing stage records that its texels hold no value outside
// [0, 1] (`restricted-depth-range`). Every texel of the family lies in [0, 1], so it moves
@@ -1239,6 +1268,26 @@ mod tests {
/// of each other by Metal's own behaviour, and this asserts it rather than leaving a reader to
/// read three rows as three compared answers. An implementation that applied a minimum here
/// would diverge from the recording, which is what the rows are for.
/// The M3 Max's recording of a `Cubic` filter reads the linear control's red at every lane,
/// and its own texel, the x86 Macs' nearest answer, exactly at the lanes the allowances leave
/// out: the allowances admit the nearest answer wherever the recording differs from it.
#[test]
fn the_cubic_allowances_are_the_lanes_nearest_moves() {
let Some(outcomes) = recorded("sampler-cubic-filter", "cubic") else {
return;
};
let allowed: Vec<usize> = cubic_as_nearest().iter().map(|&(lane, _)| lane).collect();
for bytes in outcomes {
for lane in 0..(SIDE * SIDE) as usize {
let (x, y) = (lane as u32 % SIDE, lane as u32 / SIDE);
let red = runtime_sample(&bytes, lane)[0];
assert_eq!(red, control_sample(&bytes, lane)[0], "lane {lane}");
let nearest = level_texel(0, x, y);
assert_eq!(red != nearest, allowed.contains(&lane), "lane {lane}");
}
}
}
#[test]
fn the_three_reductions_are_one_answer() {
let case = all()
@@ -0,0 +1,195 @@
//! `sparse-status-plain`: what `sparse_sample`, `sparse_gather` and `sparse_read` answer over a
//! texture that is not sparse: each one's colour, and its residency (`sparse_color::resident()`).
//!
//! The kernel is the owned fixture `a2_sparse_status`. Thread `i` of [`THREADS`] takes texel
//! `(i & 3, i >> 2)` of two 4 × 4 `RGBA32Float` textures: it samples the first at the texel's
//! centre through a constexpr nearest, clamp-to-edge sampler at level 0, gathers the first's red
//! channel there, and reads the second at the texel. It stores the three colours' words, then the
//! three residencies (1 for resident) and a tag word, `0xA2`.
//!
//! Metal's answer over a texture that is not sparse is not the same on every Mac. Our own probe of
//! this kernel, plain and under Metal's validation layer (which reported nothing), read every
//! residency as resident on the Apple M3 Max (macOS 27.0.1) and on the AMD Radeon Pro 5300M (macOS
//! 26.7.1), and as not resident on the Intel UHD Graphics 630 of the same MacBook (macOS 26.7.1),
//! with the same colours on all three. Both answers are Metal's. The runtime answers resident, the
//! M3 Max's and the 5300M's, so the recording, which is the M3 Max's, holds it to that answer, and
//! the colours compare on every venue.
//!
//! One compute pass of [`THREADS`] threads, no loop, and every coordinate inside the textures:
//! nothing here can fault a GPU.
use crate::case::{call, made, Abort, Bindings, Case, Failure, Input, MetalSource, Side};
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::texture::{TextureRequest, Upload};
use crate::transcript::{ByteLayout, Digest, Element, Gaps, Node, Observed, Region, Sites};
use metal2vulkan::metal::PixelFormat;
/// The fixture the kernel lives in, and the kernel.
const FIXTURE: &str = "a2_sparse_status";
/// The textures' width and height.
const SIDE: u32 = 4;
/// The threads: one a texel.
pub const THREADS: u32 = SIDE * SIDE;
/// The bytes a thread stores: four `uint4`s.
const STORED: u32 = 64;
/// The byte every output word holds before the dispatch.
const BLANK: u8 = 0xab;
/// The sampled texture's texel at `(x, y)`, and the read texture's: distinct within and between
/// them, and exact in `float`.
pub fn texel(read: bool, x: u32, y: u32) -> [f32; 4] {
let (x, y) = (x as f32, y as f32);
match read {
false => [x + 0.25, y + 0.5, (x + 4.0 * y) / 16.0, 1.0],
true => [x + 0.75, y + 0.25, (x + 4.0 * y) / 16.0 + 0.5, 0.5],
}
}
/// A texture's bytes, row by row.
fn texels(read: bool) -> Vec<u8> {
(0..SIDE)
.flat_map(|y| (0..SIDE).map(move |x| (x, y)))
.flat_map(|(x, y)| texel(read, x, y))
.flat_map(f32::to_le_bytes)
.collect()
}
/// The upload of `bytes` into level 0.
fn upload(bytes: &[u8]) -> [Upload<'_>; 1] {
[Upload::level_0([SIDE, SIDE], SIDE * 16, SIDE, bytes)]
}
/// A plain texture of `uploads`.
fn request<'a>(uploads: &'a [Upload<'a>]) -> TextureRequest<'a> {
TextureRequest::read_2d(PixelFormat::RGBA32Float.as_raw(), SIDE, SIDE).loaded(uploads)
}
/// The layout the stored words compare under: one row a thread.
fn stored_layout() -> ByteLayout {
let length = THREADS * STORED;
ByteLayout {
region: Region::Buffer {
offset: 0,
length: u64::from(length),
},
element: Element::U32,
row_offset: 0,
row_elements: STORED / 4,
row_pitch: STORED,
rows: THREADS,
image_pitch: length,
images: 1,
gaps: Gaps::Ignored,
}
}
/// The case.
pub struct SparseStatusPlain;
impl Case for SparseStatusPlain {
fn name(&self) -> &'static str {
"sparse-status-plain"
}
fn metal_source(&self) -> MetalSource {
MetalSource::Run
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let fixture = Fixture {
name: FIXTURE,
entry: FIXTURE,
};
let mut shaders = Vec::new();
for extension in [RUNTIME_TEXT, METAL_TEXT] {
shaders.push(ShaderRef {
fixture: format!("{FIXTURE}{extension}"),
entry: FIXTURE.to_owned(),
source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()),
});
}
Ok(shaders)
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let fixture = Fixture::new(FIXTURE);
let (sampled, read) = (texels(false), texels(true));
Ok(vec![
Input {
name: "air".to_owned(),
digest: Digest::sha256(fixture.text(RUNTIME_TEXT)?.as_bytes()),
},
Input {
name: "air-typed".to_owned(),
digest: Digest::sha256(fixture.text(METAL_TEXT)?.as_bytes()),
},
Input::bytes("texture:sampled", &request(&upload(&sampled)).words()),
Input::bytes("texture:read", &request(&upload(&read)).words()),
])
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let loaded = Fixture::new(FIXTURE).loaded().map_err(|why| Abort {
at: "library".to_owned(),
failure: Failure::named("FixtureNotRead", why),
})?;
let library = made(sites, "library", side.library(&loaded.source()))?;
let pipeline = made(sites, "pipeline", side.compute_pipeline(library, FIXTURE))?;
let (sampled, read) = (texels(false), texels(true));
let (sampled, read) = (upload(&sampled), upload(&read));
let sampled = made(sites, "texture/sampled", side.texture(&request(&sampled)))?;
let read = made(sites, "texture/read", side.texture(&request(&read)))?;
let blank = vec![BLANK; (THREADS * STORED) as usize];
let out = made(sites, "buffer/out", side.buffer(&blank))?;
let command_buffer = made(
sites,
"dispatch",
side.dispatch_threads(
pipeline,
&Bindings::new(&[sampled, read], &[out]),
&[],
[THREADS, 1, 1],
[THREADS, 1, 1],
),
)?;
call(sites, "status", side.wait(command_buffer), Clone::clone)?;
let stored = call(
sites,
"read-back",
side.read_buffer(out, 0, blank.len()),
|_| crate::transcript::Value::Absent,
)?;
sites.push(Node::leaf(
"stored",
Observed::bytes(stored, stored_layout()),
));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
/// Every texel of the two textures is distinct, so a sample, gather or read of the wrong texel
/// or the wrong texture shows as a value.
#[test]
fn every_texel_is_distinct() {
let mut seen = BTreeSet::new();
for read in [false, true] {
for y in 0..SIDE {
for x in 0..SIDE {
let bits = texel(read, x, y).map(f32::to_bits);
assert!(seen.insert(bits), "{read} ({x}, {y})");
}
}
}
assert_eq!(texels(false).len(), (SIDE * SIDE * 16) as usize);
}
}
@@ -0,0 +1,185 @@
//! `srgb-storage-fragment-writes`: what a fragment function's `access::write` stores into an 8-bit
//! sRGB texture, the fragment twin of [`srgb_storage_writes`](super::srgb_storage_writes).
//!
//! The promise is that case's: Metal writes `RGBA8Unorm_sRGB` and `BGRA8Unorm_sRGB` on every Metal
//! 3 device, and the Metal Shading Language specification (8.7.7) encodes the write from linear to
//! sRGB, alpha linear. `read_write` access is not promised for either format, so this case writes
//! only.
//!
//! The functions are the owned fixture `fpv_srgb_draw_storage`'s `fpv_srgb_fragment_write` and
//! `fpv_srgb_fragment_write_half`, drawn behind `fpv_srgb_cover`, one triangle over the whole of
//! a [`WIDTH`] by [`HEIGHT`] `RGBA8Unorm` attachment: each pixel's fragment writes buffer 0's
//! `float4` or `half4` of its pixel, element `y * WIDTH + x`, at its own texel of the texture at
//! fragment texture slot 0. The values, the formats, the texture and the layout its bytes are read
//! under are the kernel case's, so the two cases' stored bytes compare one to one: the case
//! records the texture's bytes by `getBytes:`, one code a channel.
//!
//! One pass a sweep, one fragment a texel, no loop and no sampling: nothing here can fault a GPU.
use super::srgb_storage_writes::{
request, stored_layout, values, width_bytes, FORMATS, HEIGHT, WIDTH,
};
use crate::case::{call, made, Abort, Case, Failure, Input, MetalSource, Side};
use crate::fixture::{Fixture, METAL_TEXT, RUNTIME_TEXT};
use crate::recording::ShaderRef;
use crate::render::{
ColorState, PassColor, RenderPass, RenderPipelineSpec, RenderStep, RenderWork, TargetSpec,
};
use crate::transcript::{Digest, Node, Observed, Sites, Value};
use metal2vulkan::metal::{PixelFormat, PrimitiveType};
/// The fixture the functions live in.
const FIXTURE: &str = "fpv_srgb_draw_storage";
/// The vertex function: one triangle over the whole viewport.
const COVER: &str = "fpv_srgb_cover";
/// The fragment functions the case draws: a `float4` write and a `half4` write.
const FRAGMENTS: [&str; 2] = ["fpv_srgb_fragment_write", "fpv_srgb_fragment_write_half"];
/// The attachment's format, which the fragments' returned colour lands in and nothing reads.
const ATTACHMENT: PixelFormat = PixelFormat::RGBA8Unorm;
/// The one colour attachment every pipeline carries.
const COLORS: [Option<ColorState>; 1] = [Some(ColorState::new(ATTACHMENT))];
/// The attachment: [`WIDTH`] by [`HEIGHT`], so a fragment is a texel of the written texture.
fn attachment() -> TargetSpec {
TargetSpec::read(ATTACHMENT, [WIDTH, HEIGHT])
}
/// The case.
pub struct SrgbStorageFragmentWrites;
impl Case for SrgbStorageFragmentWrites {
fn name(&self) -> &'static str {
"srgb-storage-fragment-writes"
}
fn metal_source(&self) -> MetalSource {
MetalSource::Run
}
fn shaders(&self) -> Result<Vec<ShaderRef>, String> {
let fixture = Fixture::new(FIXTURE);
let mut shaders = Vec::new();
for fragment in FRAGMENTS {
for extension in [RUNTIME_TEXT, METAL_TEXT] {
shaders.push(ShaderRef {
fixture: format!("{FIXTURE}{extension}"),
entry: format!("{COVER}+{fragment}"),
source_sha256: crate::sha256_hex(fixture.text(extension)?.as_bytes()),
});
}
}
Ok(shaders)
}
fn inputs(&self) -> Result<Vec<Input>, String> {
let fixture = Fixture::new(FIXTURE);
let mut inputs = vec![
Input {
name: "air".to_owned(),
digest: Digest::sha256(fixture.text(RUNTIME_TEXT)?.as_bytes()),
},
Input {
name: "air-typed".to_owned(),
digest: Digest::sha256(fixture.text(METAL_TEXT)?.as_bytes()),
},
Input::bytes("buffer:1", &width_bytes()),
Input::bytes("attachment", &attachment().words()),
];
for fragment in FRAGMENTS {
let pipeline = RenderPipelineSpec::new(COVER, fragment, &COLORS);
inputs.push(Input::bytes(
format!("{fragment}/pipeline"),
&pipeline.words(),
));
inputs.push(Input::bytes(
format!("{fragment}/buffer:0"),
&values(fragment),
));
}
for format in FORMATS {
inputs.push(Input::bytes(format.name(), &request(format).words()));
}
Ok(inputs)
}
fn run(&self, side: &mut dyn Side, sites: &mut Sites) -> Result<(), Abort> {
let loaded = Fixture::new(FIXTURE).loaded().map_err(|why| Abort {
at: "library".to_owned(),
failure: Failure::named("FixtureNotRead", why),
})?;
let library = made(sites, "library", side.library(&loaded.source()))?;
let shape = made(sites, "buffer/width", side.buffer(&width_bytes()))?;
for fragment in FRAGMENTS {
let pipeline = made(
sites,
&format!("{fragment}/pipeline"),
side.render_pipeline(library, &RenderPipelineSpec::new(COVER, fragment, &COLORS)),
)?;
let values = made(
sites,
&format!("{fragment}/buffer/0"),
side.buffer(&values(fragment)),
)?;
for format in FORMATS {
let at = |site: &str| format!("{}/{fragment}/{site}", format.name());
let texture = made(sites, &at("texture"), side.texture(&request(format)))?;
let into = made(sites, &at("attachment"), side.target(&attachment()))?;
let steps = vec![
RenderStep::Pipeline(pipeline),
RenderStep::FragmentTexture { texture, index: 0 },
RenderStep::FragmentBuffer {
buffer: values,
offset: 0,
index: 0,
},
RenderStep::FragmentBuffer {
buffer: shape,
offset: 0,
index: 1,
},
RenderStep::Draw {
primitive: PrimitiveType::Triangle,
first: 0,
count: 3,
instances: 1,
},
];
let pass = RenderWork::Pass(
RenderPass::clearing(vec![PassColor::cleared(into, [0.0; 4])]).drawing(steps),
);
let outcome = call(sites, &at("draw"), side.render(&[pass]), |outcome| {
outcome.status.clone()
})?;
let refused = outcome.refused.first().and_then(Option::as_ref);
sites.push(Node::leaf(
at("pass"),
Observed::value(match refused {
Some(failure) => failure.recorded(),
None => Value::ok(Value::Absent),
}),
));
if let Some(failure) = refused {
return Err(Abort {
at: at("pass"),
failure: failure.clone(),
});
}
let stored = call(
sites,
&at("texels"),
side.read_texture(texture, [WIDTH, HEIGHT], WIDTH * 4),
|_| Value::Absent,
)?;
sites.push(Node::leaf(
at("stored"),
Observed::bytes(stored, stored_layout()),
));
}
}
Ok(())
}
}
@@ -35,8 +35,9 @@ const FIXTURE: &str = "fpv_srgb_storage";
/// The kernels the case runs: a `float4` write and a `half4` write.
const KERNELS: [&str; 2] = ["fpv_srgb_write", "fpv_srgb_write_half"];
/// The formats the case writes.
const FORMATS: [PixelFormat; 2] = [PixelFormat::RGBA8UnormSRGB, PixelFormat::BGRA8UnormSRGB];
/// The formats the case, and its fragment twin, write.
pub(crate) const FORMATS: [PixelFormat; 2] =
[PixelFormat::RGBA8UnormSRGB, PixelFormat::BGRA8UnormSRGB];
/// The texture's width, which buffer 1 holds.
pub const WIDTH: u32 = 256;
@@ -86,9 +87,11 @@ pub fn texels() -> Vec<[f32; 4]> {
out
}
/// Buffer 0's bytes for `kernel`: each texel's `float4`, or its `half4`.
fn values(kernel: &str) -> Vec<u8> {
let half = kernel.ends_with("_half");
/// Buffer 0's bytes for `function`, a kernel here or a fragment function of the fragment twin
/// (`srgb-storage-fragment-writes`): each texel's `float4`, or its `half4` where the name ends in
/// `_half`.
pub(crate) fn values(function: &str) -> Vec<u8> {
let half = function.ends_with("_half");
let mut bytes = Vec::new();
for value in texels().into_iter().flatten() {
match half {
@@ -100,17 +103,17 @@ fn values(kernel: &str) -> Vec<u8> {
}
/// Buffer 1's bytes: the row's width, as the kernels' `constant uint &width`.
fn width_bytes() -> Vec<u8> {
pub(crate) fn width_bytes() -> Vec<u8> {
WIDTH.to_le_bytes().to_vec()
}
/// The texture a sweep writes: shared storage, written by shaders alone.
fn request(format: PixelFormat) -> TextureRequest<'static> {
pub(crate) fn request(format: PixelFormat) -> TextureRequest<'static> {
TextureRequest::read_2d(format.as_raw(), WIDTH, HEIGHT).used(TextureUsage::SHADER_WRITE)
}
/// The layout the stored bytes are read under: one row a texel row, one code a channel.
fn stored_layout() -> ByteLayout {
pub(crate) fn stored_layout() -> ByteLayout {
let pitch = WIDTH * 4;
ByteLayout {
region: Region::Texture {
@@ -191,7 +191,8 @@ impl Row {
/// The family is exhaustive in the directions that matter and small in every other: a step on x
/// and on y, a step rate of 1, 2 and 3, an origin inside and past the buffer's elements, a size of
/// 0, a size of 1, a size below the grid and a size equal to it, both axes of a 2D region, the
/// indexed steps, a constant step, a region set indirectly and a region set twice.
/// indexed steps at a step rate of 1, 2 and 3, a constant step, a region set indirectly and a
/// region set twice.
const ROWS: &[Row] = &[
Row {
name: "x_r8_g8",
@@ -454,6 +455,33 @@ const ROWS: &[Row] = &[
group: [4, 1],
how: How::Direct,
},
Row {
name: "xi_rate2_o1_r3_g8",
layouts: &[(StepFunction::ThreadPositionInGridXIndexed, 2)],
origin: [1, 0, 0],
size: [3, 1, 1],
grid: [8, 1],
group: [8, 1],
how: How::Direct,
},
Row {
name: "xi_rate3_o2_r4_g12",
layouts: &[(StepFunction::ThreadPositionInGridXIndexed, 3)],
origin: [2, 0, 0],
size: [4, 1, 1],
grid: [12, 1],
group: [12, 1],
how: How::Direct,
},
Row {
name: "yi_rate2_o1_r2_g2x8",
layouts: &[(StepFunction::ThreadPositionInGridYIndexed, 2)],
origin: [0, 1, 0],
size: [1, 2, 1],
grid: [2, 8],
group: [2, 8],
how: How::Direct,
},
];
/// Source buffer `index`'s bytes: buffer 1 holds `0x10 + e`, buffer 2 `0x200 + e`, and buffer 3
@@ -212,6 +212,10 @@ pub enum ComputeStep {
offset: u64,
threads: [u32; 3],
},
/// `dispatchThreads:threadsPerThreadgroup:`: a grid of `grid` threads, which need not be a
/// whole number of threadgroups, so the last threadgroup along an axis may run only the
/// threads left.
DispatchThreads { grid: [u32; 3], threads: [u32; 3] },
}
impl ComputeStep {
@@ -247,6 +251,7 @@ impl ComputeStep {
ComputeStep::DispatchThreadgroupsIndirect { .. } => {
"dispatchThreadgroupsWithIndirectBuffer"
}
ComputeStep::DispatchThreads { .. } => "dispatchThreads",
}
}
@@ -382,6 +387,11 @@ impl ComputeStep {
words.extend(axis.to_le_bytes());
}
}
ComputeStep::DispatchThreads { grid, threads } => {
for axis in grid.iter().chain(threads) {
words.extend(axis.to_le_bytes());
}
}
}
words
}
@@ -392,6 +402,7 @@ impl ComputeStep {
self,
ComputeStep::DispatchThreadgroups { .. }
| ComputeStep::DispatchThreadgroupsIndirect { .. }
| ComputeStep::DispatchThreads { .. }
)
}
}
@@ -627,7 +638,11 @@ mod tests {
offset: 0,
threads: [8, 1, 1],
},
ComputeStep::DispatchThreadgroupsIndirect { .. } => return None,
ComputeStep::DispatchThreadgroupsIndirect { .. } => ComputeStep::DispatchThreads {
grid: [9, 1, 1],
threads: [8, 1, 1],
},
ComputeStep::DispatchThreads { .. } => return None,
})
}
@@ -717,7 +732,7 @@ mod tests {
);
}
/// Both dispatch steps say they dispatch and no other step does, so a guard that bounds a
/// The three dispatch steps say they dispatch and no other step does, so a guard that bounds a
/// case's grids reads every dispatch and nothing else.
#[test]
fn only_the_dispatch_steps_dispatch() {
@@ -730,7 +745,8 @@ mod tests {
dispatching,
[
"dispatchThreadgroups",
"dispatchThreadgroupsWithIndirectBuffer"
"dispatchThreadgroupsWithIndirectBuffer",
"dispatchThreads"
]
);
}
+177 -215
View File
@@ -1,5 +1,6 @@
//! The degrade-notice codes the suite's cases name: `metal2vulkan-degrade-<kind>`, one per kind,
//! and the kind each of the runtime's precision notes announces as.
//! each its precision note's code as the translator states it (`PrecisionNote::code`), and the
//! kind each of the runtime's precision notes announces as.
//!
//! A case loosens a field by naming a code ([`crate::allowance`]), and the comparison holds it
//! there only where the run announced that code. The runtime's side announces the codes of
@@ -11,170 +12,168 @@ use metal2vulkan::pipeline::PrecisionNote;
/// A kind of degrade notice, by its code ([`Degradation::code`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Degradation {
/// `metal2vulkan-degrade-device-rounded-resolve`.
/// [`PrecisionNote::DeviceRoundedResolve`].
DeviceRoundedResolve,
/// `metal2vulkan-degrade-device-reconvergence`.
/// [`PrecisionNote::DeviceReconvergence`].
DeviceReconvergence,
/// `metal2vulkan-degrade-simdgroup-access-order`.
/// [`PrecisionNote::SimdgroupAccessOrder`].
SimdgroupAccessOrder,
/// `metal2vulkan-degrade-device-filtered-mipmaps`.
/// [`PrecisionNote::DeviceFilteredMipmaps`].
DeviceFilteredMipmaps,
/// `metal2vulkan-degrade-capped-lod-bias`.
/// [`PrecisionNote::CappedLodBias`].
CappedLodBias,
/// `metal2vulkan-degrade-snorm-minimum-kept`.
/// [`PrecisionNote::SnormMinimumKept`].
SnormMinimumKept,
/// `metal2vulkan-degrade-shared-exponent-kept`.
/// [`PrecisionNote::SharedExponentKept`].
SharedExponentKept,
/// `metal2vulkan-degrade-compressed-texel-decode`.
/// [`PrecisionNote::CompressedTexelDecode`].
CompressedTexelDecode,
/// `metal2vulkan-degrade-depth-denormals`.
/// [`PrecisionNote::DepthDenormals`].
DepthDenormals,
/// `metal2vulkan-degrade-f16-fma-double-rounding`.
/// [`PrecisionNote::F16FmaDoubleRounding`].
F16FmaDoubleRounding,
/// `metal2vulkan-degrade-f16-int-conv-double-rounding`.
/// [`PrecisionNote::F16IntConvDoubleRounding`].
F16IntConvDoubleRounding,
/// `metal2vulkan-degrade-grad-from-bias`.
/// [`PrecisionNote::GradFromBias`].
GradFromBias,
/// `metal2vulkan-degrade-device-transcendentals`.
/// [`PrecisionNote::DeviceTranscendentals`].
DeviceTranscendentals,
/// `metal2vulkan-degrade-reduction-order`.
/// [`PrecisionNote::ReductionOrder`].
ReductionOrder,
/// `metal2vulkan-degrade-device-denormals`.
/// [`PrecisionNote::DeviceDenormals`].
DeviceDenormals,
/// `metal2vulkan-degrade-pixel-sampler-scaling`.
/// [`PrecisionNote::PixelSamplerScaling`].
PixelSamplerScaling,
/// `metal2vulkan-degrade-device-arithmetic`.
/// [`PrecisionNote::DeviceArithmetic`].
DeviceArithmetic,
/// `metal2vulkan-degrade-device-signed-zero-inf-nan`.
/// [`PrecisionNote::DeviceSignedZeroInfNan`].
DeviceSignedZeroInfNan,
/// `metal2vulkan-degrade-device-ray-intersection`.
/// [`PrecisionNote::DeviceRayIntersection`].
DeviceRayIntersection,
/// `metal2vulkan-degrade-fast-math-rewrites`.
/// [`PrecisionNote::FastMathRewrites`].
FastMathRewrites,
/// `metal2vulkan-degrade-tessellation-winding`.
/// [`PrecisionNote::TessellationWinding`].
TessellationWinding,
/// `metal2vulkan-degrade-tessellation-fractional-spacing`.
/// [`PrecisionNote::TessellationFractionalSpacing`].
TessellationFractionalSpacing,
/// `metal2vulkan-degrade-tessellation-factor-edge-cases`.
/// [`PrecisionNote::TessellationFactorEdgeCases`].
TessellationFactorEdgeCases,
/// `metal2vulkan-degrade-tessellation-factor-scale`.
/// [`PrecisionNote::TessellationFactorScale`].
TessellationFactorScale,
/// `metal2vulkan-degrade-tessellation-factor-instance`.
/// [`PrecisionNote::TessellationFactorInstance`].
TessellationFactorInstance,
/// `metal2vulkan-degrade-fp8-value`.
/// [`PrecisionNote::Fp8Value`].
Fp8Value,
/// `metal2vulkan-degrade-multisample-position`.
/// [`PrecisionNote::MultisamplePosition`].
MultisamplePosition,
/// `metal2vulkan-degrade-bicubic-filter-arithmetic`.
/// [`PrecisionNote::BicubicFilterArithmetic`].
BicubicFilterArithmetic,
/// `metal2vulkan-degrade-sparse-residency`.
SparseResidency,
/// `metal2vulkan-degrade-device-nan-encoding`.
/// [`PrecisionNote::DeviceNanEncoding`].
DeviceNanEncoding,
/// `metal2vulkan-degrade-restricted-depth-range`.
/// [`PrecisionNote::RestrictedDepthRange`].
RestrictedDepthRange,
/// `metal2vulkan-degrade-cube-gradient-footprint`.
/// [`PrecisionNote::CubeGradientFootprint`].
CubeGradientFootprint,
/// `metal2vulkan-degrade-half-texel-conversion`.
/// [`PrecisionNote::HalfTexelConversion`].
HalfTexelConversion,
/// `metal2vulkan-degrade-srgb-texel-decode`.
/// [`PrecisionNote::SrgbTexelDecode`].
SrgbTexelDecode,
/// `metal2vulkan-degrade-function-storage-assumed`.
/// [`PrecisionNote::FunctionStorageAssumed`].
FunctionStorageAssumed,
/// `metal2vulkan-degrade-quads-counted-before-discard`.
/// [`PrecisionNote::QuadsCountedBeforeDiscard`].
QuadsCountedBeforeDiscard,
/// `metal2vulkan-degrade-view-base-texel-offset`.
/// [`PrecisionNote::ViewBaseTexelOffset`].
ViewBaseTexelOffset,
/// `metal2vulkan-degrade-device-color-conversion`.
/// [`PrecisionNote::DeviceColorConversion`].
DeviceColorConversion,
/// `metal2vulkan-degrade-device-interpolation`.
/// [`PrecisionNote::DeviceInterpolation`].
DeviceInterpolation,
/// `metal2vulkan-degrade-device-interpolation-offset`.
/// [`PrecisionNote::DeviceInterpolationOffset`].
DeviceInterpolationOffset,
/// `metal2vulkan-degrade-extrapolated-interpolation`.
/// [`PrecisionNote::ExtrapolatedInterpolation`].
ExtrapolatedInterpolation,
/// `metal2vulkan-degrade-quads-split-by-clipping`.
/// [`PrecisionNote::QuadsSplitByClipping`].
QuadsSplitByClipping,
/// `metal2vulkan-degrade-fragment-simdgroup-grouping`.
/// [`PrecisionNote::FragmentSimdgroupGrouping`].
FragmentSimdgroupGrouping,
/// `metal2vulkan-degrade-blended-write-rounding`.
/// [`PrecisionNote::BlendedWriteRounding`].
BlendedWriteRounding,
/// `metal2vulkan-degrade-rotated-blend-rounding`.
/// [`PrecisionNote::RotatedBlendRounding`].
RotatedBlendRounding,
/// `metal2vulkan-degrade-linked-sampler-numbering`.
/// [`PrecisionNote::LinkedSamplerNumbering`].
LinkedSamplerNumbering,
/// `metal2vulkan-degrade-argument-pixel-sampler-scaling`.
/// [`PrecisionNote::ArgumentPixelSamplerScaling`].
ArgumentPixelSamplerScaling,
/// `metal2vulkan-degrade-half-output-precision`.
/// [`PrecisionNote::HalfOutputPrecision`].
HalfOutputPrecision,
/// `metal2vulkan-degrade-anisotropic-filter`.
AnisotropicFilter,
/// `metal2vulkan-degrade-device-anisotropic-filter`.
DeviceAnisotropicFilter,
/// `metal2vulkan-degrade-device-point-size`.
/// [`PrecisionNote::DevicePointSize`].
DevicePointSize,
/// `metal2vulkan-degrade-clipped-coverage-split`.
/// [`PrecisionNote::ClippedCoverageSplit`].
ClippedCoverageSplit,
/// `metal2vulkan-degrade-looped-sample-outputs`.
/// [`PrecisionNote::LoopedSampleOutputs`].
LoopedSampleOutputs,
/// `metal2vulkan-degrade-half-output-fast-math-blend`.
/// [`PrecisionNote::HalfOutputFastMathBlend`].
HalfOutputFastMathBlend,
/// `metal2vulkan-degrade-device-sampling`.
/// [`PrecisionNote::DeviceSampling`].
DeviceSampling,
/// `metal2vulkan-degrade-native-transcendentals`.
/// [`PrecisionNote::NativeTranscendentals`].
NativeTranscendentals,
/// `metal2vulkan-degrade-native-division`.
/// [`PrecisionNote::NativeDivision`].
NativeDivision,
/// `metal2vulkan-degrade-native-fma`.
/// [`PrecisionNote::NativeFma`].
NativeFma,
/// `metal2vulkan-degrade-device-texel-conversion`.
/// [`PrecisionNote::DeviceTexelConversion`].
DeviceTexelConversion,
/// `metal2vulkan-degrade-device-vertex-conversion`.
/// [`PrecisionNote::DeviceVertexConversion`].
DeviceVertexConversion,
/// `metal2vulkan-degrade-native-half-conversion`.
/// [`PrecisionNote::NativeHalfConversion`].
NativeHalfConversion,
/// `metal2vulkan-degrade-native-half-quantize`.
/// [`PrecisionNote::NativeHalfQuantize`].
NativeHalfQuantize,
/// `metal2vulkan-degrade-native-nan-encoding`.
/// [`PrecisionNote::NativeNanEncoding`].
NativeNanEncoding,
/// `metal2vulkan-degrade-native-min-max`.
/// [`PrecisionNote::NativeMinMax`].
NativeMinMax,
/// `metal2vulkan-degrade-native-dot`.
/// [`PrecisionNote::NativeDot`].
NativeDot,
/// `metal2vulkan-degrade-native-mix`.
/// [`PrecisionNote::NativeMix`].
NativeMix,
/// `metal2vulkan-degrade-device-pack-conversion`.
/// [`PrecisionNote::DevicePackConversion`].
DevicePackConversion,
/// `metal2vulkan-degrade-tessellation-triangle-order`.
/// [`PrecisionNote::TessellationTriangleOrder`].
TessellationTriangleOrder,
/// `metal2vulkan-degrade-unmeasured-group-speculation`.
/// [`PrecisionNote::UnmeasuredGroupSpeculation`].
UnmeasuredGroupSpeculation,
/// `metal2vulkan-degrade-device-sample-level`.
/// [`PrecisionNote::DeviceSampleLevel`].
DeviceSampleLevel,
/// `metal2vulkan-degrade-coverage-reads-rounded-alpha`.
/// [`PrecisionNote::CoverageReadsRoundedAlpha`].
CoverageReadsRoundedAlpha,
/// `metal2vulkan-degrade-device-alpha-coverage`.
/// [`PrecisionNote::DeviceAlphaCoverage`].
DeviceAlphaCoverage,
/// `metal2vulkan-degrade-unordered-fetch-within-draw`.
/// [`PrecisionNote::UnorderedFetchWithinDraw`].
UnorderedFetchWithinDraw,
/// `metal2vulkan-degrade-native-logic-operation`.
/// [`PrecisionNote::NativeLogicOperation`].
NativeLogicOperation,
/// `metal2vulkan-degrade-device-depth-bias`.
/// [`PrecisionNote::DeviceDepthBias`].
DeviceDepthBias,
/// `metal2vulkan-degrade-swizzled-opaque-black-border`.
/// [`PrecisionNote::SwizzledOpaqueBlackBorder`].
SwizzledOpaqueBlackBorder,
/// `metal2vulkan-degrade-device-line-rasterization`.
/// [`PrecisionNote::DeviceLineRasterization`].
DeviceLineRasterization,
/// `metal2vulkan-degrade-device-fragment-runs`.
/// [`PrecisionNote::DeviceFragmentRuns`].
DeviceFragmentRuns,
/// `metal2vulkan-degrade-device-occlusion-count`.
/// [`PrecisionNote::DeviceOcclusionCount`].
DeviceOcclusionCount,
/// `metal2vulkan-degrade-vertex-simdgroup-grouping`.
/// [`PrecisionNote::VertexSimdgroupGrouping`].
VertexSimdgroupGrouping,
/// `metal2vulkan-degrade-restricted-depth-upload`.
/// [`PrecisionNote::RestrictedDepthUpload`].
RestrictedDepthUpload,
/// `metal2vulkan-degrade-stencil-output-overlap`.
/// [`PrecisionNote::StencilOutputOverlap`].
StencilOutputOverlap,
/// [`PrecisionNote::DeviceHalfDenormals`].
DeviceHalfDenormals,
/// [`PrecisionNote::RoundedSampleDepthCopy`].
RoundedSampleDepthCopy,
}
impl Degradation {
@@ -208,7 +207,6 @@ impl Degradation {
Degradation::Fp8Value,
Degradation::MultisamplePosition,
Degradation::BicubicFilterArithmetic,
Degradation::SparseResidency,
Degradation::DeviceNanEncoding,
Degradation::RestrictedDepthRange,
Degradation::CubeGradientFootprint,
@@ -228,8 +226,6 @@ impl Degradation {
Degradation::LinkedSamplerNumbering,
Degradation::ArgumentPixelSamplerScaling,
Degradation::HalfOutputPrecision,
Degradation::AnisotropicFilter,
Degradation::DeviceAnisotropicFilter,
Degradation::DevicePointSize,
Degradation::ClippedCoverageSplit,
Degradation::LoopedSampleOutputs,
@@ -262,135 +258,102 @@ impl Degradation {
Degradation::VertexSimdgroupGrouping,
Degradation::RestrictedDepthUpload,
Degradation::StencilOutputOverlap,
Degradation::DeviceHalfDenormals,
Degradation::RoundedSampleDepthCopy,
];
/// The kind's code, `metal2vulkan-degrade-<kind>`.
/// The kind's code, `metal2vulkan-degrade-<kind>`: its precision note's, which the translator
/// states ([`PrecisionNote::code`]).
pub const fn code(self) -> &'static str {
self.note().code()
}
/// The precision note the kind is: [`Degradation::from_precision_note`] taken back.
pub const fn note(self) -> PrecisionNote {
match self {
Degradation::DeviceRoundedResolve => "metal2vulkan-degrade-device-rounded-resolve",
Degradation::DeviceReconvergence => "metal2vulkan-degrade-device-reconvergence",
Degradation::SimdgroupAccessOrder => "metal2vulkan-degrade-simdgroup-access-order",
Degradation::DeviceFilteredMipmaps => "metal2vulkan-degrade-device-filtered-mipmaps",
Degradation::CappedLodBias => "metal2vulkan-degrade-capped-lod-bias",
Degradation::SnormMinimumKept => "metal2vulkan-degrade-snorm-minimum-kept",
Degradation::SharedExponentKept => "metal2vulkan-degrade-shared-exponent-kept",
Degradation::CompressedTexelDecode => "metal2vulkan-degrade-compressed-texel-decode",
Degradation::DepthDenormals => "metal2vulkan-degrade-depth-denormals",
Degradation::F16FmaDoubleRounding => "metal2vulkan-degrade-f16-fma-double-rounding",
Degradation::F16IntConvDoubleRounding => {
"metal2vulkan-degrade-f16-int-conv-double-rounding"
}
Degradation::GradFromBias => "metal2vulkan-degrade-grad-from-bias",
Degradation::DeviceTranscendentals => "metal2vulkan-degrade-device-transcendentals",
Degradation::ReductionOrder => "metal2vulkan-degrade-reduction-order",
Degradation::DeviceDenormals => "metal2vulkan-degrade-device-denormals",
Degradation::PixelSamplerScaling => "metal2vulkan-degrade-pixel-sampler-scaling",
Degradation::DeviceArithmetic => "metal2vulkan-degrade-device-arithmetic",
Degradation::DeviceSignedZeroInfNan => {
"metal2vulkan-degrade-device-signed-zero-inf-nan"
}
Degradation::DeviceRayIntersection => "metal2vulkan-degrade-device-ray-intersection",
Degradation::FastMathRewrites => "metal2vulkan-degrade-fast-math-rewrites",
Degradation::TessellationWinding => "metal2vulkan-degrade-tessellation-winding",
Degradation::DeviceRoundedResolve => PrecisionNote::DeviceRoundedResolve,
Degradation::DeviceReconvergence => PrecisionNote::DeviceReconvergence,
Degradation::SimdgroupAccessOrder => PrecisionNote::SimdgroupAccessOrder,
Degradation::DeviceFilteredMipmaps => PrecisionNote::DeviceFilteredMipmaps,
Degradation::CappedLodBias => PrecisionNote::CappedLodBias,
Degradation::SnormMinimumKept => PrecisionNote::SnormMinimumKept,
Degradation::SharedExponentKept => PrecisionNote::SharedExponentKept,
Degradation::CompressedTexelDecode => PrecisionNote::CompressedTexelDecode,
Degradation::DepthDenormals => PrecisionNote::DepthDenormals,
Degradation::F16FmaDoubleRounding => PrecisionNote::F16FmaDoubleRounding,
Degradation::F16IntConvDoubleRounding => PrecisionNote::F16IntConvDoubleRounding,
Degradation::GradFromBias => PrecisionNote::GradFromBias,
Degradation::DeviceTranscendentals => PrecisionNote::DeviceTranscendentals,
Degradation::ReductionOrder => PrecisionNote::ReductionOrder,
Degradation::DeviceDenormals => PrecisionNote::DeviceDenormals,
Degradation::PixelSamplerScaling => PrecisionNote::PixelSamplerScaling,
Degradation::DeviceArithmetic => PrecisionNote::DeviceArithmetic,
Degradation::DeviceSignedZeroInfNan => PrecisionNote::DeviceSignedZeroInfNan,
Degradation::DeviceRayIntersection => PrecisionNote::DeviceRayIntersection,
Degradation::FastMathRewrites => PrecisionNote::FastMathRewrites,
Degradation::TessellationWinding => PrecisionNote::TessellationWinding,
Degradation::TessellationFractionalSpacing => {
"metal2vulkan-degrade-tessellation-fractional-spacing"
PrecisionNote::TessellationFractionalSpacing
}
Degradation::TessellationFactorEdgeCases => {
"metal2vulkan-degrade-tessellation-factor-edge-cases"
}
Degradation::TessellationFactorScale => {
"metal2vulkan-degrade-tessellation-factor-scale"
}
Degradation::TessellationFactorInstance => {
"metal2vulkan-degrade-tessellation-factor-instance"
}
Degradation::Fp8Value => "metal2vulkan-degrade-fp8-value",
Degradation::MultisamplePosition => "metal2vulkan-degrade-multisample-position",
Degradation::BicubicFilterArithmetic => {
"metal2vulkan-degrade-bicubic-filter-arithmetic"
}
Degradation::SparseResidency => "metal2vulkan-degrade-sparse-residency",
Degradation::DeviceNanEncoding => "metal2vulkan-degrade-device-nan-encoding",
Degradation::RestrictedDepthRange => "metal2vulkan-degrade-restricted-depth-range",
Degradation::CubeGradientFootprint => "metal2vulkan-degrade-cube-gradient-footprint",
Degradation::HalfTexelConversion => "metal2vulkan-degrade-half-texel-conversion",
Degradation::SrgbTexelDecode => "metal2vulkan-degrade-srgb-texel-decode",
Degradation::FunctionStorageAssumed => "metal2vulkan-degrade-function-storage-assumed",
Degradation::QuadsCountedBeforeDiscard => {
"metal2vulkan-degrade-quads-counted-before-discard"
}
Degradation::ViewBaseTexelOffset => "metal2vulkan-degrade-view-base-texel-offset",
Degradation::DeviceColorConversion => "metal2vulkan-degrade-device-color-conversion",
Degradation::DeviceInterpolation => "metal2vulkan-degrade-device-interpolation",
Degradation::DeviceInterpolationOffset => {
"metal2vulkan-degrade-device-interpolation-offset"
}
Degradation::ExtrapolatedInterpolation => {
"metal2vulkan-degrade-extrapolated-interpolation"
}
Degradation::QuadsSplitByClipping => "metal2vulkan-degrade-quads-split-by-clipping",
Degradation::FragmentSimdgroupGrouping => {
"metal2vulkan-degrade-fragment-simdgroup-grouping"
}
Degradation::BlendedWriteRounding => "metal2vulkan-degrade-blended-write-rounding",
Degradation::RotatedBlendRounding => "metal2vulkan-degrade-rotated-blend-rounding",
Degradation::LinkedSamplerNumbering => "metal2vulkan-degrade-linked-sampler-numbering",
Degradation::ArgumentPixelSamplerScaling => {
"metal2vulkan-degrade-argument-pixel-sampler-scaling"
}
Degradation::HalfOutputPrecision => "metal2vulkan-degrade-half-output-precision",
Degradation::AnisotropicFilter => "metal2vulkan-degrade-anisotropic-filter",
Degradation::DeviceAnisotropicFilter => {
"metal2vulkan-degrade-device-anisotropic-filter"
}
Degradation::DevicePointSize => "metal2vulkan-degrade-device-point-size",
Degradation::ClippedCoverageSplit => "metal2vulkan-degrade-clipped-coverage-split",
Degradation::LoopedSampleOutputs => "metal2vulkan-degrade-looped-sample-outputs",
Degradation::HalfOutputFastMathBlend => {
"metal2vulkan-degrade-half-output-fast-math-blend"
}
Degradation::DeviceSampling => "metal2vulkan-degrade-device-sampling",
Degradation::NativeTranscendentals => "metal2vulkan-degrade-native-transcendentals",
Degradation::NativeDivision => "metal2vulkan-degrade-native-division",
Degradation::NativeFma => "metal2vulkan-degrade-native-fma",
Degradation::DeviceTexelConversion => "metal2vulkan-degrade-device-texel-conversion",
Degradation::DeviceVertexConversion => "metal2vulkan-degrade-device-vertex-conversion",
Degradation::NativeHalfConversion => "metal2vulkan-degrade-native-half-conversion",
Degradation::NativeHalfQuantize => "metal2vulkan-degrade-native-half-quantize",
Degradation::NativeNanEncoding => "metal2vulkan-degrade-native-nan-encoding",
Degradation::NativeMinMax => "metal2vulkan-degrade-native-min-max",
Degradation::NativeDot => "metal2vulkan-degrade-native-dot",
Degradation::NativeMix => "metal2vulkan-degrade-native-mix",
Degradation::DevicePackConversion => "metal2vulkan-degrade-device-pack-conversion",
Degradation::TessellationTriangleOrder => {
"metal2vulkan-degrade-tessellation-triangle-order"
}
Degradation::UnmeasuredGroupSpeculation => {
"metal2vulkan-degrade-unmeasured-group-speculation"
}
Degradation::DeviceSampleLevel => "metal2vulkan-degrade-device-sample-level",
Degradation::CoverageReadsRoundedAlpha => {
"metal2vulkan-degrade-coverage-reads-rounded-alpha"
}
Degradation::DeviceAlphaCoverage => "metal2vulkan-degrade-device-alpha-coverage",
Degradation::UnorderedFetchWithinDraw => {
"metal2vulkan-degrade-unordered-fetch-within-draw"
}
Degradation::NativeLogicOperation => "metal2vulkan-degrade-native-logic-operation",
Degradation::DeviceDepthBias => "metal2vulkan-degrade-device-depth-bias",
Degradation::SwizzledOpaqueBlackBorder => {
"metal2vulkan-degrade-swizzled-opaque-black-border"
}
Degradation::DeviceLineRasterization => {
"metal2vulkan-degrade-device-line-rasterization"
}
Degradation::DeviceFragmentRuns => "metal2vulkan-degrade-device-fragment-runs",
Degradation::DeviceOcclusionCount => "metal2vulkan-degrade-device-occlusion-count",
Degradation::VertexSimdgroupGrouping => {
"metal2vulkan-degrade-vertex-simdgroup-grouping"
}
Degradation::RestrictedDepthUpload => "metal2vulkan-degrade-restricted-depth-upload",
Degradation::StencilOutputOverlap => "metal2vulkan-degrade-stencil-output-overlap",
Degradation::TessellationFactorEdgeCases => PrecisionNote::TessellationFactorEdgeCases,
Degradation::TessellationFactorScale => PrecisionNote::TessellationFactorScale,
Degradation::TessellationFactorInstance => PrecisionNote::TessellationFactorInstance,
Degradation::Fp8Value => PrecisionNote::Fp8Value,
Degradation::MultisamplePosition => PrecisionNote::MultisamplePosition,
Degradation::BicubicFilterArithmetic => PrecisionNote::BicubicFilterArithmetic,
Degradation::DeviceNanEncoding => PrecisionNote::DeviceNanEncoding,
Degradation::RestrictedDepthRange => PrecisionNote::RestrictedDepthRange,
Degradation::CubeGradientFootprint => PrecisionNote::CubeGradientFootprint,
Degradation::HalfTexelConversion => PrecisionNote::HalfTexelConversion,
Degradation::SrgbTexelDecode => PrecisionNote::SrgbTexelDecode,
Degradation::FunctionStorageAssumed => PrecisionNote::FunctionStorageAssumed,
Degradation::QuadsCountedBeforeDiscard => PrecisionNote::QuadsCountedBeforeDiscard,
Degradation::ViewBaseTexelOffset => PrecisionNote::ViewBaseTexelOffset,
Degradation::DeviceColorConversion => PrecisionNote::DeviceColorConversion,
Degradation::DeviceInterpolation => PrecisionNote::DeviceInterpolation,
Degradation::DeviceInterpolationOffset => PrecisionNote::DeviceInterpolationOffset,
Degradation::ExtrapolatedInterpolation => PrecisionNote::ExtrapolatedInterpolation,
Degradation::QuadsSplitByClipping => PrecisionNote::QuadsSplitByClipping,
Degradation::FragmentSimdgroupGrouping => PrecisionNote::FragmentSimdgroupGrouping,
Degradation::BlendedWriteRounding => PrecisionNote::BlendedWriteRounding,
Degradation::RotatedBlendRounding => PrecisionNote::RotatedBlendRounding,
Degradation::LinkedSamplerNumbering => PrecisionNote::LinkedSamplerNumbering,
Degradation::ArgumentPixelSamplerScaling => PrecisionNote::ArgumentPixelSamplerScaling,
Degradation::HalfOutputPrecision => PrecisionNote::HalfOutputPrecision,
Degradation::DevicePointSize => PrecisionNote::DevicePointSize,
Degradation::ClippedCoverageSplit => PrecisionNote::ClippedCoverageSplit,
Degradation::LoopedSampleOutputs => PrecisionNote::LoopedSampleOutputs,
Degradation::HalfOutputFastMathBlend => PrecisionNote::HalfOutputFastMathBlend,
Degradation::DeviceSampling => PrecisionNote::DeviceSampling,
Degradation::NativeTranscendentals => PrecisionNote::NativeTranscendentals,
Degradation::NativeDivision => PrecisionNote::NativeDivision,
Degradation::NativeFma => PrecisionNote::NativeFma,
Degradation::DeviceTexelConversion => PrecisionNote::DeviceTexelConversion,
Degradation::DeviceVertexConversion => PrecisionNote::DeviceVertexConversion,
Degradation::NativeHalfConversion => PrecisionNote::NativeHalfConversion,
Degradation::NativeHalfQuantize => PrecisionNote::NativeHalfQuantize,
Degradation::NativeNanEncoding => PrecisionNote::NativeNanEncoding,
Degradation::NativeMinMax => PrecisionNote::NativeMinMax,
Degradation::NativeDot => PrecisionNote::NativeDot,
Degradation::NativeMix => PrecisionNote::NativeMix,
Degradation::DevicePackConversion => PrecisionNote::DevicePackConversion,
Degradation::TessellationTriangleOrder => PrecisionNote::TessellationTriangleOrder,
Degradation::UnmeasuredGroupSpeculation => PrecisionNote::UnmeasuredGroupSpeculation,
Degradation::DeviceSampleLevel => PrecisionNote::DeviceSampleLevel,
Degradation::CoverageReadsRoundedAlpha => PrecisionNote::CoverageReadsRoundedAlpha,
Degradation::DeviceAlphaCoverage => PrecisionNote::DeviceAlphaCoverage,
Degradation::UnorderedFetchWithinDraw => PrecisionNote::UnorderedFetchWithinDraw,
Degradation::NativeLogicOperation => PrecisionNote::NativeLogicOperation,
Degradation::DeviceDepthBias => PrecisionNote::DeviceDepthBias,
Degradation::SwizzledOpaqueBlackBorder => PrecisionNote::SwizzledOpaqueBlackBorder,
Degradation::DeviceLineRasterization => PrecisionNote::DeviceLineRasterization,
Degradation::DeviceFragmentRuns => PrecisionNote::DeviceFragmentRuns,
Degradation::DeviceOcclusionCount => PrecisionNote::DeviceOcclusionCount,
Degradation::VertexSimdgroupGrouping => PrecisionNote::VertexSimdgroupGrouping,
Degradation::RestrictedDepthUpload => PrecisionNote::RestrictedDepthUpload,
Degradation::StencilOutputOverlap => PrecisionNote::StencilOutputOverlap,
Degradation::DeviceHalfDenormals => PrecisionNote::DeviceHalfDenormals,
Degradation::RoundedSampleDepthCopy => PrecisionNote::RoundedSampleDepthCopy,
}
}
@@ -418,7 +381,6 @@ impl Degradation {
PrecisionNote::Fp8Value => Degradation::Fp8Value,
PrecisionNote::MultisamplePosition => Degradation::MultisamplePosition,
PrecisionNote::BicubicFilterArithmetic => Degradation::BicubicFilterArithmetic,
PrecisionNote::SparseResidency => Degradation::SparseResidency,
PrecisionNote::DeviceNanEncoding => Degradation::DeviceNanEncoding,
PrecisionNote::RestrictedDepthRange => Degradation::RestrictedDepthRange,
PrecisionNote::CubeGradientFootprint => Degradation::CubeGradientFootprint,
@@ -438,8 +400,6 @@ impl Degradation {
PrecisionNote::LinkedSamplerNumbering => Degradation::LinkedSamplerNumbering,
PrecisionNote::ArgumentPixelSamplerScaling => Degradation::ArgumentPixelSamplerScaling,
PrecisionNote::HalfOutputPrecision => Degradation::HalfOutputPrecision,
PrecisionNote::AnisotropicFilter => Degradation::AnisotropicFilter,
PrecisionNote::DeviceAnisotropicFilter => Degradation::DeviceAnisotropicFilter,
PrecisionNote::DevicePointSize => Degradation::DevicePointSize,
PrecisionNote::ClippedCoverageSplit => Degradation::ClippedCoverageSplit,
PrecisionNote::LoopedSampleOutputs => Degradation::LoopedSampleOutputs,
@@ -481,6 +441,8 @@ impl Degradation {
PrecisionNote::VertexSimdgroupGrouping => Degradation::VertexSimdgroupGrouping,
PrecisionNote::RestrictedDepthUpload => Degradation::RestrictedDepthUpload,
PrecisionNote::StencilOutputOverlap => Degradation::StencilOutputOverlap,
PrecisionNote::DeviceHalfDenormals => Degradation::DeviceHalfDenormals,
PrecisionNote::RoundedSampleDepthCopy => Degradation::RoundedSampleDepthCopy,
}
}
}
@@ -47,6 +47,16 @@
//! A row is held only against the cases a run selected, so replaying one case does not read every
//! other row as fixed.
//!
//! # More than one answer
//!
//! A row's answer is one answer, except where the hosts a venue's description covers answer the
//! site differently by a property that description does not state: llvmpipe of one Mesa and LLVM
//! stores the `x3` sites of `fetch-ordered-*-srgb` at 6,304 elements on one x86-64 AVX-512 host
//! and at 6,496 on others. Such a row lists each answer recorded there, with [`ANSWER_SEPARATOR`]
//! between them, and its gap names the run each came from. It covers each answer it lists and no
//! other, and is held while the run answers any of them ([`KnownGap::answers`]): a third answer is
//! still a new gap, and a site that no longer diverges still reads the row as fixed.
//!
//! # Typed reasons
//!
//! Three reasons are the ledger's own vocabulary ([`Reason`]), stated at the head of a row's last
@@ -74,6 +84,9 @@ pub const LEDGER_FILE: &str = "known-gaps-rt.tsv";
/// The venue field of a row that applies to every venue.
pub const EVERY_VENUE: &str = "*";
/// What stands between the answers of a row that lists more than one ([`KnownGap::answers`]).
pub const ANSWER_SEPARATOR: &str = " | ";
/// The verdict a row expects at its site.
///
/// Only these two. A case with no Metal answer, a stale recording and a case the venue could not
@@ -135,7 +148,9 @@ pub struct KnownGap {
/// What the run answers there, as the report prints it: our typed error for a refusal, and for
/// a divergence the one leaf fact that moved, which names Metal's value and ours. Part of the
/// row's identity, so a gap that changed into another gap at the same site is a new gap rather
/// than this one.
/// than this one. Where the venue's hosts answer the site differently by a property its
/// description does not state, it lists each answer recorded there, with [`ANSWER_SEPARATOR`]
/// between them ([`KnownGap::answers`]).
pub answer: String,
/// The gap the row is waiting on, in words: what Metal does, what we do instead, and where the
/// fix belongs. Not compared — it is what a reader needs — but a row must carry one.
@@ -150,10 +165,17 @@ impl KnownGap {
Reason::of(&self.waiting_on).unwrap_or(Reason::Words)
}
/// What identifies the row within a venue: the case, the verdict it expects, the site and the
/// answer there.
fn key(&self) -> (&str, Expects, &str, &str) {
(&self.case, self.expects, &self.site, &self.answer)
/// The answers the row covers at its site: its answer, or each of the answers it lists with
/// [`ANSWER_SEPARATOR`] between them.
pub fn answers(&self) -> impl Iterator<Item = &str> {
self.answer.split(ANSWER_SEPARATOR).map(str::trim)
}
/// Whether the row, within a venue it covers, is the gap a run held: the same case, verdict
/// and site, and one of its answers.
fn covers(&self, (case, expects, site, answer): (&str, Expects, &str, &str)) -> bool {
(self.case.as_str(), self.expects, self.site.as_str()) == (case, expects, site)
&& self.answers().any(|listed| listed == answer)
}
/// Whether the row is expected on `venue`.
@@ -623,7 +645,7 @@ pub fn against(rows: &[Replayed], ledger: &[KnownGap]) -> Vec<Expectation> {
for (case, expects, site, answer) in gaps {
let listed = ledger.iter().any(|gap| {
gap.covers_venue(&row.venue)
&& gap.key() == (case, *expects, site.as_str(), answer.as_str())
&& gap.covers((case, *expects, site.as_str(), answer.as_str()))
});
if !listed {
let listed = ledger
@@ -654,7 +676,7 @@ pub fn against(rows: &[Replayed], ledger: &[KnownGap]) -> Vec<Expectation> {
continue;
}
let still = gaps.iter().any(|(case, expects, site, answer)| {
(*case, *expects, site.as_str(), answer.as_str()) == gap.key()
gap.covers((case, *expects, site.as_str(), answer.as_str()))
});
if !still {
let now = if matches!(row.verdict, Verdict::LacksFeature { .. }) {
@@ -72,6 +72,7 @@ pub mod host_pages;
pub mod indirect_commands;
pub mod known_gaps;
pub mod library_facts;
pub mod managed_naming;
pub mod measured;
pub mod mesh_descriptors;
pub mod pass_descriptors;
@@ -0,0 +1,180 @@
//! Which commit takes a Managed buffer's named range to the GPU, on a device that keeps two copies
//! of it.
//!
//! `MTLBuffer.h` has a write into a Managed buffer's `contents` make the range "undefined for any
//! accesses by the GPU" until a `didModifyRange:` "followed by a commit of the MTLCommandBuffer that
//! will access the buffer". What a discrete Mac GPU answers beyond that is measured: one sequence
//! a row, each the same up to its reader.
//!
//! 1. A Managed buffer of [`LENGTH`] bytes, [`Content::Synced`] written, named and taken by a
//! committed blit that copies it, waited for.
//! 2. [`Content::Named`] written and named; a command buffer whose one blit fills another buffer
//! is committed and waited for.
//! 3. The row's reader ([`Way`]) is encoded into a command buffer, [`Content::Later`] is written
//! with no second name, and that command buffer is committed and waited for.
//!
//! The reader answers what it read ([`Way::reads`]), so the row's site is which of the three
//! contents it saw ([`Read`]). On an AMD Radeon Pro 5300M under macOS 26.7.1, 8 rounds each, the
//! readers that name the buffer (a compute slot, `useResource:`, a vertex slot with a draw, a blit
//! copy's source) read [`Content::Later`]: the range is taken at the first commit whose encoders
//! name the buffer, with its bytes as of that commit, and the commit of step 2 took nothing. A
//! reader that reaches the buffer through its address alone reads [`Content::Synced`], the bytes
//! the GPU's copy last took. An Intel UHD Graphics 630, which keeps one copy, read
//! [`Content::Later`] everywhere.
/// The bytes of the Managed buffer: 16 `float4` colours.
pub const LENGTH: usize = 256;
/// The `float4` elements the buffer holds.
pub const ELEMENTS: usize = LENGTH / 16;
/// The side of the render row's target, in texels.
pub const TARGET_SIDE: u32 = 4;
/// The three contents the sequence writes, each [`LENGTH`] bytes of one colour.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Content {
/// Written, named and taken first: opaque red.
Synced,
/// Written and named after it, before a commit that does not name the buffer: opaque green.
Named,
/// Written after the reader is encoded, with no second name: opaque blue.
Later,
}
impl Content {
/// The contents in the order the sequence writes them.
pub const ALL: [Content; 3] = [Content::Synced, Content::Named, Content::Later];
/// The colour every element holds.
pub const fn color(self) -> [f32; 4] {
match self {
Content::Synced => [1.0, 0.0, 0.0, 1.0],
Content::Named => [0.0, 1.0, 0.0, 1.0],
Content::Later => [0.0, 0.0, 1.0, 1.0],
}
}
/// The buffer's bytes.
pub fn bytes(self) -> Vec<u8> {
let element: Vec<u8> = self.color().iter().flat_map(|c| c.to_le_bytes()).collect();
element.repeat(ELEMENTS)
}
/// The word the row's site holds where the reader read this content.
pub const fn word(self) -> &'static str {
match self {
Content::Synced => "the bytes the GPU's copy last took",
Content::Named => "the bytes as the range was named",
Content::Later => "the bytes as of the reader's commit",
}
}
}
/// The reader of a row: how its command buffer reaches the Managed buffer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Way {
/// `scale_and_offset` (`examples/runtime_examples`) with the buffer at its slot 0, scale 1:
/// its output is each element's word plus its index.
ComputeSlot,
/// `ab_address` (`ab_pointers`), the buffer's `gpuAddress` in a constant buffer at slot 0, the
/// buffer declared by `useResource:usage:` read: its output is the buffer's words.
Declared,
/// `ab_address` as [`Way::Declared`], the buffer named to no encoder.
Address,
/// `colored_vertex` and `colored_fragment` (`examples/runtime_examples`) with the buffer as
/// the colours at vertex slot 1, a triangle over the whole [`TARGET_SIDE`] square target
/// drawn: its target's texels, copied out by a blit.
VertexSlot,
/// A blit copy of the buffer's [`LENGTH`] bytes into a Shared buffer.
BlitSource,
}
impl Way {
/// The word a row's name and inputs carry.
pub const fn name(self) -> &'static str {
match self {
Way::ComputeSlot => "compute-slot",
Way::Declared => "declared",
Way::Address => "address",
Way::VertexSlot => "vertex-slot",
Way::BlitSource => "blit-source",
}
}
/// What the reader answers where the buffer holds `content`.
pub fn reads(self, content: Content) -> Vec<u8> {
match self {
Way::ComputeSlot => {
let bytes = content.bytes();
let (words, _) = bytes.as_chunks::<4>();
let floats = (words.iter().enumerate())
.map(|(index, word)| f32::from_le_bytes(*word) + index as f32);
floats.flat_map(f32::to_le_bytes).collect()
}
Way::Declared | Way::Address | Way::BlitSource => content.bytes(),
Way::VertexSlot => {
let texel = content.color().map(|c| (c * 255.0) as u8);
texel.repeat((TARGET_SIDE * TARGET_SIDE) as usize)
}
}
}
/// Which content `read` is, where it is one.
pub fn read(self, read: &[u8]) -> Read {
match Content::ALL.into_iter().find(|&c| self.reads(c) == read) {
Some(content) => Read::Content(content),
None => Read::Other,
}
}
}
/// What a row's reader read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Read {
/// One of the three contents.
Content(Content),
/// None of them.
Other,
}
impl Read {
/// The word the row's site holds.
pub const fn word(self) -> &'static str {
match self {
Read::Content(content) => content.word(),
Read::Other => "none of the three contents",
}
}
}
/// The libraries a row's reader is made of, as the side made them.
#[derive(Clone, Copy, Debug)]
pub struct Libraries {
/// `examples/runtime_examples`: `scale_and_offset`, `colored_vertex`, `colored_fragment`.
pub examples: crate::case::Handle,
/// `ab_pointers`: `ab_address`.
pub pointers: crate::case::Handle,
}
#[cfg(test)]
mod tests {
use super::*;
/// Every reader tells the three contents apart.
#[test]
fn every_reader_tells_the_contents_apart() {
for way in [
Way::ComputeSlot,
Way::Declared,
Way::Address,
Way::VertexSlot,
Way::BlitSource,
] {
for content in Content::ALL {
assert_eq!(way.read(&way.reads(content)), Read::Content(content));
}
assert_eq!(way.read(&[]), Read::Other, "{way:?}");
}
}
}
@@ -2051,6 +2051,33 @@ fn linked_counts(linked: &Retained<MTLLinkedFunctions>) -> LinkedCounts {
}
}
/// Every tessellation field of `state` on `descriptor`.
fn set_tessellation(
descriptor: &MTLRenderPipelineDescriptor,
state: &crate::render::TessellationState,
) {
// SAFETY: each value is an enumerator of the SDK's own table or, for the factor, a count the
// case keeps inside `MTLDevice`'s documented 1..=64, and the descriptor is the caller's own.
// The three setters `objc2` marks unsafe take a raw `NSUInteger`.
unsafe {
descriptor.setMaxTessellationFactor(state.max_factor as usize);
descriptor.setTessellationPartitionMode(MTLTessellationPartitionMode(
state.partition.as_raw() as usize,
));
descriptor.setTessellationControlPointIndexType(MTLTessellationControlPointIndexType(
state.control_point_index_type.as_raw() as usize,
));
}
descriptor.setTessellationFactorFormat(MTLTessellationFactorFormat(
state.factor_format.as_raw() as usize,
));
descriptor.setTessellationFactorStepFunction(MTLTessellationFactorStepFunction(
state.factor_step.as_raw() as usize,
));
descriptor.setTessellationOutputWindingOrder(MTLWinding(state.winding.as_raw() as usize));
descriptor.setTessellationFactorScaleEnabled(state.factor_scale_enabled);
}
/// Metal's vertex descriptor for `layout`. The case's enumerations are Metal's own, so each one
/// crosses as its raw value.
fn vertex_descriptor(layout: &crate::render::VertexLayout<'_>) -> Retained<MTLVertexDescriptor> {
@@ -4603,6 +4630,15 @@ impl Side for MetalSide {
descriptor.setFragmentFunction(fragment);
descriptor.setRasterizationEnabled(fragment.is_some());
descriptor.setSupportIndirectCommandBuffers(fragment.is_some());
// The commands' state takes the run's vertex descriptor and tessellation state.
if fragment.is_some() {
if let Some(state) = &run.tessellation {
set_tessellation(&descriptor, state);
}
if let Some(layout) = &run.vertex_layout {
descriptor.setVertexDescriptor(Some(&vertex_descriptor(layout)));
}
}
// SAFETY: attachment 0 is inside the eight every Metal pipeline descriptor holds.
let attachment =
unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) };
@@ -4631,7 +4667,9 @@ impl Side for MetalSide {
}
};
let descriptor = MTLIndirectCommandBufferDescriptor::new();
descriptor.setCommandTypes(MTLIndirectCommandType::DrawIndexed);
descriptor.setCommandTypes(MTLIndirectCommandType::from_bits_retain(
run.command_types.as_raw() as usize,
));
descriptor.setInheritPipelineState(true);
descriptor.setInheritBuffers(false);
descriptor.setMaxVertexBufferBindCount(run.bind_counts[0] as usize);
@@ -8567,29 +8605,7 @@ impl MetalSide {
// tessellation state leaves Metal's own defaults alone, which is what every other family's
// pipeline has always been made with.
if let Some(state) = &spec.tessellation {
// SAFETY: each value is an enumerator of the SDK's own table or, for the factor, a
// count the case keeps inside `MTLDevice`'s documented 1..=64, and the descriptor is
// this call's own. The three setters `objc2` marks unsafe take a raw `NSUInteger`.
unsafe {
descriptor.setMaxTessellationFactor(state.max_factor as usize);
descriptor.setTessellationPartitionMode(MTLTessellationPartitionMode(
state.partition.as_raw() as usize,
));
descriptor.setTessellationControlPointIndexType(
MTLTessellationControlPointIndexType(
state.control_point_index_type.as_raw() as usize
),
);
}
descriptor.setTessellationFactorFormat(MTLTessellationFactorFormat(
state.factor_format.as_raw() as usize,
));
descriptor.setTessellationFactorStepFunction(MTLTessellationFactorStepFunction(
state.factor_step.as_raw() as usize,
));
descriptor
.setTessellationOutputWindingOrder(MTLWinding(state.winding.as_raw() as usize));
descriptor.setTessellationFactorScaleEnabled(state.factor_scale_enabled);
set_tessellation(&descriptor, state);
}
if let Some(layout) = &spec.vertex_layout {
descriptor.setVertexDescriptor(Some(&vertex_descriptor(layout)));
@@ -10792,6 +10808,9 @@ impl MetalSide {
);
}
}
ComputeStep::DispatchThreads { grid, threads } => {
encoder.dispatchThreads_threadsPerThreadgroup(size(*grid), size(*threads));
}
}
Ok(())
}
+22 -15
View File
@@ -93,7 +93,7 @@ pub fn record(
reason: reason.to_owned(),
});
}
check_host()?;
check_host(&*side)?;
let inputs = case.inputs().map_err(|why| RecordError::Case {
case: case.name().to_owned(),
why,
@@ -213,21 +213,12 @@ fn add(outcomes: &mut Vec<Outcome>, transcript: Transcript) {
}
}
/// Refuse to record on a host that is not the oracle the suite names.
/// Refuse to record on a host that is not the oracle the suite names: `side`'s macOS release and
/// build ([`Side::macos_release`]).
#[cfg(target_os = "macos")]
fn check_host() -> Result<(), RecordError> {
let read = |flag: &str| {
std::process::Command::new("/usr/bin/sw_vers")
.arg(flag)
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
.unwrap_or_default()
};
fn check_host(side: &dyn Side) -> Result<(), RecordError> {
use crate::recording::{ORACLE_CHIP, ORACLE_OS_BUILD, ORACLE_OS_VERSION};
let version = read("-productVersion");
let build = read("-buildVersion");
let (version, build) = side.macos_release();
if version == ORACLE_OS_VERSION && build == ORACLE_OS_BUILD {
return Ok(());
}
@@ -237,8 +228,24 @@ fn check_host() -> Result<(), RecordError> {
})
}
/// This host's macOS release and build, as `sw_vers -productVersion` and `-buildVersion` answer
/// them; each empty where it does not answer.
#[cfg(target_os = "macos")]
pub(crate) fn sw_vers() -> (String, String) {
let read = |flag: &str| {
std::process::Command::new("/usr/bin/sw_vers")
.arg(flag)
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
.unwrap_or_default()
};
(read("-productVersion"), read("-buildVersion"))
}
/// There is no Metal to record from off macOS.
#[cfg(not(target_os = "macos"))]
fn check_host() -> Result<(), RecordError> {
fn check_host(_side: &dyn Side) -> Result<(), RecordError> {
Err(RecordError::NoMetal)
}
@@ -43,6 +43,12 @@ pub const ORACLE_CHIP: &str = "apple-m3-max";
/// recordings say which chip they came from rather than implying the oracle's.
pub const APPLE_M4: &str = "apple-m4";
/// The discrete Mac GPU two families' carried answers were measured on: the Managed-buffer family's
/// table ([`crate::cases::managed_naming`]), as the oracle keeps one copy of a Managed buffer and
/// this one two, and the sample positions family's rows at 8 samples
/// ([`crate::cases::sample_positions`]), as the oracle renders no 8 samples and this one does.
pub const AMD_RADEON_PRO_5300M: &str = "amd-radeon-pro-5300m";
/// The macOS release this round records on, as macOS names it.
pub const ORACLE_OS_VERSION: &str = "27.0.1";
@@ -452,7 +452,9 @@ pub fn reads_opaque_black_border(spec: &crate::case::SamplerSpec) -> bool {
/// - **maths**: the native-maths class (`native-transcendentals`, `native-division`, `native-fma`,
/// `native-dot`, `native-mix`, `native-min-max`, `native-nan-encoding`), the device's functions
/// and precision bounds (`device-transcendentals`, `device-arithmetic`), the device's denormals
/// and NaN bits (`device-denormals`, `device-nan-encoding`), and the device's compiler's grouping
/// and NaN bits (`device-denormals`, `device-nan-encoding`), the device's half denormals where
/// it computes `half` under the 16-bit float controls without `DenormPreserve` for 16 bits, the
/// one form built there (`device-half-denormals`), and the device's compiler's grouping
/// and fusion of the fast-math arithmetic the AIR's flags let it rewrite (`fast-math-rewrites`:
/// the module states each operation in the AIR's order and reproduces no grouping of Metal's);
/// - **rounding**: the native-half class (`native-half-conversion`, `native-half-quantize`), and
@@ -477,8 +479,8 @@ pub fn reads_opaque_black_border(spec: &crate::case::SamplerSpec) -> bool {
/// visibility result (`device-occlusion-count`), announced by every such mode set.
///
/// **What is not here**, and stays each case's to declare: a note of what the device **lacks**
/// (`device-signed-zero-inf-nan`, `device-anisotropic-filter`, `device-point-size`,
/// `restricted-depth-range`, `restricted-depth-upload`), of an emulation's own precision (`grad-from-bias`,
/// (`device-signed-zero-inf-nan`, `device-point-size`, `restricted-depth-range`,
/// `restricted-depth-upload`), of an emulation's own precision (`grad-from-bias`,
/// `pixel-sampler-scaling`, `bicubic-filter-arithmetic`), of a Metal form not measured or not built
/// (`blended-write-rounding`, `device-interpolation`, `reduction-order`), a native answer whose
/// catalogue entry states the bound the cases that read it hold it to (the device's decode of a
@@ -505,6 +507,7 @@ pub const NATIVE_NOTES: &[crate::degradation::Degradation] = {
D::DeviceTranscendentals,
D::DeviceArithmetic,
D::DeviceDenormals,
D::DeviceHalfDenormals,
D::DeviceNanEncoding,
D::FastMathRewrites,
D::NativeHalfConversion,
+94 -12
View File
@@ -20,8 +20,9 @@
//! block-compressed format ([`metal2vulkan_runtime::Texture::precision_note`]) and a sampler state that
//! reads an opaque-black border ([`metal2vulkan_runtime::SamplerState::precision_note`]). This side
//! announces the notes of each state its case dispatched or drew with, of each texture and
//! sampler state it made, and of each upload into a 32-bit float depth (`upload_note`), by the
//! codes the suite's allowances name (`metal2vulkan-degrade-<kind>`).
//! sampler state it made, and of each upload into a 32-bit float depth or a multisample texture's
//! 16-bit depth (`upload_note`), by the codes the suite's allowances name
//! (`metal2vulkan-degrade-<kind>`).
use crate::case::{
Answer, ArgumentSlot, Bindings, Failure, Handle, SamplerSpec, ShaderSource, Side,
@@ -50,6 +51,7 @@ mod fences;
pub(crate) mod fields;
mod functions;
mod heap_sizes;
mod managed_naming;
mod render;
mod state_facts;
mod states;
@@ -206,11 +208,14 @@ impl RtDevice {
}
/// The next texture index ([`RtDevice::next_index`]) for a texture of `pf` and `usage` where a
/// shader reaches it (shader read or write, no bit, which the runtime takes as every usage, or
/// a colour render target, which a fragment function reads through its attachment), and
/// `None` where none does, as the runtime's texture makers take an index.
/// shader reaches it (shader read or write, the private bit `BlockWritesOnly`, which the
/// runtime takes as a write, no bit, which it takes as every usage, or a colour render target,
/// which a fragment function reads through its attachment), and `None` where none does, as the
/// runtime's texture makers take an index.
fn texture_index(&self, pf: rt::PixelFormat, usage: rt::TextureUsage) -> Option<u32> {
let reached = rt::TextureUsage::SHADER_READ | rt::TextureUsage::SHADER_WRITE;
let reached = rt::TextureUsage::SHADER_READ
| rt::TextureUsage::SHADER_WRITE
| rt::TextureUsage::BLOCK_WRITES_ONLY;
let color_target = usage.contains(rt::TextureUsage::RENDER_TARGET)
&& !metal2vulkan::metal::format::is_depth_stencil(pf);
(usage.is_empty() || usage.intersects(reached) || color_target)
@@ -357,6 +362,9 @@ pub struct RtSide<'a> {
/// Each buffer, with the block it lies in, which it alone takes.
buffers: Vec<(rt::Buffer, rt::Block)>,
textures: Vec<rt::Texture>,
/// The textures of [`textures`](Self::textures) that are shareable: each the shared creator
/// made ([`Side::shared_texture`]), and each a handle opened ([`Side::shared_texture_handle`]).
shareable: BTreeSet<u32>,
command_buffers: Vec<rt::CommandBuffer>,
samplers: Vec<rt::SamplerState>,
render_pipelines: Vec<rt::RenderPipelineState>,
@@ -393,6 +401,7 @@ impl<'a> RtSide<'a> {
pipelines: Vec::new(),
buffers: Vec::new(),
textures: Vec::new(),
shareable: BTreeSet::new(),
command_buffers: Vec::new(),
samplers: Vec::new(),
render_pipelines: Vec::new(),
@@ -519,9 +528,14 @@ impl<'a> RtSide<'a> {
/// The static note of an upload into `texture` of `option`, where it reaches a 32-bit float depth:
/// `Depth32Float`'s, or `Depth32Float_Stencil8`'s under its depth option
/// ([`rt::Texture::FLOAT_DEPTH_UPLOAD_NOTE`]).
/// ([`rt::Texture::FLOAT_DEPTH_UPLOAD_NOTE`]); or the 16-bit depth of a multisample texture, which
/// the runtime's own draw writes ([`rt::Texture::SAMPLE_DEPTH_COPY_NOTE`]).
fn upload_note(texture: &rt::Texture, option: rt::BlitOption) -> Option<rt::PrecisionNote> {
let pixel_format = texture.descriptor().pixel_format;
let d = texture.descriptor();
let pixel_format = d.pixel_format;
if pixel_format == PixelFormat::Depth16Unorm && d.sample_count > 1 {
return Some(rt::Texture::SAMPLE_DEPTH_COPY_NOTE);
}
let depth = pixel_format == PixelFormat::Depth32Float
|| (pixel_format == PixelFormat::Depth32FloatStencil8
&& option == rt::BlitOption::DepthFromDepthStencil);
@@ -1118,11 +1132,11 @@ impl Side for RtSide<'_> {
Ok(self.keep_texture(view))
}
/// The view's shape and swizzle, read of its descriptor; its parent's facts are the
/// consumer's own
/// The view's shape and swizzle, read of its descriptor; its parent's facts and `shareable` are
/// the consumer's own
/// ([`ConsumerObject::TextureViewParents`](crate::known_gaps::ConsumerObject::TextureViewParents)):
/// the runtime's view keeps the texture whose image it reads and no getter, and makes no
/// shareable texture.
/// the runtime's view keeps the texture whose image it reads and no getter, and the consumer
/// keeps what it shared.
fn texture_view_facts(
&mut self,
texture: Handle,
@@ -1145,6 +1159,66 @@ impl Side for RtSide<'_> {
})
}
/// `newSharedTextureWithDescriptor:` as the runtime's consumer answers it on the runtime's one
/// device, which every guest process shares: the texture `newTextureWithDescriptor:` makes,
/// kept as shareable. Metal answers nil outside `Private` storage and for a format it makes no
/// texture of from a descriptor alone
/// ([`WITHOUT_TEXTURES`](crate::texture_query::WITHOUT_TEXTURES)), measured on an Apple M3 Max
/// (`shared-creator-padded-format-storage`, `shared-creator-extended-range-samples`), and so
/// does this.
fn shared_texture(&mut self, query: &crate::texture_query::HeapTextureQuery) -> Answer<Handle> {
let unshared = query.storage != crate::texture_query::Storage::Private;
if unshared || crate::texture_query::WITHOUT_TEXTURES.contains(&query.format) {
return Err(Failure::named(
"Nil",
format!(
"newSharedTextureWithDescriptor: answers nil for {}",
query.site()
),
));
}
let descriptor = queried(query);
let index = (self.on).texture_index(descriptor.pixel_format, descriptor.usage);
let texture = (self.on.device.new_texture(&descriptor, index))
.map_err(|error| Failure::of_rt(&error))?;
let shared = self.keep_texture(texture);
self.shareable.insert(shared.0);
Ok(shared)
}
/// `newSharedTextureHandle` and `newSharedTextureWithHandle:` as the runtime's consumer
/// answers them on the runtime's one device: the handle is the consumer's own, of that device,
/// and the texture it opens is a clone of the same `Texture`, shareable as its texture is. A
/// texture that is not shareable answers nil, as the cases model Metal (they never ask one).
fn shared_texture_handle(
&mut self,
texture: Handle,
) -> Answer<crate::texture_views::SharedHandleFacts> {
if !self.shareable.contains(&texture.0) {
return Err(Failure::named(
"Nil",
format!(
"newSharedTextureHandle of texture {}, which is not shareable",
texture.0
),
));
}
let opened = self.held_texture(texture)?.clone();
let d = opened.descriptor();
let facts = crate::texture_views::SharedHandleFacts {
own_device: true,
opens: true,
opened_shareable: true,
opened_width: d.width.into(),
opened_height: d.height.into(),
opened_levels: d.mipmap_level_count.into(),
};
// Kept as the Metal side keeps the texture it opened.
let held = keep(&mut self.textures, opened);
self.shareable.insert(held.0);
Ok(facts)
}
fn dispatch(
&mut self,
pipeline: Handle,
@@ -1809,6 +1883,14 @@ impl Side for RtSide<'_> {
Ok(keep(&mut self.textures, texture))
}
fn managed_naming(
&mut self,
way: crate::managed_naming::Way,
libraries: crate::managed_naming::Libraries,
) -> Answer<Vec<u8>> {
self.managed_naming_run(way, libraries)
}
fn empty_command_buffers(&mut self) -> Answer<EmptyCommandBuffers> {
let of_rt = |error: rt::Error| Failure::of_rt(&error);
let order: Arc<Mutex<Vec<String>>> = Arc::default();
@@ -173,15 +173,55 @@ impl RtSide<'_> {
*threads,
))
.map_err(of_rt),
// The attribute-stride setters, the stage-in region and heaps: the runtime has no
// counterpart yet.
ComputeStep::BufferWithStride { .. }
| ComputeStep::BuffersWithStrides { .. }
| ComputeStep::BufferOffsetWithStride { .. }
| ComputeStep::BytesWithStride { .. }
| ComputeStep::StageInRegion { .. }
| ComputeStep::UseHeap { .. }
| ComputeStep::UseHeaps { .. } => Err(Failure::unavailable(step.call())),
ComputeStep::DispatchThreads { grid, threads } => {
(encoder.dispatch_threads(*grid, *threads)).map_err(of_rt)
}
ComputeStep::BufferWithStride {
buffer,
offset,
stride,
index,
} => (encoder.set_buffer_with_attribute_stride(
Some(self.held(*buffer)?),
*offset,
*stride,
*index,
))
.map_err(of_rt),
ComputeStep::BuffersWithStrides { buffers, first } => {
for (at, (buffer, offset, stride)) in (*first..).zip(buffers) {
(encoder.set_buffer_with_attribute_stride(
Some(self.held(*buffer)?),
*offset,
*stride,
at,
))
.map_err(of_rt)?;
}
Ok(())
}
ComputeStep::BufferOffsetWithStride {
offset,
stride,
index,
} => (encoder.set_buffer_offset_with_attribute_stride(*offset, *stride, *index))
.map_err(of_rt),
ComputeStep::BytesWithStride {
bytes,
stride,
index,
} => (encoder.set_bytes_with_attribute_stride(bytes, *stride, *index)).map_err(of_rt),
ComputeStep::StageInRegion { origin, size } => {
encoder.set_stage_in_region(rt::Region {
origin: *origin,
size: *size,
});
Ok(())
}
// Heaps: the runtime has no counterpart yet.
ComputeStep::UseHeap { .. } | ComputeStep::UseHeaps { .. } => {
Err(Failure::unavailable(step.call()))
}
}
}
@@ -76,7 +76,7 @@ pub(crate) fn pipeline_fields(spec: &RenderPipelineSpec<'_>) -> Answer<PipelineF
/// The runtime's `TessellationDescriptor` for `state`: every field the case names, since the
/// vocabulary is Metal's own and there is no second spelling to keep in step.
fn tessellation_descriptor(
pub(crate) fn tessellation_descriptor(
state: &crate::render::TessellationState,
) -> metal2vulkan::pipeline::TessellationDescriptor {
let mut descriptor = metal2vulkan::pipeline::TessellationDescriptor::default();
@@ -92,7 +92,7 @@ fn tessellation_descriptor(
/// The runtime's vertex descriptor for `layout`: the same attribute indices, buffer indices and
/// step functions the case states, so both sides fetch the same way.
fn vertex_descriptor(layout: &crate::render::VertexLayout<'_>) -> VertexDescriptor {
pub(crate) fn vertex_descriptor(layout: &crate::render::VertexLayout<'_>) -> VertexDescriptor {
let mut descriptor = VertexDescriptor::new();
for attribute in layout.attributes {
descriptor.attributes.insert(
@@ -7,18 +7,20 @@
//! places by before it answers it, and answers the failure where it does not hold:
//!
//! 1. the alignment is a power of two, for every query;
//! 2. for a Private query, a heap of `align + size` bytes takes a texture of the descriptor at
//! offset `align`;
//! 2. for a Private or Shared query, a heap of its storage mode, `align + size` bytes, takes a
//! texture of the descriptor at offset `align` (a Shared one on a device without unified
//! memory, as an image of its own, and on one with it where the device's image of it takes
//! the Shared memory type; it is held to the first alone where the placement is
//! `Gap::HeapTexture`);
//! 3. there, where the runtime moves the format's bytes, level 0's first slice written from a
//! buffer reads back unchanged: a `Depth32Float` slice's bytes are depths within `[0, 1]`, the
//! only ones a copy into a depth aspect keeps on every device
//! (`Texture::FLOAT_DEPTH_UPLOAD_NOTE`), and any other's a pattern of bytes.
//!
//! A Shared, Managed or Memoryless query is held to the first alone: the runtime places a heap
//! texture in a Private block only (`Gap::HeapTexture`), and placing the descriptor in a Private
//! heap would answer another query. A query whose bytes the runtime does not move, which its copy
//! answers `Gap::TextureBytes` (depth and stencil both, or multisample) for, is held to the first
//! two.
//! A Managed or Memoryless query is held to the first alone: no heap of either mode is made, and
//! placing the descriptor in a heap of another mode would answer another query. A query whose
//! bytes the runtime does not move, which its copy answers `Gap::TextureBytes` (depth and stencil
//! both, or multisample) for, is held to the first two.
use super::{waited_for, work, RtDevice, WAIT};
use crate::case::{Answer, Failure};
@@ -41,7 +43,7 @@ pub(super) fn hold(
format!("step 1: the alignment {align} is not a power of two"),
));
}
if query.storage != Storage::Private {
if !matches!(query.storage, Storage::Private | Storage::Shared) {
return Ok(());
}
let heap_size = align.checked_add(size).ok_or_else(|| {
@@ -50,10 +52,19 @@ pub(super) fn hold(
format!("step 2: a heap of {align} + {size} bytes"),
)
})?;
let (_block, heap) = work::heap_of(on, heap_size, Storage::Private)?;
let (_block, heap) = work::heap_of(on, heap_size, query.storage)?;
let index = on.texture_index(descriptor.pixel_format, descriptor.usage);
let texture = (on.device.new_heap_texture(descriptor, index, heap, align))
.map_err(|error| on.failure(&error))?;
let texture = match on.device.new_heap_texture(descriptor, index, heap, align) {
Ok(texture) => texture,
// A device with unified memory whose image of the descriptor takes no Shared memory type
// sizes it, and places none of it in a Shared heap: the answer is held to step 1 there.
Err(rt::Error::Unsupported(rt::Gap::HeapTexture { .. }))
if query.storage == Storage::Shared =>
{
return Ok(());
}
Err(error) => return Err(on.failure(&error)),
};
round_trip(on, queue, descriptor, &texture)
}
@@ -0,0 +1,246 @@
//! The runtime's side of [`crate::managed_naming`]: the sequence through the runtime's
//! Metal-shaped API, its Managed buffer in the form the device's memory-type query picks
//! (`Device::has_unified_memory`).
use super::work::{read_buffer, write};
use super::{waited_for, RtSide, WAIT};
use crate::case::{Answer, Failure};
use crate::managed_naming::{Content, Libraries, Way, LENGTH, TARGET_SIDE};
use metal2vulkan::metal::PixelFormat;
use metal2vulkan_runtime as rt;
/// What the venue lacks for a reader that reaches the buffer through its address alone, on a
/// device that keeps one copy of a Managed buffer.
const ONE_COPY: &str = "a device copy of each Managed buffer (Device::has_unified_memory false): \
with one copy a reader through the address reads the buffer's own bytes";
impl RtSide<'_> {
/// [`crate::case::Side::managed_naming`] on the runtime.
pub(super) fn managed_naming_run(&mut self, way: Way, libraries: Libraries) -> Answer<Vec<u8>> {
let on = self.on;
let device = &on.device;
let of_rt = |error: rt::Error| on.failure(&error);
let two = !device.has_unified_memory();
if way == Way::Address && !two {
let mut failure = Failure::named("OneCopy", ONE_COPY);
failure.lacks = Some(ONE_COPY.to_owned());
return Err(failure);
}
let length = LENGTH as u64;
let shared = |length: u64| -> Answer<(rt::Buffer, rt::Block)> {
let block = (device.take_block(rt::MemoryClass::Shared, length)).map_err(of_rt)?;
let buffer = (device.new_buffer(block.id, 0, length, Some(0))).map_err(of_rt)?;
Ok((buffer, block))
};
let bytes = (device.take_block(rt::MemoryClass::Shared, length)).map_err(of_rt)?;
let copy = match two {
true => Some((device.take_block(rt::MemoryClass::Private, length)).map_err(of_rt)?),
false => None,
};
let at = |block: &rt::Block| (block.id, 0);
let managed = (device.new_managed_buffer(at(&bytes), copy.as_ref().map(at), length, 0))
.map_err(of_rt)?;
let (scratch, scratch_block) = shared(length)?;
let (out, out_block) = shared(length)?;
let queue = (device.new_command_queue(4)).map_err(of_rt)?;
let run = |command_buffer: &rt::CommandBuffer| -> Answer<()> {
command_buffer.commit().map_err(of_rt)?;
match waited_for(command_buffer, WAIT) {
Some(_) => match command_buffer.error() {
None => Ok(()),
Some(error) => Err(Failure::named("CommandBufferError", format!("{error:?}"))),
},
None => Err(Failure::named(
"NeverCompleted",
"a command buffer of the sequence",
)),
}
};
let blit = |source: &rt::Buffer, destination: &rt::Buffer| -> Answer<()> {
let command_buffer = queue.command_buffer().map_err(of_rt)?;
let mut blit = command_buffer.blit_command_encoder().map_err(of_rt)?;
(blit.copy_from_buffer_to_buffer(source, 0, destination, 0, length)).map_err(of_rt)?;
blit.end_encoding();
run(&command_buffer)
};
// 1. Synced: written, named, and taken by a blit that copies the buffer.
write(&managed, &Content::Synced.bytes())?;
(managed.did_modify_range(0, length)).map_err(of_rt)?;
blit(&managed, &scratch)?;
// 2. Named: written and named; a commit whose one blit fills another buffer.
write(&managed, &Content::Named.bytes())?;
(managed.did_modify_range(0, length)).map_err(of_rt)?;
let elsewhere = queue.command_buffer().map_err(of_rt)?;
let mut fill = elsewhere.blit_command_encoder().map_err(of_rt)?;
(fill.fill_buffer(&scratch, 0..length, 0)).map_err(of_rt)?;
fill.end_encoding();
run(&elsewhere)?;
// 3. The reader encoded, Later written with no second name, its commit.
let reader = queue.command_buffer().map_err(of_rt)?;
// The reader's own buffers' blocks, given back once it completed.
let mut blocks = vec![bytes, scratch_block, out_block];
blocks.extend(copy);
let held = match way {
Way::ComputeSlot => {
self.slot_reader(&reader, libraries, &managed, &out)?;
None
}
Way::Declared | Way::Address => {
let (address, block) =
self.address_reader(&reader, way, libraries, &managed, &out)?;
blocks.push(block);
Some(address)
}
Way::VertexSlot => {
let (positions, block) = self.vertex_reader(&reader, libraries, &managed, &out)?;
blocks.push(block);
Some(positions)
}
Way::BlitSource => {
let mut blit = reader.blit_command_encoder().map_err(of_rt)?;
(blit.copy_from_buffer_to_buffer(&managed, 0, &out, 0, length)).map_err(of_rt)?;
blit.end_encoding();
None
}
};
write(&managed, &Content::Later.bytes())?;
run(&reader)?;
let read = match way {
Way::VertexSlot => (TARGET_SIDE * TARGET_SIDE * 4) as usize,
_ => LENGTH,
};
let read = read_buffer(&out, 0, read)?;
drop((held, reader, elsewhere, queue, managed, scratch, out));
for block in blocks {
device.release_block(block).map_err(of_rt)?;
}
Ok(read)
}
/// `scale_and_offset` over `managed` at slot 0 into `out` at slot 1, scale 1, one thread an
/// element's word.
fn slot_reader(
&mut self,
reader: &rt::CommandBuffer,
libraries: Libraries,
managed: &rt::Buffer,
out: &rt::Buffer,
) -> Answer<()> {
let on = self.on;
let of_rt = |error: rt::Error| on.failure(&error);
let state = self.compute_state(libraries.examples, "scale_and_offset")?;
let mut encoder =
(reader.compute_command_encoder(rt::DispatchType::Serial)).map_err(of_rt)?;
encoder.set_compute_pipeline_state(&state).map_err(of_rt)?;
encoder.set_buffer(Some(managed), 0, 0).map_err(of_rt)?;
encoder.set_buffer(Some(out), 0, 1).map_err(of_rt)?;
(encoder.set_bytes(&1.0f32.to_le_bytes(), 2)).map_err(of_rt)?;
let words = (LENGTH / 4) as u32;
(encoder.dispatch_threads([words, 1, 1], [words, 1, 1])).map_err(of_rt)?;
encoder.end_encoding();
Ok(())
}
/// `ab_address` reading `managed` through its address, which a Shared buffer at slot 0 holds,
/// into `out` at slot 1; `managed` declared by `use_resource` where `way` is
/// [`Way::Declared`]. Answers the buffer that holds the address, which the reader needs until
/// it completes.
fn address_reader(
&mut self,
reader: &rt::CommandBuffer,
way: Way,
libraries: Libraries,
managed: &rt::Buffer,
out: &rt::Buffer,
) -> Answer<(rt::Buffer, rt::Block)> {
let on = self.on;
let of_rt = |error: rt::Error| on.failure(&error);
let state = self.compute_state(libraries.pointers, "ab_address")?;
let block = (on.device.take_block(rt::MemoryClass::Shared, 8)).map_err(of_rt)?;
let address = (on.device.new_buffer(block.id, 0, 8, Some(0))).map_err(of_rt)?;
write(&address, &managed.gpu_address().to_le_bytes())?;
let mut encoder =
(reader.compute_command_encoder(rt::DispatchType::Serial)).map_err(of_rt)?;
encoder.set_compute_pipeline_state(&state).map_err(of_rt)?;
encoder.set_buffer(Some(&address), 0, 0).map_err(of_rt)?;
encoder.set_buffer(Some(out), 0, 1).map_err(of_rt)?;
if way == Way::Declared {
let read = rt::ResourceUsage::READ;
(encoder.use_resource(rt::Resource::Buffer(managed), read)).map_err(of_rt)?;
}
let words = (LENGTH / 4) as u32;
(encoder.dispatch_threads([words, 1, 1], [words, 1, 1])).map_err(of_rt)?;
encoder.end_encoding();
Ok((address, block))
}
/// `colored_vertex` and `colored_fragment` drawing one triangle over the whole target, its
/// colours `managed` at vertex slot 1, then a blit of the target's texels into `out`. Answers
/// the positions' buffer and the target, which the reader needs until it completes.
fn vertex_reader(
&mut self,
reader: &rt::CommandBuffer,
libraries: Libraries,
managed: &rt::Buffer,
out: &rt::Buffer,
) -> Answer<(rt::Buffer, rt::Block)> {
let on = self.on;
let of_rt = |error: rt::Error| on.failure(&error);
let mut d =
rt::RenderPipelineDescriptor::new(self.kernel(libraries.examples, "colored_vertex")?);
d.fragment = Some(self.kernel(libraries.examples, "colored_fragment")?);
d.color_attachments[0] = Some(rt::ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm));
let state = (on.device)
.new_render_pipeline_state(&d, |samplers| Ok(on.sampler_ids(samplers)))
.map_err(of_rt)?;
let mut t = rt::TextureDescriptor::new(
rt::TextureType::Type2D,
PixelFormat::RGBA8Unorm,
TARGET_SIDE,
TARGET_SIDE,
);
t.usage = rt::TextureUsage::RENDER_TARGET;
let index = on.texture_index(PixelFormat::RGBA8Unorm, t.usage);
let target = (on.device.new_texture(&t, index)).map_err(of_rt)?;
let corners: [f32; 6] = [-1.0, -1.0, 3.0, -1.0, -1.0, 3.0];
let block = (on.device.take_block(rt::MemoryClass::Shared, 24)).map_err(of_rt)?;
let positions = (on.device.new_buffer(block.id, 0, 24, Some(0))).map_err(of_rt)?;
let corners: Vec<u8> = corners.iter().flat_map(|c| c.to_le_bytes()).collect();
write(&positions, &corners)?;
let mut pass = rt::RenderPassDescriptor::default();
let color = &mut pass.color_attachments[0];
color.texture = Some(target.clone());
color.load_action = rt::LoadAction::Clear;
let mut encoder = (reader.render_command_encoder(&pass)).map_err(of_rt)?;
encoder.set_render_pipeline_state(&state).map_err(of_rt)?;
(encoder.set_vertex_buffer(Some(&positions), 0, 0)).map_err(of_rt)?;
(encoder.set_vertex_buffer(Some(managed), 0, 1)).map_err(of_rt)?;
(encoder.draw_primitives(rt::PrimitiveType::Triangle, 0, 3, 1, 0)).map_err(of_rt)?;
encoder.end_encoding();
let mut blit = reader.blit_command_encoder().map_err(of_rt)?;
let layout = rt::BufferLayout {
offset: 0,
bytes_per_row: u64::from(TARGET_SIDE) * 4,
bytes_per_image: 0,
};
let size = [TARGET_SIDE, TARGET_SIDE, 1];
let place = rt::TexturePlace::default();
(blit.copy_from_texture_to_buffer(&target, place, size, out, layout)).map_err(of_rt)?;
blit.end_encoding();
Ok((positions, block))
}
/// The compute pipeline state of `entry` of library `library`.
fn compute_state(
&mut self,
library: crate::case::Handle,
entry: &str,
) -> Answer<rt::ComputePipelineState> {
let descriptor = rt::ComputePipelineDescriptor::new(self.kernel(library, entry)?);
let on = self.on;
(on.device)
.new_compute_pipeline_state(&descriptor, |samplers| Ok(on.sampler_ids(samplers)))
.map_err(|error| on.failure(&error))
}
}
@@ -456,9 +456,9 @@ impl RtSide<'_> {
VisibilityResultType::Reset => rt::VisibilityResultType::Reset,
VisibilityResultType::Accumulate => rt::VisibilityResultType::Accumulate,
};
if !pass.positions.is_empty() {
return Err(Failure::unavailable("setSamplePositions:count:"));
}
descriptor.sample_positions = (pass.positions.iter())
.map(|p| rt::SamplePosition::new(p.x, p.y))
.collect();
let mut encoder = (command_buffer.render_command_encoder(&descriptor)).map_err(of_rt)?;
let encoded = (pass.steps.iter()).try_for_each(|step| self.step(&mut encoder, step));
encoder.end_encoding();
@@ -773,6 +773,35 @@ impl RtSide<'_> {
))
.map_err(of_rt)
}
RenderStep::DrawIndexedPatches {
control_points,
first,
count,
patch_indices,
patch_index_offset,
control_point_indices,
control_point_index_offset,
instances,
base_instance,
} => {
let patches = match patch_indices {
Some(held) => Some((buffer(*held)?, *patch_index_offset)),
None => None,
};
let indices = rt::PatchIndexBuffers {
patches,
control_points: (buffer(*control_point_indices)?, *control_point_index_offset),
};
(encoder.draw_indexed_patches(
*control_points,
*first,
*count,
indices,
*instances,
*base_instance,
))
.map_err(of_rt)
}
// The scope and the stages only narrow what Metal orders: the runtime's barrier orders
// every access of the encoder's draws so far before its later ones.
RenderStep::BarrierScope { .. } => encoder.memory_barrier().map_err(of_rt),
@@ -199,6 +199,13 @@ impl RtSide<'_> {
descriptor.rasterization_enabled = rasterizes;
descriptor.support_indirect_command_buffers = rasterizes;
descriptor.color_attachments[0] = Some(rt::ColorAttachmentDescriptor::new(run.format));
// The commands' state takes the run's vertex descriptor and tessellation state.
if rasterizes {
descriptor.vertex_descriptor =
(run.vertex_layout.as_ref()).map(super::fields::vertex_descriptor);
descriptor.tessellation =
(run.tessellation.as_ref()).map(super::fields::tessellation_descriptor);
}
(on.device)
.new_render_pipeline_state(&descriptor, |samplers| Ok(on.sampler_ids(samplers)))
.map_err(|error| on.failure(&error))
@@ -224,7 +231,8 @@ impl RtSide<'_> {
),
};
let mut descriptor = rt::IndirectCommandBufferDescriptor::new();
descriptor.command_types = rt::IndirectCommandType::DRAW_INDEXED;
descriptor.command_types =
rt::IndirectCommandType::from_bits(u64::from(run.command_types.as_raw()));
descriptor.inherit_pipeline_state = true;
descriptor.max_vertex_buffer_bind_count = run.bind_counts[0];
descriptor.max_fragment_buffer_bind_count = run.bind_counts[1];
+149 -1
View File
@@ -41,6 +41,10 @@ struct StubSide {
/// The device name the side's venue answers, so a test can hold a venue-scoped ledger row
/// against one venue and not another.
device: &'static str,
/// The macOS release and build the side stands for (`Side::macos_release`): the oracle's,
/// so record mode's logic runs on any Mac, where a test does not move it (`on_release`).
#[cfg(target_os = "macos")]
release: (&'static str, &'static str),
made: u32,
}
@@ -52,10 +56,22 @@ impl StubSide {
notices: Vec::new(),
refuse: Vec::new(),
device: "stub",
#[cfg(target_os = "macos")]
release: (
crate::recording::ORACLE_OS_VERSION,
crate::recording::ORACLE_OS_BUILD,
),
made: 0,
}
}
/// The same side on another macOS release and build.
#[cfg(target_os = "macos")]
fn on_release(mut self, version: &'static str, build: &'static str) -> Self {
self.release = (version, build);
self
}
/// The same side on a venue of another name.
fn on(mut self, device: &'static str) -> Self {
self.device = device;
@@ -91,6 +107,11 @@ impl Side for StubSide {
venue_named(self.device)
}
#[cfg(target_os = "macos")]
fn macos_release(&self) -> (String, String) {
(self.release.0.to_owned(), self.release.1.to_owned())
}
fn library(&mut self, _source: &ShaderSource<'_>) -> Answer<Handle> {
match self.refusal("library") {
Some(failure) => Err(failure),
@@ -1030,6 +1051,16 @@ fn one_word_moving_names_its_row_and_index() {
assert!(printed.contains("Metal 3"), "{printed}");
}
/// Each kind is one precision note's: [`Degradation::note`] takes
/// [`Degradation::from_precision_note`] back, so a kind's code is its note's
/// (`PrecisionNote::code`).
#[test]
fn every_kind_is_its_notes_kind() {
for &kind in Degradation::ALL {
assert_eq!(Degradation::from_precision_note(kind.note()), kind);
}
}
/// Every kind a case can name is a precision note's: `docs/API.md` section 9, the catalogue of
/// the notes the runtime carries, lists its code. The runtime's side announces only the codes of
/// those notes, so a kind outside the catalogue would never be announced, and a case that
@@ -2367,6 +2398,36 @@ fn record_mode_counts_the_outcomes_it_saw_with_their_runs() {
}
}
/// Record mode refuses to take an answer on a Mac that is not the oracle the suite names, naming
/// both, and the host it holds is the side's (`Side::macos_release`): Metal's side reads this
/// host's, and the stub states the oracle's but here, so the record-mode tests above check record
/// mode's logic on any Mac, the CI runner's macOS among them.
#[cfg(target_os = "macos")]
#[test]
fn record_mode_refuses_a_host_that_is_not_the_oracle() {
use crate::recording::{ORACLE_CHIP, ORACLE_OS_BUILD, ORACLE_OS_VERSION};
let case = WordsCase::new("words", 2);
let mut moved = StubSide::new(words(&[1, 2])).on_release("26.7.2", "25G332");
let error = record(&case, &mut moved, 1, Validated::Ran).unwrap_err();
assert_eq!(
error,
RecordError::HostMoved {
found: "macOS 26.7.2 (25G332)".to_owned(),
named: format!("{ORACLE_CHIP} on macOS {ORACLE_OS_VERSION} ({ORACLE_OS_BUILD})"),
}
);
assert!(
format!("{error}").contains("re-record every case"),
"{error}"
);
// The oracle's release on another build is moved too: a recording is keyed by both.
let mut rebuilt = StubSide::new(words(&[1, 2])).on_release(ORACLE_OS_VERSION, "26A999");
assert!(matches!(
record(&case, &mut rebuilt, 1, Validated::Ran),
Err(RecordError::HostMoved { .. })
));
}
#[test]
fn a_set_diff_prints_what_is_missing_and_what_is_extra() {
let metal = Transcript::new(vec![Node::leaf(
@@ -2896,10 +2957,16 @@ fn a_carried_answer_taken_on_another_chip_names_it() {
// - `sample-positions-fewer-*`: the M4's coverage for fewer custom sample positions than the
// pass's samples, which stays carried because one position **past** the pass's samples is
// measured to end Metal's process, so a record run may not walk that family.
const KNOWN: [&str; 3] = [
// - `managed-named-*`: an AMD Radeon Pro 5300M's answer for which commit takes a Managed
// buffer's named range to its second copy, which the oracle, keeping one copy, cannot give.
// - `sample-positions-8x-*`: the 5300M's resolved texels of the sample positions family's pass
// at 8 samples, which the oracle, rendering no 8 samples, cannot give.
const KNOWN: [&str; 5] = [
"texture-fills-",
crate::cases::compute_threadgroups::PAST_METALS_LIMIT,
"sample-positions-fewer-",
"managed-named-",
"sample-positions-8x-",
];
for family in KNOWN {
assert!(
@@ -4115,6 +4182,87 @@ fn a_divergence_row_is_held_in_both_directions() {
assert!(printed.contains("drop the row"), "{printed}");
}
/// A row may list more than one answer at its site, with ` | ` between them, for a venue whose
/// hosts answer the site differently by a property its description does not state: llvmpipe of
/// one Mesa and LLVM stores the `x3` sites of `fetch-ordered-*-srgb` at 6,304 elements on one
/// x86-64 AVX-512 host and at 6,496 on others. The row covers each answer it lists and no other,
/// and is held while the run answers any of them; a row of one answer is held as before.
#[test]
fn a_ledger_row_of_two_answers_covers_either_and_no_third() {
use crate::known_gaps::{against, parse, Expectation, Now};
let case = LedgerCase::new("ledger-two-answers");
let recording = recording_of(&case, case.metal(7), 3);
let answering = |ours: u32| {
let mut side = StubSide::new(words(&[ours]));
let row = replay_against(&case, &mut side, &recording).unwrap();
let found = against(std::slice::from_ref(&row), &[]);
let [Expectation::Unlisted { site, answer, .. }] = found.as_slice() else {
panic!("{found:?}");
};
(row, site.clone(), answer.clone())
};
let (nine, site, first) = answering(9);
let (eight, at, second) = answering(8);
let (six, _, third) = answering(6);
assert_eq!(at, site);
assert!(first != second && second != third && first != third);
let row = |answers: &str| {
parse(&format!(
"{}\t*\tdivergent\t{site}\t{answers}\ta difference this test writes down on purpose\n",
case.name()
))
.unwrap()
};
// Either listed answer is the row's, so neither run is a surprise.
let two = row(&format!("{first} | {second}"));
assert_eq!(two.len(), 1, "{two:?}");
assert_eq!(against(std::slice::from_ref(&nine), &two), Vec::new());
assert_eq!(against(std::slice::from_ref(&eight), &two), Vec::new());
// A third answer is a new gap, and the row, none of whose answers the run held, looks fixed.
let found = against(std::slice::from_ref(&six), &two);
assert!(
matches!(
found.as_slice(),
[
Expectation::Unlisted { answer, listed: Some(_), .. },
Expectation::NoLongerHeld { now: Now::Differs, .. },
] if *answer == third
),
"{found:?}"
);
// A run that no longer diverges reads the row as fixed, whichever answer it listed.
let mut fixed = StubSide::new(words(&[7]));
let exact = replay_against(&case, &mut fixed, &recording).unwrap();
let found = against(std::slice::from_ref(&exact), &two);
assert!(
matches!(
found.as_slice(),
[Expectation::NoLongerHeld {
now: Now::Matches,
..
}]
),
"{found:?}"
);
// A row of one answer covers that answer alone, in both directions, as before.
let one = row(&first);
assert_eq!(against(std::slice::from_ref(&nine), &one), Vec::new());
let found = against(std::slice::from_ref(&eight), &one);
assert!(
matches!(
found.as_slice(),
[
Expectation::Unlisted { answer, .. },
Expectation::NoLongerHeld { now: Now::Differs, .. },
] if *answer == second
),
"{found:?}"
);
}
/// A divergence never launders a refusal of the same case: the verdict carries both, and the
/// ledger holds a refusal row against a case that also diverges.
///
@@ -15,6 +15,20 @@
use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage};
/// The formats Metal makes no texture of from a descriptor alone: `RGBA16Float_XR`, `AnyDepth`,
/// `AnyStencil` and a two-plane YCbCr format.
///
/// Measured on an Apple M3 Max under macOS 27.0.1: `newTextureWithDescriptor:` answers nil for
/// each (`heap-sizes-formats-without-textures`), and `newSharedTextureWithDescriptor:` answers nil
/// for `RGBA16Float_XR` in `Private` storage at 1, 4 and 8 samples
/// (`shared-creator-extended-range-samples`).
pub const WITHOUT_TEXTURES: [PixelFormat; 4] = [
PixelFormat::RGBA16FloatXR,
PixelFormat::AnyDepth,
PixelFormat::AnyStencil,
PixelFormat::YCBCR84202P,
];
/// The storage mode a case asks a resource for: three of Metal's four modes, and the suite's one
/// spelling of them.
///
@@ -111,6 +111,11 @@ impl<S: Side, W: Watcher> Side for Watching<S, W> {
self.inner.venue()
}
#[cfg(target_os = "macos")]
fn macos_release(&self) -> (String, String) {
self.inner.macos_release()
}
fn library(&mut self, source: &ShaderSource<'_>) -> Answer<Handle> {
let _span = self.watch("library");
self.inner.library(source)
@@ -795,6 +800,15 @@ impl<S: Side, W: Watcher> Side for Watching<S, W> {
self.inner.empty_command_buffers()
}
fn managed_naming(
&mut self,
way: crate::managed_naming::Way,
libraries: crate::managed_naming::Libraries,
) -> Answer<Vec<u8>> {
let _span = self.watch("managed_naming");
self.inner.managed_naming(way, libraries)
}
fn sparse_tile_size_in_bytes(&mut self, page: crate::sparse_query::QueryPage) -> Answer<u64> {
let _span = self.watch("sparse_tile_size_in_bytes");
self.inner.sparse_tile_size_in_bytes(page)
+3 -11
View File
@@ -61,19 +61,12 @@ pub const THREAD_COUNTS: [u32; 2] = [32, 64];
pub struct Target {
/// Threads in the dispatch's one threadgroup, one of [`THREAD_COUNTS`].
pub threads: u32,
/// Whether the device reaches buffers by device address (Profile A): a pointer loaded from a
/// buffer can be dereferenced. Without it the engine refuses such a program as
/// `Unsupported{DereferenceLoadedPointer}`, honestly, so no generator builds one.
pub addressed: bool,
}
impl Default for Target {
/// [`THREADS`] threads on a device with device addresses.
/// [`THREADS`] threads.
fn default() -> Target {
Target {
threads: THREADS,
addressed: true,
}
Target { threads: THREADS }
}
}
@@ -81,8 +74,7 @@ impl Default for Target {
/// index the generators build is a small non-negative `i32`, so the three spellings name the same
/// element; they reach different index forms of the engine (a zero-extended word, a
/// sign-extended word, and an `i32` index the GEP itself extends), and [`IndexForm::Narrow32`]
/// programs compute no 64-bit index or offset, which a profile without `shaderInt64` (`vk12-floor`)
/// runs without two-word emulation.
/// programs compute no 64-bit index or offset.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IndexForm {
/// `zext i32 %v to i64`, the Metal front end's spelling of an unsigned index.
@@ -20,14 +20,11 @@
//! **parked** form, between the same roots stored into and loaded back from a private aggregate
//! (private pointer cells); and, in the **loaded** form, between wide pointers whose roots are
//! LOADED from a pointer table ([`Input::Addresses`]: the guest addresses of the three buffers), so
//! every choice, GEP, and access goes through the resident-set search and the root table, and a
//! lookup that missed would be counted and fail the run. The loaded form is built only for a
//! [`Target`] with device addresses (Profile A): without them the engine refuses a loaded
//! pointer's dereference, honestly. Every form may take the nullable choice.
//! every choice, GEP, and access goes through the device address the pointer holds. Every form may
//! take the nullable choice.
use super::{
air_header, kernel_metadata_written, Execute, IndexForm, Input, Kernel, Report, Target,
Xorshift, OPS,
air_header, kernel_metadata_written, Execute, IndexForm, Input, Kernel, Report, Xorshift, OPS,
};
/// The index mask the generated program applies. A power of two, so the mask is exact.
@@ -99,7 +96,7 @@ struct Program {
}
impl Program {
fn generate(seed: u64, target: Target, form: IndexForm) -> Self {
fn generate(seed: u64, form: IndexForm) -> Self {
let mut rng = Xorshift(seed | 1);
let steps = (0..STEPS)
.map(|_| {
@@ -130,7 +127,7 @@ impl Program {
// program are the same whichever form it takes.
let roots = match indirect {
false => Roots::Params,
true if target.addressed && rng.below(2) == 1 => Roots::Loaded,
true if rng.below(2) == 1 => Roots::Loaded,
true => Roots::Parked,
};
Program {
@@ -412,7 +409,7 @@ pub fn check(executor: &mut dyn Execute, seeds: std::ops::RangeInclusive<u64>) -
let mut report = Report::default();
for seed in seeds {
let form = IndexForm::of(seed);
let program = Program::generate(seed.wrapping_mul(0x9e3779b97f4a7c15), target, form);
let program = Program::generate(seed.wrapping_mul(0x9e3779b97f4a7c15), form);
let mut want: Vec<u32> = fill
.as_chunks::<4>()
.0
@@ -477,37 +474,23 @@ pub fn check(executor: &mut dyn Execute, seeds: std::ops::RangeInclusive<u64>) -
mod tests {
use super::*;
/// The engine's programs take every root form over the gate seeds, the loaded form only
/// on a device with device addresses, and nullable choices in all of them.
/// The engine's programs take every root form over the gate seeds, and nullable choices in
/// all of them.
#[test]
fn the_engine_programs_cover_every_root_form_the_device_can_run() {
let program = |seed: u64, target: Target| {
Program::generate(
seed.wrapping_mul(0x9e3779b97f4a7c15),
target,
IndexForm::Zext64,
)
};
let count = |target: Target| {
let mut counts = [0usize; 3];
for seed in crate::fuzz::GATE_SEEDS {
counts[program(seed, target).roots as usize] += 1;
}
counts
};
let addressed = count(Target::default());
assert!(addressed.iter().all(|&n| n > 0), "{addressed:?}");
fn the_engine_programs_cover_every_root_form() {
let program =
|seed: u64| Program::generate(seed.wrapping_mul(0x9e3779b97f4a7c15), IndexForm::Zext64);
let mut counts = [0usize; 3];
for seed in crate::fuzz::GATE_SEEDS {
counts[program(seed).roots as usize] += 1;
}
assert!(counts.iter().all(|&n| n > 0), "{counts:?}");
let nullable = crate::fuzz::GATE_SEEDS
.filter(|&seed| {
let p = program(seed, Target::default());
let p = program(seed);
p.roots != Roots::Params && p.steps.iter().any(|s| s.nullable && !s.phi)
})
.count();
assert!(nullable > 0);
let floor = count(Target {
addressed: false,
..Target::default()
});
assert!(floor[Roots::Loaded as usize] == 0 && floor[Roots::Parked as usize] > 0);
}
}
@@ -0,0 +1,483 @@
//! The authored kernels (inline AIR text, for `llvm-as`) of Metal's `half` simdgroup sums and
//! products, and what Metal answers: the product's CPU-interpreter tests and the runtime's device
//! test both run them ([`module`]).
//!
//! Metal's `simd_sum` and `simd_product` of `half` operands are a tree of `half` operations: in
//! round `d` (1, 2, 4, 8, 16) each aligned block of `2d` lanes holds its lower and upper halves'
//! results combined and rounded to `half`, and a lane that takes no part counts as the operation's
//! identity. Measured on an M3 Max (macOS 27.0.1), fast math on and off alike, with our own MSL:
//! [`SUMS`] (potluck job m3-max-80839), [`PRODUCTS`] (m3-max-80879), and [`MASKED_SUMS`] and
//! [`MASKED_PRODUCTS`] (m3-max-80890). Each answer is that tree's on every vector; the `float`
//! result rounded once differs on five of the sums (`0x3c10` for `0x3c0f` on the first), four of
//! the products and ten of the 48 masked results, and the tree over the active lanes packed
//! together differs on three masked sums.
//!
//! - [`FULL`] (`half_simd_reductions`): one threadgroup of [`THREADS`] threads, eight
//! simdgroups. Thread `t` takes [`SUM_OPERANDS`] and [`PRODUCT_OPERANDS`] of its simdgroup
//! `t / 32` at its lane `t % 32` and writes `simd_sum`'s bits in the low half of its word and
//! `simd_product`'s in the high half ([`full`]).
//! - [`MASKED`] (`half_simd_reductions_masked`): one threadgroup of `3 * THREADS` threads. Thread
//! `t` takes [`SUM_OPERANDS`]'s value of thread `t % 256` and, where bit `lane` of
//! [`MASKS`]`[t / 256]` is set, writes the sum and the product of that operand over those lanes
//! as [`FULL`] does; every other thread writes `0xffff_ffff` ([`masked`]).
//! - [`QUADS`] (`half_quad_reductions`): one threadgroup of [`THREADS`] threads. Thread `t` takes
//! entry `t` of [`SUM_OPERANDS`] and of [`PRODUCT_OPERANDS`] and writes [`QUAD_WORDS`] words
//! ([`quads`]): its `quad_sum` and `quad_product`, its quad's inclusive and exclusive prefix sums,
//! its quad's inclusive and exclusive prefix products, and the same four prefix operations over
//! its simdgroup, each word a pair of `half` bits, low then high. Metal's quad answers are
//! `(x0 op x1) op (x2 op x3)` and the lane-order chain over the quad's lanes, each operation
//! rounded to `half`, the empty exclusive sum `-0` and product 1 (measured on all 256 threads,
//! fast math on and off: m3-max-81130; the `float` result rounded once differs on 48 of the quad
//! sums and 64 of the products). Metal's simdgroup prefix order is none this crate models (the
//! lane-order chain, the Hillis and Steele scan and the `float` result rounded once each differ
//! on 60 to 137 of the 256 threads), so [`quads`] does not answer those two words: they make
//! the kernel a simdgroup user, which a device whose subgroups are narrower than a simdgroup
//! runs on its emulated tier, quad operations included.
/// The full kernel.
pub const FULL: &str = "half_simd_reductions";
/// The masked kernel.
pub const MASKED: &str = "half_simd_reductions_masked";
/// The threads of [`FULL`]'s threadgroup: eight simdgroups.
pub const THREADS: u32 = 256;
/// The quad kernel.
pub const QUADS: &str = "half_quad_reductions";
/// The words each thread of [`QUADS`] writes.
pub const QUAD_WORDS: u32 = 5;
/// The `half` bits each simdgroup sums: a 1 among `2^-11`s (first and last lane), a cancellation,
/// `2048` and `-2048` among ones, and four vectors of mixed signs and exponents.
pub const SUM_OPERANDS: [[u16; 32]; 8] = [
[
0x3c00, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
],
[
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x3c00,
],
[
0x63d0, 0xe3d0, 0x63d0, 0xe3d0, 0x63d0, 0xe3d0, 0x63d1, 0xe3d0, 0x63d1, 0xe3d0, 0x63d1,
0xe3d0, 0x63d2, 0xe3d0, 0x63d2, 0xe3d0, 0x63d2, 0xe3d0, 0x63d2, 0xe3d0, 0x63d2, 0xe3d0,
0x63d3, 0xe3d0, 0x63d3, 0xe3d0, 0x63d3, 0xe3d0, 0x63d4, 0xe3d0, 0x63d4, 0xe3d0,
],
[
0x6800, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00,
0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0xe800, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00,
0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0x3c00,
],
[
0x4f70, 0xc411, 0x3994, 0xceaa, 0x307c, 0xceb6, 0x3477, 0xcd6b, 0x476a, 0xc795, 0x42b3,
0xb86f, 0x487b, 0xcd7d, 0x3c4e, 0xb9c2, 0x39e4, 0xc1b3, 0x47f8, 0xc841, 0x3fff, 0xc864,
0x42bd, 0xc983, 0x3076, 0xc013, 0x4eb4, 0xb6d3, 0x3476, 0xc80b, 0x48ae, 0xb519,
],
[
0x45e3, 0xbdcc, 0x30e8, 0xc7cb, 0x4b7f, 0xc580, 0x4ebb, 0xc6df, 0x3c21, 0xbd66, 0x3b48,
0xb3ba, 0x40e5, 0xc444, 0x372d, 0xb120, 0x3257, 0xbad7, 0x3f33, 0xc225, 0x34a7, 0xc045,
0x3bfe, 0xc019, 0x4ad9, 0xb989, 0x44bc, 0xcf7f, 0x4cf3, 0xc3e4, 0x40d7, 0xcff5,
],
[
0x3d2e, 0xb651, 0x48a3, 0xbf2b, 0x4026, 0xbdf0, 0x4511, 0xbecf, 0x340a, 0xb578, 0x325b,
0xc97d, 0x3acc, 0xbfa8, 0x4db7, 0xcab2, 0x4b53, 0xb0b5, 0x3605, 0xb9b9, 0x4da5, 0xbabc,
0x3382, 0xbb9b, 0x421e, 0xb130, 0x3e73, 0xc412, 0x479d, 0xbb4c, 0x38da, 0xc575,
],
[
0x40b2, 0xd980, 0x4f25, 0xc3ab, 0x47d1, 0xc1e6, 0x4bda, 0xc21a, 0x5a83, 0xdbad, 0x564e,
0xcc98, 0x3f90, 0xc18b, 0x504c, 0xcf58, 0x4c37, 0xd72d, 0x5ace, 0xbddd, 0x5057, 0xbda9,
0x55a8, 0xbce9, 0x45a3, 0xd6e9, 0x4238, 0xcb6c, 0x49d3, 0xbc21, 0x3d18, 0xca78,
],
];
/// Metal's `simd_sum` of each vector of [`SUM_OPERANDS`].
pub const SUMS: [u16; 8] = [
0x3c0f, 0x3c0f, 0x4b80, 0x4f40, 0xd238, 0xc57c, 0x51eb, 0x5124,
];
/// The `half` bits each simdgroup multiplies: `1 + 2^-10` in every lane, that and `1 - 2^-11` in
/// turn, three vectors of `1 + k 2^-10`, and three of magnitudes in `[0.75, 1.5)` of mixed signs.
pub const PRODUCT_OPERANDS: [[u16; 32]; 8] = [
[
0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01,
0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01,
0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01, 0x3c01,
],
[
0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01,
0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff,
0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff, 0x3c01, 0x3bff,
],
[
0x3c01, 0x3bfa, 0x3bf2, 0x3bf4, 0x3bf6, 0x3bfa, 0x3bf8, 0x3bf2, 0x3bf2, 0x3bfa, 0x3bf2,
0x3c05, 0x3bf4, 0x3c03, 0x3bf0, 0x3bf2, 0x3bf8, 0x3c01, 0x3c02, 0x3bf4, 0x3c06, 0x3c01,
0x3c07, 0x3c01, 0x3c08, 0x3c02, 0x3bf0, 0x3c04, 0x3bf6, 0x3c04, 0x3bf4, 0x3bfe,
],
[
0x3c06, 0x3c08, 0x3c04, 0x3c06, 0x3c07, 0x3c02, 0x3bfa, 0x3bfa, 0x3bf4, 0x3c06, 0x3c05,
0x3bf6, 0x3bf8, 0x3c04, 0x3bf6, 0x3bfe, 0x3c02, 0x3bfc, 0x3bf4, 0x3c07, 0x3bf6, 0x3c05,
0x3bfa, 0x3c05, 0x3c01, 0x3bf0, 0x3bf6, 0x3bf2, 0x3bf6, 0x3c07, 0x3c05, 0x3c05,
],
[
0x3c07, 0x3bf8, 0x3bfa, 0x3bf8, 0x3c00, 0x3c06, 0x3bf2, 0x3c06, 0x3bf6, 0x3bf0, 0x3c00,
0x3bfc, 0x3bf2, 0x3bf0, 0x3c07, 0x3c05, 0x3bf0, 0x3c02, 0x3c00, 0x3bfa, 0x3bf8, 0x3bf4,
0x3c06, 0x3bf2, 0x3c08, 0x3c06, 0x3bfa, 0x3bf6, 0x3c00, 0x3bfc, 0x3c08, 0x3c03,
],
[
0x3bb8, 0x3bd0, 0xbd43, 0xbccd, 0xba35, 0x3de2, 0xbc89, 0x3a23, 0xbaab, 0xbcbb, 0xba56,
0xbaf0, 0xbdcb, 0x3b88, 0x3ae4, 0x3c3a, 0xbcfd, 0xba91, 0x3c90, 0x3b0d, 0x3cc9, 0xbc15,
0x3ccf, 0xbda9, 0x3b6e, 0x3c3a, 0x3a1a, 0x3d68, 0x3b24, 0xbc11, 0xbd67, 0xbcb0,
],
[
0x3d3a, 0x3c7f, 0xbc34, 0xbc71, 0xbb70, 0x3c79, 0xbc35, 0x3cc6, 0xbb25, 0xbb95, 0xba13,
0xbc58, 0xbac1, 0x3d14, 0x3bcc, 0x3d04, 0xbb3f, 0xba28, 0x3b0b, 0x3b76, 0x3cc5, 0xba53,
0x3abc, 0xbca9, 0x3c95, 0x3a2d, 0x3d15, 0x3b33, 0x3b67, 0xbc07, 0xbd33, 0xbc98,
],
[
0x3c7b, 0x3dd1, 0xbc18, 0xbdd7, 0xba1b, 0x3c7e, 0xbd30, 0x3dd5, 0xbcac, 0xbc07, 0xbc65,
0xbdbd, 0xbd48, 0x3ac6, 0x3dd4, 0x3d0c, 0xbd58, 0xbb80, 0x3b84, 0x3d76, 0x3ced, 0xba1f,
0x3dd0, 0xbd0a, 0x3c04, 0x3cc6, 0x3c6d, 0x3b26, 0x3d1a, 0xbce0, 0xbc8d, 0xbc41,
],
];
/// Metal's `simd_product` of each vector of [`PRODUCT_OPERANDS`].
pub const PRODUCTS: [u16; 8] = [
0x3c20, 0x3c00, 0x3b8e, 0x3c11, 0x3bd3, 0x43b1, 0x3e11, 0x55cb,
];
/// The active lanes of [`MASKED`]'s three cases: the odd lanes, lanes 5 to 27 but 16, and lanes 0,
/// 15, 16 and 31.
pub const MASKS: [u32; 3] = [0xaaaa_aaaa, 0x0ffe_ffe0, 0x8001_8001];
/// Metal's `simd_sum` of each vector of [`SUM_OPERANDS`] over the lanes of each of [`MASKS`].
pub const MASKED_SUMS: [[u16; 8]; 3] = [
[
0x2000, 0x3c07, 0xf3d0, 0x4c00, 0xd8c1, 0xd663, 0xd1a8, 0xe1c8,
],
[
0x2180, 0x2180, 0xe7c6, 0x4d80, 0xd272, 0xc3d4, 0x4d19, 0x5933,
],
[
0x3c01, 0x3c01, 0x3c00, 0x3c00, 0x4f5d, 0xce7a, 0xc1d0, 0xcdc7,
],
];
/// Metal's `simd_product` of each vector of [`SUM_OPERANDS`] over the lanes of each of [`MASKS`].
pub const MASKED_PRODUCTS: [[u16; 8]; 3] = [
[
0x0000, 0x0000, 0x7c00, 0x3c00, 0x7c00, 0x7c00, 0x51f1, 0x7c00,
],
[
0x0000, 0x0000, 0x7c00, 0x3c00, 0x7c00, 0x7c00, 0x611c, 0x7c00,
],
[
0x0000, 0x0000, 0x7c00, 0xfc00, 0x4506, 0x45f2, 0x656a, 0x7358,
],
];
/// What thread `t` of [`FULL`] writes.
pub fn full(t: u32) -> u32 {
let v = (t / 32) as usize;
u32::from(SUMS[v]) | (u32::from(PRODUCTS[v]) << 16)
}
/// What thread `t` of [`MASKED`] writes.
pub fn masked(t: u32) -> u32 {
let (case, v, lane) = (
(t / THREADS) as usize,
((t % THREADS) / 32) as usize,
t % 32,
);
if (MASKS[case] >> lane) & 1 == 0 {
return 0xffff_ffff;
}
u32::from(MASKED_SUMS[case][v]) | (u32::from(MASKED_PRODUCTS[case][v]) << 16)
}
/// Metal's word `w` of [`QUADS`]' output (thread `w / QUAD_WORDS`), where this crate models it:
/// the quad's reductions and prefix operations, each `half` operation rounded; `None` for the
/// simdgroup prefix operations' two words.
pub fn quads(w: u32) -> Option<u32> {
let (t, k) = (w / QUAD_WORDS, w % QUAD_WORDS);
let operand = |table: &[[u16; 32]; 8], u: u32| table[(u / 32) as usize][(u % 32) as usize];
let base = t & !3;
let lanes = |table| (base..base + 4).map(move |u| value(operand(table, u)));
let tree = |table, op: Operation| {
let x: Vec<f64> = lanes(table).collect();
let (low, high) = (round(op(x[0], x[1])), round(op(x[2], x[3])));
round(op(value(low), value(high)))
};
// The lane-order chain over the quad's lanes below the thread's (and its own when
// `inclusive`), from the empty answer `empty`.
let chain = |table, op: Operation, empty: u16, inclusive: bool| {
let upto = (t - base) + u32::from(inclusive);
lanes(table)
.take(upto as usize)
.fold(empty, |acc, x| round(op(value(acc), x)))
};
let (add, mul): (Operation, Operation) = (|a, b| a + b, |a, b| a * b);
let pair = |low: u16, high: u16| u32::from(low) | (u32::from(high) << 16);
match k {
0 => Some(pair(tree(&SUM_OPERANDS, add), tree(&PRODUCT_OPERANDS, mul))),
1 => Some(pair(
chain(&SUM_OPERANDS, add, 0x8000, true),
chain(&SUM_OPERANDS, add, 0x8000, false),
)),
2 => Some(pair(
chain(&PRODUCT_OPERANDS, mul, 0x3c00, true),
chain(&PRODUCT_OPERANDS, mul, 0x3c00, false),
)),
_ => None,
}
}
/// [`QUADS`]' word `w` as `float` arithmetic rounded to `half` once gives it, where this crate
/// models it: each operation of [`quads`]' tree or lane-order chain in `f32` (the empty answers
/// `-0` and 1), and the result rounded to `half` at the end. The answer
/// `PrecisionNote::NativeHalfConversion` admits for a word fed by `half` arithmetic where a driver
/// computes the device's 16-bit operations in `float` (Intel's Windows driver 101.2145 on a UHD
/// Graphics 630: every half of these words Metal's or this one).
pub fn quads_once(w: u32) -> Option<u32> {
let (t, k) = (w / QUAD_WORDS, w % QUAD_WORDS);
let operand = |table: &[[u16; 32]; 8], u: u32| table[(u / 32) as usize][(u % 32) as usize];
let base = t & !3;
// A `half` is exact in `f32`.
let lanes = |table| (base..base + 4).map(move |u| value(operand(table, u)) as f32);
let tree = |table, op: FloatOperation| {
let x: Vec<f32> = lanes(table).collect();
round(f64::from(op(op(x[0], x[1]), op(x[2], x[3]))))
};
let chain = |table, op: FloatOperation, empty: f32, inclusive: bool| {
let upto = (t - base) + u32::from(inclusive);
round(f64::from(lanes(table).take(upto as usize).fold(empty, op)))
};
let (add, mul): (FloatOperation, FloatOperation) = (|a, b| a + b, |a, b| a * b);
let pair = |low: u16, high: u16| u32::from(low) | (u32::from(high) << 16);
match k {
0 => Some(pair(tree(&SUM_OPERANDS, add), tree(&PRODUCT_OPERANDS, mul))),
1 => Some(pair(
chain(&SUM_OPERANDS, add, -0.0, true),
chain(&SUM_OPERANDS, add, -0.0, false),
)),
2 => Some(pair(
chain(&PRODUCT_OPERANDS, mul, 1.0, true),
chain(&PRODUCT_OPERANDS, mul, 1.0, false),
)),
_ => None,
}
}
/// A `half` operation of the model, on the operands' exact values.
type Operation = fn(f64, f64) -> f64;
/// A `float` operation of [`quads_once`], rounded to `f32`.
type FloatOperation = fn(f32, f32) -> f32;
/// The value of the `half` bits `h`.
fn value(h: u16) -> f64 {
let sign = if h & 0x8000 == 0 { 1.0 } else { -1.0 };
let (e, m) = (i32::from((h >> 10) & 0x1f), f64::from(h & 0x3ff));
sign * match e {
0 => m * 2f64.powi(-24),
31 if m == 0.0 => f64::INFINITY,
31 => f64::NAN,
e => (1024.0 + m) * 2f64.powi(e - 25),
}
}
/// The bits of the `half` nearest `x`, ties to even, where `x` is exact in `f64` (a sum or product
/// of two `half` values is): a magnitude from 65520 up is the infinity of its sign.
fn round(x: f64) -> u16 {
let sign = if x.is_sign_negative() { 0x8000 } else { 0 };
let a = x.abs();
if a.is_nan() {
return 0x7e00;
}
if a == 0.0 {
return sign;
}
if a >= 65520.0 {
return sign | 0x7c00;
}
// The binade's exponent, no lower than the smallest normal's: a `half` there is a multiple of
// `2^(e - 10)`.
let binade = i32::try_from((a.to_bits() >> 52) & 0x7ff).unwrap_or(0) - 1023;
let e = binade.max(-14);
let units = (a * 2f64.powi(10 - e)).round_ties_even();
let (e, units) = if units >= 2048.0 {
(e + 1, units / 2.0)
} else {
(e, units)
};
let units = units as u16;
if units < 1024 {
// A denormal (or zero): the units are its bits.
return sign | units;
}
let biased = u16::try_from(e + 15).unwrap_or(31);
if biased >= 31 {
return sign | 0x7c00;
}
sign | (biased << 10) | (units - 1024)
}
/// A table of `half` bits as an AIR constant array.
fn halves(table: &[[u16; 32]; 8]) -> String {
let cells: Vec<String> = table
.iter()
.flatten()
.map(|h| format!("half 0xH{h:04X}"))
.collect();
format!("[256 x half] [{}]", cells.join(", "))
}
/// [`QUADS`]' definition: ten operations on the thread's two operands, packed two to a word.
fn quads_function() -> String {
const CALLS: [(&str, &str); 10] = [
("quad_sum", "x"),
("quad_product", "y"),
("quad_prefix_inclusive_sum", "x"),
("quad_prefix_exclusive_sum", "x"),
("quad_prefix_inclusive_product", "y"),
("quad_prefix_exclusive_product", "y"),
("simd_prefix_inclusive_sum", "x"),
("simd_prefix_exclusive_sum", "x"),
("simd_prefix_inclusive_product", "y"),
("simd_prefix_exclusive_product", "y"),
];
let mut body = format!(
"define void @{QUADS}(ptr addrspace(1) noundef \"air-buffer-no-alias\" %out, i32 noundef %t) #0 {{\n\
%i = zext i32 %t to i64\n\
%px = getelementptr inbounds [256 x half], ptr addrspace(2) @sum_operands, i64 0, i64 %i\n\
%x = load half, ptr addrspace(2) %px, align 2\n\
%py = getelementptr inbounds [256 x half], ptr addrspace(2) @product_operands, i64 0, i64 %i\n\
%y = load half, ptr addrspace(2) %py, align 2\n\
%base = mul i64 %i, {QUAD_WORDS}\n"
);
for (n, (op, operand)) in CALLS.iter().enumerate() {
body.push_str(&format!(
" %r{n} = tail call half @air.{op}.f16(half %{operand}) #1\n\
%b{n} = bitcast half %r{n} to i16\n\
%z{n} = zext i16 %b{n} to i32\n"
));
}
for k in 0..CALLS.len() / 2 {
let (low, high) = (2 * k, 2 * k + 1);
body.push_str(&format!(
" %h{k} = shl i32 %z{high}, 16\n\
%w{k} = or i32 %z{low}, %h{k}\n\
%at{k} = add i64 %base, {k}\n\
%o{k} = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %at{k}\n\
store i32 %w{k}, ptr addrspace(1) %o{k}, align 4\n"
));
}
body.push_str(" ret void\n}\n\n");
for (op, _) in CALLS {
body.push_str(&format!("declare half @air.{op}.f16(half) #1\n"));
}
body
}
/// The module holding [`FULL`], [`MASKED`] and [`QUADS`].
pub fn module() -> String {
let masks: Vec<String> = MASKS.iter().map(|m| format!("i32 {}", *m as i32)).collect();
format!(
r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
target triple = "air64_v28-apple-macosx26.0.0"
@sum_operands = internal addrspace(2) constant {sums}, align 2
@product_operands = internal addrspace(2) constant {products}, align 2
@masks = internal addrspace(2) constant [3 x i32] [{masks}], align 4
define void @{FULL}(ptr addrspace(1) noundef "air-buffer-no-alias" %out, i32 noundef %t) #0 {{
%i = zext i32 %t to i64
%px = getelementptr inbounds [256 x half], ptr addrspace(2) @sum_operands, i64 0, i64 %i
%x = load half, ptr addrspace(2) %px, align 2
%py = getelementptr inbounds [256 x half], ptr addrspace(2) @product_operands, i64 0, i64 %i
%y = load half, ptr addrspace(2) %py, align 2
%s = tail call half @air.simd_sum.f16(half %x) #1
%p = tail call half @air.simd_product.f16(half %y) #1
%sb = bitcast half %s to i16
%pb = bitcast half %p to i16
%sw = zext i16 %sb to i32
%pw = zext i16 %pb to i32
%ph = shl i32 %pw, 16
%w = or i32 %sw, %ph
%o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %i
store i32 %w, ptr addrspace(1) %o, align 4
ret void
}}
define void @{MASKED}(ptr addrspace(1) noundef "air-buffer-no-alias" %out, i32 noundef %t, i32 noundef %lane) #0 {{
entry:
%i = zext i32 %t to i64
%v = and i32 %t, 255
%vi = zext i32 %v to i64
%px = getelementptr inbounds [256 x half], ptr addrspace(2) @sum_operands, i64 0, i64 %vi
%x = load half, ptr addrspace(2) %px, align 2
%case = lshr i32 %t, 8
%ci = zext i32 %case to i64
%pm = getelementptr inbounds [3 x i32], ptr addrspace(2) @masks, i64 0, i64 %ci
%m = load i32, ptr addrspace(2) %pm, align 4
%shifted = lshr i32 %m, %lane
%bit = and i32 %shifted, 1
%on = icmp ne i32 %bit, 0
br i1 %on, label %active, label %done
active:
%s = tail call half @air.simd_sum.f16(half %x) #1
%p = tail call half @air.simd_product.f16(half %x) #1
%sb = bitcast half %s to i16
%pb = bitcast half %p to i16
%sw = zext i16 %sb to i32
%pw = zext i16 %pb to i32
%ph = shl i32 %pw, 16
%w = or i32 %sw, %ph
br label %done
done:
%r = phi i32 [ %w, %active ], [ -1, %entry ]
%o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %i
store i32 %r, ptr addrspace(1) %o, align 4
ret void
}}
declare half @air.simd_sum.f16(half) #1
declare half @air.simd_product.f16(half) #1
{quads}
attributes #0 = {{ convergent mustprogress nounwind willreturn }}
attributes #1 = {{ convergent mustprogress nounwind willreturn }}
!llvm.module.flags = !{{!0, !1, !2, !3, !4, !5, !6, !7, !8}}
!air.kernel = !{{!9, !21, !23}}
!air.version = !{{!19}}
!air.language_version = !{{!20}}
!0 = !{{i32 2, !"SDK Version", [2 x i32] [i32 26, i32 5]}}
!1 = !{{i32 1, !"wchar_size", i32 4}}
!2 = !{{i32 7, !"frame-pointer", i32 2}}
!3 = !{{i32 7, !"air.max_device_buffers", i32 31}}
!4 = !{{i32 7, !"air.max_constant_buffers", i32 31}}
!5 = !{{i32 7, !"air.max_threadgroup_buffers", i32 31}}
!6 = !{{i32 7, !"air.max_textures", i32 128}}
!7 = !{{i32 7, !"air.max_read_write_textures", i32 8}}
!8 = !{{i32 7, !"air.max_samplers", i32 16}}
!9 = !{{ptr @{FULL}, !10, !11}}
!10 = !{{}}
!11 = !{{!12, !13}}
!12 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}}
!13 = !{{i32 1, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"}}
!14 = !{{i32 2, !"air.thread_index_in_simdgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"lane"}}
!19 = !{{i32 2, i32 8, i32 0}}
!20 = !{{!"Metal", i32 4, i32 0, i32 0}}
!21 = !{{ptr @{MASKED}, !10, !22}}
!22 = !{{!12, !13, !14}}
!23 = !{{ptr @{QUADS}, !10, !11}}
"#,
sums = halves(&SUM_OPERANDS),
products = halves(&PRODUCT_OPERANDS),
masks = masks.join(", "),
quads = quads_function(),
)
}
+4 -1
View File
@@ -10,7 +10,9 @@
//! both run ([`loop_kernels`]), the inputs and answer of the vector word-phase fixture the product's
//! interpreter test, the runtime's device test and the conformance suite all hold
//! ([`vector_word_phases`]), the dispatches and answer of the threadgroup-memory fixture the
//! runtime's device test and the conformance suite both hold ([`threadgroup_start`]), and the
//! runtime's device test and the conformance suite both hold ([`threadgroup_start`]), the `half`
//! simdgroup sums and products and Metal's answers to them, which the product's interpreter tests
//! and the runtime's device test both run ([`half_simd_reductions`]), and the
//! counter of a thread's user-space instructions the matrix's
//! instructions-per-draw records are measured with ([`instructions`]).
//!
@@ -32,6 +34,7 @@ use std::path::{Path, PathBuf};
use std::process::Stdio;
pub mod fuzz;
pub mod half_simd_reductions;
pub mod instructions;
pub mod linked_signatures;
pub mod litmus;
+1 -1
View File
@@ -85,7 +85,7 @@ pub fn metallib_2_2(functions: &[MtlbFunction<'_>]) -> Vec<u8> {
write(functions, &MtlbLinkage::default(), 0, Format::V2_2)
}
/// The container layout [`write`] writes.
/// The container layout [`write()`] writes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Format {
/// Today's toolchain's: format 2.9, `MDSZ` in every entry, an extended header.
+400 -3
View File
@@ -4,7 +4,7 @@
use crate::plan::{
seeded_words as words, Binding, BufferPlan, Constant, Dispatch, Expect, Filter, Grid, Plan,
SamplerPlan, Scaled, Source, TextureExpect, TexturePlan, Values,
SamplerPlan, Scaled, Source, TextureExpect, TexturePlan, TextureSource, Values,
};
use crate::{Result, Storage};
use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage};
@@ -21,7 +21,7 @@ pub struct Workload {
}
/// The authored workloads.
pub const WORKLOADS: [Workload; 40] = [
pub const WORKLOADS: [Workload; 53] = [
Workload {
name: "bandwidth",
plan: bandwidth,
@@ -150,6 +150,30 @@ pub const WORKLOADS: [Workload; 40] = [
name: "vote_loop",
plan: vote_loop,
},
Workload {
name: "row_tail_224",
plan: row_tail_224,
},
Workload {
name: "row_tail_27730",
plan: row_tail_27730,
},
Workload {
name: "row_tail_49",
plan: row_tail_49,
},
Workload {
name: "row_tail_224_private",
plan: row_tail_224_private,
},
Workload {
name: "row_tail_27730_private",
plan: row_tail_27730_private,
},
Workload {
name: "row_tail_49_private",
plan: row_tail_49_private,
},
Workload {
name: "constant_managed",
plan: constant_managed,
@@ -182,6 +206,34 @@ pub const WORKLOADS: [Workload; 40] = [
name: "bind_2000",
plan: bind_2000,
},
Workload {
name: "texel_buffer_r8_write",
plan: texel_buffer_r8_write,
},
Workload {
name: "texel_buffer_r8_read",
plan: texel_buffer_r8_read,
},
Workload {
name: "texel_buffer_r16_read",
plan: texel_buffer_r16_read,
},
Workload {
name: "texel_buffer_rgba16_read",
plan: texel_buffer_rgba16_read,
},
Workload {
name: "texel_buffer_bgra8_read",
plan: texel_buffer_bgra8_read,
},
Workload {
name: "texel_buffer_b5g6r5_write",
plan: texel_buffer_b5g6r5_write,
},
Workload {
name: "texel_buffer_b5g6r5_read",
plan: texel_buffer_b5g6r5_read,
},
];
/// A creation workload: objects of one kind made and released in turn (`Session::create`).
@@ -286,10 +338,39 @@ pub enum OwnRow {
/// command buffers held for room (`Metrics::held_for_room`). Every command buffer is to complete, and
/// each of B's to end after its signaller, or the row fails.
TwoQueues,
/// The kinds a long-running VM makes and releases all day, made and released together in each
/// of 200 iterations: a host memory import with a buffer over it, an exported block with a
/// buffer over it, a video surface of each decoder route the device exports (a dma-buf at the
/// VA-API layout, the host's opaque handle at NVIDIA's), as the replay player's video
/// surfaces are made, with a view of each plane at an index, its buffer and plane 0 kept past
/// the surface's release, as an exported surface's plane outlives it; a two-plane `RGBA8Unorm`
/// surface of the opaque handle whose plane 0 a pass renders beside another colour attachment
/// (a plane stand-in, where the device takes the plane as a linear colour attachment only in
/// a pass of planes alone); two render pipeline states; and two targets a pass each draws
/// into, then reads through a texture after a memory barrier, a Private one (an attachment
/// view, and a shadow on a device without the attachment feedback loop) and one over a Shared
/// buffer (a shadow where the device's linear image takes it in place, an image of no feedback
/// usage). Its gauges ([`OwnReport::gauges`]) are read settled after the 100th and the 200th
/// iterations, and after its device drops.
///
/// [`OwnReport::gauges`]: crate::run::OwnReport::gauges
ChurnAllDay,
/// The other kinds a program makes, made and released together in each of 200 iterations: a
/// compute pipeline state of one of 40 contents in turn, more than the device keeps stage
/// entries for; a pass that draws under a `Counting` visibility mode into a target of 4
/// samples and resolves it into a texture over a Shared buffer (a resolve image, where the
/// device's linear image of the texture takes no attachment usage); a texture over a buffer in
/// an exported block, which the device holds in an image of its own, read by a blit; a texture
/// in a heap of a Shared block, read by a blit, where the device places one; and an indirect
/// command buffer, executed whole in a pass of its own with a state made for indirect command
/// buffers, its commands as the commit resets them (each drawing nothing).
/// Its gauges, with the bytes of the preprocess regions the executions hold, are read as
/// [`ChurnAllDay`](Self::ChurnAllDay)'s are.
ChurnRest,
}
/// The rows of one runtime's own.
pub const OWN_ROWS: [Own; 5] = [
pub const OWN_ROWS: [Own; 7] = [
Own {
name: "idle_frees",
row: OwnRow::IdleFrees,
@@ -310,6 +391,14 @@ pub const OWN_ROWS: [Own; 5] = [
name: "two_queues",
row: OwnRow::TwoQueues,
},
Own {
name: "churn_all_day",
row: OwnRow::ChurnAllDay,
},
Own {
name: "churn_rest",
row: OwnRow::ChurnRest,
},
];
/// The kernel of a compute pipeline state row's warm-up
@@ -381,6 +470,13 @@ pub fn render_library_air() -> Result<Vec<u8>> {
assemble("examples/runtime_examples.ll")
}
/// The indirect command buffers' library's AIR bitcode: the owned fixture
/// `engine/icb_merged_indexed.ll`, whose `icb_indexed_vertex` and `icb_indexed_fragment` draw
/// the commands a kernel encodes, assembled by `llvm-as`.
pub fn icb_library_air() -> Result<Vec<u8>> {
assemble("engine/icb_merged_indexed.ll")
}
/// The public fixture at `file`, LLVM text, assembled by `llvm-as`.
fn assemble(file: &str) -> Result<Vec<u8>> {
let ll = metal2vulkan_devtools::fixtures_dir().join(file);
@@ -1178,6 +1274,106 @@ fn vote_loop() -> Plan {
}
}
/// Rows of 224 `float`s into a `Shared` buffer, four a thread (`row_tail`): every row starts at a
/// multiple of 16 bytes, and every thread writes four.
fn row_tail_224() -> Plan {
row_tail("row_tail_224", 224, Storage::Shared, 1)
}
/// Rows of 27,730 `float`s (2 mod 4) into a `Shared` buffer, four a thread (`row_tail`): every
/// other row starts at a multiple of 16 bytes, the others 8 past one, and a row's last thread
/// writes two.
fn row_tail_27730() -> Plan {
row_tail("row_tail_27730", 27_730, Storage::Shared, 1)
}
/// Rows of 49 `float`s into a `Shared` buffer, four a thread (`row_tail`): one row in four starts at
/// a multiple of 16 bytes, and a row's last thread writes one.
fn row_tail_49() -> Plan {
row_tail("row_tail_49", 49, Storage::Shared, 1)
}
/// [`row_tail_224`] into a `Private` buffer, 16 times the threads.
fn row_tail_224_private() -> Plan {
row_tail("row_tail_224_private", 224, Storage::Private, 16)
}
/// [`row_tail_27730`] into a `Private` buffer, 16 times the threads.
fn row_tail_27730_private() -> Plan {
row_tail("row_tail_27730_private", 27_730, Storage::Private, 16)
}
/// [`row_tail_49`] into a `Private` buffer, 16 times the threads.
fn row_tail_49_private() -> Plan {
row_tail("row_tail_49_private", 49, Storage::Private, 16)
}
/// `row_tail` over rows of `w` `float`s: about 381,000 threads times `scale` in threadgroups of
/// 1,024, as many rows as `ceil(w / 4)` threads a row make of them, each thread reading a `float4`
/// of a `Private` buffer and writing its lanes from column `4 (i mod threads a row)` of its row of
/// a buffer of `storage` and about 6.1 MB times `scale` that nothing else writes: the first lane,
/// then the three, two or one more the row holds.
fn row_tail(name: &str, w: u32, storage: Storage, scale: u32) -> Plan {
const THREADS: u32 = 381_952;
let per_row = w.div_ceil(4);
let rows = scale * THREADS / per_row;
let threads = rows * per_row;
let input: Vec<f32> = (words(15, 4 * threads as usize).into_iter())
.map(|word| (word & 0xFFFF) as f32)
.collect();
let mut output = vec![0u32; (rows * w) as usize];
for index in 0..threads {
let (row, col) = (index / per_row, (index % per_row) << 2);
let lanes = (w - col).min(4) as usize;
let at = (row * w + col) as usize;
let from = 4 * index as usize;
for lane in 0..lanes {
output[at + lane] = input[from + lane].to_bits();
}
}
let length = (4 * u64::from(rows * w)).next_multiple_of(16);
Plan {
name: name.to_owned(),
library: Source::Authored,
buffers: vec![
private(float_bytes(&input)),
BufferPlan {
length,
storage,
contents: None,
modified: None,
},
],
dispatches: vec![Dispatch {
blits: Vec::new(),
function: "row_tail".to_owned(),
linked: Vec::new(),
constants: Vec::new(),
bindings: vec![
buffer(0, 0),
buffer(1, 1),
bytes(2, word_bytes(&[w, per_row])),
],
grid: Grid::Threads {
threads: [u64::from(threads), 1, 1],
per_group: [1024, 1, 1],
},
}],
expect: vec![Expect {
buffer: 1,
values: Values::Words(output),
}],
textures: Vec::new(),
expect_textures: Vec::new(),
outputs: Vec::new(),
per_command_buffer: None,
per_encoder: None,
commit_to_complete: false,
frames: false,
scaled: None,
}
}
/// Reads of a 64 KiB table as constants (`constant_reads`): 2^20 threads in threadgroups of 256,
/// each folding 64 of the table's 4,096 entries into a word, the table `Managed`, and the first
/// 256 bytes of it written again by the CPU before each run and marked with `didModifyRange:`, as
@@ -1683,3 +1879,204 @@ fn texture_read() -> Plan {
scaled: None,
}
}
/// The texels of the texel-buffer workloads: 2^24, one a thread for a write and 16 a thread for a
/// read.
const TEXEL_BUFFER_TEXELS: u32 = 1 << 24;
/// A texture buffer (`MTLTextureTypeTextureBuffer`) of `pixel_format` and `usage` over the plan's
/// buffer 0, of [`TEXEL_BUFFER_TEXELS`] texels.
fn texel_buffer(pixel_format: PixelFormat, usage: TextureUsage) -> TexturePlan {
TexturePlan {
texture_type: TextureType::TextureBuffer,
pixel_format,
width: TEXEL_BUFFER_TEXELS,
height: 1,
array_length: 1,
sample_count: 1,
usage,
storage: Storage::Private,
source: TextureSource::Buffer { buffer: 0 },
texels: None,
bytes: None,
}
}
/// Writes of an `R8Unorm` texture buffer, one texel a thread (`texel_buffer_write`): each texel
/// the code its index's hash names, which its value `c / 255` stores. Where a device holds the
/// format's texels four to a word, neighbouring threads write one word.
fn texel_buffer_r8_write() -> Plan {
let codes: Vec<u8> = (0..TEXEL_BUFFER_TEXELS).map(texel_buffer_code).collect();
let stored = (codes.chunks(4))
.map(|word| u32::from_le_bytes([word[0], word[1], word[2], word[3]]))
.collect();
texel_buffer_write("texel_buffer_r8_write", PixelFormat::R8Unorm, stored)
}
/// The code `texel_buffer_write` writes at texel `i`: its index's hash.
fn texel_buffer_code(i: u32) -> u8 {
(i.wrapping_mul(2_654_435_761) >> 24) as u8
}
/// Writes of a `B5G6R5Unorm` texture buffer, one texel a thread (`texel_buffer_write`): each
/// texel's red, green and blue the value `c / 255` of its index's code `c` (the kernel's `float`
/// product of `c` and `1 / 255`), each channel of `n` bits its value times `2^n - 1` rounded to
/// nearest even, as Metal writes a normalized channel. A device that holds the format as words
/// writes two texels to a word, each by two atomics; one that holds it directly, its own view.
fn texel_buffer_b5g6r5_write() -> Plan {
let texels: Vec<u16> = (0..TEXEL_BUFFER_TEXELS)
.map(|i| {
let value = f64::from(f32::from(texel_buffer_code(i)) * (1.0f32 / 255.0f32));
let code = |bits: u32| (value * f64::from((1u32 << bits) - 1)).round_ties_even() as u16;
code(5) << 11 | code(6) << 5 | code(5)
})
.collect();
let stored = (texels.chunks(2))
.map(|pair| u32::from(pair[0]) | u32::from(pair[1]) << 16)
.collect();
texel_buffer_write(
"texel_buffer_b5g6r5_write",
PixelFormat::B5G6R5Unorm,
stored,
)
}
/// Writes of a texture buffer of `pixel_format` (`texel_buffer_write`), whose bytes, as words,
/// are `stored`.
fn texel_buffer_write(name: &str, pixel_format: PixelFormat, stored: Vec<u32>) -> Plan {
let bytes = crate::plan::element_bytes(pixel_format).unwrap_or(4);
Plan {
name: name.to_owned(),
library: Source::Authored,
buffers: vec![unset(u64::from(TEXEL_BUFFER_TEXELS) * u64::from(bytes))],
textures: vec![texel_buffer(pixel_format, TextureUsage::SHADER_WRITE)],
dispatches: vec![Dispatch {
blits: Vec::new(),
function: "texel_buffer_write".to_owned(),
linked: Vec::new(),
constants: Vec::new(),
bindings: vec![texture(0, 0)],
grid: Grid::groups_of_256(u64::from(TEXEL_BUFFER_TEXELS / 256)),
}],
expect: vec![Expect {
buffer: 0,
values: Values::Words(stored),
}],
expect_textures: Vec::new(),
outputs: Vec::new(),
per_command_buffer: None,
per_encoder: None,
commit_to_complete: false,
frames: false,
scaled: None,
}
}
/// [`texel_buffer_read`] of `R8Unorm`.
fn texel_buffer_r8_read() -> Plan {
texel_buffer_read("texel_buffer_r8_read", PixelFormat::R8Unorm)
}
/// [`texel_buffer_read`] of `R16Unorm`.
fn texel_buffer_r16_read() -> Plan {
texel_buffer_read("texel_buffer_r16_read", PixelFormat::R16Unorm)
}
/// [`texel_buffer_read`] of `RGBA16Unorm`.
fn texel_buffer_rgba16_read() -> Plan {
texel_buffer_read("texel_buffer_rgba16_read", PixelFormat::RGBA16Unorm)
}
/// [`texel_buffer_read`] of `BGRA8Unorm`.
fn texel_buffer_bgra8_read() -> Plan {
texel_buffer_read("texel_buffer_bgra8_read", PixelFormat::BGRA8Unorm)
}
/// [`texel_buffer_read`] of `B5G6R5Unorm`.
fn texel_buffer_b5g6r5_read() -> Plan {
texel_buffer_read("texel_buffer_b5g6r5_read", PixelFormat::B5G6R5Unorm)
}
/// Reads of a texture buffer of `pixel_format` (`R8Unorm`, `R16Unorm`, `RGBA16Unorm`,
/// `BGRA8Unorm` or `B5G6R5Unorm`), 16 texels a thread (`texel_buffer_sum16`), of seeded bytes: each thread's sum of
/// its texels' lanes, against the CPU's decode of the bytes (`c / (2^n - 1)` a channel, 1 for a
/// missing alpha).
fn texel_buffer_read(name: &str, pixel_format: PixelFormat) -> Plan {
let bytes = crate::plan::element_bytes(pixel_format).unwrap_or(4) as usize;
let length = TEXEL_BUFFER_TEXELS as usize * bytes;
let data: Vec<u8> = (words(29, length / 4).into_iter())
.flat_map(u32::to_le_bytes)
.collect();
let channels = |texel: &[u8]| -> [f64; 4] {
let u16_at = |i: usize| f64::from(u16::from_le_bytes([texel[2 * i], texel[2 * i + 1]]));
match pixel_format {
PixelFormat::R8Unorm => [f64::from(texel[0]) / 255.0, 0.0, 0.0, 1.0],
PixelFormat::R16Unorm => [u16_at(0) / 65535.0, 0.0, 0.0, 1.0],
PixelFormat::RGBA16Unorm => [0, 1, 2, 3].map(|i| u16_at(i) / 65535.0),
// Red in bits 11 to 15, green in 5 to 10, blue in 0 to 4.
PixelFormat::B5G6R5Unorm => {
let t = u16_at(0) as u32;
let field = |shift: u32, bits: u32| {
let max = (1u32 << bits) - 1;
f64::from(t >> shift & max) / f64::from(max)
};
[field(11, 5), field(5, 6), field(0, 5), 1.0]
}
// Blue, green, red, alpha in memory.
_ => [2, 1, 0, 3].map(|i| f64::from(texel[i]) / 255.0),
}
};
let sums: Vec<f32> = (data.chunks(16 * bytes))
.map(|texels| {
let total: f64 = texels.chunks(bytes).flat_map(channels).sum();
total as f32
})
.collect();
Plan {
name: name.to_owned(),
library: Source::Authored,
buffers: vec![
private(data),
unset(4 * u64::from(TEXEL_BUFFER_TEXELS / 16)),
],
textures: vec![texel_buffer(pixel_format, TextureUsage::SHADER_READ)],
dispatches: vec![Dispatch {
blits: Vec::new(),
function: "texel_buffer_sum16".to_owned(),
linked: Vec::new(),
constants: Vec::new(),
bindings: vec![texture(0, 0), buffer(0, 1)],
grid: Grid::groups_of_256(u64::from(TEXEL_BUFFER_TEXELS / 16 / 256)),
}],
expect: vec![Expect {
buffer: 1,
values: Values::Floats {
values: sums,
tolerance: TEXEL_BUFFER_TOLERANCE + 16.0 * narrow_channels(pixel_format),
},
}],
expect_textures: Vec::new(),
outputs: Vec::new(),
per_command_buffer: None,
per_encoder: None,
commit_to_complete: false,
frames: false,
scaled: None,
}
}
/// How far a texel-buffer read's sum may be from the CPU's: 64 values of at most 1, summed in
/// `float` in the kernel's order.
const TEXEL_BUFFER_TOLERANCE: f32 = 1.0 / 1024.0;
/// How far a texel of `pixel_format` read through its own view may be from the CPU's in all its
/// channels together: `PrecisionNote::DeviceTexelConversion`'s recorded bound (docs/API.md), 0.18
/// of a code for each 5- or 6-bit channel, which a device that widens it by replicating its bits
/// reaches (ANV, NVIDIA); an 8- or 16-bit code's one `f32` ulp is inside
/// [`TEXEL_BUFFER_TOLERANCE`]. A sum reads 16 texels.
fn narrow_channels(pixel_format: PixelFormat) -> f32 {
match pixel_format {
PixelFormat::B5G6R5Unorm => 0.18 * (2.0 / 31.0 + 1.0 / 63.0),
_ => 0.0,
}
}
Loaded 100 of 1095 files, more files were not shown because too many files have changed in this diff. Show more